dwave-preprocessing 0.6.12__cp315-cp315-win_amd64.whl
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.
- dwave/preprocessing/__init__.py +41 -0
- dwave/preprocessing/composites/__init__.py +34 -0
- dwave/preprocessing/composites/clip.py +116 -0
- dwave/preprocessing/composites/connected_components.py +115 -0
- dwave/preprocessing/composites/fix_variables.py +155 -0
- dwave/preprocessing/composites/scale.py +146 -0
- dwave/preprocessing/composites/spin_reversal_transform.py +263 -0
- dwave/preprocessing/cyfix_variables.cp315-win_amd64.pyd +0 -0
- dwave/preprocessing/cyfix_variables.cpp +32554 -0
- dwave/preprocessing/cyfix_variables.pyx +58 -0
- dwave/preprocessing/include/dwave/exceptions.hpp +28 -0
- dwave/preprocessing/include/dwave/flags.hpp +63 -0
- dwave/preprocessing/include/dwave/presolve.hpp +91 -0
- dwave/preprocessing/include/dwave-preprocessing/fix_variables.hpp +119 -0
- dwave/preprocessing/include/dwave-preprocessing/helper_data_structures.hpp +152 -0
- dwave/preprocessing/include/dwave-preprocessing/helper_graph_algorithms.hpp +476 -0
- dwave/preprocessing/include/dwave-preprocessing/implication_network.hpp +695 -0
- dwave/preprocessing/include/dwave-preprocessing/mapping_policy.hpp +124 -0
- dwave/preprocessing/include/dwave-preprocessing/posiform_info.hpp +384 -0
- dwave/preprocessing/include/dwave-preprocessing/push_relabel.hpp +775 -0
- dwave/preprocessing/libcpp.pxd +59 -0
- dwave/preprocessing/lower_bounds.py +94 -0
- dwave/preprocessing/presolve/__init__.pxd +13 -0
- dwave/preprocessing/presolve/__init__.py +16 -0
- dwave/preprocessing/presolve/cypresolve.cp315-win_amd64.pyd +0 -0
- dwave/preprocessing/presolve/cypresolve.cpp +42950 -0
- dwave/preprocessing/presolve/cypresolve.pxd +45 -0
- dwave/preprocessing/presolve/cypresolve.pyi +50 -0
- dwave/preprocessing/presolve/cypresolve.pyx +340 -0
- dwave/preprocessing/presolve/exceptions.py +21 -0
- dwave/preprocessing/presolve/pypresolve.py +173 -0
- dwave/preprocessing/src/exceptions.cpp +21 -0
- dwave/preprocessing/src/presolve.cpp +105 -0
- dwave/preprocessing/src/presolveimpl.hpp +1060 -0
- dwave_preprocessing-0.6.12.dist-info/DELVEWHEEL +2 -0
- dwave_preprocessing-0.6.12.dist-info/METADATA +91 -0
- dwave_preprocessing-0.6.12.dist-info/RECORD +41 -0
- dwave_preprocessing-0.6.12.dist-info/WHEEL +5 -0
- dwave_preprocessing-0.6.12.dist-info/licenses/LICENSE +203 -0
- dwave_preprocessing-0.6.12.dist-info/top_level.txt +1 -0
- dwave_preprocessing.libs/msvcp140-7c26614e1d733892c2deac7e245ce115.dll +0 -0
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# Copyright 2021 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 typing
|
|
16
|
+
|
|
17
|
+
import dimod
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from dimod import Vartype, ComposedSampler
|
|
21
|
+
|
|
22
|
+
__all__ = ['SpinReversalTransformComposite']
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# versionadded (0.6.8) to the __init__ file for context manager
|
|
26
|
+
|
|
27
|
+
class SpinReversalTransformComposite(ComposedSampler):
|
|
28
|
+
r"""Composite for applying spin reversal transform preprocessing.
|
|
29
|
+
|
|
30
|
+
A spin-reversal transform can improve sample statistics when the sampler is
|
|
31
|
+
a physical object with asymmetries such as a QPU.
|
|
32
|
+
The technique works as follows: given an :math:`n`-variable Ising problem,
|
|
33
|
+
the composite selects a random :math:`g\in\{\pm1\}^n` and transforms the
|
|
34
|
+
problem via :math:`h_i\mapsto h_ig_i` and
|
|
35
|
+
:math:`J_{ij}\mapsto J_{ij}g_ig_j`. Solutions :math:`s` of the original
|
|
36
|
+
problem and :math:`s^\prime` of the transformed problem are related by
|
|
37
|
+
:math:`s^\prime_i=s_ig_i` and have identical energies.\ [#km]_
|
|
38
|
+
|
|
39
|
+
.. note::
|
|
40
|
+
If you are configuring an anneal schedule, be mindful that this
|
|
41
|
+
composite does not recognize the ``initial_state`` parameter used by
|
|
42
|
+
dimod's :class:`~dwave.system.samplers.DWaveSampler` for reverse
|
|
43
|
+
annealing (composites do not generally process all keywords of child
|
|
44
|
+
samplers) and does not flip any of the configured initial states.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
sampler: A `dimod` sampler object.
|
|
48
|
+
|
|
49
|
+
seed: As passed to :func:`numpy.random.default_rng`.
|
|
50
|
+
|
|
51
|
+
Examples:
|
|
52
|
+
This example composes a dimod ExactSolver sampler with spin transforms then
|
|
53
|
+
uses it to sample an Ising problem.
|
|
54
|
+
|
|
55
|
+
>>> from dimod import ExactSolver
|
|
56
|
+
>>> from dwave.preprocessing.composites import SpinReversalTransformComposite
|
|
57
|
+
>>> base_sampler = ExactSolver()
|
|
58
|
+
>>> composed_sampler = SpinReversalTransformComposite(base_sampler)
|
|
59
|
+
... # Sample an Ising problem
|
|
60
|
+
>>> response = composed_sampler.sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})
|
|
61
|
+
>>> response.first.sample
|
|
62
|
+
{'a': -1, 'b': -1}
|
|
63
|
+
|
|
64
|
+
References
|
|
65
|
+
----------
|
|
66
|
+
.. [#km] Andrew D. King and Catherine C. McGeoch. Algorithm engineering
|
|
67
|
+
for a quantum annealing platform. https://arxiv.org/abs/1410.2628,
|
|
68
|
+
2014.
|
|
69
|
+
|
|
70
|
+
"""
|
|
71
|
+
_children: typing.List[dimod.core.Sampler]
|
|
72
|
+
_parameters: typing.Dict[str, typing.Sequence[str]]
|
|
73
|
+
_properties: typing.Dict[str, typing.Any]
|
|
74
|
+
|
|
75
|
+
def __init__(self, child: dimod.core.Sampler, *, seed=None):
|
|
76
|
+
self._child = child
|
|
77
|
+
self.rng = np.random.default_rng(seed)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def children(self) -> typing.List[dimod.core.Sampler]:
|
|
81
|
+
try:
|
|
82
|
+
return self._children
|
|
83
|
+
except AttributeError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
self._children = children = [self._child]
|
|
87
|
+
return children
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def parameters(self) -> typing.Dict[str, typing.Sequence[str]]:
|
|
91
|
+
try:
|
|
92
|
+
return self._parameters
|
|
93
|
+
except AttributeError:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
self._parameters = parameters = dict(spin_reversal_variables=tuple())
|
|
97
|
+
parameters.update(self._child.parameters)
|
|
98
|
+
return parameters
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def properties(self) -> typing.Dict[str, typing.Any]:
|
|
102
|
+
try:
|
|
103
|
+
return self._properties
|
|
104
|
+
except AttributeError:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
self._properties = dict(child_properties=self._child.properties)
|
|
108
|
+
return self._properties
|
|
109
|
+
|
|
110
|
+
class _SampleSets:
|
|
111
|
+
def __init__(self, samplesets: typing.List[dimod.SampleSet]):
|
|
112
|
+
self.samplesets = samplesets
|
|
113
|
+
|
|
114
|
+
def done(self) -> bool:
|
|
115
|
+
return all(ss.done() for ss in self.samplesets)
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def _reorder_variables(sampleset: dimod.SampleSet,
|
|
119
|
+
order: dimod.variables.Variables) -> dimod.SampleSet:
|
|
120
|
+
"""Return a sampleset with the given variable order."""
|
|
121
|
+
if sampleset.variables == order:
|
|
122
|
+
return sampleset
|
|
123
|
+
|
|
124
|
+
# .index(...) is O(1) for dimod's Variables objects so this isn't too bad
|
|
125
|
+
sampleset_order = sampleset.variables
|
|
126
|
+
reorder = [sampleset_order.index(v) for v in order]
|
|
127
|
+
|
|
128
|
+
return dimod.SampleSet.from_samples(
|
|
129
|
+
(sampleset.record.sample[:, reorder], order),
|
|
130
|
+
sort_labels=False,
|
|
131
|
+
vartype=sampleset.vartype,
|
|
132
|
+
info=sampleset.info,
|
|
133
|
+
**sampleset.data_vectors,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
@dimod.decorators.nonblocking_sample_method
|
|
137
|
+
def sample(self, bqm: dimod.BinaryQuadraticModel, *,
|
|
138
|
+
srts: typing.Optional[np.ndarray] = None,
|
|
139
|
+
num_spin_reversal_transforms: typing.Optional[int] = None,
|
|
140
|
+
**kwargs,
|
|
141
|
+
):
|
|
142
|
+
"""Sample from the binary quadratic model.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
bqm: Binary quadratic model to be sampled from.
|
|
146
|
+
|
|
147
|
+
srts: A boolean NumPy array with shape
|
|
148
|
+
``(num_spin_reversal_transforms, bqm.num_variables)``.
|
|
149
|
+
True indicates a flip and False indicates no flip; applied to
|
|
150
|
+
in the order given by ``bqm.variables``.
|
|
151
|
+
If this is not specified as an input values are generated uniformly
|
|
152
|
+
at random from the class pseudo-random number generator.
|
|
153
|
+
|
|
154
|
+
num_spin_reversal_transforms:
|
|
155
|
+
Number of spin reversal transform runs.
|
|
156
|
+
A value of ``0`` will not transform the problem.
|
|
157
|
+
If you specify a nonzero value, each spin reversal transform
|
|
158
|
+
will result in an independent run of the child sampler.
|
|
159
|
+
If ``srts`` is set then ``num_spin_reversal_transforms``
|
|
160
|
+
is inferred by the shape, otherwise the default is 1.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
A sample set. Note that for a sampler that returns ``num_reads`` samples,
|
|
164
|
+
the sample set will contain ``num_reads*num_spin_reversal_transforms`` samples.
|
|
165
|
+
|
|
166
|
+
Raises:
|
|
167
|
+
ValueError: If ``srts`` is inconsistent with
|
|
168
|
+
``num_spin_reversal_transforms`` or the binary quadratic model.
|
|
169
|
+
|
|
170
|
+
Examples:
|
|
171
|
+
This example runs 10 spin reversals applied to an unfrustrated chain
|
|
172
|
+
of length 6.
|
|
173
|
+
|
|
174
|
+
Using the lowest energy (ground) state returned, you can define a
|
|
175
|
+
special SRT that transforms all programmed couplers to be ferromagnetic
|
|
176
|
+
(ground state to all 1).
|
|
177
|
+
|
|
178
|
+
>>> from dimod import ExactSolver
|
|
179
|
+
>>> import numpy as np
|
|
180
|
+
>>> from dwave.preprocessing.composites import SpinReversalTransformComposite
|
|
181
|
+
>>> base_sampler = ExactSolver()
|
|
182
|
+
>>> composed_sampler = SpinReversalTransformComposite(base_sampler)
|
|
183
|
+
...
|
|
184
|
+
>>> num_var = 6
|
|
185
|
+
>>> num_spin_reversal_transforms = 10
|
|
186
|
+
>>> J = {(i, i+1): np.random.choice([-1,1]) for i in range(num_var-1)}
|
|
187
|
+
>>> h = {i: 0 for i in range(num_var)}
|
|
188
|
+
>>> response = composed_sampler.sample_ising(h, J,
|
|
189
|
+
... num_spin_reversal_transforms=num_spin_reversal_transforms)
|
|
190
|
+
>>> len(response) == 2**num_var * num_spin_reversal_transforms
|
|
191
|
+
True
|
|
192
|
+
>>> srts = np.array([[response.first.sample[i] != 1 for i in range(num_var)]])
|
|
193
|
+
>>> response = composed_sampler.sample_ising(h, J,
|
|
194
|
+
... srts=srts, num_reads=1)
|
|
195
|
+
>>> sum(response.record.num_occurrences) == 2**num_var
|
|
196
|
+
True
|
|
197
|
+
"""
|
|
198
|
+
sampler = self._child
|
|
199
|
+
|
|
200
|
+
if srts is not None:
|
|
201
|
+
nsrt, num_bqm_var = srts.shape
|
|
202
|
+
if num_bqm_var != bqm.num_variables:
|
|
203
|
+
raise ValueError('srt shape is inconsistent with the bqm')
|
|
204
|
+
if num_spin_reversal_transforms is not None:
|
|
205
|
+
if num_spin_reversal_transforms != nsrt:
|
|
206
|
+
raise ValueError('srt shape is inconsistent with num_spin_reversal_transforms')
|
|
207
|
+
else:
|
|
208
|
+
num_spin_reversal_transforms = nsrt
|
|
209
|
+
elif num_spin_reversal_transforms is None:
|
|
210
|
+
num_spin_reversal_transforms = 1
|
|
211
|
+
|
|
212
|
+
# No SRTs, so just pass the problem through
|
|
213
|
+
if num_spin_reversal_transforms == 0 or not bqm.num_variables:
|
|
214
|
+
sampleset = sampler.sample(bqm, **kwargs)
|
|
215
|
+
# yield twice because we're using the @nonblocking_sample_method
|
|
216
|
+
yield sampleset # this one signals done()-ness
|
|
217
|
+
yield sampleset # this is the one actually used by the user
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
if srts is None:
|
|
221
|
+
srts = self.rng.random((num_spin_reversal_transforms, bqm.num_variables)) > .5
|
|
222
|
+
|
|
223
|
+
# we'll be modifying the BQM, so make a copy
|
|
224
|
+
bqm = bqm.copy()
|
|
225
|
+
|
|
226
|
+
# Submit the problems
|
|
227
|
+
samplesets: typing.List[dimod.SampleSet] = []
|
|
228
|
+
flipped = np.zeros(bqm.num_variables, dtype=bool) # what variables are currently flipped
|
|
229
|
+
for i in range(num_spin_reversal_transforms):
|
|
230
|
+
# determine what needs to be flipped
|
|
231
|
+
transform = flipped != srts[i, :]
|
|
232
|
+
|
|
233
|
+
# apply the transform
|
|
234
|
+
for v, flip in zip(bqm.variables, transform):
|
|
235
|
+
if flip:
|
|
236
|
+
bqm.flip_variable(v)
|
|
237
|
+
flipped[transform] = ~flipped[transform]
|
|
238
|
+
|
|
239
|
+
samplesets.append(sampler.sample(bqm, **kwargs))
|
|
240
|
+
|
|
241
|
+
# Yield a view of the samplesets that reports done()-ness
|
|
242
|
+
yield self._SampleSets(samplesets)
|
|
243
|
+
|
|
244
|
+
# Reorder the variables of all the returned samplesets to match our
|
|
245
|
+
# original BQM
|
|
246
|
+
samplesets = [self._reorder_variables(ss, bqm.variables) for ss in samplesets]
|
|
247
|
+
|
|
248
|
+
# Undo the SRTs according to vartype
|
|
249
|
+
if bqm.vartype is Vartype.BINARY:
|
|
250
|
+
for i, sampleset in enumerate(samplesets):
|
|
251
|
+
sampleset.record.sample[:, srts[i, :]] = 1 - sampleset.record.sample[:, srts[i, :]]
|
|
252
|
+
elif bqm.vartype is Vartype.SPIN:
|
|
253
|
+
for i, sampleset in enumerate(samplesets):
|
|
254
|
+
sampleset.record.sample[:, srts[i, :]] *= -1
|
|
255
|
+
else:
|
|
256
|
+
raise RuntimeError("unexpected vartype")
|
|
257
|
+
if num_spin_reversal_transforms == 1:
|
|
258
|
+
# If one sampleset, return full information
|
|
259
|
+
# (info returned in full)
|
|
260
|
+
yield samplesets[0]
|
|
261
|
+
else:
|
|
262
|
+
# finally combine all samplesets together
|
|
263
|
+
yield dimod.concatenate(samplesets)
|
|
Binary file
|