def test_submit_continue_then_ok_reply(self):
        """Handle polling for a complete problem."""
        with Client('endpoint', 'token') as client:
            now = datetime_in_future(0)
            eta_min, eta_max = datetime_in_future(10), datetime_in_future(30)
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(a, {
                'endpoint/problems/':
                '[%s]' % continue_reply(
                    '123', 'abc123', eta_min=eta_min, eta_max=eta_max, now=now)
            },
                                                            date=now)
            client.session.get = lambda a: choose_reply(a, {
                'endpoint/problems/?id=123':
                '[%s]' % complete_no_answer_reply('123', 'abc123'),
                'endpoint/problems/123/':
                complete_reply('123', 'abc123')
            },
                                                        date=now)
            solver = Solver(client, 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)

            # test future has eta_min and eta_max parsed correctly
            self.assertEqual(results.eta_min, eta_min)
            self.assertEqual(results.eta_max, eta_max)
    def test_solver_feature_properties(self):
        self.assertTrue(solver_object('dw2000').is_qpu)
        self.assertFalse(solver_object('dw2000').is_software)
        self.assertFalse(solver_object('c4-sw_x').is_qpu)
        self.assertTrue(solver_object('c4-sw_x').is_software)

        self.assertFalse(solver_object('dw2000').is_vfyc)
        self.assertEqual(solver_object('dw2000').num_qubits, 3)
        self.assertFalse(solver_object('dw2000').has_flux_biases)

        data = json.loads(solver_data('test'))
        data['properties']['vfyc'] = 'error'
        self.assertFalse(Solver(None, data).is_vfyc)
        data['properties']['vfyc'] = True
        self.assertTrue(Solver(None, data).is_vfyc)

        data['properties']['parameters']['flux_biases'] = '...'
        self.assertTrue(Solver(None, data).has_flux_biases)

        # test `.is_online` property
        self.assertTrue(solver_object('dw2000').is_online)
        data = json.loads(solver_data('test'))
        data['status'] = 'offline'
        self.assertFalse(Solver(None, data).is_online)
        del data['status']
        self.assertTrue(Solver(None, data).is_online)
    def test_eta_min_is_respected_on_first_poll(self):
        "eta_min/earliest_estimated_completion should be respected if present in response"

        with Client('endpoint', 'token') as client:
            now = datetime_in_future(0)
            eta_min, eta_max = datetime_in_future(10), datetime_in_future(30)
            client.session = mock.Mock()
            client.session.post = lambda path, _: choose_reply(path, {
                'endpoint/problems/':
                '[%s]' % continue_reply(
                    '1', 'abc123', eta_min=eta_min, eta_max=eta_max, now=now)
            },
                                                               date=now)
            client.session.get = lambda path: choose_reply(path, {
                'endpoint/problems/?id=1':
                '[%s]' % complete_no_answer_reply('1', 'abc123'),
                'endpoint/problems/1/':
                complete_reply('1', 'abc123')
            },
                                                           date=now)

            solver = Solver(client, solver_data('abc123'))

            def assert_min_eta(s):
                s and self.assertTrue(abs(s - 10) < 1)

            with mock.patch('time.sleep', assert_min_eta):
                future = solver.sample_qubo({})
                future.result()
    def test_immediate_polling_with_local_clock_unsynced(self):
        """First poll happens with minimal delay if local clock is way off from
        the remote/server clock."""

        with Client('endpoint', 'token') as client:
            badnow = datetime_in_future(100)
            client.session = mock.Mock()
            client.session.post = lambda path, _: choose_reply(
                path,
                {'endpoint/problems/': '[%s]' % continue_reply('1', 'abc123')},
                date=badnow)
            client.session.get = lambda path: choose_reply(path, {
                'endpoint/problems/?id=1':
                '[%s]' % complete_no_answer_reply('1', 'abc123'),
                'endpoint/problems/1/':
                complete_reply('1', 'abc123')
            },
                                                           date=badnow)

            solver = Solver(client, solver_data('abc123'))

            def assert_no_delay(s):
                s and self.assertTrue(
                    abs(s - client._POLL_BACKOFF_MIN) <
                    client._POLL_BACKOFF_MIN / 10.0)

            with mock.patch('time.sleep', assert_no_delay):
                future = solver.sample_qubo({})
                future.result()
    def test_submit_continue_then_ok_reply(self):
        """Handle polling for a complete problem."""
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(
                a, {
                    'endpoint/problems/': '[%s]' % continue_reply(
                        '123', 'abc123')
                })
            client.session.get = lambda a: choose_reply(
                a, {
                    'endpoint/problems/?id=123':
                    '[%s]' % complete_no_answer_reply('123', 'abc123'),
                    'endpoint/problems/123/':
                    complete_reply('123', 'abc123')
                })
            solver = Solver(client, 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)
Ejemplo n.º 6
0
    def test_exponential_backoff_polling(self):
        "After each poll, back-off should double"

        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            # on submit, return status pending
            client.session.post = lambda path, _: choose_reply(path, {
                'endpoint/problems/': '[%s]' % continue_reply('123', 'abc123')
            })
            # on first and second status poll, return pending
            # on third status poll, return completed
            def continue_then_complete(path, state={'count': 0}):
                state['count'] += 1
                if state['count'] < 3:
                    return choose_reply(path, {
                        'endpoint/problems/?id=123': '[%s]' % continue_reply('123', 'abc123'),
                        'endpoint/problems/123/': continue_reply('123', 'abc123')
                    })
                else:
                    return choose_reply(path, {
                        'endpoint/problems/?id=123': '[%s]' % complete_no_answer_reply('123', 'abc123'),
                        'endpoint/problems/123/': complete_reply('123', 'abc123')
                    })

            client.session.get = continue_then_complete

            solver = Solver(client, solver_data('abc123'))

            future = solver.sample_qubo({})
            future.result()

            # after third poll, back-off interval should be 4 x initial back-off
            self.assertEqual(future._poll_backoff, Client._POLL_BACKOFF_MIN * 2**2)
Ejemplo n.º 7
0
    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 Client('endpoint', 'token') as client:
            client.session = mock.Mock()

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

            solver = Solver(client, 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 == 'endpoint/problems/':
                    self.assertEqual(event.body,
                                     '["{}"]'.format(submission_id))
                else:
                    self.assertEqual(
                        event.url,
                        'endpoint/problems/{}/'.format(submission_id))
Ejemplo n.º 8
0
 def test_solver_filtering_in_client(self):
     self.assertTrue(
         Client.is_solver_handled(
             Solver(None, json.loads(solver_object('test')))))
     self.assertFalse(
         Client.is_solver_handled(
             Solver(None, json.loads(solver_object('c4-sw_')))))
     self.assertFalse(None)
Ejemplo n.º 9
0
    def test_submit_continue_then_ok_and_error_reply(self):
        """Handle polling for the status of multiple problems."""

        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()

            # on first status poll, return pending for both problems
            # on second status poll, return error for first problem and complete for second
            def continue_then_complete(path, state={'count': 0}):
                state['count'] += 1
                if state['count'] < 2:
                    return choose_reply(path, {
                        'endpoint/problems/?id=1': '[{}]'.format(continue_reply('1', 'abc123')),
                        'endpoint/problems/?id=2': '[{}]'.format(continue_reply('2', 'abc123')),
                        'endpoint/problems/1/': continue_reply('1', 'abc123'),
                        'endpoint/problems/2/': continue_reply('2', 'abc123'),
                        'endpoint/problems/?id=1,2': '[{},{}]'.format(continue_reply('1', 'abc123'),
                                                                      continue_reply('2', 'abc123')),
                        'endpoint/problems/?id=2,1': '[{},{}]'.format(continue_reply('2', 'abc123'),
                                                                      continue_reply('1', 'abc123'))
                    })
                else:
                    return choose_reply(path, {
                        'endpoint/problems/?id=1': '[{}]'.format(error_reply('1', 'abc123', 'error')),
                        'endpoint/problems/?id=2': '[{}]'.format(complete_no_answer_reply('2', 'abc123')),
                        'endpoint/problems/1/': error_reply('1', 'abc123', 'error'),
                        'endpoint/problems/2/': complete_reply('2', 'abc123'),
                        'endpoint/problems/?id=1,2': '[{},{}]'.format(error_reply('1', 'abc123', 'error'),
                                                                      complete_no_answer_reply('2', 'abc123')),
                        'endpoint/problems/?id=2,1': '[{},{}]'.format(complete_no_answer_reply('2', 'abc123'),
                                                                      error_reply('1', 'abc123', 'error'))
                    })

            client.session.get = continue_then_complete

            def accept_problems_with_continue_reply(path, body, ids=iter('12')):
                problems = json.loads(body)
                return choose_reply(path, {
                    'endpoint/problems/': json.dumps(
                        [json.loads(continue_reply(next(ids), 'abc123')) for _ in problems])
                })

            client.session.post = accept_problems_with_continue_reply

            solver = Solver(client, solver_data('abc123'))

            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(SolverFailureError):
                self._check(results1, linear, quad, 100)
            self._check(results2, linear, quad, 100)
Ejemplo n.º 10
0
    def test_submit_null_reply(self):
        """Get an error when the server's response is incomplete."""
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(a, {'endpoint/problems/': ''})
            solver = Solver(client, 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
Ejemplo n.º 11
0
    def test_submit_cancel_reply(self):
        """Handle a response for a canceled job."""
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(a, {'endpoint/problems/': '[%s]' % cancel_reply('123', 'abc123')})
            solver = Solver(client, 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(CanceledFutureError):
                results.samples
Ejemplo n.º 12
0
    def test_submit_error_reply(self):
        """Handle an error on problem submission."""
        error_body = 'An error message'
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(a, {
                'endpoint/problems/': '[%s]' % error_reply('123', 'abc123', error_body)})
            solver = Solver(client, 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(SolverFailureError):
                results.samples
Ejemplo n.º 13
0
    def test_submit_continue_then_error_reply(self):
        """Handle polling for an error message."""
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(a, {'endpoint/problems/': '[%s]' % continue_reply('123', 'abc123')})
            client.session.get = lambda a: choose_reply(a, {
                'endpoint/problems/?id=123': '[%s]' % error_reply('123', 'abc123', "error message")})
            solver = Solver(client, 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(SolverFailureError):
                self._check(results, linear, quad, 100)
    def test_submit_immediate_error_reply(self):
        """Handle an (obvious) error on problem submission."""
        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda a, _: choose_reply(
                a, {
                    'endpoint/problems/':
                    '[%s]' % immediate_error_reply(
                        400, "Missing parameter 'num_reads' in problem JSON")
                })
            solver = Solver(client, solver_data('abc123'))

            linear, quad = generate_random_ising_problem(solver)
            results = solver.sample_ising(linear, quad)

            with self.assertRaises(SolverFailureError):
                results.samples
    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 Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.get = lambda a: choose_reply(
                a,
                {'endpoint/problems/?id={}'.format(submission_id): reply_body})

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

            client.session.post = post
            client.session.delete = DeleteEvent.handle

            solver = Solver(client, 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 == 'endpoint/problems/':
                    self.assertEqual(event.body,
                                     '["{}"]'.format(submission_id))
                else:
                    self.assertEqual(
                        event.url,
                        'endpoint/problems/{}/'.format(submission_id))
Ejemplo n.º 16
0
def get_solver():
    data = {
        "properties": {
            "supported_problem_types": ["qubo", "ising"],
            "qubits": [0, 1, 2, 3],
            "couplers": [(0, 1), (1, 2), (2, 3), (3, 0)],
            "num_qubits": 4,
            "parameters": {"num_reads": "Number of samples to return."}
        },
        "id": "test-solver",
        "description": "A test solver"
    }
    return Solver(client=None, data=data)
Ejemplo n.º 17
0
    def test_immediate_polling_without_eta_min(self):
        "First poll happens with minimal delay if eta_min missing"

        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.post = lambda path, _: choose_reply(path, {
                'endpoint/problems/': '[%s]' % continue_reply('1', 'abc123')
            })
            client.session.get = lambda path: choose_reply(path, {
                'endpoint/problems/?id=1': '[%s]' % complete_no_answer_reply('1', 'abc123'),
                'endpoint/problems/1/': complete_reply('1', 'abc123')
            })

            solver = Solver(client, solver_data('abc123'))

            def assert_no_delay(s):
                s and self.assertTrue(
                    abs(s - client._POLL_BACKOFF_MIN) < client._POLL_BACKOFF_MIN / 10.0)

            with mock.patch('time.sleep', assert_no_delay):
                future = solver.sample_qubo({})
                future.result()
Ejemplo n.º 18
0
    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 = Client._POLL_THREAD_COUNT
        Client._POLL_THREAD_COUNT = 1

        with Client('endpoint', 'token') as client:
            client.session = mock.Mock()
            client.session.get = lambda a: choose_reply(
                a,
                {
                    # Wait until both problems are
                    'endpoint/problems/?id=1':
                    '[%s]' % continue_reply('1', 'abc123'),
                    'endpoint/problems/?id=2':
                    '[%s]' % continue_reply('2', 'abc123'),
                    'endpoint/problems/?id=2,1':
                    '[' + complete_no_answer_reply('2', 'abc123') + ',' +
                    error_reply('1', 'abc123', 'error') + ']',
                    'endpoint/problems/?id=1,2':
                    '[' + error_reply('1', 'abc123', 'error') + ',' +
                    complete_no_answer_reply('2', 'abc123') + ']',
                    'endpoint/problems/1/':
                    error_reply('1', 'abc123', 'Error message'),
                    'endpoint/problems/2/':
                    complete_reply('2', 'abc123')
                })

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

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

            solver = Solver(client, 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(SolverFailureError):
                self._check(results1, linear, quad, 100)
            self._check(results2, linear, quad, 100)

        Client._POLL_THREAD_COUNT = old_value
Ejemplo n.º 19
0
def solver_object(id_, incomplete=False):
    return Solver(client=None, data=json.loads(solver_data(id_, incomplete)))