dwave-cloud-client 0.11.4__tar.gz → 0.12.0.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. {dwave-cloud-client-0.11.4/dwave_cloud_client.egg-info → dwave-cloud-client-0.12.0.dev0}/PKG-INFO +2 -1
  2. dwave-cloud-client-0.12.0.dev0/dwave/cloud/__init__.py +174 -0
  3. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/client.py +5 -11
  4. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/constants.py +6 -0
  5. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/models.py +12 -2
  6. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/resources.py +19 -1
  7. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/flows.py +14 -0
  8. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/cli.py +4 -1
  9. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/base.py +53 -3
  10. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/hybrid.py +1 -1
  11. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/qpu.py +1 -1
  12. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/sw.py +1 -1
  13. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/coders.py +24 -2
  14. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/computation.py +29 -9
  15. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/package_info.py +1 -1
  16. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/solver.py +200 -35
  17. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/testing/mocks.py +14 -1
  18. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/utils.py +1 -0
  19. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0/dwave_cloud_client.egg-info}/PKG-INFO +2 -1
  20. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/requires.txt +4 -0
  21. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/setup.py +3 -0
  22. dwave-cloud-client-0.11.4/dwave/cloud/__init__.py +0 -91
  23. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/LICENSE +0 -0
  24. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/README.rst +0 -0
  25. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/__init__.py +0 -0
  26. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/__init__.py +0 -0
  27. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/exceptions.py +0 -0
  28. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/__init__.py +0 -0
  29. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/_creds.py +0 -0
  30. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/config.py +0 -0
  31. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/creds.py +0 -0
  32. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/server.py +0 -0
  33. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/__init__.py +0 -0
  34. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/concurrency.py +0 -0
  35. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/__init__.py +0 -0
  36. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/loaders.py +0 -0
  37. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/models.py +0 -0
  38. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/events.py +0 -0
  39. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/exceptions.py +0 -0
  40. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/regions.py +0 -0
  41. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/testing/__init__.py +0 -0
  42. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/upload.py +0 -0
  43. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/SOURCES.txt +0 -0
  44. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  45. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  46. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  47. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  48. {dwave-cloud-client-0.11.4 → dwave-cloud-client-0.12.0.dev0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dwave-cloud-client
3
- Version: 0.11.4
3
+ Version: 0.12.0.dev0
4
4
  Summary: A minimal client for interacting with D-Wave cloud resources.
5
5
  Home-page: https://github.com/dwavesystems/dwave-cloud-client
6
6
  Author: D-Wave Systems Inc.
@@ -20,6 +20,7 @@ Provides-Extra: bqm-legacy
20
20
  Provides-Extra: dqm
21
21
  Provides-Extra: dqm-legacy
22
22
  Provides-Extra: cqm
23
+ Provides-Extra: nlm
23
24
  Provides-Extra: mocks
24
25
  License-File: LICENSE
25
26
 
@@ -0,0 +1,174 @@
1
+ # Copyright 2017 D-Wave Systems Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import io
16
+ import os
17
+ import re
18
+ import sys
19
+ import json
20
+ import logging
21
+ import datetime
22
+ import importlib
23
+ import typing
24
+
25
+ from dwave.cloud.client import Client
26
+ from dwave.cloud.solver import Solver
27
+ from dwave.cloud.computation import Future
28
+ from dwave.cloud.utils import parse_loglevel
29
+
30
+ __all__ = ['Client', 'Solver', 'Future']
31
+
32
+
33
+ # prevent log output (from library) when logging not configured by user/app
34
+ logger = logging.getLogger(__name__)
35
+ logger.addHandler(logging.NullHandler())
36
+
37
+ # add TRACE log level and Logger.trace() method
38
+ logging.TRACE = 5
39
+ logging.addLevelName(logging.TRACE, "TRACE")
40
+
41
+ def _trace(logger, message, *args, **kwargs):
42
+ logger.log(logging.TRACE, message, *args, **kwargs)
43
+
44
+ logging.Logger.trace = _trace
45
+
46
+
47
+ class ISOFormatter(logging.Formatter):
48
+ # target timezone, e.g. `datetime.timezone.utc`, or `None` for naive timestamp
49
+ as_tz: typing.Optional[datetime.timezone] = None
50
+
51
+ def __init__(self, *args, as_tz: typing.Optional[datetime.timezone] = None, **kwargs):
52
+ self.as_tz = as_tz
53
+ super().__init__(*args, **kwargs)
54
+
55
+ def formatTime(self, record: logging.LogRecord, datefmt: typing.Optional[str] = None) -> str:
56
+ return datetime.datetime.fromtimestamp(record.created, tz=self.as_tz).isoformat()
57
+
58
+
59
+ class FilteredSecretsFormatter(logging.Formatter):
60
+ """Logging formatter that filters out secrets (like Solver API tokens).
61
+
62
+ Note: we assume, for easier disambiguation, a secret/token is prefixed with
63
+ a short alphanumeric string, and comprises 40 or more hex digits.
64
+ """
65
+
66
+ # prefixed 160-bit+ hex tokens (sapi token format: `A{2,4}-X{40,}`)
67
+ _SAPI_TOKEN_PATTERN = re.compile(
68
+ r'\b([0-9A-Za-z]{2,4}-[0-9A-Fa-f]{3})([0-9A-Fa-f]{34,})([0-9A-Fa-f]{3})\b')
69
+ # 128-bit+ hex tokens (`X{32,}`)
70
+ _HEX_TOKEN_PATTERN = re.compile(
71
+ r'\b([0-9A-Fa-f]{3})([0-9A-Fa-f]{26,})([0-9A-Fa-f]{3})\b')
72
+ # 128-bit uuid tokens (`X{8}-X{4}-X{4}-X{4}-X{12}`)
73
+ _UUID_TOKEN_PATTERN = re.compile(
74
+ r'\b([0-9A-Fa-f]{3})([0-9A-Fa-f]{5}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{9})([0-9A-Fa-f]{3})\b')
75
+
76
+ def format(self, record: logging.LogRecord) -> str:
77
+ output = super().format(record)
78
+ output = re.sub(self._SAPI_TOKEN_PATTERN, r'\1...\3', output)
79
+ output = re.sub(self._HEX_TOKEN_PATTERN, r'\1...\3', output)
80
+ output = re.sub(self._UUID_TOKEN_PATTERN, r'\1...\3', output)
81
+ return output
82
+
83
+
84
+ class JSONFormatter(ISOFormatter):
85
+ def format(self, record: logging.LogRecord) -> str:
86
+ super().format(record)
87
+ # filter out message template and potentially unserializable args
88
+ rec = record.__dict__.copy()
89
+ del rec['args']
90
+ del rec['msg']
91
+ return json.dumps(rec)
92
+
93
+
94
+ def configure_logging(logger: typing.Optional[logging.Logger] = None,
95
+ *,
96
+ level: int = logging.WARNING,
97
+ filter_secrets: bool = True,
98
+ output_stream: typing.Optional[io.IOBase] = None,
99
+ in_utc: bool = False,
100
+ structured_output: bool = False,
101
+ handler_level: typing.Optional[int] = None,
102
+ additive: bool = False,
103
+ ) -> logging.Logger:
104
+ """Configure cloud-client's `dwave.cloud` base logger.
105
+
106
+ Logging output from the cloud-client is suppressed by default. This utility
107
+ function can be used to quickly setup basic logging from the library.
108
+
109
+ .. note::
110
+ This function is currently intended for internal/private use only.
111
+
112
+ .. versionadded:: 0.12.0
113
+ Explicit optional logging configuration. Previously, logger was minimally
114
+ configured by default.
115
+ """
116
+
117
+ if logger is None:
118
+ logger = logging.getLogger(__name__)
119
+ if output_stream is None:
120
+ output_stream = sys.stderr
121
+ if handler_level is None:
122
+ handler_level = level
123
+
124
+ format = dict(
125
+ fmt='%(asctime)s %(name)s %(levelname)s %(threadName)s [%(funcName)s] %(message)s',
126
+ as_tz=datetime.timezone.utc if in_utc else None,
127
+ )
128
+
129
+ if structured_output:
130
+ formatter_base = JSONFormatter
131
+ else:
132
+ formatter_base = ISOFormatter
133
+
134
+ if filter_secrets:
135
+ class Formatter(FilteredSecretsFormatter, formatter_base):
136
+ pass
137
+ else:
138
+ Formatter = formatter_base
139
+
140
+ if not additive:
141
+ # make sure handlers are not accumulated
142
+ while len(logger.handlers):
143
+ logger.removeHandler(logger.handlers[-1])
144
+
145
+ formatter = Formatter(**format)
146
+ handler = logging.StreamHandler(stream=output_stream)
147
+ handler.setFormatter(formatter)
148
+ handler.setLevel(handler_level)
149
+
150
+ logger.addHandler(handler)
151
+ logger.setLevel(level)
152
+
153
+ return logger
154
+
155
+
156
+ # configure logger if DWAVE_LOG_LEVEL present in environment
157
+ def _apply_loglevel_from_env(logger):
158
+ if log_level := os.getenv('DWAVE_LOG_LEVEL', os.getenv('dwave_log_level')):
159
+ level = parse_loglevel(log_level)
160
+ log_format = os.getenv('DWAVE_LOG_FORMAT', os.getenv('dwave_log_format', ''))
161
+ structured = log_format.strip().lower() == 'json'
162
+ configure_logging(logger, level=level, structured_output=structured)
163
+
164
+ _apply_loglevel_from_env(logger)
165
+
166
+
167
+ # alias dwave.cloud.client.{qpu,sw,hybrid} as dwave.cloud.*
168
+ def _alias_old_client_submodules():
169
+ for name in ('qpu', 'sw', 'hybrid'):
170
+ # note: create both module and local attribute
171
+ globals()[name] = sys.modules['dwave.cloud.{}'.format(name)] = \
172
+ importlib.import_module('dwave.cloud.client.{}'.format(name))
173
+
174
+ _alias_old_client_submodules()
@@ -66,7 +66,7 @@ class LoggingSession(BaseUrlSession):
66
66
  RequestRecord = namedtuple('RequestRecord',
67
67
  ('request', 'response', 'exception'))
68
68
 
69
- def send(self, request: requests.PreparedRequest, **kwargs):
69
+ def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response:
70
70
  callee = type(self).__name__
71
71
  if logger.getEffectiveLevel() >= logging.DEBUG:
72
72
  logger.debug(f"[{callee!s}] send(method={request.method!r}, url={request.url!r}, ...)")
@@ -95,13 +95,13 @@ class LoggingSession(BaseUrlSession):
95
95
  logger.debug("[%s] request failed with %r", callee, exc)
96
96
 
97
97
  req = getattr(exc, 'request', None)
98
- if req:
98
+ if req is not None:
99
99
  logger.trace("[%s] failing request=%r", callee,
100
100
  dict(method=req.method, url=req.url,
101
101
  headers=req.headers, body=req.body))
102
102
 
103
103
  res = getattr(exc, 'response', None)
104
- if res:
104
+ if res is not None:
105
105
  logger.trace("[%s] failing response=%r", callee,
106
106
  dict(status_code=res.status_code,
107
107
  headers=res.headers, text=res.text))
@@ -439,15 +439,9 @@ class DWaveAPIClient:
439
439
  # failure. However, that is currently not the case. We need to work
440
440
  # around this until it's fixed.
441
441
 
442
- # no error -> body is json
442
+ # no error -> content type verified by `VersionedAPISession ` @accepts
443
443
  # error -> body can be json or plain text error message
444
- if response.ok:
445
- try:
446
- response.json()
447
- except:
448
- raise exceptions.ResourceBadResponseError("JSON response expected")
449
-
450
- else:
444
+ if not response.ok:
451
445
  try:
452
446
  msg = response.json()
453
447
  error_msg = msg['error_msg']
@@ -58,6 +58,11 @@ class ProblemEncodingFormat(str, enum.Enum):
58
58
  class AnswerEncodingFormat(str, enum.Enum):
59
59
  QP = "qp"
60
60
  BQ = "bq" # dimod (de-)serialization-based
61
+ BINARY_REF = "binary-ref"
62
+
63
+
64
+ class BinaryRefAuthMethod(str, enum.Enum):
65
+ SAPI_TOKEN = "sapi-token"
61
66
 
62
67
 
63
68
  class ProblemType(str, enum.Enum):
@@ -66,3 +71,4 @@ class ProblemType(str, enum.Enum):
66
71
  BQM = "bqm"
67
72
  CQM = "cqm"
68
73
  DQM = "dqm"
74
+ NL = "nl"
@@ -16,7 +16,7 @@ from datetime import datetime
16
16
  from typing import List, Union, Optional, Dict, Any
17
17
  from typing_extensions import Annotated # backport for py37, py38
18
18
 
19
- from pydantic import BaseModel, RootModel
19
+ from pydantic import BaseModel, RootModel, Field
20
20
  from pydantic.functional_validators import AfterValidator
21
21
 
22
22
  from dwave.cloud.api import constants
@@ -63,8 +63,18 @@ class UnstructuredProblemAnswer(BaseModel):
63
63
  data: dict
64
64
 
65
65
 
66
+ class UnstructuredProblemAnswerBinaryRef(BaseModel):
67
+ format: constants.AnswerEncodingFormat = constants.AnswerEncodingFormat.BINARY_REF
68
+ auth_method: constants.BinaryRefAuthMethod = constants.BinaryRefAuthMethod.SAPI_TOKEN
69
+ url: str
70
+ timing: dict
71
+ shape: dict
72
+
73
+
66
74
  class ProblemAnswer(RootModel):
67
- root: Union[StructuredProblemAnswer, UnstructuredProblemAnswer]
75
+ root: Union[StructuredProblemAnswer,
76
+ UnstructuredProblemAnswer,
77
+ UnstructuredProblemAnswerBinaryRef]
68
78
 
69
79
  def __getattr__(self, item):
70
80
  return getattr(self.root, item)
@@ -12,6 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ import io
15
16
  import json
16
17
  from typing import List, Union, Optional, Callable, get_type_hints
17
18
  from functools import wraps
@@ -60,7 +61,7 @@ class ResourceBase:
60
61
  client_class: DWaveAPIClient = DWaveAPIClient
61
62
 
62
63
  # endpoint path prefix (base path) specific to all methods on the resource
63
- resource_path: str = None
64
+ resource_path: Optional[str] = None
64
65
 
65
66
  def __init__(self, client: Optional[DWaveAPIClient] = None, **config):
66
67
  if isinstance(client, DWaveAPIClient):
@@ -217,6 +218,23 @@ class Problems(ResourceBase):
217
218
  answer = response.json()['answer']
218
219
  return models.ProblemAnswer.model_validate(answer)
219
220
 
221
+ @accepts(media_type='application/octet-stream')
222
+ def get_answer_data(self, answer: models.UnstructuredProblemAnswerBinaryRef,
223
+ output: Optional[io.IOBase] = None) -> io.IOBase:
224
+ """Retrieve binary-ref answer data."""
225
+ if answer.auth_method != constants.BinaryRefAuthMethod.SAPI_TOKEN:
226
+ raise ValueError(f"Authentication method {answer.auth_method!r} not supported.")
227
+
228
+ if output is None:
229
+ output = io.BytesIO()
230
+
231
+ for chunk in self.session.get(answer.url, stream=True).iter_content(chunk_size=8192):
232
+ output.write(chunk)
233
+
234
+ output.seek(0)
235
+
236
+ return output
237
+
220
238
  @accepts(media_type='application/vnd.dwave.sapi.problem-message+json', version='>=2.1,<3')
221
239
  def get_problem_messages(self, problem_id: str) -> List[dict]:
222
240
  """Retrieve list of problem messages."""
@@ -103,6 +103,20 @@ class AuthFlow:
103
103
  authorization_endpoint=authorization_endpoint,
104
104
  token_endpoint=token_endpoint)
105
105
 
106
+ # setup response logging
107
+ def log_response(response, **kwargs):
108
+ callee = type(self.session).__name__
109
+
110
+ req = getattr(response, 'request', None)
111
+ if req is not None:
112
+ logger.trace("[%s] request=%r", callee,
113
+ dict(method=req.method, url=req.url,
114
+ headers=req.headers, body=req.body))
115
+
116
+ logger.trace("[%s] request(...) = (code=%r, body=%r, headers=%r, %r)",
117
+ callee, response.status_code, response.text, response.headers, kwargs)
118
+ self.session.hooks["response"].append(log_response)
119
+
106
120
  # set default headers (overwritten by ``session_config['headers']``)
107
121
  self.session.headers.update({'User-Agent': default_user_agent()})
108
122
 
@@ -28,7 +28,7 @@ import click
28
28
  import requests.exceptions
29
29
 
30
30
  import dwave.cloud
31
- from dwave.cloud import Client
31
+ from dwave.cloud import Client, configure_logging
32
32
  from dwave.cloud import api
33
33
  from dwave.cloud.solver import StructuredSolver, BaseUnstructuredSolver
34
34
  from dwave.cloud.utils import (
@@ -55,10 +55,12 @@ click.option = partial(click.option, show_default=True)
55
55
 
56
56
  def enable_logging(ctx, param, value):
57
57
  if value and not ctx.resilient_parsing:
58
+ configure_logging()
58
59
  set_loglevel(dwave.cloud.logger, param.name)
59
60
 
60
61
  def enable_loglevel(ctx, param, value):
61
62
  if value and not ctx.resilient_parsing:
63
+ configure_logging()
62
64
  set_loglevel(dwave.cloud.logger, value)
63
65
 
64
66
  def show_platform(ctx, param, value):
@@ -543,6 +545,7 @@ def solvers(config_file, profile, endpoint, region, client_type, solver_def,
543
545
  client_type = 'base'
544
546
  solver_def = '{}'
545
547
 
548
+ # TODO: handle exceptions like in `_get_client_solver` and `standardized_output`
546
549
  with Client.from_config(
547
550
  config_file=config_file, profile=profile,
548
551
  endpoint=endpoint, region=region,
@@ -34,6 +34,7 @@ Examples:
34
34
 
35
35
  """
36
36
 
37
+ import io
37
38
  import re
38
39
  import time
39
40
  import copy
@@ -50,10 +51,10 @@ import codecs
50
51
  import concurrent.futures
51
52
 
52
53
  from itertools import chain, zip_longest
53
- from functools import partial, wraps, cached_property
54
+ from functools import partial, wraps
54
55
  from collections import namedtuple
55
56
  from concurrent.futures import ThreadPoolExecutor
56
- from typing import Dict
57
+ from typing import Dict, Optional, Union
57
58
 
58
59
  import requests
59
60
  import urllib3
@@ -350,6 +351,9 @@ class Client(object):
350
351
  _UPLOAD_REQUEST_RETRIES = 2
351
352
  _UPLOAD_RETRIES_BACKOFF = lambda retry: 2 ** retry
352
353
 
354
+ # Binary-ref answer download parameters
355
+ _DOWNLOAD_ANSWER_THREAD_COUNT = 2
356
+
353
357
  @staticmethod
354
358
  def _legacy_config_property_proxy(self, legacy_property, config_path):
355
359
  warnings.warn(
@@ -536,6 +540,10 @@ class Client(object):
536
540
  self._encode_problem_executor = \
537
541
  ThreadPoolExecutor(self._ENCODE_PROBLEM_THREAD_COUNT)
538
542
 
543
+ # Setup binary-ref answer download executors
544
+ self._download_answer_executor = \
545
+ ThreadPoolExecutor(self._DOWNLOAD_ANSWER_THREAD_COUNT)
546
+
539
547
  def create_session(self):
540
548
  """Create a new requests session based on client's (self) params.
541
549
 
@@ -613,6 +621,9 @@ class Client(object):
613
621
  logger.debug("Shutting down problem encoder executor")
614
622
  self._encode_problem_executor.shutdown()
615
623
 
624
+ logger.debug("Shutting down answer download executor")
625
+ self._download_answer_executor.shutdown()
626
+
616
627
  # Send kill-task to all worker threads
617
628
  # Note: threads can't be 'killed' in Python, they have to die by
618
629
  # natural causes
@@ -1602,7 +1613,46 @@ class Client(object):
1602
1613
  finally:
1603
1614
  session.close()
1604
1615
 
1605
- def upload_problem_encoded(self, problem, problem_id=None):
1616
+ def _download_answer_binary_ref(self, *, auth_method: str, url: str,
1617
+ output: Optional[io.IOBase] = None) -> concurrent.futures.Future:
1618
+ """Initiate binary-ref answer download, returning the binary data in
1619
+ :class:`~concurrent.futures.Future`.
1620
+
1621
+ Args:
1622
+ auth_method:
1623
+ Authentication method used to access data at ``url``.
1624
+
1625
+ url:
1626
+ Answer binary data.
1627
+
1628
+ Returns:
1629
+ :class:`concurrent.futures.Future`[bytes | io.IOBase]:
1630
+ Answer data in a Future.
1631
+ """
1632
+ return self._download_answer_executor.submit(
1633
+ self._download_answer_worker, auth_method=auth_method, url=url, output=output)
1634
+
1635
+ def _download_answer_worker(self, *, auth_method: str, url: str,
1636
+ output: Optional[io.IOBase] = None) -> io.IOBase:
1637
+ if auth_method != api.constants.BinaryRefAuthMethod.SAPI_TOKEN:
1638
+ raise ValueError(f"Authentication method {auth_method!r} not supported.")
1639
+ if output is None:
1640
+ output = io.BytesIO()
1641
+
1642
+ logger.debug("Downloading binary-ref answer from %r using %r method.",
1643
+ url, auth_method)
1644
+
1645
+ with self.create_session() as session:
1646
+ size = 0
1647
+ for chunk in session.get(url, stream=True).iter_content(chunk_size=8192):
1648
+ size += output.write(chunk)
1649
+ output.seek(0)
1650
+
1651
+ logger.debug("Answer data downloaded from %r. Written %r bytes.", url, size)
1652
+
1653
+ return output
1654
+
1655
+ def upload_problem_encoded(self, problem, problem_id=None, **kwargs):
1606
1656
  """Initiate multipart problem upload, returning the Problem ID in a
1607
1657
  :class:`~concurrent.futures.Future`.
1608
1658
 
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  Interface to hybrid :term:`sampler`\ s available through the D-Wave Solver API
17
17
  (SAPI).
18
18
  """
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  An implementation of the REST client for D-Wave Solver API (SAPI) service.
17
17
 
18
18
  SAPI servers provide authentication, queuing, and scheduling services,
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  Interface to software :term:`sampler`\ s available through the D-Wave Solver
17
17
  API (SAPI).
18
18
 
@@ -14,13 +14,14 @@
14
14
 
15
15
  import struct
16
16
  import base64
17
+ from typing import Callable
17
18
 
18
19
  from dwave.cloud.utils import uniform_get, active_qubits
19
20
 
20
21
  __all__ = [
21
22
  'encode_problem_as_qp', 'decode_qp', 'decode_qp_numpy',
22
23
  'encode_problem_as_bq', 'decode_bq',
23
- 'encode_problem_as_ref',
24
+ 'encode_problem_as_ref', 'decode_binary_ref',
24
25
  'bqm_as_file',
25
26
  ]
26
27
 
@@ -345,7 +346,10 @@ def decode_bq(msg):
345
346
  "Re-install the library with 'bqm' support.")
346
347
 
347
348
  answer = msg['answer']
348
- assert answer['format'] == 'bq'
349
+ if answer['format'] != 'bq':
350
+ raise ValueError(f"Unsupported answer format: {answer['format']}")
351
+ if 'data' not in answer:
352
+ raise ValueError("Incomplete answer")
349
353
 
350
354
  result = {}
351
355
 
@@ -358,6 +362,24 @@ def decode_bq(msg):
358
362
  return result
359
363
 
360
364
 
365
+ def decode_binary_ref(msg: dict, ref_resolver: Callable) -> dict:
366
+ """Decode binary-ref answer."""
367
+
368
+ answer = msg['answer']
369
+ if answer['format'] != 'binary-ref':
370
+ raise ValueError(f"Unsupported answer format: {answer['format']}")
371
+ if 'auth_method' not in answer or 'url' not in answer:
372
+ raise ValueError("Incomplete binary-ref answer")
373
+
374
+ result = {
375
+ 'problem_type': msg['type'],
376
+ 'timing': answer.get('timing', {}),
377
+ 'shape': answer.get('shape', {}),
378
+ 'answer': ref_resolver(auth_method=answer['auth_method'], url=answer['url'])
379
+ }
380
+ return result
381
+
382
+
361
383
  def bqm_as_file(bqm, **options):
362
384
  """Encode in-memory BQM as DIMODBQM binary file format.
363
385
 
@@ -26,14 +26,15 @@ waiting for and retrieving results, cancelling enqueued jobs, etc.
26
26
  Some :class:`Future` methods are blocking.
27
27
  """
28
28
 
29
+ import io
29
30
  import time
30
31
  import threading
31
32
  import functools
32
33
  import weakref
33
34
 
34
- from operator import itemgetter
35
- from dateutil.parser import parse
36
35
  from concurrent.futures import TimeoutError
36
+ from dateutil.parser import parse
37
+ from operator import itemgetter
37
38
 
38
39
  from dwave.cloud.utils import (
39
40
  utcnow, datetime_to_timestamp, aliasdict, deprecated)
@@ -147,10 +148,16 @@ class Future(object):
147
148
  self._result = None
148
149
  self._exception = None
149
150
 
151
+ # make writes to self._result thread-safe
152
+ self._result_write_lock = threading.Lock()
153
+
150
154
  # Event(s) to signal when the results are ready
151
155
  self._results_ready_event = threading.Event()
152
156
  self._other_events = []
153
157
 
158
+ # set when answer data is downloaded
159
+ self._answer_data_ready_event = threading.Event()
160
+
154
161
  # current poll back-off interval, in seconds
155
162
  self._poll_backoff = None
156
163
 
@@ -160,6 +167,9 @@ class Future(object):
160
167
  # weakref to resolved (already constructed) sampleset
161
168
  self._sampleset = None
162
169
 
170
+ # file buffer for binary-ref answer data
171
+ self._answer_data = io.BytesIO()
172
+
163
173
  # make Future ordered
164
174
 
165
175
  def __lt__(self, other):
@@ -873,6 +883,10 @@ class Future(object):
873
883
  """
874
884
  return self.result()['problem_type']
875
885
 
886
+ @property
887
+ def answer_data(self):
888
+ return self.result().get('answer')
889
+
876
890
  def __getitem__(self, key):
877
891
  """Provide a simple results item getter. Blocks if future is unresolved.
878
892
 
@@ -894,13 +908,19 @@ class Future(object):
894
908
  if self._exception is not None:
895
909
  raise self._exception
896
910
 
897
- # If someone else took care of this while we were waiting
898
- if self._result is not None:
899
- return self._result
911
+ with self._result_write_lock:
912
+ # If someone else took care of decoding while we were waiting
913
+ if self._result is not None:
914
+ return self._result
915
+
916
+ # extract results from the response
917
+ # note: decoding might mutate `self._message`, so it should be only called once
918
+ self._decode()
919
+ self._alias_result()
900
920
 
901
- # Prepare results from the response
902
- self._decode()
903
- self._alias_result()
921
+ # signal answer data downloaded
922
+ if 'answer' in self._result:
923
+ self._answer_data_ready_event.set()
904
924
 
905
925
  # create a direct reference to sampleset if already available in response
906
926
  # NB: in this case we don't actually need a weakref (strong ref is fine),
@@ -938,7 +958,7 @@ class Future(object):
938
958
  """Decode answer data from the response."""
939
959
  start = time.time()
940
960
  self._patch_offset()
941
- self._result = self.solver.decode_response(self._message)
961
+ self._result = self.solver.decode_response(self._message, answer_data=self._answer_data)
942
962
  self.parse_time = time.time() - start
943
963
  return self._result
944
964
 
@@ -14,7 +14,7 @@
14
14
 
15
15
  __packagename__ = 'dwave-cloud-client'
16
16
  __title__ = 'D-Wave Cloud Client'
17
- __version__ = '0.11.4'
17
+ __version__ = '0.12.0.dev0'
18
18
  __author__ = 'D-Wave Systems Inc.'
19
19
  __description__ = 'A minimal client for interacting with D-Wave cloud resources.'
20
20
  __url__ = 'https://github.com/dwavesystems/dwave-cloud-client'