image
LP小透明

当你感到无聊的时候,就去学习,因为一旦你开始认真学习,就会立刻发现比学习有趣的事来打断你的学习

生成仿真的演化网络实验【Python版】

LP小透明    2018-11-19 21:29

 

''' 绘制动画 
'''
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()

Views: 1.9K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment