This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 143
/
ibmqfactory.py
486 lines (399 loc) · 19.9 KB
/
ibmqfactory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Factory and Account manager for IBM Quantum Experience."""
import logging
from typing import Dict, List, Union, Callable, Optional, Any
from collections import OrderedDict
import traceback
from .accountprovider import AccountProvider
from .api.clients import AuthClient, VersionClient
from .credentials import Credentials, discover_credentials
from .credentials.hubgroupproject import HubGroupProject
from .credentials.configrc import (read_credentials_from_qiskitrc,
remove_credentials,
store_credentials)
from .credentials.exceptions import HubGroupProjectInvalidStateError
from .credentials.updater import update_credentials
from .exceptions import (IBMQAccountError, IBMQAccountValueError, IBMQProviderError,
IBMQAccountCredentialsInvalidFormat, IBMQAccountCredentialsNotFound,
IBMQAccountCredentialsInvalidUrl, IBMQAccountCredentialsInvalidToken,
IBMQAccountMultipleCredentialsFound)
logger = logging.getLogger(__name__)
QX_AUTH_URL = 'https://auth.quantum-computing.ibm.com/api'
UPDATE_ACCOUNT_TEXT = "Please update your accounts and programs by following the " \
"instructions here: https://github.com/Qiskit/qiskit-ibmq-provider#" \
"updating-to-the-new-ibm-q-experience "
class IBMQFactory:
"""Factory and account manager for IBM Quantum Experience."""
def __init__(self) -> None:
"""IBMQFactory constructor."""
self._credentials = None # type: Optional[Credentials]
self._providers = OrderedDict() # type: Dict[HubGroupProject, AccountProvider]
# Account management functions.
def enable_account(
self,
token: str,
url: str = QX_AUTH_URL,
hub: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None,
**kwargs: Any
) -> Optional[AccountProvider]:
"""Authenticate against IBM Quantum Experience for use during the session.
Note:
With version 0.4 of this ``qiskit-ibmq-provider`` package, use of
the legacy Quantum Experience and Qconsole (also known as the
IBM Quantum Experience v1) credentials is no longer supported.
Args:
token: IBM Quantum Experience token.
url: URL for the IBM Quantum Experience authentication server.
hub: Name of the hub to use.
group: Name of the group to use.
project: Name of the project to use.
**kwargs: Additional settings for the connection:
* proxies (dict): proxy configuration.
* verify (bool): verify the server's TLS certificate.
Returns:
If `hub`, `group`, and `project` are specified, the corresponding provider
is returned. Otherwise the provider for the open access project is returned.
Raises:
IBMQAccountError: If an IBM Quantum Experience account is already in
use for the session.
IBMQAccountCredentialsInvalidUrl: If the URL specified is not
a valid IBM Quantum Experience authentication URL.
IBMQProviderError: If no provider matches the specified criteria,
or more than one provider matches the specified criteria.
"""
# Check if an IBM Quantum Experience account is already in use.
if self._credentials:
raise IBMQAccountError(
'An IBM Quantum Experience account is already in use for the session.')
# Check the version used by these credentials.
credentials = Credentials(token, url, **kwargs)
version_info = self._check_api_version(credentials)
# Check the URL is a valid authentication URL.
if not version_info['new_api'] or 'api-auth' not in version_info:
raise IBMQAccountCredentialsInvalidUrl(
'The URL specified ({}) is not an IBM Quantum Experience authentication '
'URL. Valid authentication URL: {}.'.format(credentials.url, QX_AUTH_URL))
# Initialize the providers.
self._initialize_providers(credentials)
# Prevent edge case where no hubs are available.
providers = self.providers()
if not providers:
logger.warning('No Hub/Group/Projects could be found for this '
'account.')
return None
# The provider for the default open access project.
default_provider = providers[0]
# If any `hub`, `group`, or `project` is specified, return the corresponding provider.
if any([hub, group, project]):
default_provider = self.get_provider(hub=hub, group=group, project=project)
return default_provider
def disable_account(self) -> None:
"""Disable the account currently in use for the session.
Raises:
IBMQAccountCredentialsNotFound: If no account is in use for the session.
"""
if not self._credentials:
raise IBMQAccountCredentialsNotFound(
'No IBM Quantum Experience account is in use for the session.')
self._credentials = None
self._providers = OrderedDict()
def load_account(self) -> Optional[AccountProvider]:
"""Authenticate against IBM Quantum Experience from stored credentials.
Returns:
If the configuration file specifies a default provider, it is returned.
Otherwise the provider for the open access project is returned.
Raises:
IBMQAccountCredentialsInvalidFormat: If the default provider stored on
disk could not be parsed.
IBMQAccountCredentialsNotFound: If no IBM Quantum Experience credentials
can be found.
IBMQAccountMultipleCredentialsFound: If multiple IBM Quantum Experience
credentials are found.
IBMQAccountCredentialsInvalidUrl: If invalid IBM Quantum Experience
credentials are found.
IBMQProviderError: If the default provider stored on disk could not
be found.
"""
# Check for valid credentials.
try:
stored_credentials, preferences = discover_credentials()
except HubGroupProjectInvalidStateError as ex:
raise IBMQAccountCredentialsInvalidFormat(
'Invalid provider (hub/group/project) data found {}'.format(str(ex))) from ex
credentials_list = list(stored_credentials.values())
if not credentials_list:
raise IBMQAccountCredentialsNotFound(
'No IBM Quantum Experience credentials found.')
if len(credentials_list) > 1:
raise IBMQAccountMultipleCredentialsFound(
'Multiple IBM Quantum Experience credentials found. ' + UPDATE_ACCOUNT_TEXT)
credentials = credentials_list[0]
# Explicitly check via a server call, to allow environment auth URLs
# contain IBM Quantum Experience v2 URL (but not auth) slipping through.
version_info = self._check_api_version(credentials)
# Check the URL is a valid authentication URL.
if not version_info['new_api'] or 'api-auth' not in version_info:
raise IBMQAccountCredentialsInvalidUrl(
'Invalid IBM Quantum Experience credentials found. ' + UPDATE_ACCOUNT_TEXT)
# Initialize the providers.
if self._credentials:
# For convention, emit a warning instead of raising.
logger.warning('Credentials are already in use. The existing '
'account in the session will be replaced.')
self.disable_account()
self._initialize_providers(credentials, preferences)
# Prevent edge case where no hubs are available.
providers = self.providers()
if not providers:
logger.warning('No Hub/Group/Projects could be found for this account.')
return None
# The provider for the default open access project.
default_provider = providers[0]
# If specified, attempt to get the provider stored for the account.
if credentials.default_provider:
hub, group, project = credentials.default_provider.to_tuple()
try:
default_provider = self.get_provider(hub=hub, group=group, project=project)
except IBMQProviderError as ex:
raise IBMQProviderError('The default provider (hub/group/project) stored on '
'disk could not be found: {}.'
'To overwrite the default provider stored on disk, use '
'the save_account(overwrite=True) method and specify the '
'default provider you would like to save.'
.format(str(ex))) from None
return default_provider
@staticmethod
def save_account(
token: str,
url: str = QX_AUTH_URL,
hub: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None,
overwrite: bool = False,
**kwargs: Any
) -> None:
"""Save the account to disk for future use.
Note:
If storing a default provider to disk, all three parameters
`hub`, `group`, `project` must be specified.
Args:
token: IBM Quantum Experience token.
url: URL for the IBM Quantum Experience authentication server.
hub: Name of the hub for the default provider to store on disk.
group: Name of the group for the default provider to store on disk.
project: Name of the project for the default provider to store on disk.
overwrite: Overwrite existing credentials.
**kwargs:
* proxies (dict): Proxy configuration for the server.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountCredentialsInvalidUrl: If the `url` is not a valid
IBM Quantum Experience authentication URL.
IBMQAccountCredentialsInvalidToken: If the `token` is not a valid
IBM Quantum Experience token.
IBMQAccountValueError: If only one or two parameters from `hub`, `group`,
`project` are specified.
"""
if url != QX_AUTH_URL:
raise IBMQAccountCredentialsInvalidUrl(
'Invalid IBM Q Experience credentials found. ' + UPDATE_ACCOUNT_TEXT)
if not token or not isinstance(token, str):
raise IBMQAccountCredentialsInvalidToken(
'Invalid IBM Quantum Experience token '
'found: "{}" of type {}.'.format(token, type(token)))
# If any `hub`, `group`, or `project` is specified, make sure all parameters are set.
if any([hub, group, project]) and not all([hub, group, project]):
raise IBMQAccountValueError('The hub, group, and project parameters must all be '
'specified when storing a default provider to disk: '
'hub = "{}", group = "{}", project = "{}"'
.format(hub, group, project))
# If specified, get the provider to store.
default_provider_hgp = HubGroupProject(hub, group, project) \
if all([hub, group, project]) else None
credentials = Credentials(token=token, url=url,
default_provider=default_provider_hgp, **kwargs)
store_credentials(credentials,
overwrite=overwrite)
@staticmethod
def delete_account() -> None:
"""Delete the saved account from disk.
Raises:
IBMQAccountCredentialsNotFound: If no valid IBM Quantum Experience
credentials can be found on disk.
IBMQAccountMultipleCredentialsFound: If multiple IBM Quantum Experience
credentials are found on disk.
IBMQAccountCredentialsInvalidUrl: If invalid IBM Quantum Experience
credentials are found on disk.
"""
stored_credentials, _ = read_credentials_from_qiskitrc()
if not stored_credentials:
raise IBMQAccountCredentialsNotFound(
'No IBM Quantum Experience credentials found on disk.')
if len(stored_credentials) != 1:
raise IBMQAccountMultipleCredentialsFound(
'Multiple IBM Quantum Experience credentials found on disk. ' + UPDATE_ACCOUNT_TEXT)
credentials = list(stored_credentials.values())[0]
if credentials.url != QX_AUTH_URL:
raise IBMQAccountCredentialsInvalidUrl(
'Invalid IBM Quantum Experience credentials found on disk. ' + UPDATE_ACCOUNT_TEXT)
remove_credentials(credentials)
@staticmethod
def stored_account() -> Dict[str, str]:
"""List the account stored on disk.
Returns:
A dictionary with information about the account stored on disk.
Raises:
IBMQAccountMultipleCredentialsFound: If multiple IBM Quantum Experience
credentials are found on disk.
IBMQAccountCredentialsInvalidUrl: If invalid IBM Quantum Experience
credentials are found on disk.
"""
stored_credentials, _ = read_credentials_from_qiskitrc()
if not stored_credentials:
return {}
if len(stored_credentials) > 1:
raise IBMQAccountMultipleCredentialsFound(
'Multiple IBM Quantum Experience credentials found on disk. ' + UPDATE_ACCOUNT_TEXT)
credentials = list(stored_credentials.values())[0]
if credentials.url != QX_AUTH_URL:
raise IBMQAccountCredentialsInvalidUrl(
'Invalid IBM Quantum Experience credentials found on disk. ' + UPDATE_ACCOUNT_TEXT)
return {
'token': credentials.token,
'url': credentials.url
}
def active_account(self) -> Optional[Dict[str, str]]:
"""Return the IBM Quantum Experience account currently in use for the session.
Returns:
Information about the account currently in the session.
"""
if not self._credentials:
# Return None instead of raising, maintaining the same behavior
# of the classic active_accounts() method.
return None
return {
'token': self._credentials.token,
'url': self._credentials.url,
}
@staticmethod
def update_account(force: bool = False) -> Optional[Credentials]:
"""Interactive helper for migrating stored credentials to IBM Quantum Experience v2.
Args:
force: If ``True``, disable interactive prompts and perform the changes.
Returns:
The credentials for IBM Quantum Experience v2 if updating is successful
or ``None`` otherwise.
"""
return update_credentials(force)
# Provider management functions.
def providers(
self,
hub: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None
) -> List[AccountProvider]:
"""Return a list of providers, subject to optional filtering.
Args:
hub: Name of the hub.
group: Name of the group.
project: Name of the project.
Returns:
A list of providers that match the specified criteria.
"""
filters = [] # type: List[Callable[[HubGroupProject], bool]]
if hub:
filters.append(lambda hgp: hgp.hub == hub)
if group:
filters.append(lambda hgp: hgp.group == group)
if project:
filters.append(lambda hgp: hgp.project == project)
providers = [provider for key, provider in self._providers.items()
if all(f(key) for f in filters)]
return providers
def get_provider(
self,
hub: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None
) -> AccountProvider:
"""Return a provider for a single hub/group/project combination.
Args:
hub: Name of the hub.
group: Name of the group.
project: Name of the project.
Returns:
A provider that matches the specified criteria.
Raises:
IBMQProviderError: If no provider matches the specified criteria,
or more than one provider matches the specified criteria.
"""
providers = self.providers(hub, group, project)
if not providers:
raise IBMQProviderError('No provider matches the specified criteria: '
'hub = {}, group = {}, project = {}'
.format(hub, group, project))
if len(providers) > 1:
raise IBMQProviderError('More than one provider matches the specified criteria.'
'hub = {}, group = {}, project = {}'
.format(hub, group, project))
return providers[0]
# Private functions.
@staticmethod
def _check_api_version(credentials: Credentials) -> Dict[str, Union[bool, str]]:
"""Check the version of the remote server in a set of credentials.
Returns:
A dictionary with version information.
"""
version_finder = VersionClient(credentials.base_url,
**credentials.connection_parameters())
return version_finder.version()
def _initialize_providers(
self, credentials: Credentials,
preferences: Optional[Dict] = None
) -> None:
"""Authenticate against IBM Quantum and populate the providers.
Args:
credentials: Credentials for IBM Quantum.
preferences: Account preferences.
"""
auth_client = AuthClient(credentials.token,
credentials.base_url,
**credentials.connection_parameters())
service_urls = auth_client.current_service_urls()
user_hubs = auth_client.user_hubs()
preferences = preferences or {}
self._credentials = credentials
for hub_info in user_hubs:
# Build credentials.
provider_credentials = Credentials(
credentials.token,
access_token=auth_client.current_access_token(),
url=service_urls['http'],
websockets_url=service_urls['ws'],
proxies=credentials.proxies,
verify=credentials.verify,
services=service_urls.get('services', {}),
default_provider=credentials.default_provider,
**hub_info, )
provider_credentials.preferences = \
preferences.get(provider_credentials.unique_id(), {})
# Build the provider.
try:
provider = AccountProvider(provider_credentials, self)
self._providers[provider_credentials.unique_id()] = provider
except Exception: # pylint: disable=broad-except
# Catch-all for errors instantiating the provider.
logger.warning('Unable to instantiate provider for %s: %s',
hub_info, traceback.format_exc())