pythongraphnetworkxminimum-spanning-tree

Networkx: Creating a complete graph for a given set of nodes


I have a list as c4_leaves = [56,78,90,112]. I'm trying to create a complete graph using these elements in c4_leaves as nodes. Here's what I've tried:

V_ex = c4_leaves
G_ex = nx.Graph() 
G_ex.add_nodes_from(V_ex)
G_ex = nx.complete_graph(4)

for u,v in G_ex.edges():
    G_ex[u][v]['distance'] = distance(points33, u, v)

And then the minimum spanning tree of the above graph as:

T_ex = nx.minimum_spanning_tree(G_ex, weight='distance')
F_ex = list(T_ex.edges())

When I draw G_ex, it gives me the correct graph, but when I print details of the minimum spanning tree, it shows that T_ex.nodes() = [0,1,2,3,56,78,90,112].

Can someone show me the mistake I'm making?


Solution

  • It is an old question. However, I am still putting my two cents in it. I was faced with the same issue. I am not sure what exactly was blocking point for the actual question but I will write down what I did.

    So, I want to create a complete graph with four nodes (56,78,90, and 112). I have a list. I looked up the definition of complete_graph And here is what I saw

    Signature: nx.complete_graph(n, create_using=None)
    Docstring:
    Return the complete graph `K_n` with n nodes.
    
    Parameters
    ----------
    n : int or iterable container of nodes
        If n is an integer, nodes are from range(n).
        If n is a container of nodes, those nodes appear in the graph.
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.
    
    Examples
    --------
    >>> G = nx.complete_graph(9)
    >>> len(G)
    9
    >>> G.size()
    36
    >>> G = nx.complete_graph(range(11, 14))
    >>> list(G.nodes())
    [11, 12, 13]
    >>> G = nx.complete_graph(4, nx.DiGraph())
    >>> G.is_directed()
    True
    

    Which means it can take an iterator. In the same spirit, I tried the following code

    In [6]: l = [56,78,90,112]
    
    In [7]: G = nx.complete_graph(l)
    
    In [8]: G.edges(data=True)
    Out[8]: EdgeDataView([(56, 78, {}), (56, 90, {}), (56, 112, {}), (78, 90, {}), (78, 112, {}), (90, 112, {})])
        
    In [10]: G.nodes(data=True)
    Out[10]: NodeDataView({56: {}, 78: {}, 90: {}, 112: {}})
    

    So, there you have it, a complete graph built out of a list.

    I hope that this answers the question.