Skip to content

Commit 492d6c6

Browse files
maffootonybruguier
authored andcommitted
Refactor qcs_notebook to use application default creds (quantumlib#5045)
Review: @95-martin-orion
1 parent 5d35706 commit 492d6c6

File tree

2 files changed

+49
-62
lines changed

2 files changed

+49
-62
lines changed

cirq-google/cirq_google/engine/qcs_notebook.py

Lines changed: 47 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import os
1615
import dataclasses
1716
from typing import Union, Optional
1817

@@ -24,8 +23,7 @@
2423
Sycamore,
2524
SQRT_ISWAP_INV_PARAMETERS,
2625
PhasedFSimCharacterization,
27-
get_engine_sampler,
28-
get_engine_device,
26+
get_engine,
2927
)
3028

3129

@@ -40,9 +38,12 @@ def is_simulator(self):
4038
return isinstance(self.sampler, PhasedFSimEngineSimulator)
4139

4240

41+
# Disable missing-raises-doc lint check, since pylint gets confused
42+
# by exceptions that are raised and caught within this function.
43+
# pylint: disable=missing-raises-doc
4344
def get_qcs_objects_for_notebook(
4445
project_id: Optional[str] = None, processor_id: Optional[str] = None
45-
) -> QCSObjectsForNotebook:
46+
) -> QCSObjectsForNotebook: # pragma: nocover
4647
"""Authenticates on Google Cloud, can return a Device and Simulator.
4748
4849
Args:
@@ -57,68 +58,54 @@ def get_qcs_objects_for_notebook(
5758
An instance of DeviceSamplerInfo.
5859
"""
5960

60-
# Converting empty strings to None for form field inputs
61-
if project_id == "":
62-
project_id = None
63-
if processor_id == "":
64-
processor_id = None
65-
66-
google_cloud_signin_failed: bool = False
67-
if project_id is None:
68-
if 'GOOGLE_CLOUD_PROJECT' not in os.environ:
69-
print("No project_id provided and environment variable GOOGLE_CLOUD_PROJECT not set.")
70-
google_cloud_signin_failed = True
71-
else: # pragma: no cover
72-
os.environ['GOOGLE_CLOUD_PROJECT'] = project_id
73-
74-
# Following code runs the user through the Colab OAuth process.
75-
76-
# Checks for Google Application Default Credentials and runs
77-
# interactive login if the notebook is executed in Colab. In
78-
# case the notebook is executed in Jupyter notebook or other
79-
# IPython runtimes, no interactive login is provided, it is
80-
# assumed that the `GOOGLE_APPLICATION_CREDENTIALS` env var is
81-
# set or `gcloud auth application-default login` was executed
82-
# already. For more information on using Application Default Credentials
83-
# see https://cloud.google.com/docs/authentication/production
84-
85-
in_colab = False
61+
# Check for Google Application Default Credentials and run
62+
# interactive login if the notebook is executed in Colab. In
63+
# case the notebook is executed in Jupyter notebook or other
64+
# IPython runtimes, no interactive login is provided, it is
65+
# assumed that the `GOOGLE_APPLICATION_CREDENTIALS` env var is
66+
# set or `gcloud auth application-default login` was executed
67+
# already. For more information on using Application Default Credentials
68+
# see https://cloud.google.com/docs/authentication/production
69+
try:
70+
from google.colab import auth
71+
except ImportError:
72+
print("Not running in a colab kernel. Will use Application Default Credentials.")
73+
else:
74+
print("Getting OAuth2 credentials.")
75+
print("Press enter after entering the verification code.")
8676
try:
87-
from IPython import get_ipython
88-
89-
in_colab = 'google.colab' in str(get_ipython())
90-
91-
if in_colab:
92-
from google.colab import auth
77+
auth.authenticate_user(clear_output=False)
78+
print("Authentication complete.")
79+
except Exception as exc:
80+
print(f"Authentication failed: {exc}")
9381

94-
print("Getting OAuth2 credentials.")
95-
print("Press enter after entering the verification code.")
96-
auth.authenticate_user(clear_output=False)
97-
print("Authentication complete.")
98-
else:
99-
print(
100-
"Notebook isn't executed with Colab, assuming "
101-
"Application Default Credentials are setup."
102-
)
103-
except:
104-
pass
105-
106-
# End of Google Colab Authentication segment
107-
108-
device: cirq.Device
82+
# Attempt to connect to the Quantum Engine API, and use a simulator if unable to connect.
10983
sampler: Union[PhasedFSimEngineSimulator, QuantumEngineSampler]
110-
if google_cloud_signin_failed or processor_id is None:
84+
try:
85+
engine = get_engine(project_id)
86+
if processor_id:
87+
processor = engine.get_processor(processor_id)
88+
else:
89+
processors = engine.list_processors()
90+
if not processors:
91+
raise ValueError("No processors available.")
92+
processor = processors[0]
93+
print(f"Available processors: {[p.processor_id for p in processors]}")
94+
print(f"Using processor: {processor.processor_id}")
95+
device = processor.get_device()
96+
sampler = processor.get_sampler()
97+
signed_in = True
98+
except Exception as exc:
99+
print(f"Unable to connect to quantum engine: {exc}")
111100
print("Using a noisy simulator.")
112101
sampler = PhasedFSimEngineSimulator.create_with_random_gaussian_sqrt_iswap(
113102
mean=SQRT_ISWAP_INV_PARAMETERS,
114103
sigma=PhasedFSimCharacterization(theta=0.01, zeta=0.10, chi=0.01, gamma=0.10, phi=0.02),
115104
)
116105
device = Sycamore
117-
else: # pragma: no cover
118-
device = get_engine_device(processor_id)
119-
sampler = get_engine_sampler(processor_id, gate_set_name="sqrt_iswap")
120-
return QCSObjectsForNotebook(
121-
device=device,
122-
sampler=sampler,
123-
signed_in=not google_cloud_signin_failed,
124-
)
106+
signed_in = False
107+
108+
return QCSObjectsForNotebook(device=device, sampler=sampler, signed_in=signed_in)
109+
110+
111+
# pylint: enable=missing-raises-doc

cirq-google/cirq_google/engine/qcs_notebook_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
def test_get_device_sampler():
2020
result = get_qcs_objects_for_notebook()
2121
assert result.device is cg.Sycamore
22-
assert result.signed_in is False
23-
assert type(result.sampler) is cg.PhasedFSimEngineSimulator
22+
assert not result.signed_in
23+
assert isinstance(result.sampler, cg.PhasedFSimEngineSimulator)
2424
assert result.is_simulator
2525

2626
result = get_qcs_objects_for_notebook("", "")

0 commit comments

Comments
 (0)