def test_self_loop_repeat2(self):
        num_variables = 4
        cases = [4, 3, 3, 5]
        dqm = dimod.DiscreteQuadraticModel()
        for i in range(num_variables):
            dqm.add_variable(cases[i], i)

        expression1 = [(0, 0, 2)]
        expression2 = [(0, 0, 2)]
        expression = expression1 + expression2
        lagrange_multiplier = 6
        constant = 4
        dqm.add_linear_equality_constraint(
            expression,
            lagrange_multiplier=lagrange_multiplier,
            constant=constant)

        expression_dict1 = {v: (c, b) for v, c, b in expression1}
        expression_dict2 = {v: (c, b) for v, c, b in expression2}

        for case_values in itertools.product(*(range(c) for c in cases)):
            state = {i: case_values[i] for i in range(num_variables)}
            s = constant
            for v, cv, bias in expression1:
                if expression_dict1[v][0] == state[v]:
                    s += bias
            for v, cv, bias in expression2:
                if expression_dict2[v][0] == state[v]:
                    s += bias
            self.assertEqual(dqm.energy(state), lagrange_multiplier * s ** 2)
def gnp_random_dqm(num_variables, num_cases, p, p_case, seed=None):
    rng = np.random.default_rng(seed)

    dqm = dimod.DiscreteQuadraticModel()

    if isinstance(num_cases, numbers.Integral):
        num_cases = np.full(num_variables, fill_value=num_cases)
    else:
        num_cases = np.asarray(num_cases)
        if num_cases.shape[0] != num_variables:
            raise ValueError

    for nc in num_cases:
        v = dqm.add_variable(nc)
        dqm.set_linear(v, rng.uniform(size=dqm.num_cases(v)))

    for u, v in itertools.combinations(range(num_variables), 2):
        if rng.uniform() < p:
            size = (dqm.num_cases(u), dqm.num_cases(v))

            r = rng.uniform(size=size)
            r[rng.binomial(1, 1-p_case, size=size) == 1] = 0

            dqm.set_quadratic(u, v, r)

    return dqm
Exemple #3
0
    def test_empty(self):
        dqm = dimod.DiscreteQuadraticModel()

        cqm = CQM.from_discrete_quadratic_model(dqm)

        self.assertEqual(len(cqm.variables), 0)
        self.assertEqual(len(cqm.constraints), 0)
Exemple #4
0
    def test_kwargs(self):
        bqm = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)
        with self.assertWarns(SamplerUnknownArgWarning):
            sampleset = dimod.ExactSolver().sample(bqm, a=1, b="abc")

        dqm = dimod.DiscreteQuadraticModel()
        with self.assertWarns(SamplerUnknownArgWarning):
            sampleset = dimod.ExactDQMSolver().sample_dqm(dqm, a=1, b="abc")
    def test_self_loop3(self):

        dqm1 = dimod.DiscreteQuadraticModel()
        dqm2 = dimod.DiscreteQuadraticModel()

        dqm1.add_variable(5)
        dqm2.add_variable(5)

        lagrange_multiplier = 1
        constant = 0
        dqm1.add_linear_equality_constraint(
            [(0, 0, 1), (0, 0, 2)],
            lagrange_multiplier=lagrange_multiplier,
            constant=constant)

        dqm2.add_linear_equality_constraint(
            [(0, 0, 3)],
            lagrange_multiplier=lagrange_multiplier,
            constant=constant)

        np.testing.assert_array_equal(dqm1.get_linear(0), dqm2.get_linear(0))
    def test_dqm(self):
        dqm = dimod.DiscreteQuadraticModel()
        dqm.add_variable(5, 'a')
        dqm.add_variable(6, 'b')
        dqm.set_quadratic_case('a', 0, 'b', 5, 1.5)

        new = load(dqm.to_file())

        self.assertEqual(dqm.num_variables(), new.num_variables())
        self.assertEqual(dqm.num_cases(), new.num_cases())
        self.assertEqual(dqm.get_quadratic_case('a', 0, 'b', 5),
                         new.get_quadratic_case('a', 0, 'b', 5))
Exemple #7
0
    def test_782(self):
        # https://github.com/dwavesystems/dimod/issues/782
        rng = np.random.default_rng(782)

        dqm1 = dimod.DiscreteQuadraticModel()
        x = {}
        for i in range(10):
            x[i] = dqm1.add_variable(5)
        for c in range(5):
            dqm1.add_linear_equality_constraint(
                ((x[i], c, rng.normal()) for i in range(10)),
                lagrange_multiplier=1.0,
                constant=-1.0)
        dqm2 = dqm1.copy()

        state = {v: rng.integers(0, dqm1.num_cases(v)) for v in dqm1.variables}

        self.assertEqual(dqm1.energy(state), dqm2.energy(state))
 def test_bug(self):
     # https://github.com/dwavesystems/dimod/issues/730
     # this is technically an internal attribute, but none-the-less has
     # surprising behavior
     dqm = dimod.DiscreteQuadraticModel()
     dqm.to_file()._file.read()
Exemple #9
0
    def test_sample_DISCRETE_empty(self):
        dqm = dimod.DiscreteQuadraticModel()
        response = dimod.ExactDQMSolver().sample_dqm(dqm)

        self.assertEqual(response.record.sample.shape, (0, 0))
        self.assertIs(response.vartype, dimod.DISCRETE)
def create_dqm(G1, G2):
    """Construct DQM based on two graphs
    
    Create discrete quadratic model to represent the problem of
    finding an isomorphism between the two graphs
    
    Args:
        G1 (networkx.Graph)
        G2 (networkx.Graph)
    
    Returns:
        DiscreteQuadraticModel
    """
    n = G1.number_of_nodes()
    if n != G2.number_of_nodes():
        raise ValueError

    G1_nodes = list(G1.nodes)
    G2_nodes = list(G2.nodes)

    dqm = dimod.DiscreteQuadraticModel()
    for node in G1.nodes:
        # Discrete variable for node i in graph G1, with cases
        # representing the nodes in graph G2
        dqm.add_variable(n, node)

    # Set up the coefficients associated with the constraints that
    # each node in G2 is chosen once.  This represents the H_A
    # component of the energy function.

    for node in G1.nodes:
        dqm.set_linear(node, np.repeat(-1.0, n))
    for itarget in range(n):
        for ivar, node1 in enumerate(G1_nodes):
            for node2 in G1_nodes[ivar + 1:]:
                dqm.set_quadratic_case(node1, itarget, node2, itarget, 2.0)

    # Set up the coefficients associated with the constraints that
    # selected edges must appear in both graphs, which is the H_B
    # component of the energy function.  The penalty coefficient B
    # controls the weight of H_B relative to H_A in the energy
    # function.  The value was selected by trial and error using
    # simple test problems.
    B = 2.0

    # For all edges in G1, penalizes mappings to edges not in G2
    for e1 in G1.edges:
        for e2_indices in itertools.combinations(range(n), 2):
            e2 = (G2_nodes[e2_indices[0]], G2_nodes[e2_indices[1]])
            if e2 in G2.edges:
                continue
            # In the DQM, the discrete variables represent nodes in
            # the first graph and are named according to the node
            # names.  The cases for each discrete variable represent
            # nodes in the second graph and are indices from 0..n-1
            dqm.set_quadratic_case(e1[0], e2_indices[0], e1[1], e2_indices[1],
                                   B)
            dqm.set_quadratic_case(e1[0], e2_indices[1], e1[1], e2_indices[0],
                                   B)

    # For all edges in G2, penalizes mappings to edges not in G1
    for e2 in G2.edges:
        e2_indices = (G2_nodes.index(e2[0]), G2_nodes.index(e2[1]))
        for e1 in itertools.combinations(G1.nodes, 2):
            if e1 in G1.edges:
                continue
            dqm.set_quadratic_case(e1[0], e2_indices[0], e1[1], e2_indices[1],
                                   B)
            dqm.set_quadratic_case(e1[0], e2_indices[1], e1[1], e2_indices[0],
                                   B)

    return dqm
Exemple #11
0
from dimod import DiscreteQuadraticModel
from dwave.system import LeapHybridDQMSampler

# Set up the map coloring example - the provinces and borders
provinces = ["AB", "BC", "ON", "MB", "NB", "NL", "NS", "NT", "NU", "PE", "QU", "SK", "YT"]
borders = [("BC", "AB"), ("BC", "NT"), ("BC", "YT"), ("AB", "SK"),
           ("AB", "NT"), ("SK", "MB"), ("SK", "NT"), ("MB", "ON"),
           ("MB", "NU"), ("ON", "QU"), ("QU", "NB"), ("QU", "NL"),
           ("NB", "NS"), ("YT", "NT"), ("NT", "NU")]

# input: number of colors in the graph
n_colors = 4
colors = np.linspace(0, n_colors - 1, n_colors)

# Initialize the DQM object
dqm = dimod.DiscreteQuadraticModel()

# Load the DQM. Define the variables, and then set quadratic weights.
# No biases necessary because we don't care what the colors are, as long as
# they are different at the borders.
for p in provinces:
    dqm.add_variable(4, label=p)
for p0, p1 in borders:
    dqm.set_quadratic(p0, p1, {(c, c): 1 for c in colors})

# Initialize the DQM solver
sampler = LeapHybridDQMSampler()

# Solve the problem using the DQM solver
sampleset = sampler.sample_dqm(dqm, label='Example - Map Coloring')