/
sampleset.py
1962 lines (1518 loc) · 72.5 KB
/
sampleset.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.
from __future__ import annotations
import collections.abc as abc
import base64
import copy
import functools
import itertools
import json
import numbers
import typing
import warnings
from collections import namedtuple
from typing import Any, Callable, Iterable, Optional
from warnings import warn
import numpy as np
from numpy.lib import recfunctions
from dimod.exceptions import WriteableError
from dimod.serialization.format import Formatter
from dimod.serialization.utils import (pack_samples as _pack_samples,
unpack_samples,
serialize_ndarray,
deserialize_ndarray,
serialize_ndarrays,
deserialize_ndarrays)
from dimod.sym import Sense
from dimod.typing import ArrayLike, DTypeLike, SampleLike, SamplesLike, Variable
from dimod.variables import Variables, iter_deserialize_variables
from dimod.vartypes import as_vartype, Vartype, DISCRETE
from dimod.views.samples import SampleView, SamplesArray
__all__ = ['append_data_vectors',
'append_variables',
'as_samples',
'concatenate',
'drop_variables',
'keep_variables',
'SampleSet',
]
def append_data_vectors(sampleset, **vectors):
"""Create a new :obj:`.SampleSet` with additional fields in
:attr:`SampleSet.record`.
Args:
sampleset (:obj:`.SampleSet`):
:obj:`.SampleSet` to build from.
**vectors (list):
Per-sample data to be appended to :attr:`SampleSet.record`. Each
keyword is a new field name and each keyword parameter should be a
list of scalar values or numpy arrays (lists and tuples will be
converted to numpy arrays).
Returns:
:obj:`.SampleSet`: SampleSet
Examples:
The following example appends a field of lists to :attr:`SampleSet.record`.
>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [-1, 1]], energy=[-1.4, -1.4], vartype='SPIN')
>>> print(sampleset)
0 1 energy num_oc.
0 -1 +1 -1.4 1
1 -1 +1 -1.4 1
['SPIN', 2 rows, 2 samples, 2 variables]
>>> sampleset = dimod.append_data_vectors(sampleset, new=[[0, 1], [1, 2]])
>>> print(sampleset)
0 1 energy num_oc. new
0 -1 +1 -1.4 1 [0 1]
1 -1 +1 -1.4 1 [1 2]
['SPIN', 2 rows, 2 samples, 2 variables]
>>> print(sampleset.record.dtype)
(numpy.record, [('sample', 'i1', (2,)), ('energy', '<f8'), ('num_occurrences', '<i8'), ('new', '<i8', (2,))])
"""
record = sampleset.record
for name, vector in vectors.items():
if len(vector) != len(record.energy):
raise ValueError("Length of vector {} must be equal to number of samples.".format(name))
try:
vector = np.asarray(vector)
if vector.ndim == 1:
record = recfunctions.append_fields(record, name, vector, usemask=False, asrecarray=True)
else:
# np's append_fields cannot append a vector with a shape that
# doesn't match the base array's, so appending non-scalar data
# requires a workaround
dtype = np.dtype([(name, vector[0].dtype, vector[0].shape)])
new_arr = recfunctions.unstructured_to_structured(vector, dtype=dtype)
record = recfunctions.merge_arrays((record, new_arr), flatten=True, asrecarray=True)
except (TypeError, AttributeError):
raise ValueError("Field value type not supported.")
return SampleSet(record, sampleset.variables, sampleset.info, sampleset.vartype)
def append_variables(sampleset, samples_like, sort_labels=True):
"""Create a new :obj:`.SampleSet` with the given variables and values.
Not defined for empty sample sets. If `sample_like` is a
:obj:`.SampleSet`, its data vectors and info are ignored.
Args:
sampleset (:obj:`.SampleSet`):
:obj:`.SampleSet` to build from.
samples_like:
Samples to add to the sample set. Either a single
sample or identical in length to the sample set.
'samples_like' is an extension of NumPy's array_like_.
See :func:`.as_samples`.
sort_labels (bool, optional, default=True):
Return :attr:`.SampleSet.variables` in sorted order. For mixed
(unsortable) types, the given order is maintained.
Returns:
:obj:`.SampleSet`: New sample set with the variables/values added.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([{'a': -1, 'b': +1},
... {'a': +1, 'b': +1}],
... dimod.SPIN,
... energy=[-1.0, 1.0])
>>> new = dimod.append_variables(sampleset, {'c': -1})
>>> print(new)
a b c energy num_oc.
0 -1 +1 -1 -1.0 1
1 +1 +1 -1 1.0 1
['SPIN', 2 rows, 2 samples, 3 variables]
Add variables from another sample set to the previous example. Note
that the energies remain unchanged.
>>> another = dimod.SampleSet.from_samples([{'c': -1, 'd': +1},
... {'c': +1, 'd': +1}],
... dimod.SPIN,
... energy=[-2.0, 1.0])
>>> new = dimod.append_variables(sampleset, another)
>>> print(new)
a b c d energy num_oc.
0 -1 +1 -1 +1 -1.0 1
1 +1 +1 +1 +1 1.0 1
['SPIN', 2 rows, 2 samples, 4 variables]
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
"""
samples, labels = as_samples(samples_like)
num_samples = len(sampleset)
# we don't handle multiple values
if samples.shape[0] == num_samples:
# we don't need to do anything, it's already the correct shape
pass
elif samples.shape[0] == 1 and num_samples:
samples = np.repeat(samples, num_samples, axis=0)
else:
msg = ("mismatched shape. The samples to append should either be "
"a single sample or should match the length of the sample "
"set. Empty sample sets cannot be appended to.")
raise ValueError(msg)
# append requires the new variables to be unique
variables = sampleset.variables
if any(v in variables for v in labels):
msg = "Appended samples cannot contain variables in sample set"
raise ValueError(msg)
new_variables = list(variables) + labels
new_samples = np.hstack((sampleset.record.sample, samples))
return type(sampleset).from_samples((new_samples, new_variables),
sampleset.vartype,
info=copy.deepcopy(sampleset.info), # make a copy
sort_labels=sort_labels,
**sampleset.data_vectors)
def _sample_array(array_like: ArrayLike, dtype: Optional[DTypeLike] = None, **kwargs) -> np.ndarray:
"""Convert an array-like into a samples array."""
if dtype is None:
dtype = getattr(array_like, 'dtype', None)
arr = np.array(array_like, dtype=dtype, **kwargs)
# make sure it's exactly 2d and handle the obvious edge cases
if arr.ndim < 2:
if arr.size:
arr = np.atleast_2d(arr)
else:
arr = arr.reshape((0, 0))
elif arr.ndim > 2:
raise ValueError("expected samples_like to be <= 2 dimensions")
if dtype is None and np.issubdtype(arr.dtype, np.integer):
# it was unspecified, so we may want to use a smaller representation
max_ = max(-arr.min(initial=0), +arr.max(initial=0))
try:
dtype = next(tp for tp in (np.int8, np.int16, np.int32, np.int64)
if max_ <= np.iinfo(tp).max)
except StopIteration:
raise ValueError('`samples like contains entries that do not fit in np.int64')
arr = np.asarray(arr, dtype=dtype) # preserves order by default
return arr
try:
ArrayOrder = typing.Literal['K', 'A', 'C', 'F']
except AttributeError:
ArrayOrder = str
@functools.singledispatch
def as_samples(samples_like: SamplesLike,
dtype: Optional[DTypeLike] = None,
copy: bool = False,
order: ArrayOrder = 'C',
labels_type: type = list,
) -> typing.Tuple[np.ndarray, typing.Sequence[Variable]]:
"""Convert a samples_like object to a NumPy array and list of labels.
Args:
samples_like:
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like_ structure. See examples below.
dtype:
dtype for the returned samples array. If not provided, it is either
derived from `samples_like`, if that object has a dtype, or set to
the smallest dtype that can hold the given values.
copy:
If true, then samples_like is guaranteed to be copied, otherwise
it is only copied if necessary.
order:
Specify the memory layout of the array. See :func:`numpy.array`.
labels_type:
The return type of the variables labels.
``labels_type`` should be a :class:`~collections.abc.Sequence`.
The ``labels_type`` constructor should accept zero arguments, or an
iterable as a single argument.
Returns:
A 2-tuple containing the samples as a :class:`~numpy.ndarray` and
the variables labels, as a ``labels_type``.
Examples:
The following examples convert a variety of samples_like objects:
NumPy arrays
>>> import numpy as np
...
>>> dimod.as_samples(np.ones(5, dtype='int8'))
(array([[1, 1, 1, 1, 1]], dtype=int8), [0, 1, 2, 3, 4])
>>> dimod.as_samples(np.zeros((5, 2), dtype='int8'))
(array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]], dtype=int8), [0, 1])
Lists
>>> dimod.as_samples([-1, +1, -1])
(array([[-1, 1, -1]], dtype=int8), [0, 1, 2])
>>> dimod.as_samples([[-1], [+1], [-1]])
(array([[-1],
[ 1],
[-1]], dtype=int8), [0])
Dicts
>>> dimod.as_samples({'a': 0, 'b': 1, 'c': 0}) # doctest: +SKIP
(array([[0, 1, 0]], dtype=int8), ['a', 'b', 'c'])
>>> dimod.as_samples([{'a': -1, 'b': +1}, {'a': 1, 'b': 1}]) # doctest: +SKIP
(array([[-1, 1],
[ 1, 1]], dtype=int8), ['a', 'b'])
A 2-tuple containing an array_like object and a list of labels
>>> dimod.as_samples(([-1, +1, -1], ['a', 'b', 'c']))
(array([[-1, 1, -1]], dtype=int8), ['a', 'b', 'c'])
>>> dimod.as_samples((np.zeros((5, 2), dtype='int8'), ['in', 'out']))
(array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]], dtype=int8), ['in', 'out'])
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
.. deprecated:: 0.10.13
Support for a 2-tuple of ``(dict, list)`` as a samples-like will be
removed in dimod 0.12.0.
"""
# single dispatch should have handled everything except array-like and mixed
if isinstance(samples_like, abc.Sequence) and any(isinstance(s, abc.Mapping) for s in samples_like):
return as_samples(iter(samples_like),
dtype=dtype, copy=copy, order=order,
labels_type=labels_type)
# array-like
arr = _sample_array(samples_like, dtype=dtype, copy=copy, order=order)
return arr, labels_type(range(arr.shape[1]))
@as_samples.register(abc.Iterator)
def _as_samples_iterator(samples_like: typing.Iterator[SampleLike],
labels_type: type = list,
**kwargs,
) -> typing.Tuple[np.ndarray, typing.Sequence[Variable]]:
stack = (as_samples(sl, **kwargs) for sl in samples_like)
try:
first_samples, first_labels = next(stack)
except StopIteration:
return np.empty((0, 0), dtype=np.int8), []
samples_stack = [first_samples]
first_set = set(first_labels)
for samples, labels in stack:
if labels != first_labels:
if set(labels) ^ first_set:
raise ValueError
# do a bit of reindex
reindex = [first_labels.index(v) for v in labels]
samples = samples[:, reindex]
samples_stack.append(samples)
if not isinstance(first_labels, labels_type):
first_labels = labels_type(first_labels)
return np.vstack(samples_stack), first_labels
@as_samples.register(abc.Mapping)
def _as_samples_dict(samples_like: typing.Mapping[Variable, float],
dtype: Optional[DTypeLike] = None,
copy: bool = False,
order: ArrayOrder = 'C',
labels_type: type = list,
) -> typing.Tuple[np.ndarray, typing.Sequence[Variable]]:
if samples_like:
labels, samples = zip(*samples_like.items())
return as_samples((samples, labels), dtype=dtype, copy=copy, order=order,
labels_type=labels_type)
else:
return np.empty((1, 0), dtype=dtype, order=order), labels_type()
@as_samples.register(tuple)
def _as_samples_tuple(samples_like: typing.Tuple[ArrayLike, typing.Sequence[Variable]],
dtype: Optional[DTypeLike] = None,
copy: bool = False,
order: ArrayOrder = 'C',
labels_type: type = list,
) -> typing.Tuple[np.ndarray, typing.Sequence[Variable]]:
try:
array_like, labels = samples_like
except ValueError:
raise ValueError("if a tuple is provided, it must be length 2") from None
# for legacy reasons we support (mapping, labels) but we'll want to drop
# that in the future
if isinstance(array_like, abc.Mapping):
warnings.warn("support for (dict, labels) as a samples-like is deprecated "
"since dimod 0.10.13 and will be removed in 0.12.0",
DeprecationWarning, stacklevel=3)
# make sure that it has the correct order by making a copy
d = dict()
try:
for v in labels:
d[v] = array_like[v]
except KeyError:
raise ValueError("inconsistent labels")
array_like, _ = as_samples(d)
if isinstance(array_like, abc.Iterator):
raise TypeError('samples_like cannot be an iterator when given as a tuple')
arr = _sample_array(array_like, dtype=dtype, copy=copy, order=order)
# make sure our labels are the correct type
if not isinstance(labels, labels_type):
# todo: generalize to other sequence types? Especially Variables
labels = labels_type(labels)
if not arr.size:
arr.shape = (arr.shape[0], len(labels))
if len(labels) != arr.shape[1]:
raise ValueError("samples_like and labels dimensions do not match")
return arr, labels
def concatenate(samplesets, defaults=None):
"""Combine sample sets.
Args:
samplesets (iterable[:obj:`.SampleSet`):
Iterable of sample sets.
defaults (dict, optional):
Dictionary mapping data vector names to the corresponding default values.
Returns:
:obj:`.SampleSet`: A sample set with the same vartype and variable order as the first
given in `samplesets`.
Examples:
>>> a = dimod.SampleSet.from_samples(([-1, +1], 'ab'), dimod.SPIN, energy=-1)
>>> b = dimod.SampleSet.from_samples(([-1, +1], 'ba'), dimod.SPIN, energy=-1)
>>> ab = dimod.concatenate((a, b))
>>> ab.record.sample
array([[-1, 1],
[ 1, -1]], dtype=int8)
"""
itertup = iter(samplesets)
try:
first = next(itertup)
except StopIteration:
raise ValueError("samplesets must contain at least one SampleSet")
vartype = first.vartype
variables = first.variables
records = [first.record]
records.extend(_iter_records(itertup, vartype, variables))
# dev note: I was able to get ~2x performance boost when trying to
# implement the same functionality here by hand (I didn't know that
# this function existed then). However I think it is better to use
# numpy's function and rely on their testing etc. If however this becomes
# a performance bottleneck in the future, it might be worth changing.
record = recfunctions.stack_arrays(records, defaults=defaults,
asrecarray=True, usemask=False)
return SampleSet(record, variables, {}, vartype)
def _iter_records(samplesets, vartype, variables):
# coerce each record into the correct vartype and variable-order
for samples in samplesets:
# coerce vartype
if samples.vartype is not vartype:
samples = samples.change_vartype(vartype, inplace=False)
if samples.variables != variables:
new_record = samples.record.copy()
order = [samples.variables.index(v) for v in variables]
new_record.sample = samples.record.sample[:, order]
yield new_record
else:
# order matches so we're done
yield samples.record
def infer_vartype(samples_like):
"""Infer the vartype of the given samples-like.
Args:
A collection of samples. 'samples_like' is an extension of NumPy's
array_like_. See :func:`.as_samples`.
Returns:
The :class:`.Vartype`, or None in the case that it is ambiguous.
"""
if isinstance(samples_like, SampleSet):
return samples_like.vartype
samples, _ = as_samples(samples_like)
ones_mask = (samples == 1)
if ones_mask.all():
# either empty or all 1s, in either case ambiguous
return None
if (ones_mask ^ (samples == 0)).all():
return Vartype.BINARY
if (ones_mask ^ (samples == -1)).all():
return Vartype.SPIN
raise ValueError("given samples_like is of an unknown vartype")
def drop_variables(sampleset: 'SampleSet', variables: Iterable[Variable]) -> 'SampleSet':
"""Return a new sample set with the given variables removed.
Args:
sampleset: A sample set.
variables: The variables to be dropped. Can contain variables not in
the sample set.
Returns:
A new sampleset without the given variables. The energies, info
and other data vectors will be the same as in the given sample set.
"""
return keep_variables(sampleset, sampleset.variables - variables)
def keep_variables(sampleset: 'SampleSet', variables: Iterable[Variable]) -> 'SampleSet':
"""Return a new sample set with only the given variables.
Args:
sampleset: A sample set.
variables: The variables to be kept. Must be a subset of the variables
in the sample set.
Returns:
A new sampleset with only the given variables kept. The energies, info
and other data vectors will be the same as in the given sample set.
"""
if isinstance(variables, abc.Sequence):
sort_labels = False # keep the original label ordering
elif isinstance(variables, abc.Iterator):
variables = list(variables)
sort_labels = False
else:
variables = list(variables)
sort_labels = True # probably a set or something, so may as well
try:
return SampleSet.from_samples(
(sampleset.samples(sorted_by=None)[:, variables], variables),
vartype=sampleset.vartype,
**sampleset.data_vectors,
info=copy.deepcopy(sampleset.info),
sort_labels=sort_labels,
)
except KeyError:
v = next(v for v in variables if v not in sampleset.variables)
raise ValueError(f'variables contains at least one variable, {v!r}, '
'not present in the sampleset')
class SampleSet(abc.Iterable, abc.Sized):
"""Samples and any other data returned by dimod samplers.
Args:
record (:obj:`numpy.recarray`)
A NumPy record array. Must have 'sample', 'energy' and 'num_occurrences' as fields.
The 'sample' field should be a 2D NumPy array where each row is a sample and each
column represents the value of a variable.
variables (iterable):
An iterable of variable labels, corresponding to columns in `record.samples`.
info (dict):
Information about the :class:`SampleSet` as a whole, formatted as a dict.
vartype (:class:`.Vartype`/str/set):
Variable type for the :class:`SampleSet`. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
* :class:`.ExtendedVartype.DISCRETE`, ``'DISCRETE'``
Examples:
This example creates a SampleSet out of a samples_like object (a NumPy array).
>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(np.ones(5, dtype='int8'),
... 'BINARY', 0)
>>> sampleset.variables
Variables([0, 1, 2, 3, 4])
"""
_REQUIRED_FIELDS = ['sample', 'energy', 'num_occurrences']
###############################################################################################
# Construction
###############################################################################################
def __init__(self, record, variables, info, vartype):
vartype = as_vartype(vartype, extended=True)
# make sure that record is a numpy recarray and that it has the expected fields
if not isinstance(record, np.recarray):
raise TypeError("input record must be a numpy recarray")
elif not set(self._REQUIRED_FIELDS).issubset(record.dtype.fields):
raise ValueError("input record must have {}, {} and {} as fields".format(*self._REQUIRED_FIELDS))
self._record = record
num_samples, num_variables = record.sample.shape
self._variables = variables = Variables(variables)
if len(variables) != num_variables:
msg = ("mismatch between number of variables in record.sample ({}) "
"and labels ({})").format(num_variables, len(variables))
raise ValueError(msg)
self._info = dict(info)
# vartype is checked by vartype_argument decorator
self._vartype = vartype
@classmethod
def from_samples(cls, samples_like, vartype, energy, info=None,
num_occurrences=None, aggregate_samples=False,
sort_labels=True, **vectors):
"""Build a :class:`SampleSet` from raw samples.
Args:
samples_like:
A collection of raw samples. 'samples_like' is an extension of NumPy's array_like_.
See :func:`.as_samples`.
vartype (:class:`.Vartype`/str/set):
Variable type for the :class:`SampleSet`. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
* :class:`.ExtendedVartype.DISCRETE`, ``'DISCRETE'``
energy (array_like):
Vector of energies.
info (dict, optional):
Information about the :class:`SampleSet` as a whole formatted as a dict.
num_occurrences (array_like, optional):
Number of occurrences for each sample. If not provided, defaults to a vector of 1s.
aggregate_samples (bool, optional, default=False):
If True, all samples in returned :obj:`.SampleSet` are unique,
with `num_occurrences` accounting for any duplicate samples in
`samples_like`.
sort_labels (bool, optional, default=True):
Return :attr:`.SampleSet.variables` in sorted order. For mixed
(unsortable) types, the given order is maintained.
**vectors (array_like):
Other per-sample data.
Returns:
:obj:`.SampleSet`
Examples:
This example creates a SampleSet out of a samples_like object (a dict).
>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(
... dimod.as_samples({'a': 0, 'b': 1, 'c': 0}), 'BINARY', 0)
>>> sampleset.variables
Variables(['a', 'b', 'c'])
.. _array_like: https://numpy.org/doc/stable/user/basics.creation.html
"""
if aggregate_samples:
return cls.from_samples(samples_like, vartype, energy,
info=info, num_occurrences=num_occurrences,
aggregate_samples=False,
**vectors).aggregate()
# get the samples, variable labels
samples, variables = as_samples(samples_like)
if sort_labels and variables: # need something to sort
try:
reindex, new_variables = zip(*sorted(enumerate(variables),
key=lambda tup: tup[1]))
except TypeError:
# unlike types are not sortable in python3, so we do nothing
pass
else:
if new_variables != variables:
# avoid the copy if possible
samples = samples[:, reindex]
variables = new_variables
num_samples, num_variables = samples.shape
energy = np.asarray(energy)
# num_occurrences
if num_occurrences is None:
num_occurrences = np.ones(num_samples, dtype=int)
else:
num_occurrences = np.asarray(num_occurrences)
# now construct the record
datatypes = [('sample', samples.dtype, (num_variables,)),
('energy', energy.dtype),
('num_occurrences', num_occurrences.dtype)]
for key, vector in vectors.items():
vectors[key] = vector = np.asarray(vector)
datatypes.append((key, vector.dtype, vector.shape[1:]))
record = np.rec.array(np.zeros(num_samples, dtype=datatypes))
record['sample'] = samples
record['energy'] = energy
record['num_occurrences'] = num_occurrences
for key, vector in vectors.items():
record[key] = vector
if info is None:
info = {}
return cls(record, variables, info, vartype)
# todo: this works with DQM/BinaryPolynomial, should change the name and/or
# update the docs.
@classmethod
def from_samples_bqm(cls, samples_like, bqm, **kwargs):
"""Build a sample set from raw samples and a binary quadratic model.
The binary quadratic model is used to calculate energies and set the
:class:`vartype`.
Args:
samples_like:
A collection of raw samples. 'samples_like' is an extension of NumPy's array_like.
See :func:`.as_samples`.
bqm (:obj:`.BinaryQuadraticModel`):
A binary quadratic model.
info (dict, optional):
Information about the :class:`SampleSet` as a whole formatted as a dict.
num_occurrences (array_like, optional):
Number of occurrences for each sample. If not provided, defaults to a vector of 1s.
aggregate_samples (bool, optional, default=False):
If True, all samples in returned :obj:`.SampleSet` are unique,
with `num_occurrences` accounting for any duplicate samples in
`samples_like`.
sort_labels (bool, optional, default=True):
Return :attr:`.SampleSet.variables` in sorted order. For mixed
(unsortable) types, the given order is maintained.
**vectors (array_like):
Other per-sample data.
Returns:
:obj:`.SampleSet`
Examples:
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> sampleset = dimod.SampleSet.from_samples_bqm({'a': -1, 'b': 1}, bqm)
"""
if len(samples_like) == 0:
return cls.from_samples(([], bqm.variables), energy=[], vartype=bqm.vartype, **kwargs)
# more performant to do this once, here rather than again in bqm.energies
# and in cls.from_samples
samples_like = as_samples(samples_like)
energies = bqm.energies(samples_like)
return cls.from_samples(samples_like, energy=energies, vartype=bqm.vartype, **kwargs)
@classmethod
def from_samples_cqm(cls, samples_like, cqm, rtol=1e-6, atol=1e-8, **kwargs):
"""Build a sample set from raw samples and a constrained quadratic model.
The constrained quadratic model is used to calculate energies and feasibility.
Args:
samples_like:
A collection of raw samples. 'samples_like' is an extension of NumPy's array_like.
See :func:`.as_samples`.
cqm (:obj:`.ConstrainedQuadraticModel`):
A constrained quadratic model.
rtol (float, optional, default=1e-6):
Relative tolerance for constraint violation.
See :meth:`.ConstrainedQuadraticModel.check_feasible` for more information.
atol (float, optional, default=1e-8):
Absolute tolerance for constraint violations.
See :meth:`.ConstrainedQuadraticModel.check_feasible` for more information.
info (dict, optional):
Information about the :class:`SampleSet` as a whole formatted as a dict.
num_occurrences (array_like, optional):
Number of occurrences for each sample. If not provided, defaults to a vector of 1s.
aggregate_samples (bool, optional, default=False):
If True, all samples in returned :obj:`.SampleSet` are unique,
with `num_occurrences` accounting for any duplicate samples in
`samples_like`.
sort_labels (bool, optional, default=True):
Return :attr:`.SampleSet.variables` in sorted order. For mixed
(unsortable) types, the given order is maintained.
**vectors (array_like):
Other per-sample data.
Returns:
:obj:`.SampleSet`
Examples:
>>> cqm = dimod.ConstrainedQuadraticModel()
>>> x, y, z = dimod.Binaries(['x', 'y', 'z'])
>>> cqm.set_objective(x*y + 2*y*z)
>>> label = cqm.add_constraint(x*y == 1, label='constraint_1')
>>> sampleset = dimod.SampleSet.from_samples_cqm({'x': 0, 'y': 1, 'z': 1}, cqm)
"""
if len(samples_like) == 0:
return cls.from_samples(([], cqm.variables),
energy=[],
vartype='INTEGER',
is_satisfied=np.empty((0, len(cqm.constraints)), dtype=bool),
is_feasible=np.empty(0, dtype=bool),
**kwargs)
# more performant to do this once, here rather than again in cqm.objective.energies
# and in cls.from_samples
# We go ahead and coerce to Variables for performance, since .energies() prefers
# that format
samples_like = samples, labels = as_samples(samples_like, labels_type=Variables)
energies = cqm.objective.energies(samples_like)
constraint_labels = []
is_satisfied = np.empty((samples.shape[0], len(cqm.constraints)), dtype=bool)
soft = set()
for i, (label, comparison) in enumerate(cqm.constraints.items()):
constraint_labels.append(label)
lhs = comparison.lhs.energies(samples_like)
rhs = comparison.rhs
sense = comparison.sense
if sense is Sense.Eq:
violation = np.abs(lhs - rhs)
elif sense is Sense.Ge:
violation = rhs - lhs
elif sense is Sense.Le:
violation = lhs - rhs
else:
raise RuntimeError("unexpected sense")
is_satisfied[:, i] = violation <= atol + rtol*abs(rhs)
if comparison.lhs.is_soft() and not is_satisfied.all():
weight = comparison.lhs.weight()
penalty = comparison.lhs.penalty()
if penalty == 'linear':
energies += weight * (is_satisfied[:, i] != True) * violation
elif penalty == 'quadratic':
energies += weight * (is_satisfied[:, i] != True) * np.power(violation, 2)
else:
raise RuntimeError("unexpected penalty")
soft.add(label)
if soft:
hard = [i for i, label in enumerate(constraint_labels) if label not in soft]
is_feasible = is_satisfied[:, hard].all(axis=1)
else:
# no soft constraints to worry about
is_feasible = is_satisfied.all(axis=1)
kwargs.setdefault('info', {})['constraint_labels'] = constraint_labels
return cls.from_samples(samples_like, energy=energies, vartype='INTEGER',
is_satisfied=is_satisfied, is_feasible=is_feasible, **kwargs)
@classmethod
def from_future(cls, future, result_hook=None):
"""Construct a :class:`SampleSet` referencing the result of a future computation.
Args:
future (object):
Object that contains or will contain the information needed to construct a
:class:`SampleSet`. If `future` has a :meth:`~concurrent.futures.Future.done` method,
this determines the value returned by :meth:`.SampleSet.done`.
result_hook (callable, optional):
A function that is called to resolve the future. Must accept the future and return
a :obj:`.SampleSet`. If not provided, set to
.. code-block:: python
def result_hook(future):
return future.result()
Returns:
:obj:`.SampleSet`
Notes:
The future is resolved on the first read of any of the :class:`SampleSet` properties.
Examples:
Run a dimod sampler on a single thread and load the returned future into :class:`SampleSet`.
>>> from concurrent.futures import ThreadPoolExecutor
...
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> with ThreadPoolExecutor(max_workers=1) as executor:
... future = executor.submit(dimod.ExactSolver().sample, bqm)
... sampleset = dimod.SampleSet.from_future(future)
>>> sampleset.first.energy # doctest: +SKIP
"""
obj = cls.__new__(cls)
obj._future = future
if result_hook is None:
def result_hook(future):
return future.result()
elif not callable(result_hook):
raise TypeError("expected result_hook to be callable")
obj._result_hook = result_hook
return obj
###############################################################################################
# Special Methods
###############################################################################################
def __len__(self):
"""The number of rows in record."""
return self.record.__len__()
def __iter__(self):
"""Iterate over the samples, low energy to high."""
# need to make it an iterator rather than just an iterable
return iter(self.samples(sorted_by='energy'))
def __eq__(self, other):
"""SampleSet equality."""
if not isinstance(other, SampleSet):
return False
if self.vartype != other.vartype or self.info != other.info:
return False
# check that all the fields match in record, order doesn't matter
if self.record.dtype.fields.keys() != other.record.dtype.fields.keys():
return False
for field in self.record.dtype.fields: