Python networkx.union() Examples

The following are 30 code examples of networkx.union(). 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_binary.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_union_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph['name'] = 'g'

    h = g.copy()
    h.graph['name'] = 'h'
    h.graph['attr'] = 'attr'
    h.nodes[0]['x'] = 7

    gh = nx.union(g, h, rename=('g', 'h'))
    assert_equal( set(gh.nodes()) , set(['h0', 'h1', 'g0', 'g1']) )
    for n in gh:
        graph, node = n
        assert_equal( gh.nodes[n], eval(graph).nodes[int(node)] )

    assert_equal(gh.graph['attr'],'attr')
    assert_equal(gh.graph['name'],'h') # h graph attributes take precendent 
Example #2
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        # G is the example graph in Figure 1 from Batagelj and
        # Zaversnik's paper titled An O(m) Algorithm for Cores
        # Decomposition of Networks, 2003,
        # http://arXiv.org/abs/cs/0310049.  With nodes labeled as
        # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
        # 9-16, the 1-core by nodes 17-20 and node 21 is in the
        # 0-core.
        t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
        t2 = nx.convert_node_labels_to_integers(t1, 5)
        G = nx.union(t1, t2)
        G.add_edges_from([(3, 7), (2, 11), (11, 5), (11, 12), (5, 12),
                          (12, 19), (12, 18), (3, 9), (7, 9), (7, 10),
                          (9, 10), (9, 20), (17, 13), (13, 14), (14, 15),
                          (15, 16), (16, 13)])
        G.add_node(21)
        self.G = G

        # Create the graph H resulting from the degree sequence
        # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.

        degseq = [0, 1, 2, 2, 2, 2, 3]
        H = nx.havel_hakimi_graph(degseq)
        mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
        self.H = nx.relabel_nodes(H, mapping) 
Example #3
Source File: test_binary.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_union_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph['name'] = 'g'

    h = g.copy()
    h.graph['name'] = 'h'
    h.graph['attr'] = 'attr'
    h.nodes[0]['x'] = 7

    gh = nx.union(g, h, rename=('g', 'h'))
    assert_equal(set(gh.nodes()), set(['h0', 'h1', 'g0', 'g1']))
    for n in gh:
        graph, node = n
        assert_equal(gh.nodes[n], eval(graph).nodes[int(node)])

    assert_equal(gh.graph['attr'], 'attr')
    assert_equal(gh.graph['name'], 'h')  # h graph attributes take precendent 
Example #4
Source File: test_chains.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_disconnected_graph(self):
        """Test for a graph with multiple connected components."""
        G = nx.barbell_graph(3, 0)
        H = nx.barbell_graph(3, 0)
        mapping = dict(zip(range(6), 'abcdef'))
        nx.relabel_nodes(H, mapping, copy=False)
        G = nx.union(G, H)
        chains = list(nx.chain_decomposition(G))
        expected = [
            [(0, 1), (1, 2), (2, 0)],
            [(3, 4), (4, 5), (5, 3)],
            [('a', 'b'), ('b', 'c'), ('c', 'a')],
            [('d', 'e'), ('e', 'f'), ('f', 'd')],
        ]
        self.assertEqual(len(chains), len(expected))
        for chain in chains:
            self.assertContainsChain(chain, expected) 
Example #5
Source File: test_core.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        # G is the example graph in Figure 1 from Batagelj and
        # Zaversnik's paper titled An O(m) Algorithm for Cores
        # Decomposition of Networks, 2003,
        # http://arXiv.org/abs/cs/0310049.  With nodes labeled as
        # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
        # 9-16, the 1-core by nodes 17-20 and node 21 is in the
        # 0-core.
        t1=nx.convert_node_labels_to_integers(nx.tetrahedral_graph(),1)
        t2=nx.convert_node_labels_to_integers(t1,5)
        G=nx.union(t1,t2)
        G.add_edges_from( [(3,7), (2,11), (11,5), (11,12), (5,12), (12,19),
                           (12,18), (3,9), (7,9), (7,10), (9,10), (9,20),
                           (17,13), (13,14), (14,15), (15,16), (16,13)])
        G.add_node(21)
        self.G=G

        # Create the graph H resulting from the degree sequence
        # [0,1,2,2,2,2,3] when using the Havel-Hakimi algorithm. 

        degseq=[0,1,2,2,2,2,3]
        H = nx.havel_hakimi_graph(degseq)
        mapping = {6:0, 0:1, 4:3, 5:6, 3:4, 1:2, 2:5 }
        self.H = nx.relabel_nodes(H, mapping) 
Example #6
Source File: test_binary.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_union_attributes():
    g = nx.Graph()
    g.add_node(0, x=4)
    g.add_node(1, x=5)
    g.add_edge(0, 1, size=5)
    g.graph['name'] = 'g'

    h = g.copy()
    h.graph['name'] = 'h'
    h.graph['attr'] = 'attr'
    h.node[0]['x'] = 7

    gh = nx.union(g, h, rename=('g', 'h'))
    assert_equal( set(gh.nodes()) , set(['h0', 'h1', 'g0', 'g1']) )
    for n in gh:
        graph, node = n
        assert_equal( gh.node[n], eval(graph).node[int(node)] )

    assert_equal(gh.graph['attr'],'attr')
    assert_equal(gh.graph['name'],'h') # h graph attributes take precendent 
Example #7
Source File: test_core.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        # G is the example graph in Figure 1 from Batagelj and
        # Zaversnik's paper titled An O(m) Algorithm for Cores
        # Decomposition of Networks, 2003,
        # http://arXiv.org/abs/cs/0310049.  With nodes labeled as
        # shown, the 3-core is given by nodes 1-8, the 2-core by nodes
        # 9-16, the 1-core by nodes 17-20 and node 21 is in the
        # 0-core.
        t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1)
        t2 = nx.convert_node_labels_to_integers(t1, 5)
        G = nx.union(t1, t2)
        G.add_edges_from([(3, 7), (2, 11), (11, 5), (11, 12), (5, 12),
                          (12, 19), (12, 18), (3, 9), (7, 9), (7, 10),
                          (9, 10), (9, 20), (17, 13), (13, 14), (14, 15),
                          (15, 16), (16, 13)])
        G.add_node(21)
        self.G = G

        # Create the graph H resulting from the degree sequence
        # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm.

        degseq = [0, 1, 2, 2, 2, 2, 3]
        H = nx.havel_hakimi_graph(degseq)
        mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5}
        self.H = nx.relabel_nodes(H, mapping) 
Example #8
Source File: test_chains.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_disconnected_graph(self):
        """Test for a graph with multiple connected components."""
        G = nx.barbell_graph(3, 0)
        H = nx.barbell_graph(3, 0)
        mapping = dict(zip(range(6), 'abcdef'))
        nx.relabel_nodes(H, mapping, copy=False)
        G = nx.union(G, H)
        chains = list(nx.chain_decomposition(G))
        expected = [
            [(0, 1), (1, 2), (2, 0)],
            [(3, 4), (4, 5), (5, 3)],
            [('a', 'b'), ('b', 'c'), ('c', 'a')],
            [('d', 'e'), ('e', 'f'), ('f', 'd')],
        ]
        self.assertEqual(len(chains), len(expected))
        for chain in chains:
            self.assertContainsChain(chain, expected) 
Example #9
Source File: gcc.py    From QTop with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, code, charge_type):
        l,d = code.depth, code.dimension
        s = {}
        for type in code.types:
            s[type] = code.Syndrome(type, charge_type)

        uc = nx.union(s['green'], nx.union(s['red'], s['blue']))
        for edge in code.Dual['red'].edges():
            break
        scale = common.euclidean_dist(edge[0], edge[1])+.1

        i = 1

        while uc.nodes() != []:
        	clusters = GCC_Partition(uc, i*scale)
        	for cluster in clusters:
        		code, uc = GCC_Annihilate(cluster, code, uc, charge_type, i*scale)
        	i += 1
        return code 
Example #10
Source File: test_binary.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_mixed_type_union():
    G = nx.Graph()
    H = nx.MultiGraph()
    U = nx.union(G,H) 
Example #11
Source File: test_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4],[1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G,C))

        # Eppstein's tests
        G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]})
        C = [[0], [1], [2],[ 3], [4], [5], [6]]
        self.gc.append((G,C))

        G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C)) 
Example #12
Source File: all.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def compose_all(graphs, name=None):
    """Return the composition of all graphs.

    Composition is the simple union of the node sets and edge sets.
    The node sets of the supplied graphs need not be disjoint.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    name : string
       Specify name for new graph

    Returns
    -------
    C : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the supplied graphs be either all directed or all
    undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    graphs = iter(graphs)
    C = next(graphs)
    for H in graphs:
        C = nx.compose(C, H, name=name)
    return C 
Example #13
Source File: all.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def disjoint_union_all(graphs):
    """Return the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    graphs = iter(graphs)
    U = next(graphs)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U 
Example #14
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4], [1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G, C))

        # Eppstein's tests
        G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
        C = [[0], [1], [2], [3], [4], [5], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        C = []
        self.gc.append((G, C)) 
Example #15
Source File: test_chains.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_disconnected_graph_root_node(self):
        """Test for a single component of a disconnected graph."""
        G = nx.barbell_graph(3, 0)
        H = nx.barbell_graph(3, 0)
        mapping = dict(zip(range(6), 'abcdef'))
        nx.relabel_nodes(H, mapping, copy=False)
        G = nx.union(G, H)
        chains = list(nx.chain_decomposition(G, root='a'))
        expected = [
            [('a', 'b'), ('b', 'c'), ('c', 'a')],
            [('d', 'e'), ('e', 'f'), ('f', 'd')],
        ]
        self.assertEqual(len(chains), len(expected))
        for chain in chains:
            self.assertContainsChain(chain, expected) 
Example #16
Source File: test_chains.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_disconnected_graph_root_node(self):
        """Test for a single component of a disconnected graph."""
        G = nx.barbell_graph(3, 0)
        H = nx.barbell_graph(3, 0)
        mapping = dict(zip(range(6), 'abcdef'))
        nx.relabel_nodes(H, mapping, copy=False)
        G = nx.union(G, H)
        chains = list(nx.chain_decomposition(G, root='a'))
        expected = [
            [('a', 'b'), ('b', 'c'), ('c', 'a')],
            [('d', 'e'), ('e', 'f'), ('f', 'd')],
        ]
        self.assertEqual(len(chains), len(expected))
        for chain in chains:
            self.assertContainsChain(chain, expected) 
Example #17
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, code, charge_type):
        errors = {}
        for type in code.types:
            errors[type] = code.Syndrome(type, charge_type)

        shrunk_errs, shrunk_exts, matches = {}, {}, {}
        loops_graph = nx.Graph()
        for t1 in code.types:
            [t2, t3] = code.complementaryTypes(t1)
            shrunk_errs[t1] = nx.union(errors[t2], errors[t3])
            shrunk_exts[t1] = code.External[t2] + code.External[t3]
            alt_ext = code.External[t1][0]
            matches[t1] = DSP_Matching(shrunk_errs[t1], shrunk_exts[t1], 2, alt_ext)

            for start in matches[t1]:
                end = matches[t1][start]
                chain = DSP_Path(code.Dual[t1], start, end)
                links = len(chain) -1

                for i in range(links):
                    node1, node2 = chain[i], chain[i+1]
                    edge = (node1, node2)
                    if edge in loops_graph.edges():
                        loops_graph.remove_edge(*edge)
                    else:
                        loops_graph.add_edge(*edge)
        Exts = code.External['red']+code.External['blue']+code.External['green']

        code, loops_graph = correctLoops(code, loops_graph, charge_type)
        while hasConnectedBoundaries(code, loops_graph, Exts):
            ext1, ext2 = connectedBoundaries(loops_graph, Exts)
            code, loops_graph = makeBoundLoop(code, loops_graph, ext1, ext2)
            code, loops_graph = correctLoops(code, loops_graph, charge_type)
        return code 
Example #18
Source File: nltk2graph.py    From ccg2lambda with Apache License 2.0 5 votes vote down vote up
def merge_graphs_to(graph, graphs):
    head_node = graph.graph['head_node']
    for i, g in enumerate(graphs):
        graph = nx.union(graph, g)
        graph.add_edge(head_node, g.graph['head_node'], arg=i)
    graph.graph['head_node'] = head_node
    return graph 
Example #19
Source File: all.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compose_all(graphs):
    """Returns the composition of all graphs.

    Composition is the simple union of the node sets and edge sets.
    The node sets of the supplied graphs need not be disjoint.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    C : A graph with the same type as the first graph in list

    Raises
    ------
    ValueError
       If `graphs` is an empty list.

    Notes
    -----
    It is recommended that the supplied graphs be either all directed or all
    undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    if not graphs:
        raise ValueError('cannot apply compose_all to an empty list')
    graphs = iter(graphs)
    C = next(graphs)
    for H in graphs:
        C = nx.compose(C, H)
    return C 
Example #20
Source File: all.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def disjoint_union_all(graphs):
    """Returns the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Raises
    ------
    ValueError
       If `graphs` is an empty list.

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    if not graphs:
        raise ValueError('cannot apply disjoint_union_all to an empty list')
    graphs = iter(graphs)
    U = next(graphs)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U 
Example #21
Source File: all.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def disjoint_union_all(graphs):
    """Return the disjoint union of all graphs.

    This operation forces distinct integer node labels starting with 0
    for the first graph in the list and numbering consecutively.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    Returns
    -------
    U : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the graphs be either all directed or all undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    graphs = iter(graphs)
    U = next(graphs)
    for H in graphs:
        U = nx.disjoint_union(U, H)
    return U 
Example #22
Source File: all.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def compose_all(graphs, name=None):
    """Return the composition of all graphs.

    Composition is the simple union of the node sets and edge sets.
    The node sets of the supplied graphs need not be disjoint.

    Parameters
    ----------
    graphs : list
       List of NetworkX graphs

    name : string
       Specify name for new graph

    Returns
    -------
    C : A graph with the same type as the first graph in list

    Notes
    -----
    It is recommended that the supplied graphs be either all directed or all
    undirected.

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.
    """
    graphs = iter(graphs)
    C = next(graphs)
    for H in graphs:
        C = nx.compose(C, H, name=name)
    return C 
Example #23
Source File: test_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4],[1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G,C))

        # Eppstein's tests
        G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]})
        C = [[0], [1], [2],[ 3], [4], [5], [6]]
        self.gc.append((G,C))

        G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C)) 
Example #24
Source File: test_binary.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_mixed_type_union():
    G = nx.Graph()
    H = nx.MultiGraph()
    U = nx.union(G, H) 
Example #25
Source File: test_binary.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_mixed_type_union():
    G = nx.Graph()
    H = nx.MultiGraph()
    U = nx.union(G,H) 
Example #26
Source File: test_all.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def test_union_all_and_compose_all():
    K3=nx.complete_graph(3)
    P3=nx.path_graph(3)

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G1.add_edge('A','C')
    G1.add_edge('A','D')
    G2=nx.DiGraph()
    G2.add_edge('1','2')
    G2.add_edge('1','3')
    G2.add_edge('1','4')

    G=nx.union_all([G1,G2])
    H=nx.compose_all([G1,G2])
    assert_edges_equal(G.edges(),H.edges())
    assert_false(G.has_edge('A','1'))
    assert_raises(nx.NetworkXError, nx.union, K3, P3)
    H1=nx.union_all([H,G1],rename=('H','G1'))
    assert_equal(sorted(H1.nodes()),
        ['G1A', 'G1B', 'G1C', 'G1D',
         'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    H2=nx.union_all([H,G2],rename=("H",""))
    assert_equal(sorted(H2.nodes()),
        ['1', '2', '3', '4',
         'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    assert_false(H1.has_edge('NB','NA'))

    G=nx.compose_all([G,G])
    assert_edges_equal(G.edges(),H.edges())

    G2=nx.union_all([G2,G2],rename=('','copy'))
    assert_equal(sorted(G2.nodes()),
        ['1', '2', '3', '4', 'copy1', 'copy2', 'copy3', 'copy4'])

    assert_equal(G2.neighbors('copy4'),[])
    assert_equal(sorted(G2.neighbors('copy1')),['copy2', 'copy3', 'copy4'])
    assert_equal(len(G),8)
    assert_equal(nx.number_of_edges(G),6)

    E=nx.disjoint_union_all([G,G])
    assert_equal(len(E),16)
    assert_equal(nx.number_of_edges(E),12)

    E=nx.disjoint_union_all([G1,G2])
    assert_equal(sorted(E.nodes()),[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G2=nx.DiGraph()
    G2.add_edge(1,2)
    G3=nx.DiGraph()
    G3.add_edge(11,22)
    G4=nx.union_all([G1,G2,G3],rename=("G1","G2","G3"))
    assert_equal(sorted(G4.nodes()),
        ['G1A', 'G1B', 'G21', 'G22',
         'G311', 'G322']) 
Example #27
Source File: all.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def union_all(graphs, rename=(None,), name=None):
    """Return the union of all graphs.

    The graphs must be disjoint, otherwise an exception is raised.

    Parameters
    ----------
    graphs : list of graphs
       List of NetworkX graphs

    rename : bool , default=(None, None)
       Node names of G and H can be changed by specifying the tuple
       rename=('G-','H-') (for example).  Node "u" in G is then renamed
       "G-u" and "v" in H is renamed "H-v".

    name : string
       Specify the name for the union graph@not_implemnted_for('direct

    Returns
    -------
    U : a graph with the same type as the first graph in list

    Notes
    -----
    To force a disjoint union with node relabeling, use
    disjoint_union_all(G,H) or convert_node_labels_to integers().

    Graph, edge, and node attributes are propagated to the union graph.
    If a graph attribute is present in multiple graphs, then the value
    from the last graph in the list with that attribute is used.

    See Also
    --------
    union
    disjoint_union_all
    """
    graphs_names = zip_longest(graphs, rename)
    U, gname = next(graphs_names)
    for H, hname in graphs_names:
        U = nx.union(U, H, (gname, hname), name=name)
        gname = None
    return U 
Example #28
Source File: test_all.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def test_union_all_and_compose_all():
    K3=nx.complete_graph(3)
    P3=nx.path_graph(3)

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G1.add_edge('A','C')
    G1.add_edge('A','D')
    G2=nx.DiGraph()
    G2.add_edge('1','2')
    G2.add_edge('1','3')
    G2.add_edge('1','4')

    G=nx.union_all([G1,G2])
    H=nx.compose_all([G1,G2])
    assert_edges_equal(G.edges(),H.edges())
    assert_false(G.has_edge('A','1'))
    assert_raises(nx.NetworkXError, nx.union, K3, P3)
    H1=nx.union_all([H,G1],rename=('H','G1'))
    assert_equal(sorted(H1.nodes()),
        ['G1A', 'G1B', 'G1C', 'G1D',
         'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    H2=nx.union_all([H,G2],rename=("H",""))
    assert_equal(sorted(H2.nodes()),
        ['1', '2', '3', '4',
         'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    assert_false(H1.has_edge('NB','NA'))

    G=nx.compose_all([G,G])
    assert_edges_equal(G.edges(),H.edges())

    G2=nx.union_all([G2,G2],rename=('','copy'))
    assert_equal(sorted(G2.nodes()),
        ['1', '2', '3', '4', 'copy1', 'copy2', 'copy3', 'copy4'])

    assert_equal(sorted(G2.neighbors('copy4')),[])
    assert_equal(sorted(G2.neighbors('copy1')),['copy2', 'copy3', 'copy4'])
    assert_equal(len(G),8)
    assert_equal(nx.number_of_edges(G),6)

    E=nx.disjoint_union_all([G,G])
    assert_equal(len(E),16)
    assert_equal(nx.number_of_edges(E),12)

    E=nx.disjoint_union_all([G1,G2])
    assert_equal(sorted(E.nodes()),[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G2=nx.DiGraph()
    G2.add_edge(1,2)
    G3=nx.DiGraph()
    G3.add_edge(11,22)
    G4=nx.union_all([G1,G2,G3],rename=("G1","G2","G3"))
    assert_equal(sorted(G4.nodes()),
        ['G1A', 'G1B', 'G21', 'G22',
         'G311', 'G322']) 
Example #29
Source File: test_binary.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def test_union_and_compose():
    K3=complete_graph(3)
    P3=path_graph(3)

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G1.add_edge('A','C')
    G1.add_edge('A','D')
    G2=nx.DiGraph()
    G2.add_edge('1','2')
    G2.add_edge('1','3')
    G2.add_edge('1','4')

    G=union(G1,G2)
    H=compose(G1,G2)
    assert_edges_equal(G.edges(),H.edges())
    assert_false(G.has_edge('A',1))
    assert_raises(nx.NetworkXError, nx.union, K3, P3)
    H1=union(H,G1,rename=('H','G1'))
    assert_equal(sorted(H1.nodes()),
                 ['G1A', 'G1B', 'G1C', 'G1D', 
                  'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    H2=union(H,G2,rename=("H",""))
    assert_equal(sorted(H2.nodes()),
                 ['1', '2', '3', '4', 
                  'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    assert_false(H1.has_edge('NB','NA'))

    G=compose(G,G)
    assert_edges_equal(G.edges(),H.edges())

    G2=union(G2,G2,rename=('','copy'))
    assert_equal(sorted(G2.nodes()),
                 ['1', '2', '3', '4', 'copy1', 'copy2', 'copy3', 'copy4'])

    assert_equal(G2.neighbors('copy4'),[])
    assert_equal(sorted(G2.neighbors('copy1')),['copy2', 'copy3', 'copy4'])
    assert_equal(len(G),8)
    assert_equal(number_of_edges(G),6)

    E=disjoint_union(G,G)
    assert_equal(len(E),16)
    assert_equal(number_of_edges(E),12)

    E=disjoint_union(G1,G2)
    assert_equal(sorted(E.nodes()),[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) 
Example #30
Source File: test_binary.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def test_union_and_compose():
    K3=complete_graph(3)
    P3=path_graph(3)

    G1=nx.DiGraph()
    G1.add_edge('A','B')
    G1.add_edge('A','C')
    G1.add_edge('A','D')
    G2=nx.DiGraph()
    G2.add_edge('1','2')
    G2.add_edge('1','3')
    G2.add_edge('1','4')

    G=union(G1,G2)
    H=compose(G1,G2)
    assert_edges_equal(G.edges(),H.edges())
    assert_false(G.has_edge('A',1))
    assert_raises(nx.NetworkXError, nx.union, K3, P3)
    H1=union(H,G1,rename=('H','G1'))
    assert_equal(sorted(H1.nodes()),
                 ['G1A', 'G1B', 'G1C', 'G1D', 
                  'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    H2=union(H,G2,rename=("H",""))
    assert_equal(sorted(H2.nodes()),
                 ['1', '2', '3', '4', 
                  'H1', 'H2', 'H3', 'H4', 'HA', 'HB', 'HC', 'HD'])

    assert_false(H1.has_edge('NB','NA'))

    G=compose(G,G)
    assert_edges_equal(G.edges(),H.edges())

    G2=union(G2,G2,rename=('','copy'))
    assert_equal(sorted(G2.nodes()),
                 ['1', '2', '3', '4', 'copy1', 'copy2', 'copy3', 'copy4'])

    assert_equal(sorted(G2.neighbors('copy4')),[])
    assert_equal(sorted(G2.neighbors('copy1')),['copy2', 'copy3', 'copy4'])
    assert_equal(len(G),8)
    assert_equal(number_of_edges(G),6)

    E=disjoint_union(G,G)
    assert_equal(len(E),16)
    assert_equal(number_of_edges(E),12)

    E=disjoint_union(G1,G2)
    assert_equal(sorted(E.nodes()),[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

    G = nx.Graph()
    H = nx.Graph()
    G.add_nodes_from([(1, {'a1': 1})])
    H.add_nodes_from([(1, {'b1': 1})])
    R = compose(G, H)
    assert_equal(R.nodes, {1: {'a1': 1, 'b1': 1}})