/
binary_quadratic_model.py
2448 lines (1899 loc) · 90.6 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 2018 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.
#
# ================================================================================================
"""
The binary quadratic model (BQM) class contains
Ising and quadratic unconstrained binary optimization (QUBO) models
used by samplers such as the D-Wave system.
The :term:`Ising` model is an objective function of :math:`N` variables
:math:`\bf s=[s_1,...,s_N]` corresponding to physical Ising spins, where :math:`h_i`
are the biases and :math:`J_{i,j}` the couplings (interactions) between spins.
.. math::
\\text{Ising:} \\qquad E(\\bf{s}|\\bf{h},\\bf{J})
= \\left\\{ \\sum_{i=1}^N h_i s_i + \\sum_{i<j}^N J_{i,j} s_i s_j \\right\}
\\qquad\\qquad s_i\\in\\{-1,+1\\}
The :term:`QUBO` model is an objective function of :math:`N` binary variables represented
as an upper-diagonal matrix :math:`Q`, where diagonal terms are the linear coefficients
and the nonzero off-diagonal terms the quadratic coefficients.
.. math::
\\text{QUBO:} \\qquad E(\\bf{x}| \\bf{Q}) = \\sum_{i\\le j}^N x_i Q_{i,j} x_j
\\qquad\\qquad x_i\\in \\{0,1\\}
The :class:`.BinaryQuadraticModel` class can contain both these models and its methods provide
convenient utilities for working with, and interworking between, the two representations
of a problem.
"""
from __future__ import absolute_import, division
import itertools
try:
import collections.abc as abc
except ImportError:
import collections as abc
from numbers import Number
import numpy as np
from six import itervalues, iteritems, iterkeys, PY2
from dimod.decorators import vartype_argument
from dimod.serialization.utils import array2bytes, bytes2array
from dimod.sampleset import as_samples
from dimod.utilities import resolve_label_conflict
from dimod.views import LinearView, QuadraticView, AdjacencyView, SampleView
from dimod.vartypes import Vartype
__all__ = 'BinaryQuadraticModel', 'BQM'
class BinaryQuadraticModel(abc.Sized, abc.Container, abc.Iterable):
"""Encodes a binary quadratic model.
Binary quadratic model is the superclass that contains the `Ising model`_ and the QUBO_.
.. _Ising model: https://en.wikipedia.org/wiki/Ising_model
.. _QUBO: https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization
Args:
linear (dict[variable, bias]):
Linear biases as a dict, where keys are the variables of
the binary quadratic model and values the linear biases associated
with these variables.
A variable can be any python object that is valid as a dictionary key.
Biases are generally numbers but this is not explicitly checked.
quadratic (dict[(variable, variable), bias]):
Quadratic biases as a dict, where keys are
2-tuples of variables and values the quadratic biases associated
with the pair of variables (the interaction).
A variable can be any python object that is valid as a dictionary key.
Biases are generally numbers but this is not explicitly checked.
Interactions that are not unique are added.
offset (number):
Constant energy offset associated with the binary quadratic model.
Any input type is allowed, but many applications assume that offset is a number.
See :meth:`.BinaryQuadraticModel.energy`.
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
**kwargs:
Any additional keyword parameters and their values are stored in
:attr:`.BinaryQuadraticModel.info`.
Notes:
The :class:`.BinaryQuadraticModel` class does not enforce types on biases
and offsets, but most applications that use this class assume that they are numeric.
Examples:
This example creates a binary quadratic model with three spin variables.
>>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},
... {(0, 1): .5, (1, 2): 1.5},
... 1.4,
... dimod.SPIN)
This example creates a binary quadratic model with non-numeric variables
(variables can be any hashable object).
>>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': -1.0, 'c': 0.5},
... {('a', 'b'): -1.0, ('b', 'c'): 1.5},
... 1.4,
... dimod.SPIN)
>>> len(bqm)
3
>>> 'b' in bqm
True
Attributes:
linear (dict[variable, bias]):
Linear biases as a dict, where keys are the variables of
the binary quadratic model and values the linear biases associated
with these variables.
quadratic (dict[(variable, variable), bias]):
Quadratic biases as a dict, where keys are 2-tuples of variables, which
represent an interaction between the two variables, and values
are the quadratic biases associated with the interactions.
offset (number):
The energy offset associated with the model. Same type as given
on instantiation.
vartype (:class:`.Vartype`):
The model's type. One of :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`.
adj (dict):
The model's interactions as nested dicts.
In graphic representation, where variables are nodes and interactions
are edges or adjacencies, keys of the outer dict (`adj`) are all
the model's nodes (e.g. `v`) and values are the inner dicts. For the
inner dict associated with outer-key/node 'v', keys are all the nodes
adjacent to `v` (e.g. `u`) and values are quadratic biases associated
with the pair of inner and outer keys (`u, v`).
info (dict):
A place to store miscellaneous data about the binary quadratic model
as a whole.
SPIN (:class:`.Vartype`): An alias of :class:`.Vartype.SPIN` for easier access.
BINARY (:class:`.Vartype`): An alias of :class:`.Vartype.BINARY` for easier access.
Examples:
This example creates an instance of the :class:`.BinaryQuadraticModel`
class for the K4 complete graph, where the nodes have biases
set equal to their sequential labels and interactions are the
concatenations of the node pairs (e.g., 23 for u,v = 2,3).
>>> import dimod
...
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> offset = 0.0
>>> vartype = dimod.BINARY
>>> bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype)
>>> bqm_k4.info = {'Complete K4 binary quadratic model.'}
>>> bqm_k4.info.issubset({'Complete K3 binary quadratic model.',
... 'Complete K4 binary quadratic model.',
... 'Complete K5 binary quadratic model.'})
True
>>> bqm_k4.adj.viewitems() # Show all adjacencies # doctest: +SKIP
[(1, {2: 12, 3: 13, 4: 14}),
(2, {1: 12, 3: 23, 4: 24}),
(3, {1: 13, 2: 23, 4: 34}),
(4, {1: 14, 2: 24, 3: 34})]
>>> bqm_k4.adj[2] # Show adjacencies for node 2 # doctest: +SKIP
{1: 12, 3: 23, 4: 24}
>>> bqm_k4.adj[2][3] # Show the quadratic bias for nodes 2,3 # doctest: +SKIP
23
"""
SPIN = Vartype.SPIN
BINARY = Vartype.BINARY
@vartype_argument('vartype')
def __init__(self, linear, quadratic, offset, vartype, **kwargs):
self._adj = {}
self.linear = LinearView(self)
self.quadratic = QuadraticView(self)
self.adj = AdjacencyView(self)
self.offset = offset # we are agnostic to type, though generally should behave like a number
self.vartype = vartype
self.info = kwargs # any additional kwargs are kept as info (metadata)
# add linear, quadratic
self.add_variables_from(linear)
self.add_interactions_from(quadratic)
@classmethod
def empty(cls, vartype):
"""Create an empty binary quadratic model.
Equivalent to instantiating a :class:`.BinaryQuadraticModel` with no bias values
and zero offset for the defined :class:`vartype`:
.. code-block:: python
BinaryQuadraticModel({}, {}, 0.0, vartype)
Args:
vartype (:class:`.Vartype`/str/set):
Variable type for the binary quadratic model. Accepted input values:
* :attr:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :attr:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Examples:
>>> bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY)
"""
return cls({}, {}, 0.0, vartype)
def __repr__(self):
return 'BinaryQuadraticModel({}, {}, {}, {})'.format(self.linear, self.quadratic, self.offset, self.vartype)
def __eq__(self, other):
"""Model is equal if and only if linear, adj, offset and vartype are all equal."""
try:
if self.vartype is not other.vartype:
return False
if self.offset != other.offset:
return False
if self.linear != other.linear:
return False
return self.adj == other.adj
except AttributeError:
return False
def __ne__(self, other):
return not (self == other)
def __len__(self):
return len(self.adj)
def __contains__(self, v):
return v in self.adj
def __iter__(self):
return iter(self.adj)
@property
def variables(self):
"""Return binary quadratic model's variables as a dictionary view object."""
if PY2:
return set(self.linear)
else:
return self.linear.keys()
##################################################################################################
# vartype properties
##################################################################################################
@property
def spin(self):
""":class:`.BinaryQuadraticModel`: An instance of the Ising model subclass
of the :class:`.BinaryQuadraticModel` superclass, corresponding to
a binary quadratic model with spins as its variables.
Enables access to biases for the spin-valued binary quadratic model
regardless of the :class:`vartype` set when the model was created.
If the model was created with the :attr:`.binary` vartype,
the Ising model subclass is instantiated upon the first use of the
:attr:`.spin` property and used in any subsequent reads.
Examples:
This example creates a QUBO model and uses the :attr:`.spin` property
to instantiate the corresponding Ising model.
>>> import dimod
...
>>> bqm_qubo = dimod.BinaryQuadraticModel({0: -1, 1: -1}, {(0, 1): 2}, 0.0, dimod.BINARY)
>>> bqm_spin = bqm_qubo.spin
>>> bqm_spin # doctest: +SKIP
BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, Vartype.SPIN)
>>> bqm_spin.spin is bqm_spin
True
Note:
Methods like :meth:`.add_variable`, :meth:`.add_variables_from`,
:meth:`.add_interaction`, etc. should only be used on the base model.
"""
# NB: The existence of the _spin property implies that it is up to date, methods that
# invalidate it will erase the property
try:
spin = self._spin
if spin is not None:
return spin
except AttributeError:
pass
if self.vartype is Vartype.SPIN:
self._spin = spin = self
else:
self._counterpart = self._spin = spin = self.change_vartype(Vartype.SPIN, inplace=False)
# we also want to go ahead and set spin.binary to refer back to self
spin._binary = self
return spin
@property
def binary(self):
""":class:`.BinaryQuadraticModel`: An instance of the QUBO model subclass of
the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic
model with binary variables.
Enables access to biases for the binary-valued binary quadratic model
regardless of the :class:`vartype` set when the model was created. If the model
was created with the :attr:`.spin` vartype, the QUBO model subclass is instantiated
upon the first use of the :attr:`.binary` property and used in any subsequent reads.
Examples:
This example creates an Ising model and uses the :attr:`.binary` property
to instantiate the corresponding QUBO model.
>>> import dimod
...
>>> bqm_spin = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> bqm_qubo = bqm_spin.binary
>>> bqm_qubo # doctest: +SKIP
BinaryQuadraticModel({0: -1.0, 1: -1.0}, {(0, 1): 2.0}, 0.0, Vartype.BINARY)
>>> bqm_qubo.binary is bqm_qubo
True
Note:
Methods like :meth:`.add_variable`, :meth:`.add_variables_from`,
:meth:`.add_interaction`, etc. should only be used on the base model.
"""
# NB: The existence of the _binary property implies that it is up to date, methods that
# invalidate it will erase the property
try:
binary = self._binary
if binary is not None:
return binary
except AttributeError:
pass
if self.vartype is Vartype.BINARY:
self._binary = binary = self
else:
self._counterpart = self._binary = binary = self.change_vartype(Vartype.BINARY, inplace=False)
# we also want to go ahead and set binary.spin to refer back to self
binary._spin = self
return binary
###################################################################################################
# update methods
###################################################################################################
def add_variable(self, v, bias, vartype=None):
"""Add variable v and/or its bias to a binary quadratic model.
Args:
v (variable):
The variable to add to the model. Can be any python object
that is a valid dict key.
bias (bias):
Linear bias associated with v. If v is already in the model, this value is added
to its current linear bias. Many methods and functions expect `bias` to be a number
but this is not explicitly checked.
vartype (:class:`.Vartype`, optional, default=None):
Vartype of the given bias. If None, the vartype of the binary
quadratic model is used. Valid values are :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
Examples:
This example creates an Ising model with two variables, adds a third,
and adds to the linear biases of the initial two.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> len(bqm.linear)
2
>>> bqm.add_variable(2, 2.0, vartype=dimod.SPIN) # Add a new variable
>>> bqm.add_variable(1, 0.33, vartype=dimod.SPIN)
>>> bqm.add_variable(0, 0.33, vartype=dimod.BINARY) # Binary value is converted to spin value
>>> len(bqm.linear)
3
>>> bqm.linear[1]
1.33
"""
# handle the case that a different vartype is provided
if vartype is not None and vartype is not self.vartype:
if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:
# convert from binary to spin
bias /= 2
self.offset += bias
elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:
# convert from spin to binary
self.offset -= bias
bias *= 2
else:
raise ValueError("unknown vartype")
# we used to do this using self.linear but working directly with _adj
# is much faster
_adj = self._adj
if v in _adj:
if v in _adj[v]:
_adj[v][v] += bias
else:
_adj[v][v] = bias
else:
_adj[v] = {v: bias}
try:
self._counterpart.add_variable(v, bias, vartype=self.vartype)
except AttributeError:
pass
def add_variables_from(self, linear, vartype=None):
"""Add variables and/or linear biases to a binary quadratic model.
Args:
linear (dict[variable, bias]/iterable[(variable, bias)]):
A collection of variables and their linear biases to add to the model.
If a dict, keys are variables in the binary quadratic model and
values are biases. Alternatively, an iterable of (variable, bias) pairs.
Variables can be any python object that is a valid dict key.
Many methods and functions expect the biases
to be numbers but this is not explicitly checked.
If any variable already exists in the model, its bias is added to
the variable's current linear bias.
vartype (:class:`.Vartype`, optional, default=None):
Vartype of the given bias. If None, the vartype of the binary
quadratic model is used. Valid values are :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
Examples:
This example creates creates an empty Ising model, adds two variables,
and subsequently adds to the bias of the one while adding a new, third,
variable.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)
>>> len(bqm.linear)
0
>>> bqm.add_variables_from({'a': .5, 'b': -1.})
>>> 'b' in bqm
True
>>> bqm.add_variables_from({'b': -1., 'c': 2.0})
>>> bqm.linear['b']
-2.0
"""
if isinstance(linear, abc.Mapping):
for v, bias in iteritems(linear):
self.add_variable(v, bias, vartype=vartype)
else:
try:
for v, bias in linear:
self.add_variable(v, bias, vartype=vartype)
except TypeError:
raise TypeError("expected 'linear' to be a dict or an iterable of 2-tuples.")
def add_interaction(self, u, v, bias, vartype=None):
"""Add an interaction and/or quadratic bias to a binary quadratic model.
Args:
v (variable):
One of the pair of variables to add to the model. Can be any python object
that is a valid dict key.
u (variable):
One of the pair of variables to add to the model. Can be any python object
that is a valid dict key.
bias (bias):
Quadratic bias associated with u, v. If u, v is already in the model, this value
is added to the current quadratic bias. Many methods and functions expect `bias` to
be a number but this is not explicitly checked.
vartype (:class:`.Vartype`, optional, default=None):
Vartype of the given bias. If None, the vartype of the binary
quadratic model is used. Valid values are :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
Examples:
This example creates an Ising model with two variables, adds a third,
adds to the bias of the initial interaction, and creates
a new interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> len(bqm.quadratic)
1
>>> bqm.add_interaction(0, 2, 2) # Add new variable 2
>>> bqm.add_interaction(0, 1, .25)
>>> bqm.add_interaction(1, 2, .25, vartype=dimod.BINARY) # Binary value is converted to spin value
>>> len(bqm.quadratic)
3
>>> bqm.quadratic[(0, 1)]
0.75
"""
if u == v:
raise ValueError("no self-loops allowed, therefore ({}, {}) is not an allowed interaction".format(u, v))
_adj = self._adj
if vartype is not None and vartype is not self.vartype:
if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:
# convert from binary to spin
bias /= 4
self.add_offset(bias)
self.add_variable(u, bias)
self.add_variable(v, bias)
elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:
# convert from spin to binary
self.add_offset(bias)
self.add_variable(u, -2 * bias)
self.add_variable(v, -2 * bias)
bias *= 4
else:
raise ValueError("unknown vartype")
else:
# so that they exist.
if u not in self:
_adj[u] = {}
if v not in self:
_adj[v] = {}
if u in _adj[v]:
_adj[u][v] = _adj[v][u] = _adj[u][v] + bias
else:
_adj[u][v] = _adj[v][u] = bias
try:
self._counterpart.add_interaction(u, v, bias, vartype=self.vartype)
except AttributeError:
pass
def add_interactions_from(self, quadratic, vartype=None):
"""Add interactions and/or quadratic biases to a binary quadratic model.
Args:
quadratic (dict[(variable, variable), bias]/iterable[(variable, variable, bias)]):
A collection of variables that have an interaction and their quadratic
bias to add to the model. If a dict, keys are 2-tuples of variables
in the binary quadratic model and values are their corresponding
bias. Alternatively, an iterable of 3-tuples. Each interaction in `quadratic` should be
unique; that is, if `(u, v)` is a key, `(v, u)` should not be.
Variables can be any python object that is a valid dict key.
Many methods and functions expect the biases to be numbers but this is not
explicitly checked.
vartype (:class:`.Vartype`, optional, default=None):
Vartype of the given bias. If None, the vartype of the binary
quadratic model is used. Valid values are :class:`.Vartype.SPIN` or
:class:`.Vartype.BINARY`.
Examples:
This example creates creates an empty Ising model, adds an interaction
for two variables, adds to its bias while adding a new variable,
then adds another interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)
>>> bqm.add_interactions_from({('a', 'b'): -.5})
>>> bqm.quadratic[('a', 'b')]
-0.5
>>> bqm.add_interactions_from({('a', 'b'): -.5, ('a', 'c'): 2})
>>> bqm.add_interactions_from({('b', 'c'): 2}, vartype=dimod.BINARY) # Binary value is converted to spin value
>>> len(bqm.quadratic)
3
>>> bqm.quadratic[('a', 'b')]
-1.0
"""
if isinstance(quadratic, abc.Mapping):
for (u, v), bias in iteritems(quadratic):
self.add_interaction(u, v, bias, vartype=vartype)
else:
try:
for u, v, bias in quadratic:
self.add_interaction(u, v, bias, vartype=vartype)
except TypeError:
raise TypeError("expected 'quadratic' to be a dict or an iterable of 3-tuples.")
def remove_variable(self, v):
"""Remove variable v and all its interactions from a binary quadratic model.
Args:
v (variable):
The variable to be removed from the binary quadratic model.
Notes:
If the specified variable is not in the binary quadratic model, this function does nothing.
Examples:
This example creates an Ising model and then removes one variable.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0},
... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75},
... -0.5, dimod.SPIN)
>>> bqm.remove_variable('a')
>>> 'a' in bqm.linear
False
>>> ('b','c') in bqm.quadratic
True
"""
if v not in self:
return
adj = self.adj
# first remove all the interactions associated with v
while adj[v]:
self.remove_interaction(v, next(iter(adj[v])))
# remove the variable
del self.linear[v]
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass
def remove_variables_from(self, variables):
"""Remove specified variables and all of their interactions from a binary quadratic model.
Args:
variables(iterable):
A collection of variables to be removed from the binary quadratic model.
If any variable is not in the model, it is ignored.
Examples:
This example creates an Ising model with three variables and interactions
among all of them, and then removes two variables.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0, 2: 2.0},
... {(0, 1): 0.25, (0,2): 0.5, (1,2): 0.75},
... -0.5, dimod.SPIN)
>>> bqm.remove_variables_from([0, 1])
>>> len(bqm.linear)
1
>>> len(bqm.quadratic)
0
"""
for v in variables:
self.remove_variable(v)
def remove_interaction(self, u, v):
"""Remove interaction of variables u, v from a binary quadratic model.
Args:
u (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
v (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interaction('b', 'c')
>>> ('b', 'c') in bqm.quadratic
False
>>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
try:
del self.quadratic[(u, v)]
except KeyError:
return # no interaction with that name
try:
# invalidates counterpart
del self._counterpart
if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):
del self._binary
elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):
del self._spin
except AttributeError:
pass
def remove_interactions_from(self, interactions):
"""Remove all specified interactions from the binary quadratic model.
Args:
interactions (iterable[[variable, variable]]):
A collection of interactions. Each interaction should be a 2-tuple of variables
in the binary quadratic model.
Notes:
Any interaction not in the binary quadratic model is ignored.
Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored
>>> len(bqm.quadratic)
1
"""
for u, v in interactions:
self.remove_interaction(u, v)
def add_offset(self, offset):
"""Add specified value to the offset of a binary quadratic model.
Args:
offset (number):
Value to be added to the constant energy offset of the binary quadratic model.
Examples:
This example creates an Ising model with an offset of -0.5 and then
adds to it.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
>>> bqm.add_offset(1.0)
>>> bqm.offset
0.5
"""
self.offset += offset
try:
self._counterpart.add_offset(offset)
except AttributeError:
pass
def remove_offset(self):
"""Set the binary quadratic model's offset to zero.
Examples:
This example creates an Ising model with a positive energy offset, and
then removes it.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {}, 1.3, dimod.SPIN)
>>> bqm.remove_offset()
>>> bqm.offset
0.0
"""
self.add_offset(-self.offset)
def scale(self, scalar, ignored_variables=None, ignored_interactions=None,
ignore_offset=False):
"""Multiply by the specified scalar all the biases and offset of a binary quadratic model.
Args:
scalar (number):
Value by which to scale the energy range of the binary quadratic model.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
Examples:
This example creates a binary quadratic model and then scales it to half
the original energy range.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)
>>> bqm.scale(0.5)
>>> bqm.linear['a']
-1.0
>>> bqm.quadratic[('a', 'b')]
-0.5
>>> bqm.offset
0.5
"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
linear = self.linear
for v in linear:
if v in ignored_variables:
continue
linear[v] *= scalar
quadratic = self.quadratic
for u, v in quadratic:
if (u, v) in ignored_interactions or (v, u) in ignored_interactions:
continue
quadratic[(u, v)] *= scalar
if not ignore_offset:
self.offset *= scalar
try:
self._counterpart.scale(scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions)
except AttributeError:
pass
def normalize(self, bias_range=1, quadratic_range=None,
ignored_variables=None, ignored_interactions=None,
ignore_offset=False):
"""Normalizes the biases of the binary quadratic model such that they
fall in the provided range(s), and adjusts the offset appropriately.
If `quadratic_range` is provided, then `bias_range` will be treated as
the range for the linear biases and `quadratic_range` will be used for
the range of the quadratic biases.
Args:
bias_range (number/pair):
Value/range by which to normalize the all the biases, or if
`quadratic_range` is provided, just the linear biases.
quadratic_range (number/pair):
Value/range by which to normalize the quadratic biases.
ignored_variables (iterable, optional):
Biases associated with these variables are not scaled.
ignored_interactions (iterable[tuple], optional):
As an iterable of 2-tuples. Biases associated with these interactions are not scaled.
ignore_offset (bool, default=False):
If True, the offset is not scaled.
Examples:
This example creates a binary quadratic model and then normalizes
all the biases in the range [-0.4, 0.8].
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 1.5}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)
>>> bqm.normalize([-0.4, 0.8])
>>> bqm.linear
{'a': -0.4, 'b': 0.30000000000000004}
>>> bqm.quadratic
{('a', 'b'): -0.2}
>>> bqm.offset
0.2
"""
def parse_range(r):
if isinstance(r, Number):
return -abs(r), abs(r)
return r
def min_and_max(iterable):
if not iterable:
return 0, 0
return min(iterable), max(iterable)
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
ignored_interactions = set()
elif not isinstance(ignored_interactions, abc.Container):
ignored_interactions = set(ignored_interactions)
if quadratic_range is None:
linear_range, quadratic_range = bias_range, bias_range
else:
linear_range = bias_range
lin_range, quad_range = map(parse_range, (linear_range,
quadratic_range))
lin_min, lin_max = min_and_max([v for k, v in self.linear.items()
if k not in ignored_variables])
quad_min, quad_max = min_and_max([v for (a,b),
v in self.quadratic.items()
if ((a, b) not in ignored_interactions
and (b, a) not in
ignored_interactions)])
inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1],
quad_min / quad_range[0], quad_max / quad_range[1])
if inv_scalar != 0:
self.scale(1 / inv_scalar, ignored_variables=ignored_variables,
ignored_interactions=ignored_interactions,
ignore_offset=ignore_offset)
def fix_variable(self, v, value):
"""Fix the value of a variable and remove it from a binary quadratic model.
Args:
v (variable):
Variable in the binary quadratic model to be fixed.
value (int):
Value assigned to the variable. Values must match the :class:`.Vartype` of the binary
quadratic model.
Examples:
This example creates a binary quadratic model with one variable and fixes
its value.
>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN)
>>> bqm.fix_variable('a', -1)
>>> bqm.offset
0.5
>>> bqm.linear['b']