From 77eec1a35a06d89af2a9f33c14a6df8a94e9c24d Mon Sep 17 00:00:00 2001 From: dyates Date: Sun, 6 Jul 2025 17:10:19 -0700 Subject: [PATCH 01/37] Add `ProcessorConfig` and `ProcessorConfigSnapshot` --- .../cirq_google/engine/processor_config.py | 99 +++++++++++++++++++ .../engine/processor_config_test.py | 29 ++++++ 2 files changed, 128 insertions(+) create mode 100644 cirq-google/cirq_google/engine/processor_config.py create mode 100644 cirq-google/cirq_google/engine/processor_config_test.py diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py new file mode 100644 index 00000000000..800b9201354 --- /dev/null +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -0,0 +1,99 @@ +# Copyright 2022 The Cirq Developers +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from cirq_google.devices import GridDevice + +import datetime + +if TYPE_CHECKING: + import cirq_google as cg + +class ProcessorConfig: + """Representation of a quantum processor configuration + + Describes available qubits, gates, and calivration data associated with + a processor configuration. + """ + + def __init__(self, + *, + name: str, + effective_device: GridDevice, + calibration: cg.Calibration, + ) -> None: + self._name = name + self._effective_device = effective_device + self._calibration = calibration + + @property + def name(self) -> str: + """The name of this configuration""" + return self._name + + @property + def effective_device(self) -> GridDevice: + """The GridDevice generated from this configuration's device specification""" + return self._effective_device + + @property + def calibration(self) -> cg.Calibration: + """Charicterization metrics captured for this configuration""" + return self._calibration + + +class ProcessorConfigSnapshot: + """A snapshot of available device configurations for a processor.""" + + def __init__(self, + *, + snapshot_id: str, + create_time: datetime.datetime, + run_names: list[str], + processor_configs: list[ProcessorConfig] + ) -> None: + self._snapshot_id = snapshot_id + self._create_time = create_time + self._run_names = run_names + self._processor_configs = processor_configs + + @property + def snapshot_id(self) -> str: + """The indentifier for this snapshot.""" + return self._snapshot_id + + @property + def run_names(self) -> list[str]: + """Alternate ids which may be used to identify this config snapshot.""" + return self._run_names + + @property + def all_configs(self) -> list[ProcessorConfig]: + """List of all configurations in this snapshot.""" + return self._processor_configs + + def get_config(self, name: str) -> ProcessorConfig | None: + """Returns the configuration with the given name in this snapshot if it exists. + + Args: + name: The name of the configuration. + """ + for config in self._processor_configs: + if name == config.name: + return config + + return None diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py new file mode 100644 index 00000000000..0de5496cff9 --- /dev/null +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -0,0 +1,29 @@ +# Copyright 2018 The Cirq Developers +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for processor_config classes.""" + +from __future__ import annotations + +import cirq_google as cg + +import datetime + +def test_get_config_returns_existing_processor_config(self): + p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibraion=None) + p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibraion=None) + + snapshot = cg.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) + + assert snapshot.get_config("p2") == p2 \ No newline at end of file From 69f13978abef44abb758100cda35268a6f2b0249 Mon Sep 17 00:00:00 2001 From: dyates Date: Sun, 6 Jul 2025 22:08:57 -0700 Subject: [PATCH 02/37] Update __init__; Add another unit test. --- cirq-google/cirq_google/engine/__init__.py | 6 ++++++ .../engine/processor_config_test.py | 19 ++++++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index ac0f46c1dbf..ae6ffb3448f 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -95,3 +95,9 @@ from cirq_google.engine.engine_result import EngineResult as EngineResult from cirq_google.engine.processor_sampler import ProcessorSampler as ProcessorSampler + +from cirq_google.engine.processor_config import ( + ProcessorConfig as ProcessorConfig, + ProcessorConfigSnapshot as ProcessorConfigSnapshot, +) + diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 0de5496cff9..9381cff8bea 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -20,10 +20,19 @@ import datetime -def test_get_config_returns_existing_processor_config(self): - p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibraion=None) - p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibraion=None) +def test_get_config_returns_existing_processor_config(): + p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibration=None) + p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibration=None) + id = 'p2' + snapshot = cg.engine.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) - snapshot = cg.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) + assert snapshot.get_config(id) == p2 - assert snapshot.get_config("p2") == p2 \ No newline at end of file +def test_get_config_returns_none(): + p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibration=None) + p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibration=None) + id_does_not_exist = 'p3' + + snapshot = cg.engine.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) + + assert snapshot.get_config(id_does_not_exist) == None \ No newline at end of file From df98f15c63ee5c7cd47bef1839f2dea37c70a14a Mon Sep 17 00:00:00 2001 From: Michael Qian Date: Wed, 16 Jul 2025 14:27:20 -0700 Subject: [PATCH 03/37] Regenerates QuantumEngineService gRPC client libraries with GAPIC --- .../cirq_google/cloud/quantum/__init__.py | 14 +- .../cloud/quantum/gapic_version.py | 16 + .../cloud/quantum_v1alpha1/__init__.py | 14 +- .../quantum_v1alpha1/gapic_metadata.json | 160 + .../cloud/quantum_v1alpha1/gapic_version.py | 16 + .../quantum_v1alpha1/services/__init__.py | 2 +- .../quantum_engine_service/__init__.py | 2 +- .../quantum_engine_service/async_client.py | 1687 +++-- .../services/quantum_engine_service/client.py | 1536 +++-- .../services/quantum_engine_service/pagers.py | 574 +- .../transports/README.rst | 9 + .../transports/__init__.py | 9 +- .../quantum_engine_service/transports/base.py | 81 +- .../quantum_engine_service/transports/grpc.py | 235 +- .../transports/grpc_asyncio.py | 340 +- .../quantum_engine_service/transports/rest.py | 5438 +++++++++++++++++ .../transports/rest_base.py | 1019 +++ .../cloud/quantum_v1alpha1/types/__init__.py | 8 +- .../cloud/quantum_v1alpha1/types/engine.py | 364 +- .../cloud/quantum_v1alpha1/types/quantum.py | 542 +- .../engine/abstract_local_processor.py | 16 +- .../engine/abstract_local_processor_test.py | 16 +- .../cirq_google/engine/abstract_processor.py | 6 +- .../cirq_google/engine/engine_client.py | 22 +- .../cirq_google/engine/engine_client_test.py | 24 +- .../cirq_google/engine/engine_processor.py | 10 +- .../engine/engine_processor_test.py | 22 +- dev_tools/notebooks/isolated_notebook_test.py | 2 + docs/google/concepts.ipynb | 2 +- docs/simulate/virtual_engine_interface.ipynb | 7 +- 30 files changed, 10489 insertions(+), 1704 deletions(-) create mode 100755 cirq-google/cirq_google/cloud/quantum/gapic_version.py create mode 100755 cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py create mode 100755 cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst create mode 100755 cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py create mode 100755 cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py diff --git a/cirq-google/cirq_google/cloud/quantum/__init__.py b/cirq-google/cirq_google/cloud/quantum/__init__.py index df76298594d..8e21eb56262 100644 --- a/cirq-google/cirq_google/cloud/quantum/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from cirq_google.cloud.quantum import gapic_version as package_version + +__version__ = package_version.__version__ + from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.client import ( QuantumEngineServiceClient, @@ -32,6 +36,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.engine import DeleteQuantumReservationRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumCalibrationRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumJobRequest +from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProcessorConfigRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProcessorRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumProgramRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import GetQuantumReservationRequest @@ -61,6 +66,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumJobRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumProgramRequest from cirq_google.cloud.quantum_v1alpha1.types.engine import UpdateQuantumReservationRequest +from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigKey from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigSelector from cirq_google.cloud.quantum_v1alpha1.types.quantum import ExecutionStatus from cirq_google.cloud.quantum_v1alpha1.types.quantum import GcsLocation @@ -70,6 +76,7 @@ from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumJob from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumJobEvent from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProcessor +from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProcessorConfig from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumProgram from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumReservation from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumReservationBudget @@ -77,7 +84,6 @@ from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumResult from cirq_google.cloud.quantum_v1alpha1.types.quantum import QuantumTimeSlot from cirq_google.cloud.quantum_v1alpha1.types.quantum import SchedulingConfig -from cirq_google.cloud.quantum_v1alpha1.types.quantum import DeviceConfigKey __all__ = ( 'QuantumEngineServiceClient', @@ -93,6 +99,7 @@ 'DeleteQuantumReservationRequest', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -122,6 +129,7 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', @@ -131,6 +139,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -138,5 +147,4 @@ 'QuantumResult', 'QuantumTimeSlot', 'SchedulingConfig', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum/gapic_version.py b/cirq-google/cirq_google/cloud/quantum/gapic_version.py new file mode 100755 index 00000000000..20a9cd975b0 --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py index 8d2c1d80b27..59b88e65999 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from . import gapic_version as package_version + +__version__ = package_version.__version__ + from .services.quantum_engine_service import QuantumEngineServiceClient from .services.quantum_engine_service import QuantumEngineServiceAsyncClient @@ -28,6 +32,7 @@ from .types.engine import DeleteQuantumReservationRequest from .types.engine import GetQuantumCalibrationRequest from .types.engine import GetQuantumJobRequest +from .types.engine import GetQuantumProcessorConfigRequest from .types.engine import GetQuantumProcessorRequest from .types.engine import GetQuantumProgramRequest from .types.engine import GetQuantumReservationRequest @@ -57,6 +62,7 @@ from .types.engine import UpdateQuantumJobRequest from .types.engine import UpdateQuantumProgramRequest from .types.engine import UpdateQuantumReservationRequest +from .types.quantum import DeviceConfigKey from .types.quantum import DeviceConfigSelector from .types.quantum import ExecutionStatus from .types.quantum import GcsLocation @@ -66,6 +72,7 @@ from .types.quantum import QuantumJob from .types.quantum import QuantumJobEvent from .types.quantum import QuantumProcessor +from .types.quantum import QuantumProcessorConfig from .types.quantum import QuantumProgram from .types.quantum import QuantumReservation from .types.quantum import QuantumReservationBudget @@ -73,7 +80,6 @@ from .types.quantum import QuantumResult from .types.quantum import QuantumTimeSlot from .types.quantum import SchedulingConfig -from .types.quantum import DeviceConfigKey __all__ = ( 'QuantumEngineServiceAsyncClient', @@ -86,11 +92,13 @@ 'DeleteQuantumJobRequest', 'DeleteQuantumProgramRequest', 'DeleteQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -120,6 +128,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -134,5 +143,4 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json index be41be96981..fd2ec7bfb5d 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_metadata.json @@ -65,6 +65,11 @@ "get_quantum_processor" ] }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, "GetQuantumProgram": { "methods": [ "get_quantum_program" @@ -210,6 +215,161 @@ "get_quantum_processor" ] }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, + "GetQuantumProgram": { + "methods": [ + "get_quantum_program" + ] + }, + "GetQuantumReservation": { + "methods": [ + "get_quantum_reservation" + ] + }, + "GetQuantumResult": { + "methods": [ + "get_quantum_result" + ] + }, + "ListQuantumCalibrations": { + "methods": [ + "list_quantum_calibrations" + ] + }, + "ListQuantumJobEvents": { + "methods": [ + "list_quantum_job_events" + ] + }, + "ListQuantumJobs": { + "methods": [ + "list_quantum_jobs" + ] + }, + "ListQuantumProcessors": { + "methods": [ + "list_quantum_processors" + ] + }, + "ListQuantumPrograms": { + "methods": [ + "list_quantum_programs" + ] + }, + "ListQuantumReservationBudgets": { + "methods": [ + "list_quantum_reservation_budgets" + ] + }, + "ListQuantumReservationGrants": { + "methods": [ + "list_quantum_reservation_grants" + ] + }, + "ListQuantumReservations": { + "methods": [ + "list_quantum_reservations" + ] + }, + "ListQuantumTimeSlots": { + "methods": [ + "list_quantum_time_slots" + ] + }, + "QuantumRunStream": { + "methods": [ + "quantum_run_stream" + ] + }, + "ReallocateQuantumReservationGrant": { + "methods": [ + "reallocate_quantum_reservation_grant" + ] + }, + "UpdateQuantumJob": { + "methods": [ + "update_quantum_job" + ] + }, + "UpdateQuantumProgram": { + "methods": [ + "update_quantum_program" + ] + }, + "UpdateQuantumReservation": { + "methods": [ + "update_quantum_reservation" + ] + } + } + }, + "rest": { + "libraryClient": "QuantumEngineServiceClient", + "rpcs": { + "CancelQuantumJob": { + "methods": [ + "cancel_quantum_job" + ] + }, + "CancelQuantumReservation": { + "methods": [ + "cancel_quantum_reservation" + ] + }, + "CreateQuantumJob": { + "methods": [ + "create_quantum_job" + ] + }, + "CreateQuantumProgram": { + "methods": [ + "create_quantum_program" + ] + }, + "CreateQuantumReservation": { + "methods": [ + "create_quantum_reservation" + ] + }, + "DeleteQuantumJob": { + "methods": [ + "delete_quantum_job" + ] + }, + "DeleteQuantumProgram": { + "methods": [ + "delete_quantum_program" + ] + }, + "DeleteQuantumReservation": { + "methods": [ + "delete_quantum_reservation" + ] + }, + "GetQuantumCalibration": { + "methods": [ + "get_quantum_calibration" + ] + }, + "GetQuantumJob": { + "methods": [ + "get_quantum_job" + ] + }, + "GetQuantumProcessor": { + "methods": [ + "get_quantum_processor" + ] + }, + "GetQuantumProcessorConfig": { + "methods": [ + "get_quantum_processor_config" + ] + }, "GetQuantumProgram": { "methods": [ "get_quantum_program" diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py new file mode 100755 index 00000000000..20a9cd975b0 --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py index e8e1c3845db..cbf94b283c7 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py index 5d1df2327fd..9d8d7fff59d 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py index e66026f47dc..e94701fa899 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/async_client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,32 +12,32 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# +import importlib.util +import logging as std_logging +from typing import AsyncIterable, AsyncIterator, Awaitable, Callable, Optional, Sequence -# ruff: noqa: E501 - -from __future__ import annotations +import google.protobuf +from google.api_core import gapic_v1, retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials -import importlib.metadata -from typing import AsyncIterable, AsyncIterator, Awaitable, Sequence, TYPE_CHECKING +from cirq_google.cloud.quantum_v1alpha1 import gapic_version as package_version -from google.api_core import gapic_v1, retry as retries +try: + OptionalRetry = retries.AsyncRetry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.AsyncRetry, object, None # type: ignore from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service import pagers from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .client import QuantumEngineServiceClient -from .transports.base import DEFAULT_CLIENT_INFO +from .transports.base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.api_core.client_options import ClientOptions - from google.auth import credentials as ga_credentials +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None - from .transports.base import QuantumEngineServiceTransport - -try: - OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault -except AttributeError: # pragma: NO COVER - OptionalRetry = retries.Retry | object # type: ignore +_LOGGER = std_logging.getLogger(__name__) class QuantumEngineServiceAsyncClient: @@ -45,8 +45,12 @@ class QuantumEngineServiceAsyncClient: _client: QuantumEngineServiceClient + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = QuantumEngineServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = QuantumEngineServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = QuantumEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = QuantumEngineServiceClient._DEFAULT_UNIVERSE quantum_job_path = staticmethod(QuantumEngineServiceClient.quantum_job_path) parse_quantum_job_path = staticmethod(QuantumEngineServiceClient.parse_quantum_job_path) @@ -54,6 +58,12 @@ class QuantumEngineServiceAsyncClient: parse_quantum_processor_path = staticmethod( QuantumEngineServiceClient.parse_quantum_processor_path ) + quantum_processor_config_path = staticmethod( + QuantumEngineServiceClient.quantum_processor_config_path + ) + parse_quantum_processor_config_path = staticmethod( + QuantumEngineServiceClient.parse_quantum_processor_config_path + ) quantum_program_path = staticmethod(QuantumEngineServiceClient.quantum_program_path) parse_quantum_program_path = staticmethod(QuantumEngineServiceClient.parse_quantum_program_path) quantum_reservation_path = staticmethod(QuantumEngineServiceClient.quantum_reservation_path) @@ -90,7 +100,9 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: QuantumEngineServiceAsyncClient: The constructed client. """ - return QuantumEngineServiceClient.from_service_account_info.__func__(QuantumEngineServiceAsyncClient, info, *args, **kwargs) # type: ignore + return QuantumEngineServiceClient.from_service_account_info.__func__( # type: ignore + QuantumEngineServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -106,12 +118,14 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: QuantumEngineServiceAsyncClient: The constructed client. """ - return QuantumEngineServiceClient.from_service_account_file.__func__(QuantumEngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore + return QuantumEngineServiceClient.from_service_account_file.__func__( # type: ignore + QuantumEngineServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: ClientOptions | None = None): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -136,7 +150,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: ClientOptions | None in this method. Returns: - tuple[str, Callable[[], tuple[bytes, bytes]]]: returns the API endpoint and the + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the client cert source to use. Raises: @@ -153,17 +167,38 @@ def transport(self) -> QuantumEngineServiceTransport: """ return self._client.transport + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + get_transport_class = QuantumEngineServiceClient.get_transport_class def __init__( self, *, - credentials: ga_credentials.Credentials | None = None, - transport: str | QuantumEngineServiceTransport = "grpc_asyncio", - client_options: ClientOptions | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + str | QuantumEngineServiceTransport | Callable[..., QuantumEngineServiceTransport] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiates the quantum engine service client. + """Instantiates the quantum engine service async client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -171,26 +206,49 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (str | ~.QuantumEngineServiceTransport): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: + transport ( + Optional[ + str | + QuantumEngineServiceTransport | + Callable[..., QuantumEngineServiceTransport] + ] + ): + The transport to use, or a Callable that constructs and returns a new transport to + use. If a Callable is given, it will be called with the same set of initialization + arguments as used in the QuantumEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[google.api_core.client_options.ClientOptions | dict]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If + to provide a client certificate for mTLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. @@ -202,57 +260,96 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + ( + "Created client `cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceAsyncClient`." + ), + extra=( + { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", # noqa E501 + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "credentialsType": None, + } + ), + ) + async def create_quantum_program( self, - request: engine.CreateQuantumProgramRequest | dict | None = None, + request: Optional[engine.CreateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_program(): + async def sample_create_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumProgramRequest( ) # Make the request - response = client.create_quantum_program(request=request) + response = await client.create_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict): + request ( + Optional[ + cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict + ] + ): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - """ # Create or coerce a protobuf request object. - request = engine.CreateQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumProgramRequest): + request = engine.CreateQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -260,6 +357,9 @@ def sample_create_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -268,55 +368,63 @@ def sample_create_quantum_program(): async def get_quantum_program( self, - request: engine.GetQuantumProgramRequest | dict | None = None, + request: Optional[engine.GetQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_program(): + async def sample_get_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumProgramRequest( ) # Make the request - response = client.get_quantum_program(request=request) + response = await client.get_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict): + request (Optional[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProgramRequest): + request = engine.GetQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_program] # Certain fields should be provided within the metadata header; # add these here. @@ -324,6 +432,9 @@ def sample_get_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -332,21 +443,28 @@ def sample_get_quantum_program(): async def list_quantum_programs( self, - request: engine.ListQuantumProgramsRequest | dict | None = None, + request: Optional[engine.ListQuantumProgramsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProgramsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_programs(): + async def sample_list_quantum_programs(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumProgramsRequest( @@ -356,36 +474,40 @@ def sample_list_quantum_programs(): page_result = client.list_quantum_programs(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumProgramsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumProgramsRequest): + request = engine.ListQuantumProgramsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_programs, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_programs + ] # Certain fields should be provided within the metadata header; # add these here. @@ -393,13 +515,21 @@ def sample_list_quantum_programs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumProgramsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -407,48 +537,58 @@ def sample_list_quantum_programs(): async def delete_quantum_program( self, - request: engine.DeleteQuantumProgramRequest | dict | None = None, + request: Optional[engine.DeleteQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_program(): + async def sample_delete_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumProgramRequest( ) # Make the request - client.delete_quantum_program(request=request) + await client.delete_quantum_program(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumProgramRequest): + request = engine.DeleteQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -456,60 +596,73 @@ def sample_delete_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def update_quantum_program( self, - request: engine.UpdateQuantumProgramRequest | dict | None = None, + request: Optional[engine.UpdateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_program(): + async def sample_update_quantum_program(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumProgramRequest( ) # Make the request - response = client.update_quantum_program(request=request) + response = await client.update_quantum_program(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumProgramRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumProgramRequest): + request = engine.UpdateQuantumProgramRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_program, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_quantum_program + ] # Certain fields should be provided within the metadata header; # add these here. @@ -517,6 +670,9 @@ def sample_update_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -525,55 +681,63 @@ def sample_update_quantum_program(): async def create_quantum_job( self, - request: engine.CreateQuantumJobRequest | dict | None = None, + request: Optional[engine.CreateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_job(): + async def sample_create_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumJobRequest( ) # Make the request - response = client.create_quantum_job(request=request) + response = await client.create_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CreateQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumJobRequest): + request = engine.CreateQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.create_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -581,6 +745,9 @@ def sample_create_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -589,55 +756,63 @@ def sample_create_quantum_job(): async def get_quantum_job( self, - request: engine.GetQuantumJobRequest | dict | None = None, + request: Optional[engine.GetQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_job(): + async def sample_get_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumJobRequest( ) # Make the request - response = client.get_quantum_job(request=request) + response = await client.get_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumJobRequest): + request = engine.GetQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -645,6 +820,9 @@ def sample_get_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -653,21 +831,28 @@ def sample_get_quantum_job(): async def list_quantum_jobs( self, - request: engine.ListQuantumJobsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_jobs(): + async def sample_list_quantum_jobs(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumJobsRequest( @@ -677,36 +862,38 @@ def sample_list_quantum_jobs(): page_result = client.list_quantum_jobs(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumJobsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumJobsRequest): + request = engine.ListQuantumJobsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_jobs, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.list_quantum_jobs] # Certain fields should be provided within the metadata header; # add these here. @@ -714,13 +901,21 @@ def sample_list_quantum_jobs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumJobsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -728,48 +923,56 @@ def sample_list_quantum_jobs(): async def delete_quantum_job( self, - request: engine.DeleteQuantumJobRequest | dict | None = None, + request: Optional[engine.DeleteQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_job(): + async def sample_delete_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumJobRequest( ) # Make the request - client.delete_quantum_job(request=request) + await client.delete_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumJobRequest): + request = engine.DeleteQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -777,60 +980,71 @@ def sample_delete_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def update_quantum_job( self, - request: engine.UpdateQuantumJobRequest | dict | None = None, + request: Optional[engine.UpdateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_job(): + async def sample_update_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumJobRequest( ) # Make the request - response = client.update_quantum_job(request=request) + response = await client.update_quantum_job(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumJobRequest): + request = engine.UpdateQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_job, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.update_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -838,6 +1052,9 @@ def sample_update_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -846,48 +1063,56 @@ def sample_update_quantum_job(): async def cancel_quantum_job( self, - request: engine.CancelQuantumJobRequest | dict | None = None, + request: Optional[engine.CancelQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_cancel_quantum_job(): + async def sample_cancel_quantum_job(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CancelQuantumJobRequest( ) # Make the request - client.cancel_quantum_job(request=request) + await client.cancel_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CancelQuantumJobRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CancelQuantumJobRequest): + request = engine.CancelQuantumJobRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_quantum_job, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.cancel_quantum_job] # Certain fields should be provided within the metadata header; # add these here. @@ -895,26 +1120,36 @@ def sample_cancel_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def list_quantum_job_events( self, - request: engine.ListQuantumJobEventsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobEventsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobEventsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_job_events(): + async def sample_list_quantum_job_events(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumJobEventsRequest( @@ -924,36 +1159,40 @@ def sample_list_quantum_job_events(): page_result = client.list_quantum_job_events(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumJobEventsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumJobEventsRequest): + request = engine.ListQuantumJobEventsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_job_events, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_job_events + ] # Certain fields should be provided within the metadata header; # add these here. @@ -961,13 +1200,21 @@ def sample_list_quantum_job_events(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumJobEventsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -975,55 +1222,63 @@ def sample_list_quantum_job_events(): async def get_quantum_result( self, - request: engine.GetQuantumResultRequest | dict | None = None, + request: Optional[engine.GetQuantumResultRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumResult: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_result(): + async def sample_get_quantum_result(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumResultRequest( ) # Make the request - response = client.get_quantum_result(request=request) + response = await client.get_quantum_result(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumResult: + cirq_google.cloud.quantum_v1alpha1.types.QuantumResult: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumResultRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumResultRequest): + request = engine.GetQuantumResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_result, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_quantum_result] # Certain fields should be provided within the metadata header; # add these here. @@ -1031,6 +1286,9 @@ def sample_get_quantum_result(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1039,21 +1297,28 @@ def sample_get_quantum_result(): async def list_quantum_processors( self, - request: engine.ListQuantumProcessorsRequest | dict | None = None, + request: Optional[engine.ListQuantumProcessorsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProcessorsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_processors(): + async def sample_list_quantum_processors(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumProcessorsRequest( @@ -1063,36 +1328,40 @@ def sample_list_quantum_processors(): page_result = client.list_quantum_processors(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumProcessorsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumProcessorsRequest): + request = engine.ListQuantumProcessorsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_processors, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_processors + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1100,13 +1369,21 @@ def sample_list_quantum_processors(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumProcessorsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1114,62 +1391,174 @@ def sample_list_quantum_processors(): async def get_quantum_processor( self, - request: engine.GetQuantumProcessorRequest | dict | None = None, + request: Optional[engine.GetQuantumProcessorRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProcessor: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_processor(): + async def sample_get_quantum_processor(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumProcessorRequest( ) # Make the request - response = client.get_quantum_processor(request=request) + response = await client.get_quantum_processor(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProcessor: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumProcessorRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorRequest): + request = engine.GetQuantumProcessorRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_processor, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_processor + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) + + # Done; return the response. + return response + + async def get_quantum_processor_config( + self, + request: Optional[engine.GetQuantumProcessorConfigRequest | dict] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""- + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import quantum_v1alpha1 + + async def sample_get_quantum_processor_config(): + # Create a client + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() + + # Initialize request argument(s) + request = quantum_v1alpha1.GetQuantumProcessorConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_quantum_processor_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorConfigRequest, dict]]): + The request object. - + name (:class:`str`): + Required. - + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessorConfig: + - + """ # noqa E501 + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorConfigRequest): + request = engine.GetQuantumProcessorConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_processor_config + ] + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1178,21 +1567,28 @@ def sample_get_quantum_processor(): async def list_quantum_calibrations( self, - request: engine.ListQuantumCalibrationsRequest | dict | None = None, + request: Optional[engine.ListQuantumCalibrationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumCalibrationsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_calibrations(): + async def sample_list_quantum_calibrations(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumCalibrationsRequest( @@ -1202,36 +1598,40 @@ def sample_list_quantum_calibrations(): page_result = client.list_quantum_calibrations(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumCalibrationsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumCalibrationsRequest): + request = engine.ListQuantumCalibrationsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_calibrations, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_calibrations + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1239,13 +1639,21 @@ def sample_list_quantum_calibrations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumCalibrationsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1253,55 +1661,65 @@ def sample_list_quantum_calibrations(): async def get_quantum_calibration( self, - request: engine.GetQuantumCalibrationRequest | dict | None = None, + request: Optional[engine.GetQuantumCalibrationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumCalibration: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_calibration(): + async def sample_get_quantum_calibration(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumCalibrationRequest( ) # Make the request - response = client.get_quantum_calibration(request=request) + response = await client.get_quantum_calibration(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumCalibration: + cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumCalibrationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumCalibrationRequest): + request = engine.GetQuantumCalibrationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_calibration, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_calibration + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1309,6 +1727,9 @@ def sample_get_quantum_calibration(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1317,55 +1738,65 @@ def sample_get_quantum_calibration(): async def create_quantum_reservation( self, - request: engine.CreateQuantumReservationRequest | dict | None = None, + request: Optional[engine.CreateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_create_quantum_reservation(): + async def sample_create_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CreateQuantumReservationRequest( ) # Make the request - response = client.create_quantum_reservation(request=request) + response = await client.create_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CreateQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CreateQuantumReservationRequest): + request = engine.CreateQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1373,6 +1804,9 @@ def sample_create_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1381,55 +1815,65 @@ def sample_create_quantum_reservation(): async def cancel_quantum_reservation( self, - request: engine.CancelQuantumReservationRequest | dict | None = None, + request: Optional[engine.CancelQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_cancel_quantum_reservation(): + async def sample_cancel_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.CancelQuantumReservationRequest( ) # Make the request - response = client.cancel_quantum_reservation(request=request) + response = await client.cancel_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.CancelQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.CancelQuantumReservationRequest): + request = engine.CancelQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.cancel_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1437,6 +1881,9 @@ def sample_cancel_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1445,48 +1892,58 @@ def sample_cancel_quantum_reservation(): async def delete_quantum_reservation( self, - request: engine.DeleteQuantumReservationRequest | dict | None = None, + request: Optional[engine.DeleteQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_delete_quantum_reservation(): + async def sample_delete_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.DeleteQuantumReservationRequest( ) # Make the request - client.delete_quantum_reservation(request=request) + await client.delete_quantum_reservation(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.DeleteQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.DeleteQuantumReservationRequest): + request = engine.DeleteQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1494,60 +1951,73 @@ def sample_delete_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. await rpc(request, retry=retry, timeout=timeout, metadata=metadata) async def get_quantum_reservation( self, - request: engine.GetQuantumReservationRequest | dict | None = None, + request: Optional[engine.GetQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_get_quantum_reservation(): + async def sample_get_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.GetQuantumReservationRequest( ) # Make the request - response = client.get_quantum_reservation(request=request) + response = await client.get_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.GetQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumReservationRequest): + request = engine.GetQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1555,6 +2025,9 @@ def sample_get_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1563,21 +2036,28 @@ def sample_get_quantum_reservation(): async def list_quantum_reservations( self, - request: engine.ListQuantumReservationsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservations(): + async def sample_list_quantum_reservations(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationsRequest( @@ -1587,36 +2067,40 @@ def sample_list_quantum_reservations(): page_result = client.list_quantum_reservations(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationsRequest): + request = engine.ListQuantumReservationsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservations, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservations + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1624,13 +2108,21 @@ def sample_list_quantum_reservations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1638,55 +2130,65 @@ def sample_list_quantum_reservations(): async def update_quantum_reservation( self, - request: engine.UpdateQuantumReservationRequest | dict | None = None, + request: Optional[engine.UpdateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_update_quantum_reservation(): + async def sample_update_quantum_reservation(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.UpdateQuantumReservationRequest( ) # Make the request - response = client.update_quantum_reservation(request=request) + response = await client.update_quantum_reservation(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.UpdateQuantumReservationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.UpdateQuantumReservationRequest): + request = engine.UpdateQuantumReservationRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_quantum_reservation, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_quantum_reservation + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1694,6 +2196,9 @@ def sample_update_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1702,21 +2207,28 @@ def sample_update_quantum_reservation(): def quantum_run_stream( self, - requests: AsyncIterator[engine.QuantumRunStreamRequest] | None = None, + requests: Optional[AsyncIterator[engine.QuantumRunStreamRequest]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> Awaitable[AsyncIterable[engine.QuantumRunStreamResponse]]: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_quantum_run_stream(): + async def sample_quantum_run_stream(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.QuantumRunStreamRequest( @@ -1733,33 +2245,34 @@ def request_generator(): yield request # Make the request - stream = client.quantum_run_stream(requests=request_generator()) + stream = await client.quantum_run_stream(requests=request_generator()) # Handle the response - for response in stream: + async for response in stream: print(response) Args: - requests (AsyncIterator[`google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest`]): + requests (AsyncIterator[`cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest`]): The request object AsyncIterator. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - AsyncIterable[google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: + AsyncIterable[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: - - """ + """ # noqa E501 # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.quantum_run_stream, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.quantum_run_stream] + + # Validate the universe domain. + self._client._validate_universe_domain() # Send the request. response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) @@ -1769,21 +2282,28 @@ def request_generator(): async def list_quantum_reservation_grants( self, - request: engine.ListQuantumReservationGrantsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationGrantsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationGrantsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservation_grants(): + async def sample_list_quantum_reservation_grants(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationGrantsRequest( @@ -1793,36 +2313,40 @@ def sample_list_quantum_reservation_grants(): page_result = client.list_quantum_reservation_grants(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationGrantsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationGrantsRequest): + request = engine.ListQuantumReservationGrantsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservation_grants, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservation_grants + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1830,13 +2354,21 @@ def sample_list_quantum_reservation_grants(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationGrantsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1844,55 +2376,65 @@ def sample_list_quantum_reservation_grants(): async def reallocate_quantum_reservation_grant( self, - request: engine.ReallocateQuantumReservationGrantRequest | dict | None = None, + request: Optional[engine.ReallocateQuantumReservationGrantRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservationGrant: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_reallocate_quantum_reservation_grant(): + async def sample_reallocate_quantum_reservation_grant(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ReallocateQuantumReservationGrantRequest( ) # Make the request - response = client.reallocate_quantum_reservation_grant(request=request) + response = await client.reallocate_quantum_reservation_grant(request=request) # Handle the response print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ReallocateQuantumReservationGrantRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ReallocateQuantumReservationGrantRequest): + request = engine.ReallocateQuantumReservationGrantRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.reallocate_quantum_reservation_grant, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reallocate_quantum_reservation_grant + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1900,6 +2442,9 @@ def sample_reallocate_quantum_reservation_grant(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1908,21 +2453,28 @@ def sample_reallocate_quantum_reservation_grant(): async def list_quantum_reservation_budgets( self, - request: engine.ListQuantumReservationBudgetsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationBudgetsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationBudgetsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_reservation_budgets(): + async def sample_list_quantum_reservation_budgets(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumReservationBudgetsRequest( @@ -1932,36 +2484,40 @@ def sample_list_quantum_reservation_budgets(): page_result = client.list_quantum_reservation_budgets(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumReservationBudgetsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumReservationBudgetsRequest): + request = engine.ListQuantumReservationBudgetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_reservation_budgets, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_reservation_budgets + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1969,13 +2525,21 @@ def sample_list_quantum_reservation_budgets(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumReservationBudgetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1983,21 +2547,28 @@ def sample_list_quantum_reservation_budgets(): async def list_quantum_time_slots( self, - request: engine.ListQuantumTimeSlotsRequest | dict | None = None, + request: Optional[engine.ListQuantumTimeSlotsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumTimeSlotsAsyncPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 - def sample_list_quantum_time_slots(): + async def sample_list_quantum_time_slots(): # Create a client - client = quantum_v1alpha1.QuantumEngineServiceClient() + client = quantum_v1alpha1.QuantumEngineServiceAsyncClient() # Initialize request argument(s) request = quantum_v1alpha1.ListQuantumTimeSlotsRequest( @@ -2007,36 +2578,40 @@ def sample_list_quantum_time_slots(): page_result = client.list_quantum_time_slots(request=request) # Handle the response - for response in page_result: + async for response in page_result: print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest | dict): + request (Optional[Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest, dict]]): The request object. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, str | bytes]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsAsyncPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsAsyncPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - request = engine.ListQuantumTimeSlotsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.ListQuantumTimeSlotsRequest): + request = engine.ListQuantumTimeSlotsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_quantum_time_slots, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_quantum_time_slots + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2044,31 +2619,37 @@ def sample_list_quantum_time_slots(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._client._validate_universe_domain() + # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListQuantumTimeSlotsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - async def __aenter__(self): + async def __aenter__(self) -> "QuantumEngineServiceAsyncClient": return self async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ __all__ = ("QuantumEngineServiceAsyncClient",) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py index 4515e2ae319..423e6b8adec 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,36 +12,50 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - -from __future__ import annotations - -import importlib.metadata +# +import json +import logging as std_logging import os import re +import warnings from collections import OrderedDict -from typing import Iterable, Iterator, Sequence, TYPE_CHECKING - -from google.api_core import client_options as client_options_lib, gapic_v1, retry as retries +from http import HTTPStatus +from typing import Callable, cast, Iterable, Iterator, Optional, Sequence + +import google.protobuf +from google.api_core import ( + client_options as client_options_lib, + exceptions as core_exceptions, + gapic_v1, + retry as retries, +) +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.auth.transport import mtls from google.oauth2 import service_account +from cirq_google.cloud.quantum_v1alpha1 import gapic_version as package_version from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service import pagers from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .transports.base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport from .transports.grpc import QuantumEngineServiceGrpcTransport from .transports.grpc_asyncio import QuantumEngineServiceGrpcAsyncIOTransport - -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials +from .transports.rest import QuantumEngineServiceRestTransport try: - OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None except AttributeError: # pragma: NO COVER - OptionalRetry = retries.Retry | object # type: ignore + OptionalRetry = retries.Retry | object | None # type: ignore + +try: + from google.api_core import client_logging + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) class QuantumEngineServiceClientMeta(type): @@ -52,11 +66,14 @@ class QuantumEngineServiceClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: dict[str, type[QuantumEngineServiceTransport]] + _transport_registry: dict[str, type[QuantumEngineServiceTransport]] = OrderedDict() _transport_registry["grpc"] = QuantumEngineServiceGrpcTransport _transport_registry["grpc_asyncio"] = QuantumEngineServiceGrpcAsyncIOTransport + _transport_registry["rest"] = QuantumEngineServiceRestTransport - def get_transport_class(cls, label: str | None = None) -> type[QuantumEngineServiceTransport]: + def get_transport_class( + cls, label: Optional[str] = None + ) -> type[QuantumEngineServiceTransport]: """Returns an appropriate transport class. Args: @@ -97,7 +114,7 @@ def _get_default_mtls_endpoint(api_endpoint): ) m = mtls_endpoint_re.match(api_endpoint) - _, mtls, sandbox, googledomain = m.groups() + name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint @@ -106,9 +123,13 @@ def _get_default_mtls_endpoint(api_endpoint): return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = "quantum.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(DEFAULT_ENDPOINT) # type: ignore + _DEFAULT_ENDPOINT_TEMPLATE = "quantum.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -159,7 +180,9 @@ def transport(self) -> QuantumEngineServiceTransport: @staticmethod def quantum_job_path(project: str, program: str, job: str) -> str: """Returns a fully-qualified quantum_job string.""" - return f"projects/{project}/programs/{program}/jobs/{job}" + return "projects/{project}/programs/{program}/jobs/{job}".format( + project=project, program=program, job=job + ) @staticmethod def parse_quantum_job_path(path: str) -> dict[str, str]: @@ -172,7 +195,9 @@ def parse_quantum_job_path(path: str) -> dict[str, str]: @staticmethod def quantum_processor_path(project_id: str, processor_id: str) -> str: """Returns a fully-qualified quantum_processor string.""" - return f"projects/{project_id}/processors/{processor_id}" + return "projects/{project_id}/processors/{processor_id}".format( + project_id=project_id, processor_id=processor_id + ) @staticmethod def parse_quantum_processor_path(path: str) -> dict[str, str]: @@ -180,10 +205,31 @@ def parse_quantum_processor_path(path: str) -> dict[str, str]: m = re.match(r"^projects/(?P.+?)/processors/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def quantum_processor_config_path( + project: str, processor: str, snapshot_id: str, quantum_processor_config: str + ) -> str: + """Returns a fully-qualified quantum_processor_config string.""" + return "projects/{project}/processors/{processor}/configSnapshots/{snapshot_id}/configs/{quantum_processor_config}".format( # noqa E501 + project=project, + processor=processor, + snapshot_id=snapshot_id, + quantum_processor_config=quantum_processor_config, + ) + + @staticmethod + def parse_quantum_processor_config_path(path: str) -> dict[str, str]: + """Parses a quantum_processor_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/processors/(?P.+?)/configSnapshots/(?P.+?)/configs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def quantum_program_path(project: str, program: str) -> str: """Returns a fully-qualified quantum_program string.""" - return f"projects/{project}/programs/{program}" + return "projects/{project}/programs/{program}".format(project=project, program=program) @staticmethod def parse_quantum_program_path(path: str) -> dict[str, str]: @@ -194,7 +240,11 @@ def parse_quantum_program_path(path: str) -> dict[str, str]: @staticmethod def quantum_reservation_path(project_id: str, processor_id: str, reservation_id: str) -> str: """Returns a fully-qualified quantum_reservation string.""" - return f"projects/{project_id}/processors/{processor_id}/reservations/{reservation_id}" + return ( + "projects/{project_id}/processors/{processor_id}/reservations/{reservation_id}".format( + project_id=project_id, processor_id=processor_id, reservation_id=reservation_id + ) + ) @staticmethod def parse_quantum_reservation_path(path: str) -> dict[str, str]: @@ -208,7 +258,7 @@ def parse_quantum_reservation_path(path: str) -> dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str) -> str: """Returns a fully-qualified billing_account string.""" - return f"billingAccounts/{billing_account}" + return "billingAccounts/{billing_account}".format(billing_account=billing_account) @staticmethod def parse_common_billing_account_path(path: str) -> dict[str, str]: @@ -219,7 +269,7 @@ def parse_common_billing_account_path(path: str) -> dict[str, str]: @staticmethod def common_folder_path(folder: str) -> str: """Returns a fully-qualified folder string.""" - return f"folders/{folder}" + return "folders/{folder}".format(folder=folder) @staticmethod def parse_common_folder_path(path: str) -> dict[str, str]: @@ -230,7 +280,7 @@ def parse_common_folder_path(path: str) -> dict[str, str]: @staticmethod def common_organization_path(organization: str) -> str: """Returns a fully-qualified organization string.""" - return f"organizations/{organization}" + return "organizations/{organization}".format(organization=organization) @staticmethod def parse_common_organization_path(path: str) -> dict[str, str]: @@ -241,7 +291,7 @@ def parse_common_organization_path(path: str) -> dict[str, str]: @staticmethod def common_project_path(project: str) -> str: """Returns a fully-qualified project string.""" - return f"projects/{project}" + return "projects/{project}".format(project=project) @staticmethod def parse_common_project_path(path: str) -> dict[str, str]: @@ -252,7 +302,7 @@ def parse_common_project_path(path: str) -> dict[str, str]: @staticmethod def common_location_path(project: str, location: str) -> str: """Returns a fully-qualified location string.""" - return f"projects/{project}/locations/{location}" + return "projects/{project}/locations/{location}".format(project=project, location=location) @staticmethod def parse_common_location_path(path: str) -> dict[str, str]: @@ -262,9 +312,9 @@ def parse_common_location_path(path: str) -> dict[str, str]: @classmethod def get_mtls_endpoint_and_cert_source( - cls, client_options: client_options_lib.ClientOptions | None = None + cls, client_options: Optional[client_options_lib.ClientOptions] = None ): - """Return the API endpoint and client cert source for mutual TLS. + """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the @@ -288,23 +338,33 @@ def get_mtls_endpoint_and_cert_source( in this method. Returns: - tuple[str, Callable[[], tuple[bytes, bytes]]]: returns the API endpoint and the + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the client cert source to use. Raises: google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ + + warnings.warn( + ( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property " + "instead." + ), + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` " + "or `false`" ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or " + "`always`" ) # Figure out the client cert source to use. @@ -325,12 +385,171 @@ def get_mtls_endpoint_and_cert_source( return api_endpoint, client_cert_source + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or " + "`false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or " + "`always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other + parameters. Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = QuantumEngineServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = QuantumEngineServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = QuantumEngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client + options. + universe_domain_env (Optional[str]): The universe domain configured via the + "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = QuantumEngineServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors(self, error: core_exceptions.GoogleAPICallError) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + def __init__( self, *, - credentials: ga_credentials.Credentials | None = None, - transport: str | QuantumEngineServiceTransport | None = None, - client_options: client_options_lib.ClientOptions | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + str | QuantumEngineServiceTransport | Callable[..., QuantumEngineServiceTransport] + ] = None, + client_options: Optional[client_options_lib.ClientOptions | dict] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the quantum engine service client. @@ -341,25 +560,37 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (str | QuantumEngineServiceTransport): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: + transport (Optional[Union[str,QuantumEngineServiceTransport,Callable[..., QuantumEngineServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the QuantumEngineServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If + to provide a client certificate for mTLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. @@ -369,64 +600,133 @@ def __init__( Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( - client_options + """ # noqa E501 + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + QuantumEngineServiceClient._read_environment_variables() + ) + self._client_cert_source = QuantumEngineServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = QuantumEngineServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env ) + self._api_endpoint = None # updated below, depending on `transport` - api_key_value = getattr(client_options, "api_key", None) + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. - if isinstance(transport, QuantumEngineServiceTransport): + transport_provided = isinstance(transport, QuantumEngineServiceTransport) + if transport_provided: # transport is a QuantumEngineServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: + if credentials or self._client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) - if client_options.scopes: + if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " "directly." ) - self._transport = transport - else: + self._transport = cast(QuantumEngineServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or QuantumEngineServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: import google.auth._default if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): credentials = google.auth._default.get_api_key_credentials(api_key_value) - Transport = type(self).get_transport_class(transport) - self._transport = Transport( + transport_init: ( + type[QuantumEngineServiceTransport] | Callable[..., QuantumEngineServiceTransport] + ) = ( + QuantumEngineServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., QuantumEngineServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + ( + "Created client `cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient`." + ), + extra=( + { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", # noqa E501 + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "credentialsType": None, + } + ), + ) + def create_quantum_program( self, - request: engine.CreateQuantumProgramRequest | dict | None = None, + request: Optional[engine.CreateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_program(): @@ -444,23 +744,23 @@ def sample_create_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumProgramRequest): request = engine.CreateQuantumProgramRequest(request) @@ -474,6 +774,9 @@ def sample_create_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -482,16 +785,23 @@ def sample_create_quantum_program(): def get_quantum_program( self, - request: engine.GetQuantumProgramRequest | dict | None = None, + request: Optional[engine.GetQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_program(): @@ -509,23 +819,23 @@ def sample_get_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumProgramRequest): request = engine.GetQuantumProgramRequest(request) @@ -539,6 +849,9 @@ def sample_get_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -547,16 +860,23 @@ def sample_get_quantum_program(): def list_quantum_programs( self, - request: engine.ListQuantumProgramsRequest | dict | None = None, + request: Optional[engine.ListQuantumProgramsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProgramsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_programs(): @@ -575,27 +895,28 @@ def sample_list_quantum_programs(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProgramsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumProgramsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumProgramsRequest): request = engine.ListQuantumProgramsRequest(request) @@ -609,13 +930,21 @@ def sample_list_quantum_programs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumProgramsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -623,16 +952,23 @@ def sample_list_quantum_programs(): def delete_quantum_program( self, - request: engine.DeleteQuantumProgramRequest | dict | None = None, + request: Optional[engine.DeleteQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_program(): @@ -647,19 +983,19 @@ def sample_delete_quantum_program(): client.delete_quantum_program(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumProgramRequest): request = engine.DeleteQuantumProgramRequest(request) @@ -673,21 +1009,31 @@ def sample_delete_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def update_quantum_program( self, - request: engine.UpdateQuantumProgramRequest | dict | None = None, + request: Optional[engine.UpdateQuantumProgramRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProgram: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_program(): @@ -705,23 +1051,23 @@ def sample_update_quantum_program(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumProgramRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProgram: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumProgramRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumProgramRequest): request = engine.UpdateQuantumProgramRequest(request) @@ -735,6 +1081,9 @@ def sample_update_quantum_program(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -743,16 +1092,23 @@ def sample_update_quantum_program(): def create_quantum_job( self, - request: engine.CreateQuantumJobRequest | dict | None = None, + request: Optional[engine.CreateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_job(): @@ -770,23 +1126,23 @@ def sample_create_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumJobRequest): request = engine.CreateQuantumJobRequest(request) @@ -800,6 +1156,9 @@ def sample_create_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -808,16 +1167,23 @@ def sample_create_quantum_job(): def get_quantum_job( self, - request: engine.GetQuantumJobRequest | dict | None = None, + request: Optional[engine.GetQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_job(): @@ -835,23 +1201,23 @@ def sample_get_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumJobRequest): request = engine.GetQuantumJobRequest(request) @@ -865,6 +1231,9 @@ def sample_get_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -873,16 +1242,23 @@ def sample_get_quantum_job(): def list_quantum_jobs( self, - request: engine.ListQuantumJobsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_jobs(): @@ -901,27 +1277,28 @@ def sample_list_quantum_jobs(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobsPager: - + Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumJobsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumJobsRequest): request = engine.ListQuantumJobsRequest(request) @@ -935,13 +1312,21 @@ def sample_list_quantum_jobs(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumJobsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -949,16 +1334,23 @@ def sample_list_quantum_jobs(): def delete_quantum_job( self, - request: engine.DeleteQuantumJobRequest | dict | None = None, + request: Optional[engine.DeleteQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_job(): @@ -973,19 +1365,19 @@ def sample_delete_quantum_job(): client.delete_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumJobRequest): request = engine.DeleteQuantumJobRequest(request) @@ -999,21 +1391,31 @@ def sample_delete_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def update_quantum_job( self, - request: engine.UpdateQuantumJobRequest | dict | None = None, + request: Optional[engine.UpdateQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumJob: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_job(): @@ -1031,23 +1433,23 @@ def sample_update_quantum_job(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumJob: + cirq_google.cloud.quantum_v1alpha1.types.QuantumJob: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumJobRequest): request = engine.UpdateQuantumJobRequest(request) @@ -1061,6 +1463,9 @@ def sample_update_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1069,16 +1474,23 @@ def sample_update_quantum_job(): def cancel_quantum_job( self, - request: engine.CancelQuantumJobRequest | dict | None = None, + request: Optional[engine.CancelQuantumJobRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_cancel_quantum_job(): @@ -1093,19 +1505,19 @@ def sample_cancel_quantum_job(): client.cancel_quantum_job(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumJobRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CancelQuantumJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CancelQuantumJobRequest): request = engine.CancelQuantumJobRequest(request) @@ -1119,21 +1531,31 @@ def sample_cancel_quantum_job(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def list_quantum_job_events( self, - request: engine.ListQuantumJobEventsRequest | dict | None = None, + request: Optional[engine.ListQuantumJobEventsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumJobEventsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_job_events(): @@ -1152,27 +1574,28 @@ def sample_list_quantum_job_events(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumJobEventsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumJobEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumJobEventsRequest): request = engine.ListQuantumJobEventsRequest(request) @@ -1186,13 +1609,21 @@ def sample_list_quantum_job_events(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumJobEventsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1200,16 +1631,23 @@ def sample_list_quantum_job_events(): def get_quantum_result( self, - request: engine.GetQuantumResultRequest | dict | None = None, + request: Optional[engine.GetQuantumResultRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumResult: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_result(): @@ -1227,23 +1665,23 @@ def sample_get_quantum_result(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumResult: + cirq_google.cloud.quantum_v1alpha1.types.QuantumResult: - """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumResultRequest): request = engine.GetQuantumResultRequest(request) @@ -1257,6 +1695,9 @@ def sample_get_quantum_result(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1265,16 +1706,23 @@ def sample_get_quantum_result(): def list_quantum_processors( self, - request: engine.ListQuantumProcessorsRequest | dict | None = None, + request: Optional[engine.ListQuantumProcessorsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumProcessorsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_processors(): @@ -1293,27 +1741,28 @@ def sample_list_quantum_processors(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumProcessorsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumProcessorsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumProcessorsRequest): request = engine.ListQuantumProcessorsRequest(request) @@ -1327,13 +1776,21 @@ def sample_list_quantum_processors(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumProcessorsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1341,16 +1798,23 @@ def sample_list_quantum_processors(): def get_quantum_processor( self, - request: engine.GetQuantumProcessorRequest | dict | None = None, + request: Optional[engine.GetQuantumProcessorRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumProcessor: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_processor(): @@ -1368,23 +1832,23 @@ def sample_get_quantum_processor(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumProcessor: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumProcessorRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumProcessorRequest): request = engine.GetQuantumProcessorRequest(request) @@ -1398,6 +1862,105 @@ def sample_get_quantum_processor(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + + # Done; return the response. + return response + + def get_quantum_processor_config( + self, + request: Optional[engine.GetQuantumProcessorConfigRequest | dict] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""- + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import quantum_v1alpha1 + + def sample_get_quantum_processor_config(): + # Create a client + client = quantum_v1alpha1.QuantumEngineServiceClient() + + # Initialize request argument(s) + request = quantum_v1alpha1.GetQuantumProcessorConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_quantum_processor_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumProcessorConfigRequest, dict]): + The request object. - + name (str): + Required. - + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessorConfig: + - + """ # noqa E501 + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError( + 'If the `request` argument is set, then none of ' + 'the individual field arguments should be set.' + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, engine.GetQuantumProcessorConfigRequest): + request = engine.GetQuantumProcessorConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_quantum_processor_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1406,16 +1969,23 @@ def sample_get_quantum_processor(): def list_quantum_calibrations( self, - request: engine.ListQuantumCalibrationsRequest | dict | None = None, + request: Optional[engine.ListQuantumCalibrationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumCalibrationsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_calibrations(): @@ -1434,27 +2004,28 @@ def sample_list_quantum_calibrations(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumCalibrationsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumCalibrationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumCalibrationsRequest): request = engine.ListQuantumCalibrationsRequest(request) @@ -1468,13 +2039,21 @@ def sample_list_quantum_calibrations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumCalibrationsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1482,16 +2061,23 @@ def sample_list_quantum_calibrations(): def get_quantum_calibration( self, - request: engine.GetQuantumCalibrationRequest | dict | None = None, + request: Optional[engine.GetQuantumCalibrationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumCalibration: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_calibration(): @@ -1509,23 +2095,23 @@ def sample_get_quantum_calibration(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumCalibrationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumCalibration: + cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumCalibrationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumCalibrationRequest): request = engine.GetQuantumCalibrationRequest(request) @@ -1539,6 +2125,9 @@ def sample_get_quantum_calibration(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1547,16 +2136,23 @@ def sample_get_quantum_calibration(): def create_quantum_reservation( self, - request: engine.CreateQuantumReservationRequest | dict | None = None, + request: Optional[engine.CreateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_create_quantum_reservation(): @@ -1574,23 +2170,23 @@ def sample_create_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CreateQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CreateQuantumReservationRequest): request = engine.CreateQuantumReservationRequest(request) @@ -1604,6 +2200,9 @@ def sample_create_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1612,16 +2211,23 @@ def sample_create_quantum_reservation(): def cancel_quantum_reservation( self, - request: engine.CancelQuantumReservationRequest | dict | None = None, + request: Optional[engine.CancelQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_cancel_quantum_reservation(): @@ -1639,23 +2245,23 @@ def sample_cancel_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.CancelQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.CancelQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.CancelQuantumReservationRequest): request = engine.CancelQuantumReservationRequest(request) @@ -1669,6 +2275,9 @@ def sample_cancel_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1677,16 +2286,23 @@ def sample_cancel_quantum_reservation(): def delete_quantum_reservation( self, - request: engine.DeleteQuantumReservationRequest | dict | None = None, + request: Optional[engine.DeleteQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> None: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_delete_quantum_reservation(): @@ -1701,19 +2317,19 @@ def sample_delete_quantum_reservation(): client.delete_quantum_reservation(request=request) Args: - request (google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.DeleteQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.DeleteQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.DeleteQuantumReservationRequest): request = engine.DeleteQuantumReservationRequest(request) @@ -1727,21 +2343,31 @@ def sample_delete_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. rpc(request, retry=retry, timeout=timeout, metadata=metadata) def get_quantum_reservation( self, - request: engine.GetQuantumReservationRequest | dict | None = None, + request: Optional[engine.GetQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_get_quantum_reservation(): @@ -1759,23 +2385,23 @@ def sample_get_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.GetQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.GetQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.GetQuantumReservationRequest): request = engine.GetQuantumReservationRequest(request) @@ -1789,6 +2415,9 @@ def sample_get_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1797,16 +2426,23 @@ def sample_get_quantum_reservation(): def list_quantum_reservations( self, - request: engine.ListQuantumReservationsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservations(): @@ -1825,27 +2461,28 @@ def sample_list_quantum_reservations(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationsRequest): request = engine.ListQuantumReservationsRequest(request) @@ -1859,13 +2496,21 @@ def sample_list_quantum_reservations(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -1873,16 +2518,23 @@ def sample_list_quantum_reservations(): def update_quantum_reservation( self, - request: engine.UpdateQuantumReservationRequest | dict | None = None, + request: Optional[engine.UpdateQuantumReservationRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservation: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_update_quantum_reservation(): @@ -1900,23 +2552,23 @@ def sample_update_quantum_reservation(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.UpdateQuantumReservationRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservation: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.UpdateQuantumReservationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.UpdateQuantumReservationRequest): request = engine.UpdateQuantumReservationRequest(request) @@ -1930,6 +2582,9 @@ def sample_update_quantum_reservation(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -1938,16 +2593,23 @@ def sample_update_quantum_reservation(): def quantum_run_stream( self, - requests: Iterator[engine.QuantumRunStreamRequest] | None = None, + requests: Optional[Iterator[engine.QuantumRunStreamRequest]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> Iterable[engine.QuantumRunStreamResponse]: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_quantum_run_stream(): @@ -1976,16 +2638,18 @@ def request_generator(): print(response) Args: - requests (Iterator[google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest]): + requests (Iterator[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamRequest]): The request object iterator. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - Iterable[google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: + Iterable[cirq_google.cloud.quantum_v1alpha1.types.QuantumRunStreamResponse]: - """ @@ -1993,6 +2657,9 @@ def request_generator(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.quantum_run_stream] + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) @@ -2001,16 +2668,23 @@ def request_generator(): def list_quantum_reservation_grants( self, - request: engine.ListQuantumReservationGrantsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationGrantsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationGrantsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservation_grants(): @@ -2029,27 +2703,28 @@ def sample_list_quantum_reservation_grants(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationGrantsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationGrantsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationGrantsRequest): request = engine.ListQuantumReservationGrantsRequest(request) @@ -2063,13 +2738,21 @@ def sample_list_quantum_reservation_grants(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationGrantsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -2077,16 +2760,23 @@ def sample_list_quantum_reservation_grants(): def reallocate_quantum_reservation_grant( self, - request: engine.ReallocateQuantumReservationGrantRequest | dict | None = None, + request: Optional[engine.ReallocateQuantumReservationGrantRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> quantum.QuantumReservationGrant: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_reallocate_quantum_reservation_grant(): @@ -2104,23 +2794,23 @@ def sample_reallocate_quantum_reservation_grant(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ReallocateQuantumReservationGrantRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: + cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant: - - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ReallocateQuantumReservationGrantRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ReallocateQuantumReservationGrantRequest): request = engine.ReallocateQuantumReservationGrantRequest(request) @@ -2134,6 +2824,9 @@ def sample_reallocate_quantum_reservation_grant(): gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) @@ -2142,16 +2835,23 @@ def sample_reallocate_quantum_reservation_grant(): def list_quantum_reservation_budgets( self, - request: engine.ListQuantumReservationBudgetsRequest | dict | None = None, + request: Optional[engine.ListQuantumReservationBudgetsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumReservationBudgetsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_reservation_budgets(): @@ -2170,27 +2870,28 @@ def sample_list_quantum_reservation_budgets(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumReservationBudgetsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumReservationBudgetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumReservationBudgetsRequest): request = engine.ListQuantumReservationBudgetsRequest(request) @@ -2204,13 +2905,21 @@ def sample_list_quantum_reservation_budgets(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumReservationBudgetsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. @@ -2218,16 +2927,23 @@ def sample_list_quantum_reservation_budgets(): def list_quantum_time_slots( self, - request: engine.ListQuantumTimeSlotsRequest | dict | None = None, + request: Optional[engine.ListQuantumTimeSlotsRequest | dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float | None = None, - metadata: Sequence[tuple[str, str]] = (), + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ) -> pagers.ListQuantumTimeSlotsPager: r"""- .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import quantum_v1alpha1 def sample_list_quantum_time_slots(): @@ -2246,27 +2962,28 @@ def sample_list_quantum_time_slots(): print(response) Args: - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest | dict): + request (Union[cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest, dict]): The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: - google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsPager: + cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.pagers.ListQuantumTimeSlotsPager: - + Iterating over this object will yield results and resolve additional pages automatically. - """ + """ # noqa E501 # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a engine.ListQuantumTimeSlotsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, engine.ListQuantumTimeSlotsRequest): request = engine.ListQuantumTimeSlotsRequest(request) @@ -2280,22 +2997,30 @@ def sample_list_quantum_time_slots(): gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) + # Validate the universe domain. + self._validate_universe_domain() + # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListQuantumTimeSlotsPager( - method=rpc, request=request, response=response, metadata=metadata + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - def __enter__(self): + def __enter__(self) -> "QuantumEngineServiceClient": return self - def __exit__(self, type_, value, traceback): + def __exit__(self, typ, value, traceback): """Releases underlying transport's resources. .. warning:: @@ -2306,12 +3031,9 @@ def __exit__(self, type_, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ __all__ = ("QuantumEngineServiceClient",) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py index a2c2963fb46..e4350252fd7 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/pagers.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,10 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Sequence -from __future__ import annotations +from google.api_core import gapic_v1, retry as retries, retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Sequence +try: + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None + OptionalAsyncRetry = retries_async.AsyncRetry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.Retry | object | None # type: ignore + OptionalAsyncRetry = retries_async.AsyncRetry | object | None # type: ignore from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum @@ -25,7 +31,7 @@ class ListQuantumProgramsPager: """A pager for iterating through ``list_quantum_programs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and provides an ``__iter__`` method to iterate through its ``programs`` field. @@ -34,7 +40,7 @@ class ListQuantumProgramsPager: through the ``programs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -45,23 +51,32 @@ def __init__( request: engine.ListQuantumProgramsRequest, response: engine.ListQuantumProgramsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProgramsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -72,7 +87,9 @@ def pages(self) -> Iterator[engine.ListQuantumProgramsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumProgram]: @@ -80,14 +97,14 @@ def __iter__(self) -> Iterator[quantum.QuantumProgram]: yield from page.programs def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProgramsAsyncPager: """A pager for iterating through ``list_quantum_programs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` object, and provides an ``__aiter__`` method to iterate through its ``programs`` field. @@ -96,7 +113,7 @@ class ListQuantumProgramsAsyncPager: through the ``programs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -107,23 +124,32 @@ def __init__( request: engine.ListQuantumProgramsRequest, response: engine.ListQuantumProgramsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProgramsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProgramsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -134,7 +160,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumProgramsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumProgram]: @@ -146,14 +174,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobsPager: """A pager for iterating through ``list_quantum_jobs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and provides an ``__iter__`` method to iterate through its ``jobs`` field. @@ -162,7 +190,7 @@ class ListQuantumJobsPager: through the ``jobs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -173,23 +201,32 @@ def __init__( request: engine.ListQuantumJobsRequest, response: engine.ListQuantumJobsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -200,7 +237,9 @@ def pages(self) -> Iterator[engine.ListQuantumJobsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumJob]: @@ -208,14 +247,14 @@ def __iter__(self) -> Iterator[quantum.QuantumJob]: yield from page.jobs def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobsAsyncPager: """A pager for iterating through ``list_quantum_jobs`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` object, and provides an ``__aiter__`` method to iterate through its ``jobs`` field. @@ -224,7 +263,7 @@ class ListQuantumJobsAsyncPager: through the ``jobs`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -235,23 +274,32 @@ def __init__( request: engine.ListQuantumJobsRequest, response: engine.ListQuantumJobsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -262,7 +310,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumJobsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumJob]: @@ -274,14 +324,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobEventsPager: """A pager for iterating through ``list_quantum_job_events`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and provides an ``__iter__`` method to iterate through its ``events`` field. @@ -290,7 +340,7 @@ class ListQuantumJobEventsPager: through the ``events`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -301,23 +351,32 @@ def __init__( request: engine.ListQuantumJobEventsRequest, response: engine.ListQuantumJobEventsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobEventsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -328,7 +387,9 @@ def pages(self) -> Iterator[engine.ListQuantumJobEventsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumJobEvent]: @@ -336,14 +397,14 @@ def __iter__(self) -> Iterator[quantum.QuantumJobEvent]: yield from page.events def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumJobEventsAsyncPager: """A pager for iterating through ``list_quantum_job_events`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` object, and provides an ``__aiter__`` method to iterate through its ``events`` field. @@ -352,7 +413,7 @@ class ListQuantumJobEventsAsyncPager: through the ``events`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -363,23 +424,32 @@ def __init__( request: engine.ListQuantumJobEventsRequest, response: engine.ListQuantumJobEventsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumJobEventsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumJobEventsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -390,7 +460,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumJobEventsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumJobEvent]: @@ -402,14 +474,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProcessorsPager: """A pager for iterating through ``list_quantum_processors`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and provides an ``__iter__`` method to iterate through its ``processors`` field. @@ -418,7 +490,7 @@ class ListQuantumProcessorsPager: through the ``processors`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -429,23 +501,32 @@ def __init__( request: engine.ListQuantumProcessorsRequest, response: engine.ListQuantumProcessorsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProcessorsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -456,7 +537,9 @@ def pages(self) -> Iterator[engine.ListQuantumProcessorsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumProcessor]: @@ -464,14 +547,14 @@ def __iter__(self) -> Iterator[quantum.QuantumProcessor]: yield from page.processors def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumProcessorsAsyncPager: """A pager for iterating through ``list_quantum_processors`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` object, and provides an ``__aiter__`` method to iterate through its ``processors`` field. @@ -480,7 +563,7 @@ class ListQuantumProcessorsAsyncPager: through the ``processors`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -491,23 +574,32 @@ def __init__( request: engine.ListQuantumProcessorsRequest, response: engine.ListQuantumProcessorsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumProcessorsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumProcessorsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -518,7 +610,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumProcessorsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumProcessor]: @@ -530,14 +624,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumCalibrationsPager: """A pager for iterating through ``list_quantum_calibrations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and provides an ``__iter__`` method to iterate through its ``calibrations`` field. @@ -546,7 +640,7 @@ class ListQuantumCalibrationsPager: through the ``calibrations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -557,23 +651,32 @@ def __init__( request: engine.ListQuantumCalibrationsRequest, response: engine.ListQuantumCalibrationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumCalibrationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -584,7 +687,9 @@ def pages(self) -> Iterator[engine.ListQuantumCalibrationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumCalibration]: @@ -592,14 +697,14 @@ def __iter__(self) -> Iterator[quantum.QuantumCalibration]: yield from page.calibrations def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumCalibrationsAsyncPager: """A pager for iterating through ``list_quantum_calibrations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` object, and provides an ``__aiter__`` method to iterate through its ``calibrations`` field. @@ -608,7 +713,7 @@ class ListQuantumCalibrationsAsyncPager: through the ``calibrations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -619,23 +724,32 @@ def __init__( request: engine.ListQuantumCalibrationsRequest, response: engine.ListQuantumCalibrationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumCalibrationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -646,7 +760,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumCalibrationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumCalibration]: @@ -658,14 +774,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationsPager: """A pager for iterating through ``list_quantum_reservations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and provides an ``__iter__`` method to iterate through its ``reservations`` field. @@ -674,7 +790,7 @@ class ListQuantumReservationsPager: through the ``reservations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -685,23 +801,32 @@ def __init__( request: engine.ListQuantumReservationsRequest, response: engine.ListQuantumReservationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumReservationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -712,7 +837,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservation]: @@ -720,14 +847,14 @@ def __iter__(self) -> Iterator[quantum.QuantumReservation]: yield from page.reservations def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationsAsyncPager: """A pager for iterating through ``list_quantum_reservations`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` object, and provides an ``__aiter__`` method to iterate through its ``reservations`` field. @@ -736,7 +863,7 @@ class ListQuantumReservationsAsyncPager: through the ``reservations`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -747,23 +874,32 @@ def __init__( request: engine.ListQuantumReservationsRequest, response: engine.ListQuantumReservationsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumReservationsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -774,7 +910,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservation]: @@ -786,25 +924,25 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationGrantsPager: """A pager for iterating through ``list_quantum_reservation_grants`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``reservation_grants`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, + and provides an ``__iter__`` method to iterate through its ``reservation_grants`` field. If there are more pages, the ``__iter__`` method will make additional ``ListQuantumReservationGrants`` requests and continue to iterate through the ``reservation_grants`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -813,23 +951,32 @@ def __init__( request: engine.ListQuantumReservationGrantsRequest, response: engine.ListQuantumReservationGrantsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationGrantsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -840,7 +987,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationGrantsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservationGrant]: @@ -848,25 +997,25 @@ def __iter__(self) -> Iterator[quantum.QuantumReservationGrant]: yield from page.reservation_grants def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationGrantsAsyncPager: """A pager for iterating through ``list_quantum_reservation_grants`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``reservation_grants`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` object, + and provides an ``__aiter__`` method to iterate through its ``reservation_grants`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListQuantumReservationGrants`` requests and continue to iterate through the ``reservation_grants`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -875,23 +1024,32 @@ def __init__( request: engine.ListQuantumReservationGrantsRequest, response: engine.ListQuantumReservationGrantsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationGrantsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationGrantsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -902,7 +1060,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationGrantsRespon yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservationGrant]: @@ -914,25 +1074,25 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationBudgetsPager: """A pager for iterating through ``list_quantum_reservation_budgets`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``reservation_budgets`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, + and provides an ``__iter__`` method to iterate through its ``reservation_budgets`` field. If there are more pages, the ``__iter__`` method will make additional ``ListQuantumReservationBudgets`` requests and continue to iterate through the ``reservation_budgets`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -941,23 +1101,32 @@ def __init__( request: engine.ListQuantumReservationBudgetsRequest, response: engine.ListQuantumReservationBudgetsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationBudgetsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -968,7 +1137,9 @@ def pages(self) -> Iterator[engine.ListQuantumReservationBudgetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumReservationBudget]: @@ -976,25 +1147,25 @@ def __iter__(self) -> Iterator[quantum.QuantumReservationBudget]: yield from page.reservation_budgets def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumReservationBudgetsAsyncPager: """A pager for iterating through ``list_quantum_reservation_budgets`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``reservation_budgets`` field. + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` object, + and provides an ``__aiter__`` method to iterate through its ``reservation_budgets`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListQuantumReservationBudgets`` requests and continue to iterate through the ``reservation_budgets`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. + All the usual + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse` + attributes are available on the pager. If multiple requests are made, only the most recent + response is retained, and thus used for attribute lookup. """ def __init__( @@ -1003,23 +1174,32 @@ def __init__( request: engine.ListQuantumReservationBudgetsRequest, response: engine.ListQuantumReservationBudgetsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumReservationBudgetsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ # noqa E501 self._method = method self._request = engine.ListQuantumReservationBudgetsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1030,7 +1210,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumReservationBudgetsRespo yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumReservationBudget]: @@ -1042,14 +1224,14 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumTimeSlotsPager: """A pager for iterating through ``list_quantum_time_slots`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and provides an ``__iter__`` method to iterate through its ``time_slots`` field. @@ -1058,7 +1240,7 @@ class ListQuantumTimeSlotsPager: through the ``time_slots`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -1069,23 +1251,32 @@ def __init__( request: engine.ListQuantumTimeSlotsRequest, response: engine.ListQuantumTimeSlotsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumTimeSlotsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1096,7 +1287,9 @@ def pages(self) -> Iterator[engine.ListQuantumTimeSlotsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) + self._response = self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __iter__(self) -> Iterator[quantum.QuantumTimeSlot]: @@ -1104,14 +1297,14 @@ def __iter__(self) -> Iterator[quantum.QuantumTimeSlot]: yield from page.time_slots def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListQuantumTimeSlotsAsyncPager: """A pager for iterating through ``list_quantum_time_slots`` requests. This class thinly wraps an initial - :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and + :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` object, and provides an ``__aiter__`` method to iterate through its ``time_slots`` field. @@ -1120,7 +1313,7 @@ class ListQuantumTimeSlotsAsyncPager: through the ``time_slots`` field on the corresponding responses. - All the usual :class:`google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` + All the usual :class:`cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -1131,23 +1324,32 @@ def __init__( request: engine.ListQuantumTimeSlotsRequest, response: engine.ListQuantumTimeSlotsResponse, *, - metadata: Sequence[tuple[str, str]] = (), + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: float | object = gapic_v1.method.DEFAULT, + metadata: Sequence[tuple[str, str | bytes]] = (), ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): + request (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsRequest): The initial request object. - response (google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): + response (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumTimeSlotsResponse): The initial response object. - metadata (Sequence[tuple[str, str]]): Strings which should be - sent along with the request as metadata. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = engine.ListQuantumTimeSlotsRequest(request) self._response = response + self._retry = retry + self._timeout = timeout self._metadata = metadata def __getattr__(self, name: str) -> Any: @@ -1158,7 +1360,9 @@ async def pages(self) -> AsyncIterator[engine.ListQuantumTimeSlotsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) + self._response = await self._method( + self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata + ) yield self._response def __aiter__(self) -> AsyncIterator[quantum.QuantumTimeSlot]: @@ -1170,4 +1374,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return f'{self.__class__.__name__}<{self._response!r}>' + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst new file mode 100755 index 00000000000..2e942691dec --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`QuantumEngineServiceTransport` is the ABC for all transports. +- public child `QuantumEngineServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `QuantumEngineServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseQuantumEngineServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `QuantumEngineServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py index f6edf4f3e46..b9c62c311c4 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,15 +18,20 @@ from .base import QuantumEngineServiceTransport from .grpc import QuantumEngineServiceGrpcTransport from .grpc_asyncio import QuantumEngineServiceGrpcAsyncIOTransport +from .rest import QuantumEngineServiceRestTransport +from .rest import QuantumEngineServiceRestInterceptor # Compile a registry of transports. -_transport_registry = OrderedDict() # type: dict[str, type[QuantumEngineServiceTransport]] +_transport_registry: dict[str, type[QuantumEngineServiceTransport]] = OrderedDict() _transport_registry['grpc'] = QuantumEngineServiceGrpcTransport _transport_registry['grpc_asyncio'] = QuantumEngineServiceGrpcAsyncIOTransport +_transport_registry['rest'] = QuantumEngineServiceRestTransport __all__ = ( 'QuantumEngineServiceTransport', 'QuantumEngineServiceGrpcTransport', 'QuantumEngineServiceGrpcAsyncIOTransport', + 'QuantumEngineServiceRestTransport', + 'QuantumEngineServiceRestInterceptor', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py index ee1ebfc8bd8..62df83b82c0 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/base.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,32 +12,25 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - -from __future__ import annotations - +# import abc -import importlib.metadata -from typing import Awaitable, Callable, Sequence, TYPE_CHECKING +from typing import Awaitable, Callable, Optional, Sequence import google.api_core import google.auth +import google.protobuf from google.api_core import exceptions as core_exceptions, gapic_v1 +from google.auth import credentials as ga_credentials from google.oauth2 import service_account +from google.protobuf import empty_pb2 -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials - from google.protobuf import empty_pb2 +from cirq_google.cloud.quantum_v1alpha1 import gapic_version as package_version +from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum - from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=importlib.metadata.version("google-cloud-quantum") - ) -except ModuleNotFoundError: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ class QuantumEngineServiceTransport(abc.ABC): @@ -51,19 +44,20 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -83,15 +77,13 @@ def __init__( always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False # If no credentials are provided, then determine the appropriate # defaults. @@ -104,10 +96,14 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: + elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - # If the credentials are service account credentials, then always try to use self signed JWT. + # If the credentials are service account credentials, then always try to use self signed + # JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) @@ -118,6 +114,15 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -166,6 +171,9 @@ def _prep_wrapped_messages(self, client_info): self.get_quantum_processor: gapic_v1.method.wrap_method( self.get_quantum_processor, default_timeout=60.0, client_info=client_info ), + self.get_quantum_processor_config: gapic_v1.method.wrap_method( + self.get_quantum_processor_config, default_timeout=60.0, client_info=client_info + ), self.list_quantum_calibrations: gapic_v1.method.wrap_method( self.list_quantum_calibrations, default_timeout=60.0, client_info=client_info ), @@ -342,6 +350,15 @@ def get_quantum_processor( ]: raise NotImplementedError() + @property + def get_quantum_processor_config( + self, + ) -> Callable[ + [engine.GetQuantumProcessorConfigRequest], + quantum.QuantumProcessorConfig | Awaitable[quantum.QuantumProcessorConfig], + ]: + raise NotImplementedError() + @property def list_quantum_calibrations( self, @@ -460,5 +477,9 @@ def list_quantum_time_slots( ]: raise NotImplementedError() + @property + def kind(self) -> str: + raise NotImplementedError() + __all__ = ('QuantumEngineServiceTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py index 91ff63267f8..50d42b6c358 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,23 +13,86 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from __future__ import annotations - +import importlib.util +import logging as std_logging +import pickle import warnings -from typing import Callable, Sequence, TYPE_CHECKING +from typing import Callable, Optional, Sequence +import google.auth +import google.protobuf.message import grpc # type: ignore +import proto from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials from google.auth.transport.grpc import SslCredentials from google.protobuf import empty_pb2 +from google.protobuf.json_format import MessageToJson from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = {"payload": response_payload, "metadata": metadata, "status": "OK"} + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response class QuantumEngineServiceGrpcTransport(QuantumEngineServiceTransport): @@ -51,50 +114,54 @@ def __init__( self, *, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - channel: grpc.Channel | None = None, - api_mtls_endpoint: str | None = None, - client_cert_source: Callable[[], tuple[bytes, bytes]] | None = None, - ssl_channel_credentials: grpc.ChannelCredentials | None = None, - client_cert_source_for_mtls: Callable[[], tuple[bytes, bytes]] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel | Callable[..., grpc.Channel]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], tuple[bytes, bytes]]]): + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], tuple[bytes, bytes]]]): + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -120,9 +187,10 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, grpc.Channel): # Ignore credentials if a channel was passed. credentials = None + self._ignore_credentials = True # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None @@ -157,10 +225,13 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -171,23 +242,25 @@ def __init__( ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ - ('grpc.max_send_message_length', 20 * 1024 * 1024), # 20MiB - ('grpc.max_receive_message_length', -1), # unlimited - ('grpc.max_metadata_length', 10 * 1024 * 1024), # 10MiB + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -251,7 +324,7 @@ def create_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_program' not in self._stubs: - self._stubs['create_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumProgram', request_serializer=engine.CreateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -277,7 +350,7 @@ def get_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_program' not in self._stubs: - self._stubs['get_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProgram', request_serializer=engine.GetQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -303,7 +376,7 @@ def list_quantum_programs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_programs' not in self._stubs: - self._stubs['list_quantum_programs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_programs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumPrograms', request_serializer=engine.ListQuantumProgramsRequest.serialize, response_deserializer=engine.ListQuantumProgramsResponse.deserialize, @@ -329,7 +402,7 @@ def delete_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_program' not in self._stubs: - self._stubs['delete_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumProgram', request_serializer=engine.DeleteQuantumProgramRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -355,7 +428,7 @@ def update_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_program' not in self._stubs: - self._stubs['update_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumProgram', request_serializer=engine.UpdateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -379,7 +452,7 @@ def create_quantum_job(self) -> Callable[[engine.CreateQuantumJobRequest], quant # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_job' not in self._stubs: - self._stubs['create_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumJob', request_serializer=engine.CreateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -403,7 +476,7 @@ def get_quantum_job(self) -> Callable[[engine.GetQuantumJobRequest], quantum.Qua # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_job' not in self._stubs: - self._stubs['get_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumJob', request_serializer=engine.GetQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -429,7 +502,7 @@ def list_quantum_jobs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_jobs' not in self._stubs: - self._stubs['list_quantum_jobs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_jobs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobs', request_serializer=engine.ListQuantumJobsRequest.serialize, response_deserializer=engine.ListQuantumJobsResponse.deserialize, @@ -453,7 +526,7 @@ def delete_quantum_job(self) -> Callable[[engine.DeleteQuantumJobRequest], empty # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_job' not in self._stubs: - self._stubs['delete_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumJob', request_serializer=engine.DeleteQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -477,7 +550,7 @@ def update_quantum_job(self) -> Callable[[engine.UpdateQuantumJobRequest], quant # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_job' not in self._stubs: - self._stubs['update_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumJob', request_serializer=engine.UpdateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -501,7 +574,7 @@ def cancel_quantum_job(self) -> Callable[[engine.CancelQuantumJobRequest], empty # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_job' not in self._stubs: - self._stubs['cancel_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumJob', request_serializer=engine.CancelQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -527,7 +600,7 @@ def list_quantum_job_events( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_job_events' not in self._stubs: - self._stubs['list_quantum_job_events'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_job_events'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobEvents', request_serializer=engine.ListQuantumJobEventsRequest.serialize, response_deserializer=engine.ListQuantumJobEventsResponse.deserialize, @@ -553,7 +626,7 @@ def get_quantum_result( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_result' not in self._stubs: - self._stubs['get_quantum_result'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_result'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumResult', request_serializer=engine.GetQuantumResultRequest.serialize, response_deserializer=quantum.QuantumResult.deserialize, @@ -579,7 +652,7 @@ def list_quantum_processors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_processors' not in self._stubs: - self._stubs['list_quantum_processors'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_processors'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumProcessors', request_serializer=engine.ListQuantumProcessorsRequest.serialize, response_deserializer=engine.ListQuantumProcessorsResponse.deserialize, @@ -605,13 +678,39 @@ def get_quantum_processor( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_processor' not in self._stubs: - self._stubs['get_quantum_processor'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_processor'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessor', request_serializer=engine.GetQuantumProcessorRequest.serialize, response_deserializer=quantum.QuantumProcessor.deserialize, ) return self._stubs['get_quantum_processor'] + @property + def get_quantum_processor_config( + self, + ) -> Callable[[engine.GetQuantumProcessorConfigRequest], quantum.QuantumProcessorConfig]: + r"""Return a callable for the get quantum processor config method over gRPC. + + - + + Returns: + Callable[[~.GetQuantumProcessorConfigRequest], + ~.QuantumProcessorConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_quantum_processor_config' not in self._stubs: + self._stubs['get_quantum_processor_config'] = self._logged_channel.unary_unary( + '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessorConfig', + request_serializer=engine.GetQuantumProcessorConfigRequest.serialize, + response_deserializer=quantum.QuantumProcessorConfig.deserialize, + ) + return self._stubs['get_quantum_processor_config'] + @property def list_quantum_calibrations( self, @@ -631,7 +730,7 @@ def list_quantum_calibrations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_calibrations' not in self._stubs: - self._stubs['list_quantum_calibrations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_calibrations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumCalibrations', request_serializer=engine.ListQuantumCalibrationsRequest.serialize, response_deserializer=engine.ListQuantumCalibrationsResponse.deserialize, @@ -657,7 +756,7 @@ def get_quantum_calibration( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_calibration' not in self._stubs: - self._stubs['get_quantum_calibration'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_calibration'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumCalibration', request_serializer=engine.GetQuantumCalibrationRequest.serialize, response_deserializer=quantum.QuantumCalibration.deserialize, @@ -683,7 +782,7 @@ def create_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_reservation' not in self._stubs: - self._stubs['create_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumReservation', request_serializer=engine.CreateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -709,7 +808,7 @@ def cancel_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_reservation' not in self._stubs: - self._stubs['cancel_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumReservation', request_serializer=engine.CancelQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -735,7 +834,7 @@ def delete_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_reservation' not in self._stubs: - self._stubs['delete_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumReservation', request_serializer=engine.DeleteQuantumReservationRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -761,7 +860,7 @@ def get_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_reservation' not in self._stubs: - self._stubs['get_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumReservation', request_serializer=engine.GetQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -787,7 +886,7 @@ def list_quantum_reservations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservations' not in self._stubs: - self._stubs['list_quantum_reservations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservations', request_serializer=engine.ListQuantumReservationsRequest.serialize, response_deserializer=engine.ListQuantumReservationsResponse.deserialize, @@ -813,7 +912,7 @@ def update_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_reservation' not in self._stubs: - self._stubs['update_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumReservation', request_serializer=engine.UpdateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -839,7 +938,7 @@ def quantum_run_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'quantum_run_stream' not in self._stubs: - self._stubs['quantum_run_stream'] = self.grpc_channel.stream_stream( + self._stubs['quantum_run_stream'] = self._logged_channel.stream_stream( '/google.cloud.quantum.v1alpha1.QuantumEngineService/QuantumRunStream', request_serializer=engine.QuantumRunStreamRequest.serialize, response_deserializer=engine.QuantumRunStreamResponse.deserialize, @@ -868,7 +967,7 @@ def list_quantum_reservation_grants( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_grants' not in self._stubs: - self._stubs['list_quantum_reservation_grants'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_grants'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationGrants', request_serializer=engine.ListQuantumReservationGrantsRequest.serialize, response_deserializer=engine.ListQuantumReservationGrantsResponse.deserialize, @@ -897,7 +996,7 @@ def reallocate_quantum_reservation_grant( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'reallocate_quantum_reservation_grant' not in self._stubs: - self._stubs['reallocate_quantum_reservation_grant'] = self.grpc_channel.unary_unary( + self._stubs['reallocate_quantum_reservation_grant'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ReallocateQuantumReservationGrant', request_serializer=engine.ReallocateQuantumReservationGrantRequest.serialize, response_deserializer=quantum.QuantumReservationGrant.deserialize, @@ -926,7 +1025,7 @@ def list_quantum_reservation_budgets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_budgets' not in self._stubs: - self._stubs['list_quantum_reservation_budgets'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_budgets'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationBudgets', request_serializer=engine.ListQuantumReservationBudgetsRequest.serialize, response_deserializer=engine.ListQuantumReservationBudgetsResponse.deserialize, @@ -952,7 +1051,7 @@ def list_quantum_time_slots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_time_slots' not in self._stubs: - self._stubs['list_quantum_time_slots'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_time_slots'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumTimeSlots', request_serializer=engine.ListQuantumTimeSlotsRequest.serialize, response_deserializer=engine.ListQuantumTimeSlotsResponse.deserialize, @@ -960,7 +1059,11 @@ def list_quantum_time_slots( return self._stubs['list_quantum_time_slots'] def close(self): - self.grpc_channel.close() + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" __all__ = ('QuantumEngineServiceGrpcTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py index 42fdf91e477..61e6cd3c935 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/grpc_asyncio.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,24 +13,87 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -from __future__ import annotations - +import importlib.util +import inspect +import logging as std_logging +import pickle import warnings -from typing import Awaitable, Callable, Sequence, TYPE_CHECKING +from typing import Awaitable, Callable, Optional, Sequence +import google.protobuf.message import grpc # type: ignore +import proto from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials from google.auth.transport.grpc import SslCredentials from google.protobuf import empty_pb2 +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport -if TYPE_CHECKING: - from google.auth import credentials as ga_credentials - from grpc.experimental import aio # type: ignore +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = {"payload": response_payload, "metadata": metadata, "status": "OK"} + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response class QuantumEngineServiceGrpcAsyncIOTransport(QuantumEngineServiceTransport): @@ -53,10 +116,10 @@ class QuantumEngineServiceGrpcAsyncIOTransport(QuantumEngineServiceTransport): def create_channel( cls, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - quota_project_id: str | None = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. @@ -69,7 +132,6 @@ def create_channel( the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -96,51 +158,55 @@ def __init__( self, *, host: str = 'quantum.googleapis.com', - credentials: ga_credentials.Credentials | None = None, - credentials_file: str | None = None, - scopes: Sequence[str] | None = None, - channel: aio.Channel | None = None, - api_mtls_endpoint: str | None = None, - client_cert_source: Callable[[], tuple[bytes, bytes]] | None = None, - ssl_channel_credentials: grpc.ChannelCredentials | None = None, - client_cert_source_for_mtls: Callable[[], tuple[bytes, bytes]] | None = None, - quota_project_id=None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel | Callable[..., aio.Channel]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: bool | None = False, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. Args: host (Optional[str]): - The hostname to connect to. + The hostname to connect to (default: 'quantum.googleapis.com'). credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], tuple[bytes, bytes]]]): + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], tuple[bytes, bytes]]]): + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -166,9 +232,10 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, aio.Channel): # Ignore credentials if a channel was passed. credentials = None + self._ignore_credentials = True # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None @@ -202,10 +269,13 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -216,13 +286,18 @@ def __init__( ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ - ('grpc.max_send_message_length', 20 * 1024 * 1024), # 20MiB - ('grpc.max_receive_message_length', -1), # unlimited - ('grpc.max_metadata_length', 10 * 1024 * 1024), # 10MiB + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -254,7 +329,7 @@ def create_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_program' not in self._stubs: - self._stubs['create_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumProgram', request_serializer=engine.CreateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -280,7 +355,7 @@ def get_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_program' not in self._stubs: - self._stubs['get_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProgram', request_serializer=engine.GetQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -308,7 +383,7 @@ def list_quantum_programs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_programs' not in self._stubs: - self._stubs['list_quantum_programs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_programs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumPrograms', request_serializer=engine.ListQuantumProgramsRequest.serialize, response_deserializer=engine.ListQuantumProgramsResponse.deserialize, @@ -334,7 +409,7 @@ def delete_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_program' not in self._stubs: - self._stubs['delete_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumProgram', request_serializer=engine.DeleteQuantumProgramRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -360,7 +435,7 @@ def update_quantum_program( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_program' not in self._stubs: - self._stubs['update_quantum_program'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_program'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumProgram', request_serializer=engine.UpdateQuantumProgramRequest.serialize, response_deserializer=quantum.QuantumProgram.deserialize, @@ -386,7 +461,7 @@ def create_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_job' not in self._stubs: - self._stubs['create_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumJob', request_serializer=engine.CreateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -412,7 +487,7 @@ def get_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_job' not in self._stubs: - self._stubs['get_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumJob', request_serializer=engine.GetQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -438,7 +513,7 @@ def list_quantum_jobs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_jobs' not in self._stubs: - self._stubs['list_quantum_jobs'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_jobs'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobs', request_serializer=engine.ListQuantumJobsRequest.serialize, response_deserializer=engine.ListQuantumJobsResponse.deserialize, @@ -464,7 +539,7 @@ def delete_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_job' not in self._stubs: - self._stubs['delete_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumJob', request_serializer=engine.DeleteQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -490,7 +565,7 @@ def update_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_job' not in self._stubs: - self._stubs['update_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumJob', request_serializer=engine.UpdateQuantumJobRequest.serialize, response_deserializer=quantum.QuantumJob.deserialize, @@ -516,7 +591,7 @@ def cancel_quantum_job( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_job' not in self._stubs: - self._stubs['cancel_quantum_job'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_job'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumJob', request_serializer=engine.CancelQuantumJobRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -544,7 +619,7 @@ def list_quantum_job_events( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_job_events' not in self._stubs: - self._stubs['list_quantum_job_events'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_job_events'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobEvents', request_serializer=engine.ListQuantumJobEventsRequest.serialize, response_deserializer=engine.ListQuantumJobEventsResponse.deserialize, @@ -570,7 +645,7 @@ def get_quantum_result( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_result' not in self._stubs: - self._stubs['get_quantum_result'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_result'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumResult', request_serializer=engine.GetQuantumResultRequest.serialize, response_deserializer=quantum.QuantumResult.deserialize, @@ -598,7 +673,7 @@ def list_quantum_processors( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_processors' not in self._stubs: - self._stubs['list_quantum_processors'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_processors'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumProcessors', request_serializer=engine.ListQuantumProcessorsRequest.serialize, response_deserializer=engine.ListQuantumProcessorsResponse.deserialize, @@ -624,13 +699,41 @@ def get_quantum_processor( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_processor' not in self._stubs: - self._stubs['get_quantum_processor'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_processor'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessor', request_serializer=engine.GetQuantumProcessorRequest.serialize, response_deserializer=quantum.QuantumProcessor.deserialize, ) return self._stubs['get_quantum_processor'] + @property + def get_quantum_processor_config( + self, + ) -> Callable[ + [engine.GetQuantumProcessorConfigRequest], Awaitable[quantum.QuantumProcessorConfig] + ]: + r"""Return a callable for the get quantum processor config method over gRPC. + + - + + Returns: + Callable[[~.GetQuantumProcessorConfigRequest], + Awaitable[~.QuantumProcessorConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_quantum_processor_config' not in self._stubs: + self._stubs['get_quantum_processor_config'] = self._logged_channel.unary_unary( + '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessorConfig', + request_serializer=engine.GetQuantumProcessorConfigRequest.serialize, + response_deserializer=quantum.QuantumProcessorConfig.deserialize, + ) + return self._stubs['get_quantum_processor_config'] + @property def list_quantum_calibrations( self, @@ -652,7 +755,7 @@ def list_quantum_calibrations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_calibrations' not in self._stubs: - self._stubs['list_quantum_calibrations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_calibrations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumCalibrations', request_serializer=engine.ListQuantumCalibrationsRequest.serialize, response_deserializer=engine.ListQuantumCalibrationsResponse.deserialize, @@ -678,7 +781,7 @@ def get_quantum_calibration( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_calibration' not in self._stubs: - self._stubs['get_quantum_calibration'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_calibration'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumCalibration', request_serializer=engine.GetQuantumCalibrationRequest.serialize, response_deserializer=quantum.QuantumCalibration.deserialize, @@ -704,7 +807,7 @@ def create_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'create_quantum_reservation' not in self._stubs: - self._stubs['create_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['create_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumReservation', request_serializer=engine.CreateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -730,7 +833,7 @@ def cancel_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'cancel_quantum_reservation' not in self._stubs: - self._stubs['cancel_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['cancel_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumReservation', request_serializer=engine.CancelQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -756,7 +859,7 @@ def delete_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'delete_quantum_reservation' not in self._stubs: - self._stubs['delete_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['delete_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumReservation', request_serializer=engine.DeleteQuantumReservationRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, @@ -782,7 +885,7 @@ def get_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'get_quantum_reservation' not in self._stubs: - self._stubs['get_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['get_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumReservation', request_serializer=engine.GetQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -810,7 +913,7 @@ def list_quantum_reservations( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservations' not in self._stubs: - self._stubs['list_quantum_reservations'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservations'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservations', request_serializer=engine.ListQuantumReservationsRequest.serialize, response_deserializer=engine.ListQuantumReservationsResponse.deserialize, @@ -836,7 +939,7 @@ def update_quantum_reservation( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'update_quantum_reservation' not in self._stubs: - self._stubs['update_quantum_reservation'] = self.grpc_channel.unary_unary( + self._stubs['update_quantum_reservation'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumReservation', request_serializer=engine.UpdateQuantumReservationRequest.serialize, response_deserializer=quantum.QuantumReservation.deserialize, @@ -862,7 +965,7 @@ def quantum_run_stream( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'quantum_run_stream' not in self._stubs: - self._stubs['quantum_run_stream'] = self.grpc_channel.stream_stream( + self._stubs['quantum_run_stream'] = self._logged_channel.stream_stream( '/google.cloud.quantum.v1alpha1.QuantumEngineService/QuantumRunStream', request_serializer=engine.QuantumRunStreamRequest.serialize, response_deserializer=engine.QuantumRunStreamResponse.deserialize, @@ -892,7 +995,7 @@ def list_quantum_reservation_grants( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_grants' not in self._stubs: - self._stubs['list_quantum_reservation_grants'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_grants'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationGrants', request_serializer=engine.ListQuantumReservationGrantsRequest.serialize, response_deserializer=engine.ListQuantumReservationGrantsResponse.deserialize, @@ -922,7 +1025,7 @@ def reallocate_quantum_reservation_grant( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'reallocate_quantum_reservation_grant' not in self._stubs: - self._stubs['reallocate_quantum_reservation_grant'] = self.grpc_channel.unary_unary( + self._stubs['reallocate_quantum_reservation_grant'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ReallocateQuantumReservationGrant', request_serializer=engine.ReallocateQuantumReservationGrantRequest.serialize, response_deserializer=quantum.QuantumReservationGrant.deserialize, @@ -952,7 +1055,7 @@ def list_quantum_reservation_budgets( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_reservation_budgets' not in self._stubs: - self._stubs['list_quantum_reservation_budgets'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_reservation_budgets'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationBudgets', request_serializer=engine.ListQuantumReservationBudgetsRequest.serialize, response_deserializer=engine.ListQuantumReservationBudgetsResponse.deserialize, @@ -980,15 +1083,118 @@ def list_quantum_time_slots( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if 'list_quantum_time_slots' not in self._stubs: - self._stubs['list_quantum_time_slots'] = self.grpc_channel.unary_unary( + self._stubs['list_quantum_time_slots'] = self._logged_channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumTimeSlots', request_serializer=engine.ListQuantumTimeSlotsRequest.serialize, response_deserializer=engine.ListQuantumTimeSlotsResponse.deserialize, ) return self._stubs['list_quantum_time_slots'] + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" # noqa E501 + self._wrapped_methods = { + self.create_quantum_program: self._wrap_method( + self.create_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_program: self._wrap_method( + self.get_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_programs: self._wrap_method( + self.list_quantum_programs, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_program: self._wrap_method( + self.delete_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_program: self._wrap_method( + self.update_quantum_program, default_timeout=60.0, client_info=client_info + ), + self.create_quantum_job: self._wrap_method( + self.create_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_job: self._wrap_method( + self.get_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_jobs: self._wrap_method( + self.list_quantum_jobs, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_job: self._wrap_method( + self.delete_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_job: self._wrap_method( + self.update_quantum_job, default_timeout=60.0, client_info=client_info + ), + self.cancel_quantum_job: self._wrap_method( + self.cancel_quantum_job, default_timeout=None, client_info=client_info + ), + self.list_quantum_job_events: self._wrap_method( + self.list_quantum_job_events, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_result: self._wrap_method( + self.get_quantum_result, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_processors: self._wrap_method( + self.list_quantum_processors, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_processor: self._wrap_method( + self.get_quantum_processor, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_processor_config: self._wrap_method( + self.get_quantum_processor_config, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_calibrations: self._wrap_method( + self.list_quantum_calibrations, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_calibration: self._wrap_method( + self.get_quantum_calibration, default_timeout=60.0, client_info=client_info + ), + self.create_quantum_reservation: self._wrap_method( + self.create_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.cancel_quantum_reservation: self._wrap_method( + self.cancel_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.delete_quantum_reservation: self._wrap_method( + self.delete_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.get_quantum_reservation: self._wrap_method( + self.get_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_reservations: self._wrap_method( + self.list_quantum_reservations, default_timeout=60.0, client_info=client_info + ), + self.update_quantum_reservation: self._wrap_method( + self.update_quantum_reservation, default_timeout=60.0, client_info=client_info + ), + self.quantum_run_stream: self._wrap_method( + self.quantum_run_stream, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_reservation_grants: self._wrap_method( + self.list_quantum_reservation_grants, default_timeout=60.0, client_info=client_info + ), + self.reallocate_quantum_reservation_grant: self._wrap_method( + self.reallocate_quantum_reservation_grant, + default_timeout=60.0, + client_info=client_info, + ), + self.list_quantum_reservation_budgets: self._wrap_method( + self.list_quantum_reservation_budgets, default_timeout=60.0, client_info=client_info + ), + self.list_quantum_time_slots: self._wrap_method( + self.list_quantum_time_slots, default_timeout=60.0, client_info=client_info + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" __all__ = ('QuantumEngineServiceGrpcAsyncIOTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py new file mode 100755 index 00000000000..44c8ebdbb79 --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest.py @@ -0,0 +1,5438 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import importlib.util +import logging +from typing import Callable, Optional, Sequence + +import google.protobuf +from google.api_core import ( + exceptions as core_exceptions, + gapic_v1, + rest_helpers, + rest_streaming, + retry as retries, +) +from google.auth import credentials as ga_credentials +from google.auth.transport.requests import AuthorizedSession +from google.protobuf import empty_pb2, json_format +from requests import __version__ as requests_version + +from cirq_google.cloud.quantum_v1alpha1.types import engine, quantum + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseQuantumEngineServiceRestTransport + +try: + OptionalRetry = retries.Retry | gapic_v1.method._MethodDefault | None +except AttributeError: # pragma: NO COVER + OptionalRetry = retries.Retry | object | None # type: ignore + +CLIENT_LOGGING_SUPPORTED = importlib.util.find_spec("google.api_core.client_logging") is not None + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class QuantumEngineServiceRestInterceptor: + """Interceptor for QuantumEngineService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the QuantumEngineServiceRestTransport. + + .. code-block:: python + class MyCustomQuantumEngineServiceInterceptor(QuantumEngineServiceRestInterceptor): + def pre_cancel_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_cancel_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_quantum_calibration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_calibration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_processor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_processor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_processor_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_processor_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_quantum_result(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_quantum_result(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_calibrations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_calibrations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_job_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_job_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_processors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_processors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_programs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_programs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservation_budgets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservation_budgets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservation_grants(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservation_grants(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_reservations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_reservations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_quantum_time_slots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_quantum_time_slots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reallocate_quantum_reservation_grant(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reallocate_quantum_reservation_grant(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_quantum_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_quantum_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = QuantumEngineServiceRestTransport( + interceptor=MyCustomQuantumEngineServiceInterceptor() + ) + client = QuantumEngineServiceClient(transport=transport) + + + """ + + def pre_cancel_quantum_job( + self, request: engine.CancelQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.CancelQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for cancel_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_cancel_quantum_reservation( + self, + request: engine.CancelQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CancelQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for cancel_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_cancel_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for cancel_quantum_reservation + + DEPRECATED. Please use the `post_cancel_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_cancel_quantum_reservation` interceptor runs + before the `post_cancel_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_cancel_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for cancel_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_cancel_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_cancel_quantum_reservation` interceptor. + When both interceptors are used, this `post_cancel_quantum_reservation_with_metadata` + interceptor runs after the `post_cancel_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_cancel_quantum_reservation` will be passed to + `post_cancel_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_job( + self, request: engine.CreateQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.CreateQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for create_quantum_job + + DEPRECATED. Please use the `post_create_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_job` interceptor runs + before the `post_create_quantum_job_with_metadata` interceptor. + """ + return response + + def post_create_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_job_with_metadata` + interceptor in new development instead of the `post_create_quantum_job` interceptor. + When both interceptors are used, this `post_create_quantum_job_with_metadata` interceptor + runs after the `post_create_quantum_job` interceptor. The (possibly modified) response + returned by `post_create_quantum_job` will be passed to + `post_create_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_program( + self, + request: engine.CreateQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CreateQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_program( + self, response: quantum.QuantumProgram + ) -> quantum.QuantumProgram: + """Post-rpc interceptor for create_quantum_program + + DEPRECATED. Please use the `post_create_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_program` interceptor runs + before the `post_create_quantum_program_with_metadata` interceptor. + """ + return response + + def post_create_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_program_with_metadata` + interceptor in new development instead of the `post_create_quantum_program` interceptor. + When both interceptors are used, this `post_create_quantum_program_with_metadata` + interceptor runs after the `post_create_quantum_program` interceptor. The (possibly + modified) response returned by `post_create_quantum_program` will be passed to + `post_create_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_create_quantum_reservation( + self, + request: engine.CreateQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.CreateQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for create_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_create_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for create_quantum_reservation + + DEPRECATED. Please use the `post_create_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_create_quantum_reservation` interceptor runs + before the `post_create_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_create_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for create_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_create_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_create_quantum_reservation` interceptor. + When both interceptors are used, this `post_create_quantum_reservation_with_metadata` + interceptor runs after the `post_create_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_create_quantum_reservation` will be passed to + `post_create_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_delete_quantum_job( + self, request: engine.DeleteQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.DeleteQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_delete_quantum_program( + self, + request: engine.DeleteQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.DeleteQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_delete_quantum_reservation( + self, + request: engine.DeleteQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.DeleteQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for delete_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def pre_get_quantum_calibration( + self, + request: engine.GetQuantumCalibrationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumCalibrationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_calibration + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_calibration( + self, response: quantum.QuantumCalibration + ) -> quantum.QuantumCalibration: + """Post-rpc interceptor for get_quantum_calibration + + DEPRECATED. Please use the `post_get_quantum_calibration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_calibration` interceptor runs + before the `post_get_quantum_calibration_with_metadata` interceptor. + """ + return response + + def post_get_quantum_calibration_with_metadata( + self, response: quantum.QuantumCalibration, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumCalibration, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_calibration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_calibration_with_metadata` + interceptor in new development instead of the `post_get_quantum_calibration` interceptor. + When both interceptors are used, this `post_get_quantum_calibration_with_metadata` + interceptor runs after the `post_get_quantum_calibration` interceptor. The (possibly + modified) response returned by `post_get_quantum_calibration` will be passed to + `post_get_quantum_calibration_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_job( + self, request: engine.GetQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for get_quantum_job + + DEPRECATED. Please use the `post_get_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_job` interceptor runs + before the `post_get_quantum_job_with_metadata` interceptor. + """ + return response + + def post_get_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_job_with_metadata` + interceptor in new development instead of the `post_get_quantum_job` interceptor. + When both interceptors are used, this `post_get_quantum_job_with_metadata` interceptor runs + after the `post_get_quantum_job` interceptor. The (possibly modified) response returned by + `post_get_quantum_job` will be passed to `post_get_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_processor( + self, + request: engine.GetQuantumProcessorRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumProcessorRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_processor + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_processor( + self, response: quantum.QuantumProcessor + ) -> quantum.QuantumProcessor: + """Post-rpc interceptor for get_quantum_processor + + DEPRECATED. Please use the `post_get_quantum_processor_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_processor` interceptor runs + before the `post_get_quantum_processor_with_metadata` interceptor. + """ + return response + + def post_get_quantum_processor_with_metadata( + self, response: quantum.QuantumProcessor, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProcessor, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_processor + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_processor_with_metadata` + interceptor in new development instead of the `post_get_quantum_processor` interceptor. + When both interceptors are used, this `post_get_quantum_processor_with_metadata` + interceptor runs after the `post_get_quantum_processor` interceptor. The (possibly + modified) response returned by `post_get_quantum_processor` will be passed to + `post_get_quantum_processor_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_processor_config( + self, + request: engine.GetQuantumProcessorConfigRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumProcessorConfigRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_processor_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_processor_config( + self, response: quantum.QuantumProcessorConfig + ) -> quantum.QuantumProcessorConfig: + """Post-rpc interceptor for get_quantum_processor_config + + DEPRECATED. Please use the `post_get_quantum_processor_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_processor_config` interceptor runs + before the `post_get_quantum_processor_config_with_metadata` interceptor. + """ + return response + + def post_get_quantum_processor_config_with_metadata( + self, response: quantum.QuantumProcessorConfig, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProcessorConfig, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_processor_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_processor_config_with_metadata` + interceptor in new development instead of the `post_get_quantum_processor_config` + interceptor. When both interceptors are used, this + `post_get_quantum_processor_config_with_metadata` interceptor runs after the + `post_get_quantum_processor_config` interceptor. The (possibly modified) response returned + by `post_get_quantum_processor_config` will be passed to + `post_get_quantum_processor_config_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_program( + self, request: engine.GetQuantumProgramRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_program(self, response: quantum.QuantumProgram) -> quantum.QuantumProgram: + """Post-rpc interceptor for get_quantum_program + + DEPRECATED. Please use the `post_get_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_program` interceptor runs + before the `post_get_quantum_program_with_metadata` interceptor. + """ + return response + + def post_get_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_program_with_metadata` + interceptor in new development instead of the `post_get_quantum_program` interceptor. + When both interceptors are used, this `post_get_quantum_program_with_metadata` interceptor + runs after the `post_get_quantum_program` interceptor. The (possibly modified) response + returned by `post_get_quantum_program` will be passed to + `post_get_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_reservation( + self, + request: engine.GetQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.GetQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for get_quantum_reservation + + DEPRECATED. Please use the `post_get_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_reservation` interceptor runs + before the `post_get_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_get_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_get_quantum_reservation` interceptor. + When both interceptors are used, this `post_get_quantum_reservation_with_metadata` + interceptor runs after the `post_get_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_get_quantum_reservation` will be passed to + `post_get_quantum_reservation_with_metadata`. + """ + return response, metadata + + def pre_get_quantum_result( + self, request: engine.GetQuantumResultRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.GetQuantumResultRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for get_quantum_result + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_get_quantum_result(self, response: quantum.QuantumResult) -> quantum.QuantumResult: + """Post-rpc interceptor for get_quantum_result + + DEPRECATED. Please use the `post_get_quantum_result_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_get_quantum_result` interceptor runs + before the `post_get_quantum_result_with_metadata` interceptor. + """ + return response + + def post_get_quantum_result_with_metadata( + self, response: quantum.QuantumResult, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumResult, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for get_quantum_result + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_get_quantum_result_with_metadata` + interceptor in new development instead of the `post_get_quantum_result` interceptor. + When both interceptors are used, this `post_get_quantum_result_with_metadata` interceptor + runs after the `post_get_quantum_result` interceptor. The (possibly modified) response + returned by `post_get_quantum_result` will be passed to + `post_get_quantum_result_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_calibrations( + self, + request: engine.ListQuantumCalibrationsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumCalibrationsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_calibrations + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_calibrations( + self, response: engine.ListQuantumCalibrationsResponse + ) -> engine.ListQuantumCalibrationsResponse: + """Post-rpc interceptor for list_quantum_calibrations + + DEPRECATED. Please use the `post_list_quantum_calibrations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_calibrations` interceptor runs + before the `post_list_quantum_calibrations_with_metadata` interceptor. + """ + return response + + def post_list_quantum_calibrations_with_metadata( + self, + response: engine.ListQuantumCalibrationsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumCalibrationsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_calibrations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_calibrations_with_metadata` + interceptor in new development instead of the `post_list_quantum_calibrations` interceptor. + When both interceptors are used, this `post_list_quantum_calibrations_with_metadata` + interceptor runs after the `post_list_quantum_calibrations` interceptor. The (possibly + modified) response returned by `post_list_quantum_calibrations` will be passed to + `post_list_quantum_calibrations_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_job_events( + self, + request: engine.ListQuantumJobEventsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumJobEventsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_job_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_job_events( + self, response: engine.ListQuantumJobEventsResponse + ) -> engine.ListQuantumJobEventsResponse: + """Post-rpc interceptor for list_quantum_job_events + + DEPRECATED. Please use the `post_list_quantum_job_events_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_job_events` interceptor runs + before the `post_list_quantum_job_events_with_metadata` interceptor. + """ + return response + + def post_list_quantum_job_events_with_metadata( + self, + response: engine.ListQuantumJobEventsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumJobEventsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_job_events + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_job_events_with_metadata` + interceptor in new development instead of the `post_list_quantum_job_events` interceptor. + When both interceptors are used, this `post_list_quantum_job_events_with_metadata` + interceptor runs after the `post_list_quantum_job_events` interceptor. The (possibly + modified) response returned by `post_list_quantum_job_events` will be passed to + `post_list_quantum_job_events_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_jobs( + self, request: engine.ListQuantumJobsRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.ListQuantumJobsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_jobs( + self, response: engine.ListQuantumJobsResponse + ) -> engine.ListQuantumJobsResponse: + """Post-rpc interceptor for list_quantum_jobs + + DEPRECATED. Please use the `post_list_quantum_jobs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_jobs` interceptor runs + before the `post_list_quantum_jobs_with_metadata` interceptor. + """ + return response + + def post_list_quantum_jobs_with_metadata( + self, response: engine.ListQuantumJobsResponse, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.ListQuantumJobsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_jobs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_jobs_with_metadata` + interceptor in new development instead of the `post_list_quantum_jobs` interceptor. + When both interceptors are used, this `post_list_quantum_jobs_with_metadata` interceptor + runs after the `post_list_quantum_jobs` interceptor. The (possibly modified) response + returned by `post_list_quantum_jobs` will be passed to + `post_list_quantum_jobs_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_processors( + self, + request: engine.ListQuantumProcessorsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProcessorsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_processors + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_processors( + self, response: engine.ListQuantumProcessorsResponse + ) -> engine.ListQuantumProcessorsResponse: + """Post-rpc interceptor for list_quantum_processors + + DEPRECATED. Please use the `post_list_quantum_processors_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_processors` interceptor runs + before the `post_list_quantum_processors_with_metadata` interceptor. + """ + return response + + def post_list_quantum_processors_with_metadata( + self, + response: engine.ListQuantumProcessorsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProcessorsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_processors + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_processors_with_metadata` + interceptor in new development instead of the `post_list_quantum_processors` interceptor. + When both interceptors are used, this `post_list_quantum_processors_with_metadata` + interceptor runs after the `post_list_quantum_processors` interceptor. The (possibly + modified) response returned by `post_list_quantum_processors` will be passed to + `post_list_quantum_processors_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_programs( + self, + request: engine.ListQuantumProgramsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProgramsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_programs + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_programs( + self, response: engine.ListQuantumProgramsResponse + ) -> engine.ListQuantumProgramsResponse: + """Post-rpc interceptor for list_quantum_programs + + DEPRECATED. Please use the `post_list_quantum_programs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_programs` interceptor runs + before the `post_list_quantum_programs_with_metadata` interceptor. + """ + return response + + def post_list_quantum_programs_with_metadata( + self, + response: engine.ListQuantumProgramsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumProgramsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_programs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_programs_with_metadata` + interceptor in new development instead of the `post_list_quantum_programs` interceptor. + When both interceptors are used, this `post_list_quantum_programs_with_metadata` interceptor + runs after the `post_list_quantum_programs` interceptor. The (possibly modified) response + returned by `post_list_quantum_programs` will be passed to + `post_list_quantum_programs_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservation_budgets( + self, + request: engine.ListQuantumReservationBudgetsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationBudgetsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservation_budgets + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservation_budgets( + self, response: engine.ListQuantumReservationBudgetsResponse + ) -> engine.ListQuantumReservationBudgetsResponse: + """Post-rpc interceptor for list_quantum_reservation_budgets + + DEPRECATED. Please use the `post_list_quantum_reservation_budgets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservation_budgets` interceptor runs + before the `post_list_quantum_reservation_budgets_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservation_budgets_with_metadata( + self, + response: engine.ListQuantumReservationBudgetsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationBudgetsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservation_budgets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservation_budgets_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservation_budgets` + interceptor. When both interceptors are used, this + `post_list_quantum_reservation_budgets_with_metadata` interceptor runs after the + `post_list_quantum_reservation_budgets` interceptor. The (possibly modified) response + returned by `post_list_quantum_reservation_budgets` will be passed to + `post_list_quantum_reservation_budgets_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservation_grants( + self, + request: engine.ListQuantumReservationGrantsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationGrantsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservation_grants + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservation_grants( + self, response: engine.ListQuantumReservationGrantsResponse + ) -> engine.ListQuantumReservationGrantsResponse: + """Post-rpc interceptor for list_quantum_reservation_grants + + DEPRECATED. Please use the `post_list_quantum_reservation_grants_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservation_grants` interceptor runs + before the `post_list_quantum_reservation_grants_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservation_grants_with_metadata( + self, + response: engine.ListQuantumReservationGrantsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationGrantsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservation_grants + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservation_grants_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservation_grants` + interceptor. When both interceptors are used, this + `post_list_quantum_reservation_grants_with_metadata` interceptor runs after the + `post_list_quantum_reservation_grants` interceptor. The (possibly modified) response + returned by `post_list_quantum_reservation_grants` will be passed to + `post_list_quantum_reservation_grants_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_reservations( + self, + request: engine.ListQuantumReservationsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_reservations + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_reservations( + self, response: engine.ListQuantumReservationsResponse + ) -> engine.ListQuantumReservationsResponse: + """Post-rpc interceptor for list_quantum_reservations + + DEPRECATED. Please use the `post_list_quantum_reservations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_reservations` interceptor runs + before the `post_list_quantum_reservations_with_metadata` interceptor. + """ + return response + + def post_list_quantum_reservations_with_metadata( + self, + response: engine.ListQuantumReservationsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumReservationsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_reservations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_reservations_with_metadata` + interceptor in new development instead of the `post_list_quantum_reservations` interceptor. + When both interceptors are used, this `post_list_quantum_reservations_with_metadata` + interceptor runs after the `post_list_quantum_reservations` interceptor. The (possibly + modified) response returned by `post_list_quantum_reservations` will be passed to + `post_list_quantum_reservations_with_metadata`. + """ + return response, metadata + + def pre_list_quantum_time_slots( + self, + request: engine.ListQuantumTimeSlotsRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumTimeSlotsRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for list_quantum_time_slots + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_list_quantum_time_slots( + self, response: engine.ListQuantumTimeSlotsResponse + ) -> engine.ListQuantumTimeSlotsResponse: + """Post-rpc interceptor for list_quantum_time_slots + + DEPRECATED. Please use the `post_list_quantum_time_slots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_list_quantum_time_slots` interceptor runs + before the `post_list_quantum_time_slots_with_metadata` interceptor. + """ + return response + + def post_list_quantum_time_slots_with_metadata( + self, + response: engine.ListQuantumTimeSlotsResponse, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ListQuantumTimeSlotsResponse, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for list_quantum_time_slots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_list_quantum_time_slots_with_metadata` + interceptor in new development instead of the `post_list_quantum_time_slots` interceptor. + When both interceptors are used, this `post_list_quantum_time_slots_with_metadata` + interceptor runs after the `post_list_quantum_time_slots` interceptor. The (possibly + modified) response returned by `post_list_quantum_time_slots` will be passed to + `post_list_quantum_time_slots_with_metadata`. + """ + return response, metadata + + def pre_reallocate_quantum_reservation_grant( + self, + request: engine.ReallocateQuantumReservationGrantRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.ReallocateQuantumReservationGrantRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for reallocate_quantum_reservation_grant + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_reallocate_quantum_reservation_grant( + self, response: quantum.QuantumReservationGrant + ) -> quantum.QuantumReservationGrant: + """Post-rpc interceptor for reallocate_quantum_reservation_grant + + DEPRECATED. Please use the `post_reallocate_quantum_reservation_grant_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_reallocate_quantum_reservation_grant` interceptor + runs before the `post_reallocate_quantum_reservation_grant_with_metadata` interceptor. + """ + return response + + def post_reallocate_quantum_reservation_grant_with_metadata( + self, response: quantum.QuantumReservationGrant, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservationGrant, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for reallocate_quantum_reservation_grant + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_reallocate_quantum_reservation_grant_with_metadata` + interceptor in new development instead of the `post_reallocate_quantum_reservation_grant` + interceptor. When both interceptors are used, this + `post_reallocate_quantum_reservation_grant_with_metadata` interceptor runs after the + `post_reallocate_quantum_reservation_grant` interceptor. The (possibly modified) response + returned by `post_reallocate_quantum_reservation_grant` will be passed to + `post_reallocate_quantum_reservation_grant_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_job( + self, request: engine.UpdateQuantumJobRequest, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[engine.UpdateQuantumJobRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_job(self, response: quantum.QuantumJob) -> quantum.QuantumJob: + """Post-rpc interceptor for update_quantum_job + + DEPRECATED. Please use the `post_update_quantum_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_job` interceptor runs + before the `post_update_quantum_job_with_metadata` interceptor. + """ + return response + + def post_update_quantum_job_with_metadata( + self, response: quantum.QuantumJob, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumJob, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_job_with_metadata` + interceptor in new development instead of the `post_update_quantum_job` interceptor. + When both interceptors are used, this `post_update_quantum_job_with_metadata` interceptor + runs after the `post_update_quantum_job` interceptor. The (possibly modified) response + returned by `post_update_quantum_job` will be passed to + `post_update_quantum_job_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_program( + self, + request: engine.UpdateQuantumProgramRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.UpdateQuantumProgramRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_program( + self, response: quantum.QuantumProgram + ) -> quantum.QuantumProgram: + """Post-rpc interceptor for update_quantum_program + + DEPRECATED. Please use the `post_update_quantum_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_program` interceptor runs + before the `post_update_quantum_program_with_metadata` interceptor. + """ + return response + + def post_update_quantum_program_with_metadata( + self, response: quantum.QuantumProgram, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumProgram, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_program_with_metadata` + interceptor in new development instead of the `post_update_quantum_program` interceptor. + When both interceptors are used, this `post_update_quantum_program_with_metadata` + interceptor runs after the `post_update_quantum_program` interceptor. The (possibly + modified) response returned by `post_update_quantum_program` will be passed to + `post_update_quantum_program_with_metadata`. + """ + return response, metadata + + def pre_update_quantum_reservation( + self, + request: engine.UpdateQuantumReservationRequest, + metadata: Sequence[tuple[str, str | bytes]], + ) -> tuple[engine.UpdateQuantumReservationRequest, Sequence[tuple[str, str | bytes]]]: + """Pre-rpc interceptor for update_quantum_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuantumEngineService server. + """ + return request, metadata + + def post_update_quantum_reservation( + self, response: quantum.QuantumReservation + ) -> quantum.QuantumReservation: + """Post-rpc interceptor for update_quantum_reservation + + DEPRECATED. Please use the `post_update_quantum_reservation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the QuantumEngineService server but before + it is returned to user code. This `post_update_quantum_reservation` interceptor runs + before the `post_update_quantum_reservation_with_metadata` interceptor. + """ + return response + + def post_update_quantum_reservation_with_metadata( + self, response: quantum.QuantumReservation, metadata: Sequence[tuple[str, str | bytes]] + ) -> tuple[quantum.QuantumReservation, Sequence[tuple[str, str | bytes]]]: + """Post-rpc interceptor for update_quantum_reservation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the QuantumEngineService server but before it is returned to user code. + + We recommend only using this `post_update_quantum_reservation_with_metadata` + interceptor in new development instead of the `post_update_quantum_reservation` interceptor. + When both interceptors are used, this `post_update_quantum_reservation_with_metadata` + interceptor runs after the `post_update_quantum_reservation` interceptor. The (possibly + modified) response returned by `post_update_quantum_reservation` will be passed to + `post_update_quantum_reservation_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class QuantumEngineServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: QuantumEngineServiceRestInterceptor + + +class QuantumEngineServiceRestTransport(_BaseQuantumEngineServiceRestTransport): + """REST backend synchronous transport for QuantumEngineService. + + - + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = 'quantum.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[QuantumEngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'quantum.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession(self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or QuantumEngineServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CancelQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CancelQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CancelQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the cancel quantum job method over HTTP. + + Args: + request (~.engine.CancelQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CancelQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CancelQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _CancelQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CancelQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CancelQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the cancel quantum + reservation method over HTTP. + + Args: + request (~.engine.CancelQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCancelQuantumReservation._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CancelQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CancelQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.cancel_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CancelQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the create quantum job method over HTTP. + + Args: + request (~.engine.CreateQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the create quantum program method over HTTP. + + Args: + request (~.engine.CreateQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumProgram._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_program", + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.CreateQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.CreateQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the create quantum + reservation method over HTTP. + + Args: + request (~.engine.CreateQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_transcoded_request( # noqa E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_request_body_json( # noqa E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseCreateQuantumReservation._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.CreateQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._CreateQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.create_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "CreateQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum job method over HTTP. + + Args: + request (~.engine.DeleteQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_transcoded_request( # noqa E501 + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum program method over HTTP. + + Args: + request (~.engine.DeleteQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_transcoded_request( # noqa E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumProgram._get_query_params_json( # noqa E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.DeleteQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.DeleteQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ): + r"""Call the delete quantum + reservation method over HTTP. + + Args: + request (~.engine.DeleteQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseDeleteQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.DeleteQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "DeleteQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._DeleteQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetQuantumCalibration( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumCalibration") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumCalibrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumCalibration: + r"""Call the get quantum calibration method over HTTP. + + Args: + request (~.engine.GetQuantumCalibrationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumCalibration: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_calibration(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumCalibration._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumCalibration" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumCalibration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumCalibration._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumCalibration() + pb_resp = quantum.QuantumCalibration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_calibration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_calibration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumCalibration.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_calibration" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumCalibration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the get quantum job method over HTTP. + + Args: + request (~.engine.GetQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_job(request, metadata) + transcoded_request = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_job_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProcessor( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProcessor") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProcessorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessor: + r"""Call the get quantum processor method over HTTP. + + Args: + request (~.engine.GetQuantumProcessorRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProcessor: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_processor(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessor._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProcessor" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessor", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProcessor._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProcessor() + pb_resp = quantum.QuantumProcessor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_processor(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_processor_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProcessor.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_processor" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessor", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProcessorConfig( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProcessorConfig") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProcessorConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProcessorConfig: + r"""Call the get quantum processor + config method over HTTP. + + Args: + request (~.engine.GetQuantumProcessorConfigRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProcessorConfig: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_processor_config( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProcessorConfig" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessorConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProcessorConfig._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProcessorConfig() + pb_resp = quantum.QuantumProcessorConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_processor_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_processor_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProcessorConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_processor_config" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProcessorConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the get quantum program method over HTTP. + + Args: + request (~.engine.GetQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProgram._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_program" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the get quantum reservation method over HTTP. + + Args: + request (~.engine.GetQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetQuantumResult( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.GetQuantumResult") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.GetQuantumResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumResult: + r"""Call the get quantum result method over HTTP. + + Args: + request (~.engine.GetQuantumResultRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumResult: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_quantum_result(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumResult._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.GetQuantumResult" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumResult", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._GetQuantumResult._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumResult() + pb_resp = quantum.QuantumResult.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_quantum_result(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_quantum_result_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumResult.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.get_quantum_result" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "GetQuantumResult", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumCalibrations( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumCalibrations") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumCalibrationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumCalibrationsResponse: + r"""Call the list quantum calibrations method over HTTP. + + Args: + request (~.engine.ListQuantumCalibrationsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumCalibrationsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_calibrations(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumCalibrations._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumCalibrations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumCalibrations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumCalibrations._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumCalibrationsResponse() + pb_resp = engine.ListQuantumCalibrationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_calibrations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_calibrations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumCalibrationsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_calibrations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumCalibrations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumJobEvents( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumJobEvents") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumJobEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumJobEventsResponse: + r"""Call the list quantum job events method over HTTP. + + Args: + request (~.engine.ListQuantumJobEventsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumJobEventsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_job_events(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobEvents._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumJobEvents" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobEvents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumJobEvents._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumJobEventsResponse() + pb_resp = engine.ListQuantumJobEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_job_events(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_job_events_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumJobEventsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_job_events" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobEvents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumJobs( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumJobs") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumJobsResponse: + r"""Call the list quantum jobs method over HTTP. + + Args: + request (~.engine.ListQuantumJobsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumJobsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_jobs(request, metadata) + transcoded_request = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumJobs._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumJobs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumJobs._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumJobsResponse() + pb_resp = engine.ListQuantumJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_jobs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_jobs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumJobsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_jobs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumJobs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumProcessors( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumProcessors") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumProcessorsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumProcessorsResponse: + r"""Call the list quantum processors method over HTTP. + + Args: + request (~.engine.ListQuantumProcessorsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumProcessorsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_processors(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumProcessors._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumProcessors" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumProcessors", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumProcessors._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumProcessorsResponse() + pb_resp = engine.ListQuantumProcessorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_processors(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_processors_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumProcessorsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_processors" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumProcessors", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumPrograms( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumPrograms") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumProgramsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumProgramsResponse: + r"""Call the list quantum programs method over HTTP. + + Args: + request (~.engine.ListQuantumProgramsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumProgramsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_programs(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumPrograms._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumPrograms" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumPrograms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumPrograms._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumProgramsResponse() + pb_resp = engine.ListQuantumProgramsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_programs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_programs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumProgramsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_programs" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumPrograms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservationBudgets( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservationBudgets") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationBudgetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationBudgetsResponse: + r"""Call the list quantum reservation + budgets method over HTTP. + + Args: + request (~.engine.ListQuantumReservationBudgetsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationBudgetsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservation_budgets( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationBudgets._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservationBudgets" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationBudgets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ListQuantumReservationBudgets._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationBudgetsResponse() + pb_resp = engine.ListQuantumReservationBudgetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservation_budgets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservation_budgets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationBudgetsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservation_budgets" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationBudgets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservationGrants( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservationGrants") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationGrantsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationGrantsResponse: + r"""Call the list quantum reservation + grants method over HTTP. + + Args: + request (~.engine.ListQuantumReservationGrantsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationGrantsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservation_grants( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservationGrants._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservationGrants" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationGrants", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ListQuantumReservationGrants._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationGrantsResponse() + pb_resp = engine.ListQuantumReservationGrantsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservation_grants(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservation_grants_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationGrantsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservation_grants" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservationGrants", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumReservations( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumReservations") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumReservationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumReservationsResponse: + r"""Call the list quantum reservations method over HTTP. + + Args: + request (~.engine.ListQuantumReservationsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumReservationsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_reservations(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumReservations._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumReservations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumReservations._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumReservationsResponse() + pb_resp = engine.ListQuantumReservationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_reservations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_reservations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumReservationsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_reservations" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumReservations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListQuantumTimeSlots( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ListQuantumTimeSlots") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: engine.ListQuantumTimeSlotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> engine.ListQuantumTimeSlotsResponse: + r"""Call the list quantum time slots method over HTTP. + + Args: + request (~.engine.ListQuantumTimeSlotsRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.engine.ListQuantumTimeSlotsResponse: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_quantum_time_slots(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_transcoded_request( # noqa: E501 + http_options, request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseListQuantumTimeSlots._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ListQuantumTimeSlots" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumTimeSlots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._ListQuantumTimeSlots._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.ListQuantumTimeSlotsResponse() + pb_resp = engine.ListQuantumTimeSlotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_quantum_time_slots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_quantum_time_slots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = engine.ListQuantumTimeSlotsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.list_quantum_time_slots" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ListQuantumTimeSlots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _QuantumRunStream( + _BaseQuantumEngineServiceRestTransport._BaseQuantumRunStream, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.QuantumRunStream") + + def __call__( + self, + request: engine.QuantumRunStreamRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method QuantumRunStream is not available over REST transport" + ) + + class _ReallocateQuantumReservationGrant( + _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.ReallocateQuantumReservationGrant") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.ReallocateQuantumReservationGrantRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservationGrant: + r"""Call the reallocate quantum + reservation grant method over HTTP. + + Args: + request (~.engine.ReallocateQuantumReservationGrantRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservationGrant: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_http_options() + ) + + request, metadata = self._interceptor.pre_reallocate_quantum_reservation_grant( + request, metadata + ) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseReallocateQuantumReservationGrant._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.ReallocateQuantumReservationGrant" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ReallocateQuantumReservationGrant", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + QuantumEngineServiceRestTransport._ReallocateQuantumReservationGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservationGrant() + pb_resp = quantum.QuantumReservationGrant.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_reallocate_quantum_reservation_grant(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_reallocate_quantum_reservation_grant_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservationGrant.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.reallocate_quantum_reservation_grant" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "ReallocateQuantumReservationGrant", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumJob( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob, QuantumEngineServiceRestStub + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumJob") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumJob: + r"""Call the update quantum job method over HTTP. + + Args: + request (~.engine.UpdateQuantumJobRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumJob: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_job(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumJob._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumJob" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumJob._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumJob() + pb_resp = quantum.QuantumJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumJob.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_job" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumProgram( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumProgram") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumProgram: + r"""Call the update quantum program method over HTTP. + + Args: + request (~.engine.UpdateQuantumProgramRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type + `str`, but for metadata keys ending with the suffix `-bin`, the corresponding + values must be of type `bytes`. + + Returns: + ~.quantum.QuantumProgram: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_program(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumProgram._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumProgram" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumProgram._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumProgram() + pb_resp = quantum.QuantumProgram.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumProgram.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_program" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateQuantumReservation( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation, + QuantumEngineServiceRestStub, + ): + def __hash__(self): + return hash("QuantumEngineServiceRestTransport.UpdateQuantumReservation") + + @staticmethod + def _get_response( + host, metadata, query_params, session, timeout, transcoded_request, body=None + ): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: engine.UpdateQuantumReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[tuple[str, str | bytes]] = (), + ) -> quantum.QuantumReservation: + r"""Call the update quantum + reservation method over HTTP. + + Args: + request (~.engine.UpdateQuantumReservationRequest): + The request object. - + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should + be sent along with the request as metadata. Normally, each value must be of + type `str`, but for metadata keys ending with the suffix `-bin`, the + corresponding values must be of type `bytes`. + + Returns: + ~.quantum.QuantumReservation: + - + """ + + http_options = ( + _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_quantum_reservation(request, metadata) + transcoded_request = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_transcoded_request( # noqa: E501 + http_options, request + ) + + body = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_request_body_json( # noqa: E501 + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseQuantumEngineServiceRestTransport._BaseUpdateQuantumReservation._get_query_params_json( # noqa: E501 + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + ( + "Sending request for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.UpdateQuantumReservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumReservation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = QuantumEngineServiceRestTransport._UpdateQuantumReservation._get_response( + self._host, metadata, query_params, self._session, timeout, transcoded_request, body + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = quantum.QuantumReservation() + pb_resp = quantum.QuantumReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_quantum_reservation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_quantum_reservation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = quantum.QuantumReservation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + ( + "Received response for cirq_google.cloud.quantum_v1alpha1." + "QuantumEngineServiceClient.update_quantum_reservation" + ), + extra={ + "serviceName": "google.cloud.quantum.v1alpha1.QuantumEngineService", + "rpcName": "UpdateQuantumReservation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def cancel_quantum_job(self) -> Callable[[engine.CancelQuantumJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CancelQuantumJob(self._session, self._host, self._interceptor) + + @property + def cancel_quantum_reservation( + self, + ) -> Callable[[engine.CancelQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CancelQuantumReservation(self._session, self._host, self._interceptor) + + @property + def create_quantum_job(self) -> Callable[[engine.CreateQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumJob(self._session, self._host, self._interceptor) + + @property + def create_quantum_program( + self, + ) -> Callable[[engine.CreateQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumProgram(self._session, self._host, self._interceptor) + + @property + def create_quantum_reservation( + self, + ) -> Callable[[engine.CreateQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._CreateQuantumReservation(self._session, self._host, self._interceptor) + + @property + def delete_quantum_job(self) -> Callable[[engine.DeleteQuantumJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumJob(self._session, self._host, self._interceptor) + + @property + def delete_quantum_program( + self, + ) -> Callable[[engine.DeleteQuantumProgramRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumProgram(self._session, self._host, self._interceptor) + + @property + def delete_quantum_reservation( + self, + ) -> Callable[[engine.DeleteQuantumReservationRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._DeleteQuantumReservation(self._session, self._host, self._interceptor) + + @property + def get_quantum_calibration( + self, + ) -> Callable[[engine.GetQuantumCalibrationRequest], quantum.QuantumCalibration]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumCalibration(self._session, self._host, self._interceptor) + + @property + def get_quantum_job(self) -> Callable[[engine.GetQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumJob(self._session, self._host, self._interceptor) + + @property + def get_quantum_processor( + self, + ) -> Callable[[engine.GetQuantumProcessorRequest], quantum.QuantumProcessor]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProcessor(self._session, self._host, self._interceptor) + + @property + def get_quantum_processor_config( + self, + ) -> Callable[[engine.GetQuantumProcessorConfigRequest], quantum.QuantumProcessorConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProcessorConfig(self._session, self._host, self._interceptor) + + @property + def get_quantum_program( + self, + ) -> Callable[[engine.GetQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumProgram(self._session, self._host, self._interceptor) + + @property + def get_quantum_reservation( + self, + ) -> Callable[[engine.GetQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumReservation(self._session, self._host, self._interceptor) + + @property + def get_quantum_result( + self, + ) -> Callable[[engine.GetQuantumResultRequest], quantum.QuantumResult]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._GetQuantumResult(self._session, self._host, self._interceptor) + + @property + def list_quantum_calibrations( + self, + ) -> Callable[[engine.ListQuantumCalibrationsRequest], engine.ListQuantumCalibrationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumCalibrations(self._session, self._host, self._interceptor) + + @property + def list_quantum_job_events( + self, + ) -> Callable[[engine.ListQuantumJobEventsRequest], engine.ListQuantumJobEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumJobEvents(self._session, self._host, self._interceptor) + + @property + def list_quantum_jobs( + self, + ) -> Callable[[engine.ListQuantumJobsRequest], engine.ListQuantumJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumJobs(self._session, self._host, self._interceptor) + + @property + def list_quantum_processors( + self, + ) -> Callable[[engine.ListQuantumProcessorsRequest], engine.ListQuantumProcessorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumProcessors(self._session, self._host, self._interceptor) + + @property + def list_quantum_programs( + self, + ) -> Callable[[engine.ListQuantumProgramsRequest], engine.ListQuantumProgramsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumPrograms(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservation_budgets( + self, + ) -> Callable[ + [engine.ListQuantumReservationBudgetsRequest], engine.ListQuantumReservationBudgetsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservationBudgets(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservation_grants( + self, + ) -> Callable[ + [engine.ListQuantumReservationGrantsRequest], engine.ListQuantumReservationGrantsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservationGrants(self._session, self._host, self._interceptor) + + @property + def list_quantum_reservations( + self, + ) -> Callable[[engine.ListQuantumReservationsRequest], engine.ListQuantumReservationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumReservations(self._session, self._host, self._interceptor) + + @property + def list_quantum_time_slots( + self, + ) -> Callable[[engine.ListQuantumTimeSlotsRequest], engine.ListQuantumTimeSlotsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ListQuantumTimeSlots(self._session, self._host, self._interceptor) + + @property + def quantum_run_stream( + self, + ) -> Callable[[engine.QuantumRunStreamRequest], engine.QuantumRunStreamResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._QuantumRunStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def reallocate_quantum_reservation_grant( + self, + ) -> Callable[ + [engine.ReallocateQuantumReservationGrantRequest], quantum.QuantumReservationGrant + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._ReallocateQuantumReservationGrant(self._session, self._host, self._interceptor) + + @property + def update_quantum_job(self) -> Callable[[engine.UpdateQuantumJobRequest], quantum.QuantumJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumJob(self._session, self._host, self._interceptor) + + @property + def update_quantum_program( + self, + ) -> Callable[[engine.UpdateQuantumProgramRequest], quantum.QuantumProgram]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumProgram(self._session, self._host, self._interceptor) + + @property + def update_quantum_reservation( + self, + ) -> Callable[[engine.UpdateQuantumReservationRequest], quantum.QuantumReservation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on + # here. In C++ this would require a dynamic_cast + return self._UpdateQuantumReservation(self._session, self._host, self._interceptor) + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ('QuantumEngineServiceRestTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py new file mode 100755 index 00000000000..da956a90993 --- /dev/null +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/services/quantum_engine_service/transports/rest_base.py @@ -0,0 +1,1019 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import re +from typing import Any, Optional + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from cirq_google.cloud.quantum_v1alpha1.types import engine + +from .base import DEFAULT_CLIENT_INFO, QuantumEngineServiceTransport + + +class _BaseQuantumEngineServiceRestTransport(QuantumEngineServiceTransport): + """Base REST backend transport for QuantumEngineService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = 'quantum.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'quantum.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCancelQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}:cancel', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CancelQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}:cancel', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CancelQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/programs/*}/jobs', + 'body': 'quantum_job', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*}/programs', + 'body': 'quantum_program', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/processors/*}/reservations', + 'body': 'quantum_reservation', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.CreateQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'delete', 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'delete', 'uri': '/v1alpha1/{name=projects/*/programs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.DeleteQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumCalibration: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*/calibrations/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumCalibrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProcessor: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProcessorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProcessorConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/processors/*/configSnapshots/*/configs/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/processors/*/configAutomationRuns/*/configs/*}', # noqa E501 + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProcessorConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + query_params.update( + _BaseQuantumEngineServiceRestTransport._BaseGetQuantumProcessorConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/programs/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetQuantumResult: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*/jobs/*}/result'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.GetQuantumResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumCalibrations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/calibrations'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumCalibrationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumJobEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*/jobs/*}/events'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumJobEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumJobs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/programs/*}/jobs'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumProcessors: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/processors'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumProcessorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumPrograms: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/programs'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumProgramsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservationBudgets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/reservationBudgets'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationBudgetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservationGrants: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*}/reservationGrant'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationGrantsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumReservations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/reservations'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumReservationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListQuantumTimeSlots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + {'method': 'get', 'uri': '/v1alpha1/{parent=projects/*/processors/*}/timeSlots'} + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ListQuantumTimeSlotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseQuantumRunStream: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseReallocateQuantumReservationGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/reservationGrant/*}:reallocate', + 'body': '*', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.ReallocateQuantumReservationGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/programs/*/jobs/*}', + 'body': 'quantum_job', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumProgram: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/programs/*}', + 'body': 'quantum_program', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumProgramRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateQuantumReservation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: list[dict[str, str]] = [ + { + 'method': 'patch', + 'uri': '/v1alpha1/{name=projects/*/processors/*/reservations/*}', + 'body': 'quantum_reservation', + } + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = engine.UpdateQuantumReservationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request['query_params'], use_integers_for_enums=True + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ('_BaseQuantumEngineServiceRestTransport',) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py index d298e09478b..22bdca165e4 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ DeleteQuantumReservationRequest, GetQuantumCalibrationRequest, GetQuantumJobRequest, + GetQuantumProcessorConfigRequest, GetQuantumProcessorRequest, GetQuantumProgramRequest, GetQuantumReservationRequest, @@ -66,6 +67,7 @@ QuantumJob, QuantumJobEvent, QuantumProcessor, + QuantumProcessorConfig, QuantumProgram, QuantumReservation, QuantumReservationBudget, @@ -87,6 +89,7 @@ 'DeleteQuantumReservationRequest', 'GetQuantumCalibrationRequest', 'GetQuantumJobRequest', + 'GetQuantumProcessorConfigRequest', 'GetQuantumProcessorRequest', 'GetQuantumProgramRequest', 'GetQuantumReservationRequest', @@ -116,6 +119,7 @@ 'UpdateQuantumJobRequest', 'UpdateQuantumProgramRequest', 'UpdateQuantumReservationRequest', + 'DeviceConfigKey', 'DeviceConfigSelector', 'ExecutionStatus', 'GcsLocation', @@ -125,6 +129,7 @@ 'QuantumJob', 'QuantumJobEvent', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumProgram', 'QuantumReservation', 'QuantumReservationBudget', @@ -132,5 +137,4 @@ 'QuantumResult', 'QuantumTimeSlot', 'SchedulingConfig', - 'DeviceConfigKey', ) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py index 91a316e16cf..a289e296ffc 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/engine.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,11 +12,11 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -# ruff: noqa: E501 - +# from __future__ import annotations +from typing import MutableSequence + import proto from google.protobuf import duration_pb2, field_mask_pb2 @@ -44,6 +44,7 @@ 'ListQuantumProcessorsRequest', 'ListQuantumProcessorsResponse', 'GetQuantumProcessorRequest', + 'GetQuantumProcessorConfigRequest', 'ListQuantumCalibrationsRequest', 'ListQuantumCalibrationsResponse', 'GetQuantumCalibrationRequest', @@ -75,15 +76,17 @@ class CreateQuantumJobRequest(proto.Message): Attributes: parent (str): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - overwrite_existing_run_context (bool): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_job = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumJob) - overwrite_existing_run_context = proto.Field(proto.BOOL, number=3) + parent: str = proto.Field(proto.STRING, number=1) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumJob + ) + overwrite_existing_run_context: bool = proto.Field(proto.BOOL, number=3) class GetQuantumJobRequest(proto.Message): @@ -96,8 +99,8 @@ class GetQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - return_run_context = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + return_run_context: bool = proto.Field(proto.BOOL, number=2) class ListQuantumJobsRequest(proto.Message): @@ -114,17 +117,17 @@ class ListQuantumJobsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumJobsResponse(proto.Message): r"""- Attributes: - jobs (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJob]): + jobs (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumJob]): - next_page_token (str): - @@ -134,8 +137,10 @@ class ListQuantumJobsResponse(proto.Message): def raw_page(self): return self - jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumJob) - next_page_token = proto.Field(proto.STRING, number=2) + jobs: MutableSequence[quantum.QuantumJob] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumJob + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class DeleteQuantumJobRequest(proto.Message): @@ -146,7 +151,7 @@ class DeleteQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class UpdateQuantumJobRequest(proto.Message): @@ -155,15 +160,19 @@ class UpdateQuantumJobRequest(proto.Message): Attributes: name (str): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_job = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumJob) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumJob + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class CancelQuantumJobRequest(proto.Message): @@ -174,7 +183,7 @@ class CancelQuantumJobRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class ListQuantumJobEventsRequest(proto.Message): @@ -189,16 +198,16 @@ class ListQuantumJobEventsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) class ListQuantumJobEventsResponse(proto.Message): r"""- Attributes: - events (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJobEvent]): + events (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumJobEvent]): - next_page_token (str): - @@ -208,8 +217,10 @@ class ListQuantumJobEventsResponse(proto.Message): def raw_page(self): return self - events = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumJobEvent) - next_page_token = proto.Field(proto.STRING, number=2) + events: MutableSequence[quantum.QuantumJobEvent] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumJobEvent + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumResultRequest(proto.Message): @@ -220,7 +231,7 @@ class GetQuantumResultRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) + parent: str = proto.Field(proto.STRING, number=1) class CreateQuantumProgramRequest(proto.Message): @@ -229,15 +240,17 @@ class CreateQuantumProgramRequest(proto.Message): Attributes: parent (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - overwrite_existing_source_code (bool): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - overwrite_existing_source_code = proto.Field(proto.BOOL, number=3) + parent: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + overwrite_existing_source_code: bool = proto.Field(proto.BOOL, number=3) class GetQuantumProgramRequest(proto.Message): @@ -250,8 +263,8 @@ class GetQuantumProgramRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - return_code = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + return_code: bool = proto.Field(proto.BOOL, number=2) class ListQuantumProgramsRequest(proto.Message): @@ -268,17 +281,17 @@ class ListQuantumProgramsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumProgramsResponse(proto.Message): r"""- Attributes: - programs (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProgram]): + programs (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram]): - next_page_token (str): - @@ -288,8 +301,10 @@ class ListQuantumProgramsResponse(proto.Message): def raw_page(self): return self - programs = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumProgram) - next_page_token = proto.Field(proto.STRING, number=2) + programs: MutableSequence[quantum.QuantumProgram] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumProgram + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class DeleteQuantumProgramRequest(proto.Message): @@ -302,8 +317,8 @@ class DeleteQuantumProgramRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - delete_jobs = proto.Field(proto.BOOL, number=2) + name: str = proto.Field(proto.STRING, number=1) + delete_jobs: bool = proto.Field(proto.BOOL, number=2) class UpdateQuantumProgramRequest(proto.Message): @@ -312,15 +327,19 @@ class UpdateQuantumProgramRequest(proto.Message): Attributes: name (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class ListQuantumProcessorsRequest(proto.Message): @@ -337,17 +356,17 @@ class ListQuantumProcessorsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumProcessorsResponse(proto.Message): r"""- Attributes: - processors (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProcessor]): + processors (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor]): - next_page_token (str): - @@ -357,8 +376,10 @@ class ListQuantumProcessorsResponse(proto.Message): def raw_page(self): return self - processors = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumProcessor) - next_page_token = proto.Field(proto.STRING, number=2) + processors: MutableSequence[quantum.QuantumProcessor] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumProcessor + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumProcessorRequest(proto.Message): @@ -369,7 +390,18 @@ class GetQuantumProcessorRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) + + +class GetQuantumProcessorConfigRequest(proto.Message): + r"""- + + Attributes: + name (str): + Required. - + """ + + name: str = proto.Field(proto.STRING, number=1) class ListQuantumCalibrationsRequest(proto.Message): @@ -378,7 +410,7 @@ class ListQuantumCalibrationsRequest(proto.Message): Attributes: parent (str): - - view (google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest.QuantumCalibrationView): + view (cirq_google.cloud.quantum_v1alpha1.types.ListQuantumCalibrationsRequest.QuantumCalibrationView): - page_size (int): - @@ -386,27 +418,36 @@ class ListQuantumCalibrationsRequest(proto.Message): - filter (str): - - """ + """ # noqa E501 class QuantumCalibrationView(proto.Enum): - r"""-""" + r"""- + + Values: + QUANTUM_CALIBRATION_VIEW_UNSPECIFIED (0): + - + BASIC (1): + - + FULL (2): + - + """ QUANTUM_CALIBRATION_VIEW_UNSPECIFIED = 0 BASIC = 1 FULL = 2 - parent = proto.Field(proto.STRING, number=1) - view = proto.Field(proto.ENUM, number=5, enum=QuantumCalibrationView) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + view: QuantumCalibrationView = proto.Field(proto.ENUM, number=5, enum=QuantumCalibrationView) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumCalibrationsResponse(proto.Message): r"""- Attributes: - calibrations (Sequence[google.cloud.quantum_v1alpha1.types.QuantumCalibration]): + calibrations (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumCalibration]): - next_page_token (str): - @@ -416,8 +457,10 @@ class ListQuantumCalibrationsResponse(proto.Message): def raw_page(self): return self - calibrations = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumCalibration) - next_page_token = proto.Field(proto.STRING, number=2) + calibrations: MutableSequence[quantum.QuantumCalibration] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumCalibration + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class GetQuantumCalibrationRequest(proto.Message): @@ -428,7 +471,7 @@ class GetQuantumCalibrationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class CreateQuantumReservationRequest(proto.Message): @@ -437,12 +480,14 @@ class CreateQuantumReservationRequest(proto.Message): Attributes: parent (str): - - quantum_reservation (google.cloud.quantum_v1alpha1.types.QuantumReservation): + quantum_reservation (cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_reservation = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumReservation) + parent: str = proto.Field(proto.STRING, number=1) + quantum_reservation: quantum.QuantumReservation = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumReservation + ) class CancelQuantumReservationRequest(proto.Message): @@ -453,7 +498,7 @@ class CancelQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class DeleteQuantumReservationRequest(proto.Message): @@ -464,7 +509,7 @@ class DeleteQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class GetQuantumReservationRequest(proto.Message): @@ -475,7 +520,7 @@ class GetQuantumReservationRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) + name: str = proto.Field(proto.STRING, number=1) class ListQuantumReservationsRequest(proto.Message): @@ -492,17 +537,17 @@ class ListQuantumReservationsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationsResponse(proto.Message): r"""- Attributes: - reservations (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservation]): + reservations (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation]): - next_page_token (str): - @@ -512,8 +557,10 @@ class ListQuantumReservationsResponse(proto.Message): def raw_page(self): return self - reservations = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumReservation) - next_page_token = proto.Field(proto.STRING, number=2) + reservations: MutableSequence[quantum.QuantumReservation] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumReservation + ) + next_page_token: str = proto.Field(proto.STRING, number=2) class UpdateQuantumReservationRequest(proto.Message): @@ -522,15 +569,19 @@ class UpdateQuantumReservationRequest(proto.Message): Attributes: name (str): - - quantum_reservation (google.cloud.quantum_v1alpha1.types.QuantumReservation): + quantum_reservation (cirq_google.cloud.quantum_v1alpha1.types.QuantumReservation): - update_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - name = proto.Field(proto.STRING, number=1) - quantum_reservation = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumReservation) - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + name: str = proto.Field(proto.STRING, number=1) + quantum_reservation: quantum.QuantumReservation = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumReservation + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class QuantumRunStreamRequest(proto.Message): @@ -548,29 +599,29 @@ class QuantumRunStreamRequest(proto.Message): - parent (str): - - create_quantum_program_and_job (google.cloud.quantum_v1alpha1.types.CreateQuantumProgramAndJobRequest): + create_quantum_program_and_job (cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumProgramAndJobRequest): - This field is a member of `oneof`_ ``request``. - create_quantum_job (google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest): + create_quantum_job (cirq_google.cloud.quantum_v1alpha1.types.CreateQuantumJobRequest): - This field is a member of `oneof`_ ``request``. - get_quantum_result (google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest): + get_quantum_result (cirq_google.cloud.quantum_v1alpha1.types.GetQuantumResultRequest): - This field is a member of `oneof`_ ``request``. - """ + """ # noqa E501 - message_id = proto.Field(proto.STRING, number=1) - parent = proto.Field(proto.STRING, number=2) - create_quantum_program_and_job = proto.Field( + message_id: str = proto.Field(proto.STRING, number=1) + parent: str = proto.Field(proto.STRING, number=2) + create_quantum_program_and_job: CreateQuantumProgramAndJobRequest = proto.Field( proto.MESSAGE, number=3, oneof='request', message='CreateQuantumProgramAndJobRequest' ) - create_quantum_job = proto.Field( + create_quantum_job: CreateQuantumJobRequest = proto.Field( proto.MESSAGE, number=4, oneof='request', message='CreateQuantumJobRequest' ) - get_quantum_result = proto.Field( + get_quantum_result: GetQuantumResultRequest = proto.Field( proto.MESSAGE, number=5, oneof='request', message='GetQuantumResultRequest' ) @@ -581,15 +632,19 @@ class CreateQuantumProgramAndJobRequest(proto.Message): Attributes: parent (str): - - quantum_program (google.cloud.quantum_v1alpha1.types.QuantumProgram): + quantum_program (cirq_google.cloud.quantum_v1alpha1.types.QuantumProgram): - - quantum_job (google.cloud.quantum_v1alpha1.types.QuantumJob): + quantum_job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - """ - parent = proto.Field(proto.STRING, number=1) - quantum_program = proto.Field(proto.MESSAGE, number=2, message=quantum.QuantumProgram) - quantum_job = proto.Field(proto.MESSAGE, number=3, message=quantum.QuantumJob) + parent: str = proto.Field(proto.STRING, number=1) + quantum_program: quantum.QuantumProgram = proto.Field( + proto.MESSAGE, number=2, message=quantum.QuantumProgram + ) + quantum_job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=3, message=quantum.QuantumJob + ) class QuantumRunStreamResponse(proto.Message): @@ -605,38 +660,67 @@ class QuantumRunStreamResponse(proto.Message): Attributes: message_id (str): - - error (google.cloud.quantum_v1alpha1.types.StreamError): + error (cirq_google.cloud.quantum_v1alpha1.types.StreamError): - This field is a member of `oneof`_ ``response``. - job (google.cloud.quantum_v1alpha1.types.QuantumJob): + job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - This field is a member of `oneof`_ ``response``. - result (google.cloud.quantum_v1alpha1.types.QuantumResult): + result (cirq_google.cloud.quantum_v1alpha1.types.QuantumResult): - This field is a member of `oneof`_ ``response``. """ - message_id = proto.Field(proto.STRING, number=1) - error = proto.Field(proto.MESSAGE, number=2, oneof='response', message='StreamError') - job = proto.Field(proto.MESSAGE, number=3, oneof='response', message=quantum.QuantumJob) - result = proto.Field(proto.MESSAGE, number=4, oneof='response', message=quantum.QuantumResult) + message_id: str = proto.Field(proto.STRING, number=1) + error: StreamError = proto.Field( + proto.MESSAGE, number=2, oneof='response', message='StreamError' + ) + job: quantum.QuantumJob = proto.Field( + proto.MESSAGE, number=3, oneof='response', message=quantum.QuantumJob + ) + result: quantum.QuantumResult = proto.Field( + proto.MESSAGE, number=4, oneof='response', message=quantum.QuantumResult + ) class StreamError(proto.Message): r"""- Attributes: - code (google.cloud.quantum_v1alpha1.types.StreamError.Code): + code (cirq_google.cloud.quantum_v1alpha1.types.StreamError.Code): - message (str): - """ class Code(proto.Enum): - r"""-""" + r"""- + + Values: + CODE_UNSPECIFIED (0): + - + INTERNAL (1): + - + INVALID_ARGUMENT (2): + - + PERMISSION_DENIED (3): + - + PROGRAM_ALREADY_EXISTS (4): + - + JOB_ALREADY_EXISTS (5): + - + PROGRAM_DOES_NOT_EXIST (6): + - + JOB_DOES_NOT_EXIST (7): + - + PROCESSOR_DOES_NOT_EXIST (8): + - + INVALID_PROCESSOR_FOR_JOB (9): + - + """ CODE_UNSPECIFIED = 0 INTERNAL = 1 @@ -649,8 +733,8 @@ class Code(proto.Enum): PROCESSOR_DOES_NOT_EXIST = 8 INVALID_PROCESSOR_FOR_JOB = 9 - code = proto.Field(proto.ENUM, number=1, enum=Code) - message = proto.Field(proto.STRING, number=2) + code: Code = proto.Field(proto.ENUM, number=1, enum=Code) + message: str = proto.Field(proto.STRING, number=2) class ListQuantumReservationGrantsRequest(proto.Message): @@ -667,30 +751,30 @@ class ListQuantumReservationGrantsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationGrantsResponse(proto.Message): r"""- Attributes: - reservation_grants (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationGrant]): + reservation_grants (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant]): - next_page_token (str): - - """ + """ # noqa E501 @property def raw_page(self): return self - reservation_grants = proto.RepeatedField( + reservation_grants: MutableSequence[quantum.QuantumReservationGrant] = proto.RepeatedField( proto.MESSAGE, number=1, message=quantum.QuantumReservationGrant ) - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token: str = proto.Field(proto.STRING, number=2) class ReallocateQuantumReservationGrantRequest(proto.Message): @@ -707,10 +791,12 @@ class ReallocateQuantumReservationGrantRequest(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - source_project_id = proto.Field(proto.STRING, number=2) - target_project_id = proto.Field(proto.STRING, number=3) - duration = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration) + name: str = proto.Field(proto.STRING, number=1) + source_project_id: str = proto.Field(proto.STRING, number=2) + target_project_id: str = proto.Field(proto.STRING, number=3) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration + ) class ListQuantumReservationBudgetsRequest(proto.Message): @@ -727,30 +813,30 @@ class ListQuantumReservationBudgetsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumReservationBudgetsResponse(proto.Message): r"""- Attributes: - reservation_budgets (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationBudget]): + reservation_budgets (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationBudget]): - next_page_token (str): - - """ + """ # noqa E501 @property def raw_page(self): return self - reservation_budgets = proto.RepeatedField( + reservation_budgets: MutableSequence[quantum.QuantumReservationBudget] = proto.RepeatedField( proto.MESSAGE, number=1, message=quantum.QuantumReservationBudget ) - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token: str = proto.Field(proto.STRING, number=2) class ListQuantumTimeSlotsRequest(proto.Message): @@ -767,17 +853,17 @@ class ListQuantumTimeSlotsRequest(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - page_size = proto.Field(proto.INT32, number=2) - page_token = proto.Field(proto.STRING, number=3) - filter = proto.Field(proto.STRING, number=4) + parent: str = proto.Field(proto.STRING, number=1) + page_size: int = proto.Field(proto.INT32, number=2) + page_token: str = proto.Field(proto.STRING, number=3) + filter: str = proto.Field(proto.STRING, number=4) class ListQuantumTimeSlotsResponse(proto.Message): r"""- Attributes: - time_slots (Sequence[google.cloud.quantum_v1alpha1.types.QuantumTimeSlot]): + time_slots (MutableSequence[cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot]): - next_page_token (str): - @@ -787,8 +873,10 @@ class ListQuantumTimeSlotsResponse(proto.Message): def raw_page(self): return self - time_slots = proto.RepeatedField(proto.MESSAGE, number=1, message=quantum.QuantumTimeSlot) - next_page_token = proto.Field(proto.STRING, number=2) + time_slots: MutableSequence[quantum.QuantumTimeSlot] = proto.RepeatedField( + proto.MESSAGE, number=1, message=quantum.QuantumTimeSlot + ) + next_page_token: str = proto.Field(proto.STRING, number=2) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py index 5749ead9fc4..3f2da574c50 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/types/quantum.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2022 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from __future__ import annotations import proto @@ -26,19 +25,20 @@ 'QuantumJob', 'SchedulingConfig', 'ExecutionStatus', + 'DeviceConfigSelector', + 'DeviceConfigKey', 'OutputConfig', 'GcsLocation', 'InlineData', 'QuantumJobEvent', 'QuantumResult', 'QuantumProcessor', + 'QuantumProcessorConfig', 'QuantumCalibration', 'QuantumReservationGrant', 'QuantumReservationBudget', 'QuantumTimeSlot', 'QuantumReservation', - 'DeviceConfigSelector', - 'DeviceConfigKey', }, ) @@ -60,17 +60,17 @@ class QuantumProgram(proto.Message): - update_time (google.protobuf.timestamp_pb2.Timestamp): - - labels (Sequence[google.cloud.quantum_v1alpha1.types.QuantumProgram.LabelsEntry]): + labels (dict[str, str]): - label_fingerprint (str): - description (str): - - gcs_code_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_code_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``code_location``. - code_inline_data (google.cloud.quantum_v1alpha1.types.InlineData): + code_inline_data (cirq_google.cloud.quantum_v1alpha1.types.InlineData): - This field is a member of `oneof`_ ``code_location``. @@ -78,19 +78,23 @@ class QuantumProgram(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - labels = proto.MapField(proto.STRING, proto.STRING, number=4) - label_fingerprint = proto.Field(proto.STRING, number=5) - description = proto.Field(proto.STRING, number=6) - gcs_code_location = proto.Field( + name: str = proto.Field(proto.STRING, number=1) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + labels: dict[str, str] = proto.MapField(proto.STRING, proto.STRING, number=4) + label_fingerprint: str = proto.Field(proto.STRING, number=5) + description: str = proto.Field(proto.STRING, number=6) + gcs_code_location: GcsLocation = proto.Field( proto.MESSAGE, number=7, oneof='code_location', message='GcsLocation' ) - code_inline_data = proto.Field( + code_inline_data: InlineData = proto.Field( proto.MESSAGE, number=9, oneof='code_location', message='InlineData' ) - code = proto.Field(proto.MESSAGE, number=8, message=any_pb2.Any) + code: any_pb2.Any = proto.Field(proto.MESSAGE, number=8, message=any_pb2.Any) class QuantumJob(proto.Message): @@ -110,23 +114,23 @@ class QuantumJob(proto.Message): - update_time (google.protobuf.timestamp_pb2.Timestamp): - - labels (Sequence[google.cloud.quantum_v1alpha1.types.QuantumJob.LabelsEntry]): + labels (dict[str, str]): - label_fingerprint (str): - description (str): - - scheduling_config (google.cloud.quantum_v1alpha1.types.SchedulingConfig): + scheduling_config (cirq_google.cloud.quantum_v1alpha1.types.SchedulingConfig): - - output_config (google.cloud.quantum_v1alpha1.types.OutputConfig): + output_config (cirq_google.cloud.quantum_v1alpha1.types.OutputConfig): - - execution_status (google.cloud.quantum_v1alpha1.types.ExecutionStatus): + execution_status (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus): - - gcs_run_context_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_run_context_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``run_context_location``. - run_context_inline_data (google.cloud.quantum_v1alpha1.types.InlineData): + run_context_inline_data (cirq_google.cloud.quantum_v1alpha1.types.InlineData): - This field is a member of `oneof`_ ``run_context_location``. @@ -134,68 +138,30 @@ class QuantumJob(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - labels = proto.MapField(proto.STRING, proto.STRING, number=4) - label_fingerprint = proto.Field(proto.STRING, number=5) - description = proto.Field(proto.STRING, number=6) - scheduling_config = proto.Field(proto.MESSAGE, number=7, message='SchedulingConfig') - output_config = proto.Field(proto.MESSAGE, number=8, message='OutputConfig') - execution_status = proto.Field(proto.MESSAGE, number=9, message='ExecutionStatus') - gcs_run_context_location = proto.Field( + name: str = proto.Field(proto.STRING, number=1) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + labels: dict[str, str] = proto.MapField(proto.STRING, proto.STRING, number=4) + label_fingerprint: str = proto.Field(proto.STRING, number=5) + description: str = proto.Field(proto.STRING, number=6) + scheduling_config: SchedulingConfig = proto.Field( + proto.MESSAGE, number=7, message='SchedulingConfig' + ) + output_config: OutputConfig = proto.Field(proto.MESSAGE, number=8, message='OutputConfig') + execution_status: ExecutionStatus = proto.Field( + proto.MESSAGE, number=9, message='ExecutionStatus' + ) + gcs_run_context_location: GcsLocation = proto.Field( proto.MESSAGE, number=10, oneof='run_context_location', message='GcsLocation' ) - run_context_inline_data = proto.Field( + run_context_inline_data: InlineData = proto.Field( proto.MESSAGE, number=12, oneof='run_context_location', message='InlineData' ) - run_context = proto.Field(proto.MESSAGE, number=11, message=any_pb2.Any) - - -class DeviceConfigSelector(proto.Message): - r"""- - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: - run_name (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - snapshot_id (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - config_alias (str): - - - """ - - run_name: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') - snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') - config_alias: str = proto.Field(proto.STRING, number=2) - - -class DeviceConfigKey(proto.Message): - r"""- - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: - run (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - snapshot_id (str): - - - This field is a member of `oneof`_ ``top_level_identifier``. - config_alias (str): - - - """ - - run: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') - snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') - config_alias: str = proto.Field(proto.STRING, number=2) + run_context: any_pb2.Any = proto.Field(proto.MESSAGE, number=11, message=any_pb2.Any) class SchedulingConfig(proto.Message): @@ -204,51 +170,76 @@ class SchedulingConfig(proto.Message): Attributes: target_route (str): - - processor_selector (google.cloud.quantum_v1alpha1.types.SchedulingConfig.ProcessorSelector): + processor_selector (cirq_google.cloud.quantum_v1alpha1.types.SchedulingConfig.ProcessorSelector): - priority (int): - - """ + """ # noqa E501 class ProcessorSelector(proto.Message): r"""- + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: - processor_names (Sequence[str]): + processor_names (list[str]): - processor (str): - - device_config_selector ((google.cloud.quantum_v1alpha1.types.DeviceConfigSelector): + device_config_selector (cirq_google.cloud.quantum_v1alpha1.types.DeviceConfigSelector): - + + This field is a member of `oneof`_ ``_device_config_selector``. """ - processor_names = proto.RepeatedField(proto.STRING, number=1) - processor = proto.Field(proto.STRING, number=2) - device_config_selector = proto.Field(proto.MESSAGE, number=3, message=DeviceConfigSelector) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=1) + processor: str = proto.Field(proto.STRING, number=2) + device_config_selector: DeviceConfigSelector = proto.Field( + proto.MESSAGE, number=3, optional=True, message='DeviceConfigSelector' + ) - target_route = proto.Field(proto.STRING, number=1) - processor_selector = proto.Field(proto.MESSAGE, number=3, message=ProcessorSelector) - priority = proto.Field(proto.INT32, number=2) + target_route: str = proto.Field(proto.STRING, number=1) + processor_selector: ProcessorSelector = proto.Field( + proto.MESSAGE, number=3, message=ProcessorSelector + ) + priority: int = proto.Field(proto.INT32, number=2) class ExecutionStatus(proto.Message): r"""- Attributes: - state (google.cloud.quantum_v1alpha1.types.ExecutionStatus.State): + state (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.State): - processor_name (str): - calibration_name (str): - - failure (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure): + failure (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure): - - timing (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Timing): + timing (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Timing): - """ class State(proto.Enum): - r"""-""" + r"""- + + Values: + STATE_UNSPECIFIED (0): + - + READY (1): + - + RUNNING (2): + - + CANCELLING (3): + - + CANCELLED (4): + - + SUCCESS (5): + - + FAILURE (6): + - + """ STATE_UNSPECIFIED = 0 READY = 1 @@ -262,14 +253,45 @@ class Failure(proto.Message): r"""- Attributes: - error_code (google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure.Code): + error_code (cirq_google.cloud.quantum_v1alpha1.types.ExecutionStatus.Failure.Code): - error_message (str): - """ class Code(proto.Enum): - r"""-""" + r"""- + + Values: + CODE_UNSPECIFIED (0): + - + SYSTEM_ERROR (1): + - + INVALID_PROGRAM (2): + - + INVALID_RUN_CONTEXT (3): + - + READ_PROGRAM_NOT_FOUND_IN_GCS (4): + - + READ_PROGRAM_PERMISSION_DENIED (5): + - + READ_PROGRAM_UNKNOWN_ERROR (6): + - + READ_RUN_CONTEXT_NOT_FOUND_IN_GCS (7): + - + READ_RUN_CONTEXT_PERMISSION_DENIED (8): + - + READ_RUN_CONTEXT_UNKNOWN_ERROR (9): + - + WRITE_RESULT_ALREADY_EXISTS_IN_GCS (10): + - + WRITE_RESULT_GCS_PERMISSION_DENIED (11): + - + SCHEDULING_EXPIRED (14): + - + FAILED_PRECONDITION (15): + - + """ CODE_UNSPECIFIED = 0 SYSTEM_ERROR = 1 @@ -286,8 +308,10 @@ class Code(proto.Enum): SCHEDULING_EXPIRED = 14 FAILED_PRECONDITION = 15 - error_code = proto.Field(proto.ENUM, number=1, enum='ExecutionStatus.Failure.Code') - error_message = proto.Field(proto.STRING, number=2) + error_code: ExecutionStatus.Failure.Code = proto.Field( + proto.ENUM, number=1, enum='ExecutionStatus.Failure.Code' + ) + error_message: str = proto.Field(proto.STRING, number=2) class Timing(proto.Message): r"""- @@ -299,14 +323,74 @@ class Timing(proto.Message): - """ - started_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp) - completed_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) + started_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp + ) + completed_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + + state: State = proto.Field(proto.ENUM, number=1, enum=State) + processor_name: str = proto.Field(proto.STRING, number=3) + calibration_name: str = proto.Field(proto.STRING, number=4) + failure: Failure = proto.Field(proto.MESSAGE, number=5, message=Failure) + timing: Timing = proto.Field(proto.MESSAGE, number=6, message=Timing) + + +class DeviceConfigSelector(proto.Message): + r"""- + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + run_name (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + snapshot_id (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + config_alias (str): + - + """ - state = proto.Field(proto.ENUM, number=1, enum=State) - processor_name = proto.Field(proto.STRING, number=3) - calibration_name = proto.Field(proto.STRING, number=4) - failure = proto.Field(proto.MESSAGE, number=5, message=Failure) - timing = proto.Field(proto.MESSAGE, number=6, message=Timing) + run_name: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') + snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') + config_alias: str = proto.Field(proto.STRING, number=2) + + +class DeviceConfigKey(proto.Message): + r"""- + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + run (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + snapshot_id (str): + - + + This field is a member of `oneof`_ ``top_level_identifier``. + config_alias (str): + - + """ + + run: str = proto.Field(proto.STRING, number=1, oneof='top_level_identifier') + snapshot_id: str = proto.Field(proto.STRING, number=3, oneof='top_level_identifier') + config_alias: str = proto.Field(proto.STRING, number=2) class OutputConfig(proto.Message): @@ -315,7 +399,7 @@ class OutputConfig(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - gcs_results_location (google.cloud.quantum_v1alpha1.types.GcsLocation): + gcs_results_location (cirq_google.cloud.quantum_v1alpha1.types.GcsLocation): - This field is a member of `oneof`_ ``output_destination``. @@ -323,10 +407,10 @@ class OutputConfig(proto.Message): - """ - gcs_results_location = proto.Field( + gcs_results_location: GcsLocation = proto.Field( proto.MESSAGE, number=1, oneof='output_destination', message='GcsLocation' ) - overwrite_existing = proto.Field(proto.BOOL, number=2) + overwrite_existing: bool = proto.Field(proto.BOOL, number=2) class GcsLocation(proto.Message): @@ -339,8 +423,8 @@ class GcsLocation(proto.Message): - """ - uri = proto.Field(proto.STRING, number=1) - type_url = proto.Field(proto.STRING, number=2) + uri: str = proto.Field(proto.STRING, number=1) + type_url: str = proto.Field(proto.STRING, number=2) class InlineData(proto.Message): @@ -351,7 +435,7 @@ class InlineData(proto.Message): - """ - type_url = proto.Field(proto.STRING, number=1) + type_url: str = proto.Field(proto.STRING, number=1) class QuantumJobEvent(proto.Message): @@ -360,15 +444,19 @@ class QuantumJobEvent(proto.Message): Attributes: event_time (google.protobuf.timestamp_pb2.Timestamp): - - job (google.cloud.quantum_v1alpha1.types.QuantumJob): + job (cirq_google.cloud.quantum_v1alpha1.types.QuantumJob): - modified_field_mask (google.protobuf.field_mask_pb2.FieldMask): - """ - event_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp) - job = proto.Field(proto.MESSAGE, number=2, message='QuantumJob') - modified_field_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp + ) + job: QuantumJob = proto.Field(proto.MESSAGE, number=2, message='QuantumJob') + modified_field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask + ) class QuantumResult(proto.Message): @@ -381,8 +469,8 @@ class QuantumResult(proto.Message): - """ - parent = proto.Field(proto.STRING, number=1) - result = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) + parent: str = proto.Field(proto.STRING, number=1) + result: any_pb2.Any = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) class QuantumProcessor(proto.Message): @@ -391,13 +479,13 @@ class QuantumProcessor(proto.Message): Attributes: name (str): - - health (google.cloud.quantum_v1alpha1.types.QuantumProcessor.Health): + health (cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor.Health): - expected_down_time (google.protobuf.timestamp_pb2.Timestamp): - expected_recovery_time (google.protobuf.timestamp_pb2.Timestamp): - - supported_languages (Sequence[str]): + supported_languages (list[str]): - device_spec (google.protobuf.any_pb2.Any): - @@ -407,17 +495,29 @@ class QuantumProcessor(proto.Message): - current_calibration (str): Output only. - - active_time_slot (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot): + active_time_slot (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot): Output only. - - activity_stats (google.cloud.quantum_v1alpha1.types.QuantumProcessor.ActivityStats): + activity_stats (cirq_google.cloud.quantum_v1alpha1.types.QuantumProcessor.ActivityStats): - - default_device_config_key (google.cloud.quantum_v1alpha1.types.DeviceConfigKey): + default_device_config_key (cirq_google.cloud.quantum_v1alpha1.types.DeviceConfigKey): - - """ class Health(proto.Enum): - r"""-""" + r"""- + + Values: + HEALTH_UNSPECIFIED (0): + - + OK (1): + - + DOWN (2): + - + INACTIVE (4): + - + UNAVAILABLE (3): + - + """ HEALTH_UNSPECIFIED = 0 OK = 1 @@ -435,21 +535,50 @@ class ActivityStats(proto.Message): - """ - active_users_count = proto.Field(proto.INT64, number=1) - active_jobs_count = proto.Field(proto.INT64, number=2) + active_users_count: int = proto.Field(proto.INT64, number=1) + active_jobs_count: int = proto.Field(proto.INT64, number=2) + + name: str = proto.Field(proto.STRING, number=1) + health: Health = proto.Field(proto.ENUM, number=3, enum=Health) + expected_down_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp + ) + expected_recovery_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + supported_languages: list[str] = proto.RepeatedField(proto.STRING, number=5) + device_spec: any_pb2.Any = proto.Field(proto.MESSAGE, number=6, message=any_pb2.Any) + schedule_horizon: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration + ) + schedule_frozen_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=9, message=duration_pb2.Duration + ) + current_calibration: str = proto.Field(proto.STRING, number=10) + active_time_slot: QuantumTimeSlot = proto.Field( + proto.MESSAGE, number=11, message='QuantumTimeSlot' + ) + activity_stats: ActivityStats = proto.Field(proto.MESSAGE, number=12, message=ActivityStats) + default_device_config_key: DeviceConfigKey = proto.Field( + proto.MESSAGE, number=13, message='DeviceConfigKey' + ) + - name = proto.Field(proto.STRING, number=1) - health = proto.Field(proto.ENUM, number=3, enum=Health) - expected_down_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp) - expected_recovery_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - supported_languages = proto.RepeatedField(proto.STRING, number=5) - device_spec = proto.Field(proto.MESSAGE, number=6, message=any_pb2.Any) - schedule_horizon = proto.Field(proto.MESSAGE, number=8, message=duration_pb2.Duration) - schedule_frozen_period = proto.Field(proto.MESSAGE, number=9, message=duration_pb2.Duration) - current_calibration = proto.Field(proto.STRING, number=10) - active_time_slot = proto.Field(proto.MESSAGE, number=11, message='QuantumTimeSlot') - activity_stats = proto.Field(proto.MESSAGE, number=12, message=ActivityStats) - default_device_config_key = proto.Field(proto.MESSAGE, number=13, message='DeviceConfigKey') +class QuantumProcessorConfig(proto.Message): + r"""- + + Attributes: + name (str): + Identifier. - + device_specification (google.protobuf.any_pb2.Any): + - + characterization (google.protobuf.any_pb2.Any): + - + """ + + name: str = proto.Field(proto.STRING, number=1) + device_specification: any_pb2.Any = proto.Field(proto.MESSAGE, number=2, message=any_pb2.Any) + characterization: any_pb2.Any = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) class QuantumCalibration(proto.Message): @@ -464,9 +593,11 @@ class QuantumCalibration(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - timestamp = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - data = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) + name: str = proto.Field(proto.STRING, number=1) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + data: any_pb2.Any = proto.Field(proto.MESSAGE, number=3, message=any_pb2.Any) class QuantumReservationGrant(proto.Message): @@ -475,7 +606,7 @@ class QuantumReservationGrant(proto.Message): Attributes: name (str): - - processor_names (Sequence[str]): + processor_names (list[str]): - effective_time (google.protobuf.timestamp_pb2.Timestamp): - @@ -485,7 +616,7 @@ class QuantumReservationGrant(proto.Message): - available_duration (google.protobuf.duration_pb2.Duration): - - budgets (Sequence[google.cloud.quantum_v1alpha1.types.QuantumReservationGrant.Budget]): + budgets (list[cirq_google.cloud.quantum_v1alpha1.types.QuantumReservationGrant.Budget]): - """ @@ -501,17 +632,29 @@ class Budget(proto.Message): - """ - project_id = proto.Field(proto.STRING, number=1) - granted_duration = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=3, message=duration_pb2.Duration) - - name = proto.Field(proto.STRING, number=1) - processor_names = proto.RepeatedField(proto.STRING, number=2) - effective_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - expire_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - granted_duration = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration) - budgets = proto.RepeatedField(proto.MESSAGE, number=7, message=Budget) + project_id: str = proto.Field(proto.STRING, number=1) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=2, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=3, message=duration_pb2.Duration + ) + + name: str = proto.Field(proto.STRING, number=1) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=2) + effective_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration + ) + budgets: list[Budget] = proto.RepeatedField(proto.MESSAGE, number=7, message=Budget) class QuantumReservationBudget(proto.Message): @@ -520,7 +663,7 @@ class QuantumReservationBudget(proto.Message): Attributes: name (str): - - processor_names (Sequence[str]): + processor_names (list[str]): - effective_time (google.protobuf.timestamp_pb2.Timestamp): - @@ -532,12 +675,20 @@ class QuantumReservationBudget(proto.Message): - """ - name = proto.Field(proto.STRING, number=1) - processor_names = proto.RepeatedField(proto.STRING, number=2) - effective_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - expire_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - granted_duration = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration) - available_duration = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration) + name: str = proto.Field(proto.STRING, number=1) + processor_names: list[str] = proto.RepeatedField(proto.STRING, number=2) + effective_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + granted_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration + ) + available_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration + ) class QuantumTimeSlot(proto.Message): @@ -557,20 +708,33 @@ class QuantumTimeSlot(proto.Message): - end_time (google.protobuf.timestamp_pb2.Timestamp): - - time_slot_type (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.TimeSlotType): + time_slot_type (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.TimeSlotType): - - reservation_config (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.ReservationConfig): + reservation_config (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.ReservationConfig): - This field is a member of `oneof`_ ``type_config``. - maintenance_config (google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.MaintenanceConfig): + maintenance_config (cirq_google.cloud.quantum_v1alpha1.types.QuantumTimeSlot.MaintenanceConfig): - This field is a member of `oneof`_ ``type_config``. - """ + """ # noqa E501 class TimeSlotType(proto.Enum): - r"""-""" + r"""- + + Values: + TIME_SLOT_TYPE_UNSPECIFIED (0): + - + MAINTENANCE (1): + - + OPEN_SWIM (2): + - + RESERVATION (3): + - + UNALLOCATED (4): + - + """ TIME_SLOT_TYPE_UNSPECIFIED = 0 MAINTENANCE = 1 @@ -586,13 +750,13 @@ class ReservationConfig(proto.Message): - project_id (str): - - whitelisted_users (Sequence[str]): + allowlisted_users (list[str]): - """ - reservation = proto.Field(proto.STRING, number=3) - project_id = proto.Field(proto.STRING, number=1) - whitelisted_users = proto.RepeatedField(proto.STRING, number=2) + reservation: str = proto.Field(proto.STRING, number=3) + project_id: str = proto.Field(proto.STRING, number=1) + allowlisted_users: list[str] = proto.RepeatedField(proto.STRING, number=2) class MaintenanceConfig(proto.Message): r"""- @@ -604,17 +768,21 @@ class MaintenanceConfig(proto.Message): - """ - title = proto.Field(proto.STRING, number=1) - description = proto.Field(proto.STRING, number=2) + title: str = proto.Field(proto.STRING, number=1) + description: str = proto.Field(proto.STRING, number=2) - processor_name = proto.Field(proto.STRING, number=1) - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - time_slot_type = proto.Field(proto.ENUM, number=5, enum=TimeSlotType) - reservation_config = proto.Field( + processor_name: str = proto.Field(proto.STRING, number=1) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + time_slot_type: TimeSlotType = proto.Field(proto.ENUM, number=5, enum=TimeSlotType) + reservation_config: ReservationConfig = proto.Field( proto.MESSAGE, number=6, oneof='type_config', message=ReservationConfig ) - maintenance_config = proto.Field( + maintenance_config: MaintenanceConfig = proto.Field( proto.MESSAGE, number=7, oneof='type_config', message=MaintenanceConfig ) @@ -631,15 +799,21 @@ class QuantumReservation(proto.Message): - cancelled_time (google.protobuf.timestamp_pb2.Timestamp): - - whitelisted_users (Sequence[str]): + allowlisted_users (list[str]): - """ - name = proto.Field(proto.STRING, number=1) - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp) - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp) - cancelled_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp) - whitelisted_users = proto.RepeatedField(proto.STRING, number=5) + name: str = proto.Field(proto.STRING, number=1) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp + ) + cancelled_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp + ) + allowlisted_users: list[str] = proto.RepeatedField(proto.STRING, number=5) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/cirq-google/cirq_google/engine/abstract_local_processor.py b/cirq-google/cirq_google/engine/abstract_local_processor.py index 6b76ecba8ab..f356a9a5038 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor.py @@ -238,14 +238,14 @@ def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> quantum.QuantumReservation: """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). @@ -259,7 +259,7 @@ def create_reservation( name=reservation_id, start_time=Timestamp(seconds=int(start_time.timestamp())), end_time=Timestamp(seconds=int(end_time.timestamp())), - whitelisted_users=whitelisted_users, + allowlisted_users=allowlisted_users, ) time_slot = self._reservation_to_time_slot(new_reservation) if not self._is_available(time_slot): @@ -286,7 +286,7 @@ def update_reservation( reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> None: """Updates a reservation with new information. @@ -300,7 +300,7 @@ def update_reservation( starting time is left unchanged. end_time: New ending time of the reservation. If unspecified, ending time is left unchanged. - whitelisted_users: The new list of whitelisted users to allow on + allowlisted_users: The new list of allowlisted users to allow on the reservation. If unspecified, the users are left unchanged. Raises: @@ -316,9 +316,9 @@ def update_reservation( self._reservations[reservation_id].end_time = datetime.datetime.fromtimestamp( _to_timestamp(end_time) ) - if whitelisted_users is not None: - del self._reservations[reservation_id].whitelisted_users[:] - self._reservations[reservation_id].whitelisted_users.extend(whitelisted_users) + if allowlisted_users is not None: + del self._reservations[reservation_id].allowlisted_users[:] + self._reservations[reservation_id].allowlisted_users.extend(allowlisted_users) def list_reservations( self, diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index cbaf6f1057b..01f8828dde2 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -96,11 +96,11 @@ def test_reservations(): # Create Reservation reservation = p.create_reservation( - start_time=start_reservation, end_time=end_reservation, whitelisted_users=users + start_time=start_reservation, end_time=end_reservation, allowlisted_users=users ) assert reservation.start_time.timestamp() == int(start_reservation.timestamp()) assert reservation.end_time.timestamp() == int(end_reservation.timestamp()) - assert reservation.whitelisted_users == users + assert reservation.allowlisted_users == users # Get Reservation assert p.get_reservation(reservation.name) == reservation @@ -116,12 +116,12 @@ def test_reservations(): reservation = p.get_reservation(reservation.name) assert reservation.start_time.timestamp() == int(start_reservation.timestamp()) users = ['gooduser@test.com', 'otheruser@prod.com'] - p.update_reservation(reservation_id=reservation.name, whitelisted_users=users) + p.update_reservation(reservation_id=reservation.name, allowlisted_users=users) reservation = p.get_reservation(reservation.name) - assert reservation.whitelisted_users == users + assert reservation.allowlisted_users == users with pytest.raises(ValueError, match='does not exist'): - p.update_reservation(reservation_id='invalid', whitelisted_users=users) + p.update_reservation(reservation_id='invalid', allowlisted_users=users) def test_list_reservations(): @@ -131,13 +131,13 @@ def test_list_reservations(): users = ['abc@def.com'] reservation1 = p.create_reservation( - start_time=now - hour, end_time=now, whitelisted_users=users + start_time=now - hour, end_time=now, allowlisted_users=users ) reservation2 = p.create_reservation( - start_time=now, end_time=now + hour, whitelisted_users=users + start_time=now, end_time=now + hour, allowlisted_users=users ) reservation3 = p.create_reservation( - start_time=now + hour, end_time=now + 2 * hour, whitelisted_users=users + start_time=now + hour, end_time=now + 2 * hour, allowlisted_users=users ) assert p.list_reservations(now - 2 * hour, now + 3 * hour) == [ diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index de34bb248ca..64cfe92f986 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -284,14 +284,14 @@ def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ) -> quantum.QuantumReservation: """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). """ @@ -310,7 +310,7 @@ def update_reservation( reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a reservation with new information. diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index f67de08e440..4b1f3a2250e 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -951,7 +951,7 @@ async def create_reservation_async( processor_id: str, start: datetime.datetime, end: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Creates a quantum reservation and returns the created object. @@ -962,7 +962,7 @@ async def create_reservation_async( or None if the engine should generate an id start: the starting time of the reservation as a datetime object end: the ending time of the reservation as a datetime object - whitelisted_users: a list of emails that can use the reservation. + allowlisted_users: a list of emails that can use the reservation. """ parent = _processor_name_from_ids(project_id, processor_id) reservation = quantum.QuantumReservation( @@ -970,8 +970,8 @@ async def create_reservation_async( start_time=Timestamp(seconds=int(start.timestamp())), end_time=Timestamp(seconds=int(end.timestamp())), ) - if whitelisted_users: - reservation.whitelisted_users.extend(whitelisted_users) + if allowlisted_users: + reservation.allowlisted_users.extend(allowlisted_users) request = quantum.CreateQuantumReservationRequest( parent=parent, quantum_reservation=reservation ) @@ -1090,12 +1090,12 @@ async def update_reservation_async( reservation_id: str, start: datetime.datetime | None = None, end: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a quantum reservation. This will update a quantum reservation's starting time, ending time, - and list of whitelisted users. If any field is not filled, it will + and list of allowlisted users. If any field is not filled, it will not be updated. Args: @@ -1104,8 +1104,8 @@ async def update_reservation_async( reservation_id: Unique ID of the reservation in the parent project, start: the new starting time of the reservation as a datetime object end: the new ending time of the reservation as a datetime object - whitelisted_users: a list of emails that can use the reservation. - The empty list, [], will clear the whitelisted_users while None + allowlisted_users: a list of emails that can use the reservation. + The empty list, [], will clear the allowlisted_users while None will leave the value unchanged. """ name = ( @@ -1122,9 +1122,9 @@ async def update_reservation_async( if end: reservation.end_time = end paths.append('end_time') - if whitelisted_users is not None: - reservation.whitelisted_users.extend(whitelisted_users) - paths.append('whitelisted_users') + if allowlisted_users is not None: + reservation.allowlisted_users.extend(allowlisted_users) + paths.append('allowlisted_users') request = quantum.UpdateQuantumReservationRequest( name=name, diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 7b714c16756..335742dce1b 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1530,7 +1530,7 @@ def test_create_reservation(client_constructor, default_engine_client): name='projects/proj/processors/processor0/reservations/papar-party-44', start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=users, + allowlisted_users=users, ) grpc_client.create_quantum_reservation.return_value = result @@ -1555,7 +1555,7 @@ def test_cancel_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.cancel_quantum_reservation.return_value = result @@ -1575,7 +1575,7 @@ def test_delete_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.delete_quantum_reservation.return_value = result @@ -1595,7 +1595,7 @@ def test_get_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.get_quantum_reservation.return_value = result @@ -1635,13 +1635,13 @@ def test_list_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ), quantum.QuantumReservation( name=name, start_time=Timestamp(seconds=1200000000), end_time=Timestamp(seconds=1200002000), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ), ] grpc_client.list_quantum_reservations.return_value = Pager(results) @@ -1657,7 +1657,7 @@ def test_update_reservation(client_constructor, default_engine_client): name=name, start_time=Timestamp(seconds=1000001000), end_time=Timestamp(seconds=1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) grpc_client.update_quantum_reservation.return_value = result @@ -1668,7 +1668,7 @@ def test_update_reservation(client_constructor, default_engine_client): 'papar-party-44', start=datetime.datetime.fromtimestamp(1000001000), end=datetime.datetime.fromtimestamp(1000002000), - whitelisted_users=['jeff@google.com'], + allowlisted_users=['jeff@google.com'], ) == result ) @@ -1676,7 +1676,7 @@ def test_update_reservation(client_constructor, default_engine_client): quantum.UpdateQuantumReservationRequest( name=name, quantum_reservation=result, - update_mask=FieldMask(paths=['start_time', 'end_time', 'whitelisted_users']), + update_mask=FieldMask(paths=['start_time', 'end_time', 'allowlisted_users']), ) ) @@ -1685,12 +1685,12 @@ def test_update_reservation(client_constructor, default_engine_client): def test_update_reservation_remove_all_users(client_constructor, default_engine_client): grpc_client = _setup_client_mock(client_constructor) name = 'projects/proj/processors/processor0/reservations/papar-party-44' - result = quantum.QuantumReservation(name=name, whitelisted_users=[]) + result = quantum.QuantumReservation(name=name, allowlisted_users=[]) grpc_client.update_quantum_reservation.return_value = result assert ( default_engine_client.update_reservation( - 'proj', 'processor0', 'papar-party-44', whitelisted_users=[] + 'proj', 'processor0', 'papar-party-44', allowlisted_users=[] ) == result ) @@ -1698,7 +1698,7 @@ def test_update_reservation_remove_all_users(client_constructor, default_engine_ quantum.UpdateQuantumReservationRequest( name=name, quantum_reservation=result, - update_mask=FieldMask(paths=['whitelisted_users']), + update_mask=FieldMask(paths=['allowlisted_users']), ) ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 22a2a2c85d0..562afb579e8 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -324,19 +324,19 @@ def create_reservation( self, start_time: datetime.datetime, end_time: datetime.datetime, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Creates a reservation on this processor. Args: start_time: the starting date/time of the reservation. end_time: the ending date/time of the reservation. - whitelisted_users: a list of emails that are allowed + allowlisted_users: a list of emails that are allowed to send programs during this reservation (in addition to users with permission "quantum.reservations.use" on the project). """ response = self.context.client.create_reservation( - self.project_id, self.processor_id, start_time, end_time, whitelisted_users + self.project_id, self.processor_id, start_time, end_time, allowlisted_users ) return response @@ -393,7 +393,7 @@ def update_reservation( reservation_id: str, start_time: datetime.datetime | None = None, end_time: datetime.datetime | None = None, - whitelisted_users: list[str] | None = None, + allowlisted_users: list[str] | None = None, ): """Updates a reservation with new information. @@ -407,7 +407,7 @@ def update_reservation( reservation_id, start=start_time, end=end_time, - whitelisted_users=whitelisted_users, + allowlisted_users=allowlisted_users, ) def list_reservations( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 79f03c56516..f99b26674cc 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -465,7 +465,7 @@ def test_create_reservation(create_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) create_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -490,7 +490,7 @@ def test_delete_reservation(delete_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) delete_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -505,7 +505,7 @@ def test_cancel_reservation(cancel_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) cancel_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -522,7 +522,7 @@ def test_remove_reservation_delete(delete_reservation, get_reservation): name=name, start_time=Timestamp(seconds=now + 20000), end_time=Timestamp(seconds=now + 23610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result delete_reservation.return_value = result @@ -545,7 +545,7 @@ def test_remove_reservation_cancel(cancel_reservation, get_reservation): name=name, start_time=Timestamp(seconds=now + 10), end_time=Timestamp(seconds=now + 3610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result cancel_reservation.return_value = result @@ -581,7 +581,7 @@ def test_remove_reservation_failures(get_reservation, get_processor): name=name, start_time=Timestamp(seconds=now + 10), end_time=Timestamp(seconds=now + 3610), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result get_processor.return_value = None @@ -604,7 +604,7 @@ def test_get_reservation(get_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) get_reservation.return_value = result processor = cg.EngineProcessor('proj', 'p0', EngineContext()) @@ -619,7 +619,7 @@ def test_update_reservation(update_reservation): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ) start = datetime.datetime.fromtimestamp(1000000000) end = datetime.datetime.fromtimestamp(1000003600) @@ -627,7 +627,7 @@ def test_update_reservation(update_reservation): processor = cg.EngineProcessor('proj', 'p0', EngineContext()) assert processor.update_reservation('rid', start, end, ['dstrain@google.com']) == result update_reservation.assert_called_once_with( - 'proj', 'p0', 'rid', start=start, end=end, whitelisted_users=['dstrain@google.com'] + 'proj', 'p0', 'rid', start=start, end=end, allowlisted_users=['dstrain@google.com'] ) @@ -639,13 +639,13 @@ def test_list_reservation(list_reservations): name=name, start_time=Timestamp(seconds=1000000000), end_time=Timestamp(seconds=1000003600), - whitelisted_users=['dstrain@google.com'], + allowlisted_users=['dstrain@google.com'], ), quantum.QuantumReservation( name=name + '2', start_time=Timestamp(seconds=1000003600), end_time=Timestamp(seconds=1000007200), - whitelisted_users=['wcourtney@google.com'], + allowlisted_users=['wcourtney@google.com'], ), ] list_reservations.return_value = results diff --git a/dev_tools/notebooks/isolated_notebook_test.py b/dev_tools/notebooks/isolated_notebook_test.py index cfecaff9593..578389ca19f 100644 --- a/dev_tools/notebooks/isolated_notebook_test.py +++ b/dev_tools/notebooks/isolated_notebook_test.py @@ -67,6 +67,8 @@ # temporary: need to fix QVM metrics and device spec 'docs/tutorials/google/spin_echoes.ipynb', 'docs/tutorials/google/visualizing_calibration_metrics.ipynb', + # temporary: allow name changes of keyword arguments in quantum engine interfaces to stabilize + 'docs/simulate/virtual_engine_interface.ipynb', ] SKIP_NOTEBOOKS += [ # notebooks that import the examples module which is not installed with cirq diff --git a/docs/google/concepts.ipynb b/docs/google/concepts.ipynb index 2fd286aa311..a259b053438 100644 --- a/docs/google/concepts.ipynb +++ b/docs/google/concepts.ipynb @@ -269,7 +269,7 @@ "\n", "* OPEN_SWIM: Anyone with processor access may run jobs. There may be additional restrictions per processor that restrict large jobs.\n", "* MAINTENANCE: restrictions behave the same as during open swim, but there are no guarantees about the availability of the processor or quality of jobs run during this period.\n", - "* RESERVATION: The processor is reserved for restricted use by a user or set of users. Reservations are rooted under a project and editors of that project may run jobs during that project's reservations while using any project they wish. Additional users may also be whitelisted to specific reservations.\n", + "* RESERVATION: The processor is reserved for restricted use by a user or set of users. Reservations are rooted under a project and editors of that project may run jobs during that project's reservations while using any project they wish. Additional users may also be allowlisted to specific reservations.\n", "* UNALLOCATED: The processor has not been scheduled for any purpose. A reservation may be made during this time. If nothing is scheduled during this block, it will default to behaving as open swim.\n", "\n", "During non-reservation times, jobs are restricted to run for at most 5 minutes and may have no more than 1,500,000 total shots on the processor.\n", diff --git a/docs/simulate/virtual_engine_interface.ipynb b/docs/simulate/virtual_engine_interface.ipynb index 9872d7873d7..a77bb3028f0 100644 --- a/docs/simulate/virtual_engine_interface.ipynb +++ b/docs/simulate/virtual_engine_interface.ipynb @@ -94,13 +94,14 @@ "source": [ "try:\n", " import cirq\n", + " import cirq_google\n", "except ImportError:\n", " print(\"installing cirq...\")\n", - " !pip install --quiet cirq\n", + " !pip install --quiet cirq~=1.0.dev cirq-google~=1.0.dev\n", " print(\"installed cirq.\")\n", " import cirq\n", + " import cirq_google\n", "\n", - "import cirq_google\n", "import sympy" ] }, @@ -286,7 +287,7 @@ " weber.create_reservation(\n", " start_time=now + 2 * hour,\n", " end_time=now + 3 * hour,\n", - " whitelisted_users=['mysterious_fake_user@nonexistentwebsite.domain'],\n", + " allowlisted_users=['mysterious_fake_user@nonexistentwebsite.domain'],\n", " )\n", "except ValueError as e:\n", " # If you re-run this cell, it will note that you already have a reservation\n", From 6866f26862f1b05f90544776938694faafb1d5af Mon Sep 17 00:00:00 2001 From: dyates Date: Wed, 30 Jul 2025 00:57:53 +0000 Subject: [PATCH 04/37] Add `get_quantum_processor_config_by_snapshot_id` --- .../cirq_google/engine/engine_client.py | 19 ++++++++++++++ .../cirq_google/engine/engine_client_test.py | 26 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 3405d5a4640..78b64ef6e31 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1182,6 +1182,20 @@ async def list_time_slots_async( list_time_slots = duet.sync(list_time_slots_async) + async def get_quantum_processor_config_by_snapshot_id_async(self, + project_id: str, processor_id: str, config_id: str, snapshot_id: str + ) -> quantum.QuantumProcessorConfig: + request = quantum.GetQuantumProcessorConfigRequest( + name=_quantum_processor_name_with_snapshot_id( + project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + ) + ) + return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) + + get_quantum_processor_config_by_snapshot_id = duet.sync(get_quantum_processor_config_by_snapshot_id_async) + + + def _project_name(project_id: str) -> str: return f'projects/{project_id}' @@ -1229,6 +1243,11 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: parts = calibration_name.split('/') return parts[1], parts[3], int(parts[5]) +def _quantum_processor_name_with_snapshot_id( + project_id: str, processor_id: str, snapshot_id: str, config_id: str +) -> str: + return f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + def _date_or_time_to_filter_expr(param_name: str, param: datetime.datetime | datetime.date): """Formats datetime or date to filter expressions. diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 9ca4eaf1ddc..e7f8886ebfc 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1743,3 +1743,29 @@ def test_list_time_slots(client_constructor, default_engine_client): grpc_client.list_quantum_time_slots.return_value = Pager(results) assert default_engine_client.list_time_slots('proj', 'processor0') == results + +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_snapshot_id( + client_constructor, default_engine_client): + grpc_client = _setup_client_mock(client_constructor) + project_id = "test_project" + processor_id = "test_processor" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + + result = quantum.QuantumProcessorConfig( + name=name, + device_specification=any_pb2.Any(), + characterization=any_pb2.Any() + ) + grpc_client = _setup_client_mock(client_constructor) + grpc_client.get_quantum_processor_config_by_snapshot_id.return_value = result + + assert default_engine_client.get_quantum_processor_config_by_snapshot_id( + project_id=project_id, processor_id=processor_id, config_id=config_id, snapshot_id=snapshot_id + ) + grpc_client.get_quantum_processor_config.assert_called_with( + quantum.GetQuantumProcessorConfigRequest(name=name) + ) + From 20ca033e2bb4acc938506f8d586b41c99df14c74 Mon Sep 17 00:00:00 2001 From: dyates Date: Wed, 30 Jul 2025 17:11:39 +0000 Subject: [PATCH 05/37] Add unit test for missing config. --- .../cirq_google/engine/engine_client.py | 31 +++++++++++---- .../cirq_google/engine/engine_client_test.py | 39 +++++++++++++------ 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 78b64ef6e31..55e6d72f5d8 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1184,13 +1184,30 @@ async def list_time_slots_async( async def get_quantum_processor_config_by_snapshot_id_async(self, project_id: str, processor_id: str, config_id: str, snapshot_id: str - ) -> quantum.QuantumProcessorConfig: - request = quantum.GetQuantumProcessorConfigRequest( - name=_quantum_processor_name_with_snapshot_id( - project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id - ) - ) - return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) + ) -> quantum.QuantumProcessorConfig | None: + """Returns the QuantumProcessorConfig for the given snapshot id. + + Args: + project_id: A project_id of the parent Google Cloud Project. + processor_id: The processor unique identifier. + config_id: The id of the quantum processor config. + snapshot_id: The id of the snapshot that contains the quantum processor config. + + Returns: + The quantum procesor config or None if it does not exist. + + Raises: + EngineException: If the request to get the config fails. + """ + try: + name = _quantum_processor_name_with_snapshot_id( + project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id) + request = quantum.GetQuantumProcessorConfigRequest(name=name) + return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) + except EngineException as err: + if isinstance(err.__cause__, NotFound): + return None + raise get_quantum_processor_config_by_snapshot_id = duet.sync(get_quantum_processor_config_by_snapshot_id_async) diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index e7f8886ebfc..607a1efc2a3 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1747,25 +1747,40 @@ def test_list_time_slots(client_constructor, default_engine_client): @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_snapshot_id( client_constructor, default_engine_client): - grpc_client = _setup_client_mock(client_constructor) - project_id = "test_project" - processor_id = "test_processor" + + project_id = "test_project_id" + processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' - result = quantum.QuantumProcessorConfig( - name=name, - device_specification=any_pb2.Any(), - characterization=any_pb2.Any() - ) grpc_client = _setup_client_mock(client_constructor) - grpc_client.get_quantum_processor_config_by_snapshot_id.return_value = result + expected_result = quantum.QuantumProcessorConfig(name=resource_name) + grpc_client.get_quantum_processor_config.return_value = expected_result - assert default_engine_client.get_quantum_processor_config_by_snapshot_id( + actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( project_id=project_id, processor_id=processor_id, config_id=config_id, snapshot_id=snapshot_id ) grpc_client.get_quantum_processor_config.assert_called_with( - quantum.GetQuantumProcessorConfigRequest(name=name) + quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) + assert actual_result == expected_result + +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructor, default_engine_client): + project_id = "test_project_id" + processor_id = "test_processor_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + grpc_client = _setup_client_mock(client_constructor) + grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') + + actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( + project_id=project_id, processor_id=processor_id, config_id=config_id, snapshot_id=snapshot_id + ) + grpc_client.get_quantum_processor_config.assert_called_with( + quantum.GetQuantumProcessorConfigRequest(name=resource_name) + ) + assert actual_result is None From b3413a4f22ee681dfdac4c686a911f00aa77a0f2 Mon Sep 17 00:00:00 2001 From: dyates Date: Wed, 30 Jul 2025 19:42:10 +0000 Subject: [PATCH 06/37] Add `get_quantum_processor_config_by_run_name`. --- .../cirq_google/engine/engine_client.py | 52 +++++++++++++++---- .../cirq_google/engine/engine_client_test.py | 40 ++++++++++++++ 2 files changed, 83 insertions(+), 9 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 55e6d72f5d8..c9fa7c8a1ca 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1181,9 +1181,21 @@ async def list_time_slots_async( list_time_slots = duet.sync(list_time_slots_async) + async def _get_quantum_processor_config( + self, name: str + ) -> quantum.QuantumProcessorConfig | None: + """Runs get_quantum_processor_config with the given resource name.""" + try: + request = quantum.GetQuantumProcessorConfigRequest(name=name) + return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) + except EngineException as err: + if isinstance(err.__cause__, NotFound): + return None + raise + async def get_quantum_processor_config_by_snapshot_id_async(self, - project_id: str, processor_id: str, config_id: str, snapshot_id: str + project_id: str, processor_id: str, snapshot_id: str, config_id: str, ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1199,19 +1211,35 @@ async def get_quantum_processor_config_by_snapshot_id_async(self, Raises: EngineException: If the request to get the config fails. """ - try: - name = _quantum_processor_name_with_snapshot_id( + name = _quantum_processor_name_with_snapshot_id( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id) - request = quantum.GetQuantumProcessorConfigRequest(name=name) - return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) - except EngineException as err: - if isinstance(err.__cause__, NotFound): - return None - raise + return await self._get_quantum_processor_config(name) get_quantum_processor_config_by_snapshot_id = duet.sync(get_quantum_processor_config_by_snapshot_id_async) + async def get_quantum_processor_config_by_run_name_async(self, + project_id: str, processor_id: str, run_name: str, config_id: str, + ) -> quantum.QuantumProcessorConfig | None: + """Returns the QuantumProcessorConfig for the given run_name. + Args: + project_id: A project_id of the parent Google Cloud Project. + processor_id: The processor unique identifier. + config_id: The id of the quantum processor config. + run_name: The run_name that contains the quantum processor config. + + Returns: + The quantum procesor config or None if it does not exist. + + Raises: + EngineException: If the request to get the config fails. + """ + name = _quantum_processor_name_with_run_name( + project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id + ) + return await self._get_quantum_processor_config(name) + + get_quantum_processor_config_by_run_name = duet.sync(get_quantum_processor_config_by_run_name_async) def _project_name(project_id: str) -> str: return f'projects/{project_id}' @@ -1266,6 +1294,12 @@ def _quantum_processor_name_with_snapshot_id( return f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' +def _quantum_processor_name_with_run_name( + project_id: str, processor_id: str, run_name: str, config_id: str +) -> str: + return f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + + def _date_or_time_to_filter_expr(param_name: str, param: datetime.datetime | datetime.date): """Formats datetime or date to filter expressions. diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 607a1efc2a3..c1f1d78bbff 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1784,3 +1784,43 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructo quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) assert actual_result is None + +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_run_name( + client_constructor, default_engine_client): + + project_id = "test_project_id" + processor_id = "test_processor_id" + run_name = "test_run_name" + config_id = "test_config_id" + resource_name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + + grpc_client = _setup_client_mock(client_constructor) + expected_result = quantum.QuantumProcessorConfig(name=resource_name) + grpc_client.get_quantum_processor_config.return_value = expected_result + + actual_result = default_engine_client.get_quantum_processor_config_by_run_name( + project_id=project_id, processor_id=processor_id, config_id=config_id, run_name=run_name + ) + grpc_client.get_quantum_processor_config.assert_called_with( + quantum.GetQuantumProcessorConfigRequest(name=resource_name) + ) + assert actual_result == expected_result + +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_run_name_not_found(client_constructor, default_engine_client): + project_id = "test_project_id" + processor_id = "test_processor_id" + run_name = "test_run_name" + config_id = "test_config_id" + resource_name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + grpc_client = _setup_client_mock(client_constructor) + grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') + + actual_result = default_engine_client.get_quantum_processor_config_by_run_name( + project_id=project_id, processor_id=processor_id, config_id=config_id, run_name=run_name + ) + grpc_client.get_quantum_processor_config.assert_called_with( + quantum.GetQuantumProcessorConfigRequest(name=resource_name) + ) + assert actual_result is None From eed577da614ff5fb77b295bea245f668bedf87cb Mon Sep 17 00:00:00 2001 From: dyates Date: Thu, 31 Jul 2025 04:14:48 +0000 Subject: [PATCH 07/37] Implement `get_config` for `ProcessorConfigSnapshot`. --- .../cirq_google/engine/engine_client.py | 3 +- .../cirq_google/engine/processor_config.py | 73 ++++++++++----- .../engine/processor_config_test.py | 90 ++++++++++++++++--- 3 files changed, 130 insertions(+), 36 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index c9fa7c8a1ca..cf698b319db 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1202,8 +1202,8 @@ async def get_quantum_processor_config_by_snapshot_id_async(self, Args: project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. - config_id: The id of the quantum processor config. snapshot_id: The id of the snapshot that contains the quantum processor config. + config_id: The id of the quantum processor config. Returns: The quantum procesor config or None if it does not exist. @@ -1288,6 +1288,7 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: parts = calibration_name.split('/') return parts[1], parts[3], int(parts[5]) + def _quantum_processor_name_with_snapshot_id( project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> str: diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 800b9201354..09554330638 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -17,11 +17,15 @@ from typing import TYPE_CHECKING from cirq_google.devices import GridDevice +from cirq_google.api import v2 +from cirq_google.cloud.quantum_v1alpha1.types import quantum -import datetime + +from cirq_google.engine import util +import cirq_google as cg if TYPE_CHECKING: - import cirq_google as cg + import cirq_google.engine.engine as engine_base class ProcessorConfig: """Representation of a quantum processor configuration @@ -39,6 +43,35 @@ def __init__(self, self._name = name self._effective_device = effective_device self._calibration = calibration + + @classmethod + def from_quantum_config( + cls, quantum_config: quantum.QuantumProcessorConfig + ) -> ProcessorConfig: + """Create instance from a QuantumProcessorConfig + + Args: + quantum_config: The `QuantumProcessorConfig` to create. + + Raises: + ValueError: If the quantum_config.device_specification is invalid + + Returns: + The ProcessorConfig + """ + name = quantum_config.name + device_spec = util.unpack_any( + quantum_config.device_specification, v2.device_pb2.DeviceSpecification() + ) + characterization = util.unpack_any( + quantum_config.characterization, v2.metrics_pb2.MetricsSnapshot() + ) + + return ProcessorConfig( + name=name, + effective_device=cg.GridDevice.from_proto(device_spec), + calibration=cg.Calibration(characterization) + ) @property def name(self) -> str: @@ -61,39 +94,33 @@ class ProcessorConfigSnapshot: def __init__(self, *, + project_id: str, + processor_id: str, snapshot_id: str, - create_time: datetime.datetime, - run_names: list[str], - processor_configs: list[ProcessorConfig] + context: engine_base.EngineContext, ) -> None: + self._project_id = project_id + self._processor_id = processor_id self._snapshot_id = snapshot_id - self._create_time = create_time - self._run_names = run_names - self._processor_configs = processor_configs + self._context = context @property def snapshot_id(self) -> str: """The indentifier for this snapshot.""" return self._snapshot_id - @property - def run_names(self) -> list[str]: - """Alternate ids which may be used to identify this config snapshot.""" - return self._run_names - - @property - def all_configs(self) -> list[ProcessorConfig]: - """List of all configurations in this snapshot.""" - return self._processor_configs - def get_config(self, name: str) -> ProcessorConfig | None: """Returns the configuration with the given name in this snapshot if it exists. Args: name: The name of the configuration. + + Raises: + ValueError: If config is invalid. """ - for config in self._processor_configs: - if name == config.name: - return config - - return None + response = self._context.client.get_quantum_processor_config_by_snapshot_id( + project_id=self._project_id, processor_id=self._processor_id, + snapshot_id=self._snapshot_id, config_id=name + ) + return ProcessorConfig.from_quantum_config(response) + diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 9381cff8bea..a7ea39be23c 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -18,21 +18,87 @@ import cirq_google as cg +from unittest import mock import datetime +import pytest -def test_get_config_returns_existing_processor_config(): - p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibration=None) - p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibration=None) - id = 'p2' - snapshot = cg.engine.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) +from google.protobuf.text_format import Merge +from google.protobuf.timestamp_pb2 import Timestamp +from cirq_google.api import v2 +from cirq_google.cloud import quantum +from cirq_google.devices import GridDevice +from cirq_google.engine import engine_client, util +from cirq_google.engine.engine import EngineContext - assert snapshot.get_config(id) == p2 +_METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( + timestamp_ms=1562544000021, + metrics=[ + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '0_1'], + values=[v2.metrics_pb2.Value(double_val=0.9999)], + ), + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '1_0'], + values=[v2.metrics_pb2.Value(double_val=0.9998)], + ), + ], + ) -def test_get_config_returns_none(): - p1 = cg.engine.ProcessorConfig(name="p1", effective_device=None, calibration=None) - p2 = cg.engine.ProcessorConfig(name="p2", effective_device=None, calibration=None) - id_does_not_exist = 'p3' - snapshot = cg.engine.ProcessorConfigSnapshot(snapshot_id="test_snap", create_time=datetime.datetime.now, run_names=[], processor_configs=[p1, p2]) +_DEVICE_SPEC = v2.device_pb2.DeviceSpecification( + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target( + ids=["0_0", "1_1"] + )] + ) + ], +) - assert snapshot.get_config(id_does_not_exist) == None \ No newline at end of file + +@pytest.fixture(scope='module', autouse=True) +def mock_grpc_client(): + with mock.patch( + 'cirq_google.engine.engine_client.quantum.QuantumEngineServiceClient' + ) as _fixture: + yield _fixture + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +def test_get_config(get_quantum_processor): + project_id = "test_project_id" + processor_id = "test_proc_id" + snapshot_id = "test_proc_id" + config_id = "test_config_id" + name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + snapshot = cg.engine.ProcessorConfigSnapshot( + project_id=project_id, processor_id=processor_id, + snapshot_id=snapshot_id, context=EngineContext() + ) + + expected_config = cg.engine.ProcessorConfig( + name=name, + effective_device=GridDevice.from_proto(_DEVICE_SPEC), + calibration=cg.Calibration(_METRIC_SNAPSHOT) + ) + + quantum_config = quantum.QuantumProcessorConfig( + name=name, + device_specification=util.pack_any(_DEVICE_SPEC), + characterization=util.pack_any(_METRIC_SNAPSHOT) + ) + get_quantum_processor.return_value = quantum_config + + actual_config = snapshot.get_config(config_id) + + get_quantum_processor.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + snapshot_id=snapshot_id, config_id=config_id + ) + assert actual_config.name == expected_config.name + assert actual_config.effective_device == expected_config.effective_device + assert actual_config.calibration == expected_config.calibration From cc447ff21b8f23e57ab221a43cd87e549f7a8127 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 4 Aug 2025 17:30:30 +0000 Subject: [PATCH 08/37] Add `get_config*` functions to EngineProcessor. --- .../cirq_google/engine/abstract_processor.py | 33 ++++ .../cirq_google/engine/engine_processor.py | 45 ++++- .../engine/engine_processor_test.py | 157 +++++++++++++++++- 3 files changed, 232 insertions(+), 3 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 64cfe92f986..fe0a004e2e4 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -35,6 +35,7 @@ import cirq_google.engine.abstract_engine as abstract_engine import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.calibration as calibration + from cirq_google.engine import ProcessorConfig class AbstractProcessor(abc.ABC): @@ -377,3 +378,35 @@ def get_schedule( Returns: Schedule time slots. """ + + @abc.abstractmethod + def get_config_by_run_name( + self, config_id: str, run_name: str = "current" + ) -> ProcessorConfig: + """Retrieves a ProcessorConfig from an automation run. + + If no run name is provided, the config from the most recent run + is returned. + + Args: + processor_id: The processor unique identifier. + confi_id: The quantum processor's unique identifier. + run_name: The automation run name. Use 'current' + if none id provided. + + Returns: The quantum processor config. + """ + + @abc.abstractmethod + def get_config_by_snapshot( + self, config_id: str, snapshot_id: str + ) -> ProcessorConfig: + """Retrieves a ProcessorConfig from a given snapshot id. + + Args: + processor_id: The processor unique identifier. + confi_id: The quantum processor's unique identifier. + snapshot_id: The snapshot's unique identifier. + + Returns: The quantum processor config. + """ diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index b23abc7a311..f0c0b984226 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -20,7 +20,7 @@ from cirq import _compat from cirq_google.api import v2 from cirq_google.devices import grid_device -from cirq_google.engine import abstract_processor, calibration, processor_sampler, util +from cirq_google.engine import abstract_processor, calibration, processor_sampler, util, processor_config if TYPE_CHECKING: from google.protobuf import any_pb2 @@ -497,6 +497,49 @@ def get_schedule( filter_str = ' AND '.join(filters) return self.context.client.list_time_slots(self.project_id, self.processor_id, filter_str) + def get_config_by_run_name( + self, config_id: str, run_name: str = "current" + ) -> processor_config.ProcessorConfig: + """Retrieves a ProcessorConfig from an automation run. + + If no run name is provided, the config from the most recent run + is returned. + + Args: + processor_id: The processor unique identifier. + confi_id: The quantum processor's unique identifier. + run_name: The automation run name. Use 'current' + if none id provided. + + Returns: The quantum processor config. + """ + response = self.context.client.get_quantum_processor_config_by_run_name( + project_id=self.project_id, processor_id=self.processor_id, + run_name=run_name, config_id=config_id + ) + return processor_config.ProcessorConfig.from_quantum_config(response) + + def get_config_by_snapshot( + self, config_id: str, snapshot_id: str + ) -> processor_config.ProcessorConfig: + """Retrieves a ProcessorConfig from a given snapshot id. + + Args: + processor_id: The processor unique identifier. + confi_id: The quantum processor's unique identifier. + snapshot_id: The snapshot's unique identifier. + + Returns: The quantum processor config. + + Raises: + EngineException: If the request to get the config fails. + """ + response = self.context.client.get_quantum_processor_config_by_snapshot_id( + project_id=self.project_id, processor_id=self.processor_id, + snapshot_id=snapshot_id, config_id=config_id + ) + return processor_config.ProcessorConfig.from_quantum_config(response) + def __str__(self): return ( f"EngineProcessor(project_id={self.project_id!r}, " diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index dee637b5e25..192c4f296ce 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -28,8 +28,9 @@ import cirq import cirq_google as cg from cirq_google.api import v2 +from cirq_google.devices import grid_device from cirq_google.cloud import quantum -from cirq_google.engine import engine_client, util +from cirq_google.engine import engine_client, util, calibration, ProcessorConfig from cirq_google.engine.engine import EngineContext @@ -181,6 +182,23 @@ def _to_timestamp(json_string): ) +_METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( + timestamp_ms=1562544000021, + metrics=[ + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '0_1'], + values=[v2.metrics_pb2.Value(double_val=0.9999)], + ), + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '1_0'], + values=[v2.metrics_pb2.Value(double_val=0.9998)], + ), + ], + ) + + class FakeEngineContext(EngineContext): """Fake engine context for testing.""" @@ -997,7 +1015,142 @@ def test_sampler_with_stream_rpcs(client): assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')} assert client().run_job_over_stream.call_args[1]['project_id'] == 'proj' - def test_str(): processor = cg.EngineProcessor('a', 'p', EngineContext()) assert str(processor) == 'EngineProcessor(project_id=\'a\', processor_id=\'p\')' + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +def test_get_config_by_run_name(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + run_name = "test_run_name" + config_id = "test_config_id" + name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + + device_spec = v2.device_pb2.DeviceSpecification( + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target( + ids=["0_0", "1_1"] + )] + ) + ], + ) + expected_config = ProcessorConfig( + name=name, + effective_device=grid_device.GridDevice.from_proto(device_spec), + calibration=cg.Calibration(_METRIC_SNAPSHOT) + ) + quantum_config = quantum.QuantumProcessorConfig( + name=name, + device_specification=util.pack_any(device_spec), + characterization=util.pack_any(_METRIC_SNAPSHOT) + ) + get_quantum_config.return_value = quantum_config + processor = cg.EngineProcessor( + project_id=project_id, + processor_id=processor_id, + context=EngineContext() + ) + + actual_config = processor.get_config_by_run_name( + config_id=config_id, run_name=run_name + ) + + get_quantum_config.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + run_name=run_name, config_id=config_id + ) + assert actual_config.name == expected_config.name + assert actual_config.effective_device == expected_config.effective_device + assert actual_config.calibration == expected_config.calibration + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +def test_get_current_config_by_run_name(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + config_id = "test_config_id" + name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/current/configs/{config_id}' + + device_spec = v2.device_pb2.DeviceSpecification( + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target( + ids=["0_0", "1_1"] + )] + ) + ], + ) + quantum_config = quantum.QuantumProcessorConfig( + name=name, + device_specification=util.pack_any(device_spec), + characterization=util.pack_any(_METRIC_SNAPSHOT) + ) + get_quantum_config.return_value = quantum_config + processor = cg.EngineProcessor( + project_id=project_id, + processor_id=processor_id, + context=EngineContext() + ) + + _ = processor.get_config_by_run_name(config_id=config_id) + + get_quantum_config.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + run_name="current", config_id=config_id + ) + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +def test_get_config_by_snapshot_id(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + + device_spec = v2.device_pb2.DeviceSpecification( + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target( + ids=["0_0", "1_1"] + )] + ) + ], + ) + expected_config = ProcessorConfig( + name=name, + effective_device=grid_device.GridDevice.from_proto(device_spec), + calibration=cg.Calibration(_METRIC_SNAPSHOT) + ) + quantum_config = quantum.QuantumProcessorConfig( + name=name, + device_specification=util.pack_any(device_spec), + characterization=util.pack_any(_METRIC_SNAPSHOT) + ) + get_quantum_config.return_value = quantum_config + processor = cg.EngineProcessor( + project_id=project_id, + processor_id=processor_id, + context=EngineContext() + ) + + actual_config = processor.get_config_by_snapshot( + config_id=config_id, snapshot_id=snapshot_id + ) + + get_quantum_config.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + snapshot_id=snapshot_id, config_id=config_id + ) + assert actual_config.name == expected_config.name + assert actual_config.effective_device == expected_config.effective_device + assert actual_config.calibration == expected_config.calibration \ No newline at end of file From c30bde833aa579c0253d1b0d4f437f1e0a584e4d Mon Sep 17 00:00:00 2001 From: dyates Date: Tue, 5 Aug 2025 00:05:58 +0000 Subject: [PATCH 09/37] Sync changes --- cirq-google/cirq_google/engine/__init__.py | 1 - .../cirq_google/engine/processor_config.py | 37 +----------------- .../engine/processor_config_test.py | 38 ++++--------------- 3 files changed, 10 insertions(+), 66 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index ae6ffb3448f..16b91102108 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -98,6 +98,5 @@ from cirq_google.engine.processor_config import ( ProcessorConfig as ProcessorConfig, - ProcessorConfigSnapshot as ProcessorConfigSnapshot, ) diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 09554330638..0e885a49aaa 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -87,40 +87,7 @@ def effective_device(self) -> GridDevice: def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" return self._calibration - - -class ProcessorConfigSnapshot: - """A snapshot of available device configurations for a processor.""" - - def __init__(self, - *, - project_id: str, - processor_id: str, - snapshot_id: str, - context: engine_base.EngineContext, - ) -> None: - self._project_id = project_id - self._processor_id = processor_id - self._snapshot_id = snapshot_id - self._context = context - @property - def snapshot_id(self) -> str: - """The indentifier for this snapshot.""" - return self._snapshot_id - - def get_config(self, name: str) -> ProcessorConfig | None: - """Returns the configuration with the given name in this snapshot if it exists. - - Args: - name: The name of the configuration. - - Raises: - ValueError: If config is invalid. - """ - response = self._context.client.get_quantum_processor_config_by_snapshot_id( - project_id=self._project_id, processor_id=self._processor_id, - snapshot_id=self._snapshot_id, config_id=name - ) - return ProcessorConfig.from_quantum_config(response) + def __repr__(self) -> str: + return f'cirq_google.ProcessorConfig(name={self.name}, effective_device={repr(self.effective_device)}, calibration={repr(self.calibration)})' diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index a7ea39be23c..1331afff594 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -18,17 +18,12 @@ import cirq_google as cg -from unittest import mock -import datetime import pytest -from google.protobuf.text_format import Merge -from google.protobuf.timestamp_pb2 import Timestamp from cirq_google.api import v2 from cirq_google.cloud import quantum from cirq_google.devices import GridDevice -from cirq_google.engine import engine_client, util -from cirq_google.engine.engine import EngineContext +from cirq_google.engine import util _METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( timestamp_ms=1562544000021, @@ -60,45 +55,28 @@ ], ) +def test_from_quantum_config(): -@pytest.fixture(scope='module', autouse=True) -def mock_grpc_client(): - with mock.patch( - 'cirq_google.engine.engine_client.quantum.QuantumEngineServiceClient' - ) as _fixture: - yield _fixture - -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') -def test_get_config(get_quantum_processor): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_proc_id" config_id = "test_config_id" name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' - snapshot = cg.engine.ProcessorConfigSnapshot( - project_id=project_id, processor_id=processor_id, - snapshot_id=snapshot_id, context=EngineContext() - ) - expected_config = cg.engine.ProcessorConfig( name=name, effective_device=GridDevice.from_proto(_DEVICE_SPEC), calibration=cg.Calibration(_METRIC_SNAPSHOT) ) - quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(_DEVICE_SPEC), characterization=util.pack_any(_METRIC_SNAPSHOT) ) - get_quantum_processor.return_value = quantum_config - - actual_config = snapshot.get_config(config_id) - get_quantum_processor.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - snapshot_id=snapshot_id, config_id=config_id + processor_config = cg.engine.ProcessorConfig.from_quantum_config( + quantum_config ) - assert actual_config.name == expected_config.name - assert actual_config.effective_device == expected_config.effective_device - assert actual_config.calibration == expected_config.calibration + + assert processor_config.name == expected_config.name + assert processor_config.effective_device == expected_config.effective_device + assert processor_config.calibration == expected_config.calibration From 2eb9ee95567014684e93fde82a5fa31fe3d8f67b Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 8 Aug 2025 20:37:36 +0000 Subject: [PATCH 10/37] Add `AbstractProcessorConfig` interface. --- .../engine/abstract_processor_config.py | 51 +++++++ .../cirq_google/engine/engine_processor.py | 9 +- .../engine/engine_processor_test.py | 28 ++-- .../cirq_google/engine/processor_config.py | 126 +++++++++++------- .../engine/processor_config_test.py | 99 +++++++++++--- 5 files changed, 231 insertions(+), 82 deletions(-) create mode 100644 cirq-google/cirq_google/engine/abstract_processor_config.py diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py new file mode 100644 index 00000000000..74d3155d005 --- /dev/null +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import abc +import datetime +from typing import TYPE_CHECKING + +import cirq + +import cirq_google as cg + +class AbstractProcessorConfig(abc.ABC): + """Interface for a QuantumProcessorConfig. + + Describes available qubits, gates, and calivration data associated with + a processor configuration. + """ + + @property + @abc.abstractmethod + def effective_device(self) -> cirq.Device: + """The Device generated from thi configuration's device specification""" + + @property + @abc.abstractmethod + def calibration(self) -> cg.Calibration: + """Charicterization metrics captured for this configuration""" + + @property + @abc.abstractmethod + def snapshot_id(self) -> str: + """The snapshot that contains this processor config""" + + @property + @abc.abstractmethod + def run_name(self) -> str: + """The run that generated this config if avaiable.""" + + @property + @abc.abstractmethod + def project_id(self) -> str: + """The if of the project that contains this config.""" + + @property + @abc.abstractmethod + def processor_id(self) -> str: + """The processor id for this config.""" + + @property + @abc.abstractmethod + def config_id(self) -> str: + """The unique identifier for this config.""" \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index f0c0b984226..ebf23ef4a67 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -517,7 +517,10 @@ def get_config_by_run_name( project_id=self.project_id, processor_id=self.processor_id, run_name=run_name, config_id=config_id ) - return processor_config.ProcessorConfig.from_quantum_config(response) + return processor_config.ProcessorConfig( + quantum_processor_config=response, + run_name=run_name + ) def get_config_by_snapshot( self, config_id: str, snapshot_id: str @@ -538,7 +541,9 @@ def get_config_by_snapshot( project_id=self.project_id, processor_id=self.processor_id, snapshot_id=snapshot_id, config_id=config_id ) - return processor_config.ProcessorConfig.from_quantum_config(response) + return processor_config.ProcessorConfig( + quantum_processor_config=response + ) def __str__(self): return ( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 192c4f296ce..46c03a9ef7a 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1039,17 +1039,16 @@ def test_get_config_by_run_name(get_quantum_config): ) ], ) - expected_config = ProcessorConfig( - name=name, - effective_device=grid_device.GridDevice.from_proto(device_spec), - calibration=cg.Calibration(_METRIC_SNAPSHOT) - ) quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT) ) get_quantum_config.return_value = quantum_config + expected_config = ProcessorConfig( + quantum_processor_config=quantum_config, + run_name=run_name + ) processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, @@ -1064,7 +1063,10 @@ def test_get_config_by_run_name(get_quantum_config): project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id ) - assert actual_config.name == expected_config.name + assert actual_config.project_id == expected_config.project_id + assert actual_config.processor_id == expected_config.processor_id + assert actual_config.config_id == config_id + assert actual_config.run_name == run_name assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration @@ -1126,17 +1128,15 @@ def test_get_config_by_snapshot_id(get_quantum_config): ) ], ) - expected_config = ProcessorConfig( - name=name, - effective_device=grid_device.GridDevice.from_proto(device_spec), - calibration=cg.Calibration(_METRIC_SNAPSHOT) - ) quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT) ) get_quantum_config.return_value = quantum_config + expected_config = ProcessorConfig( + quantum_processor_config=quantum_config + ) processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, @@ -1151,6 +1151,10 @@ def test_get_config_by_snapshot_id(get_quantum_config): project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id ) - assert actual_config.name == expected_config.name + assert actual_config.project_id == expected_config.project_id + assert actual_config.processor_id == expected_config.processor_id + assert actual_config.config_id == config_id + assert actual_config.run_name == '' + assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 0e885a49aaa..324d1584e8b 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -16,78 +16,106 @@ from typing import TYPE_CHECKING -from cirq_google.devices import GridDevice +import cirq +import cirq_google as cg + from cirq_google.api import v2 from cirq_google.cloud.quantum_v1alpha1.types import quantum - +from cirq_google.engine import abstract_processor_config from cirq_google.engine import util -import cirq_google as cg -if TYPE_CHECKING: - import cirq_google.engine.engine as engine_base - -class ProcessorConfig: +class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): """Representation of a quantum processor configuration Describes available qubits, gates, and calivration data associated with a processor configuration. + + Raise: + ValueError: If quantum_processor_config is contains incompatible types. """ def __init__(self, *, - name: str, - effective_device: GridDevice, - calibration: cg.Calibration, + quantum_processor_config: quantum.QuantumProcessorConfig, + run_name: str = '' ) -> None: - self._name = name - self._effective_device = effective_device - self._calibration = calibration - - @classmethod - def from_quantum_config( - cls, quantum_config: quantum.QuantumProcessorConfig - ) -> ProcessorConfig: - """Create instance from a QuantumProcessorConfig - - Args: - quantum_config: The `QuantumProcessorConfig` to create. - - Raises: - ValueError: If the quantum_config.device_specification is invalid - - Returns: - The ProcessorConfig - """ - name = quantum_config.name - device_spec = util.unpack_any( - quantum_config.device_specification, v2.device_pb2.DeviceSpecification() - ) - characterization = util.unpack_any( - quantum_config.characterization, v2.metrics_pb2.MetricsSnapshot() - ) + self._quantum_processor_config = quantum_processor_config + self._run_name = run_name - return ProcessorConfig( - name=name, - effective_device=cg.GridDevice.from_proto(device_spec), - calibration=cg.Calibration(characterization) + device_spec = quantum_processor_config.device_specification + if not device_spec.Is(v2.device_pb2.DeviceSpecification.DESCRIPTOR): + raise ValueError( + f'Invalid device_specification type `{device_spec.type_url}`. ' + f'Expected type.googleapis.com/cirq.google.api.v2.DeviceSpecification' + ) + self._device_spec = util.unpack_any( + self._quantum_processor_config.device_specification, + v2.device_pb2.DeviceSpecification() ) - @property - def name(self) -> str: - """The name of this configuration""" - return self._name + metrics = quantum_processor_config.characterization + if not metrics.Is(v2.metrics_pb2.MetricsSnapshot.DESCRIPTOR): + raise ValueError( + f'Invalid characterization type `{metrics.type_url}`. ' + f'Expected type.googleapis.com/cirq.google.api.v2.MetricsSnapshot' + ) + self._metric_snapshot = util.unpack_any( + self._quantum_processor_config.characterization, + v2.metrics_pb2.MetricsSnapshot() + ) @property - def effective_device(self) -> GridDevice: + def effective_device(self) -> cirq.Device: """The GridDevice generated from this configuration's device specification""" - return self._effective_device + return cg.GridDevice.from_proto(self._device_spec) @property def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" - return self._calibration + return cg.Calibration(self._metric_snapshot) + + @property + def snapshot_id(self) -> str: + """The snapshot that contains this processor config""" + if 'configSnapshots' not in self._quantum_processor_config.name: + # We assume the calling `get_quantume_processor_config` always + # returns a config with the snapshot resouce nanme. This check + # is added in case this behavior changes in the future. + return '' + parts = self._quantum_processor_config.name.split('/') + return parts[5] + + @property + def run_name(self) -> str: + """The run that generated this config if avaiable.""" + return self._run_name - def __repr__(self) -> str: - return f'cirq_google.ProcessorConfig(name={self.name}, effective_device={repr(self.effective_device)}, calibration={repr(self.calibration)})' + @property + def project_id(self) -> str: + """The project that contains this config.""" + parts = self._quantum_processor_config.name.split('/') + return parts[1] + + @property + def processor_id(self) -> str: + """The processor id for this config.""" + parts = self._quantum_processor_config.name.split('/') + return parts[3] + + @property + def config_id(self) -> str: + """The unique identifier for this config.""" + parts = self._quantum_processor_config.name.split('/') + return parts[-1] + def __repr__(self) -> str: + return( + f'cirq_google.ProcessorConfig' + f'(project_id={self.project_id}, ' + f'processor_id={self.processor_id}, ' + f'snapshot_id={self.snapshot_id}, ' + f'run_name={self.run_name} ' + f'config_id={self.config_id}' + ) + \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 1331afff594..cbc8d8a00bd 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -25,6 +25,8 @@ from cirq_google.devices import GridDevice from cirq_google.engine import util +from google.protobuf import any_pb2 + _METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( timestamp_ms=1562544000021, metrics=[ @@ -55,28 +57,87 @@ ], ) -def test_from_quantum_config(): - - project_id = "test_project_id" - processor_id = "test_proc_id" - snapshot_id = "test_proc_id" - config_id = "test_config_id" - name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' - expected_config = cg.engine.ProcessorConfig( - name=name, - effective_device=GridDevice.from_proto(_DEVICE_SPEC), - calibration=cg.Calibration(_METRIC_SNAPSHOT) - ) - quantum_config = quantum.QuantumProcessorConfig( - name=name, +_PROCESSOR_ID = 'test_processor_id' +_PROJECT_ID = 'test_project_id' +_SNAPSHOT_ID = 'test_snapshot_id' +_CONFIG_ID = 'test_config_id' + +_VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( + name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ID}', device_specification=util.pack_any(_DEVICE_SPEC), characterization=util.pack_any(_METRIC_SNAPSHOT) ) - processor_config = cg.engine.ProcessorConfig.from_quantum_config( - quantum_config +def test_processor_config_init_fails_with_invalid_device_spec(): + quantum_config = quantum.QuantumProcessorConfig( + name='', + device_specification=any_pb2.Any(), + characterization=util.pack_any(_METRIC_SNAPSHOT) ) + with pytest.raises(ValueError): + _ = cg.engine.ProcessorConfig( + quantum_processor_config=quantum_config + ) + +def test_processor_config_init_fails_with_invalid_characterization(): + quantum_config = quantum.QuantumProcessorConfig( + name='', + device_specification=util.pack_any(_DEVICE_SPEC), + characterization=any_pb2.Any() + ) + with pytest.raises(ValueError): + _ = cg.engine.ProcessorConfig( + quantum_processor_config=quantum_config + ) + +def test_processor_config_snapshot_id(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG + ) + + assert config.snapshot_id == _SNAPSHOT_ID + +def test_processor_config_run_name(): + run_name = 'test_run_name' + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + run_name=run_name + ) + + assert config.run_name == run_name + +def test_processor_config_effective_device(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + + assert config.effective_device == GridDevice.from_proto(_DEVICE_SPEC) + +def test_processor_config_calibration(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + + assert config.calibration == cg.Calibration(_METRIC_SNAPSHOT) + +def test_processor_project_id(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + + assert config.project_id == _PROJECT_ID + +def test_processor_processor_id(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + + assert config.processor_id == _PROCESSOR_ID + +def test_processor_config_id(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + + assert config.config_id == _CONFIG_ID - assert processor_config.name == expected_config.name - assert processor_config.effective_device == expected_config.effective_device - assert processor_config.calibration == expected_config.calibration From aee07e62d2aa050ee324b49817a3026c5e4b31de Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 8 Aug 2025 21:27:05 +0000 Subject: [PATCH 11/37] Add `get_config*` methods to the `Engine` class. --- cirq-google/cirq_google/engine/__init__.py | 2 + .../cirq_google/engine/abstract_engine.py | 40 +++++++++++- cirq-google/cirq_google/engine/engine.py | 61 +++++++++++++++++++ cirq-google/cirq_google/engine/engine_test.py | 60 ++++++++++++++++++ .../cirq_google/engine/processor_config.py | 16 +---- .../engine/processor_config_test.py | 22 ------- 6 files changed, 163 insertions(+), 38 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index 16b91102108..def68eb0116 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -20,6 +20,8 @@ from cirq_google.engine.abstract_processor import AbstractProcessor as AbstractProcessor +from cirq_google.engine.abstract_processor_config import AbstractProcessorConfig as AbstractProcessorConfig + from cirq_google.engine.abstract_program import AbstractProgram as AbstractProgram from cirq_google.engine.abstract_local_engine import AbstractLocalEngine as AbstractLocalEngine diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 08fa878f589..b133c4b6ead 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: import cirq from cirq_google.cloud import quantum - from cirq_google.engine import abstract_job, abstract_processor, abstract_program + from cirq_google.engine import abstract_job, abstract_processor, abstract_program, abstract_processor_config VALID_DATE_TYPE = datetime.datetime | datetime.date @@ -134,3 +134,41 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: processor_id: String identifier, or list of string identifiers, determining which processors may be used when sampling. """ + + @abc.abstractmethod + def get_processor_config_by_snapshot_id( + self, + processor_id: str, + snapshot_id: str, + config_id: str + ) -> abstract_processor_config.AbstractProcessorConfig: + """Returns a ProcessorConfig from this project and the given processor id. + + Args: + processor_id: The processor unique identifier. + snapshot_id: The unique identifier for the snapshot. + config_id: The unique identifier for the snapshot. + + Returns: + The ProcessorConfig from this project and processor. + """ + + @abc.abstractmethod + def get_processor_config_by_run_name( + self, + processor_id: str, + config_id: str, + run_name: str = 'current' + ) -> abstract_processor_config.AbstractProcessorConfig: + """Returns a ProcessorConfig from this project and the given processor id. + + If no run_name is provided, the config from the most recent run is returned. + + Args: + processor_id: The processor unique identifier. + run_name: The unique identifier for the automation run. + config_id: The unique identifier for the snapshot. + + Returns: + The ProcessorConfig from this project and processor. + """ diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 1c9f7b21f28..03a0fd1963d 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -43,6 +43,7 @@ engine_job, engine_processor, engine_program, + processor_config, util, ) from cirq_google.serialization import CIRCUIT_SERIALIZER, Serializer @@ -622,6 +623,66 @@ def get_sampler( snapshot_id=snapshot_id, max_concurrent_jobs=max_concurrent_jobs, ) + + async def get_processor_config_by_snapshot_id_async( + self, + processor_id: str, + snapshot_id: str, + config_id: str + ) -> processor_config.ProcessorConfig: + """Returns a ProcessorConfig from this project and the given processor id. + + Args: + processor_id: The processor unique identifier. + snapshot_id: The unique identifier for the snapshot. + config_id: The unique identifier for the snapshot. + + Returns: + The ProcessorConfig from this project and processor. + """ + quantum_config = await self.context.client.get_quantum_processor_config_by_snapshot_id_async( + project_id=self.project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id + ) + return processor_config.ProcessorConfig( + quantum_processor_config=quantum_config + ) + + get_processor_config_by_snapshot_id = duet.sync(get_processor_config_by_snapshot_id_async) + + + async def get_processor_config_by_run_name_async( + self, + processor_id: str, + config_id: str, + run_name: str = 'current' + ) -> processor_config.ProcessorConfig: + """Returns a ProcessorConfig from this project and the given processor id. + + If no run_name is provided, the config from the most recent run is returned. + + Args: + processor_id: The processor unique identifier. + run_name: The unique identifier for the automation run. + config_id: The unique identifier for the snapshot. + + Returns: + The ProcessorConfig from this project and processor. + """ + quantum_config = await self.context.client.get_quantum_processor_config_by_run_name_async( + project_id=self.project_id, + processor_id=processor_id, + run_name=run_name, + config_id=config_id + ) + return processor_config.ProcessorConfig( + quantum_processor_config=quantum_config, + run_name=run_name + ) + + get_processor_config_by_run_name = duet.sync(get_processor_config_by_run_name_async) def get_engine(project_id: str | None = None) -> Engine: diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index c9d94abca73..7e92bf2c957 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -907,3 +907,63 @@ def test_get_engine_device(get_processor): ) with pytest.raises(ValueError): device.validate_operation(cirq.CZ(cirq.GridQubit(1, 1), cirq.GridQubit(2, 2))) + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +def test_get_processor_config_by_snapshot_id(get_quantum_config_async): + project_id = "test_project_id" + processor_id = "test_processor_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) + + get_quantum_config_async.return_value = quantum_confg + + result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id + ) + + get_quantum_config_async.assert_called_with( + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id + ) + assert result.project_id == project_id + assert result.processor_id == processor_id + assert result.snapshot_id == snapshot_id + assert result.config_id == config_id + assert result.run_name == '' + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +def test_get_processor_config_by_run_name(get_quantum_config_async): + project_id = "test_project_id" + processor_id = "test_processor_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + run_name = "test_run_name" + resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) + + get_quantum_config_async.return_value = quantum_confg + + result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( + processor_id=processor_id, + run_name=run_name, + config_id=config_id + ) + + get_quantum_config_async.assert_called_with( + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_id=config_id + ) + assert result.project_id == project_id + assert result.processor_id == processor_id + assert result.snapshot_id == snapshot_id + assert result.run_name == run_name + assert result.config_id == config_id + \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 324d1584e8b..84e589a7eda 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -42,24 +42,10 @@ def __init__(self, ) -> None: self._quantum_processor_config = quantum_processor_config self._run_name = run_name - - device_spec = quantum_processor_config.device_specification - if not device_spec.Is(v2.device_pb2.DeviceSpecification.DESCRIPTOR): - raise ValueError( - f'Invalid device_specification type `{device_spec.type_url}`. ' - f'Expected type.googleapis.com/cirq.google.api.v2.DeviceSpecification' - ) self._device_spec = util.unpack_any( self._quantum_processor_config.device_specification, v2.device_pb2.DeviceSpecification() ) - - metrics = quantum_processor_config.characterization - if not metrics.Is(v2.metrics_pb2.MetricsSnapshot.DESCRIPTOR): - raise ValueError( - f'Invalid characterization type `{metrics.type_url}`. ' - f'Expected type.googleapis.com/cirq.google.api.v2.MetricsSnapshot' - ) self._metric_snapshot = util.unpack_any( self._quantum_processor_config.characterization, v2.metrics_pb2.MetricsSnapshot() @@ -67,7 +53,7 @@ def __init__(self, @property def effective_device(self) -> cirq.Device: - """The GridDevice generated from this configuration's device specification""" + """The GridDevice generated from thisc configuration's device specification""" return cg.GridDevice.from_proto(self._device_spec) @property diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index cbc8d8a00bd..19f5a8aac86 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -68,28 +68,6 @@ characterization=util.pack_any(_METRIC_SNAPSHOT) ) -def test_processor_config_init_fails_with_invalid_device_spec(): - quantum_config = quantum.QuantumProcessorConfig( - name='', - device_specification=any_pb2.Any(), - characterization=util.pack_any(_METRIC_SNAPSHOT) - ) - with pytest.raises(ValueError): - _ = cg.engine.ProcessorConfig( - quantum_processor_config=quantum_config - ) - -def test_processor_config_init_fails_with_invalid_characterization(): - quantum_config = quantum.QuantumProcessorConfig( - name='', - device_specification=util.pack_any(_DEVICE_SPEC), - characterization=any_pb2.Any() - ) - with pytest.raises(ValueError): - _ = cg.engine.ProcessorConfig( - quantum_processor_config=quantum_config - ) - def test_processor_config_snapshot_id(): config = cg.engine.ProcessorConfig( quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG From 9e2fdcde75ac2927e7779bd8266d2c997e2f2548 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 8 Aug 2025 22:46:01 +0000 Subject: [PATCH 12/37] Add missing methods from other abstract engines and processors. --- .../engine/abstract_local_engine.py | 41 ++++++++++++++++++- .../engine/abstract_local_engine_test.py | 6 +++ .../engine/abstract_local_processor_test.py | 8 ++++ .../engine/simulated_local_engine_test.py | 6 +++ .../engine/simulated_local_processor.py | 8 ++++ 5 files changed, 68 insertions(+), 1 deletion(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index d8140390e22..ac0528de145 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -24,6 +24,7 @@ from cirq_google.engine.abstract_job import AbstractJob from cirq_google.engine.abstract_local_processor import AbstractLocalProcessor from cirq_google.engine.abstract_program import AbstractProgram + from cirq_google.engine.abstract_processor_config import AbstractProcessorConfig class AbstractLocalEngine(AbstractEngine): @@ -35,10 +36,21 @@ class AbstractLocalEngine(AbstractEngine): """ - def __init__(self, processors: list[AbstractLocalProcessor]): + def __init__( + self, + processors: list[AbstractLocalProcessor], + configs: list[AbstractProcessorConfig] = [] + ): for processor in processors: processor.set_engine(self) self._processors = {proc.processor_id: proc for proc in processors} + self._snapshot_configs = { + config.snapshot_id:{ config.config_id: config } for config in configs} + self._run_name_configs = { + config.run_name:{ + config.config_id: config + } for config in configs if config.run_name + } def get_program(self, program_id: str) -> AbstractProgram: """Returns an existing AbstractProgram given an identifier. @@ -175,3 +187,30 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: if not isinstance(processor_id, str): raise ValueError(f'Invalid processor {processor_id}') return self._processors[processor_id].get_sampler() + + def get_processor_config_by_snapshot_id( + self, + processor_id: str, + snapshot_id: str, + config_id: str + ) -> AbstractProcessorConfig: + """Returns a ProcessorConfig from this project and the given processor id. + + Args: + processor_id: The processor unique identifier. + snapshot_id: The unique identifier for the snapshot. + config_id: The unique identifier for the snapshot. + + Returns: + The ProcessorConfig from this project and processor. + """ + return self._snapshot_configs[snapshot_id][config_id] + + def get_processor_config_by_run_name( + self, + processor_id: str, + config_id: str, + run_name: str = 'current' + ) -> AbstractProcessorConfig: + return self._run_name_configs[run_name][config_id] + \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/abstract_local_engine_test.py b/cirq-google/cirq_google/engine/abstract_local_engine_test.py index 000915d61ca..9700fd8d40a 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine_test.py @@ -80,6 +80,12 @@ def list_programs( def get_program(self, program_id: str) -> AbstractProgram: return self._programs[program_id] + + def get_config_by_run_name(self, *args, **kwargs): + pass + + def get_config_by_snapshot(self, *args, **kwargs): + pass class NothingEngine(AbstractLocalEngine): diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index 890c435d7ec..4b562d9d6a6 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -71,6 +71,14 @@ def list_programs(self, *args, **kwargs): def get_program(self, *args, **kwargs): pass + def get_config_by_run_name( + self, config_id: str, run_name: str = "current" + ): + pass + + def get_config_by_snapshot(self, config_id: str, snapshot_id: str): + pass + def test_datetime(): recovery_time = datetime.datetime.now() diff --git a/cirq-google/cirq_google/engine/simulated_local_engine_test.py b/cirq-google/cirq_google/engine/simulated_local_engine_test.py index e4e78dad22a..715b80b469c 100644 --- a/cirq-google/cirq_google/engine/simulated_local_engine_test.py +++ b/cirq-google/cirq_google/engine/simulated_local_engine_test.py @@ -71,6 +71,12 @@ def get_sampler(self, *args, **kwargs): def supported_languages(self, *args, **kwargs): pass + def get_config_by_run_name(self, *args, **kwargs): + pass + + def get_config_by_snapshot(self, *args, **kwargs): + pass + def list_programs( self, created_before: datetime.datetime | datetime.date | None = None, diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 8207d3292d1..731a9e30d39 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -235,3 +235,11 @@ async def run_sweep_async( ) self._programs[program_id].add_job(job_id, job) return job + + def get_config_by_run_name( + self, config_id: str, run_name: str = "current" + ): + pass + + def get_config_by_snapshot(self, config_id: str, snapshot_id: str): + pass From cc4b43e564e69f06332d2a0eaec8b4185abe8dd3 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 16:43:56 +0000 Subject: [PATCH 13/37] Add test for __repr__; Remove config logic from LocalAbstractEnginer. --- .../engine/abstract_local_engine.py | 40 +------------------ .../engine/processor_config_test.py | 32 +++++++++++++++ 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index ac0528de145..7e3eac43f69 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -24,7 +24,6 @@ from cirq_google.engine.abstract_job import AbstractJob from cirq_google.engine.abstract_local_processor import AbstractLocalProcessor from cirq_google.engine.abstract_program import AbstractProgram - from cirq_google.engine.abstract_processor_config import AbstractProcessorConfig class AbstractLocalEngine(AbstractEngine): @@ -38,20 +37,11 @@ class AbstractLocalEngine(AbstractEngine): def __init__( self, - processors: list[AbstractLocalProcessor], - configs: list[AbstractProcessorConfig] = [] + processors: list[AbstractLocalProcessor] ): for processor in processors: processor.set_engine(self) self._processors = {proc.processor_id: proc for proc in processors} - self._snapshot_configs = { - config.snapshot_id:{ config.config_id: config } for config in configs} - self._run_name_configs = { - config.run_name:{ - config.config_id: config - } for config in configs if config.run_name - } - def get_program(self, program_id: str) -> AbstractProgram: """Returns an existing AbstractProgram given an identifier. @@ -186,31 +176,5 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: """ if not isinstance(processor_id, str): raise ValueError(f'Invalid processor {processor_id}') - return self._processors[processor_id].get_sampler() - - def get_processor_config_by_snapshot_id( - self, - processor_id: str, - snapshot_id: str, - config_id: str - ) -> AbstractProcessorConfig: - """Returns a ProcessorConfig from this project and the given processor id. - - Args: - processor_id: The processor unique identifier. - snapshot_id: The unique identifier for the snapshot. - config_id: The unique identifier for the snapshot. - - Returns: - The ProcessorConfig from this project and processor. - """ - return self._snapshot_configs[snapshot_id][config_id] - - def get_processor_config_by_run_name( - self, - processor_id: str, - config_id: str, - run_name: str = 'current' - ) -> AbstractProcessorConfig: - return self._run_name_configs[run_name][config_id] + return self._processors[processor_id].get_sampler() \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 19f5a8aac86..3193eac0316 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -119,3 +119,35 @@ def test_processor_config_id(): assert config.config_id == _CONFIG_ID +def test_processor_config_repr(): + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + ) + expected_repr = ( + f'cirq_google.ProcessorConfig' + f'(project_id={_PROJECT_ID}, ' + f'processor_id={_PROCESSOR_ID}, ' + f'snapshot_id={_SNAPSHOT_ID}, ' + f'run_name={''} ' + f'config_id={_CONFIG_ID}' + ) + + assert repr(config) == expected_repr + +def test_processor_config_repr_with_run_name(): + run_name = 'test_run_name' + config = cg.engine.ProcessorConfig( + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, + run_name=run_name + ) + expected_repr = ( + f'cirq_google.ProcessorConfig' + f'(project_id={_PROJECT_ID}, ' + f'processor_id={_PROCESSOR_ID}, ' + f'snapshot_id={_SNAPSHOT_ID}, ' + f'run_name={run_name} ' + f'config_id={_CONFIG_ID}' + ) + + assert repr(config) == expected_repr + From 6835a615b84711e04cda4f98f68ddc29ce8819ca Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 17:07:55 +0000 Subject: [PATCH 14/37] Update imports. --- .../cirq_google/engine/abstract_engine.py | 2 +- .../engine/abstract_local_engine.py | 20 ++++++++++++++++++- .../engine/abstract_processor_config.py | 7 +++---- .../cirq_google/engine/engine_processor.py | 8 ++++---- .../engine/engine_processor_test.py | 3 +-- .../cirq_google/engine/processor_config.py | 4 ++-- .../engine/processor_config_test.py | 3 --- 7 files changed, 30 insertions(+), 17 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index b133c4b6ead..e1c829f4b6d 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: import cirq from cirq_google.cloud import quantum - from cirq_google.engine import abstract_job, abstract_processor, abstract_program, abstract_processor_config + from cirq_google.engine import abstract_job, abstract_processor, abstract_processor_config, abstract_program VALID_DATE_TYPE = datetime.datetime | datetime.date diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index 7e3eac43f69..b9e9185ff62 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -176,5 +176,23 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: """ if not isinstance(processor_id, str): raise ValueError(f'Invalid processor {processor_id}') - return self._processors[processor_id].get_sampler() + return self._processors[processor_id].get_sampler() + + def get_processor_config_by_snapshot_id( + self, + processor_id: str, + snapshot_id: str, + config_id: str + ): + # TODO: Implement later as needed. + pass + + def get_processor_config_by_run_name( + self, + processor_id: str, + config_id: str, + run_name: str = 'current' + ): + # TODO: Implement later as needed. + pass \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 74d3155d005..8507add87aa 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -1,13 +1,12 @@ from __future__ import annotations import abc -import datetime -from typing import TYPE_CHECKING - import cirq - import cirq_google as cg +from typing import TYPE_CHECKING + + class AbstractProcessorConfig(abc.ABC): """Interface for a QuantumProcessorConfig. diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index ebf23ef4a67..8ed0ee64f65 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -18,19 +18,19 @@ from typing import Any, TYPE_CHECKING from cirq import _compat +import cirq_google as cg from cirq_google.api import v2 from cirq_google.devices import grid_device -from cirq_google.engine import abstract_processor, calibration, processor_sampler, util, processor_config +from cirq_google.engine import abstract_processor, calibration, processor_config, processor_sampler, util if TYPE_CHECKING: - from google.protobuf import any_pb2 - import cirq - import cirq_google as cg import cirq_google.cloud.quantum as quantum import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.engine as engine_base + from google.protobuf import any_pb2 + def _date_to_timestamp(union_time: datetime.datetime | datetime.date | int | None) -> int | None: if isinstance(union_time, int): diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 46c03a9ef7a..f6c37ad3b98 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -28,9 +28,8 @@ import cirq import cirq_google as cg from cirq_google.api import v2 -from cirq_google.devices import grid_device from cirq_google.cloud import quantum -from cirq_google.engine import engine_client, util, calibration, ProcessorConfig +from cirq_google.engine import engine_client, util, ProcessorConfig from cirq_google.engine.engine import EngineContext diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 84e589a7eda..68b2e90ce97 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -16,14 +16,14 @@ from typing import TYPE_CHECKING + import cirq import cirq_google as cg from cirq_google.api import v2 from cirq_google.cloud.quantum_v1alpha1.types import quantum -from cirq_google.engine import abstract_processor_config +from cirq_google.engine import abstract_processor_config, util -from cirq_google.engine import util class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): """Representation of a quantum processor configuration diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 3193eac0316..93a0335ef5c 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -18,14 +18,11 @@ import cirq_google as cg -import pytest - from cirq_google.api import v2 from cirq_google.cloud import quantum from cirq_google.devices import GridDevice from cirq_google.engine import util -from google.protobuf import any_pb2 _METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( timestamp_ms=1562544000021, From e96871c4209672980e6fbf5c8f5e0fd8769eef37 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 17:43:03 +0000 Subject: [PATCH 15/37] Fix more formatting errors. --- .../cirq_google/engine/abstract_engine.py | 3 +- .../engine/abstract_processor_config.py | 5 +-- cirq-google/cirq_google/engine/engine.py | 3 +- .../cirq_google/engine/engine_client.py | 30 ++++++++++++---- .../cirq_google/engine/engine_client_test.py | 36 +++++++++++++++---- .../cirq_google/engine/engine_processor.py | 3 +- .../engine/engine_processor_test.py | 20 +++++++++-- cirq-google/cirq_google/engine/engine_test.py | 14 ++++++-- .../cirq_google/engine/processor_config.py | 6 ++-- .../engine/processor_config_test.py | 2 +- 10 files changed, 97 insertions(+), 25 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index e1c829f4b6d..394399f54af 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -26,7 +26,8 @@ if TYPE_CHECKING: import cirq from cirq_google.cloud import quantum - from cirq_google.engine import abstract_job, abstract_processor, abstract_processor_config, abstract_program + from cirq_google.engine import abstract_job, abstract_processor, abstract_processor_config + from cirq_google.engine import abstract_program VALID_DATE_TYPE = datetime.datetime | datetime.date diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 8507add87aa..1b3f726bbc0 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -1,11 +1,12 @@ from __future__ import annotations import abc -import cirq -import cirq_google as cg from typing import TYPE_CHECKING +if TYPE_CHECKING: + import cirq + import cirq_google as cg class AbstractProcessorConfig(abc.ABC): """Interface for a QuantumProcessorConfig. diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 03a0fd1963d..eec39175e78 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -640,7 +640,8 @@ async def get_processor_config_by_snapshot_id_async( Returns: The ProcessorConfig from this project and processor. """ - quantum_config = await self.context.client.get_quantum_processor_config_by_snapshot_id_async( + client = self.context.client + quantum_config = await client.get_quantum_processor_config_by_snapshot_id_async( project_id=self.project_id, processor_id=processor_id, snapshot_id=snapshot_id, diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index cf698b319db..4ea7db43adf 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1187,7 +1187,10 @@ async def _get_quantum_processor_config( """Runs get_quantum_processor_config with the given resource name.""" try: request = quantum.GetQuantumProcessorConfigRequest(name=name) - return await self._send_request_async(self.grpc_client.get_quantum_processor_config, request) + return await self._send_request_async( + self.grpc_client.get_quantum_processor_config, + request + ) except EngineException as err: if isinstance(err.__cause__, NotFound): return None @@ -1212,10 +1215,15 @@ async def get_quantum_processor_config_by_snapshot_id_async(self, EngineException: If the request to get the config fails. """ name = _quantum_processor_name_with_snapshot_id( - project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id) + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id + ) return await self._get_quantum_processor_config(name) - get_quantum_processor_config_by_snapshot_id = duet.sync(get_quantum_processor_config_by_snapshot_id_async) + get_quantum_processor_config_by_snapshot_id = duet.sync( + get_quantum_processor_config_by_snapshot_id_async) async def get_quantum_processor_config_by_run_name_async(self, project_id: str, processor_id: str, run_name: str, config_id: str, @@ -1239,7 +1247,8 @@ async def get_quantum_processor_config_by_run_name_async(self, ) return await self._get_quantum_processor_config(name) - get_quantum_processor_config_by_run_name = duet.sync(get_quantum_processor_config_by_run_name_async) + get_quantum_processor_config_by_run_name = duet.sync( + get_quantum_processor_config_by_run_name_async) def _project_name(project_id: str) -> str: return f'projects/{project_id}' @@ -1292,13 +1301,22 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: def _quantum_processor_name_with_snapshot_id( project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> str: - return f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + return ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) def _quantum_processor_name_with_run_name( project_id: str, processor_id: str, run_name: str, config_id: str ) -> str: - return f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + return ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/{run_name}/' + f'configs/{config_id}') def _date_or_time_to_filter_expr(param_name: str, param: datetime.datetime | datetime.date): diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index c1f1d78bbff..f7caa2daf5e 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1752,14 +1752,22 @@ def test_get_quantum_processor_config_by_snapshot_id( processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) grpc_client.get_quantum_processor_config.return_value = expected_result actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( - project_id=project_id, processor_id=processor_id, config_id=config_id, snapshot_id=snapshot_id + project_id=project_id, + processor_id=processor_id, + config_id=config_id, + snapshot_id=snapshot_id ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) @@ -1767,12 +1775,18 @@ def test_get_quantum_processor_config_by_snapshot_id( assert actual_result == expected_result @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_snapshot_id_not_found( + client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') @@ -1793,7 +1807,12 @@ def test_get_quantum_processor_config_by_run_name( processor_id = "test_processor_id" run_name = "test_run_name" config_id = "test_config_id" - resource_name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/{run_name}/' + f'configs/{config_id}' + ) grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) @@ -1813,7 +1832,12 @@ def test_get_quantum_processor_config_by_run_name_not_found(client_constructor, processor_id = "test_processor_id" run_name = "test_run_name" config_id = "test_config_id" - resource_name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/{run_name}/' + f'configs/{config_id}' + ) grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 8ed0ee64f65..becc35bd705 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -21,7 +21,8 @@ import cirq_google as cg from cirq_google.api import v2 from cirq_google.devices import grid_device -from cirq_google.engine import abstract_processor, calibration, processor_config, processor_sampler, util +from cirq_google.engine import abstract_processor, calibration, processor_config, processor_sampler +from cirq_google.engine import util if TYPE_CHECKING: import cirq diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index f6c37ad3b98..3296411be67 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1024,7 +1024,12 @@ def test_get_config_by_run_name(get_quantum_config): processor_id = "test_proc_id" run_name = "test_run_name" config_id = "test_config_id" - name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/{run_name}/configs/{config_id}' + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/{run_name}/' + f'configs/{config_id}' + ) device_spec = v2.device_pb2.DeviceSpecification( valid_qubits=["0_0", "1_1", "2_2"], @@ -1074,7 +1079,11 @@ def test_get_current_config_by_run_name(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" config_id = "test_config_id" - name = f'projects/{project_id}/processors/{processor_id}/configAutomationRuns/current/configs/{config_id}' + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/current/configs/{config_id}' + ) device_spec = v2.device_pb2.DeviceSpecification( valid_qubits=["0_0", "1_1", "2_2"], @@ -1113,7 +1122,12 @@ def test_get_config_by_snapshot_id(get_quantum_config): processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) device_spec = v2.device_pb2.DeviceSpecification( valid_qubits=["0_0", "1_1", "2_2"], diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 7e92bf2c957..a5ea7b6df0f 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -914,7 +914,12 @@ def test_get_processor_config_by_snapshot_id(get_quantum_config_async): processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg @@ -944,7 +949,12 @@ def test_get_processor_config_by_run_name(get_quantum_config_async): snapshot_id = "test_snapshot_id" config_id = "test_config_id" run_name = "test_run_name" - resource_name = f'projects/{project_id}/processors/{processor_id}/configSnapshots/{snapshot_id}/configs/{config_id}' + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 68b2e90ce97..517473cc809 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -17,13 +17,15 @@ from typing import TYPE_CHECKING -import cirq import cirq_google as cg from cirq_google.api import v2 -from cirq_google.cloud.quantum_v1alpha1.types import quantum from cirq_google.engine import abstract_processor_config, util +if TYPE_CHECKING: + import cirq + from cirq_google.cloud.quantum_v1alpha1.types import quantum + class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): """Representation of a quantum processor configuration diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 93a0335ef5c..b6e8c229450 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -125,7 +125,7 @@ def test_processor_config_repr(): f'(project_id={_PROJECT_ID}, ' f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' - f'run_name={''} ' + f'run_name={""} ' f'config_id={_CONFIG_ID}' ) From e2429c3564e924f2c67451d516ccbca4fca9d347 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 20:02:01 +0000 Subject: [PATCH 16/37] Update test and linting errors. --- .../cirq_google/engine/abstract_processor.py | 4 +- .../cirq_google/engine/engine_client_test.py | 38 ++++++++++- .../cirq_google/engine/engine_processor.py | 25 ++++--- .../engine/engine_processor_test.py | 66 ++++++++++++++++++- 4 files changed, 117 insertions(+), 16 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index fe0a004e2e4..41d6f75dcb5 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -382,7 +382,7 @@ def get_schedule( @abc.abstractmethod def get_config_by_run_name( self, config_id: str, run_name: str = "current" - ) -> ProcessorConfig: + ) -> ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. If no run name is provided, the config from the most recent run @@ -400,7 +400,7 @@ def get_config_by_run_name( @abc.abstractmethod def get_config_by_snapshot( self, config_id: str, snapshot_id: str - ) -> ProcessorConfig: + ) -> ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. Args: diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index f7caa2daf5e..b2ac29268ce 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1792,13 +1792,30 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found( grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( - project_id=project_id, processor_id=processor_id, config_id=config_id, snapshot_id=snapshot_id + project_id=project_id, + processor_id=processor_id, + config_id=config_id, + snapshot_id=snapshot_id ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) assert actual_result is None +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_snapshot_id_exception( + client_constructor, default_engine_client): + grpc_client = _setup_client_mock(client_constructor) + grpc_client.get_quantum_processor_config.side_effect = exceptions.BadRequest('invalid_reueust') + + with pytest.raises(EngineException, match='invalid_reueust'): + _ = default_engine_client.get_quantum_processor_config_by_snapshot_id( + project_id="test_project_id", + processor_id="test_processor_id", + config_id="test_config_id", + snapshot_id="test_snapshot_id" + ) + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_run_name( client_constructor, default_engine_client): @@ -1827,7 +1844,9 @@ def test_get_quantum_processor_config_by_run_name( assert actual_result == expected_result @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_run_name_not_found(client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_run_name_not_found( + client_constructor, default_engine_client +): project_id = "test_project_id" processor_id = "test_processor_id" run_name = "test_run_name" @@ -1848,3 +1867,18 @@ def test_get_quantum_processor_config_by_run_name_not_found(client_constructor, quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) assert actual_result is None + +@mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) +def test_get_quantum_processor_config_by_run_name_exception( + client_constructor, default_engine_client +): + grpc_client = _setup_client_mock(client_constructor) + grpc_client.get_quantum_processor_config.side_effect = exceptions.BadRequest('invalid_reueust') + + with pytest.raises(EngineException, match='invalid_reueust'): + _ = default_engine_client.get_quantum_processor_config_by_run_name( + project_id="test_project_id", + processor_id="test_processor_id", + config_id="test_config_id", + run_name="test_run_name" + ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index becc35bd705..088280e948c 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -18,7 +18,6 @@ from typing import Any, TYPE_CHECKING from cirq import _compat -import cirq_google as cg from cirq_google.api import v2 from cirq_google.devices import grid_device from cirq_google.engine import abstract_processor, calibration, processor_config, processor_sampler @@ -26,6 +25,7 @@ if TYPE_CHECKING: import cirq + import cirq_google as cg import cirq_google.cloud.quantum as quantum import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.engine as engine_base @@ -500,7 +500,7 @@ def get_schedule( def get_config_by_run_name( self, config_id: str, run_name: str = "current" - ) -> processor_config.ProcessorConfig: + ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. If no run name is provided, the config from the most recent run @@ -517,15 +517,17 @@ def get_config_by_run_name( response = self.context.client.get_quantum_processor_config_by_run_name( project_id=self.project_id, processor_id=self.processor_id, run_name=run_name, config_id=config_id - ) - return processor_config.ProcessorConfig( - quantum_processor_config=response, - run_name=run_name ) + if response: + return processor_config.ProcessorConfig( + quantum_processor_config=response, + run_name=run_name + ) + return None def get_config_by_snapshot( self, config_id: str, snapshot_id: str - ) -> processor_config.ProcessorConfig: + ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. Args: @@ -541,10 +543,13 @@ def get_config_by_snapshot( response = self.context.client.get_quantum_processor_config_by_snapshot_id( project_id=self.project_id, processor_id=self.processor_id, snapshot_id=snapshot_id, config_id=config_id - ) - return processor_config.ProcessorConfig( - quantum_processor_config=response ) + if response: + return processor_config.ProcessorConfig( + quantum_processor_config=response + ) + return None + def __str__(self): return ( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 3296411be67..3fced8de811 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1109,8 +1109,9 @@ def test_get_current_config_by_run_name(get_quantum_config): context=EngineContext() ) - _ = processor.get_config_by_run_name(config_id=config_id) + result = processor.get_config_by_run_name(config_id=config_id) + assert not result.snapshot_id get_quantum_config.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name="current", config_id=config_id @@ -1170,4 +1171,65 @@ def test_get_config_by_snapshot_id(get_quantum_config): assert actual_config.run_name == '' assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device - assert actual_config.calibration == expected_config.calibration \ No newline at end of file + assert actual_config.calibration == expected_config.calibration + + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +def test_get_config_by_snapshot_id_not_found(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) + + get_quantum_config.return_value = None + + processor = cg.EngineProcessor( + project_id=project_id, + processor_id=processor_id, + context=EngineContext() + ) + + result = processor.get_config_by_snapshot( + config_id=config_id, snapshot_id=snapshot_id + ) + + get_quantum_config.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + snapshot_id=snapshot_id, config_id=config_id + ) + + assert result == None + +@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +def test_get_current_config_by_run_name_not_found(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + config_id = "test_config_id" + run_name = 'test_run_name' + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configAutomationRuns/{run_name}/configs/{config_id}' + ) + + get_quantum_config.return_value = None + + processor = cg.EngineProcessor( + project_id=project_id, + processor_id=processor_id, + context=EngineContext() + ) + + result = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) + + get_quantum_config.assert_called_once_with( + project_id=project_id, processor_id=processor_id, + run_name=run_name, config_id=config_id + ) + assert result == None \ No newline at end of file From 093cd1e5a2b7b32ac4ea3eaec0863d7d1ca16596 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 20:54:13 +0000 Subject: [PATCH 17/37] More formatting fixes. --- cirq-google/cirq_google/engine/__init__.py | 5 +- .../cirq_google/engine/abstract_engine.py | 36 ++-- .../engine/abstract_local_engine.py | 15 +- .../engine/abstract_local_processor_test.py | 4 +- .../cirq_google/engine/abstract_processor.py | 9 +- .../engine/abstract_processor_config.py | 10 +- cirq-google/cirq_google/engine/engine.py | 35 ++-- .../cirq_google/engine/engine_client.py | 24 +-- .../cirq_google/engine/engine_client_test.py | 16 +- .../cirq_google/engine/engine_processor.py | 26 +-- .../engine/engine_processor_test.py | 160 ++++++++---------- cirq-google/cirq_google/engine/engine_test.py | 18 +- .../cirq_google/engine/processor_config.py | 25 +-- .../engine/processor_config_test.py | 98 +++++------ .../engine/simulated_local_processor.py | 6 +- 15 files changed, 227 insertions(+), 260 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index def68eb0116..ef24af4a5e8 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -98,7 +98,4 @@ from cirq_google.engine.processor_sampler import ProcessorSampler as ProcessorSampler -from cirq_google.engine.processor_config import ( - ProcessorConfig as ProcessorConfig, -) - +from cirq_google.engine.processor_config import ProcessorConfig as ProcessorConfig diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 394399f54af..554529d73e3 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -26,8 +26,12 @@ if TYPE_CHECKING: import cirq from cirq_google.cloud import quantum - from cirq_google.engine import abstract_job, abstract_processor, abstract_processor_config - from cirq_google.engine import abstract_program + from cirq_google.engine import ( + abstract_job, + abstract_processor, + abstract_processor_config, + abstract_program, + ) VALID_DATE_TYPE = datetime.datetime | datetime.date @@ -138,11 +142,8 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: @abc.abstractmethod def get_processor_config_by_snapshot_id( - self, - processor_id: str, - snapshot_id: str, - config_id: str - ) -> abstract_processor_config.AbstractProcessorConfig: + self, processor_id: str, snapshot_id: str, config_id: str + ) -> abstract_processor_config.AbstractProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. Args: @@ -156,20 +157,17 @@ def get_processor_config_by_snapshot_id( @abc.abstractmethod def get_processor_config_by_run_name( - self, - processor_id: str, - config_id: str, - run_name: str = 'current' - ) -> abstract_processor_config.AbstractProcessorConfig: + self, processor_id: str, config_id: str, run_name: str = 'current' + ) -> abstract_processor_config.AbstractProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. - If no run_name is provided, the config from the most recent run is returned. + If no run_name is provided, the config from the most recent run is returned. - Args: - processor_id: The processor unique identifier. - run_name: The unique identifier for the automation run. - config_id: The unique identifier for the snapshot. + Args: + processor_id: The processor unique identifier. + run_name: The unique identifier for the automation run. + config_id: The unique identifier for the snapshot. - Returns: - The ProcessorConfig from this project and processor. + Returns: + The ProcessorConfig from this project and processor. """ diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index b9e9185ff62..608b10d754f 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -35,10 +35,7 @@ class AbstractLocalEngine(AbstractEngine): """ - def __init__( - self, - processors: list[AbstractLocalProcessor] - ): + def __init__(self, processors: list[AbstractLocalProcessor]): for processor in processors: processor.set_engine(self) self._processors = {proc.processor_id: proc for proc in processors} @@ -179,19 +176,13 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: return self._processors[processor_id].get_sampler() def get_processor_config_by_snapshot_id( - self, - processor_id: str, - snapshot_id: str, - config_id: str + self, processor_id: str, snapshot_id: str, config_id: str ): # TODO: Implement later as needed. pass def get_processor_config_by_run_name( - self, - processor_id: str, - config_id: str, - run_name: str = 'current' + self, processor_id: str, config_id: str, run_name: str = 'current' ): # TODO: Implement later as needed. pass diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index 4b562d9d6a6..675bab09685 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -71,9 +71,7 @@ def list_programs(self, *args, **kwargs): def get_program(self, *args, **kwargs): pass - def get_config_by_run_name( - self, config_id: str, run_name: str = "current" - ): + def get_config_by_run_name(self, config_id: str, run_name: str = "current"): pass def get_config_by_snapshot(self, config_id: str, snapshot_id: str): diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 41d6f75dcb5..21d8fc533f5 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -35,7 +35,7 @@ import cirq_google.engine.abstract_engine as abstract_engine import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.calibration as calibration - from cirq_google.engine import ProcessorConfig + from cirq_google.engine import abstract_processor_config class AbstractProcessor(abc.ABC): @@ -380,9 +380,8 @@ def get_schedule( """ @abc.abstractmethod - def get_config_by_run_name( - self, config_id: str, run_name: str = "current" - ) -> ProcessorConfig | None: + def get_config_by_run_name(self, config_id: str, run_name: str = "current" + ) -> abstract_processor_config.AbstractProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. If no run name is provided, the config from the most recent run @@ -400,7 +399,7 @@ def get_config_by_run_name( @abc.abstractmethod def get_config_by_snapshot( self, config_id: str, snapshot_id: str - ) -> ProcessorConfig | None: + ) -> abstract_processor_config.AbstractProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. Args: diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 1b3f726bbc0..8edac5ee237 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -20,32 +20,38 @@ class AbstractProcessorConfig(abc.ABC): def effective_device(self) -> cirq.Device: """The Device generated from thi configuration's device specification""" + @property @abc.abstractmethod def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" + @property @abc.abstractmethod def snapshot_id(self) -> str: """The snapshot that contains this processor config""" + @property @abc.abstractmethod def run_name(self) -> str: """The run that generated this config if avaiable.""" + @property @abc.abstractmethod def project_id(self) -> str: """The if of the project that contains this config.""" - + + @property @abc.abstractmethod def processor_id(self) -> str: """The processor id for this config.""" + @property @abc.abstractmethod def config_id(self) -> str: - """The unique identifier for this config.""" \ No newline at end of file + """The unique identifier for this config.""" diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index eec39175e78..b711009f711 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -625,11 +625,8 @@ def get_sampler( ) async def get_processor_config_by_snapshot_id_async( - self, - processor_id: str, - snapshot_id: str, - config_id: str - ) -> processor_config.ProcessorConfig: + self, processor_id: str, snapshot_id: str, config_id: str + ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. Args: @@ -647,30 +644,25 @@ async def get_processor_config_by_snapshot_id_async( snapshot_id=snapshot_id, config_id=config_id ) - return processor_config.ProcessorConfig( - quantum_processor_config=quantum_config - ) + return processor_config.ProcessorConfig(quantum_processor_config=quantum_config) get_processor_config_by_snapshot_id = duet.sync(get_processor_config_by_snapshot_id_async) async def get_processor_config_by_run_name_async( - self, - processor_id: str, - config_id: str, - run_name: str = 'current' - ) -> processor_config.ProcessorConfig: + self, processor_id: str, config_id: str, run_name: str = 'current' + ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. - If no run_name is provided, the config from the most recent run is returned. + If no run_name is provided, the config from the most recent run is returned. - Args: - processor_id: The processor unique identifier. - run_name: The unique identifier for the automation run. - config_id: The unique identifier for the snapshot. + Args: + processor_id: The processor unique identifier. + run_name: The unique identifier for the automation run. + config_id: The unique identifier for the snapshot. - Returns: - The ProcessorConfig from this project and processor. + Returns: + The ProcessorConfig from this project and processor. """ quantum_config = await self.context.client.get_quantum_processor_config_by_run_name_async( project_id=self.project_id, @@ -679,8 +671,7 @@ async def get_processor_config_by_run_name_async( config_id=config_id ) return processor_config.ProcessorConfig( - quantum_processor_config=quantum_config, - run_name=run_name + quantum_processor_config=quantum_config, run_name=run_name ) get_processor_config_by_run_name = duet.sync(get_processor_config_by_run_name_async) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 4ea7db43adf..13740f9baa7 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1188,8 +1188,7 @@ async def _get_quantum_processor_config( try: request = quantum.GetQuantumProcessorConfigRequest(name=name) return await self._send_request_async( - self.grpc_client.get_quantum_processor_config, - request + self.grpc_client.get_quantum_processor_config, request ) except EngineException as err: if isinstance(err.__cause__, NotFound): @@ -1198,7 +1197,7 @@ async def _get_quantum_processor_config( async def get_quantum_processor_config_by_snapshot_id_async(self, - project_id: str, processor_id: str, snapshot_id: str, config_id: str, + project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1215,18 +1214,19 @@ async def get_quantum_processor_config_by_snapshot_id_async(self, EngineException: If the request to get the config fails. """ name = _quantum_processor_name_with_snapshot_id( - project_id=project_id, - processor_id=processor_id, - snapshot_id=snapshot_id, - config_id=config_id + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id, ) return await self._get_quantum_processor_config(name) get_quantum_processor_config_by_snapshot_id = duet.sync( - get_quantum_processor_config_by_snapshot_id_async) + get_quantum_processor_config_by_snapshot_id_async + ) async def get_quantum_processor_config_by_run_name_async(self, - project_id: str, processor_id: str, run_name: str, config_id: str, + project_id: str, processor_id: str, run_name: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given run_name. @@ -1248,7 +1248,8 @@ async def get_quantum_processor_config_by_run_name_async(self, return await self._get_quantum_processor_config(name) get_quantum_processor_config_by_run_name = duet.sync( - get_quantum_processor_config_by_run_name_async) + get_quantum_processor_config_by_run_name_async + ) def _project_name(project_id: str) -> str: return f'projects/{project_id}' @@ -1316,7 +1317,8 @@ def _quantum_processor_name_with_run_name( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_id}') + f'configs/{config_id}' + ) def _date_or_time_to_filter_expr(param_name: str, param: datetime.datetime | datetime.date): diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index b2ac29268ce..2734457e52c 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1744,9 +1744,9 @@ def test_list_time_slots(client_constructor, default_engine_client): assert default_engine_client.list_time_slots('proj', 'processor0') == results + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id( - client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_snapshot_id(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" @@ -1759,6 +1759,7 @@ def test_get_quantum_processor_config_by_snapshot_id( f'configs/{config_id}' ) + grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) grpc_client.get_quantum_processor_config.return_value = expected_result @@ -1767,16 +1768,16 @@ def test_get_quantum_processor_config_by_snapshot_id( project_id=project_id, processor_id=processor_id, config_id=config_id, - snapshot_id=snapshot_id + snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) assert actual_result == expected_result + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id_not_found( - client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" @@ -1802,6 +1803,7 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found( ) assert actual_result is None + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_snapshot_id_exception( client_constructor, default_engine_client): @@ -1813,7 +1815,7 @@ def test_get_quantum_processor_config_by_snapshot_id_exception( project_id="test_project_id", processor_id="test_processor_id", config_id="test_config_id", - snapshot_id="test_snapshot_id" + snapshot_id="test_snapshot_id", ) @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) @@ -1880,5 +1882,5 @@ def test_get_quantum_processor_config_by_run_name_exception( project_id="test_project_id", processor_id="test_processor_id", config_id="test_config_id", - run_name="test_run_name" + run_name="test_run_name", ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 088280e948c..0063627afe0 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -20,18 +20,23 @@ from cirq import _compat from cirq_google.api import v2 from cirq_google.devices import grid_device -from cirq_google.engine import abstract_processor, calibration, processor_config, processor_sampler -from cirq_google.engine import util +from cirq_google.engine import ( + abstract_processor, + calibration, + processor_config, + processor_sampler, + util, +) if TYPE_CHECKING: + from google.protobuf import any_pb2 + import cirq import cirq_google as cg import cirq_google.cloud.quantum as quantum import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.engine as engine_base - from google.protobuf import any_pb2 - def _date_to_timestamp(union_time: datetime.datetime | datetime.date | int | None) -> int | None: if isinstance(union_time, int): @@ -520,8 +525,7 @@ def get_config_by_run_name( ) if response: return processor_config.ProcessorConfig( - quantum_processor_config=response, - run_name=run_name + quantum_processor_config=response, run_name=run_name ) return None @@ -541,13 +545,13 @@ def get_config_by_snapshot( EngineException: If the request to get the config fails. """ response = self.context.client.get_quantum_processor_config_by_snapshot_id( - project_id=self.project_id, processor_id=self.processor_id, - snapshot_id=snapshot_id, config_id=config_id + project_id=self.project_id, + processor_id=self.processor_id, + snapshot_id=snapshot_id, + config_id=config_id ) if response: - return processor_config.ProcessorConfig( - quantum_processor_config=response - ) + return processor_config.ProcessorConfig(quantum_processor_config=response) return None diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 3fced8de811..b25e6818e65 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -29,7 +29,7 @@ import cirq_google as cg from cirq_google.api import v2 from cirq_google.cloud import quantum -from cirq_google.engine import engine_client, util, ProcessorConfig +from cirq_google.engine import engine_client, ProcessorConfig, util from cirq_google.engine.engine import EngineContext @@ -182,20 +182,20 @@ def _to_timestamp(json_string): _METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( - timestamp_ms=1562544000021, - metrics=[ - v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '0_1'], - values=[v2.metrics_pb2.Value(double_val=0.9999)], - ), - v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '1_0'], - values=[v2.metrics_pb2.Value(double_val=0.9998)], - ), - ], - ) + timestamp_ms=1562544000021, + metrics=[ + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '0_1'], + values=[v2.metrics_pb2.Value(double_val=0.9999)], + ), + v2.metrics_pb2.Metric( + name='xeb', + targets=['0_0', '1_0'], + values=[v2.metrics_pb2.Value(double_val=0.9998)], + ), + ], +) class FakeEngineContext(EngineContext): @@ -1018,7 +1018,9 @@ def test_str(): processor = cg.EngineProcessor('a', 'p', EngineContext()) assert str(processor) == 'EngineProcessor(project_id=\'a\', processor_id=\'p\')' -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' +) def test_get_config_by_run_name(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" @@ -1032,36 +1034,27 @@ def test_get_config_by_run_name(get_quantum_config): ) device_spec = v2.device_pb2.DeviceSpecification( - valid_qubits=["0_0", "1_1", "2_2"], - valid_targets=[ - v2.device_pb2.TargetSet( - name="2_quibit_targets", - target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target( - ids=["0_0", "1_1"] - )] + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] ) ], ) quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(device_spec), - characterization=util.pack_any(_METRIC_SNAPSHOT) + characterization=util.pack_any(_METRIC_SNAPSHOT), ) get_quantum_config.return_value = quantum_config - expected_config = ProcessorConfig( - quantum_processor_config=quantum_config, - run_name=run_name - ) + expected_config = ProcessorConfig(quantum_processor_config=quantum_config, run_name=run_name) processor = cg.EngineProcessor( - project_id=project_id, - processor_id=processor_id, - context=EngineContext() + project_id=project_id, processor_id=processor_id, context=EngineContext() ) - actual_config = processor.get_config_by_run_name( - config_id=config_id, run_name=run_name - ) + actual_config = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) get_quantum_config.assert_called_once_with( project_id=project_id, processor_id=processor_id, @@ -1074,7 +1067,9 @@ def test_get_config_by_run_name(get_quantum_config): assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' +) def test_get_current_config_by_run_name(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" @@ -1086,38 +1081,35 @@ def test_get_current_config_by_run_name(get_quantum_config): ) device_spec = v2.device_pb2.DeviceSpecification( - valid_qubits=["0_0", "1_1", "2_2"], - valid_targets=[ - v2.device_pb2.TargetSet( - name="2_quibit_targets", - target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target( - ids=["0_0", "1_1"] - )] + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] ) ], ) quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(device_spec), - characterization=util.pack_any(_METRIC_SNAPSHOT) + characterization=util.pack_any(_METRIC_SNAPSHOT), ) get_quantum_config.return_value = quantum_config processor = cg.EngineProcessor( - project_id=project_id, - processor_id=processor_id, - context=EngineContext() + project_id=project_id, processor_id=processor_id, context=EngineContext() ) result = processor.get_config_by_run_name(config_id=config_id) assert not result.snapshot_id get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - run_name="current", config_id=config_id + project_id=project_id, processor_id=processor_id, run_name="current", config_id=config_id ) -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' +) def test_get_config_by_snapshot_id(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" @@ -1131,30 +1123,24 @@ def test_get_config_by_snapshot_id(get_quantum_config): ) device_spec = v2.device_pb2.DeviceSpecification( - valid_qubits=["0_0", "1_1", "2_2"], - valid_targets=[ - v2.device_pb2.TargetSet( - name="2_quibit_targets", - target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target( - ids=["0_0", "1_1"] - )] + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] ) ], ) quantum_config = quantum.QuantumProcessorConfig( name=name, device_specification=util.pack_any(device_spec), - characterization=util.pack_any(_METRIC_SNAPSHOT) + characterization=util.pack_any(_METRIC_SNAPSHOT), ) get_quantum_config.return_value = quantum_config - expected_config = ProcessorConfig( - quantum_processor_config=quantum_config - ) + expected_config = ProcessorConfig(quantum_processor_config=quantum_config) processor = cg.EngineProcessor( - project_id=project_id, - processor_id=processor_id, - context=EngineContext() + project_id=project_id, processor_id=processor_id, context=EngineContext() ) actual_config = processor.get_config_by_snapshot( @@ -1162,8 +1148,10 @@ def test_get_config_by_snapshot_id(get_quantum_config): ) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - snapshot_id=snapshot_id, config_id=config_id + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id ) assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id @@ -1174,7 +1162,9 @@ def test_get_config_by_snapshot_id(get_quantum_config): assert actual_config.calibration == expected_config.calibration -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' +) def test_get_config_by_snapshot_id_not_found(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" @@ -1190,23 +1180,23 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): get_quantum_config.return_value = None processor = cg.EngineProcessor( - project_id=project_id, - processor_id=processor_id, - context=EngineContext() + project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_by_snapshot( - config_id=config_id, snapshot_id=snapshot_id - ) + result = processor.get_config_by_snapshot(config_id=config_id, snapshot_id=snapshot_id) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - snapshot_id=snapshot_id, config_id=config_id + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_id=config_id ) - assert result == None + assert result is None -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +@mock.patch('' \ +'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' +) def test_get_current_config_by_run_name_not_found(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" @@ -1221,15 +1211,15 @@ def test_get_current_config_by_run_name_not_found(get_quantum_config): get_quantum_config.return_value = None processor = cg.EngineProcessor( - project_id=project_id, - processor_id=processor_id, - context=EngineContext() + project_id=project_id, processor_id=processor_id, context=EngineContext() ) result = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - run_name=run_name, config_id=config_id + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_id=config_id ) - assert result == None \ No newline at end of file + assert result is None \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index a5ea7b6df0f..cfc82c3d9e5 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -908,7 +908,9 @@ def test_get_engine_device(get_processor): with pytest.raises(ValueError): device.validate_operation(cirq.CZ(cirq.GridQubit(1, 1), cirq.GridQubit(2, 2))) -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' +) def test_get_processor_config_by_snapshot_id(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" @@ -925,16 +927,14 @@ def test_get_processor_config_by_snapshot_id(get_quantum_config_async): get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( - processor_id=processor_id, - snapshot_id=snapshot_id, - config_id=config_id + processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id ) get_quantum_config_async.assert_called_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id + config_id=config_id, ) assert result.project_id == project_id assert result.processor_id == processor_id @@ -942,7 +942,9 @@ def test_get_processor_config_by_snapshot_id(get_quantum_config_async): assert result.config_id == config_id assert result.run_name == '' -@mock.patch('cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async') +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' +) def test_get_processor_config_by_run_name(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" @@ -960,9 +962,7 @@ def test_get_processor_config_by_run_name(get_quantum_config_async): get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( - processor_id=processor_id, - run_name=run_name, - config_id=config_id + processor_id=processor_id, run_name=run_name, config_id=config_id ) get_quantum_config_async.assert_called_with( diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 517473cc809..56ee2badd94 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -39,30 +39,30 @@ class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): def __init__(self, *, - quantum_processor_config: quantum.QuantumProcessorConfig, - run_name: str = '' + quantum_processor_config: quantum.QuantumProcessorConfig, run_name: str = '' ) -> None: self._quantum_processor_config = quantum_processor_config self._run_name = run_name self._device_spec = util.unpack_any( - self._quantum_processor_config.device_specification, - v2.device_pb2.DeviceSpecification() + self._quantum_processor_config.device_specification, v2.device_pb2.DeviceSpecification() ) self._metric_snapshot = util.unpack_any( - self._quantum_processor_config.characterization, - v2.metrics_pb2.MetricsSnapshot() + self._quantum_processor_config.characterization, v2.metrics_pb2.MetricsSnapshot() ) + @property def effective_device(self) -> cirq.Device: """The GridDevice generated from thisc configuration's device specification""" return cg.GridDevice.from_proto(self._device_spec) + @property def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" return cg.Calibration(self._metric_snapshot) + @property def snapshot_id(self) -> str: """The snapshot that contains this processor config""" @@ -74,31 +74,36 @@ def snapshot_id(self) -> str: parts = self._quantum_processor_config.name.split('/') return parts[5] + @property def run_name(self) -> str: """The run that generated this config if avaiable.""" return self._run_name - + + @property def project_id(self) -> str: """The project that contains this config.""" parts = self._quantum_processor_config.name.split('/') return parts[1] - + + @property def processor_id(self) -> str: """The processor id for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[3] - + + @property def config_id(self) -> str: """The unique identifier for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[-1] + def __repr__(self) -> str: - return( + return ( f'cirq_google.ProcessorConfig' f'(project_id={self.project_id}, ' f'processor_id={self.processor_id}, ' diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index b6e8c229450..d8efaa7f457 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -17,28 +17,22 @@ from __future__ import annotations import cirq_google as cg - from cirq_google.api import v2 from cirq_google.cloud import quantum from cirq_google.devices import GridDevice from cirq_google.engine import util - _METRIC_SNAPSHOT = v2.metrics_pb2.MetricsSnapshot( - timestamp_ms=1562544000021, - metrics=[ - v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '0_1'], - values=[v2.metrics_pb2.Value(double_val=0.9999)], - ), - v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '1_0'], - values=[v2.metrics_pb2.Value(double_val=0.9998)], - ), - ], - ) + timestamp_ms=1562544000021, + metrics=[ + v2.metrics_pb2.Metric( + name='xeb', targets=['0_0', '0_1'], values=[v2.metrics_pb2.Value(double_val=0.9999)] + ), + v2.metrics_pb2.Metric( + name='xeb', targets=['0_0', '1_0'], values=[v2.metrics_pb2.Value(double_val=0.9998)] + ), + ], +) _DEVICE_SPEC = v2.device_pb2.DeviceSpecification( @@ -47,9 +41,7 @@ v2.device_pb2.TargetSet( name="2_quibit_targets", target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target( - ids=["0_0", "1_1"] - )] + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] ) ], ) @@ -60,66 +52,59 @@ _CONFIG_ID = 'test_config_id' _VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( - name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ID}', - device_specification=util.pack_any(_DEVICE_SPEC), - characterization=util.pack_any(_METRIC_SNAPSHOT) - ) + name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ID}', + device_specification=util.pack_any(_DEVICE_SPEC), + characterization=util.pack_any(_METRIC_SNAPSHOT) +) + def test_processor_config_snapshot_id(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.snapshot_id == _SNAPSHOT_ID + def test_processor_config_run_name(): run_name = 'test_run_name' config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - run_name=run_name - ) + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name + ) assert config.run_name == run_name + def test_processor_config_effective_device(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.effective_device == GridDevice.from_proto(_DEVICE_SPEC) + def test_processor_config_calibration(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.calibration == cg.Calibration(_METRIC_SNAPSHOT) + def test_processor_project_id(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.project_id == _PROJECT_ID + def test_processor_processor_id(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.processor_id == _PROCESSOR_ID + def test_processor_config_id(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) assert config.config_id == _CONFIG_ID + def test_processor_config_repr(): - config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - ) + config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) expected_repr = ( f'cirq_google.ProcessorConfig' f'(project_id={_PROJECT_ID}, ' @@ -131,20 +116,19 @@ def test_processor_config_repr(): assert repr(config) == expected_repr + def test_processor_config_repr_with_run_name(): run_name = 'test_run_name' config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, - run_name=run_name + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name ) expected_repr = ( - f'cirq_google.ProcessorConfig' - f'(project_id={_PROJECT_ID}, ' - f'processor_id={_PROCESSOR_ID}, ' - f'snapshot_id={_SNAPSHOT_ID}, ' - f'run_name={run_name} ' - f'config_id={_CONFIG_ID}' - ) + f'cirq_google.ProcessorConfig' + f'(project_id={_PROJECT_ID}, ' + f'processor_id={_PROCESSOR_ID}, ' + f'snapshot_id={_SNAPSHOT_ID}, ' + f'run_name={run_name} ' + f'config_id={_CONFIG_ID}' + ) assert repr(config) == expected_repr - diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 731a9e30d39..21da6f21365 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -236,10 +236,10 @@ async def run_sweep_async( self._programs[program_id].add_job(job_id, job) return job - def get_config_by_run_name( - self, config_id: str, run_name: str = "current" - ): + + def get_config_by_run_name(self, config_id: str, run_name: str = "current"): pass + def get_config_by_snapshot(self, config_id: str, snapshot_id: str): pass From 11d97f542124b5d98b8d753d0e1e5fdb689726eb Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:16:28 +0000 Subject: [PATCH 18/37] More fixes. --- cirq-google/cirq_google/engine/__init__.py | 4 +- .../cirq_google/engine/abstract_engine.py | 1 + .../cirq_google/engine/abstract_processor.py | 3 +- .../engine/abstract_processor_config.py | 9 +--- cirq-google/cirq_google/engine/engine.py | 18 +++++--- .../cirq_google/engine/engine_client.py | 12 ++--- .../cirq_google/engine/engine_processor.py | 8 ++-- .../engine/engine_processor_test.py | 5 --- cirq-google/cirq_google/engine/engine_test.py | 44 ++++++++++++++++++- 9 files changed, 72 insertions(+), 32 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index ef24af4a5e8..ceb442c4ecc 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -18,7 +18,9 @@ from cirq_google.engine.abstract_job import AbstractJob as AbstractJob -from cirq_google.engine.abstract_processor import AbstractProcessor as AbstractProcessor +from cirq_google.engine.abstract_processor import ( + AbstractProcessor as AbstractProcessor +) from cirq_google.engine.abstract_processor_config import AbstractProcessorConfig as AbstractProcessorConfig diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 554529d73e3..5a53c5214f1 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -140,6 +140,7 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: determining which processors may be used when sampling. """ + @abc.abstractmethod def get_processor_config_by_snapshot_id( self, processor_id: str, snapshot_id: str, config_id: str diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 21d8fc533f5..dfc43afee00 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -380,7 +380,8 @@ def get_schedule( """ @abc.abstractmethod - def get_config_by_run_name(self, config_id: str, run_name: str = "current" + def get_config_by_run_name( + self, config_id: str, run_name: str = "current" ) -> abstract_processor_config.AbstractProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 8edac5ee237..1a487196ef7 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -1,13 +1,12 @@ from __future__ import annotations import abc - from typing import TYPE_CHECKING - if TYPE_CHECKING: import cirq import cirq_google as cg + class AbstractProcessorConfig(abc.ABC): """Interface for a QuantumProcessorConfig. @@ -20,37 +19,31 @@ class AbstractProcessorConfig(abc.ABC): def effective_device(self) -> cirq.Device: """The Device generated from thi configuration's device specification""" - @property @abc.abstractmethod def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" - @property @abc.abstractmethod def snapshot_id(self) -> str: """The snapshot that contains this processor config""" - @property @abc.abstractmethod def run_name(self) -> str: """The run that generated this config if avaiable.""" - @property @abc.abstractmethod def project_id(self) -> str: """The if of the project that contains this config.""" - @property @abc.abstractmethod def processor_id(self) -> str: """The processor id for this config.""" - @property @abc.abstractmethod def config_id(self) -> str: diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index b711009f711..055d074369e 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -642,10 +642,12 @@ async def get_processor_config_by_snapshot_id_async( project_id=self.project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id + config_id=config_id, ) - return processor_config.ProcessorConfig(quantum_processor_config=quantum_config) - + if quantum_config: + return processor_config.ProcessorConfig(quantum_processor_config=quantum_config) + return None + get_processor_config_by_snapshot_id = duet.sync(get_processor_config_by_snapshot_id_async) @@ -668,11 +670,13 @@ async def get_processor_config_by_run_name_async( project_id=self.project_id, processor_id=processor_id, run_name=run_name, - config_id=config_id - ) - return processor_config.ProcessorConfig( - quantum_processor_config=quantum_config, run_name=run_name + config_id=config_id, ) + if quantum_config: + return processor_config.ProcessorConfig( + quantum_processor_config=quantum_config, run_name=run_name + ) + return None get_processor_config_by_run_name = duet.sync(get_processor_config_by_run_name_async) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 13740f9baa7..74058b1e5b8 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1196,8 +1196,8 @@ async def _get_quantum_processor_config( raise - async def get_quantum_processor_config_by_snapshot_id_async(self, - project_id: str, processor_id: str, snapshot_id: str, config_id: str + async def get_quantum_processor_config_by_snapshot_id_async( + self, project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1225,8 +1225,8 @@ async def get_quantum_processor_config_by_snapshot_id_async(self, get_quantum_processor_config_by_snapshot_id_async ) - async def get_quantum_processor_config_by_run_name_async(self, - project_id: str, processor_id: str, run_name: str, config_id: str + async def get_quantum_processor_config_by_run_name_async( + self, project_id: str, processor_id: str, run_name: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given run_name. @@ -1300,7 +1300,7 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: def _quantum_processor_name_with_snapshot_id( - project_id: str, processor_id: str, snapshot_id: str, config_id: str + project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> str: return ( f'projects/{project_id}/' @@ -1311,7 +1311,7 @@ def _quantum_processor_name_with_snapshot_id( def _quantum_processor_name_with_run_name( - project_id: str, processor_id: str, run_name: str, config_id: str + project_id: str, processor_id: str, run_name: str, config_id: str ) -> str: return ( f'projects/{project_id}/' diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 0063627afe0..9a0484771f6 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -520,8 +520,10 @@ def get_config_by_run_name( Returns: The quantum processor config. """ response = self.context.client.get_quantum_processor_config_by_run_name( - project_id=self.project_id, processor_id=self.processor_id, - run_name=run_name, config_id=config_id + project_id=self.project_id, + processor_id=self.processor_id, + run_name=run_name, + config_id=config_id, ) if response: return processor_config.ProcessorConfig( @@ -548,7 +550,7 @@ def get_config_by_snapshot( project_id=self.project_id, processor_id=self.processor_id, snapshot_id=snapshot_id, - config_id=config_id + config_id=config_id, ) if response: return processor_config.ProcessorConfig(quantum_processor_config=response) diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index b25e6818e65..e14d39d93d6 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1202,11 +1202,6 @@ def test_get_current_config_by_run_name_not_found(get_quantum_config): processor_id = "test_proc_id" config_id = "test_config_id" run_name = 'test_run_name' - name = ( - f'projects/{project_id}/' - f'processors/{processor_id}/' - f'configAutomationRuns/{run_name}/configs/{config_id}' - ) get_quantum_config.return_value = None diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index cfc82c3d9e5..636ca6f2398 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -976,4 +976,46 @@ def test_get_processor_config_by_run_name(get_quantum_config_async): assert result.snapshot_id == snapshot_id assert result.run_name == run_name assert result.config_id == config_id - \ No newline at end of file + + +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' +) +def test_get_processor_config_by_snapshot_id_none(get_quantum_config_async): + project_id = "test_project_id" + processor_id = "test_processor_id" + snapshot_id = "test_snapshot_id" + config_id = "test_config_id" + resource_name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/{config_id}' + ) + + get_quantum_config_async.return_value = None + + result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( + processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + ) + + assert result is None + + +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' +) +def test_get_processor_config_by_run_name(get_quantum_config_async): + project_id = "test_project_id" + processor_id = "test_processor_id" + config_id = "test_config_id" + run_name = "test_run_name" + + get_quantum_config_async.return_value = None + + result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( + processor_id=processor_id, run_name=run_name, config_id=config_id + ) + + assert result is None + From 2365a578cf692b299214ff32bde695f02f4c8803 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:20:41 +0000 Subject: [PATCH 19/37] Fix test name --- cirq-google/cirq_google/engine/engine_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 636ca6f2398..968b796f64b 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -1005,7 +1005,7 @@ def test_get_processor_config_by_snapshot_id_none(get_quantum_config_async): @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) -def test_get_processor_config_by_run_name(get_quantum_config_async): +def test_get_processor_config_by_run_name_nine(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" config_id = "test_config_id" From 67cabf468ba0c021eba4c448e25b544e460963ba Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:23:11 +0000 Subject: [PATCH 20/37] More syntax errors. --- cirq-google/cirq_google/engine/engine_processor_test.py | 8 +------- cirq-google/cirq_google/engine/engine_test.py | 6 ------ 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index e14d39d93d6..4d5e4ae61f2 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1170,12 +1170,6 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - name = ( - f'projects/{project_id}/' - f'processors/{processor_id}/' - f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' - ) get_quantum_config.return_value = None @@ -1194,7 +1188,7 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): assert result is None -@mock.patch('' \ +@mock.patch(' 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) def test_get_current_config_by_run_name_not_found(get_quantum_config): diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 968b796f64b..29922e96b23 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -986,12 +986,6 @@ def test_get_processor_config_by_snapshot_id_none(get_quantum_config_async): processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" config_id = "test_config_id" - resource_name = ( - f'projects/{project_id}/' - f'processors/{processor_id}/' - f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' - ) get_quantum_config_async.return_value = None From afe7f0efd4b149fbe7ad45312ff914fd1e672a68 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:26:13 +0000 Subject: [PATCH 21/37] More formatting fixes. --- cirq-google/cirq_google/engine/__init__.py | 8 ++++---- cirq-google/cirq_google/engine/engine_processor_test.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index ceb442c4ecc..9d445a35983 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -18,11 +18,11 @@ from cirq_google.engine.abstract_job import AbstractJob as AbstractJob -from cirq_google.engine.abstract_processor import ( - AbstractProcessor as AbstractProcessor -) +from cirq_google.engine.abstract_processor import AbstractProcessor as AbstractProcessor -from cirq_google.engine.abstract_processor_config import AbstractProcessorConfig as AbstractProcessorConfig +from cirq_google.engine.abstract_processor_config import ( + AbstractProcessorConfig as AbstractProcessorConfig +) from cirq_google.engine.abstract_program import AbstractProgram as AbstractProgram diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 4d5e4ae61f2..0ed686f5dfb 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1188,7 +1188,7 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): assert result is None -@mock.patch(' +@mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) def test_get_current_config_by_run_name_not_found(get_quantum_config): From 947ad46249bab9bc1ac1d1879db5ebb17b412dc1 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:48:36 +0000 Subject: [PATCH 22/37] Fix remaining format issues --- cirq-google/cirq_google/engine/__init__.py | 2 +- .../cirq_google/engine/abstract_engine.py | 5 +- .../engine/abstract_local_engine.py | 4 +- .../engine/abstract_local_engine_test.py | 2 +- .../cirq_google/engine/abstract_processor.py | 2 +- .../engine/abstract_processor_config.py | 7 +-- cirq-google/cirq_google/engine/engine.py | 7 ++- .../cirq_google/engine/engine_client.py | 8 +-- .../cirq_google/engine/engine_client_test.py | 22 ++++---- .../cirq_google/engine/engine_processor.py | 6 +-- .../engine/engine_processor_test.py | 39 +++++++------- cirq-google/cirq_google/engine/engine_test.py | 16 +++--- .../cirq_google/engine/processor_config.py | 18 ++----- .../engine/processor_config_test.py | 51 +++++++++---------- .../engine/simulated_local_processor.py | 2 - 15 files changed, 86 insertions(+), 105 deletions(-) diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index 9d445a35983..658d78292b0 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -21,7 +21,7 @@ from cirq_google.engine.abstract_processor import AbstractProcessor as AbstractProcessor from cirq_google.engine.abstract_processor_config import ( - AbstractProcessorConfig as AbstractProcessorConfig + AbstractProcessorConfig as AbstractProcessorConfig, ) from cirq_google.engine.abstract_program import AbstractProgram as AbstractProgram diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 5a53c5214f1..8c6fa638a59 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -139,8 +139,7 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: processor_id: String identifier, or list of string identifiers, determining which processors may be used when sampling. """ - - + @abc.abstractmethod def get_processor_config_by_snapshot_id( self, processor_id: str, snapshot_id: str, config_id: str @@ -163,7 +162,7 @@ def get_processor_config_by_run_name( """Returns a ProcessorConfig from this project and the given processor id. If no run_name is provided, the config from the most recent run is returned. - + Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index 608b10d754f..7ff5cacb73e 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -39,6 +39,7 @@ def __init__(self, processors: list[AbstractLocalProcessor]): for processor in processors: processor.set_engine(self) self._processors = {proc.processor_id: proc for proc in processors} + def get_program(self, program_id: str) -> AbstractProgram: """Returns an existing AbstractProgram given an identifier. @@ -174,7 +175,7 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: if not isinstance(processor_id, str): raise ValueError(f'Invalid processor {processor_id}') return self._processors[processor_id].get_sampler() - + def get_processor_config_by_snapshot_id( self, processor_id: str, snapshot_id: str, config_id: str ): @@ -186,4 +187,3 @@ def get_processor_config_by_run_name( ): # TODO: Implement later as needed. pass - \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/abstract_local_engine_test.py b/cirq-google/cirq_google/engine/abstract_local_engine_test.py index 9700fd8d40a..d595c25f5e3 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine_test.py @@ -80,7 +80,7 @@ def list_programs( def get_program(self, program_id: str) -> AbstractProgram: return self._programs[program_id] - + def get_config_by_run_name(self, *args, **kwargs): pass diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index dfc43afee00..313e3044b99 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -384,7 +384,7 @@ def get_config_by_run_name( self, config_id: str, run_name: str = "current" ) -> abstract_processor_config.AbstractProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. - + If no run name is provided, the config from the most recent run is returned. diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 1a487196ef7..5d51c2eac5a 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -2,6 +2,7 @@ import abc from typing import TYPE_CHECKING + if TYPE_CHECKING: import cirq import cirq_google as cg @@ -18,17 +19,17 @@ class AbstractProcessorConfig(abc.ABC): @abc.abstractmethod def effective_device(self) -> cirq.Device: """The Device generated from thi configuration's device specification""" - + @property @abc.abstractmethod def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" - + @property @abc.abstractmethod def snapshot_id(self) -> str: """The snapshot that contains this processor config""" - + @property @abc.abstractmethod def run_name(self) -> str: diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 055d074369e..1425b3df25a 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -623,7 +623,7 @@ def get_sampler( snapshot_id=snapshot_id, max_concurrent_jobs=max_concurrent_jobs, ) - + async def get_processor_config_by_snapshot_id_async( self, processor_id: str, snapshot_id: str, config_id: str ) -> processor_config.ProcessorConfig | None: @@ -649,7 +649,6 @@ async def get_processor_config_by_snapshot_id_async( return None get_processor_config_by_snapshot_id = duet.sync(get_processor_config_by_snapshot_id_async) - async def get_processor_config_by_run_name_async( self, processor_id: str, config_id: str, run_name: str = 'current' @@ -657,7 +656,7 @@ async def get_processor_config_by_run_name_async( """Returns a ProcessorConfig from this project and the given processor id. If no run_name is provided, the config from the most recent run is returned. - + Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. @@ -677,7 +676,7 @@ async def get_processor_config_by_run_name_async( quantum_processor_config=quantum_config, run_name=run_name ) return None - + get_processor_config_by_run_name = duet.sync(get_processor_config_by_run_name_async) diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 74058b1e5b8..076a56a7c55 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1195,9 +1195,8 @@ async def _get_quantum_processor_config( return None raise - async def get_quantum_processor_config_by_snapshot_id_async( - self, project_id: str, processor_id: str, snapshot_id: str, config_id: str + self, project_id: str, processor_id: str, snapshot_id: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1224,7 +1223,7 @@ async def get_quantum_processor_config_by_snapshot_id_async( get_quantum_processor_config_by_snapshot_id = duet.sync( get_quantum_processor_config_by_snapshot_id_async ) - + async def get_quantum_processor_config_by_run_name_async( self, project_id: str, processor_id: str, run_name: str, config_id: str ) -> quantum.QuantumProcessorConfig | None: @@ -1246,11 +1245,12 @@ async def get_quantum_processor_config_by_run_name_async( project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id ) return await self._get_quantum_processor_config(name) - + get_quantum_processor_config_by_run_name = duet.sync( get_quantum_processor_config_by_run_name_async ) + def _project_name(project_id: str) -> str: return f'projects/{project_id}' diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 2734457e52c..6e9b96d1218 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1758,7 +1758,6 @@ def test_get_quantum_processor_config_by_snapshot_id(client_constructor, default f'configSnapshots/{snapshot_id}/' f'configs/{config_id}' ) - grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) @@ -1774,10 +1773,12 @@ def test_get_quantum_processor_config_by_snapshot_id(client_constructor, default quantum.GetQuantumProcessorConfigRequest(name=resource_name) ) assert actual_result == expected_result - + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_snapshot_id_not_found( + client_constructor, default_engine_client +): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" @@ -1788,7 +1789,7 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructo f'configSnapshots/{snapshot_id}/' f'configs/{config_id}' ) - + grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') @@ -1796,7 +1797,7 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructo project_id=project_id, processor_id=processor_id, config_id=config_id, - snapshot_id=snapshot_id + snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) @@ -1806,7 +1807,8 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found(client_constructo @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_snapshot_id_exception( - client_constructor, default_engine_client): + client_constructor, default_engine_client +): grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.BadRequest('invalid_reueust') @@ -1818,9 +1820,9 @@ def test_get_quantum_processor_config_by_snapshot_id_exception( snapshot_id="test_snapshot_id", ) + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_run_name( - client_constructor, default_engine_client): +def test_get_quantum_processor_config_by_run_name(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" @@ -1832,7 +1834,7 @@ def test_get_quantum_processor_config_by_run_name( f'configAutomationRuns/{run_name}/' f'configs/{config_id}' ) - + grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) grpc_client.get_quantum_processor_config.return_value = expected_result @@ -1845,6 +1847,7 @@ def test_get_quantum_processor_config_by_run_name( ) assert actual_result == expected_result + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_run_name_not_found( client_constructor, default_engine_client @@ -1870,6 +1873,7 @@ def test_get_quantum_processor_config_by_run_name_not_found( ) assert actual_result is None + @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) def test_get_quantum_processor_config_by_run_name_exception( client_constructor, default_engine_client diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 9a0484771f6..0e6128c7ba3 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -507,7 +507,7 @@ def get_config_by_run_name( self, config_id: str, run_name: str = "current" ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. - + If no run name is provided, the config from the most recent run is returned. @@ -525,7 +525,8 @@ def get_config_by_run_name( run_name=run_name, config_id=config_id, ) - if response: + + if response: return processor_config.ProcessorConfig( quantum_processor_config=response, run_name=run_name ) @@ -555,7 +556,6 @@ def get_config_by_snapshot( if response: return processor_config.ProcessorConfig(quantum_processor_config=response) return None - def __str__(self): return ( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 0ed686f5dfb..097d33a6f49 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -185,14 +185,10 @@ def _to_timestamp(json_string): timestamp_ms=1562544000021, metrics=[ v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '0_1'], - values=[v2.metrics_pb2.Value(double_val=0.9999)], + name='xeb', targets=['0_0', '0_1'], values=[v2.metrics_pb2.Value(double_val=0.9999)] ), v2.metrics_pb2.Metric( - name='xeb', - targets=['0_0', '1_0'], - values=[v2.metrics_pb2.Value(double_val=0.9998)], + name='xeb', targets=['0_0', '1_0'], values=[v2.metrics_pb2.Value(double_val=0.9998)] ), ], ) @@ -1014,10 +1010,12 @@ def test_sampler_with_stream_rpcs(client): assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')} assert client().run_job_over_stream.call_args[1]['project_id'] == 'proj' + def test_str(): processor = cg.EngineProcessor('a', 'p', EngineContext()) assert str(processor) == 'EngineProcessor(project_id=\'a\', processor_id=\'p\')' + @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) @@ -1039,7 +1037,7 @@ def test_get_config_by_run_name(get_quantum_config): v2.device_pb2.TargetSet( name="2_quibit_targets", target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])], ) ], ) @@ -1057,8 +1055,7 @@ def test_get_config_by_run_name(get_quantum_config): actual_config = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, - run_name=run_name, config_id=config_id + project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id ) assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id @@ -1067,6 +1064,7 @@ def test_get_config_by_run_name(get_quantum_config): assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration + @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) @@ -1086,7 +1084,7 @@ def test_get_current_config_by_run_name(get_quantum_config): v2.device_pb2.TargetSet( name="2_quibit_targets", target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])], ) ], ) @@ -1107,6 +1105,7 @@ def test_get_current_config_by_run_name(get_quantum_config): project_id=project_id, processor_id=processor_id, run_name="current", config_id=config_id ) + @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' ) @@ -1128,7 +1127,7 @@ def test_get_config_by_snapshot_id(get_quantum_config): v2.device_pb2.TargetSet( name="2_quibit_targets", target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])], ) ], ) @@ -1143,15 +1142,13 @@ def test_get_config_by_snapshot_id(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - actual_config = processor.get_config_by_snapshot( - config_id=config_id, snapshot_id=snapshot_id - ) + actual_config = processor.get_config_by_snapshot(config_id=config_id, snapshot_id=snapshot_id) get_quantum_config.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id + config_id=config_id, ) assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id @@ -1183,13 +1180,14 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id + config_id=config_id, ) assert result is None + @mock.patch( -'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) def test_get_current_config_by_run_name_not_found(get_quantum_config): project_id = "test_project_id" @@ -1206,9 +1204,6 @@ def test_get_current_config_by_run_name_not_found(get_quantum_config): result = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) get_quantum_config.assert_called_once_with( - project_id=project_id, - processor_id=processor_id, - run_name=run_name, - config_id=config_id + project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id ) - assert result is None \ No newline at end of file + assert result is None diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 29922e96b23..5f7009e9c88 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -908,6 +908,7 @@ def test_get_engine_device(get_processor): with pytest.raises(ValueError): device.validate_operation(cirq.CZ(cirq.GridQubit(1, 1), cirq.GridQubit(2, 2))) + @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' ) @@ -927,7 +928,7 @@ def test_get_processor_config_by_snapshot_id(get_quantum_config_async): get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( - processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id ) get_quantum_config_async.assert_called_with( @@ -942,6 +943,7 @@ def test_get_processor_config_by_snapshot_id(get_quantum_config_async): assert result.config_id == config_id assert result.run_name == '' + @mock.patch( 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' ) @@ -962,14 +964,11 @@ def test_get_processor_config_by_run_name(get_quantum_config_async): get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( - processor_id=processor_id, run_name=run_name, config_id=config_id + processor_id=processor_id, run_name=run_name, config_id=config_id ) get_quantum_config_async.assert_called_with( - project_id=project_id, - processor_id=processor_id, - run_name=run_name, - config_id=config_id + project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id ) assert result.project_id == project_id assert result.processor_id == processor_id @@ -990,7 +989,7 @@ def test_get_processor_config_by_snapshot_id_none(get_quantum_config_async): get_quantum_config_async.return_value = None result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( - processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id ) assert result is None @@ -1008,8 +1007,7 @@ def test_get_processor_config_by_run_name_nine(get_quantum_config_async): get_quantum_config_async.return_value = None result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( - processor_id=processor_id, run_name=run_name, config_id=config_id + processor_id=processor_id, run_name=run_name, config_id=config_id ) assert result is None - diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 56ee2badd94..82dae8a76c1 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -16,9 +16,7 @@ from typing import TYPE_CHECKING - import cirq_google as cg - from cirq_google.api import v2 from cirq_google.engine import abstract_processor_config, util @@ -37,32 +35,28 @@ class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): ValueError: If quantum_processor_config is contains incompatible types. """ - def __init__(self, - *, - quantum_processor_config: quantum.QuantumProcessorConfig, run_name: str = '' + def __init__( + self, *, quantum_processor_config: quantum.QuantumProcessorConfig, run_name: str = '' ) -> None: self._quantum_processor_config = quantum_processor_config self._run_name = run_name - self._device_spec = util.unpack_any( + self._device_spec = util.unpack_any( self._quantum_processor_config.device_specification, v2.device_pb2.DeviceSpecification() ) self._metric_snapshot = util.unpack_any( self._quantum_processor_config.characterization, v2.metrics_pb2.MetricsSnapshot() ) - @property def effective_device(self) -> cirq.Device: """The GridDevice generated from thisc configuration's device specification""" return cg.GridDevice.from_proto(self._device_spec) - @property def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" return cg.Calibration(self._metric_snapshot) - @property def snapshot_id(self) -> str: """The snapshot that contains this processor config""" @@ -74,34 +68,29 @@ def snapshot_id(self) -> str: parts = self._quantum_processor_config.name.split('/') return parts[5] - @property def run_name(self) -> str: """The run that generated this config if avaiable.""" return self._run_name - @property def project_id(self) -> str: """The project that contains this config.""" parts = self._quantum_processor_config.name.split('/') return parts[1] - @property def processor_id(self) -> str: """The processor id for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[3] - @property def config_id(self) -> str: """The unique identifier for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[-1] - def __repr__(self) -> str: return ( f'cirq_google.ProcessorConfig' @@ -111,4 +100,3 @@ def __repr__(self) -> str: f'run_name={self.run_name} ' f'config_id={self.config_id}' ) - \ No newline at end of file diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index d8efaa7f457..47d7125e1cc 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -34,14 +34,13 @@ ], ) - _DEVICE_SPEC = v2.device_pb2.DeviceSpecification( valid_qubits=["0_0", "1_1", "2_2"], valid_targets=[ v2.device_pb2.TargetSet( name="2_quibit_targets", target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, - targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])] + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])], ) ], ) @@ -54,74 +53,74 @@ _VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ID}', device_specification=util.pack_any(_DEVICE_SPEC), - characterization=util.pack_any(_METRIC_SNAPSHOT) + characterization=util.pack_any(_METRIC_SNAPSHOT), ) def test_processor_config_snapshot_id(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.snapshot_id == _SNAPSHOT_ID -def test_processor_config_run_name(): +def test_processor_config_run_name(): run_name = 'test_run_name' config = cg.engine.ProcessorConfig( quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name ) - + assert config.run_name == run_name def test_processor_config_effective_device(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.effective_device == GridDevice.from_proto(_DEVICE_SPEC) -def test_processor_config_calibration(): +def test_processor_config_calibration(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.calibration == cg.Calibration(_METRIC_SNAPSHOT) -def test_processor_project_id(): +def test_processor_project_id(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.project_id == _PROJECT_ID -def test_processor_processor_id(): +def test_processor_processor_id(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.processor_id == _PROCESSOR_ID -def test_processor_config_id(): +def test_processor_config_id(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - + assert config.config_id == _CONFIG_ID def test_processor_config_repr(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) expected_repr = ( - f'cirq_google.ProcessorConfig' - f'(project_id={_PROJECT_ID}, ' - f'processor_id={_PROCESSOR_ID}, ' - f'snapshot_id={_SNAPSHOT_ID}, ' - f'run_name={""} ' - f'config_id={_CONFIG_ID}' - ) - + f'cirq_google.ProcessorConfig' + f'(project_id={_PROJECT_ID}, ' + f'processor_id={_PROCESSOR_ID}, ' + f'snapshot_id={_SNAPSHOT_ID}, ' + f'run_name={""} ' + f'config_id={_CONFIG_ID}' + ) + assert repr(config) == expected_repr def test_processor_config_repr_with_run_name(): run_name = 'test_run_name' config = cg.engine.ProcessorConfig( - quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name - ) + quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name + ) expected_repr = ( f'cirq_google.ProcessorConfig' f'(project_id={_PROJECT_ID}, ' @@ -130,5 +129,5 @@ def test_processor_config_repr_with_run_name(): f'run_name={run_name} ' f'config_id={_CONFIG_ID}' ) - + assert repr(config) == expected_repr diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 21da6f21365..104f3d4884b 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -235,11 +235,9 @@ async def run_sweep_async( ) self._programs[program_id].add_job(job_id, job) return job - def get_config_by_run_name(self, config_id: str, run_name: str = "current"): pass - def get_config_by_snapshot(self, config_id: str, snapshot_id: str): pass From 4783519a936b05a91ee35f541c48b1f8e429e4bb Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 11 Aug 2025 21:59:23 +0000 Subject: [PATCH 23/37] Add missing documentation. --- .../cirq_google/engine/abstract_processor.py | 4 ++-- .../engine/abstract_processor_config.py | 14 ++++++++++++++ cirq-google/cirq_google/engine/engine_processor.py | 4 ++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 313e3044b99..abd6ba5cc1e 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -390,7 +390,7 @@ def get_config_by_run_name( Args: processor_id: The processor unique identifier. - confi_id: The quantum processor's unique identifier. + config_id: The quantum processor's unique identifier. run_name: The automation run name. Use 'current' if none id provided. @@ -405,7 +405,7 @@ def get_config_by_snapshot( Args: processor_id: The processor unique identifier. - confi_id: The quantum processor's unique identifier. + config_id: The quantum processor's unique identifier. snapshot_id: The snapshot's unique identifier. Returns: The quantum processor config. diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py index 5d51c2eac5a..04ffe91f039 100644 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ b/cirq-google/cirq_google/engine/abstract_processor_config.py @@ -1,3 +1,17 @@ +# Copyright 2025 The Cirq Developers +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + from __future__ import annotations import abc diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 0e6128c7ba3..b8cae332706 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -513,7 +513,7 @@ def get_config_by_run_name( Args: processor_id: The processor unique identifier. - confi_id: The quantum processor's unique identifier. + config_id: The quantum processor's unique identifier. run_name: The automation run name. Use 'current' if none id provided. @@ -539,7 +539,7 @@ def get_config_by_snapshot( Args: processor_id: The processor unique identifier. - confi_id: The quantum processor's unique identifier. + config_id: The quantum processor's unique identifier. snapshot_id: The snapshot's unique identifier. Returns: The quantum processor config. From 1505ba8df58bd7e33193936fc86a83842d627535 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 15 Aug 2025 18:15:19 +0000 Subject: [PATCH 24/37] Rename parameters and functioncs for consistency. --- .../cirq_google/cloud/quantum/__init__.py | 4 - cirq-google/cirq_google/engine/__init__.py | 4 - .../cirq_google/engine/abstract_engine.py | 18 +-- .../engine/abstract_local_engine.py | 4 +- .../engine/abstract_local_engine_test.py | 4 +- .../engine/abstract_local_processor_test.py | 4 +- .../cirq_google/engine/abstract_processor.py | 20 +-- .../engine/abstract_processor_config.py | 65 ---------- cirq-google/cirq_google/engine/engine.py | 24 ++-- .../cirq_google/engine/engine_client.py | 35 ++--- .../cirq_google/engine/engine_client_test.py | 62 ++++----- .../cirq_google/engine/engine_processor.py | 22 ++-- .../engine/engine_processor_test.py | 120 +++++++++++++----- cirq-google/cirq_google/engine/engine_test.py | 55 ++++---- .../cirq_google/engine/processor_config.py | 25 ++-- .../engine/processor_config_test.py | 12 +- .../engine/simulated_local_engine_test.py | 4 +- .../engine/simulated_local_processor.py | 4 +- 18 files changed, 241 insertions(+), 245 deletions(-) delete mode 100644 cirq-google/cirq_google/engine/abstract_processor_config.py diff --git a/cirq-google/cirq_google/cloud/quantum/__init__.py b/cirq-google/cirq_google/cloud/quantum/__init__.py index 8e21eb56262..752ac85ab3f 100644 --- a/cirq-google/cirq_google/cloud/quantum/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum/__init__.py @@ -13,10 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from cirq_google.cloud.quantum import gapic_version as package_version - -__version__ = package_version.__version__ - from cirq_google.cloud.quantum_v1alpha1.services.quantum_engine_service.client import ( QuantumEngineServiceClient, diff --git a/cirq-google/cirq_google/engine/__init__.py b/cirq-google/cirq_google/engine/__init__.py index 658d78292b0..30e8fb0aba8 100644 --- a/cirq-google/cirq_google/engine/__init__.py +++ b/cirq-google/cirq_google/engine/__init__.py @@ -20,10 +20,6 @@ from cirq_google.engine.abstract_processor import AbstractProcessor as AbstractProcessor -from cirq_google.engine.abstract_processor_config import ( - AbstractProcessorConfig as AbstractProcessorConfig, -) - from cirq_google.engine.abstract_program import AbstractProgram as AbstractProgram from cirq_google.engine.abstract_local_engine import AbstractLocalEngine as AbstractLocalEngine diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 8c6fa638a59..fca1caa768a 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -29,8 +29,8 @@ from cirq_google.engine import ( abstract_job, abstract_processor, - abstract_processor_config, abstract_program, + processor_config, ) VALID_DATE_TYPE = datetime.datetime | datetime.date @@ -141,24 +141,24 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: """ @abc.abstractmethod - def get_processor_config_by_snapshot_id( - self, processor_id: str, snapshot_id: str, config_id: str - ) -> abstract_processor_config.AbstractProcessorConfig | None: + def get_processor_config_from_snapshot( + self, processor_id: str, snapshot_id: str, config_alias: str = 'default' + ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. Args: processor_id: The processor unique identifier. snapshot_id: The unique identifier for the snapshot. - config_id: The unique identifier for the snapshot. + config_alias: The identifier for the config. Returns: The ProcessorConfig from this project and processor. """ @abc.abstractmethod - def get_processor_config_by_run_name( - self, processor_id: str, config_id: str, run_name: str = 'current' - ) -> abstract_processor_config.AbstractProcessorConfig | None: + def get_processor_config_from_run( + self, processor_id: str, run_name: str = 'default', config_alias: str = 'default' + ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. If no run_name is provided, the config from the most recent run is returned. @@ -166,7 +166,7 @@ def get_processor_config_by_run_name( Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. - config_id: The unique identifier for the snapshot. + config_alias: The identifier for the config. Returns: The ProcessorConfig from this project and processor. diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index 7ff5cacb73e..ed740eae8a0 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -176,13 +176,13 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: raise ValueError(f'Invalid processor {processor_id}') return self._processors[processor_id].get_sampler() - def get_processor_config_by_snapshot_id( + def get_processor_config_from_snapshot( self, processor_id: str, snapshot_id: str, config_id: str ): # TODO: Implement later as needed. pass - def get_processor_config_by_run_name( + def get_processor_config_from_run( self, processor_id: str, config_id: str, run_name: str = 'current' ): # TODO: Implement later as needed. diff --git a/cirq-google/cirq_google/engine/abstract_local_engine_test.py b/cirq-google/cirq_google/engine/abstract_local_engine_test.py index d595c25f5e3..64ef0d65822 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine_test.py @@ -81,10 +81,10 @@ def list_programs( def get_program(self, program_id: str) -> AbstractProgram: return self._programs[program_id] - def get_config_by_run_name(self, *args, **kwargs): + def get_config_from_run(self, *args, **kwargs): pass - def get_config_by_snapshot(self, *args, **kwargs): + def get_config_from_snapshot(self, *args, **kwargs): pass diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index 675bab09685..2cc04756826 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -71,10 +71,10 @@ def list_programs(self, *args, **kwargs): def get_program(self, *args, **kwargs): pass - def get_config_by_run_name(self, config_id: str, run_name: str = "current"): + def get_config_from_run(self, config_id: str, run_name: str = "current"): pass - def get_config_by_snapshot(self, config_id: str, snapshot_id: str): + def get_config_from_snapshot(self, config_id: str, snapshot_id: str): pass diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index abd6ba5cc1e..5817ae4ae61 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -35,7 +35,7 @@ import cirq_google.engine.abstract_engine as abstract_engine import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.calibration as calibration - from cirq_google.engine import abstract_processor_config + import cirq_google.engine.processor_config as processor_config class AbstractProcessor(abc.ABC): @@ -380,9 +380,9 @@ def get_schedule( """ @abc.abstractmethod - def get_config_by_run_name( - self, config_id: str, run_name: str = "current" - ) -> abstract_processor_config.AbstractProcessorConfig | None: + def get_config_from_run( + self, run_name: str = 'default', config_alias: str = 'default' + ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. If no run name is provided, the config from the most recent run @@ -390,22 +390,22 @@ def get_config_by_run_name( Args: processor_id: The processor unique identifier. - config_id: The quantum processor's unique identifier. - run_name: The automation run name. Use 'current' + config_alias: The quantum processor's unique identifier. + run_name: The automation run name. Use 'default' if none id provided. Returns: The quantum processor config. """ @abc.abstractmethod - def get_config_by_snapshot( - self, config_id: str, snapshot_id: str - ) -> abstract_processor_config.AbstractProcessorConfig | None: + def get_config_from_snapshot( + self, snapshot_id: str, config_alias: str = 'default' + ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. Args: processor_id: The processor unique identifier. - config_id: The quantum processor's unique identifier. + config_alias: The quantum processor's unique identifier. snapshot_id: The snapshot's unique identifier. Returns: The quantum processor config. diff --git a/cirq-google/cirq_google/engine/abstract_processor_config.py b/cirq-google/cirq_google/engine/abstract_processor_config.py deleted file mode 100644 index 04ffe91f039..00000000000 --- a/cirq-google/cirq_google/engine/abstract_processor_config.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2025 The Cirq Developers -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import abc -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - import cirq - import cirq_google as cg - - -class AbstractProcessorConfig(abc.ABC): - """Interface for a QuantumProcessorConfig. - - Describes available qubits, gates, and calivration data associated with - a processor configuration. - """ - - @property - @abc.abstractmethod - def effective_device(self) -> cirq.Device: - """The Device generated from thi configuration's device specification""" - - @property - @abc.abstractmethod - def calibration(self) -> cg.Calibration: - """Charicterization metrics captured for this configuration""" - - @property - @abc.abstractmethod - def snapshot_id(self) -> str: - """The snapshot that contains this processor config""" - - @property - @abc.abstractmethod - def run_name(self) -> str: - """The run that generated this config if avaiable.""" - - @property - @abc.abstractmethod - def project_id(self) -> str: - """The if of the project that contains this config.""" - - @property - @abc.abstractmethod - def processor_id(self) -> str: - """The processor id for this config.""" - - @property - @abc.abstractmethod - def config_id(self) -> str: - """The unique identifier for this config.""" diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 4952f10bff1..1e6db9c858e 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -636,34 +636,34 @@ def get_sampler( max_concurrent_jobs=max_concurrent_jobs, ) - async def get_processor_config_by_snapshot_id_async( - self, processor_id: str, snapshot_id: str, config_id: str + async def get_processor_config_from_snapshot_async( + self, processor_id: str, snapshot_id: str, config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. Args: processor_id: The processor unique identifier. snapshot_id: The unique identifier for the snapshot. - config_id: The unique identifier for the snapshot. + config_alias: The identifier for the config. Returns: The ProcessorConfig from this project and processor. """ client = self.context.client - quantum_config = await client.get_quantum_processor_config_by_snapshot_id_async( + quantum_config = await client.get_quantum_processor_config_from_snapshot_async( project_id=self.project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) if quantum_config: return processor_config.ProcessorConfig(quantum_processor_config=quantum_config) return None - get_processor_config_by_snapshot_id = duet.sync(get_processor_config_by_snapshot_id_async) + get_processor_config_from_snapshot = duet.sync(get_processor_config_from_snapshot_async) - async def get_processor_config_by_run_name_async( - self, processor_id: str, config_id: str, run_name: str = 'current' + async def get_processor_config_from_run_async( + self, processor_id: str, run_name: str = 'current', config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. @@ -672,16 +672,16 @@ async def get_processor_config_by_run_name_async( Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. - config_id: The unique identifier for the snapshot. + config_alias: The identifier for the config. Returns: The ProcessorConfig from this project and processor. """ - quantum_config = await self.context.client.get_quantum_processor_config_by_run_name_async( + quantum_config = await self.context.client.get_quantum_processor_config_from_run_async( project_id=self.project_id, processor_id=processor_id, run_name=run_name, - config_id=config_id, + config_alias=config_alias, ) if quantum_config: return processor_config.ProcessorConfig( @@ -689,7 +689,7 @@ async def get_processor_config_by_run_name_async( ) return None - get_processor_config_by_run_name = duet.sync(get_processor_config_by_run_name_async) + get_processor_config_from_run = duet.sync(get_processor_config_from_run_async) def get_engine(project_id: str | None = None) -> Engine: diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 076a56a7c55..3a2da5b9ae2 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1195,8 +1195,8 @@ async def _get_quantum_processor_config( return None raise - async def get_quantum_processor_config_by_snapshot_id_async( - self, project_id: str, processor_id: str, snapshot_id: str, config_id: str + async def get_quantum_processor_config_from_snapshot_async( + self, project_id: str, processor_id: str, snapshot_id: str, config_alias: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1204,7 +1204,7 @@ async def get_quantum_processor_config_by_snapshot_id_async( project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. snapshot_id: The id of the snapshot that contains the quantum processor config. - config_id: The id of the quantum processor config. + config_alias: The id of the quantum processor config. Returns: The quantum procesor config or None if it does not exist. @@ -1216,23 +1216,23 @@ async def get_quantum_processor_config_by_snapshot_id_async( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) return await self._get_quantum_processor_config(name) - get_quantum_processor_config_by_snapshot_id = duet.sync( - get_quantum_processor_config_by_snapshot_id_async + get_quantum_processor_config_from_snapshot = duet.sync( + get_quantum_processor_config_from_snapshot_async ) - async def get_quantum_processor_config_by_run_name_async( - self, project_id: str, processor_id: str, run_name: str, config_id: str + async def get_quantum_processor_config_from_run_async( + self, project_id: str, processor_id: str, run_name: str, config_alias: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given run_name. Args: project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. - config_id: The id of the quantum processor config. + config_alias: The id of the quantum processor config. run_name: The run_name that contains the quantum processor config. Returns: @@ -1242,13 +1242,14 @@ async def get_quantum_processor_config_by_run_name_async( EngineException: If the request to get the config fails. """ name = _quantum_processor_name_with_run_name( - project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_alias=config_alias, ) return await self._get_quantum_processor_config(name) - get_quantum_processor_config_by_run_name = duet.sync( - get_quantum_processor_config_by_run_name_async - ) + get_quantum_processor_config_from_run = duet.sync(get_quantum_processor_config_from_run_async) def _project_name(project_id: str) -> str: @@ -1300,24 +1301,24 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: def _quantum_processor_name_with_snapshot_id( - project_id: str, processor_id: str, snapshot_id: str, config_id: str + project_id: str, processor_id: str, snapshot_id: str, config_alias: str ) -> str: return ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) def _quantum_processor_name_with_run_name( - project_id: str, processor_id: str, run_name: str, config_id: str + project_id: str, processor_id: str, run_name: str, config_alias: str ) -> str: return ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 6e9b96d1218..36b6f48c137 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1746,27 +1746,27 @@ def test_list_time_slots(client_constructor, default_engine_client): @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id(client_constructor, default_engine_client): +def test_get_quantum_processor_config_from_snapshot(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) grpc_client.get_quantum_processor_config.return_value = expected_result - actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( + actual_result = default_engine_client.get_quantum_processor_config_from_snapshot( project_id=project_id, processor_id=processor_id, - config_id=config_id, + config_alias=config_alias, snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1776,27 +1776,27 @@ def test_get_quantum_processor_config_by_snapshot_id(client_constructor, default @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id_not_found( +def test_get_quantum_processor_config_from_snapshot_not_found( client_constructor, default_engine_client ): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') - actual_result = default_engine_client.get_quantum_processor_config_by_snapshot_id( + actual_result = default_engine_client.get_quantum_processor_config_from_snapshot( project_id=project_id, processor_id=processor_id, - config_id=config_id, + config_alias=config_alias, snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1806,41 +1806,44 @@ def test_get_quantum_processor_config_by_snapshot_id_not_found( @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_snapshot_id_exception( +def test_get_quantum_processor_config_from_snapshot_exception( client_constructor, default_engine_client ): grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.BadRequest('invalid_reueust') with pytest.raises(EngineException, match='invalid_reueust'): - _ = default_engine_client.get_quantum_processor_config_by_snapshot_id( + _ = default_engine_client.get_quantum_processor_config_from_snapshot( project_id="test_project_id", processor_id="test_processor_id", - config_id="test_config_id", + config_alias="test_config_alias", snapshot_id="test_snapshot_id", ) @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_run_name(client_constructor, default_engine_client): +def test_get_quantum_processor_config_from_run(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" run_name = "test_run_name" - config_id = "test_config_id" + config_alias = "test_config_alias" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) grpc_client = _setup_client_mock(client_constructor) expected_result = quantum.QuantumProcessorConfig(name=resource_name) grpc_client.get_quantum_processor_config.return_value = expected_result - actual_result = default_engine_client.get_quantum_processor_config_by_run_name( - project_id=project_id, processor_id=processor_id, config_id=config_id, run_name=run_name + actual_result = default_engine_client.get_quantum_processor_config_from_run( + project_id=project_id, + processor_id=processor_id, + config_alias=config_alias, + run_name=run_name, ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) @@ -1849,24 +1852,25 @@ def test_get_quantum_processor_config_by_run_name(client_constructor, default_en @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_run_name_not_found( - client_constructor, default_engine_client -): +def test_get_quantum_processor_config_from_run_not_found(client_constructor, default_engine_client): project_id = "test_project_id" processor_id = "test_processor_id" run_name = "test_run_name" - config_id = "test_config_id" + config_alias = "test_config_alias" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') - actual_result = default_engine_client.get_quantum_processor_config_by_run_name( - project_id=project_id, processor_id=processor_id, config_id=config_id, run_name=run_name + actual_result = default_engine_client.get_quantum_processor_config_from_run( + project_id=project_id, + processor_id=processor_id, + config_alias=config_alias, + run_name=run_name, ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) @@ -1875,16 +1879,14 @@ def test_get_quantum_processor_config_by_run_name_not_found( @mock.patch.object(quantum, 'QuantumEngineServiceAsyncClient', autospec=True) -def test_get_quantum_processor_config_by_run_name_exception( - client_constructor, default_engine_client -): +def test_get_quantum_processor_config_from_run_exception(client_constructor, default_engine_client): grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.BadRequest('invalid_reueust') with pytest.raises(EngineException, match='invalid_reueust'): - _ = default_engine_client.get_quantum_processor_config_by_run_name( + _ = default_engine_client.get_quantum_processor_config_from_run( project_id="test_project_id", processor_id="test_processor_id", - config_id="test_config_id", + config_alias="test_config_alias", run_name="test_run_name", ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index b8cae332706..4fe827d602d 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -503,8 +503,8 @@ def get_schedule( filter_str = ' AND '.join(filters) return self.context.client.list_time_slots(self.project_id, self.processor_id, filter_str) - def get_config_by_run_name( - self, config_id: str, run_name: str = "current" + def get_config_from_run( + self, run_name: str = 'default', config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. @@ -513,17 +513,17 @@ def get_config_by_run_name( Args: processor_id: The processor unique identifier. - config_id: The quantum processor's unique identifier. - run_name: The automation run name. Use 'current' + config_alias: The quantum processor's unique identifier. + run_name: The automation run name. Use 'default' if none id provided. Returns: The quantum processor config. """ - response = self.context.client.get_quantum_processor_config_by_run_name( + response = self.context.client.get_quantum_processor_config_from_run( project_id=self.project_id, processor_id=self.processor_id, run_name=run_name, - config_id=config_id, + config_alias=config_alias, ) if response: @@ -532,14 +532,14 @@ def get_config_by_run_name( ) return None - def get_config_by_snapshot( - self, config_id: str, snapshot_id: str + def get_config_from_snapshot( + self, snapshot_id: str, config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. Args: processor_id: The processor unique identifier. - config_id: The quantum processor's unique identifier. + config_alias: The quantum processor's unique identifier. snapshot_id: The snapshot's unique identifier. Returns: The quantum processor config. @@ -547,11 +547,11 @@ def get_config_by_snapshot( Raises: EngineException: If the request to get the config fails. """ - response = self.context.client.get_quantum_processor_config_by_snapshot_id( + response = self.context.client.get_quantum_processor_config_from_snapshot( project_id=self.project_id, processor_id=self.processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) if response: return processor_config.ProcessorConfig(quantum_processor_config=response) diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 097d33a6f49..4689020c70b 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1017,18 +1017,18 @@ def test_str(): @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' ) -def test_get_config_by_run_name(get_quantum_config): +def test_get_config_from_run(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" run_name = "test_run_name" - config_id = "test_config_id" + config_alias = "test_config_alias" name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) device_spec = v2.device_pb2.DeviceSpecification( @@ -1052,30 +1052,32 @@ def test_get_config_by_run_name(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - actual_config = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) + actual_config = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_alias=config_alias, ) assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_id == config_id + assert actual_config.config_alias == config_alias assert actual_config.run_name == run_name assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' ) -def test_get_current_config_by_run_name(get_quantum_config): +def test_get_default_config_from_run(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" - config_id = "test_config_id" name = ( f'projects/{project_id}/' f'processors/{processor_id}/' - f'configAutomationRuns/current/configs/{config_id}' + f'configAutomationRuns/default/configs/default' ) device_spec = v2.device_pb2.DeviceSpecification( @@ -1098,27 +1100,26 @@ def test_get_current_config_by_run_name(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_by_run_name(config_id=config_id) + _ = processor.get_config_from_run() - assert not result.snapshot_id get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, run_name="current", config_id=config_id + project_id=project_id, processor_id=processor_id, run_name='default', config_alias='default' ) @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' ) -def test_get_config_by_snapshot_id(get_quantum_config): +def test_get_config_from_snapshot(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) device_spec = v2.device_pb2.DeviceSpecification( @@ -1142,17 +1143,19 @@ def test_get_config_by_snapshot_id(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - actual_config = processor.get_config_by_snapshot(config_id=config_id, snapshot_id=snapshot_id) + actual_config = processor.get_config_from_snapshot( + config_alias=config_alias, snapshot_id=snapshot_id + ) get_quantum_config.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_id == config_id + assert actual_config.config_alias == config_alias assert actual_config.run_name == '' assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device @@ -1160,13 +1163,65 @@ def test_get_config_by_snapshot_id(get_quantum_config): @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' ) -def test_get_config_by_snapshot_id_not_found(get_quantum_config): +def test_get_default_config_from_snapshot(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + name = ( + f'projects/{project_id}/' + f'processors/{processor_id}/' + f'configSnapshots/{snapshot_id}/' + f'configs/default' + ) + + device_spec = v2.device_pb2.DeviceSpecification( + valid_qubits=["0_0", "1_1", "2_2"], + valid_targets=[ + v2.device_pb2.TargetSet( + name="2_quibit_targets", + target_ordering=v2.device_pb2.TargetSet.SYMMETRIC, + targets=[v2.device_pb2.Target(ids=["0_0", "1_1"])], + ) + ], + ) + quantum_config = quantum.QuantumProcessorConfig( + name=name, + device_specification=util.pack_any(device_spec), + characterization=util.pack_any(_METRIC_SNAPSHOT), + ) + get_quantum_config.return_value = quantum_config + expected_config = ProcessorConfig(quantum_processor_config=quantum_config) + processor = cg.EngineProcessor( + project_id=project_id, processor_id=processor_id, context=EngineContext() + ) + + actual_config = processor.get_config_from_snapshot(snapshot_id=snapshot_id) + + get_quantum_config.assert_called_once_with( + project_id=project_id, + processor_id=processor_id, + snapshot_id=snapshot_id, + config_alias='default', + ) + assert actual_config.project_id == expected_config.project_id + assert actual_config.processor_id == expected_config.processor_id + assert actual_config.config_alias == 'default' + assert actual_config.run_name == '' + assert actual_config.snapshot_id == snapshot_id + assert actual_config.effective_device == expected_config.effective_device + assert actual_config.calibration == expected_config.calibration + + +@mock.patch( + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' +) +def test_get_config_from_snapshot_not_found(get_quantum_config): + project_id = "test_project_id" + processor_id = "test_proc_id" + snapshot_id = "test_snapshot_id" + config_alias = "test_config_alias" get_quantum_config.return_value = None @@ -1174,25 +1229,25 @@ def test_get_config_by_snapshot_id_not_found(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_by_snapshot(config_id=config_id, snapshot_id=snapshot_id) + result = processor.get_config_from_snapshot(config_alias=config_alias, snapshot_id=snapshot_id) get_quantum_config.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) assert result is None @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' ) -def test_get_current_config_by_run_name_not_found(get_quantum_config): +def test_get_current_config_from_run_not_found(get_quantum_config): project_id = "test_project_id" processor_id = "test_proc_id" - config_id = "test_config_id" + config_alias = "test_config_alias" run_name = 'test_run_name' get_quantum_config.return_value = None @@ -1201,9 +1256,12 @@ def test_get_current_config_by_run_name_not_found(get_quantum_config): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_by_run_name(config_id=config_id, run_name=run_name) + result = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) get_quantum_config.assert_called_once_with( - project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_alias=config_alias, ) assert result is None diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 04298598a63..8bfb1660c37 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -915,104 +915,107 @@ def test_get_engine_device(get_processor): @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' ) -def test_get_processor_config_by_snapshot_id(get_quantum_config_async): +def test_get_processor_config_from_snapshot(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg - result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( - processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + result = cg.Engine(project_id=project_id).get_processor_config_from_snapshot( + processor_id=processor_id, snapshot_id=snapshot_id, config_alias=config_alias ) get_quantum_config_async.assert_called_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_id=config_id, + config_alias=config_alias, ) assert result.project_id == project_id assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id - assert result.config_id == config_id + assert result.config_alias == config_alias assert result.run_name == '' @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' ) -def test_get_processor_config_by_run_name(get_quantum_config_async): +def test_get_processor_config_from_run(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" run_name = "test_run_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_id}' + f'configs/{config_alias}' ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg - result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( - processor_id=processor_id, run_name=run_name, config_id=config_id + result = cg.Engine(project_id=project_id).get_processor_config_from_run( + processor_id=processor_id, run_name=run_name, config_alias=config_alias ) get_quantum_config_async.assert_called_with( - project_id=project_id, processor_id=processor_id, run_name=run_name, config_id=config_id + project_id=project_id, + processor_id=processor_id, + run_name=run_name, + config_alias=config_alias, ) assert result.project_id == project_id assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id assert result.run_name == run_name - assert result.config_id == config_id + assert result.config_alias == config_alias @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_snapshot_id_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' ) -def test_get_processor_config_by_snapshot_id_none(get_quantum_config_async): +def test_get_processor_config_from_snapshot_none(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_id = "test_config_id" + config_alias = "test_config_alias" get_quantum_config_async.return_value = None - result = cg.Engine(project_id=project_id).get_processor_config_by_snapshot_id( - processor_id=processor_id, snapshot_id=snapshot_id, config_id=config_id + result = cg.Engine(project_id=project_id).get_processor_config_from_snapshot( + processor_id=processor_id, snapshot_id=snapshot_id, config_alias=config_alias ) assert result is None @mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_by_run_name_async' + 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' ) -def test_get_processor_config_by_run_name_nine(get_quantum_config_async): +def test_get_processor_config_from_run_nine(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" - config_id = "test_config_id" + config_alias = "test_config_alias" run_name = "test_run_name" get_quantum_config_async.return_value = None - result = cg.Engine(project_id=project_id).get_processor_config_by_run_name( - processor_id=processor_id, run_name=run_name, config_id=config_id + result = cg.Engine(project_id=project_id).get_processor_config_from_run( + processor_id=processor_id, run_name=run_name, config_alias=config_alias ) assert result is None diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index 82dae8a76c1..cbf99835d99 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -18,14 +18,14 @@ import cirq_google as cg from cirq_google.api import v2 -from cirq_google.engine import abstract_processor_config, util +from cirq_google.engine import util if TYPE_CHECKING: import cirq from cirq_google.cloud.quantum_v1alpha1.types import quantum -class ProcessorConfig(abstract_processor_config.AbstractProcessorConfig): +class ProcessorConfig: """Representation of a quantum processor configuration Describes available qubits, gates, and calivration data associated with @@ -40,22 +40,27 @@ def __init__( ) -> None: self._quantum_processor_config = quantum_processor_config self._run_name = run_name - self._device_spec = util.unpack_any( - self._quantum_processor_config.device_specification, v2.device_pb2.DeviceSpecification() + self._grid_device = cg.GridDevice.from_proto( + util.unpack_any( + self._quantum_processor_config.device_specification, + v2.device_pb2.DeviceSpecification(), + ) ) - self._metric_snapshot = util.unpack_any( - self._quantum_processor_config.characterization, v2.metrics_pb2.MetricsSnapshot() + self._calibration = cg.Calibration( + util.unpack_any( + self._quantum_processor_config.characterization, v2.metrics_pb2.MetricsSnapshot() + ) ) @property def effective_device(self) -> cirq.Device: """The GridDevice generated from thisc configuration's device specification""" - return cg.GridDevice.from_proto(self._device_spec) + return self._grid_device @property def calibration(self) -> cg.Calibration: """Charicterization metrics captured for this configuration""" - return cg.Calibration(self._metric_snapshot) + return self._calibration @property def snapshot_id(self) -> str: @@ -86,7 +91,7 @@ def processor_id(self) -> str: return parts[3] @property - def config_id(self) -> str: + def config_alias(self) -> str: """The unique identifier for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[-1] @@ -98,5 +103,5 @@ def __repr__(self) -> str: f'processor_id={self.processor_id}, ' f'snapshot_id={self.snapshot_id}, ' f'run_name={self.run_name} ' - f'config_id={self.config_id}' + f'config_alias={self.config_alias}' ) diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 47d7125e1cc..910049b558d 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -48,10 +48,10 @@ _PROCESSOR_ID = 'test_processor_id' _PROJECT_ID = 'test_project_id' _SNAPSHOT_ID = 'test_snapshot_id' -_CONFIG_ID = 'test_config_id' +_CONFIG_ALIAS = 'test_CONFIG_ALIAS' _VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( - name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ID}', + name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ALIAS}', device_specification=util.pack_any(_DEVICE_SPEC), characterization=util.pack_any(_METRIC_SNAPSHOT), ) @@ -96,10 +96,10 @@ def test_processor_processor_id(): assert config.processor_id == _PROCESSOR_ID -def test_processor_config_id(): +def test_processor_CONFIG_ALIAS(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - assert config.config_id == _CONFIG_ID + assert config.config_alias == _CONFIG_ALIAS def test_processor_config_repr(): @@ -110,7 +110,7 @@ def test_processor_config_repr(): f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={""} ' - f'config_id={_CONFIG_ID}' + f'config_alias={_CONFIG_ALIAS}' ) assert repr(config) == expected_repr @@ -127,7 +127,7 @@ def test_processor_config_repr_with_run_name(): f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={run_name} ' - f'config_id={_CONFIG_ID}' + f'config_alias={_CONFIG_ALIAS}' ) assert repr(config) == expected_repr diff --git a/cirq-google/cirq_google/engine/simulated_local_engine_test.py b/cirq-google/cirq_google/engine/simulated_local_engine_test.py index 715b80b469c..e3410f6f931 100644 --- a/cirq-google/cirq_google/engine/simulated_local_engine_test.py +++ b/cirq-google/cirq_google/engine/simulated_local_engine_test.py @@ -71,10 +71,10 @@ def get_sampler(self, *args, **kwargs): def supported_languages(self, *args, **kwargs): pass - def get_config_by_run_name(self, *args, **kwargs): + def get_config_from_run(self, *args, **kwargs): pass - def get_config_by_snapshot(self, *args, **kwargs): + def get_config_from_snapshot(self, *args, **kwargs): pass def list_programs( diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 104f3d4884b..2c26dba2d7b 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -236,8 +236,8 @@ async def run_sweep_async( self._programs[program_id].add_job(job_id, job) return job - def get_config_by_run_name(self, config_id: str, run_name: str = "current"): + def get_config_from_run(self, config_id: str, run_name: str = "current"): pass - def get_config_by_snapshot(self, config_id: str, snapshot_id: str): + def get_config_from_snapshot(self, config_id: str, snapshot_id: str): pass From f7bba2852b01857725dcd646d86497dcef5696d0 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 15 Aug 2025 18:37:24 +0000 Subject: [PATCH 25/37] Fix function params in AbstractLocalEngine --- cirq-google/cirq_google/engine/abstract_local_engine.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index ed740eae8a0..9df1d032b3f 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -177,13 +177,13 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: return self._processors[processor_id].get_sampler() def get_processor_config_from_snapshot( - self, processor_id: str, snapshot_id: str, config_id: str + self, processor_id: str, snapshot_id: str, config_alias: str = 'default' ): # TODO: Implement later as needed. pass def get_processor_config_from_run( - self, processor_id: str, config_id: str, run_name: str = 'current' + self, processor_id: str, run_name: str = 'default', config_alias: str = 'default' ): # TODO: Implement later as needed. pass From f15e7510687fe874c36de237dcbfcfce2f66b62b Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 15 Aug 2025 19:33:45 +0000 Subject: [PATCH 26/37] More `check/` fixes. --- .../engine/abstract_local_processor_test.py | 4 ++-- .../cirq_google/engine/processor_config_test.py | 11 +++++++++++ .../cirq_google/engine/simulated_local_processor.py | 4 ++-- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index 2cc04756826..72dc88a2e01 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -71,10 +71,10 @@ def list_programs(self, *args, **kwargs): def get_program(self, *args, **kwargs): pass - def get_config_from_run(self, config_id: str, run_name: str = "current"): + def get_config_from_run(self, run_name: str = "default", config_alias: str = 'default'): pass - def get_config_from_snapshot(self, config_id: str, snapshot_id: str): + def get_config_from_snapshot(self, snapshot_id: str, config_alias: str = 'default'): pass diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 910049b558d..ab981379312 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -63,6 +63,17 @@ def test_processor_config_snapshot_id(): assert config.snapshot_id == _SNAPSHOT_ID +def test_processor_config_snapshot_id_empty(): + quantum_config = quantum.QuantumProcessorConfig( + name=f'projects/proj_id/processors/proc_id/configAutomationRuns/default/configs/default', + device_specification=util.pack_any(_DEVICE_SPEC), + characterization=util.pack_any(_METRIC_SNAPSHOT), +) + config = cg.engine.ProcessorConfig(quantum_processor_config=quantum_config) + + assert config.snapshot_id == '' + + def test_processor_config_run_name(): run_name = 'test_run_name' config = cg.engine.ProcessorConfig( diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 2c26dba2d7b..0a3b3b14ad2 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -236,8 +236,8 @@ async def run_sweep_async( self._programs[program_id].add_job(job_id, job) return job - def get_config_from_run(self, config_id: str, run_name: str = "current"): + def get_config_from_run(self, run_name: str = "default", config_alias: str = 'default'): pass - def get_config_from_snapshot(self, config_id: str, snapshot_id: str): + def get_config_from_snapshot(self, snapshot_id: str, config_id: str = 'default'): pass From 449fdd4e7acd09ce0642324d4ed7f7abc9b0ea18 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 15 Aug 2025 19:42:17 +0000 Subject: [PATCH 27/37] More check fixes. --- cirq-google/cirq_google/engine/processor_config_test.py | 8 ++++---- .../cirq_google/engine/simulated_local_processor.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index ab981379312..06dc9aa0d75 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -65,10 +65,10 @@ def test_processor_config_snapshot_id(): def test_processor_config_snapshot_id_empty(): quantum_config = quantum.QuantumProcessorConfig( - name=f'projects/proj_id/processors/proc_id/configAutomationRuns/default/configs/default', - device_specification=util.pack_any(_DEVICE_SPEC), - characterization=util.pack_any(_METRIC_SNAPSHOT), -) + name='projects/proj_id/processors/proc_id/configAutomationRuns/default/configs/default', + device_specification=util.pack_any(_DEVICE_SPEC), + characterization=util.pack_any(_METRIC_SNAPSHOT), + ) config = cg.engine.ProcessorConfig(quantum_processor_config=quantum_config) assert config.snapshot_id == '' diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index 0a3b3b14ad2..dc301f237e7 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -236,7 +236,7 @@ async def run_sweep_async( self._programs[program_id].add_job(job_id, job) return job - def get_config_from_run(self, run_name: str = "default", config_alias: str = 'default'): + def get_config_from_run(self, run_name: str = 'default', config_alias: str = 'default'): pass def get_config_from_snapshot(self, snapshot_id: str, config_id: str = 'default'): From 6eba4b4bbcc0bf7e779d465d39f83365dc99cb15 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 22 Aug 2025 22:23:09 +0000 Subject: [PATCH 28/37] Address new comments. --- .../cloud/quantum/gapic_version.py | 16 ----- .../cloud/quantum_v1alpha1/__init__.py | 3 - .../cloud/quantum_v1alpha1/gapic_version.py | 16 ----- .../cirq_google/engine/abstract_engine.py | 32 --------- .../cirq_google/engine/abstract_processor.py | 32 --------- .../cirq_google/engine/engine_processor.py | 23 ++----- .../engine/engine_processor_test.py | 69 ++++++++----------- cirq-google/cirq_google/engine/engine_test.py | 6 +- .../cirq_google/engine/processor_config.py | 25 +++---- .../engine/processor_config_test.py | 20 ++---- 10 files changed, 49 insertions(+), 193 deletions(-) delete mode 100755 cirq-google/cirq_google/cloud/quantum/gapic_version.py delete mode 100755 cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py diff --git a/cirq-google/cirq_google/cloud/quantum/gapic_version.py b/cirq-google/cirq_google/cloud/quantum/gapic_version.py deleted file mode 100755 index 20a9cd975b0..00000000000 --- a/cirq-google/cirq_google/cloud/quantum/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py index 59b88e65999..6619a386edc 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py @@ -13,9 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from . import gapic_version as package_version - -__version__ = package_version.__version__ from .services.quantum_engine_service import QuantumEngineServiceClient diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py deleted file mode 100755 index 20a9cd975b0..00000000000 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index fca1caa768a..2927c7c55d1 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -139,35 +139,3 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: processor_id: String identifier, or list of string identifiers, determining which processors may be used when sampling. """ - - @abc.abstractmethod - def get_processor_config_from_snapshot( - self, processor_id: str, snapshot_id: str, config_alias: str = 'default' - ) -> processor_config.ProcessorConfig | None: - """Returns a ProcessorConfig from this project and the given processor id. - - Args: - processor_id: The processor unique identifier. - snapshot_id: The unique identifier for the snapshot. - config_alias: The identifier for the config. - - Returns: - The ProcessorConfig from this project and processor. - """ - - @abc.abstractmethod - def get_processor_config_from_run( - self, processor_id: str, run_name: str = 'default', config_alias: str = 'default' - ) -> processor_config.ProcessorConfig | None: - """Returns a ProcessorConfig from this project and the given processor id. - - If no run_name is provided, the config from the most recent run is returned. - - Args: - processor_id: The processor unique identifier. - run_name: The unique identifier for the automation run. - config_alias: The identifier for the config. - - Returns: - The ProcessorConfig from this project and processor. - """ diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 5817ae4ae61..7d22a27d2a6 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -378,35 +378,3 @@ def get_schedule( Returns: Schedule time slots. """ - - @abc.abstractmethod - def get_config_from_run( - self, run_name: str = 'default', config_alias: str = 'default' - ) -> processor_config.ProcessorConfig | None: - """Retrieves a ProcessorConfig from an automation run. - - If no run name is provided, the config from the most recent run - is returned. - - Args: - processor_id: The processor unique identifier. - config_alias: The quantum processor's unique identifier. - run_name: The automation run name. Use 'default' - if none id provided. - - Returns: The quantum processor config. - """ - - @abc.abstractmethod - def get_config_from_snapshot( - self, snapshot_id: str, config_alias: str = 'default' - ) -> processor_config.ProcessorConfig | None: - """Retrieves a ProcessorConfig from a given snapshot id. - - Args: - processor_id: The processor unique identifier. - config_alias: The quantum processor's unique identifier. - snapshot_id: The snapshot's unique identifier. - - Returns: The quantum processor config. - """ diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 4fe827d602d..edf2bc98b27 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -519,19 +519,10 @@ def get_config_from_run( Returns: The quantum processor config. """ - response = self.context.client.get_quantum_processor_config_from_run( - project_id=self.project_id, - processor_id=self.processor_id, - run_name=run_name, - config_alias=config_alias, + return self.engine().get_processor_config_from_run( + processor_id=self.processor_id, run_name=run_name, config_alias=config_alias ) - if response: - return processor_config.ProcessorConfig( - quantum_processor_config=response, run_name=run_name - ) - return None - def get_config_from_snapshot( self, snapshot_id: str, config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: @@ -547,15 +538,9 @@ def get_config_from_snapshot( Raises: EngineException: If the request to get the config fails. """ - response = self.context.client.get_quantum_processor_config_from_snapshot( - project_id=self.project_id, - processor_id=self.processor_id, - snapshot_id=snapshot_id, - config_alias=config_alias, + return self.engine().get_processor_config_from_snapshot( + processor_id=self.processor_id, snapshot_id=snapshot_id, config_alias=config_alias ) - if response: - return processor_config.ProcessorConfig(quantum_processor_config=response) - return None def __str__(self): return ( diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 4689020c70b..3435eaac65a 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1016,10 +1016,8 @@ def test_str(): assert str(processor) == 'EngineProcessor(project_id=\'a\', processor_id=\'p\')' -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' -) -def test_get_config_from_run(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_config_from_run(client): project_id = "test_project_id" processor_id = "test_proc_id" run_name = "test_run_name" @@ -1046,7 +1044,7 @@ def test_get_config_from_run(get_quantum_config): device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT), ) - get_quantum_config.return_value = quantum_config + client().get_quantum_processor_config_from_run_async.return_value = quantum_config expected_config = ProcessorConfig(quantum_processor_config=quantum_config, run_name=run_name) processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() @@ -1054,24 +1052,21 @@ def test_get_config_from_run(get_quantum_config): actual_config = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_run_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name=run_name, config_alias=config_alias, ) - assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_alias == config_alias + assert actual_config.config_name == config_alias assert actual_config.run_name == run_name assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' -) -def test_get_default_config_from_run(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_default_config_from_run(client): project_id = "test_project_id" processor_id = "test_proc_id" name = ( @@ -1095,22 +1090,20 @@ def test_get_default_config_from_run(get_quantum_config): device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT), ) - get_quantum_config.return_value = quantum_config + client().get_quantum_processor_config_from_run_async.return_value = quantum_config processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() ) _ = processor.get_config_from_run() - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_run_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name='default', config_alias='default' ) -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' -) -def test_get_config_from_snapshot(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_config_from_snapshot(client): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" @@ -1137,7 +1130,7 @@ def test_get_config_from_snapshot(get_quantum_config): device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT), ) - get_quantum_config.return_value = quantum_config + client().get_quantum_processor_config_from_snapshot_async.return_value = quantum_config expected_config = ProcessorConfig(quantum_processor_config=quantum_config) processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() @@ -1147,25 +1140,22 @@ def test_get_config_from_snapshot(get_quantum_config): config_alias=config_alias, snapshot_id=snapshot_id ) - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_snapshot_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_alias=config_alias, ) - assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_alias == config_alias + assert actual_config.config_name == config_alias assert actual_config.run_name == '' assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' -) -def test_get_default_config_from_snapshot(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_default_config_from_snapshot(client): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" @@ -1191,7 +1181,7 @@ def test_get_default_config_from_snapshot(get_quantum_config): device_specification=util.pack_any(device_spec), characterization=util.pack_any(_METRIC_SNAPSHOT), ) - get_quantum_config.return_value = quantum_config + client().get_quantum_processor_config_from_snapshot_async.return_value = quantum_config expected_config = ProcessorConfig(quantum_processor_config=quantum_config) processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() @@ -1199,31 +1189,28 @@ def test_get_default_config_from_snapshot(get_quantum_config): actual_config = processor.get_config_from_snapshot(snapshot_id=snapshot_id) - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_snapshot_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, config_alias='default', ) - assert actual_config.project_id == expected_config.project_id assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_alias == 'default' + assert actual_config.config_name == 'default' assert actual_config.run_name == '' assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_snapshot_async' -) -def test_get_config_from_snapshot_not_found(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_config_from_snapshot_not_found(client): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" config_alias = "test_config_alias" - get_quantum_config.return_value = None + client().get_quantum_processor_config_from_snapshot_async.return_value = None processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() @@ -1231,7 +1218,7 @@ def test_get_config_from_snapshot_not_found(get_quantum_config): result = processor.get_config_from_snapshot(config_alias=config_alias, snapshot_id=snapshot_id) - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_snapshot_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, @@ -1241,16 +1228,14 @@ def test_get_config_from_snapshot_not_found(get_quantum_config): assert result is None -@mock.patch( - 'cirq_google.engine.engine_client.EngineClient.get_quantum_processor_config_from_run_async' -) -def test_get_current_config_from_run_not_found(get_quantum_config): +@mock.patch('cirq_google.engine.engine_client.EngineClient', autospec=True) +def test_get_current_config_from_run_not_found(client): project_id = "test_project_id" processor_id = "test_proc_id" config_alias = "test_config_alias" run_name = 'test_run_name' - get_quantum_config.return_value = None + client().get_quantum_processor_config_from_run_async.return_value = None processor = cg.EngineProcessor( project_id=project_id, processor_id=processor_id, context=EngineContext() @@ -1258,7 +1243,7 @@ def test_get_current_config_from_run_not_found(get_quantum_config): result = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) - get_quantum_config.assert_called_once_with( + client().get_quantum_processor_config_from_run_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name=run_name, diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 8bfb1660c37..581bfe66cc6 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -942,10 +942,9 @@ def test_get_processor_config_from_snapshot(get_quantum_config_async): snapshot_id=snapshot_id, config_alias=config_alias, ) - assert result.project_id == project_id assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id - assert result.config_alias == config_alias + assert result.config_name == config_alias assert result.run_name == '' @@ -978,11 +977,10 @@ def test_get_processor_config_from_run(get_quantum_config_async): run_name=run_name, config_alias=config_alias, ) - assert result.project_id == project_id assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id assert result.run_name == run_name - assert result.config_alias == config_alias + assert result.config_name == config_alias @mock.patch( diff --git a/cirq-google/cirq_google/engine/processor_config.py b/cirq-google/cirq_google/engine/processor_config.py index cbf99835d99..a336ce55824 100644 --- a/cirq-google/cirq_google/engine/processor_config.py +++ b/cirq-google/cirq_google/engine/processor_config.py @@ -26,18 +26,20 @@ class ProcessorConfig: - """Representation of a quantum processor configuration + """Representation of a quantum processor configuration. - Describes available qubits, gates, and calivration data associated with + Describes available qubits, gates, and calibration data associated with a processor configuration. - - Raise: - ValueError: If quantum_processor_config is contains incompatible types. """ def __init__( self, *, quantum_processor_config: quantum.QuantumProcessorConfig, run_name: str = '' ) -> None: + """Contructs a Processor Config. + + Args: + quantum_processor_config: The quantum processor config. + """ self._quantum_processor_config = quantum_processor_config self._run_name = run_name self._grid_device = cg.GridDevice.from_proto( @@ -78,12 +80,6 @@ def run_name(self) -> str: """The run that generated this config if avaiable.""" return self._run_name - @property - def project_id(self) -> str: - """The project that contains this config.""" - parts = self._quantum_processor_config.name.split('/') - return parts[1] - @property def processor_id(self) -> str: """The processor id for this config.""" @@ -91,17 +87,16 @@ def processor_id(self) -> str: return parts[3] @property - def config_alias(self) -> str: + def config_name(self) -> str: """The unique identifier for this config.""" parts = self._quantum_processor_config.name.split('/') return parts[-1] def __repr__(self) -> str: return ( - f'cirq_google.ProcessorConfig' - f'(project_id={self.project_id}, ' + 'cirq_google.ProcessorConfig' f'processor_id={self.processor_id}, ' f'snapshot_id={self.snapshot_id}, ' f'run_name={self.run_name} ' - f'config_alias={self.config_alias}' + f'config_name={self.config_name}' ) diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index 06dc9aa0d75..d09e87e5514 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -48,7 +48,7 @@ _PROCESSOR_ID = 'test_processor_id' _PROJECT_ID = 'test_project_id' _SNAPSHOT_ID = 'test_snapshot_id' -_CONFIG_ALIAS = 'test_CONFIG_ALIAS' +_CONFIG_ALIAS = 'test_config_name' _VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ALIAS}', @@ -95,12 +95,6 @@ def test_processor_config_calibration(): assert config.calibration == cg.Calibration(_METRIC_SNAPSHOT) -def test_processor_project_id(): - config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - - assert config.project_id == _PROJECT_ID - - def test_processor_processor_id(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) @@ -110,18 +104,17 @@ def test_processor_processor_id(): def test_processor_CONFIG_ALIAS(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - assert config.config_alias == _CONFIG_ALIAS + assert config.config_name == _CONFIG_ALIAS def test_processor_config_repr(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) expected_repr = ( - f'cirq_google.ProcessorConfig' - f'(project_id={_PROJECT_ID}, ' + 'cirq_google.ProcessorConfig' f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={""} ' - f'config_alias={_CONFIG_ALIAS}' + f'config_name={_CONFIG_ALIAS}' ) assert repr(config) == expected_repr @@ -133,12 +126,11 @@ def test_processor_config_repr_with_run_name(): quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG, run_name=run_name ) expected_repr = ( - f'cirq_google.ProcessorConfig' - f'(project_id={_PROJECT_ID}, ' + 'cirq_google.ProcessorConfig' f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={run_name} ' - f'config_alias={_CONFIG_ALIAS}' + f'config_name={_CONFIG_ALIAS}' ) assert repr(config) == expected_repr From cd8164601e559bc10fc14f109f398fd290ac4254 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 22 Aug 2025 22:32:59 +0000 Subject: [PATCH 29/37] Remove unused imports. --- cirq-google/cirq_google/engine/abstract_engine.py | 1 - cirq-google/cirq_google/engine/abstract_processor.py | 1 - cirq-google/cirq_google/engine/engine.py | 2 -- cirq-google/cirq_google/engine/engine_processor.py | 3 --- 4 files changed, 7 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 2927c7c55d1..80d85dfe177 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -30,7 +30,6 @@ abstract_job, abstract_processor, abstract_program, - processor_config, ) VALID_DATE_TYPE = datetime.datetime | datetime.date diff --git a/cirq-google/cirq_google/engine/abstract_processor.py b/cirq-google/cirq_google/engine/abstract_processor.py index 7d22a27d2a6..64cfe92f986 100644 --- a/cirq-google/cirq_google/engine/abstract_processor.py +++ b/cirq-google/cirq_google/engine/abstract_processor.py @@ -35,7 +35,6 @@ import cirq_google.engine.abstract_engine as abstract_engine import cirq_google.engine.abstract_job as abstract_job import cirq_google.engine.calibration as calibration - import cirq_google.engine.processor_config as processor_config class AbstractProcessor(abc.ABC): diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 1e6db9c858e..4db80cc9caa 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -667,8 +667,6 @@ async def get_processor_config_from_run_async( ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. - If no run_name is provided, the config from the most recent run is returned. - Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index edf2bc98b27..fe077978f6e 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -508,9 +508,6 @@ def get_config_from_run( ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. - If no run name is provided, the config from the most recent run - is returned. - Args: processor_id: The processor unique identifier. config_alias: The quantum processor's unique identifier. From 4a03de10b6fc19aaaf8918a61a4efe4f06446889 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 22 Aug 2025 22:36:20 +0000 Subject: [PATCH 30/37] Update import format. --- cirq-google/cirq_google/engine/abstract_engine.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_engine.py b/cirq-google/cirq_google/engine/abstract_engine.py index 80d85dfe177..08fa878f589 100644 --- a/cirq-google/cirq_google/engine/abstract_engine.py +++ b/cirq-google/cirq_google/engine/abstract_engine.py @@ -26,11 +26,7 @@ if TYPE_CHECKING: import cirq from cirq_google.cloud import quantum - from cirq_google.engine import ( - abstract_job, - abstract_processor, - abstract_program, - ) + from cirq_google.engine import abstract_job, abstract_processor, abstract_program VALID_DATE_TYPE = datetime.datetime | datetime.date From 000ce5d1f3c06f35b36562dba18e3b6058405072 Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 25 Aug 2025 17:05:30 +0000 Subject: [PATCH 31/37] Update doc comments to mention default configs. --- cirq-google/cirq_google/engine/engine.py | 3 +++ cirq-google/cirq_google/engine/engine_processor.py | 7 ++++++- cirq-google/cirq_google/engine/engine_processor_test.py | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 4db80cc9caa..2278c95d772 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -667,6 +667,9 @@ async def get_processor_config_from_run_async( ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. + If no `run_name` and `config_alias` are specified, the inernally configured default config + is returned. + Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index fe077978f6e..0b06c1ab6e7 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -504,10 +504,13 @@ def get_schedule( return self.context.client.list_time_slots(self.project_id, self.processor_id, filter_str) def get_config_from_run( - self, run_name: str = 'default', config_alias: str = 'default' + self, run_name: str = 'current', config_alias: str = 'default' ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. + If no `run_name` and `config_alias` are specified, the inernally configured default config + is returned. + Args: processor_id: The processor unique identifier. config_alias: The quantum processor's unique identifier. @@ -525,6 +528,8 @@ def get_config_from_snapshot( ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. + If not `config_alias` is specified, the internally configured default is returned. + Args: processor_id: The processor unique identifier. config_alias: The quantum processor's unique identifier. diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 3435eaac65a..32188706932 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1098,7 +1098,7 @@ def test_get_default_config_from_run(client): _ = processor.get_config_from_run() client().get_quantum_processor_config_from_run_async.assert_called_once_with( - project_id=project_id, processor_id=processor_id, run_name='default', config_alias='default' + project_id=project_id, processor_id=processor_id, run_name='current', config_alias='default' ) From 4584bffba6cf74ef7cbfa45d10c754cc8a06d09c Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 25 Aug 2025 17:11:31 +0000 Subject: [PATCH 32/37] Remove N/A changes. --- cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py | 1 - dev_tools/notebooks/isolated_notebook_test.py | 2 -- 2 files changed, 3 deletions(-) diff --git a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py index 6619a386edc..42cd1d84046 100644 --- a/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py +++ b/cirq-google/cirq_google/cloud/quantum_v1alpha1/__init__.py @@ -14,7 +14,6 @@ # limitations under the License. # - from .services.quantum_engine_service import QuantumEngineServiceClient from .services.quantum_engine_service import QuantumEngineServiceAsyncClient diff --git a/dev_tools/notebooks/isolated_notebook_test.py b/dev_tools/notebooks/isolated_notebook_test.py index 0fd85606589..a4caadb3f2d 100644 --- a/dev_tools/notebooks/isolated_notebook_test.py +++ b/dev_tools/notebooks/isolated_notebook_test.py @@ -63,8 +63,6 @@ # temporary: need to fix QVM metrics and device spec 'docs/tutorials/google/spin_echoes.ipynb', 'docs/tutorials/google/visualizing_calibration_metrics.ipynb', - # temporary: allow name changes of keyword arguments in quantum engine interfaces to stabilize - 'docs/simulate/virtual_engine_interface.ipynb', ] SKIP_NOTEBOOKS += [ # notebooks that import the examples module which is not installed with cirq From a89213e9b360577f218ab38a07ae330ce277416b Mon Sep 17 00:00:00 2001 From: dyates Date: Mon, 25 Aug 2025 17:13:32 +0000 Subject: [PATCH 33/37] Remove changes to simulated_* engine files. --- .../cirq_google/engine/simulated_local_engine_test.py | 6 ------ cirq-google/cirq_google/engine/simulated_local_processor.py | 6 ------ 2 files changed, 12 deletions(-) diff --git a/cirq-google/cirq_google/engine/simulated_local_engine_test.py b/cirq-google/cirq_google/engine/simulated_local_engine_test.py index e3410f6f931..e4e78dad22a 100644 --- a/cirq-google/cirq_google/engine/simulated_local_engine_test.py +++ b/cirq-google/cirq_google/engine/simulated_local_engine_test.py @@ -71,12 +71,6 @@ def get_sampler(self, *args, **kwargs): def supported_languages(self, *args, **kwargs): pass - def get_config_from_run(self, *args, **kwargs): - pass - - def get_config_from_snapshot(self, *args, **kwargs): - pass - def list_programs( self, created_before: datetime.datetime | datetime.date | None = None, diff --git a/cirq-google/cirq_google/engine/simulated_local_processor.py b/cirq-google/cirq_google/engine/simulated_local_processor.py index dc301f237e7..8207d3292d1 100644 --- a/cirq-google/cirq_google/engine/simulated_local_processor.py +++ b/cirq-google/cirq_google/engine/simulated_local_processor.py @@ -235,9 +235,3 @@ async def run_sweep_async( ) self._programs[program_id].add_job(job_id, job) return job - - def get_config_from_run(self, run_name: str = 'default', config_alias: str = 'default'): - pass - - def get_config_from_snapshot(self, snapshot_id: str, config_id: str = 'default'): - pass From f9ef67a9db159d663936f37b90268a78cbeb0bb6 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 29 Aug 2025 17:53:02 +0000 Subject: [PATCH 34/37] Change `config_alias` to `config_name`. --- .../engine/abstract_local_engine.py | 12 ------- cirq-google/cirq_google/engine/engine.py | 14 ++++---- .../cirq_google/engine/engine_client.py | 20 +++++------ .../cirq_google/engine/engine_client_test.py | 28 +++++++-------- .../cirq_google/engine/engine_processor.py | 16 ++++----- .../engine/engine_processor_test.py | 36 +++++++++---------- cirq-google/cirq_google/engine/engine_test.py | 28 +++++++-------- .../engine/processor_config_test.py | 12 +++---- 8 files changed, 77 insertions(+), 89 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_engine.py b/cirq-google/cirq_google/engine/abstract_local_engine.py index 9df1d032b3f..d8140390e22 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine.py @@ -175,15 +175,3 @@ def get_sampler(self, processor_id: str | list[str]) -> cirq.Sampler: if not isinstance(processor_id, str): raise ValueError(f'Invalid processor {processor_id}') return self._processors[processor_id].get_sampler() - - def get_processor_config_from_snapshot( - self, processor_id: str, snapshot_id: str, config_alias: str = 'default' - ): - # TODO: Implement later as needed. - pass - - def get_processor_config_from_run( - self, processor_id: str, run_name: str = 'default', config_alias: str = 'default' - ): - # TODO: Implement later as needed. - pass diff --git a/cirq-google/cirq_google/engine/engine.py b/cirq-google/cirq_google/engine/engine.py index 2278c95d772..aedd6efb471 100644 --- a/cirq-google/cirq_google/engine/engine.py +++ b/cirq-google/cirq_google/engine/engine.py @@ -637,14 +637,14 @@ def get_sampler( ) async def get_processor_config_from_snapshot_async( - self, processor_id: str, snapshot_id: str, config_alias: str = 'default' + self, processor_id: str, snapshot_id: str, config_name: str = 'default' ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. Args: processor_id: The processor unique identifier. snapshot_id: The unique identifier for the snapshot. - config_alias: The identifier for the config. + config_name: The identifier for the config. Returns: The ProcessorConfig from this project and processor. @@ -654,7 +654,7 @@ async def get_processor_config_from_snapshot_async( project_id=self.project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias=config_alias, + config_name=config_name, ) if quantum_config: return processor_config.ProcessorConfig(quantum_processor_config=quantum_config) @@ -663,17 +663,17 @@ async def get_processor_config_from_snapshot_async( get_processor_config_from_snapshot = duet.sync(get_processor_config_from_snapshot_async) async def get_processor_config_from_run_async( - self, processor_id: str, run_name: str = 'current', config_alias: str = 'default' + self, processor_id: str, run_name: str = 'current', config_name: str = 'default' ) -> processor_config.ProcessorConfig | None: """Returns a ProcessorConfig from this project and the given processor id. - If no `run_name` and `config_alias` are specified, the inernally configured default config + If no `run_name` and `config_name` are specified, the inernally configured default config is returned. Args: processor_id: The processor unique identifier. run_name: The unique identifier for the automation run. - config_alias: The identifier for the config. + config_name: The identifier for the config. Returns: The ProcessorConfig from this project and processor. @@ -682,7 +682,7 @@ async def get_processor_config_from_run_async( project_id=self.project_id, processor_id=processor_id, run_name=run_name, - config_alias=config_alias, + config_name=config_name, ) if quantum_config: return processor_config.ProcessorConfig( diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 3a2da5b9ae2..0ec25da40d7 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1196,7 +1196,7 @@ async def _get_quantum_processor_config( raise async def get_quantum_processor_config_from_snapshot_async( - self, project_id: str, processor_id: str, snapshot_id: str, config_alias: str + self, project_id: str, processor_id: str, snapshot_id: str, config_name: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given snapshot id. @@ -1204,7 +1204,7 @@ async def get_quantum_processor_config_from_snapshot_async( project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. snapshot_id: The id of the snapshot that contains the quantum processor config. - config_alias: The id of the quantum processor config. + config_name: The id of the quantum processor config. Returns: The quantum procesor config or None if it does not exist. @@ -1216,7 +1216,7 @@ async def get_quantum_processor_config_from_snapshot_async( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias=config_alias, + config_name=config_name, ) return await self._get_quantum_processor_config(name) @@ -1225,14 +1225,14 @@ async def get_quantum_processor_config_from_snapshot_async( ) async def get_quantum_processor_config_from_run_async( - self, project_id: str, processor_id: str, run_name: str, config_alias: str + self, project_id: str, processor_id: str, run_name: str, config_name: str ) -> quantum.QuantumProcessorConfig | None: """Returns the QuantumProcessorConfig for the given run_name. Args: project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. - config_alias: The id of the quantum processor config. + config_name: The id of the quantum processor config. run_name: The run_name that contains the quantum processor config. Returns: @@ -1245,7 +1245,7 @@ async def get_quantum_processor_config_from_run_async( project_id=project_id, processor_id=processor_id, run_name=run_name, - config_alias=config_alias, + config_name=config_name, ) return await self._get_quantum_processor_config(name) @@ -1301,24 +1301,24 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: def _quantum_processor_name_with_snapshot_id( - project_id: str, processor_id: str, snapshot_id: str, config_alias: str + project_id: str, processor_id: str, snapshot_id: str, config_name: str ) -> str: return ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) def _quantum_processor_name_with_run_name( - project_id: str, processor_id: str, run_name: str, config_alias: str + project_id: str, processor_id: str, run_name: str, config_name: str ) -> str: return ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 36b6f48c137..09f9ac8f711 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1751,12 +1751,12 @@ def test_get_quantum_processor_config_from_snapshot(client_constructor, default_ project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) grpc_client = _setup_client_mock(client_constructor) @@ -1766,7 +1766,7 @@ def test_get_quantum_processor_config_from_snapshot(client_constructor, default_ actual_result = default_engine_client.get_quantum_processor_config_from_snapshot( project_id=project_id, processor_id=processor_id, - config_alias=config_alias, + config_name=config_name, snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1782,12 +1782,12 @@ def test_get_quantum_processor_config_from_snapshot_not_found( project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) grpc_client = _setup_client_mock(client_constructor) @@ -1796,7 +1796,7 @@ def test_get_quantum_processor_config_from_snapshot_not_found( actual_result = default_engine_client.get_quantum_processor_config_from_snapshot( project_id=project_id, processor_id=processor_id, - config_alias=config_alias, + config_name=config_name, snapshot_id=snapshot_id, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1816,7 +1816,7 @@ def test_get_quantum_processor_config_from_snapshot_exception( _ = default_engine_client.get_quantum_processor_config_from_snapshot( project_id="test_project_id", processor_id="test_processor_id", - config_alias="test_config_alias", + config_name="test_config_name", snapshot_id="test_snapshot_id", ) @@ -1827,12 +1827,12 @@ def test_get_quantum_processor_config_from_run(client_constructor, default_engin project_id = "test_project_id" processor_id = "test_processor_id" run_name = "test_run_name" - config_alias = "test_config_alias" + config_name = "test_config_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) grpc_client = _setup_client_mock(client_constructor) @@ -1842,7 +1842,7 @@ def test_get_quantum_processor_config_from_run(client_constructor, default_engin actual_result = default_engine_client.get_quantum_processor_config_from_run( project_id=project_id, processor_id=processor_id, - config_alias=config_alias, + config_name=config_name, run_name=run_name, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1856,12 +1856,12 @@ def test_get_quantum_processor_config_from_run_not_found(client_constructor, def project_id = "test_project_id" processor_id = "test_processor_id" run_name = "test_run_name" - config_alias = "test_config_alias" + config_name = "test_config_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) grpc_client = _setup_client_mock(client_constructor) grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') @@ -1869,7 +1869,7 @@ def test_get_quantum_processor_config_from_run_not_found(client_constructor, def actual_result = default_engine_client.get_quantum_processor_config_from_run( project_id=project_id, processor_id=processor_id, - config_alias=config_alias, + config_name=config_name, run_name=run_name, ) grpc_client.get_quantum_processor_config.assert_called_with( @@ -1887,6 +1887,6 @@ def test_get_quantum_processor_config_from_run_exception(client_constructor, def _ = default_engine_client.get_quantum_processor_config_from_run( project_id="test_project_id", processor_id="test_processor_id", - config_alias="test_config_alias", + config_name="test_config_name", run_name="test_run_name", ) diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 0b06c1ab6e7..772c44d298d 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -504,35 +504,35 @@ def get_schedule( return self.context.client.list_time_slots(self.project_id, self.processor_id, filter_str) def get_config_from_run( - self, run_name: str = 'current', config_alias: str = 'default' + self, run_name: str = 'current', config_name: str = 'default' ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from an automation run. - If no `run_name` and `config_alias` are specified, the inernally configured default config + If no `run_name` and `config_name` are specified, the inernally configured default config is returned. Args: processor_id: The processor unique identifier. - config_alias: The quantum processor's unique identifier. + config_name: The quantum processor's unique identifier. run_name: The automation run name. Use 'default' if none id provided. Returns: The quantum processor config. """ return self.engine().get_processor_config_from_run( - processor_id=self.processor_id, run_name=run_name, config_alias=config_alias + processor_id=self.processor_id, run_name=run_name, config_name=config_name ) def get_config_from_snapshot( - self, snapshot_id: str, config_alias: str = 'default' + self, snapshot_id: str, config_name: str = 'default' ) -> processor_config.ProcessorConfig | None: """Retrieves a ProcessorConfig from a given snapshot id. - If not `config_alias` is specified, the internally configured default is returned. + If not `config_name` is specified, the internally configured default is returned. Args: processor_id: The processor unique identifier. - config_alias: The quantum processor's unique identifier. + config_name: The quantum processor's unique identifier. snapshot_id: The snapshot's unique identifier. Returns: The quantum processor config. @@ -541,7 +541,7 @@ def get_config_from_snapshot( EngineException: If the request to get the config fails. """ return self.engine().get_processor_config_from_snapshot( - processor_id=self.processor_id, snapshot_id=snapshot_id, config_alias=config_alias + processor_id=self.processor_id, snapshot_id=snapshot_id, config_name=config_name ) def __str__(self): diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 32188706932..408c2bed639 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1021,12 +1021,12 @@ def test_get_config_from_run(client): project_id = "test_project_id" processor_id = "test_proc_id" run_name = "test_run_name" - config_alias = "test_config_alias" + config_name = "test_config_name" name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configAutomationRuns/{run_name}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) device_spec = v2.device_pb2.DeviceSpecification( @@ -1050,16 +1050,16 @@ def test_get_config_from_run(client): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - actual_config = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) + actual_config = processor.get_config_from_run(config_name=config_name, run_name=run_name) client().get_quantum_processor_config_from_run_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name=run_name, - config_alias=config_alias, + config_name=config_name, ) assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_name == config_alias + assert actual_config.config_name == config_name assert actual_config.run_name == run_name assert actual_config.effective_device == expected_config.effective_device assert actual_config.calibration == expected_config.calibration @@ -1098,7 +1098,7 @@ def test_get_default_config_from_run(client): _ = processor.get_config_from_run() client().get_quantum_processor_config_from_run_async.assert_called_once_with( - project_id=project_id, processor_id=processor_id, run_name='current', config_alias='default' + project_id=project_id, processor_id=processor_id, run_name='current', config_name='default' ) @@ -1107,12 +1107,12 @@ def test_get_config_from_snapshot(client): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) device_spec = v2.device_pb2.DeviceSpecification( @@ -1137,17 +1137,17 @@ def test_get_config_from_snapshot(client): ) actual_config = processor.get_config_from_snapshot( - config_alias=config_alias, snapshot_id=snapshot_id + config_name=config_name, snapshot_id=snapshot_id ) client().get_quantum_processor_config_from_snapshot_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias=config_alias, + config_name=config_name, ) assert actual_config.processor_id == expected_config.processor_id - assert actual_config.config_name == config_alias + assert actual_config.config_name == config_name assert actual_config.run_name == '' assert actual_config.snapshot_id == snapshot_id assert actual_config.effective_device == expected_config.effective_device @@ -1193,7 +1193,7 @@ def test_get_default_config_from_snapshot(client): project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias='default', + config_name='default', ) assert actual_config.processor_id == expected_config.processor_id assert actual_config.config_name == 'default' @@ -1208,7 +1208,7 @@ def test_get_config_from_snapshot_not_found(client): project_id = "test_project_id" processor_id = "test_proc_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" client().get_quantum_processor_config_from_snapshot_async.return_value = None @@ -1216,13 +1216,13 @@ def test_get_config_from_snapshot_not_found(client): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_from_snapshot(config_alias=config_alias, snapshot_id=snapshot_id) + result = processor.get_config_from_snapshot(config_name=config_name, snapshot_id=snapshot_id) client().get_quantum_processor_config_from_snapshot_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias=config_alias, + config_name=config_name, ) assert result is None @@ -1232,7 +1232,7 @@ def test_get_config_from_snapshot_not_found(client): def test_get_current_config_from_run_not_found(client): project_id = "test_project_id" processor_id = "test_proc_id" - config_alias = "test_config_alias" + config_name = "test_config_name" run_name = 'test_run_name' client().get_quantum_processor_config_from_run_async.return_value = None @@ -1241,12 +1241,12 @@ def test_get_current_config_from_run_not_found(client): project_id=project_id, processor_id=processor_id, context=EngineContext() ) - result = processor.get_config_from_run(config_alias=config_alias, run_name=run_name) + result = processor.get_config_from_run(config_name=config_name, run_name=run_name) client().get_quantum_processor_config_from_run_async.assert_called_once_with( project_id=project_id, processor_id=processor_id, run_name=run_name, - config_alias=config_alias, + config_name=config_name, ) assert result is None diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index 581bfe66cc6..abd040de975 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -921,30 +921,30 @@ def test_get_processor_config_from_snapshot(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_from_snapshot( - processor_id=processor_id, snapshot_id=snapshot_id, config_alias=config_alias + processor_id=processor_id, snapshot_id=snapshot_id, config_name=config_name ) get_quantum_config_async.assert_called_with( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, - config_alias=config_alias, + config_name=config_name, ) assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id - assert result.config_name == config_alias + assert result.config_name == config_name assert result.run_name == '' @@ -955,32 +955,32 @@ def test_get_processor_config_from_run(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" run_name = "test_run_name" resource_name = ( f'projects/{project_id}/' f'processors/{processor_id}/' f'configSnapshots/{snapshot_id}/' - f'configs/{config_alias}' + f'configs/{config_name}' ) quantum_confg = quantum.QuantumProcessorConfig(name=resource_name) get_quantum_config_async.return_value = quantum_confg result = cg.Engine(project_id=project_id).get_processor_config_from_run( - processor_id=processor_id, run_name=run_name, config_alias=config_alias + processor_id=processor_id, run_name=run_name, config_name=config_name ) get_quantum_config_async.assert_called_with( project_id=project_id, processor_id=processor_id, run_name=run_name, - config_alias=config_alias, + config_name=config_name, ) assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id assert result.run_name == run_name - assert result.config_name == config_alias + assert result.config_name == config_name @mock.patch( @@ -990,12 +990,12 @@ def test_get_processor_config_from_snapshot_none(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" snapshot_id = "test_snapshot_id" - config_alias = "test_config_alias" + config_name = "test_config_name" get_quantum_config_async.return_value = None result = cg.Engine(project_id=project_id).get_processor_config_from_snapshot( - processor_id=processor_id, snapshot_id=snapshot_id, config_alias=config_alias + processor_id=processor_id, snapshot_id=snapshot_id, config_name=config_name ) assert result is None @@ -1007,13 +1007,13 @@ def test_get_processor_config_from_snapshot_none(get_quantum_config_async): def test_get_processor_config_from_run_nine(get_quantum_config_async): project_id = "test_project_id" processor_id = "test_processor_id" - config_alias = "test_config_alias" + config_name = "test_config_name" run_name = "test_run_name" get_quantum_config_async.return_value = None result = cg.Engine(project_id=project_id).get_processor_config_from_run( - processor_id=processor_id, run_name=run_name, config_alias=config_alias + processor_id=processor_id, run_name=run_name, config_name=config_name ) assert result is None diff --git a/cirq-google/cirq_google/engine/processor_config_test.py b/cirq-google/cirq_google/engine/processor_config_test.py index d09e87e5514..fcba9a4ef58 100644 --- a/cirq-google/cirq_google/engine/processor_config_test.py +++ b/cirq-google/cirq_google/engine/processor_config_test.py @@ -48,10 +48,10 @@ _PROCESSOR_ID = 'test_processor_id' _PROJECT_ID = 'test_project_id' _SNAPSHOT_ID = 'test_snapshot_id' -_CONFIG_ALIAS = 'test_config_name' +_CONFIG_NAME = 'test_config_name' _VALID_QUANTUM_PROCESSOR_CONFIG = quantum.QuantumProcessorConfig( - name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_ALIAS}', + name=f'projects/{_PROJECT_ID}/processors/{_PROCESSOR_ID}/configSnapshots/{_SNAPSHOT_ID}/configs/{_CONFIG_NAME}', device_specification=util.pack_any(_DEVICE_SPEC), characterization=util.pack_any(_METRIC_SNAPSHOT), ) @@ -101,10 +101,10 @@ def test_processor_processor_id(): assert config.processor_id == _PROCESSOR_ID -def test_processor_CONFIG_ALIAS(): +def test_processor_CONFIG_NAME(): config = cg.engine.ProcessorConfig(quantum_processor_config=_VALID_QUANTUM_PROCESSOR_CONFIG) - assert config.config_name == _CONFIG_ALIAS + assert config.config_name == _CONFIG_NAME def test_processor_config_repr(): @@ -114,7 +114,7 @@ def test_processor_config_repr(): f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={""} ' - f'config_name={_CONFIG_ALIAS}' + f'config_name={_CONFIG_NAME}' ) assert repr(config) == expected_repr @@ -130,7 +130,7 @@ def test_processor_config_repr_with_run_name(): f'processor_id={_PROCESSOR_ID}, ' f'snapshot_id={_SNAPSHOT_ID}, ' f'run_name={run_name} ' - f'config_name={_CONFIG_ALIAS}' + f'config_name={_CONFIG_NAME}' ) assert repr(config) == expected_repr From 32ad541f744e2a46856aa8683c2ebf1ebcde66c1 Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 29 Aug 2025 17:57:18 +0000 Subject: [PATCH 35/37] Remove config functions from local processor unit test. --- .../cirq_google/engine/abstract_local_processor_test.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_processor_test.py b/cirq-google/cirq_google/engine/abstract_local_processor_test.py index 72dc88a2e01..890c435d7ec 100644 --- a/cirq-google/cirq_google/engine/abstract_local_processor_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_processor_test.py @@ -71,12 +71,6 @@ def list_programs(self, *args, **kwargs): def get_program(self, *args, **kwargs): pass - def get_config_from_run(self, run_name: str = "default", config_alias: str = 'default'): - pass - - def get_config_from_snapshot(self, snapshot_id: str, config_alias: str = 'default'): - pass - def test_datetime(): recovery_time = datetime.datetime.now() From 2ef680521f00bde0650859cd065de0debca16a5d Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 29 Aug 2025 18:04:05 +0000 Subject: [PATCH 36/37] Format fixes. --- cirq-google/cirq_google/engine/engine_client_test.py | 10 ++-------- .../cirq_google/engine/engine_processor_test.py | 10 ++-------- cirq-google/cirq_google/engine/engine_test.py | 5 +---- 3 files changed, 5 insertions(+), 20 deletions(-) diff --git a/cirq-google/cirq_google/engine/engine_client_test.py b/cirq-google/cirq_google/engine/engine_client_test.py index 09f9ac8f711..61fa5b5f3b0 100644 --- a/cirq-google/cirq_google/engine/engine_client_test.py +++ b/cirq-google/cirq_google/engine/engine_client_test.py @@ -1840,10 +1840,7 @@ def test_get_quantum_processor_config_from_run(client_constructor, default_engin grpc_client.get_quantum_processor_config.return_value = expected_result actual_result = default_engine_client.get_quantum_processor_config_from_run( - project_id=project_id, - processor_id=processor_id, - config_name=config_name, - run_name=run_name, + project_id=project_id, processor_id=processor_id, config_name=config_name, run_name=run_name ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) @@ -1867,10 +1864,7 @@ def test_get_quantum_processor_config_from_run_not_found(client_constructor, def grpc_client.get_quantum_processor_config.side_effect = exceptions.NotFound('not found') actual_result = default_engine_client.get_quantum_processor_config_from_run( - project_id=project_id, - processor_id=processor_id, - config_name=config_name, - run_name=run_name, + project_id=project_id, processor_id=processor_id, config_name=config_name, run_name=run_name ) grpc_client.get_quantum_processor_config.assert_called_with( quantum.GetQuantumProcessorConfigRequest(name=resource_name) diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index 408c2bed639..d359271e5da 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -1053,10 +1053,7 @@ def test_get_config_from_run(client): actual_config = processor.get_config_from_run(config_name=config_name, run_name=run_name) client().get_quantum_processor_config_from_run_async.assert_called_once_with( - project_id=project_id, - processor_id=processor_id, - run_name=run_name, - config_name=config_name, + project_id=project_id, processor_id=processor_id, run_name=run_name, config_name=config_name ) assert actual_config.processor_id == expected_config.processor_id assert actual_config.config_name == config_name @@ -1244,9 +1241,6 @@ def test_get_current_config_from_run_not_found(client): result = processor.get_config_from_run(config_name=config_name, run_name=run_name) client().get_quantum_processor_config_from_run_async.assert_called_once_with( - project_id=project_id, - processor_id=processor_id, - run_name=run_name, - config_name=config_name, + project_id=project_id, processor_id=processor_id, run_name=run_name, config_name=config_name ) assert result is None diff --git a/cirq-google/cirq_google/engine/engine_test.py b/cirq-google/cirq_google/engine/engine_test.py index abd040de975..99e75208981 100644 --- a/cirq-google/cirq_google/engine/engine_test.py +++ b/cirq-google/cirq_google/engine/engine_test.py @@ -972,10 +972,7 @@ def test_get_processor_config_from_run(get_quantum_config_async): ) get_quantum_config_async.assert_called_with( - project_id=project_id, - processor_id=processor_id, - run_name=run_name, - config_name=config_name, + project_id=project_id, processor_id=processor_id, run_name=run_name, config_name=config_name ) assert result.processor_id == processor_id assert result.snapshot_id == snapshot_id From 54cc85c13ffe54e114acb26f38ad0838388742da Mon Sep 17 00:00:00 2001 From: dyates Date: Fri, 12 Sep 2025 17:12:07 +0000 Subject: [PATCH 37/37] Adress final comments; Use existing id functions; Remove unused config functions from abstract classes. --- .../engine/abstract_local_engine_test.py | 6 ------ cirq-google/cirq_google/engine/engine_client.py | 14 ++++++-------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/cirq-google/cirq_google/engine/abstract_local_engine_test.py b/cirq-google/cirq_google/engine/abstract_local_engine_test.py index 64ef0d65822..000915d61ca 100644 --- a/cirq-google/cirq_google/engine/abstract_local_engine_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_engine_test.py @@ -81,12 +81,6 @@ def list_programs( def get_program(self, program_id: str) -> AbstractProgram: return self._programs[program_id] - def get_config_from_run(self, *args, **kwargs): - pass - - def get_config_from_snapshot(self, *args, **kwargs): - pass - class NothingEngine(AbstractLocalEngine): """Engine for Testing.""" diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 0ec25da40d7..baa32be5239 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -1212,7 +1212,7 @@ async def get_quantum_processor_config_from_snapshot_async( Raises: EngineException: If the request to get the config fails. """ - name = _quantum_processor_name_with_snapshot_id( + name = _quantum_processor_config_name_from_snapshot_id( project_id=project_id, processor_id=processor_id, snapshot_id=snapshot_id, @@ -1241,7 +1241,7 @@ async def get_quantum_processor_config_from_run_async( Raises: EngineException: If the request to get the config fails. """ - name = _quantum_processor_name_with_run_name( + name = _quantum_processor_config_name_from_run_name( project_id=project_id, processor_id=processor_id, run_name=run_name, @@ -1300,23 +1300,21 @@ def _ids_from_calibration_name(calibration_name: str) -> tuple[str, str, int]: return parts[1], parts[3], int(parts[5]) -def _quantum_processor_name_with_snapshot_id( +def _quantum_processor_config_name_from_snapshot_id( project_id: str, processor_id: str, snapshot_id: str, config_name: str ) -> str: return ( - f'projects/{project_id}/' - f'processors/{processor_id}/' + f'{_processor_name_from_ids(project_id, processor_id)}/' f'configSnapshots/{snapshot_id}/' f'configs/{config_name}' ) -def _quantum_processor_name_with_run_name( +def _quantum_processor_config_name_from_run_name( project_id: str, processor_id: str, run_name: str, config_name: str ) -> str: return ( - f'projects/{project_id}/' - f'processors/{processor_id}/' + f'{_processor_name_from_ids(project_id, processor_id)}/' f'configAutomationRuns/{run_name}/' f'configs/{config_name}' )