使用我自己的力导向算法与Networkx

时间:2014-09-20 14:55:38

标签: algorithm graph-algorithm networkx

我正在尝试使用我正在编写的强制定向算法。我没有使用Networkx附带的那个,因为我们想稍后为了我们自己的目的修改它。目前,当我运行它时,我在第54行得到“结果太大”的错误。知道为什么会这样吗?

import math
import networkx as nx
import matplotlib.pyplot as plt

node_data = {0:[0,0], 1:[0,0], 2:[0,0], 3:[0,0], 4:[0,0], 5:[0,0], 6:[0,0], 7:[0,0]}
graph = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7)]
pi = 3.14159265358979323
k = 1 # number of the node, ie the Kth node

# assign nodes an initial position evenly spaced around the unit circle
for key, value in node_data.items():
    value[0] = math.cos((2 * pi * k) / len(node_data))
    value[1] = math.sin((2 * pi * k) / len(node_data))
    k += 1


#print node_data[0]
for i in range(0,600):

    # repulsion forces
    for key, value in node_data.items(): 
        for key1, value1 in node_data.items():
            if key1 > key:
                # compare the x, y values of every element to every other 
                x0 = value[0]
                y0 = value[1]
                x1 = value1[0]
                y1 = value1[1]
                # compute repulsion force for each node
                krepel = 0.001
                frepel = krepel / math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
                theta = math.atan((y1 - y0) / (x1 - x0))
                # update x and y values
                value[0] -= frepel * math.cos(theta)
                value[1] -= frepel * math.sin(theta)
                value1[0] += frepel * math.cos(theta)
                value1[1] += frepel * math.sin(theta)

    #print node_data[0]

    # attractive forces

    for e in graph:
        # compare nodes with nodes they are connected to
        n0 = node_data[e[0]] 
        n1 = node_data[e[1]]
        x0 = n0[0]
        y0 = n0[1]
        x1 = n1[0]
        y1 = n1[1]

        # compute fattract
        kattract = 0.001
        fattract = kattract * ((x1 - x0) ** 2 + (y1 + y0) ** 2)
        theta = math.atan((y1 - y0) / (x1 - x0))
        # update x and y values
        n0[0] += fattract * math.cos(theta)
        n0[1] += fattract * math.sin(theta)
        n1[0] -= fattract * math.cos(theta)
        n1[1] -= fattract * math.sin(theta)

        #print node_data[0]

G = nx.Graph()

# add node

for key, value in node_data.items():   
    G.add_node(key, posxy=(value[0], value[1]))

# add edges
for e in graph:
    G.add_edge(e[0], e[1])

print G.nodes()
print G.edges()
pos = nx.get_node_attributes(G, 'posxy')       

# draw graph

nx.draw(G, pos)

# show graph
plt.show()

0 个答案:

没有答案