Skip to content

Commit

Permalink
Merge pull request #450 from arcondello/fix/sampleset.samples-iterator
Browse files Browse the repository at this point in the history
Make SampleSet.samples an iterator
  • Loading branch information
arcondello authored Mar 28, 2019
2 parents f47b45f + 8a775f7 commit 7d22497
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
21 changes: 19 additions & 2 deletions dimod/views/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ def __iter__(self):
return iter(self._mapping._data.flat)


class SamplesArray(abc.Sequence):
__slots__ = ('_samples', '_variables')
# developer note: Iterator functionality is deprecated
class SamplesArray(abc.Sequence, abc.Iterator):
__slots__ = ('_samples', '_variables',
'_itercount') # used for deprecated iteration feature

def __init__(self, samples, variables):
self._samples = samples
Expand Down Expand Up @@ -136,5 +138,20 @@ def __iter__(self):
for row in self._samples:
yield SampleView(row, variables)

def __next__(self):
import warnings
msg = ("SampleSet.samples() will return an iterable not an iterator in "
"the future")
warnings.warn(msg, DeprecationWarning)

itercount = getattr(self, '_itercount', 0)
if itercount < len(self):
self._itercount = itercount + 1
return self[itercount]
raise StopIteration

next = __next__ # for python2


def __len__(self):
return self._samples.shape[0]
14 changes: 14 additions & 0 deletions tests/test_sampleset.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
import unittest
import json

try:
import collections.abc as abc
except ImportError:
import collections as abc

from collections import OrderedDict

import numpy as np
Expand Down Expand Up @@ -354,6 +359,15 @@ def test_data_reverse(self):
reversed_samples = list(sampleset.data(reverse=True))
self.assertEqual(samples, list(reversed(reversed_samples)))

def test_iterator(self):
# deprecated feature
bqm = dimod.BinaryQuadraticModel.from_ising({}, {'ab': -1})
sampleset = dimod.SampleSet.from_samples_bqm([{'a': -1, 'b': 1}, {'a': 1, 'b': 1}], bqm)
self.assertIsInstance(sampleset.samples(), abc.Iterator)
self.assertIsInstance(sampleset.samples(n=2), abc.Iterator)
spl = next(sampleset.samples())
self.assertEqual(spl, {'a': 1, 'b': 1})


class TestSerialization(unittest.TestCase):
def test_empty_with_bytes(self):
Expand Down

0 comments on commit 7d22497

Please sign in to comment.