forked from Qiskit/qiskit-ibmq-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount.py
379 lines (293 loc) · 12.1 KB
/
account.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
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""Client for accessing an individual IBM Q Experience account."""
import asyncio
import logging
from typing import List, Dict, Any, Optional
# Disabled unused-import because datetime is used only for type hints.
from datetime import datetime # pylint: disable=unused-import
from ..exceptions import RequestsApiError
from ..rest import Api
from ..session import RetrySession
from .base import BaseClient
from .websocket import WebsocketClient
logger = logging.getLogger(__name__)
class AccountClient(BaseClient):
"""Client for accessing an individual IBM Q Experience account.
This client provides access to an individual IBM Q hub/group/project.
"""
def __init__(
self,
access_token: str,
project_url: str,
websockets_url: str,
**request_kwargs: Dict
) -> None:
"""AccountClient constructor.
Args:
access_token (str): IBM Q Experience access token.
project_url (str): IBM Q Experience URL for a specific h/g/p.
websockets_url (str): URL for the websockets server.
**request_kwargs (dict): arguments for the `requests` Session.
"""
self.client_api = Api(RetrySession(project_url, access_token,
**request_kwargs))
self.client_ws = WebsocketClient(websockets_url, access_token)
# Backend-related public functions.
def list_backends(self, timeout: Optional[float] = None) -> List[Dict[str, Any]]:
"""Return the list of backends.
Args:
timeout (float or None): number of seconds to wait for the request.
Returns:
list[dict]: a list of backends.
"""
return self.client_api.backends(timeout=timeout)
def backend_status(self, backend_name: str) -> Dict[str, Any]:
"""Return the status of a backend.
Args:
backend_name (str): the name of the backend.
Returns:
dict: backend status.
"""
return self.client_api.backend(backend_name).status()
def backend_properties(
self,
backend_name: str,
datetime: Optional[datetime] = None
) -> Dict[str, Any]:
"""Return the properties of a backend.
Args:
backend_name (str): the name of the backend.
datetime (datetime.datetime): datetime for
additional filtering of backend properties.
Returns:
dict: backend properties.
"""
# pylint: disable=redefined-outer-name
return self.client_api.backend(backend_name).properties(datetime=datetime)
def backend_pulse_defaults(self, backend_name: str) -> Dict:
"""Return the pulse defaults of a backend.
Args:
backend_name (str): the name of the backend.
Returns:
dict: backend pulse defaults.
"""
return self.client_api.backend(backend_name).pulse_defaults()
# Jobs-related public functions.
def list_jobs_statuses(
self,
limit: int = 10,
skip: int = 0,
extra_filter: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
"""Return a list of statuses of jobs, with filtering and pagination.
Args:
limit (int): maximum number of items to return.
skip (int): offset for the items to return.
extra_filter (dict): additional filtering passed to the query.
Returns:
list[dict]: a list of job statuses.
"""
return self.client_api.jobs(limit=limit, skip=skip,
extra_filter=extra_filter)
def job_submit(self, backend_name: str, qobj_dict: Dict[str, Any],
job_name: Optional[str] = None) -> Dict[str, Any]:
"""Submit a Qobj to a device.
Args:
backend_name (str): the name of the backend.
qobj_dict (dict): the Qobj to be executed, as a dictionary.
job_name (str): custom name to be assigned to the job.
Returns:
dict: job status.
"""
return self.client_api.submit_job(backend_name, qobj_dict, job_name)
def job_submit_object_storage(self, backend_name: str, qobj_dict: Dict[str, Any],
job_name: Optional[str] = None) -> Dict:
"""Submit a Qobj to a device using object storage.
Args:
backend_name (str): the name of the backend.
qobj_dict (dict): the Qobj to be executed, as a dictionary.
job_name (str): custom name to be assigned to the job.
Returns:
dict: job status.
"""
# Get the job via object storage.
job_info = self.client_api.submit_job_object_storage(backend_name, job_name=job_name)
# Get the upload URL.
job_id = job_info['id']
job_api = self.client_api.job(job_id)
upload_url = job_api.upload_url()['url']
# Upload the Qobj to object storage.
_ = job_api.put_object_storage(upload_url, qobj_dict)
# Notify the API via the callback.
response = job_api.callback_upload()
return response['job']
def job_download_qobj_object_storage(self, job_id: str) -> Dict:
"""Retrieve and return a Qobj using object storage.
Args:
job_id (str): the id of the job.
Returns:
dict: Qobj, in dict form.
"""
job_api = self.client_api.job(job_id)
# Get the download URL.
download_url = job_api.download_url()['url']
# Download the result from object storage.
return job_api.get_object_storage(download_url)
def job_result_object_storage(self, job_id: str) -> Dict:
"""Retrieve and return a result using object storage.
Args:
job_id (str): the id of the job.
Returns:
dict: job information.
"""
job_api = self.client_api.job(job_id)
# Get the download URL.
download_url = job_api.result_url()['url']
# Download the result from object storage.
result_response = job_api.get_object_storage(download_url)
# Notify the API via the callback
try:
_ = job_api.callback_download()
except (RequestsApiError, ValueError) as ex:
logger.warning("An error occurred while sending download completion acknowledgement: "
"%s", ex)
return result_response
def job_get(
self,
job_id: str,
excluded_fields: Optional[List[str]] = None,
included_fields: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Return information about a job.
Args:
job_id (str): the id of the job.
excluded_fields (list[str]): names of the fields to explicitly
exclude from the result.
included_fields (list[str]): names of the fields, if present, to explicitly
include in the result. All the other fields will not be included in the result.
Returns:
dict: job information.
"""
return self.client_api.job(job_id).get(excluded_fields,
included_fields)
def job_status(self, job_id: str) -> Dict[str, Any]:
"""Return the status of a job.
Args:
job_id (str): the id of the job.
Returns:
dict: job status.
"""
return self.client_api.job(job_id).status()
def job_final_status_websocket(
self,
job_id: str,
timeout: Optional[float] = None
) -> Dict[str, Any]:
"""Return the final status of a job via websocket.
Args:
job_id (str): the id of the job.
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
Returns:
dict: job status.
Raises:
RuntimeError: if an unexpected error occurred while getting the event loop.
"""
# As mentioned in `websocket.py`, in jupyter we need to use
# `nest_asyncio` to allow nested event loops.
try:
loop = asyncio.get_event_loop()
except RuntimeError as ex:
# Event loop may not be set in a child thread.
if 'There is no current event loop' in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
raise
return loop.run_until_complete(
self.client_ws.get_job_status(job_id, timeout=timeout))
def job_properties(self, job_id: str) -> Dict:
"""Return the backend properties of a job.
Args:
job_id (str): the id of the job.
Returns:
dict: backend properties.
"""
return self.client_api.job(job_id).properties()
def job_cancel(self, job_id: str) -> Dict[str, Any]:
"""Submit a request for cancelling a job.
Args:
job_id (str): the id of the job.
Returns:
dict: job cancellation response.
"""
return self.client_api.job(job_id).cancel()
# Circuits-related public functions.
def circuit_run(self, name: str, **kwargs: Dict) -> Dict:
"""Execute a Circuit.
Args:
name (str): name of the Circuit.
**kwargs (dict): arguments for the Circuit.
Returns:
dict: json response.
"""
return self.client_api.circuit(name, **kwargs)
def circuit_job_get(self, job_id: str) -> Dict:
"""Return information about a Circuit job.
Args:
job_id (str): the id of the job.
Returns:
dict: job information.
"""
return self.client_api.job(job_id).get([], [])
def circuit_job_status(self, job_id: str) -> Dict:
"""Return the status of a Circuits job.
Args:
job_id (str): the id of the job.
Returns:
dict: job status.
"""
return self.job_status(job_id)
# Endpoints for compatibility with classic IBMQConnector. These functions
# are meant to facilitate the transition, and should be removed moving
# forward.
def get_status_job(self, id_job):
# pylint: disable=missing-docstring
return self.job_status(id_job)
def submit_job(self, qobj_dict, backend_name, job_name=None):
# pylint: disable=missing-docstring
return self.job_submit(backend_name, qobj_dict, job_name)
def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False,
filter=None):
# pylint: disable=missing-docstring,redefined-builtin
# TODO: this function seems to be unused currently in IBMQConnector.
raise NotImplementedError
def get_status_jobs(self, limit=10, skip=0, backend=None, filter=None):
# pylint: disable=missing-docstring,redefined-builtin
if backend:
filter = filter or {}
filter.update({'backend.name': backend})
return self.list_jobs_statuses(limit, skip, filter)
def cancel_job(self, id_job):
# pylint: disable=missing-docstring
return self.job_cancel(id_job)
def backend_defaults(self, backend):
# pylint: disable=missing-docstring
return self.backend_pulse_defaults(backend)
def available_backends(self, timeout=None):
# pylint: disable=missing-docstring
return self.list_backends(timeout=timeout)
def get_job(self, id_job, exclude_fields=None, include_fields=None):
# pylint: disable=missing-docstring
return self.job_get(id_job, exclude_fields, include_fields)