Repository: dwavesystems/dimod

Issue:
Consistent variable order for integer-labelled responses
**Application**
When using index labels, it would be nice if the samples in `response.record.sample` where column-ordered by index. This would save needing to do things like `response.record.sample[label_to_idx[0]]`. There is a small performance benefit (skipping the dict look up), and it results in cleaner code. I also think that this might be the less unexpected behaviour, though I do like the consistency of the current approach.

**Proposed Solution/Alternatives Considered**

Three options occur to me:
1) On construction of the response object, we could check that the labels are [0,n) and in that case, sort.
2) Add a kwarg that would toggle the sorting behaviour, perhaps defaulting to True
3) Do nothing but update the existing solvers to return the samples in the appropriate order

@caja-matematica @sploiber 

Discussion:
codecov-io: # [Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=h1) Report
> Merging [#398](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=desc) into [master](https://codecov.io/gh/dwavesystems/dimod/commit/cbcea2e9809fa2016e5728cf6d170db7f02e2712?src=pr&el=desc) will **decrease** coverage by `0.16%`.
> The diff coverage is `93.54%`.

[![Impacted file tree graph](https://codecov.io/gh/dwavesystems/dimod/pull/398/graphs/tree.svg?width=650&token=KyxipO4fvT&height=150&src=pr)](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #398      +/-   ##
==========================================
- Coverage   91.58%   91.41%   -0.17%     
==========================================
  Files          40       40              
  Lines        2496     2517      +21     
==========================================
+ Hits         2286     2301      +15     
- Misses        210      216       +6
```


| [Impacted Files](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [dimod/sampleset.py](https://codecov.io/gh/dwavesystems/dimod/pull/398/diff?src=pr&el=tree#diff-ZGltb2Qvc2FtcGxlc2V0LnB5) | `93.45% <100%> (-1.46%)` | :arrow_down: |
| [dimod/compatibility23.py](https://codecov.io/gh/dwavesystems/dimod/pull/398/diff?src=pr&el=tree#diff-ZGltb2QvY29tcGF0aWJpbGl0eTIzLnB5) | `93.75% <90.47%> (-6.25%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=footer). Last update [cbcea2e...8a46dcc](https://codecov.io/gh/dwavesystems/dimod/pull/398?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

arcondello: A simpler approach might be to simply sort them if they are sortable (int-labelled for instance) and otherwise leave them unsorted.

Patch:
diff --git a/dimod/compatibility23.py b/dimod/compatibility23.py
index d60f2d00..d5dd2e5c 100644
--- a/dimod/compatibility23.py
+++ b/dimod/compatibility23.py
@@ -12,7 +12,7 @@
 #    See the License for the specific language governing permissions and
 #    limitations under the License.
 #
-# ================================================================================================
+# =============================================================================
 
 import sys
 import inspect
diff --git a/dimod/sampleset.py b/dimod/sampleset.py
index d53c8f8a..215ecc3a 100644
--- a/dimod/sampleset.py
+++ b/dimod/sampleset.py
@@ -173,7 +173,6 @@ def as_samples(samples_like, dtype=None, copy=False, order='C'):
     if labels is None:
         return arr, list(range(arr.shape[1]))
     elif len(labels) != arr.shape[1]:
-        print(arr, arr.shape, samples_like, labels, len(labels))
         raise ValueError("samples_like and labels dimensions do not match")
     else:
         return arr, labels
@@ -320,7 +319,8 @@ class SampleSet(abc.Iterable, abc.Sized):
 
     @classmethod
     def from_samples(cls, samples_like, vartype, energy, info=None,
-                     num_occurrences=None, aggregate_samples=False, **vectors):
+                     num_occurrences=None, aggregate_samples=False,
+                     sort_labels=True, **vectors):
         """Build a :class:`SampleSet` from raw samples.
 
         Args:
@@ -346,6 +346,11 @@ class SampleSet(abc.Iterable, abc.Sized):
             aggregate_samples (bool, optional, default=False):
                 If true, returned :obj:`.SampleSet` will have all unique samples.
 
+            sort_labels (bool, optional, default=True):
+                If true, :attr:`.SampleSet.variables` will be in sorted-order.
+                Note that mixed types are not sortable in which case the given
+                order will be maintained.
+
             **vectors (array_like):
                 Other per-sample data.
 
@@ -375,6 +380,19 @@ class SampleSet(abc.Iterable, abc.Sized):
         # 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)
@@ -427,6 +445,11 @@ class SampleSet(abc.Iterable, abc.Sized):
             aggregate_samples (bool, optional, default=False):
                 If true, returned :obj:`.SampleSet` will have all unique samples.
 
+            sort_labels (bool, optional, default=True):
+                If true, :attr:`.SampleSet.variables` will be in sorted-order.
+                Note that mixed types are not sortable in which case the given
+                order will be maintained.
+
             **vectors (array_like):
                 Other per-sample data.
 


Test patch:
diff --git a/tests/test_sampleset.py b/tests/test_sampleset.py
index 4ac0ad4f..a3ba8f2d 100644
--- a/tests/test_sampleset.py
+++ b/tests/test_sampleset.py
@@ -221,6 +221,16 @@ class TestConstruction(unittest.TestCase):
         self.assertEqual(samples,
                          dimod.SampleSet.from_samples(([-1, 1], 'ab'), dimod.SPIN, energy=1))
 
+    def test_from_bqm_with_sorting(self):
+        bqm = dimod.BinaryQuadraticModel.from_ising({}, {(0, 1): -1, (1, 2): -1})
+
+        raw = np.triu(np.ones((3, 3)))
+        variables = [2, 1, 0]
+
+        samples = dimod.SampleSet.from_samples_bqm((raw, variables), bqm)
+        self.assertEqual(samples.variables, [0, 1, 2])
+        np.testing.assert_array_equal(np.flip(raw, 1), samples.record.sample)
+
 
 class TestEq(unittest.TestCase):
     def test_ordered(self):