刚刚开始学习网络科学,我是 Python 新手,所以即使在阅读了大量的 networkx 文档后,我也很难弄清楚这一点。我需要比较所有节点之间的距离,并在距离小于 d 时生成一条边。
1) 如何将节点 1 与节点 (2...99) 进行比较,然后将节点 2 与节点 (3...99) 进行比较,依此类推。如果有比 O(n^ 更好的方法) 2)请告诉我。
2) 如何使用存储在node_loc{}中的x,y坐标将每个节点绘制到坐标平面?
import random, math
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pylab
# Calc distance given (x1,x2,y1,y2)
def distance(x1,x2,y1,y2):
return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
# Generate coordinate value
def coord_val():
# node needs x and y coordinates (floats) from 0->100
return random.uniform(0.0,100.0)
def main():
# The distance that applies to link generation
d = 20
# Make a graph and name it
g = nx.Graph(name = "100x100 Field Random Network")
# Generate 100 nodes
for num in range(0,100):
# generate a dict with the node's location
node_loc = {'x': coord_val(), 'y': coord_val()}
# Add node with x,y dict
g.add_node(num,node_loc)
# Check node n against node n+1
for n,d in g.nodes(data=True):
if n == 99:
break
# I don't think this loop is correct
for rl in g.nodes(data=True):
# Don't go out of bounds on the loop
if n == 99:
break
# grab coordinates from nodes
y1=g.node[n]['y']
x1=g.node[n]['x']
y2=g.node[n+1]['y']
x2=g.node[n+1]['x']
# Check the distance, if < d, generate edge
if distance(x1,x2,y1,y2) < d:
# add edge
g.add_edge(n,n+1)
# plot
# draw_random draws it on a plane, but randomly :(
nx.draw_random(g,node_size=50)
plt.show()
if __name__ == '__main__':
main()
NetworkX有nx.grid_2d_graph
,一个Graph generator ,返回 mxn 节点的二维网格图,每个节点都连接到其最近的邻居。默认情况下,其标签将是网格的坐标。
如果我们有兴趣将节点作为坐标,我们可以旋转位置,使原点位于左上角。否则你可以保持原样。这是一个例子:
import networkx as nx
from matplotlib import pyplot as plt
G = nx.grid_2d_graph(3,3)
plt.figure(figsize=(6,6))
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos,
node_color='lightgreen',
with_labels=True,
node_size=600)
请注意,nx.grid_2d_graph
将生成具有任意大的 m
和 n
的网格图,通过定位标签,您可以也如上所示绘制坐标网格:
我是一名优秀的程序员,十分优秀!