Python networkx.path_graph() Examples

The following are 30 code examples of networkx.path_graph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_cover.py    From dwave_networkx with Apache License 2.0 6 votes vote down vote up
def test_vertex_cover_weighted(self):
        weight = 'weight'
        G = nx.path_graph(6)

        # favor even nodes
        nx.set_node_attributes(G, {node: node % 2 + 1 for node in G}, weight)
        cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
        self.assertEqual(set(cover), {0, 2, 4})

        # favor odd nodes
        nx.set_node_attributes(G, {node: (node + 1) % 2 + 1 for node in G}, weight)
        cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
        self.assertEqual(set(cover), {1, 3, 5})

        # make nodes 1 and 4 unlikely
        nx.set_node_attributes(G, {0: 1, 1: 3, 2: 1, 3: 1, 4: 3, 5: 1}, weight)
        cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
        self.assertEqual(set(cover), {0, 2, 3, 5})

        for __ in range(10):
            G = nx.gnp_random_graph(5, .5)
            nx.set_node_attributes(G, {node: random.random() for node in G}, weight)
            cover = dnx.min_weighted_vertex_cover(G, weight, ExactSolver())
            self.vertex_cover_check(G, cover) 
Example #2
Source File: test_propagate.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_prop_nodes_topo():
    # bi-directional chain
    g = dgl.DGLGraph(nx.path_graph(5))
    g = dgl.graph(g.edges())
    assert U.check_fail(dgl.prop_nodes_topo, g)  # has loop

    # tree
    tree = dgl.DGLGraph()
    tree.add_nodes(5)
    tree.add_edge(1, 0)
    tree.add_edge(2, 0)
    tree.add_edge(3, 2)
    tree.add_edge(4, 2)
    tree = dgl.graph(tree.edges())
    # init node feature data
    tree.ndata['x'] = F.zeros((5, 2))
    # set all leaf nodes to be ones
    tree.nodes[[1, 3, 4]].data['x'] = F.ones((3, 2))
    dgl.prop_nodes_topo(tree, message_func=mfunc, reduce_func=rfunc, apply_node_func=None)
    # root node get the sum
    assert F.allclose(tree.nodes[0].data['x'], F.tensor([[3., 3.]])) 
Example #3
Source File: test_udf.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_node_batch():
    g = dgl.DGLGraph(nx.path_graph(20))
    feat = F.randn((g.number_of_nodes(), 10))
    g.ndata['x'] = feat

    # test all
    v = utils.toindex(slice(0, g.number_of_nodes()))
    n_repr = g.get_n_repr(v)
    nbatch = NodeBatch(v, n_repr)
    assert F.allclose(nbatch.data['x'], feat)
    assert nbatch.mailbox is None
    assert F.allclose(nbatch.nodes(), g.nodes())
    assert nbatch.batch_size() == g.number_of_nodes()
    assert len(nbatch) == g.number_of_nodes()

    # test partial
    v = utils.toindex(F.tensor([0, 3, 5, 7, 9]))
    n_repr = g.get_n_repr(v)
    nbatch = NodeBatch(v, n_repr)
    assert F.allclose(nbatch.data['x'], F.gather_row(feat, F.tensor([0, 3, 5, 7, 9])))
    assert nbatch.mailbox is None
    assert F.allclose(nbatch.nodes(), F.tensor([0, 3, 5, 7, 9]))
    assert nbatch.batch_size() == 5
    assert len(nbatch) == 5 
Example #4
Source File: test_readout.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_broadcast_edges():
    # test#1: basic
    g0 = dgl.DGLGraph(nx.path_graph(10))
    feat0 = F.randn((1, 40))
    ground_truth = F.stack([feat0] * g0.number_of_edges(), 0)
    assert F.allclose(dgl.broadcast_edges(g0, feat0), ground_truth)

    # test#2: batched graph
    g1 = dgl.DGLGraph(nx.path_graph(3))
    g2 = dgl.DGLGraph()
    g3 = dgl.DGLGraph(nx.path_graph(12))
    bg = dgl.batch([g0, g1, g2, g3])
    feat1 = F.randn((1, 40))
    feat2 = F.randn((1, 40))
    feat3 = F.randn((1, 40))
    ground_truth = F.cat(
        [feat0] * g0.number_of_edges() +\
        [feat1] * g1.number_of_edges() +\
        [feat2] * g2.number_of_edges() +\
        [feat3] * g3.number_of_edges(), 0
    )
    assert F.allclose(dgl.broadcast_edges(
        bg, F.cat([feat0, feat1, feat2, feat3], 0)
    ), ground_truth) 
Example #5
Source File: test_readout.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_broadcast_nodes():
    # test#1: basic
    g0 = dgl.DGLGraph(nx.path_graph(10))
    feat0 = F.randn((1, 40))
    ground_truth = F.stack([feat0] * g0.number_of_nodes(), 0)
    assert F.allclose(dgl.broadcast_nodes(g0, feat0), ground_truth)

    # test#2: batched graph
    g1 = dgl.DGLGraph(nx.path_graph(3))
    g2 = dgl.DGLGraph()
    g3 = dgl.DGLGraph(nx.path_graph(12))
    bg = dgl.batch([g0, g1, g2, g3])
    feat1 = F.randn((1, 40))
    feat2 = F.randn((1, 40))
    feat3 = F.randn((1, 40))
    ground_truth = F.cat(
        [feat0] * g0.number_of_nodes() +\
        [feat1] * g1.number_of_nodes() +\
        [feat2] * g2.number_of_nodes() +\
        [feat3] * g3.number_of_nodes(), 0
    )
    assert F.allclose(dgl.broadcast_nodes(
        bg, F.cat([feat0, feat1, feat2, feat3], 0)
    ), ground_truth) 
Example #6
Source File: pajek.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def write_pajek(G, path, encoding='UTF-8'):
    """Write graph in Pajek format to path.

    Parameters
    ----------
    G : graph
       A Networkx graph
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_pajek(G, "test.net")

    References
    ----------
    See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm
    for format information.
    """
    for line in generate_pajek(G):
        line+='\n'
        path.write(line.encode(encoding)) 
Example #7
Source File: test_propagate.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_prop_edges_dfs():
    g = dgl.DGLGraph(nx.path_graph(5))
    g = dgl.graph(g.edges())
    g.ndata['x'] = F.ones((5, 2))
    dgl.prop_edges_dfs(g, 0, message_func=mfunc, reduce_func=rfunc, apply_node_func=None)
    # snr using dfs results in a cumsum
    assert F.allclose(g.ndata['x'],
            F.tensor([[1., 1.], [2., 2.], [3., 3.], [4., 4.], [5., 5.]]))

    g.ndata['x'] = F.ones((5, 2))
    dgl.prop_edges_dfs(g, 0, has_reverse_edge=True, message_func=mfunc, reduce_func=rfunc, apply_node_func=None)
    # result is cumsum[i] + cumsum[i-1]
    assert F.allclose(g.ndata['x'],
            F.tensor([[1., 1.], [3., 3.], [5., 5.], [7., 7.], [9., 9.]]))

    g.ndata['x'] = F.ones((5, 2))
    dgl.prop_edges_dfs(g, 0, has_nontree_edge=True, message_func=mfunc, reduce_func=rfunc, apply_node_func=None)
    # result is cumsum[i] + cumsum[i+1]
    assert F.allclose(g.ndata['x'],
            F.tensor([[3., 3.], [5., 5.], [7., 7.], [9., 9.], [5., 5.]])) 
Example #8
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_glob_att_pool():
    ctx = F.ctx()
    g = dgl.DGLGraph(nx.path_graph(10))

    gap = nn.GlobalAttentionPooling(th.nn.Linear(5, 1), th.nn.Linear(5, 10))
    gap = gap.to(ctx)
    print(gap)

    # test#1: basic
    h0 = F.randn((g.number_of_nodes(), 5))
    h1 = gap(g, h0)
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.dim() == 2

    # test#2: batched graph
    bg = dgl.batch([g, g, g, g])
    h0 = F.randn((bg.number_of_nodes(), 5))
    h1 = gap(bg, h0)
    assert h1.shape[0] == 4 and h1.shape[1] == 10 and h1.dim() == 2 
Example #9
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_set2set():
    g = dgl.DGLGraph(nx.path_graph(10))
    ctx = F.ctx()

    s2s = nn.Set2Set(5, 3, 3) # hidden size 5, 3 iters, 3 layers
    s2s.initialize(ctx=ctx)
    print(s2s)

    # test#1: basic
    h0 = F.randn((g.number_of_nodes(), 5))
    h1 = s2s(g, h0)
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.ndim == 2

    # test#2: batched graph
    bg = dgl.batch([g, g, g])
    h0 = F.randn((bg.number_of_nodes(), 5))
    h1 = s2s(bg, h0)
    assert h1.shape[0] == 3 and h1.shape[1] == 10 and h1.ndim == 2 
Example #10
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_glob_att_pool():
    g = dgl.DGLGraph(nx.path_graph(10))
    ctx = F.ctx()

    gap = nn.GlobalAttentionPooling(gluon.nn.Dense(1), gluon.nn.Dense(10))
    gap.initialize(ctx=ctx)
    print(gap)
    # test#1: basic
    h0 = F.randn((g.number_of_nodes(), 5))
    h1 = gap(g, h0)
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.ndim == 2

    # test#2: batched graph
    bg = dgl.batch([g, g, g, g])
    h0 = F.randn((bg.number_of_nodes(), 5))
    h1 = gap(bg, h0)
    assert h1.shape[0] == 4 and h1.shape[1] == 10 and h1.ndim == 2 
Example #11
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_edge_softmax():
    # Basic
    g = dgl.DGLGraph(nx.path_graph(3))
    edata = F.ones((g.number_of_edges(), 1))
    a = nn.edge_softmax(g, edata)
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
    assert np.allclose(a.asnumpy(), uniform_attention(g, a.shape).asnumpy(),
            1e-4, 1e-4)

    # Test higher dimension case
    edata = F.ones((g.number_of_edges(), 3, 1))
    a = nn.edge_softmax(g, edata)
    assert len(g.ndata) == 0
    assert len(g.edata) == 0
    assert np.allclose(a.asnumpy(), uniform_attention(g, a.shape).asnumpy(),
            1e-4, 1e-4) 
Example #12
Source File: test_database_manager.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
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, dimod.SPIN)

        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.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) 
Example #13
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_glob_att_pool():
    g = dgl.DGLGraph(nx.path_graph(10))

    gap = nn.GlobalAttentionPooling(layers.Dense(1), layers.Dense(10))
    print(gap)

    # test#1: basic
    h0 = F.randn((g.number_of_nodes(), 5))
    h1 = gap(g, h0)
    assert h1.shape[0] == 1 and h1.shape[1] == 10 and h1.ndim == 2

    # test#2: batched graph
    bg = dgl.batch([g, g, g, g])
    h0 = F.randn((bg.number_of_nodes(), 5))
    h1 = gap(bg, h0)
    assert h1.shape[0] == 4 and h1.shape[1] == 10 and h1.ndim == 2 
Example #14
Source File: nx_edge_augmentation.py    From ibeis with Apache License 2.0 6 votes vote down vote up
def complement_edges(G):
    """Returns only the edges in the complement of G

    Example
    -------
    >>> G = nx.path_graph((1, 2, 3, 4))
    >>> sorted(complement_edges(G))
    [(1, 3), (1, 4), (2, 4)]
    >>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
    >>> sorted(complement_edges(G))
    [(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
    >>> G = nx.complete_graph(1000)
    >>> sorted(complement_edges(G))
    []
    """
    if G.is_directed():
        for u, v in it.combinations(G.nodes(), 2):
            if v not in G.adj[u]:
                yield (u, v)
            if u not in G.adj[v]:
                yield (v, u)
    else:
        for u, v in it.combinations(G.nodes(), 2):
            if v not in G.adj[u]:
                yield (u, v) 
Example #15
Source File: test_embedding_chimera.py    From dwave-system with Apache License 2.0 6 votes vote down vote up
def test_1d_3_on_c16(self):
        embedding = find_grid_embedding([3], 16)

        self.assertEqual(len(embedding), 3)

        target_adj = dwave.embedding.target_to_source(dnx.chimera_graph(16), embedding)

        G = nx.path_graph(3)
        for u in G.adj:
            for v in G.adj[u]:
                self.assertIn(u, target_adj)
                self.assertIn(v, target_adj[u])

        for u in target_adj:
            for v in target_adj[u]:
                self.assertIn(u, G.adj)
                self.assertIn(v, G.adj[u]) 
Example #16
Source File: test_interface.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
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, dimod.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.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) 
Example #17
Source File: test_penaltymodel.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
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=dimod.SPIN)

        linear = {v: -3 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.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 = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)
        with self.assertRaises(ValueError):
            widget = pm.PenaltyModel.from_specification(spec, model, 2., -2) 
Example #18
Source File: test_independent_set.py    From dwave_networkx with Apache License 2.0 6 votes vote down vote up
def test_maximum_independent_set_weighted(self):
        weight = 'weight'
        G = nx.path_graph(6)

        # favor odd nodes
        nx.set_node_attributes(G, {node: node % 2 + 1 for node in G}, weight)
        indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
        self.assertEqual(set(indep_set), {1, 3, 5})

        # favor even nodes
        nx.set_node_attributes(G, {node: (node + 1) % 2 + 1 for node in G}, weight)
        indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
        self.assertEqual(set(indep_set), {0, 2, 4})

        # make nodes 1 and 4 likely
        nx.set_node_attributes(G, {0: 1, 1: 3, 2: 1, 3: 1, 4: 3, 5: 1}, weight)
        indep_set = dnx.maximum_weighted_independent_set(G, weight, dimod.ExactSolver())
        self.assertEqual(set(indep_set), {1, 4}) 
Example #19
Source File: test_generation.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_impossible_AND_3path(self):
        """AND gate cannot exist on a 3-path"""

        graph = nx.path_graph(3)

        configurations = {(-1, -1, -1): 0,
                          (-1, +1, -1): 0,
                          (+1, -1, -1): 0,
                          (+1, +1, +1): 0}

        decision_variables = (0, 1, 2)

        linear_energy_ranges = {v: (-2., 2.) for v in graph}

        quadratic_energy_ranges = {(u, v): (-1., 1.) for u, v in graph.edges}

        with self.assertRaises(pm.ImpossiblePenaltyModel):
            mip.generate_bqm(graph,
                             configurations,
                             decision_variables,
                             linear_energy_ranges=linear_energy_ranges,
                             quadratic_energy_ranges=quadratic_energy_ranges) 
Example #20
Source File: test_generation.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_impossible(self):
        graph = nx.path_graph(3)
        configurations = {(-1, -1, -1): 0,
                          (-1, +1, -1): 0,
                          (+1, -1, -1): 0,
                          (+1, +1, +1): 0}
        decision_variables = (0, 1, 2)
        linear_energy_ranges = {v: (-2., 2.) for v in graph}
        quadratic_energy_ranges = {(u, v): (-1., 1.) for u, v in graph.edges}
        min_classical_gap = 2

        with self.assertRaises(pm.ImpossiblePenaltyModel):
            maxgap.generate(graph, configurations, decision_variables,
                            linear_energy_ranges,
                            quadratic_energy_ranges,
                            min_classical_gap) 
Example #21
Source File: test_matching.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def test_dimod_vs_list(self):
        G = nx.path_graph(5)

        matching = dnx.min_maximal_matching(G, ExactSolver())
        matching = dnx.algorithms.matching.maximal_matching(G, ExactSolver())
        matching = dnx.min_maximal_matching(G, SimulatedAnnealingSampler())
        matching = dnx.algorithms.matching.maximal_matching(G, SimulatedAnnealingSampler()) 
Example #22
Source File: test_clique.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def test_path3(self):
        G = nx.path_graph(3)
        self.assertTrue(dnx.is_clique(G, [0]))
        self.assertTrue(dnx.is_clique(G, [0, 1]))
        self.assertTrue(dnx.is_clique(G, []))
        self.assertFalse(dnx.is_clique(G, [0, 2])) 
Example #23
Source File: mininet_multidp_tests.py    From faucet with Apache License 2.0 5 votes vote down vote up
def set_up(self, host_links=None, host_vlans=None, switch_to_switch_links=1):
        """
        Args:
            host_links (dict): Host index map to list of DPs it is connected to
            host_vlans (dict): Host index map to list of vlans it belongs to
        """
        super().setUp()
        network_graph = networkx.path_graph(self.NUM_DPS)
        dp_options = {}
        for dp_i in network_graph.nodes():
            dp_options.setdefault(dp_i, {
                'group_table': self.GROUP_TABLE,
                'ofchannel_log': self.debug_log_path + str(dp_i) if self.debug_log_path else None,
                'hardware': self.hardware if dp_i == 0 and self.hw_dpid else 'Open vSwitch'
            })
            if dp_i == 0:
                dp_options[0]['stack'] = {'priority': 1}
        switch_links = list(network_graph.edges()) * switch_to_switch_links
        link_vlans = {edge: None for edge in switch_links}
        if host_links is None:
            host_links = {0: [0], 1: [1], 2: [2]}
        if host_vlans is None:
            host_vlans = {h_i: 0 for h_i in host_links.keys()}
        self.build_net(
            host_links=host_links,
            host_vlans=host_vlans,
            switch_links=switch_links,
            link_vlans=link_vlans,
            n_vlans=self.NUM_VLANS,
            dp_options=dp_options,
        )
        self.start_net() 
Example #24
Source File: test_coloring.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def test_5path(self):
        G = nx.path_graph(5)
        coloring = dnx.min_vertex_coloring(G, dimod.ExactSolver())
        self.assertTrue(dnx.is_vertex_coloring(G, coloring))
        self.assertEqual(len(set(coloring.values())), 2)  # bipartite 
Example #25
Source File: test_clique.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def test_maximum_independent_set_basic(self):
        """Runs the function on some small and simple graphs, just to make
        sure it works in basic functionality.
        """
        G = dnx.chimera_graph(1, 2, 2)
        clique = dnx.maximum_clique(G, dimod.ExactSolver())
        self.assertTrue(dnx.is_clique(G, clique))

        G = nx.path_graph(5)
        clique = dnx.maximum_clique(G, dimod.ExactSolver())
        self.assertTrue(dnx.is_clique(G, clique)) 
Example #26
Source File: test_matching.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def test_path_graph(self):
        G = nx.path_graph(10)
        matching = dnx.algorithms.matching.maximal_matching(G, ExactSolver())
        self.assertTrue(dnx.is_maximal_matching(G, matching))

        matching = dnx.min_maximal_matching(G, ExactSolver())
        self.assertTrue(dnx.is_maximal_matching(G, matching))

        G.add_edge(0, 9)

        matching = dnx.algorithms.matching.maximal_matching(G, ExactSolver())
        self.assertTrue(dnx.is_maximal_matching(G, matching))

        matching = dnx.min_maximal_matching(G, ExactSolver())
        self.assertTrue(dnx.is_maximal_matching(G, matching)) 
Example #27
Source File: test_specification.py    From penaltymodel with Apache License 2.0 5 votes vote down vote up
def test_bad_relabel(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=dimod.SPIN)

        mapping = {0: 2, 1: 1}

        with self.assertRaises(ValueError):
            spec.relabel_variables(mapping, inplace=False)

        with self.assertRaises(ValueError):
            spec.relabel_variables(mapping, inplace=True) 
Example #28
Source File: test_penaltymodel.py    From penaltymodel with Apache License 2.0 5 votes vote down vote up
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=dimod.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.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=dimod.SPIN)
        linear = {v: 0 for v in graph}
        quadratic = {edge: -1 for edge in graph.edges}
        model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)
        test_widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)

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

        widget.relabel_variables({0: 'a'}, inplace=True)
        self.assertEqual(widget, test_widget)
        self.assertEqual(widget.decision_variables, ('a', 2)) 
Example #29
Source File: gpickle.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def read_gpickle(path):
    """Read graph object in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be uncompressed.

    Returns
    -------
    G : graph
       A NetworkX graph

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gpickle(G, "test.gpickle")
    >>> G = nx.read_gpickle("test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    return pickle.load(path)

# fixture for nose tests 
Example #30
Source File: gpickle.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def write_gpickle(G, path, protocol=pickle.HIGHEST_PROTOCOL):
    """Write graph in Python pickle format.

    Pickles are a serialized byte stream of a Python object [1]_.
    This format will preserve Python objects used as nodes or edges.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.

    protocol : integer
        Pickling protocol to use. Default value: ``pickle.HIGHEST_PROTOCOL``.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_gpickle(G, "test.gpickle")

    References
    ----------
    .. [1] http://docs.python.org/library/pickle.html
    """
    pickle.dump(G, path, protocol)