Monday, February 9, 2009

Network Layout using NetworkX

Below is the Python code that uses the Networkx module to layout the network. Hopefully the code is self-explanatory. The code is saved in "c/nxAutoLayout.py"

import pytc
import networkx as nx

nodes = pytc.itemsOfFamily("node");

connections = pytc.itemsOfFamily("connection");

numNodes = len(nodes);

numConnections = len(connections);

M = [];

for i in range(0,numConnections):

   pytc.setStraight(connections[i]);

   connected_nodes = pytc.getConnectedParts( connections[i] );

   for j in connected_nodes:

       n = 0;

       for k in range(0,numNodes):

           if nodes[k] == j:

           n = k;

           break;

       n += numConnections;

       M.append( (i,n) ); #connection i and node k are connected


G = nx.Graph();

G.add_nodes_from( range( 0, numConnections + numNodes ) );

G.add_edges_from(M);


Pos = nx.spring_layout(G);


minx = 0;

maxx = 0;

miny = 0;

maxy = 0;


for i in range(0,len(Pos)):

    if minx == 0 or minx > Pos[i][0]:

        minx = Pos[i][0];

    if miny == 0 or miny > Pos[i][1]:

        miny = Pos[i][1];

    if maxx == 0 or maxx <>

        maxx = Pos[i][0];

    if maxy == 0 or maxy <>

        maxy = Pos[i][0];


for i in range(0,len(Pos)):

   Pos[i][0] += - minx;

   Pos[i][0] *= 500.0/(maxx - minx);

   Pos[i][1] += - miny;

   Pos[i][1] *= 500.0/(maxy - miny);


for i in range(0,numConnections):

   pytc.setCenterPoint(connections[i],Pos[i][0],Pos[i][1]);


for i in range(numConnections,numConnections+numNodes):

   pytc.setPos(nodes[i-numConnections],Pos[i][0],Pos[i][1]);


print "layout finished";

No comments: