示例#1
0
    def test_instantiation_keyword_arguments(self):
        conn = microclient.Connection()

        for solver_name in conn.solver_names():
            solver = microclient.Connection().get_solver(
                solver_name)  # the solver the is wrapped by dimod
            sampler = micro.DWaveSampler(solver_name=solver_name)

            for param in solver.parameters:
                self.assertIn(param, sampler.sample_kwargs)
示例#2
0
 def test_submit_invalid_parameter(self):
     """Ensure that the parameters are populated."""
     con = dwave_micro_client.Connection(config_url, config_token)
     solver = con.get_solver(config_solver)
     assert 'not_a_parameter' not in solver.parameters
     with self.assertRaises(KeyError):
         solver.sample_ising({}, {}, not_a_parameter=True)
    def test_cancel_with_id(self):
        """Make sure the cancel method submits to the right endpoint.

        When cancel is called after the submission is finished.
        """
        submission_id = 'test-id'
        reply_body = '[%s]' % continue_reply(submission_id, 'solver')

        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()

            con.session.get = lambda a: choose_reply(
                a, {'/problems/?id={}'.format(submission_id): reply_body})
            con.session.delete = DeleteEvent.handle

            solver = dwave_micro_client.Solver(con, solver_data('abc123'))
            future = solver.retrieve_problem(submission_id)
            future.cancel()

            try:
                self.assertTrue(future.id is not None)
                future.samples
                self.fail()
            except DeleteEvent as event:
                if event.url == '/problems/':
                    self.assertEqual(event.body,
                                     '["{}"]'.format(submission_id))
                else:
                    self.assertEqual(event.url,
                                     '/problems/{}/'.format(submission_id))
示例#4
0
 def test_load_missing_solver(self):
     """Try to load a solver that does not exist."""
     with requests_mock.mock() as m:
         m.get(requests_mock.ANY, status_code=404)
         con = dwave_micro_client.Connection(url, token)
         with self.assertRaises(KeyError):
             con.get_solver(solver_name)
示例#5
0
 def test_bad_token(self):
     """Connect with a bad token."""
     with requests_mock.mock() as m:
         setup_server(m)
         with self.assertRaises(IOError):
             con = dwave_micro_client.Connection(url, bad_token)
             con.solver_names()
示例#6
0
 def test_load_solver_missing_data(self):
     """Try to load a solver that has incomplete data."""
     with requests_mock.mock() as m:
         m.get(solver1_url, text=solver_object(solver_name, True))
         con = dwave_micro_client.Connection(url, token)
         with self.assertRaises(KeyError):
             con.get_solver(solver_name)
示例#7
0
    def test_submit_partial_problem(self):
        """Submit a probem with only some of the terms set."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # Build a linear problem
        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}

        # Remove half the qubits
        nodes = list(solver.nodes)
        for index in nodes[0:len(nodes) // 2]:
            linear[index] = 0
            quad = {
                key: value
                for key, value in quad.items() if index not in key
            }

        # Solve the problem
        self._submit_and_check(solver, linear, quad)
示例#8
0
    def test_wait_many(self):
        """Submit a batch of problems then use `wait_multiple` to wait on all of them."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # Build a linear problem
        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}

        result_list = []
        for _ in range(100):

            results = solver.sample_ising(linear, quad, num_reads=40)
            result_list.append([results, linear, quad])

        dwave_micro_client.Future.wait_multiple([f[0] for f in result_list])

        for results, _, _ in result_list:
            self.assertTrue(results.done())

        for results, linear, quad in result_list:
            # Did we get the right number of samples?
            self.assertTrue(40 == sum(results.occurrences))

            # Make sure the number of occurrences and energies are all correct
            for energy, state in zip(results.energies, results.samples):
                self.assertTrue(energy == dwave_micro_client._evaluate_ising(
                    linear, quad, state))
示例#9
0
 def test_nothing(self):
     """With no values set, we should get an error when trying to open the config file."""
     m = mock.mock_open()
     m.side_effect = IOError
     with mock.patch("dwave_micro_client.open", m):
         with self.assertRaises(IOError):
             dwave_micro_client.Connection()
    def test_submit_continue_then_ok_and_error_reply(self):
        """Handle polling for the status of multiple problems."""
        # Reduce the number of poll threads to 1 so that the system can be tested
        old_value = dwave_micro_client.Connection._POLL_THREAD_COUNT
        dwave_micro_client.Connection._POLL_THREAD_COUNT = 1
        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.get = lambda a: choose_reply(
                a,
                {
                    # Wait until both problems are
                    '/problems/?id=1':
                    '[%s]' % continue_reply('1', 'abc123'),
                    '/problems/?id=2':
                    '[%s]' % continue_reply('2', 'abc123'),
                    '/problems/?id=2,1':
                    '[' + complete_no_answer_reply('2', 'abc123') + ',' +
                    error_reply('1', 'abc123', 'error') + ']',
                    '/problems/?id=1,2':
                    '[' + error_reply('1', 'abc123', 'error') + ',' +
                    complete_no_answer_reply('2', 'abc123') + ']',
                    '/problems/1/':
                    error_reply('1', 'abc123', 'Error message'),
                    '/problems/2/':
                    complete_reply('2', 'abc123')
                })

            def switch_post_reply(path, body):
                message = json.loads(body)
                if len(message) == 1:
                    con.session.post = lambda a, _: choose_reply(
                        a,
                        {'/problems/': '[%s]' % continue_reply('2', 'abc123')})
                    return choose_reply(
                        '', {'': '[%s]' % continue_reply('1', 'abc123')})
                else:
                    con.session.post = None
                    return choose_reply(
                        '', {
                            '':
                            '[%s, %s]' % (continue_reply(
                                '1', 'abc123'), continue_reply('2', 'abc123'))
                        })

            con.session.post = lambda a, body: switch_post_reply(a, body)

            solver = dwave_micro_client.Solver(con, solver_data('abc123'))
            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}

            results1 = solver.sample_ising(linear, quad, num_reads=100)
            results2 = solver.sample_ising(linear, quad, num_reads=100)

            #
            with self.assertRaises(dwave_micro_client.SolverFailureError):
                self._check(results1, linear, quad, 100)
            self._check(results2, linear, quad, 100)
        dwave_micro_client.Connection._POLL_THREAD_COUNT = old_value
示例#11
0
 def test_load_solver_broken_response(self):
     """Try to load a solver for which the server has returned a truncated response."""
     with requests_mock.mock() as m:
         body = solver_object(solver_name)
         m.get(solver1_url, text=body[0:len(body) // 2])
         con = dwave_micro_client.Connection(url, token)
         with self.assertRaises(ValueError):
             con.get_solver(solver_name)
示例#12
0
 def test_explicit_only(self):
     """Specify information only through function arguments."""
     con = dwave_micro_client.Connection('arg-url', 'arg-token')
     con.session.get = GetEvent.handle
     try:
         con.get_solver('arg-solver')
     except GetEvent as event:
         self.assertTrue(event.url.startswith('arg-url'))
         return
     self.fail()
示例#13
0
    def test_submit_dict_problem(self):
        """Submit a problem using a dict for the linear terms."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # Build a problem
        linear = {index: random.choice([-1, 1]) for index in solver.nodes}
        quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}

        # Solve the problem
        self._submit_and_check(solver, linear, quad)
示例#14
0
 def test_only_file_key(self):
     """If give a name from the config file the proper URL should be loaded."""
     with mock.patch("dwave_micro_client.open",
                     mock.mock_open(read_data=config_body)):
         con = dwave_micro_client.Connection('alpha')
         con.session.get = GetEvent.handle
         try:
             con.get_solver('arg-solver')
         except GetEvent as event:
             self.assertTrue(event.url.startswith('file-alpha-url'))
             return
         self.fail()
示例#15
0
 def test_only_file(self):
     """With no arguments or environment variables, the default connection from the config file should be used."""
     with mock.patch("dwave_micro_client.open",
                     mock.mock_open(read_data=config_body)):
         con = dwave_micro_client.Connection()
         con.session.get = GetEvent.handle
         try:
             con.get_solver('arg-solver')
         except GetEvent as event:
             self.assertTrue(event.url.startswith('file-prod-url'))
             return
         self.fail()
示例#16
0
 def test_explicit_with_file(self):
     """With arguments and a config file, the config file should be ignored."""
     with mock.patch("dwave_micro_client.open",
                     mock.mock_open(read_data=config_body)):
         con = dwave_micro_client.Connection('arg-url', 'arg-token')
         con.session.get = GetEvent.handle
         try:
             con.get_solver('arg-solver')
         except GetEvent as event:
             self.assertTrue(event.url.startswith('arg-url'))
             return
         self.fail()
示例#17
0
 def test_env_args_set(self):
     """With arguments and environment variables, the environment variables should be ignored."""
     with mock.patch.dict(os.environ, {
             'DW_INTERNAL__HTTPLINK': 'env-url',
             'DW_INTERNAL__TOKEN': 'env-token'
     }):
         con = dwave_micro_client.Connection('args-url', 'args-token')
         con.session.get = GetEvent.handle
         try:
             con.get_solver('arg-solver')
         except GetEvent as event:
             self.assertTrue(event.url.startswith('args-url'))
             return
         self.fail()
示例#18
0
    def test_submit_linear_problem(self):
        """Submit a problem with all the linear terms populated."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # Build a linear problem
        linear = [0] * (max(solver.nodes) + 1)
        for index in solver.nodes:
            linear[index] = 1
        quad = {}

        # Solve the problem
        self._submit_and_check(solver, linear, quad)
示例#19
0
    def test_request_raw_list_with_numpy(self):
        """Submit a problem using a dict for the linear terms."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        assert dwave_micro_client._numpy
        solver = con.get_solver(config_solver)
        solver.return_matrix = False

        # Build a problem
        linear = {index: random.choice([-1, 1]) for index in solver.nodes}
        quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}

        # Solve the problem
        self._submit_and_check(solver, linear, quad)
示例#20
0
    def test_request_raw_matrix_with_no_numpy(self):
        """Submit a problem using a dict for the linear terms."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        dwave_micro_client._numpy = False
        solver = con.get_solver(config_solver)
        solver.return_matrix = True

        # Build a problem
        linear = {index: random.choice([-1, 1]) for index in solver.nodes}
        quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}

        # Solve the problem
        with self.assertRaises(ValueError):
            self._submit_and_check(solver, linear, quad, answer_mode='raw')
    def test_submit_null_reply(self):
        """Get an error when the server's response is incomplete."""
        # con = mock.Mock()
        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.post = lambda a, _: choose_reply(a, {'/problems/': ''})
            solver = dwave_micro_client.Solver(con, solver_data('abc123'))

            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}
            results = solver.sample_ising(linear, quad, num_reads=100)

            #
            with self.assertRaises(ValueError):
                results.samples
示例#22
0
    def test_submit_full_problem(self):
        """Submit a problem with all supported coefficents set."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # Build a linear problem
        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}

        # Solve the problem
        self._submit_and_check(solver, linear, quad)
    def test_submit_cancel_reply(self):
        """Handle a response for a canceled job."""
        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.post = lambda a, _: choose_reply(
                a, {'/problems/': '[%s]' % cancel_reply('123', 'abc123')})
            solver = dwave_micro_client.Solver(con, solver_data('abc123'))

            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}
            results = solver.sample_ising(linear, quad, num_reads=100)

            #
            with self.assertRaises(dwave_micro_client.CanceledFutureError):
                results.samples
示例#24
0
 def test_env_with_file_set(self):
     """With environment variables and a config file, the config file should be ignored."""
     with mock.patch("dwave_micro_client.open",
                     mock.mock_open(read_data=config_body)):
         with mock.patch.dict(
                 os.environ, {
                     'DW_INTERNAL__HTTPLINK': 'env-url',
                     'DW_INTERNAL__TOKEN': 'env-token'
                 }):
             con = dwave_micro_client.Connection()
             con.session.get = GetEvent.handle
             try:
                 con.get_solver('arg-solver')
             except GetEvent as event:
                 self.assertTrue(event.url.startswith('env-url'))
                 return
             self.fail()
示例#25
0
    def test_submit_extra_qubit(self):
        """Submit a defective problem with an unsupported variable."""
        # Connect
        con = dwave_micro_client.Connection(config_url, config_token)
        solver = con.get_solver(config_solver)

        # 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
        linear.append(1)

        with self.assertRaises(ValueError):
            results = solver.sample_ising(linear, quad)
            results.samples
示例#26
0
    def test_request_matrix_with_numpy(self):
        """Submit a problem using a dict for the linear terms."""
        # Connect
        import numpy
        con = dwave_micro_client.Connection(config_url, config_token)
        assert dwave_micro_client._numpy
        solver = con.get_solver(config_solver)
        solver.return_matrix = True

        # Build a problem
        linear = {index: random.choice([-1, 1]) for index in solver.nodes}
        quad = {key: random.choice([-1, 1]) for key in solver.undirected_edges}

        # Solve the problem
        result = self._submit_and_check(solver, linear, quad)
        self.assertIsInstance(result.samples, numpy.ndarray)
        self.assertIsInstance(result.energies, numpy.ndarray)
        self.assertIsInstance(result.occurrences, numpy.ndarray)
    def test_submit_error_reply(self):
        """Handle an error on problem submission."""
        error_body = 'An error message'
        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.post = lambda a, _: choose_reply(
                a, {
                    '/problems/': '[%s]' % error_reply('123', 'abc123',
                                                       error_body)
                })
            solver = dwave_micro_client.Solver(con, solver_data('abc123'))

            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}
            results = solver.sample_ising(linear, quad, num_reads=100)

            #
            with self.assertRaises(dwave_micro_client.SolverFailureError):
                results.samples
示例#28
0
    def test_instantiation_structure(self):
        """check that the correct structure was assigned to the dimod sampler"""

        # these should refer to the same thing
        sampler = micro.DWaveSampler()
        solver = microclient.Connection().get_solver(
        )  # the solver the is wrapped by dimod

        nodelist, edgelist, adj = sampler.structure
        nodes = set(nodelist)
        edges = set(edgelist)

        for u, v in solver.edges:
            self.assertTrue((u, v) in edges or (v, u) in edges)
            self.assertIn(u, nodes)
            self.assertIn(v, nodes)
            self.assertIn(v, adj)
            self.assertIn(v, adj[u])
            self.assertIn(u, adj)
            self.assertIn(u, adj[v])
    def test_submit_ok_reply(self):
        """Handle a normal query and response."""
        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.post = lambda a, _: choose_reply(
                a, {
                    '/problems/':
                    '[%s]' % complete_no_answer_reply('123', 'abc123')
                })
            con.session.get = lambda a: choose_reply(
                a, {'/problems/123/': complete_reply('123', 'abc123')})
            solver = dwave_micro_client.Solver(con, solver_data('abc123'))

            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}
            results = solver.sample_ising(linear, quad, num_reads=100)

            #
            self._check(results, linear, quad, 100)
    def test_cancel_without_id(self):
        """Make sure the cancel method submits to the right endpoint.

        When cancel is called before the submission has returned the problem id.
        """
        submission_id = 'test-id'
        reply_body = '[%s]' % continue_reply(submission_id, 'solver')

        release_reply = threading.Event()

        with dwave_micro_client.Connection('', '') as con:
            con.session = mock.Mock()
            con.session.get = lambda a: choose_reply(
                a, {'/problems/?id={}'.format(submission_id): reply_body})

            def post(a, _):
                release_reply.wait()
                return choose_reply(
                    a, {'/problems/'.format(submission_id): reply_body})

            con.session.post = post
            con.session.delete = DeleteEvent.handle

            solver = dwave_micro_client.Solver(con, solver_data('abc123'))
            # Build a problem
            linear = {index: 1 for index in solver.nodes}
            quad = {key: -1 for key in solver.undirected_edges}
            future = solver.sample_ising(linear, quad)
            future.cancel()

            try:
                release_reply.set()
                future.samples
                self.fail()
            except DeleteEvent as event:
                if event.url == '/problems/':
                    self.assertEqual(event.body,
                                     '["{}"]'.format(submission_id))
                else:
                    self.assertEqual(event.url,
                                     '/problems/{}/'.format(submission_id))