def test_embed_bqm(self):
        #octahedron
        g = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0),
             (0, 2), (1, 3), (2, 4), (3, 5), (4, 0), (5, 1)]
        emb = {'a': (1, 2), 'b': (3, 4), 'c': (5, 0)}
        emb_s = dwave.embedding.EmbeddedStructure(g, emb)
        chain_strength = {'a': 10, 'b': 20, 'c': 30}
        linear = {'a': -1, 'b': -2, 'c': -3}
        quadratic = {('a', 'b'): 1, ('a', 'c'): -1, ('b', 'c'): 2}
        source_bqm = dimod.BQM(linear, quadratic, 5, dimod.SPIN)

        goal_linear = {0: -3/2, 1: -1/2, 2: -1/2, 3: -1, 4: -1, 5: -3/2}
        goal_quadratic = {
            (0, 5): -30, (1, 2): -10, (3, 4): -20, #chain edges
            (1, 3): 1/3, (2, 3): 1/3, (2, 4): 1/3, #a-b
            (0, 1): -1/3, (0, 2): -1/3, (1, 5): -1/3, #a-c
            (3, 5): 2/3, (4, 5): 2/3, (4, 0): 2/3, #b-c
        }
        goal_offset = 5 + 10 + 20 + 30
        goal_bqm = dimod.BQM(goal_linear, goal_quadratic, goal_offset, dimod.SPIN)

        target_bqm = emb_s.embed_bqm(source_bqm, chain_strength=chain_strength)

        dimod.testing.assert_bqm_almost_equal(target_bqm, goal_bqm)

        #test the chain_strength is a function case:
        def strength_func(S, E):
            return chain_strength

        target_bqm = emb_s.embed_bqm(source_bqm, chain_strength=strength_func)

        dimod.testing.assert_bqm_almost_equal(target_bqm, goal_bqm)
예제 #2
0
    def test_valid_bqm_graph(self):
        class Dummy(dimod.Structured):
            @property
            def nodelist(self):
                return list(range(5))

            @property
            def edgelist(self):
                return [(0, 1), (1, 2), (2, 3)]

        valid_structure_bqm = dimod.BQM({
            0: 0,
            1: 1,
            2: 2,
            3: 3,
            4: 4
        }, {
            (0, 1): 1,
            (1, 2): 1,
            (2, 3): 1
        }, 0.0, dimod.BINARY)

        # Invalid due to extra variable '5' not present in nodelist/edgelist of dummy sampler.
        invalid_structure_bqm = dimod.BQM({
            1: 1,
            2: 2,
            5: 5
        }, {(1, 2): 1}, 0.0, dimod.BINARY)

        dummy = Dummy()

        self.assertTrue(dummy.valid_bqm_graph(valid_structure_bqm))
        self.assertFalse(dummy.valid_bqm_graph(invalid_structure_bqm))
예제 #3
0
    def test_large(self):
        # submit large CQMs of binary, spin, integer and mixed
        num_variables = 5000

        objectives = dict()

        objectives['binary'] = dimod.BQM(num_variables, 'BINARY')
        objectives['spin'] = dimod.BQM(num_variables, 'SPIN')

        objectives['integer'] = integer = dimod.QM()
        integer.add_variables_from('INTEGER', range(num_variables))

        objectives['mixed'] = mixed = dimod.QM()
        mixed.add_variables_from('INTEGER', range(num_variables // 3))
        mixed.add_variables_from(
            'SPIN', range(mixed.num_variables, mixed.num_variables + (num_variables // 3)))
        mixed.add_variables_from('BINARY', range(mixed.num_variables, num_variables))

        for vartype, model in objectives.items():
            with self.subTest(f"one constraint, vartype={vartype}"):
                cqm = dimod.ConstrainedQuadraticModel()
                cqm.set_objective(model)
                cqm.add_constraint(model, rhs=1, sense='==')
                sampleset = sampler.sample_cqm(cqm)
                self.assertConsistent(cqm, sampleset)

            with self.subTest(f"no constraints, vartype={vartype}"):
                cqm = dimod.ConstrainedQuadraticModel()
                cqm.set_objective(model)
                sampleset = sampler.sample_cqm(cqm)
                self.assertConsistent(cqm, sampleset)
예제 #4
0
    def test_small(self):
        # submit 3-variable CQMs of binary, spin, integer and mixed
        objectives = dict()

        objectives['binary'] = dimod.BQM({'a': 1, 'b': 1, 'c': 1}, {}, 0, 'BINARY')
        objectives['spin'] = dimod.BQM({'a': 1, 'b': 1, 'c': 1}, {}, 0, 'SPIN')

        objectives['integer'] = integer = dimod.QM()
        integer.add_variables_from('INTEGER', 'abc')

        objectives['mixed'] = mixed = dimod.QM()
        mixed.add_variable('BINARY', 'a')
        mixed.add_variable('SPIN', 'b')
        mixed.add_variable('INTEGER', 'c')

        for vartype, model in objectives.items():
            with self.subTest(f"one constraint, vartype={vartype}"):
                cqm = dimod.ConstrainedQuadraticModel()
                cqm.set_objective(model)
                cqm.add_constraint(model, rhs=1, sense='==')
                sampleset = sampler.sample_cqm(cqm)
                self.assertConsistent(cqm, sampleset)

            with self.subTest(f"no constraints, vartype={vartype}"):
                cqm = dimod.ConstrainedQuadraticModel()
                cqm.set_objective(model)
                sampleset = sampler.sample_cqm(cqm)
                self.assertConsistent(cqm, sampleset)
예제 #5
0
 def sample_bqm(self, sapi_problem_id, time_limit):
     #Workaround until TabuSampler supports C BQMs
     bqm = dimod.BQM(sapi_problem_id.linear, sapi_problem_id.quadratic,
                     sapi_problem_id.offset, sapi_problem_id.vartype)
     result = TabuSampler().sample(bqm, timeout=1000 * int(time_limit))
     future = dwave.cloud.computation.Future('fake_solver', None)
     future._result = {'sampleset': result, 'problem_type': 'bqm'}
     return future
예제 #6
0
 def test_new_bqm(self):
     bqm = dimod.BQM({'a': 1}, {'ab': 3}, 6, 'SPIN')
     with self.assertWarns(DeprecationWarning):
         new = dimod.AdjDictBQM(bqm)
     self.assertEqual(bqm.linear, new.linear)
     self.assertEqual(bqm.quadratic, new.quadratic)
     self.assertEqual(bqm.offset, new.offset)
     self.assertEqual(bqm.vartype, new.vartype)
예제 #7
0
 def construct_null_bqm(self):
     bqm_vars = set(self.bqm.variables)
     qpu_vars = set(self.tiling_composite.child.properties['qubits'])
     self.null_bqm.update(
         dimod.BQM(linear={v: 0
                           for v in qpu_vars.difference(bqm_vars)},
                   quadratic={},
                   offset=0,
                   vartype=dimod.SPIN))
    def test_bqm(self):
        graph = nx.barbell_graph(17, 8)

        bqm = dimod.BQM(vartype=dimod.SPIN)

        bqm.add_interactions_from((u, v, 1) for u, v in graph.edges())

        edgelist = dwave.embedding.utils.adjacency_to_edges(bqm)

        edges0 = sorted(map(sorted, graph.edges()))
        edges1 = sorted(map(sorted, edgelist))

        self.assertEqual(edges0, edges1)
예제 #9
0
def _build_bqm(H, y, lam):
    """Build BQM.

    Args:
        H (array):
            2D array of weak classifier predictions.  Each row is a
            sample point, each column is a classifier.
        y (array):
            Outputs
        lam (float):
            Coefficient that controls strength of regularization term
            (larger values encourage decreased model complexity).
    """
    n_samples = np.size(H, 0)
    n_classifiers = np.size(H, 1)

    # samples_factor is a factor that appears in front of the squared
    # loss term in the objective.  In theory, it does not affect the
    # problem solution, but it does affect the relative weighting of
    # the loss and regularization terms, which is otherwise absorbed
    # into the lambda parameter.

    # Using an average seems to be more intuitive, otherwise, lambda
    # is sample-size dependent.
    samples_factor = 1.0 / n_samples

    bqm = dimod.BQM('BINARY')
    bqm.offset = samples_factor * n_samples

    for i in range(n_classifiers):
        # Note: the last term with h_i^2 is part of the first term in
        # Eq. (12) of Neven et al. (2008), where i=j.
        bqm.add_variable(
            i, lam - 2.0 * samples_factor * np.dot(H[:, i], y) +
            samples_factor * np.dot(H[:, i], H[:, i]))

    for i in range(n_classifiers):
        for j in range(i + 1, n_classifiers):
            # Relative to Eq. (12) from Neven et al. (2008), the
            # factor of 2 appears here because each term appears twice
            # in a sum over all i,j.
            bqm.add_interaction(
                i, j, 2.0 * samples_factor * np.dot(H[:, i], H[:, j]))

    return bqm
예제 #10
0
    def test_warnings_chain_strength_dict(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        linear = {'a': -1, 'b': -2, 'c': -3}
        quadratic = {('a', 'b'): 1, ('a', 'c'): -1, ('b', 'c'): 2}
        bqm = dimod.BQM(linear, quadratic, 0, dimod.SPIN)

        chain_strength = {'a': 10, 'b': 20, 'c': 1.5}   
        ss = sampler.sample(bqm, chain_strength=chain_strength, warnings='SAVE')

        self.assertIn('warnings', ss.info)
        self.assertEqual(len(ss.info['warnings']), 1)

        warning = ss.info['warnings'][0]
        self.assertEqual(warning['type'], ChainStrengthWarning)

        interactions = warning['data']['source_interactions']
        self.assertEqual(len(interactions), 1)
        self.assertCountEqual(interactions[0], ('b','c'))
예제 #11
0
 def _update_bqm(self, old_bqm, beta_nudge):
     linear = {u: beta_nudge * bias for u, bias in old_bqm.linear.items()}
     quadratic = {(u, v): beta_nudge * bias
                  for (u, v), bias in old_bqm.quadratic.items()}
     return dimod.BQM(linear, quadratic, offset=0, vartype=dimod.SPIN)
예제 #12
0
# Represent the graph problem as a binary quadratic model
import dimod
import networkx as nx
import random
import hybrid

graph = nx.barabasi_albert_graph(100, 3, seed=1)  # Build a quasi-random graph
# Set node and edge values for the problem
h = {v: 0.0 for v in graph.nodes}
J = {edge: random.choice([-1, 1]) for edge in graph.edges}
bqm = dimod.BQM(h, J, offset=0, vartype=dimod.SPIN)

#Set a workflow of tabu search in parallel to submissions to a D-Wave system

workflow = hybrid.Loop(hybrid.RacingBranches(
    hybrid.InterruptableTabuSampler(),
    hybrid.EnergyImpactDecomposer(size=30, rolling=True, rolling_history=0.75)
    | hybrid.QPUSubproblemAutoEmbeddingSampler()
    | hybrid.SplatComposer()) | hybrid.ArgMin(),
                       convergence=3)

# Convert to dimod sampler and run workflow
result = hybrid.HybridSampler(workflow).sample(bqm)

print("Solution: sample={}".format(result.first))  # doctest: +SKIP
예제 #13
0
 def test_other_quadratic_model(self):
     with self.assertRaises(TypeError):
         sampler.sample_cqm(dimod.BQM('SPIN'))