def test_upload_failure(self): """Submit should gracefully fail if upload as part of submit fails.""" # build a test problem bqm = dimod.BQM.from_ising({}, {'ab': 1}) # use a global mocked session, so we can modify it on-fly session = mock.Mock() # upload is now part of submit, so we need to mock it mock_upload_exc = ValueError('error') def mock_upload(self, bqm): return Present(exception=mock_upload_exc) # construct a functional solver by mocking client and api response data with mock.patch.object(Client, 'create_session', lambda self: session): with Client('endpoint', 'token') as client: with mock.patch.object(BaseUnstructuredSolver, 'upload_problem', mock_upload): solver = UnstructuredSolver(client, unstructured_solver_data()) # direct bqm sampling ss = dimod.ExactSolver().sample(bqm) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss)}) fut = solver.sample_bqm(bqm) with self.assertRaises(type(mock_upload_exc)): fut.result()
def test_many_upload_failures(self): """Failure handling in high concurrency mode works correctly.""" # build a test problem bqm = dimod.BQM.from_ising({}, {'ab': 1}) # use a global mocked session, so we can modify it on-fly session = mock.Mock() # upload is now part of submit, so we need to mock it mock_upload_exc = ValueError('error') def mock_upload(self, bqm): return Present(exception=mock_upload_exc) # construct a functional solver by mocking client and api response data with mock.patch.object(Client, 'create_session', lambda self: session): with Client('endpoint', 'token') as client: with mock.patch.object(UnstructuredSolver, 'upload_bqm', mock_upload): solver = UnstructuredSolver(client, unstructured_solver_data()) futs = [solver.sample_bqm(bqm) for _ in range(100)] for fut in futs: with self.assertRaises(type(mock_upload_exc)): fut.result()
def setUp(self): # mock client self.client = Client(endpoint='e', token='t', solver=dict(name__contains='test')) self.client._fetch_solvers = lambda **kw: self.solvers self.client._submit = lambda *pa, **kw: None self.client.upload_problem_encoded = lambda *pa, **kw: Present( result=mock_problem_id) # mock solvers self.structured_solver = StructuredSolver( client=self.client, data={ "properties": { "supported_problem_types": ["qubo", "ising"], "qubits": [0, 1, 2], "couplers": [[0, 1], [0, 2], [1, 2]], "num_qubits": 3, "num_reads_range": [0, 100], "parameters": { "num_reads": "Number of samples to return.", "postprocess": "either 'sampling' or 'optimization'" }, "topology": { "type": "chimera", "shape": [16, 16, 4] }, "category": "qpu", "tags": ["lower_noise"] }, "id": "test-qpu-solver", "description": "A test solver 1", "status": "online" }) self.unstructured_solver = UnstructuredSolver( client=self.client, data={ "properties": { "supported_problem_types": ["bqm"], "parameters": { "num_reads": "Number of samples to return." }, "category": "hybrid", }, "id": "test-unstructured-solver", "description": "A test unstructured solver" }) self.solvers = [self.structured_solver] # we can't use unstructured solvers without dimod installed, # so don't even try testing it if dimod: self.solvers.append(self.unstructured_solver) # reset all event handlers from dwave.cloud.events import _client_event_hooks_registry as reg reg.update({k: [] for k in reg})
def get_unstructured_solver(): data = { "properties": { "supported_problem_types": ["bqm"], "parameters": {"num_reads": "Number of samples to return."} }, "id": "test-unstructured-solver", "description": "A test unstructured solver" } return UnstructuredSolver(client=None, data=data)
def test_submit_immediate_reply(self): """Construction of and sampling from an unstructured solver works.""" # build a test problem bqm = dimod.BQM.from_ising({}, {'ab': 1}) # use a global mocked session, so we can modify it on-fly session = mock.Mock() # construct a functional solver by mocking client and api response data with mock.patch.object(Client, 'create_session', lambda self: session): with Client('endpoint', 'token') as client: solver = UnstructuredSolver(client, unstructured_solver_data()) # direct bqm sampling ss = dimod.ExactSolver().sample(bqm) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss)}) fut = solver.sample_bqm(bqm) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.occurrences, ss.record.num_occurrences) # ising sampling lin, quad, _ = bqm.to_ising() ss = dimod.ExactSolver().sample_ising(lin, quad) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss)}) fut = solver.sample_ising(lin, quad) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.occurrences, ss.record.num_occurrences) # qubo sampling qubo, _ = bqm.to_qubo() ss = dimod.ExactSolver().sample_qubo(qubo) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss)}) fut = solver.sample_qubo(qubo) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.occurrences, ss.record.num_occurrences)
def __init__(self, **kwargs): import dimod solver = UnstructuredSolver(client=None, data=hybrid_bqm_solver_data()) bqm = dimod.BQM.from_ising({}, {'ab': 1, 'bc': 1, 'ca': 1}) sampleset = dimod.ExactSolver().sample(bqm) kwargs.setdefault('solver', solver) kwargs.setdefault('problem', bqm) kwargs.setdefault('problem_type', 'bqm') kwargs.setdefault('answer', self._problem_answer(sampleset)) super().__init__(**kwargs) # unstructured problem specific self.problem_data_id = str( uuid.uuid4()) # mock `self.problem` uploaded
def test_sample_bqm_immediate_reply(self): """Construction of and sampling from an unstructured BQM solver works.""" # build a test problem bqm = dimod.BQM.from_ising({}, {'ab': 1}) # use a global mocked session, so we can modify it on-fly session = mock.Mock() # upload is now part of submit, so we need to mock it mock_problem_id = 'mock-problem-id' def mock_upload(self, bqm): return Present(result=mock_problem_id) # construct a functional solver by mocking client and api response data with mock.patch.multiple(Client, create_session=lambda self: session, upload_problem_encoded=mock_upload): with Client('endpoint', 'token') as client: solver = BQMSolver(client, unstructured_solver_data()) # make sure this still works _ = UnstructuredSolver(client, unstructured_solver_data()) # direct bqm sampling ss = dimod.ExactSolver().sample(bqm) ss.info.update(problem_id=mock_problem_id) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss, id_=mock_problem_id)}) fut = solver.sample_bqm(bqm) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.num_occurrences, ss.record.num_occurrences) # submit of pre-uploaded bqm problem fut = solver.sample_bqm(mock_problem_id) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.num_occurrences, ss.record.num_occurrences) # ising sampling lin, quad, _ = bqm.to_ising() ss = dimod.ExactSolver().sample_ising(lin, quad) ss.info.update(problem_id=mock_problem_id) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss, id_=mock_problem_id)}) fut = solver.sample_ising(lin, quad) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.num_occurrences, ss.record.num_occurrences) # qubo sampling qubo, _ = bqm.to_qubo() ss = dimod.ExactSolver().sample_qubo(qubo) ss.info.update(problem_id=mock_problem_id) session.post = lambda path, _: choose_reply( path, {'problems/': complete_reply(ss, id_=mock_problem_id)}) fut = solver.sample_qubo(qubo) numpy.testing.assert_array_equal(fut.sampleset, ss) numpy.testing.assert_array_equal(fut.samples, ss.record.sample) numpy.testing.assert_array_equal(fut.energies, ss.record.energy) numpy.testing.assert_array_equal(fut.num_occurrences, ss.record.num_occurrences)
def setUp(self): # mock solvers self.qpu1 = StructuredSolver( client=None, data={ "properties": { "supported_problem_types": ["qubo", "ising"], "qubits": [0, 1, 2], "couplers": [[0, 1], [0, 2], [1, 2]], "num_qubits": 3, "num_reads_range": [0, 100], "parameters": { "num_reads": "Number of samples to return.", "postprocess": "either 'sampling' or 'optimization'" }, "topology": { "type": "chimera", "shape": [16, 16, 4] }, "category": "qpu", "tags": ["lower_noise"] }, "id": "qpu1", "description": "QPU Chimera solver", "status": "online", "avg_load": 0.1 }) self.qpu2 = StructuredSolver( client=None, data={ "properties": { "supported_problem_types": ["qubo", "ising"], "qubits": [0, 1, 2, 3, 4], "couplers": [[0, 1], [0, 2], [1, 2], [2, 3], [3, 4]], "num_qubits": 5, "num_reads_range": [0, 200], "parameters": { "num_reads": "Number of samples to return.", "flux_biases": "Supported ...", "anneal_schedule": "Supported ..." }, "topology": { "type": "pegasus", "shape": [6, 6, 12] }, "category": "qpu", "vfyc": True }, "id": "qpu2", "description": "QPU Pegasus solver", "avg_load": 0.2 }) self.software = StructuredSolver( client=None, data={ "properties": { "supported_problem_types": ["qubo", "ising"], "qubits": [0, 1], "couplers": [[0, 1]], "num_qubits": 7, "num_reads_range": [0, 1000], "parameters": { "num_reads": "Number of samples to return." }, "vfyc": False, "topology": { "type": "chimera", "shape": [4, 4, 4] }, "category": "software", # the following are only present in this solver "some_set": [1, 2], "some_range": [1, 2], "some_string": "x", "tags": ["tag"] }, "id": "sw_solver1", "description": "Software solver", "avg_load": 0.7 }) self.hybrid = UnstructuredSolver(client=None, data={ "properties": { "supported_problem_types": ["bqm"], "maximum_number_of_variables": 10000, "maximum_time_limit_hrs": 24.0, "minimum_time_limit": [[1, 3.0], [1024, 3.0], [4096, 10.0], [10000, 40.0]], "quota_conversion_rate": 20, "parameters": { "time_limit": "" }, "category": "hybrid", }, "id": "hybrid_v1", "description": "Hybrid solver" }) self.qpu_solvers = [self.qpu1, self.qpu2] self.software_solvers = [self.software] self.hybrid_solvers = [self.hybrid] self.structured_solvers = self.qpu_solvers + self.software_solvers self.unstructured_solvers = self.hybrid_solvers self.solvers = self.structured_solvers + self.unstructured_solvers # mock client self.client = Client('endpoint', 'token') self.client._fetch_solvers = lambda **kw: self.solvers
from_bqm_sampleset, from_objects, _validated_embedding) rec = vcr.VCR( serializer='yaml', cassette_library_dir='tests/fixtures/cassettes', record_mode='none', match_on=['uri', 'method'], filter_headers=['x-auth-token'], ) # minimal mock of an unstructured solver unstructured_solver_mock = UnstructuredSolver( client=None, data={ 'id': 'mock', 'properties': { 'supported_problem_types': ['bqm'] } }) # we can use a fake token because outbound requests are intercepted anyway BrickedClient = partial(Client, token='fake') @mock.patch('dwave.system.samplers.dwave_sampler.Client.from_config', BrickedClient) class TestAdapters(unittest.TestCase): @rec.use_cassette('triangle-ising.yaml') def setUp(self): with BrickedClient() as client: self.solver = client.get_solver(qpu=True)