Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 doing?

like image 535
ccc Avatar asked Sep 21 '18 16:09

ccc


People also ask

How do I create a complete graph in NetworkX?

The command G_ex = nx. complete_graph(4) creates a complete graph G whose nodes are 0, 1, 2, and 3. You then add more to G , but it has those nodes. Thanks for that.

How do you create a directed graph in Python?

Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph). In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph. Edges: G can also be grown by adding edges.


1 Answers

Instead of using complete_graph, which generates a new complete graph with other nodes, create the desired graph as follows:

import itertools
import networkx as nx

c4_leaves = [56,78,90,112]
G_ex = nx.Graph()
G_ex.add_nodes_from(c4_leaves)
G_ex.add_edges_from(itertools.combinations(c4_leaves, 2))

In the case of directed graphs use:

G_ex.add_edges_from(itertools.permutations(c4_leaves, 2))
like image 86
zohar.kom Avatar answered Nov 15 '22 08:11

zohar.kom