/
binary_quadratic_model.py
2191 lines (1725 loc) · 79 KB
/
binary_quadratic_model.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections.abc as abc
import copy
import itertools
import io
import json
import operator
import tempfile
import warnings
from numbers import Integral, Number
from typing import (Any, BinaryIO, ByteString, Callable,
Hashable, Iterable, Iterator,
Mapping, MutableMapping, Optional, Sequence,
Tuple, Union,
)
import numpy as np
try:
from numpy.typing import ArrayLike, DTypeLike
except ImportError:
ArrayLike = Any
DTypeLike = Any
from dimod.binary.cybqm import cyBQM_float32, cyBQM_float64
from dimod.binary.pybqm import pyBQM
from dimod.binary.vartypeview import VartypeView
from dimod.core.bqm import BQM as BQMabc
from dimod.decorators import forwarding_method, unique_variable_labels
from dimod.quadratic import QuadraticModel, QM
from dimod.serialization.fileview import SpooledTemporaryFile, _BytesIO, VariablesSection
from dimod.serialization.fileview import load, read_header, write_header
from dimod.sym import Eq, Ge, Le
from dimod.typing import Bias, Variable, VartypeLike
from dimod.variables import Variables, iter_deserialize_variables
from dimod.vartypes import as_vartype, Vartype
from dimod.views.quadratic import QuadraticViewsMixin
__all__ = ['BinaryQuadraticModel',
'BQM',
'DictBQM',
'Float32BQM',
'Float64BQM',
'as_bqm',
'Spin', 'Binary', 'Spins', 'Binaries',
'quicksum',
]
BQM_MAGIC_PREFIX = b'DIMODBQM'
class BinaryQuadraticModel(QuadraticViewsMixin):
r"""Binary quadratic model.
Binary quadratic models (BQMs) are problems of the form:
.. math::
E(\bf{v})
= \sum_{i=1} a_i v_i
+ \sum_{i<j} b_{i,j} v_i v_j
+ c
\qquad\qquad v_i \in\{-1,+1\} \text{ or } \{0,1\}
where :math:`a_{i}, b_{ij}, c` are real values.
This class encodes Ising and quadratic unconstrained binary optimization
(QUBO) models used by samplers such as the D-Wave system.
BQMs can be created in several ways:
``BinaryQuadraticModel(vartype)``
Create a BQM with no variables or interactions.
``vartype`` must be one of:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, +1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
``BinaryQuadraticModel(bqm)``
Create a BQM from another BQM. The resulting BQM will have the
same variables, linear biases, quadratic biases and offset as
``bqm``.
``BinaryQuadraticModel(bqm, vartype)``
Create a BQM from another BQM, changing it to the appropriate
``vartype`` if necessary.
``BinaryQuadraticModel(n, vartype)``
Create a BQM with ``n`` variables, indexed linearly from zero,
setting all biases to zero.
``BinaryQuadraticModel(quadratic, vartype)``
Create a BQM from quadratic biases given as a square array_like_
or a dictionary of the form ``{(u, v): b, ...}``. Note that when
formed with SPIN-variables, biases on the diagonal are added to the
offset.
``BinaryQuadraticModel(linear, quadratic, vartype)``
Create a BQM from linear and quadratic biases, where ``linear`` is a
one-dimensional array_like_ or a dictionary of the form
``{v: b, ...}``.
``BinaryQuadraticModel(linear, quadratic, offset, vartype)``
Create a BQM from linear and quadratic biases and an offset.
``offset`` must be a number.
Args:
*args: See above
offset: The offset (see above) may be supplied as a keyword argument.
vartype: The variable type (see above) may be supplied as a keyword
argument.
dtype: The data type.
:class:`numpy.float32` and :class:`numpy.float64` are supported.
Defaults to :class:`numpy.float64`.
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
"""
_DATA_CLASSES = {
np.dtype(np.float32): cyBQM_float32,
np.dtype(np.float64): cyBQM_float64,
np.dtype(object): pyBQM,
}
DEFAULT_DTYPE = np.float64
"""The default dtype used to construct the class."""
def __init__(self, *args,
offset: Optional[Bias] = None,
vartype: Optional[VartypeLike] = None,
dtype: Optional[DTypeLike] = None):
if vartype is not None:
args = [*args, vartype]
# developer note: I regret ever setting up this construction system
# but it's gotten out there so we're stuck with it
# I would like to reestablish kwarg construction at some point
if len(args) == 0:
raise TypeError("A valid vartype or another bqm must be provided")
if len(args) == 1:
# BQM(bqm) or BQM(vartype)
if hasattr(args[0], 'vartype'):
# bqm case
if offset is not None:
# see note for (linear, quadratic, offset, vartype) below
raise TypeError("cannot provide 'offset' when input is a binary quadratic model")
self._init_bqm(args[0], vartype=args[0].vartype, dtype=dtype)
else:
self._init_empty(vartype=args[0], dtype=dtype)
elif len(args) == 2:
# BQM(bqm, vartype), BQM(n, vartype) or BQM(M, vartype)
if isinstance(args[0], Integral):
self._init_empty(vartype=args[1], dtype=dtype)
self.resize(args[0])
elif hasattr(args[0], 'vartype'):
if offset is not None:
# see note for (linear, quadratic, offset, vartype) below
raise TypeError("cannot provide 'offset' when input is a binary quadratic model")
self._init_bqm(args[0], vartype=args[1], dtype=dtype)
else:
self._init_components([], args[0], 0.0, args[1], dtype=dtype)
elif len(args) == 3:
# BQM(linear, quadratic, vartype)
self._init_components(args[0], args[1], 0.0, args[2], dtype=dtype)
elif len(args) == 4:
# BQM(linear, quadratic, offset, vartype)
if offset is not None:
# we don't strictly need to fail in this case, we could instead
# add it, but I think this is closer to the normal python behavior
# of failing if an argument is provided twice
raise TypeError("BinaryQuadraticModel() got multiple values for 'offset'")
self._init_components(*args, dtype=dtype)
else:
msg = "__init__() takes 4 positional arguments but {} were given."
raise TypeError(msg.format(len(args)))
# we already checked the one case that doesn't support offset
if offset is not None:
self.offset += offset
def _init_bqm(self, bqm, vartype, dtype):
if dtype is None:
dtype = bqm.dtype
if vartype is None:
vartype = bqm.vartype
self.data = type(self)._DATA_CLASSES[np.dtype(dtype)](vartype)
self.update(bqm)
def _init_components(self, linear, quadratic, offset, vartype, dtype):
self._init_empty(vartype, dtype)
self.offset = offset
vartype = self.vartype
if isinstance(quadratic, (abc.Mapping, abc.Iterator)):
if isinstance(quadratic, abc.Mapping):
quadratic = ((u, v, b) for (u, v), b in quadratic.items())
for u, v, bias in quadratic:
if u == v:
if vartype is Vartype.BINARY:
self.add_linear(u, bias)
elif vartype is Vartype.SPIN:
self.offset += bias
else:
raise RuntimeError(f"unexpected vartype: {vartype}")
else:
self.add_quadratic(u, v, bias)
else:
if self.dtype == np.dtype('O') and not hasattr(quadratic, 'dtype'):
dt = np.dtype('O')
else:
dt = None
quadratic = np.asarray(quadratic, order='C', dtype=dt)
diag = np.diagonal(quadratic)
if diag.any():
if vartype is Vartype.SPIN:
self.offset += diag.sum()
elif vartype is Vartype.BINARY:
self.add_linear_from_array(diag)
else:
raise RuntimeError(f"unexpected vartype: {vartype}")
# zero out the diagonal
new_quadratic = np.array(quadratic, copy=True)
np.fill_diagonal(new_quadratic, 0)
self.add_quadratic_from_dense(new_quadratic)
else:
self.add_quadratic_from_dense(quadratic)
if isinstance(linear, (abc.Iterator, abc.Mapping)):
self.add_linear_from(linear)
else:
self.add_linear_from_array(linear)
def _init_empty(self, vartype, dtype):
dtype = self.DEFAULT_DTYPE if dtype is None else dtype
self.data = type(self)._DATA_CLASSES[np.dtype(dtype)](vartype)
def __init_subclass__(cls, default_dtype=np.float64, **kwargs):
super().__init_subclass__(**kwargs)
cls.DEFAULT_DTYPE = np.dtype(default_dtype)
def __copy__(self):
new = type(self).__new__(type(self))
new.data = copy.copy(self.data)
return new
def __deepcopy__(self, memo):
new = type(self).__new__(type(self))
new.data = copy.deepcopy(self.data, memo)
memo[id(self)] = new
return new
def __len__(self):
return self.num_variables
def __repr__(self):
return "{!s}({!s}, {!s}, {!r}, {!r})".format(type(self).__name__,
self.linear,
self.quadratic,
self.offset,
self.vartype.name)
# todo: singledisptach in 3.8
def __add__(self, other: Union['BQM', QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, BinaryQuadraticModel):
if other.num_variables and other.vartype != self.vartype:
# promote to QM
qm = QuadraticModel.from_bqm(self)
qm += QuadraticModel.from_bqm(other)
return qm
bqm = self.copy()
bqm.update(other)
return bqm
if isinstance(other, QuadraticModel):
return QuadraticModel.from_bqm(self) + other
if isinstance(other, Number):
bqm = self.copy()
bqm.offset += other
return bqm
return NotImplemented
def __iadd__(self, other: Union['BQM', Bias]) -> 'BQM':
if isinstance(other, BinaryQuadraticModel):
if other.num_variables and other.vartype != self.vartype:
return NotImplemented # fallback on __add__
self.update(other)
return self
if isinstance(other, Number):
self.offset += other
return self
return NotImplemented
def __radd__(self, other: Union[QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, Number):
return self + other # communative
if isinstance(other, QuadraticModel):
# promote to QM
qm = other.copy()
qm += QuadraticModel.from_bqm(self)
return qm
return NotImplemented
def __mul__(self, other: Union['BQM', QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, BinaryQuadraticModel):
if not (self.is_linear() and other.is_linear()):
raise TypeError(
"cannot multiply BQMs with interactions")
elif other.num_variables and other.vartype != self.vartype:
# promote self
return QuadraticModel.from_bqm(self) * other
bqm = self.empty(self.vartype)
self_offset = self.offset
other_offset = other.offset
for u, ubias in self.linear.items():
for v, vbias in other.linear.items():
if u == v:
if self.vartype is Vartype.BINARY:
bqm.add_linear(u, ubias*vbias)
else:
bqm.offset += ubias * vbias
else:
bqm.add_quadratic(u, v, ubias * vbias)
bqm.add_linear(u, ubias * other_offset)
for v, bias in other.linear.items():
bqm.add_linear(v, bias*self_offset)
bqm.offset += self_offset*other_offset
return bqm
if isinstance(other, QuadraticModel):
# promote to QM
qm = QuadraticModel.from_bqm(self)
qm *= other
return qm
if isinstance(other, Number):
bqm = self.copy()
bqm.scale(other)
return bqm
return NotImplemented
def __imul__(self, other: Bias) -> 'BQM':
# in-place multiplication is only defined for numbers
if isinstance(other, Number):
self.scale(other)
return self
return NotImplemented
def __rmul__(self, other: Union[QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, Number):
return self * other # communative
if isinstance(other, QuadraticModel):
# promote self to QM
qm = QuadraticModel.from_bqm(self)
qm *= other
return qm
return NotImplemented
def __neg__(self: 'BinaryQuadraticModel') -> 'BinaryQuadraticModel':
new = self.copy()
new.scale(-1)
return new
def __pos__(self: 'BinaryQuadraticModel') -> 'BinaryQuadraticModel':
return self
def __pow__(self, other: int) -> 'BinaryQuadraticModel':
if isinstance(other, int):
if other != 2:
raise ValueError("the only supported power for binary quadratic models is 2")
if not self.is_linear():
raise ValueError("only linear models can be squared")
return self * self
return NotImplemented
def __sub__(self, other: Union['BQM', QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, BinaryQuadraticModel):
if other.num_variables and other.vartype != self.vartype:
qm = QuadraticModel.from_bqm(self)
qm -= QuadraticModel.from_bqm(other)
return qm
bqm = self.copy()
bqm.scale(-1)
bqm.update(other)
bqm.scale(-1)
return bqm
if isinstance(other, QuadraticModel):
# promote self to QM
return QuadraticModel.from_bqm(self) - other
if isinstance(other, Number):
bqm = self.copy()
bqm.offset -= other
return bqm
return NotImplemented
def __isub__(self, other: Union['BQM', Bias]) -> 'BQM':
if isinstance(other, BinaryQuadraticModel):
if other.num_variables and other.vartype != self.vartype:
return NotImplemented # fallback on __sub__
self.scale(-1)
self.update(other)
self.scale(-1)
return self
if isinstance(other, Number):
self.offset -= other
return self
return NotImplemented
def __rsub__(self, other: Union[QM, Bias]) -> Union['BQM', QM]:
if isinstance(other, Number):
bqm = -self # makes a new one
bqm.offset += other
return bqm
if isinstance(other, QuadraticModel):
# promote to QM
return other - QuadraticModel.from_bqm(self)
return NotImplemented
def __truediv__(self, other: Bias) -> 'BQM':
return self * (1 / other)
def __itruediv__(self, other: Bias) -> 'BQM':
self *= (1 / other)
return self
def __eq__(self, other):
if isinstance(other, Number):
return Eq(self, other)
# support equality for backwards compatibility
return self.is_equal(other)
def __ge__(self, other: Bias):
if isinstance(other, Number):
return Ge(self, other)
return NotImplemented
def __le__(self, other: Bias):
if isinstance(other, Number):
return Le(self, other)
return NotImplemented
def __ne__(self, other):
return not self.is_equal(other)
@property
def binary(self) -> 'BinaryQuadraticModel':
"""Binary-valued version of the binary quadratic model.
If the binary quadratic model is binary-valued, this references itself,
otherwise it references a view.
"""
if self.vartype is Vartype.BINARY:
return self
try:
bqm = self._binary
except AttributeError:
pass
else:
if bqm.vartype is Vartype.BINARY:
return bqm
bqm = type(self).__new__(type(self))
bqm.data = VartypeView(self.data, Vartype.BINARY)
bqm._spin = self
self._binary: BinaryQuadraticModel = bqm
return bqm
@property
def dtype(self) -> np.dtype:
"""Data-type of the model's biases."""
return self.data.dtype
@property
def offset(self) -> np.number:
"""Constant energy offset associated with the model."""
return self.data.offset
@offset.setter
def offset(self, offset):
self.data.offset = offset
@property
def num_interactions(self) -> int:
"""Number of interactions in the model.
The complexity is linear in the number of variables.
"""
return self.data.num_interactions()
@property
def num_variables(self) -> int:
"""Number of variables in the model."""
return self.data.num_variables()
@property
def shape(self) -> Tuple[int, int]:
"""A 2-tuple of :attr:`num_variables` and :attr:`num_interactions`."""
return self.num_variables, self.num_interactions
@property
def spin(self) -> 'BinaryQuadraticModel':
"""Spin-valued version of the binary quadratic model.
If the binary quadratic model is spin-valued, this references itself,
otherwise it references a view.
"""
if self.vartype is Vartype.SPIN:
return self
try:
bqm = self._spin
except AttributeError:
pass
else:
if bqm.vartype is Vartype.SPIN:
return bqm
bqm = type(self).__new__(type(self))
bqm.data = VartypeView(self.data, Vartype.SPIN)
bqm._binary = self
self._spin: BinaryQuadraticModel = bqm
return bqm
@property
def variables(self) -> Variables:
"""The variables of the binary quadratic model"""
return self.data.variables
@property
def vartype(self) -> Vartype:
"""The model's variable type.
One of :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`.
"""
return self.data.vartype()
@classmethod
def shapeable(cls) -> bool:
"""Returns True if the binary quadratic model is shapeable.
This method is deprecated. All BQMs are shapeable.
"""
name = cls.__name__
warnings.warn(
f"{name}.shapeable() is deprecated. All BQMs are shapeable.",
DeprecationWarning,
stacklevel=2)
return True
@forwarding_method
def add_linear(self, v: Variable, bias: Bias):
"""Add a linear term."""
return self.data.add_linear
def add_linear_equality_constraint(
self, terms: Iterable[Tuple[Variable, Bias]],
lagrange_multiplier: Bias, constant: Bias):
"""Add a linear constraint as a quadratic objective.
Adds a linear constraint of the form
:math:`\\sum_{i} a_{i} x_{i} + C = 0`
to the binary quadratic model as a quadratic objective.
Args:
terms (iterable/iterator):
An iterable of 2-tuples, (variable, bias), with each tuple
constituting a term in :math:`\sum_{i} a_{i} x_{i},
with :math:`i` being the length of the iterable.
lagrange_multiplier:
A weight or the penalty strength. This value is
multiplied by the entire constraint objective and added to the
binary quadratic model (it does not appear explicitly in the
equation above).
constant:
The constant value of the constraint, :math:`C`, in the equation
above.
"""
try:
self.data.add_linear_equality_constraint(
terms, lagrange_multiplier, constant)
return
except NotImplementedError:
pass
for pair in itertools.combinations_with_replacement(terms, 2):
(u, ubias), (v, vbias) = pair
if u == v:
if self.vartype is Vartype.SPIN:
self.add_linear(
u, 2 * lagrange_multiplier * ubias * constant)
self.offset += lagrange_multiplier * ubias * vbias
else:
self.add_linear(
u, lagrange_multiplier * ubias * (2*constant + vbias))
else:
self.add_quadratic(
u, v, 2 * lagrange_multiplier * ubias * vbias)
self.offset += lagrange_multiplier * constant * constant
def add_linear_inequality_constraint(
self, terms: Iterable[Tuple[Variable, int]],
lagrange_multiplier: Bias,
label: str,
constant: int = 0,
lb: int = np.iinfo(np.int64).min,
ub: int = 0,
cross_zero: bool = False
) -> Iterable[Tuple[Variable, int]]:
"""Add a linear inequality constraint as a quadratic objective.
Adds a linear inequality constraint of the form:
math:'lb <= \sum_{i,k} a_{i,k} x_{i,k} + constant <= ub'
to the binary quadratic model as a quadratic objective.
For constraints with fractional coefficients, multiply both sides of the
inequality by an appropriate factor of ten to attain or approximate
integer coefficients.
Args:
terms (iterable/iterator):
An iterable of 2-tuples, (variable, bias), with each tuple
constituting a term in :math:`\sum_{i} a_{i} x_{i},
with :math:`i` being the length of the iterable.
lagrange_multiplier:
A weight or the penalty strength. This value is
multiplied by the entire constraint objective and added to the
binary quadratic model (it does not appear explicitly in the
equation above).
label:
Prefix used to label the slack variables used to create the new
objective.
constant:
The constant value of the constraint.
lb:
lower bound for the constraint.
ub:
upper bound for the constraint.
cross_zero:
When True, adds zero to the domain of constraint.
Returns:
slack_terms: An iterable of 2-tuples for the new slack variables
(variable, int), with each tuple constituting a term in
:math:`\sum_{i} b_{i} slack {i},
with :math:`i` being the length of the iterable and :math:`b` being
the coefficient for the slack variable.
"""
if isinstance(terms, Iterator):
terms = list(terms)
if int(constant) != constant or int(lb) != lb or int(ub) != ub or any(
int(bias) != bias for _, bias in terms):
warnings.warn("For constraints with fractional coefficients, "
"multiply both sides of the inequality by an "
"appropriate factor of ten to attain or "
"approximate integer coefficients. ")
terms_upper_bound = sum(v for _, v in terms if v > 0)
terms_lower_bound = sum(v for _, v in terms if v < 0)
ub_c = min(terms_upper_bound, ub - constant)
lb_c = max(terms_lower_bound, lb - constant)
if terms_upper_bound <= ub_c and terms_lower_bound >= lb_c:
warnings.warn(
f'Did not add constraint {label}.'
' This constraint is feasible'
' with any value for state variables.')
return []
if ub_c < lb_c:
raise ValueError(
f'The given constraint ({label}) is infeasible with any value'
' for state variables.')
slack_upper_bound = int(ub_c - lb_c)
if slack_upper_bound == 0:
self.add_linear_equality_constraint(terms, lagrange_multiplier, -ub_c)
return []
else:
slack_terms = []
zero_constraint = False
if cross_zero:
if lb_c > 0 or ub_c < 0:
if ub_c-slack_upper_bound > 0:
zero_constraint = True
num_slack = int(np.floor(np.log2(slack_upper_bound)))
slack_coefficients = [2 ** j for j in range(num_slack)]
if slack_upper_bound - 2 ** num_slack >= 0:
slack_coefficients.append(slack_upper_bound - 2 ** num_slack + 1)
for j, s in enumerate(slack_coefficients):
sv = self.add_variable(f'slack_{label}_{j}')
slack_terms.append((sv, s))
if zero_constraint:
sv = self.add_variable(f'slack_{label}_{num_slack + 1}')
slack_terms.append((sv, ub_c - slack_upper_bound))
self.add_linear_equality_constraint(terms + slack_terms,
lagrange_multiplier, -ub_c)
return slack_terms
def add_linear_from(self, linear: Union[Iterable, Mapping]):
"""Add variables and linear biases to a binary quadratic model.
Args:
linear:
A collection of variables and their associated linear biases.
If a dict, should be of the form `{v: bias, ...}` where `v` is
a variable and `bias` is its associated linear bias.
Otherwise, should be an iterable of `(v, bias)` pairs.
"""
if isinstance(linear, abc.Mapping):
iterator = linear.items()
elif isinstance(linear, abc.Iterator):
iterator = linear
else:
raise TypeError(
"expected 'linear' to be a dict or an iterable of 2-tuples.")
for v, bias in iterator:
self.add_linear(v, bias)
def add_linear_from_array(self, linear: Sequence):
"""Add linear biases from an array-like to a binary quadratic model.
Args:
linear:
A one-dimensional `array_like`_ of linear biases.
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
"""
ldata = np.asarray(linear)
# cython has trouble with readonly buffers as of 0.29.22, in the
# future we can remove this
if not ldata.flags.writeable:
ldata = np.array(ldata, copy=True)
self.data.add_linear_from_array(np.asarray(ldata))
add_variables_from = add_linear_from
"""Alias for :meth:`add_linear_from`."""
def add_offset(self, bias):
"""Add offset to to the model."""
name = type(self).__name__
warnings.warn(
f"{name}.add_offset(b) is deprecated. Please use bqm.offset += b.",
DeprecationWarning,
stacklevel=2)
self.offset += bias
@forwarding_method
def add_quadratic(self, u: Variable, v: Variable, bias: Bias):
"""Add a quadratic bias between two variables."""
return self.data.add_quadratic
def add_interaction(self, *args, **kwargs):
"""Alias for :meth:`.add_quadratic`."""
return self.add_quadratic(*args, **kwargs)
def add_quadratic_from(self, quadratic: Union[Mapping, Iterable]):
"""Add quadratic biases to the binary quadratic model.
Args:
quadratic:
Collection of interactions and their associated quadratic
bias. If a dict, should be of the form ``{(u, v): bias, ...}``
where ``u`` and ``v`` are variables in the model and ``bias`` is
the associated quadratic bias. Otherwise, should be an
iterable of ``(u, v, bias)`` triplets.
If a variable is not present in the model, it is added.
If the interaction already exists, the bias is added.
Raises:
ValueError:
If any self-loops are given. E.g. ``(u, u, bias)`` is not a valid
triplet.
"""
add_quadratic = self.data.add_quadratic
if isinstance(quadratic, abc.Mapping):
for (u, v), bias in quadratic.items():
add_quadratic(u, v, bias)
else:
for u, v, bias in quadratic:
add_quadratic(u, v, bias)
add_interactions_from = add_quadratic_from
"""Alias for :meth:`add_quadratic_from`."""
def add_quadratic_from_dense(self, quadratic: ArrayLike):
"""Add quadratic biases from a square 2d array-like.
Args:
quadratic:
An square 2d `array_like`_ of quadratic biases.
.. _`array_like`: https://numpy.org/doc/stable/user/basics.creation.html
"""
quadratic = np.asarray(quadratic, order='C')
# cython has trouble with readonly buffers as of 0.29.22, in the
# future we can remove this
if not quadratic.flags.writeable:
quadratic = np.array(quadratic, copy=True)
self.data.add_quadratic_from_dense(quadratic)
@forwarding_method
def add_variable(self, v: Optional[Variable] = None, bias: Bias = 0):
"""Add a variable to a binary quadratic model.
Args:
v: Variable label. If not provided, the next interger label
is used.
bias: Linear bias for the added variable.
"""
return self.data.add_variable
def change_vartype(self, vartype, inplace=True):
"""Return a binary quadratic model with the specified vartype.
Args:
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the changed model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
inplace (bool, optional, default=True):
If True, the binary quadratic model is updated in-place;
otherwise, a new binary quadratic model is returned.
Returns:
:obj:`.BQM`: A binary quadratic model with the specified
vartype.
"""
if not inplace:
return self.copy().change_vartype(vartype, inplace=True)
self.data.change_vartype(vartype)
return self
def contract_variables(self, u, v):
"""Enforce u, v being the same variable in a binary quadratic model.
The resulting variable is labeled ``u``. Values of interactions between
``v`` and variables that ``u`` interacts with are added to the
corresponding interactions of ``u``.
Args:
u (variable):
Variable in the binary quadratic model.
v (variable):
Variable in the binary quadratic model.
"""
if u not in self.variables:
raise ValueError(f"unknown variable: {u}")
if v not in self.variables:
raise ValueError(f"unknown variable: {v}")
self.add_linear(u, self.get_linear(v))
if self.vartype is Vartype.BINARY:
self.add_linear(u, self.get_quadratic(u, v, default=0))
elif self.vartype is Vartype.SPIN:
self.offset += self.get_quadratic(u, v, default=0)
else:
raise RuntimeError(f"unknown vartype: {self.vartype}")
self.remove_interaction(u, v)
# add all of v's interactions to u's
for w, b in self.iter_neighborhood(v):
self.add_quadratic(u, w, b)
# finally remove v
self.remove_variable(v)
def copy(self, deep=False):
"""Return a copy."""
if deep:
return copy.deepcopy(self)
else:
return copy.copy(self)
@forwarding_method
def degree(self, v: Variable) -> int:
"""Return the degree of a variable.
The degree is the number of interactions that contain ``v``.
"""
return self.data.degree
def degrees(self, array: bool = False, dtype: DTypeLike = int
) -> Union[np.ndarray, Mapping[Variable, int]]:
"""Return the degrees of a binary quadratic model's variables.
Args:
array (optional, default=False):
If True, returns a :obj:`numpy.ndarray`; otherwise returns a dict.
dtype (optional, default=:class:`numpy.int`):
The data type of the returned degrees. Applies only if
``array==True``.
Returns:
Degrees of all variables.
"""
if array:
return np.fromiter(map(self.degree, self.variables),
count=len(self), dtype=dtype)
return {v: self.degree(v) for v in self.variables}
@classmethod
def empty(cls, vartype):
"""Create a new binary quadratic model with no variables and no offset.
"""
return cls(vartype)
def energies(self, samples_like, dtype: Optional[DTypeLike] = None) -> np.ndarray:
"""Determine the energies of the given samples-like.
Args:
samples_like (samples_like):
Raw samples. `samples_like` is an extension of
NumPy's `array_like`_ structure. See :func:`.as_samples`.
dtype:
Desired NumPy data type for the energy. Matches
:attr:`.dtype` by default.
Returns:
Energies for the samples.
.. _`array_like`: https://numpy.org/doc/stable/user/basics.creation.html
"""
return self.data.energies(samples_like, dtype=dtype)
def energy(self, sample, dtype: Optional[DTypeLike] = None) -> Bias:
"""Determine the energy of the given sample.
Args:
sample (samples_like):
Raw sample. `samples_like` is an extension of
NumPy's `array_like`_ structure. See :func:`.as_samples`.