如何解决使用Mesa和Networkx可视化代理
我目前正在使用Mesa和Networkx进行多代理路径查找。节点表示在一个时间点只能驻留1个代理的位置。边缘代表节点之间的距离。如何可视化每个时间步长代理沿着边缘的移动?例如,在时间步长= 4处,代理A位于连接节点1和2的边缘中间。
解决方法
我猜您想使用networkx
和matplotlib
在节点之间绘制一些代理遍历。
import matplotlib.pyplot as plt
import networkx as nx
import matplotlib.animation as animation
import matplotlib
import numpy as np
matplotlib.use('TkAgg')
plt.ion()
H = nx.octahedral_graph() # generate a random graph
pos = nx.spring_layout(H,iterations=200) # find good positions for nodes
为此,首先我们需要在遍历时了解代理在每个步骤或框架中的位置。如果我们假设每个节点(或每个边缘)之间有50步,我们可以编写一个生成器来更新代理在每个帧中的位置:
def traverse(graph,start,end,steps_between_nodes=50):
"""Generate the new position of the agent.
:param graph: the graph you want to put your agent to traverse on.
:param start: the node to start from.
:param end: the node to end at.
:param steps_between_nodes: number of steps on each edge.
"""
steps = np.linspace(0,1,steps_between_nodes)
# find the best path from start to end
path = nx.shortest_path(graph,source=start,target=end)
stops = np.empty((0,2))
for i,j in zip(path[1:],path):
# get the position of the agent at each step
new_stops = steps[...,None] * pos[i] + (1 - steps[...,None]) * pos[j]
stops = np.vstack((stops,new_stops))
for s in stops:
yield s
然后我们可以对其进行如下动画设置:
agent_pos = traverse(H,4) # make an agent traversing from 1 to 4
def update_position(n):
plt.cla()
nx.draw(H,pos,node_size=700,with_labels=True,node_color='green')
c = plt.Circle(next(agent_pos),0.05,color='purple',zorder=2,alpha=0.7)
plt.gca().add_patch(c)
ani = animation.FuncAnimation(plt.gcf(),update_position,interval=30,repeat=False)
plt.ioff()
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。