python 仿真实验_生成仿真的演化网络实验【Python版】
''' 繪制動畫
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import networkx as nx
import random
fig, ax = plt.subplots()
G = nx.Graph()
G.add_edge(0,1)
def init_network():
# nx.draw(G, node_size=10, node_color='c')
return G,
def animate_network(i):
# 定義網絡動態變化的幾種形式,分別代表刪除邊,刪除節點,維持不動,增加節點,增加邊
d = [-2, -1, 0, 1, 2]
# 從中隨機選擇一種操作
c = random.randint(0,len(d)-1)
edges = list(G.edges())
nodes = list(G.nodes())
if d[c] == -2:
if edges:
u,v = random.choice(edges)
G.remove_edge(u,v)
if d[c] == -1:
if nodes:
node = random.choice(nodes)
G.remove_node(node)
if d[c] == 0:
# 網絡不發生變化
pass
if d[c] == 1:
G.add_node(len(nodes))
if d[c] == 2:
if nodes:
G.add_edge(len(nodes), random.choice(nodes))
nx.draw(G, pos = nx.spring_layout(G), node_size=10, node_color='c',edge_color='grey')
return G,
ani = animation.FuncAnimation(fig=fig, func=animate_network, frames=30, init_func=init_network, interval=100, blit=False,)
ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
總結
以上是生活随笔為你收集整理的python 仿真实验_生成仿真的演化网络实验【Python版】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python文件操作与异常处理_Pyth
- 下一篇: 限制python内存上限_Python限