Пример #1
0
    def test_input_checking_vartype(self):
        """Check that exceptions get thrown for broken inputs"""

        # this biases values are themselves not important, so just choose them randomly
        linear = {v: random.uniform(-2, 2) for v in range(10)}
        quadratic = {(u, v): random.uniform(-1, 1)
                     for (u, v) in itertools.combinations(linear, 2)}
        offset = random.random()

        with self.assertRaises(TypeError):
            pm.BinaryQuadraticModel(linear, quadratic, offset, 147)

        with self.assertRaises(TypeError):
            pm.BinaryQuadraticModel(linear, quadratic, offset,
                                    'my made up type')

        self.assertEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset,
                                    pm.BINARY).vartype, pm.BINARY)

        self.assertEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset,
                                    {-1, 1}).vartype, pm.SPIN)

        self.assertEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset,
                                    'BINARY').vartype, pm.BINARY)
Пример #2
0
    def test_not_equal(self):
        # two equal models
        model0 = pm.BinaryQuadraticModel({
            0: 0,
            1: 0,
            2: 0,
            3: 0
        }, {
            (1, 2): -1,
            (0, 1): -1,
            (2, 3): -1,
            (0, 2): -1
        }, 0.0, pm.Vartype.SPIN)
        model1 = pm.BinaryQuadraticModel({
            0: 0,
            1: 0,
            2: 0,
            3: 0
        }, {
            (0, 1): -1,
            (1, 2): -1,
            (2, 3): -1,
            (0, 2): -1
        }, 0.0, pm.Vartype.SPIN)

        self.assertFalse(model0 != model1)
        self.assertTrue(model0 == model1)
Пример #3
0
    def test_bad_energy_range(self):
        graph = nx.path_graph(3)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)

        linear = {v: -3 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        with self.assertRaises(ValueError):
            widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        linear = {v: 0 for v in graph}
        quadratic = {edge: 5 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        with self.assertRaises(ValueError):
            widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)
Пример #4
0
    def test_relabel_forwards_and_backwards(self):
        graph = nx.path_graph(4)
        graph.add_edge(0, 2)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        # make another one
        graph = nx.path_graph(4)
        graph.add_edge(0, 2)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        original_widget = pm.PenaltyModel.from_specification(
            spec, model, 2., -2)

        new_label_sets = [(10, 1), ('a', 'b'), (1, 'b'), ('1', '2', '3', '4'),
                          ('a', 'b', 'c', 'd')]
        new_label_sets.extend(itertools.permutations(graph))

        for new in new_label_sets:
            mapping = dict(enumerate(new))
            inv_mapping = {u: v for v, u in mapping.items()}

            # apply then invert with copy=False
            widget.relabel_variables(mapping, copy=False)
            widget.relabel_variables(inv_mapping, copy=False)
            self.assertEqual(widget, original_widget)

            # apply then invert with copy=True
            copy_widget = widget.relabel_variables(mapping, copy=True)
            inv_copy = copy_widget.relabel_variables(inv_mapping, copy=True)
            self.assertEqual(inv_copy, original_widget)
Пример #5
0
    def test_construction(self):

        # build a specification
        graph = nx.complete_graph(10)
        decision_variables = (0, 4, 5)
        feasible_configurations = {(-1, -1, -1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)

        # build a model
        model = pm.BinaryQuadraticModel({v: 0
                                         for v in graph},
                                        {edge: 0
                                         for edge in graph.edges},
                                        0.0,
                                        vartype=pm.Vartype.SPIN)

        # build a PenaltyModel explicitly
        pm0 = pm.PenaltyModel(graph, decision_variables,
                              feasible_configurations, pm.SPIN, model, .1, 0)

        # build from spec
        pm1 = pm.PenaltyModel.from_specification(spec, model, .1, 0)

        # should result in equality
        self.assertEqual(pm0, pm1)
Пример #6
0
    def test_copy(self):
        linear = {0: .5, 1: 1.3}
        quadratic = {(0, 1): -.435}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        new_model = model.copy()

        # everything should have a new id
        self.assertNotEqual(id(model.linear), id(new_model.linear))
        self.assertNotEqual(id(model.quadratic), id(new_model.quadratic))
        self.assertNotEqual(id(model.adj), id(new_model.adj))

        for v in model.linear:
            self.assertNotEqual(id(model.adj[v]), id(new_model.adj[v]))

        # values should all be equal
        self.assertEqual(model.linear, new_model.linear)
        self.assertEqual(model.quadratic, new_model.quadratic)
        self.assertEqual(model.adj, new_model.adj)

        for v in model.linear:
            self.assertEqual(model.adj[v], new_model.adj[v])

        self.assertEqual(model, new_model)
Пример #7
0
    def test_penalty_model_insert_retrieve(self):
        conn = self.clean_connection

        graph = nx.path_graph(3)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph, decision_variables,
                                feasible_configurations, pm.SPIN)

        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)

        widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        with conn as cur:
            pmc.insert_penalty_model(cur, widget)

        with conn as cur:
            pms = list(pmc.iter_penalty_model_from_specification(cur, spec))

            self.assertEqual(len(pms), 1)
            widget_, = pms
            self.assertEqual(widget_, widget)
Пример #8
0
    def test__eq__quadratic_ordering(self):
        linear = {v: random.uniform(-2, 2) for v in range(11)}
        quadratic = {(u, v): random.uniform(-1, 1)
                     for (u, v) in itertools.combinations(linear, 2)}
        offset = random.random()
        vartype = pm.SPIN

        model0 = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        reversed_quadratic = {(v, u): bias
                              for (u, v), bias in quadratic.items()}

        model1 = pm.BinaryQuadraticModel(linear, reversed_quadratic, offset,
                                         vartype)

        self.assertEqual(model1, model0)
Пример #9
0
    def test_adj_construction_partial_quadratic(self):
        """bug was detected, test shows the exploration of causes and confirms that it was fixed"""
        linear = {
            0: 2.0,
            1: 0.0,
            2: 0.0,
            3: 2.0,
            4: 0.0,
            5: 0.0,
            6: 0.0,
            7: 0.0
        }
        quadratic = {(0, 3): -4.0}

        model = pm.BinaryQuadraticModel(linear, quadratic, -1.0,
                                        pm.Vartype.BINARY)

        # test that the model adj was created the way we expected
        for v in linear:
            self.assertIn(v, model.adj)

        for (u, v), bias in quadratic.items():
            self.assertIn(u, model.adj)
            self.assertIn(v, model.adj[u])
            self.assertEqual(model.adj[u][v], bias)

            v, u = u, v
            self.assertIn(u, model.adj)
            self.assertIn(v, model.adj[u])
            self.assertEqual(model.adj[u][v], bias)

        for u in model.adj:
            for v in model.adj[u]:
                self.assertTrue((u, v) in quadratic or (v, u) in quadratic)
Пример #10
0
    def test_construction_typical_binary(self):

        linear = {0: 1, 1: -1, 2: .5}
        quadratic = {(0, 1): .5, (1, 2): 1.5}
        offset = 1.4
        vartype = pm.BINARY
        m = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        self.assertEqual(linear, m.linear)
        self.assertEqual(quadratic, m.quadratic)
        self.assertEqual(offset, m.offset)

        for (u, v), bias in quadratic.items():
            self.assertIn(u, m.adj)
            self.assertIn(v, m.adj[u])
            self.assertEqual(m.adj[u][v], bias)

            v, u = u, v
            self.assertIn(u, m.adj)
            self.assertIn(v, m.adj[u])
            self.assertEqual(m.adj[u][v], bias)

        for u in m.adj:
            for v in m.adj[u]:
                self.assertTrue((u, v) in quadratic or (v, u) in quadratic)
Пример #11
0
    def test__eq__(self):
        linear = {v: random.uniform(-2, 2) for v in range(11)}
        quadratic = {(u, v): random.uniform(-1, 1)
                     for (u, v) in itertools.combinations(linear, 2)}
        offset = random.random()
        vartype = pm.SPIN

        self.assertEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset, vartype),
            pm.BinaryQuadraticModel(linear, quadratic, offset, vartype))

        # mismatched type
        self.assertNotEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset, vartype), -1)

        self.assertNotEqual(pm.BinaryQuadraticModel({}, {}, 0.0, pm.SPIN),
                            pm.BinaryQuadraticModel({}, {}, 0.0, pm.BINARY))
Пример #12
0
    def test_relabel_typical(self):
        linear = {0: .5, 1: 1.3}
        quadratic = {(0, 1): -.435}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        mapping = {0: 'a', 1: 'b'}
        newmodel = model.relabel_variables(mapping)

        # check that new model is the same as old model
        linear = {'a': .5, 'b': 1.3}
        quadratic = {('a', 'b'): -.435}
        offset = 1.2
        vartype = pm.SPIN
        testmodel = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        self.assertEqual(newmodel, testmodel)
Пример #13
0
    def test_change_vartype(self):
        linear = {0: 1, 1: -1, 2: .5}
        quadratic = {(0, 1): .5, (1, 2): 1.5}
        offset = 1.4
        vartype = pm.BINARY
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        # should not change
        new_model = model.change_vartype(pm.BINARY)
        self.assertEqual(model, new_model)
        self.assertNotEqual(id(model), id(new_model))

        # change vartype
        new_model = model.change_vartype(pm.SPIN)

        # check all of the energies
        for spins in itertools.product((-1, 1), repeat=len(linear)):
            spin_sample = {v: spins[v] for v in linear}
            binary_sample = {v: (spins[v] + 1) // 2 for v in linear}

            self.assertAlmostEqual(model.energy(binary_sample),
                                   new_model.energy(spin_sample))

        linear = {0: 1, 1: -1, 2: .5}
        quadratic = {(0, 1): .5, (1, 2): 1.5}
        offset = -1.4
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        # should not change
        new_model = model.change_vartype(pm.SPIN)
        self.assertEqual(model, new_model)
        self.assertNotEqual(id(model), id(new_model))

        # change vartype
        new_model = model.change_vartype(pm.BINARY)

        # check all of the energies
        for spins in itertools.product((-1, 1), repeat=len(linear)):
            spin_sample = {v: spins[v] for v in linear}
            binary_sample = {v: (spins[v] + 1) // 2 for v in linear}

            self.assertAlmostEqual(model.energy(spin_sample),
                                   new_model.energy(binary_sample))
Пример #14
0
    def test_relabel(self):
        graph = nx.path_graph(3)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        # now set up the same widget with 0 relabelled to 'a'
        graph = nx.path_graph(3)
        graph = nx.relabel_nodes(graph, {0: 'a'})
        decision_variables = ('a', 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        test_widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        # without copy
        new_widget = widget.relabel_variables({0: 'a'}, copy=True)
        self.assertEqual(test_widget, new_widget)
        self.assertEqual(new_widget.decision_variables, ('a', 2))

        widget.relabel_variables({0: 'a'}, copy=False)
        self.assertEqual(widget, test_widget)
        self.assertEqual(widget.decision_variables, ('a', 2))
Пример #15
0
    def test_input_checking_quadratic(self):
        linear = {v: random.uniform(-2, 2) for v in range(11)}
        quadratic = {(u, v): random.uniform(-1, 1)
                     for (u, v) in itertools.combinations(linear, 2)}
        offset = random.random()
        vartype = pm.SPIN

        self.assertEqual(
            pm.BinaryQuadraticModel(linear, quadratic, offset,
                                    pm.BINARY).quadratic, quadratic)

        # quadratic should be a dict
        with self.assertRaises(TypeError):
            pm.BinaryQuadraticModel(linear, [], offset, pm.BINARY)

        # unknown varialbe (vars must be in linear)
        with self.assertRaises(ValueError):
            pm.BinaryQuadraticModel(linear, {('a', 1): .5}, offset, pm.BINARY)

        # not 2-tuple
        with self.assertRaises(ValueError):
            pm.BinaryQuadraticModel(linear, {'edge': .5}, offset, pm.BINARY)

        # not upper triangular
        with self.assertRaises(ValueError):
            pm.BinaryQuadraticModel(linear, {
                (0, 1): .5,
                (1, 0): -.5
            }, offset, pm.BINARY)

        # no self-loops
        with self.assertRaises(ValueError):
            pm.BinaryQuadraticModel(linear, {(0, 0): .5}, offset, pm.BINARY)
Пример #16
0
    def test_relabel_typical_inplace(self):
        linear = {0: .5, 1: 1.3}
        quadratic = {(0, 1): -.435}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        mapping = {0: 'a', 1: 'b'}
        newmodel = model.relabel_variables(mapping, copy=False)
        self.assertEqual(id(model), id(newmodel))
        self.assertEqual(id(model.linear), id(newmodel.linear))
        self.assertEqual(id(model.quadratic), id(newmodel.quadratic))

        # check that model is the same as old model
        linear = {'a': .5, 'b': 1.3}
        quadratic = {('a', 'b'): -.435}
        offset = 1.2
        vartype = pm.SPIN
        testmodel = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)
        self.assertEqual(model, testmodel)

        self.assertEqual(model.adj, testmodel.adj)
Пример #17
0
    def test__repr__(self):
        """check that repr works correctly."""
        linear = {0: 1, 1: -1, 2: .5}
        quadratic = {(0, 1): .5, (1, 2): 1.5}
        offset = 1.4

        m = pm.BinaryQuadraticModel(linear, quadratic, offset, pm.SPIN)

        # should recreate the model
        from penaltymodel import BinaryQuadraticModel, Vartype
        m2 = eval(m.__repr__())

        self.assertEqual(m, m2)
Пример #18
0
    def test_as_qubo_binary_to_qubo(self):
        """Binary model's as_qubo method"""
        linear = {0: 0, 1: 0}
        quadratic = {(0, 1): 1}
        offset = 0.0
        vartype = pm.BINARY

        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        Q, off = model.as_qubo()

        self.assertEqual(off, offset)
        self.assertEqual({(0, 0): 0, (1, 1): 0, (0, 1): 1}, Q)
Пример #19
0
    def test_as_ising_spin_to_ising(self):
        linear = {0: 7.1, 1: 103}
        quadratic = {(0, 1): .97}
        offset = 0.3
        vartype = pm.SPIN

        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        h, J, off = model.as_ising()

        self.assertEqual(off, offset)
        self.assertEqual(linear, h)
        self.assertEqual(quadratic, J)
Пример #20
0
    def test_retrieval(self):
        # put some stuff in the database

        spec = pm.Specification(nx.path_graph(2), (0, 1), {(-1, -1), (1, 1)}, vartype=pm.SPIN)
        model = pm.BinaryQuadraticModel({0: 0, 1: 0}, {(0, 1): -1}, 0.0, vartype=pm.SPIN)
        widget = pm.PenaltyModel.from_specification(spec, model, 2, -1)

        for cache in pm.iter_caches():
            cache(widget)

        # now try to get it back
        new_widget = pm.get_penalty_model(spec)

        self.assertEqual(widget, new_widget)
Пример #21
0
    def test_relabel_with_identity(self):
        linear = {v: .1 * v for v in range(-5, 4)}
        quadratic = {(u, v): .1 * u * v
                     for u, v in itertools.combinations(linear, 2)}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)
        old_model = model.copy()

        identity_mapping = {v: v for v in linear}

        model.relabel_variables(identity_mapping, copy=False)

        # should have stayed the same
        self.assertEqual(old_model, model)
        self.assertEqual(old_model.adj, model.adj)
Пример #22
0
    def test_insert_retrieve(self):
        dbfile = self.database

        linear = {'1': 0.0, '0': -0.5, '3': 1.0, '2': -0.5}
        quadratic = {
            ('0', '3'): -1.0,
            ('1', '2'): 1.0,
            ('0', '2'): 0.5,
            ('1', '3'): 1.0
        }
        offset = 0.0
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        offset,
                                        vartype=pm.SPIN)

        graph = nx.Graph()
        graph.add_edges_from(quadratic)
        decision_variables = ('0', '2', '3')
        feasible_configurations = ((-1, -1, -1), (-1, 1, -1), (1, -1, -1),
                                   (1, 1, 1))
        spec = pm.Specification(graph, decision_variables,
                                feasible_configurations, pm.SPIN)

        classical_gap = 2
        ground = -2.5

        pmodel = pm.PenaltyModel.from_specification(spec, model, classical_gap,
                                                    ground)

        pmc.cache_penalty_model(pmodel, database=dbfile)

        # print(spec.feasible_configurations)
        # print(spec.decision_variables)

        # get it back
        ret_pmodel = pmc.get_penalty_model(spec, database=dbfile)

        # now get back one with a different decision_variables
        spec2 = pm.Specification(graph, ('3', '0', '2'),
                                 feasible_configurations, pm.SPIN)
        try:
            ret_pmodel = pmc.get_penalty_model(spec2, database=dbfile)
            self.assertNotEqual(ret_pmodel, pmodel)
        except:
            pass
Пример #23
0
    def test_arbitrary_labels_on_k44(self):
        dbfile = self.database

        graph = nx.Graph()
        for i in range(3):
            for j in range(3, 6):
                graph.add_edge(i, j)

        decision_variables = (0, 5)
        feasible_configurations = ((0, 0), (1, 1))  # equality

        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.BINARY)

        linear = {v: 0 for v in graph}
        quadratic = {edge: 0 for edge in graph.edges}
        if decision_variables in quadratic:
            quadratic[decision_variables] = -1
        else:
            u, v = decision_variables
            assert (v, u) in quadratic
            quadratic[(v, u)] = -1
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)

        # now cache the pmodel to make sure there is something to find

        for thingy in itertools.permutations(range(6)):
            mapping = dict(enumerate(thingy))
            pmodel = pmodel.relabel_variables(mapping, copy=True)
            pmc.cache_penalty_model(pmodel, database=dbfile)

        # now relabel some variables
        mapping = {1: '1', 2: '2', 3: '3', 4: '4'}

        new_spec = spec.relabel_variables(mapping)

        # retrieve from the new_spec
        # now try to retrieve it
        retreived_pmodel = pmc.get_penalty_model(new_spec, database=dbfile)
Пример #24
0
    def test_partial_relabel_inplace(self):
        linear = {v: .1 * v for v in range(-5, 5)}
        quadratic = {(u, v): .1 * u * v
                     for u, v in itertools.combinations(linear, 2)}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        newlinear = linear.copy()
        newlinear['a'] = newlinear[0]
        newlinear['b'] = newlinear[1]
        del newlinear[0]
        del newlinear[1]

        mapping = {0: 'a', 1: 'b'}  # partial mapping
        model.relabel_variables(mapping, copy=False)

        self.assertEqual(newlinear, model.linear)
Пример #25
0
    def test_to_networkx_graph(self):
        graph = nx.barbell_graph(7, 6)

        # build a BQM
        model = pm.BinaryQuadraticModel({v: -.1
                                         for v in graph},
                                        {edge: -.4
                                         for edge in graph.edges},
                                        1.3,
                                        vartype=pm.SPIN)

        # get the graph
        BQM = model.to_networkx_graph()

        self.assertEqual(set(graph), set(BQM))
        for u, v in graph.edges:
            self.assertIn(u, BQM[v])

        for v, bias in model.linear.items():
            self.assertEqual(bias, BQM.nodes[v]['bias'])
Пример #26
0
    def test_binary_specification(self):
        dbfile = self.database

        # set up a specification and a corresponding penaltymodel
        graph = nx.Graph()
        for i in 'abcd':
            for j in 'efgh':
                graph.add_edge(i, j)

        decision_variables = ('a', 'e')
        feasible_configurations = ((0, 0), (1, 1))  # equality

        spec = pm.Specification(graph,
                                decision_variables,
                                feasible_configurations,
                                vartype=pm.BINARY)

        linear = {v: 0 for v in graph}
        quadratic = {edge: 0 for edge in graph.edges}
        if decision_variables in quadratic:
            quadratic[decision_variables] = -1
        else:
            u, v = decision_variables
            assert (v, u) in quadratic
            quadratic[(v, u)] = -1
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)

        # now cache the pmodel to make sure there is something to find
        pmc.cache_penalty_model(pmodel, database=dbfile)

        # now try to retrieve it
        retreived_pmodel = pmc.get_penalty_model(spec, database=dbfile)

        self.assertIs(retreived_pmodel.model.vartype, pm.BINARY)

        # check that the specification is equal to the retreived_pmodel
        self.assertTrue(spec.__eq__(retreived_pmodel))
Пример #27
0
def get_penalty_model(specification):
    """Factory function for penaltymodel_maxgap.

    Args:
        specification (penaltymodel.Specification): The specification
            for the desired penalty model.

    Returns:
        :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.

    Raises:
        :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.

    Parameters:
        priority (int): -100

    """

    # check that the feasible_configurations are spin
    feasible_configurations = specification.feasible_configurations
    if specification.vartype is pm.BINARY:
        feasible_configurations = {
            tuple(2 * v - 1 for v in config): en
            for config, en in iteritems(feasible_configurations)
        }

    # convert ising_quadratic_ranges to the form we expect
    ising_quadratic_ranges = specification.ising_quadratic_ranges
    quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v]
                        for u, v in specification.graph.edges}

    linear, quadratic, ground, gap = generate_ising(
        specification.graph, feasible_configurations,
        specification.decision_variables, specification.ising_linear_ranges,
        quadratic_ranges, None)  # unspecified smt solver

    # set of the model with 0.0 offset
    model = pm.BinaryQuadraticModel(linear, quadratic, 0.0, pm.SPIN)

    return pm.PenaltyModel.from_specification(specification, model, gap,
                                              ground)
Пример #28
0
    def test_as_qubo_spin_to_qubo(self):
        """Spin model's as_qubo method"""
        linear = {0: .5, 1: 1.3}
        quadratic = {(0, 1): -.435}
        offset = 1.2
        vartype = pm.SPIN

        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        Q, off = model.as_qubo()

        for spins in itertools.product((-1, 1), repeat=len(model)):
            spin_sample = dict(zip(range(len(spins)), spins))
            bin_sample = {v: (s + 1) // 2 for v, s in spin_sample.items()}

            # calculate the qubo's energy
            energy = off
            for (u, v), bias in Q.items():
                energy += bin_sample[u] * bin_sample[v] * bias

            # and the energy of the model
            self.assertAlmostEqual(energy, model.energy(spin_sample))
Пример #29
0
    def test_relabel_with_overlap(self):
        linear = {v: .1 * v for v in range(-5, 4)}
        quadratic = {(u, v): .1 * u * v
                     for u, v in itertools.combinations(linear, 2)}
        offset = 1.2
        vartype = pm.SPIN
        model = pm.BinaryQuadraticModel(linear, quadratic, offset, vartype)

        partial_overlap_mapping = {
            v: -v
            for v in linear
        }  # has variables mapped to other old labels

        # construct a test model by using copy
        testmodel = model.relabel_variables(partial_overlap_mapping, copy=True)

        # now apply in place
        model.relabel_variables(partial_overlap_mapping, copy=False)

        # should have stayed the same
        self.assertEqual(testmodel, model)
        self.assertEqual(testmodel.adj, model.adj)
Пример #30
0
    def test_typical(self):
        dbfile = self.database

        # insert a penalty model
        graph = nx.path_graph(3)
        decision_variables = (0, 2)
        feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
        spec = pm.Specification(graph, decision_variables,
                                feasible_configurations, pm.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = pm.BinaryQuadraticModel(linear,
                                        quadratic,
                                        0.0,
                                        vartype=pm.SPIN)
        widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

        # cache the penaltymodel
        pmc.cache_penalty_model(widget, database=dbfile)

        # retrieve it
        widget_ = pmc.get_penalty_model(spec, database=dbfile)

        self.assertEqual(widget_, widget)