Repository: dwavesystems/dwave-cloud-client
Pull request #169 (2018-05-10 21:24:59)

Fix max number of reads in tests to max supported


Patch:
diff --git a/dwave/cloud/__init__.py b/dwave/cloud/__init__.py
index 15e0bed..e0e4baf 100644
--- a/dwave/cloud/__init__.py
+++ b/dwave/cloud/__init__.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import
 
+import os
 import logging
 
 from dwave.cloud.client import Client
@@ -20,11 +21,24 @@ root.addHandler(handler)
 
 
 # add TRACE log level and Logger.trace() method
-TRACE_LOGLEVEL = 5
+logging.TRACE = 5
+logging.addLevelName(logging.TRACE, "TRACE")
 
-logging.addLevelName(TRACE_LOGLEVEL, "TRACE")
-def _trace(logger, message, *args, **kws):
-    if logger.isEnabledFor(TRACE_LOGLEVEL):
-        logger._log(TRACE_LOGLEVEL, message, args, **kws)
+def _trace(logger, message, *args, **kwargs):
+    if logger.isEnabledFor(logging.TRACE):
+        logger._log(logging.TRACE, message, *args, **kwargs)
 
 logging.Logger.trace = _trace
+
+
+# apply DWAVE_LOG_LEVEL
+def _apply_loglevel_from_env(logger):
+    name = os.getenv('DWAVE_LOG_LEVEL') or ''
+    if not name:
+        return
+    levels = {'debug': logging.DEBUG, 'trace': logging.TRACE}
+    requested_level = levels.get(name.lower())
+    if requested_level:
+        logger.setLevel(requested_level)
+
+_apply_loglevel_from_env(root)
diff --git a/dwave/cloud/utils.py b/dwave/cloud/utils.py
index 6d67e0b..f48a20d 100644
--- a/dwave/cloud/utils.py
+++ b/dwave/cloud/utils.py
@@ -46,9 +46,21 @@ def evaluate_ising(linear, quad, state):
 
 def active_qubits(linear, quadratic):
     """Calculate a set of all active qubits. Qubit is "active" if it has
-    bias or coupling attached."""
+    bias or coupling attached.
 
-    active = set(linear)
+    Args:
+        linear (dict[variable, bias]/list[variable, bias]):
+            Linear terms of the model.
+
+        quadratic (dict[(variable, variable), bias]):
+            Quadratic terms of the model.
+
+    Returns:
+        set:
+            Active qubits' indices.
+    """
+
+    active = {idx for idx,bias in uniform_iterator(linear)}
     for edge, _ in six.iteritems(quadratic):
         active.update(edge)
     return active


Test patch:
diff --git a/tests/test_solver.py b/tests/test_solver.py
index 3a65561..e745b1e 100644
--- a/tests/test_solver.py
+++ b/tests/test_solver.py
@@ -98,8 +98,6 @@ class Submission(_QueryTest):
 
             # Build a linear problem
             linear = [0] * (max(solver.nodes) + 1)
-            for index in solver.nodes:
-                linear[index] = 1
             quad = {}
 
             # Add a variable that shouldn't exist
@@ -116,9 +114,7 @@ class Submission(_QueryTest):
             solver = client.get_solver()
 
             # Build a linear problem
-            linear = [0] * (max(solver.nodes) + 1)
-            for index in solver.nodes:
-                linear[index] = 1
+            linear = [1] * (max(solver.nodes) + 1)
             quad = {}
 
             # Solve the problem
@@ -215,13 +211,13 @@ class Submission(_QueryTest):
             linear = [0] * (max(solver.nodes) + 1)
             for index in solver.nodes:
                 linear[index] = random.choice([-1, 1])
-
-            # Build a
             quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}
 
+            max_num_reads = max(solver.properties.get('num_reads_range', [1, 100]))
+
             result_list = []
             for _ in range(1000):
-                results = solver.sample_ising(linear, quad, num_reads=10000)
+                results = solver.sample_ising(linear, quad, num_reads=max_num_reads)
                 result_list.append([results, linear, quad])
 
             [r[0].cancel() for r in result_list]
@@ -230,7 +226,7 @@ class Submission(_QueryTest):
                 # Responses must be canceled or correct
                 try:
                     # Did we get the right number of samples?
-                    self.assertTrue(10000 == sum(results.occurrences))
+                    self.assertTrue(max_num_reads == sum(results.occurrences))
 
                     # Make sure the number of occurrences and energies are all correct
                     for energy, state in zip(results.energies, results.samples):
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 8a6f4db..30e157d 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -2,7 +2,8 @@ import unittest
 from collections import OrderedDict
 
 from dwave.cloud.utils import (
-    readline_input, uniform_iterator, uniform_get, strip_head, strip_tail)
+    readline_input, uniform_iterator, uniform_get, strip_head, strip_tail,
+    active_qubits)
 from dwave.cloud.testing import mock
 
 
@@ -35,6 +36,19 @@ class TestUtils(unittest.TestCase):
         self.assertEqual(strip_tail([1], []), [1])
         self.assertEqual(strip_tail([0, 0, 1, 2], [0, 1, 2]), [])
 
+    def test_active_qubits_dict(self):
+        self.assertEqual(active_qubits({}, {}), set())
+        self.assertEqual(active_qubits({0: 0}, {}), {0})
+        self.assertEqual(active_qubits({}, {(0, 1): 0}), {0, 1})
+        self.assertEqual(active_qubits({2: 0}, {(0, 1): 0}), {0, 1, 2})
+
+    def test_active_qubits_list(self):
+        self.assertEqual(active_qubits([], {}), set())
+        self.assertEqual(active_qubits([2], {}), {0})
+        self.assertEqual(active_qubits([2, 2, 0], {}), {0, 1, 2})
+        self.assertEqual(active_qubits([], {(0, 1): 0}), {0, 1})
+        self.assertEqual(active_qubits([0, 0], {(0, 2): 0}), {0, 1, 2})
+
     def test_readline_input(self):
         val = "value"
         with mock.patch("six.moves.input", side_effect=[val], create=True):