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.
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.
 

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 
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):

pip install -e .[all]
parse_log_pytest
requirements.txt
pytest coverage codecov
apt-get update apt-get install -y libboost-dev
3.6
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
Cython==3.0.12
decorator==5.1.1
-e git+https://github.com/dwavesystems/dimod.git@15e6f93638b937156e8f0fff008c3b63a451aa45#egg=dimod
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
jsonschema==2.6.0
mock==2.0.0
networkx==2.0
numpy==1.15.0
packaging==21.3
pandas==0.22.0
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pymongo==3.7.1
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.27.1
six==1.11.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0

name: dimod
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - attrs==22.2.0
      - charset-normalizer==2.0.12
      - codecov==2.1.13
      - coverage==6.2
      - cython==3.0.12
      - decorator==5.1.1
      - idna==3.10
      - importlib-metadata==4.8.3
      - iniconfig==1.1.1
      - jsonschema==2.6.0
      - mock==2.0.0
      - networkx==2.0
      - numpy==1.15.0
      - packaging==21.3
      - pandas==0.22.0
      - pbr==6.1.1
      - pluggy==1.0.0
      - py==1.11.0
      - pymongo==3.7.1
      - pyparsing==3.1.4
      - pytest==7.0.1
      - python-dateutil==2.9.0.post0
      - pytz==2025.2
      - requests==2.27.1
      - six==1.11.0
      - tomli==1.2.3
      - typing-extensions==4.1.1
      - urllib3==1.26.20
      - zipp==3.6.0
prefix: /opt/conda/envs/dimod

tests/test_sampleset.py::TestConstruction::test_from_bqm_with_sorting
tests/test_sampleset.py::Test_as_samples::test_copy_false tests/test_sampleset.py::Test_as_samples::test_dict_with_inconsistent_labels tests/test_sampleset.py::Test_as_samples::test_dict_with_labels tests/test_sampleset.py::Test_as_samples::test_empty_dict tests/test_sampleset.py::Test_as_samples::test_empty_list tests/test_sampleset.py::Test_as_samples::test_empty_list_labelled tests/test_sampleset.py::Test_as_samples::test_empty_ndarray tests/test_sampleset.py::Test_as_samples::test_iterator tests/test_sampleset.py::Test_as_samples::test_iterator_labelled tests/test_sampleset.py::Test_as_samples::test_list_of_empty tests/test_sampleset.py::Test_as_samples::test_mixed_sampletype tests/test_sampleset.py::Test_as_samples::test_ndarray tests/test_sampleset.py::Test_as_samples::test_ndarray_labelled tests/test_sampleset.py::TestConstruction::test_from_bqm_single_sample tests/test_sampleset.py::TestConstruction::test_from_samples tests/test_sampleset.py::TestConstruction::test_from_samples_empty tests/test_sampleset.py::TestConstruction::test_from_samples_fields_multiple tests/test_sampleset.py::TestConstruction::test_from_samples_fields_single tests/test_sampleset.py::TestConstruction::test_from_samples_iterator tests/test_sampleset.py::TestConstruction::test_from_samples_single_sample tests/test_sampleset.py::TestConstruction::test_from_samples_str_labels tests/test_sampleset.py::TestConstruction::test_from_samples_with_aggregation tests/test_sampleset.py::TestConstruction::test_mismatched_shapes tests/test_sampleset.py::TestConstruction::test_shorter_samples tests/test_sampleset.py::TestEq::test_ordered tests/test_sampleset.py::TestAggregate::test_aggregate_simple tests/test_sampleset.py::TestTruncate::test_typical tests/test_sampleset.py::TestTruncate::test_unordered tests/test_sampleset.py::TestIteration::test_data_reverse tests/test_sampleset.py::TestSerialization::test_empty_with_bytes tests/test_sampleset.py::TestSerialization::test_from_serializable_empty_v1 tests/test_sampleset.py::TestSerialization::test_from_serializable_empty_variables_v1 tests/test_sampleset.py::TestSerialization::test_from_serializable_triu_v1 tests/test_sampleset.py::TestSerialization::test_functional_json tests/test_sampleset.py::TestSerialization::test_functional_simple_shapes tests/test_sampleset.py::TestSerialization::test_functional_str tests/test_sampleset.py::TestSerialization::test_triu_with_bytes tests/test_sampleset.py::TestPandas::test_sample_column tests/test_sampleset.py::TestPandas::test_simple tests/test_sampleset.py::TestFirst::test_empty tests/test_sampleset.py::TestDataVectors::test_empty tests/test_sampleset.py::TestDataVectors::test_view tests/test_sampleset.py::Test_concatenate::test_empty tests/test_sampleset.py::Test_concatenate::test_simple tests/test_sampleset.py::Test_concatenate::test_variables_order tests/test_sampleset.py::Test_concatenate::test_variables_order_and_vartype
dimod/sampleset.py dimod/compatibility23.py
dimod/sampleset.py dimod/compatibility23.py