asyncionetworkxFuncAnimation学习--动态显示计算图的运行情况

本文主要是介绍asyncionetworkxFuncAnimation学习--动态显示计算图的运行情况,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

asyncio&networkx&FuncAnimation学习--动态显示计算图的运行情况

  • 一.效果
  • 二.代码

一.目的
1.动态显示计算图的运行状态(点或边是否已完成)
二.步骤:
1.定义计算图
2.asyncio 并行计算
3.networkx 显示计算图
4.FuncAnimation 动态更新
三.依赖:
conda install pygraphviz

一.效果

请添加图片描述

二.代码

# -*- coding: utf-8 -*-'''
一.目的
1.动态显示计算图的运行状态(点或边是否已完成)
二.步骤:
1.定义计算图
2.asyncio 并行计算
3.networkx 显示计算图
4.FuncAnimation 动态更新
三.依赖:
conda install pygraphviz
'''import networkx as nx
import matplotlib.pyplot as plt
import asyncio
from matplotlib.animation import FuncAnimation
import asyncio
import datetime
import numpy as np
import threading
from io import BytesIO
from PIL import Imageclass Node:'''节点信息'''event_man = {}node_refs = {}    def __init__(self, name, inputs,callback) -> None:self.name = nameself.event_man = Node.event_manself.callback = callbackself.node_refs = Node.node_refsself.event_man[self.name] = Noneself.node_refs[self.name] = inputsself.delay = np.random.randint(1, 5)async def run(self):# 等待上游节点for ev in self.node_refs[self.name]:await self.event_man[ev].wait()self.callback((ev, self.name), "edge")# 模拟耗时await asyncio.sleep(self.delay)# 触发下游节点self.callback(f"{self.name}", "node")self.event_man[self.name].set()if __name__ == "__main__":G = nx.DiGraph()node_colors = {}edge_colors = {}semaphore = threading.Semaphore(0)def event_callback(name, event):print(datetime.datetime.now().strftime("%H:%M:%S.%f"), name)# 修改节点或边的颜色if event == "node":node_colors[name] = "red"elif event == "edge":edge_colors[name] = "red"semaphore.release()graph_nodes = []graph_nodes.append(Node("A", [], event_callback))graph_nodes.append(Node("B", ["A"], event_callback))graph_nodes.append(Node("B1", ["B"], event_callback))graph_nodes.append(Node("B2", ["B1"], event_callback))graph_nodes.append(Node("B3", ["B2"], event_callback))graph_nodes.append(Node("B4", ["B2"], event_callback))graph_nodes.append(Node("C", ["A"], event_callback))graph_nodes.append(Node("D", ["B4", "B3", "C"], event_callback))# 添加节点for x in graph_nodes:G.add_node(x.name, name=x.name, color="green")# 添加边for k, v in Node.node_refs.items():for j in v:G.add_edge(j, k, name=f"{j}->{k}", color="green")# 设置layoutfor layer, nodes in enumerate(nx.topological_generations(G)):for node in nodes:G.nodes[node]["layer"] = layer#pos = nx.multipartite_layout(G, subset_key="layer")pos = nx.nx_agraph.pygraphviz_layout(G, prog='dot') #垂直布局node_labels = nx.get_node_attributes(G, 'name')edge_labels = nx.get_edge_attributes(G, 'name')node_colors = nx.get_node_attributes(G, 'color')edge_colors = nx.get_edge_attributes(G, 'color')async def graph_forward(nodes):global node_colorsglobal edge_colorsnode_colors = nx.get_node_attributes(G, 'color')edge_colors = nx.get_edge_attributes(G, 'color')for k in Node.event_man.keys():Node.event_man[k] = asyncio.Event()        await asyncio.gather(*[asyncio.create_task(x.run()) for x in nodes])fig = plt.figure(figsize=(6,12))snapshots = []def fig_update(data):semaphore.acquire() #有事件触发才更新nx.draw_networkx_labels(G, pos, labels=node_labels)nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)nx.draw_networkx(G, pos,nodelist=node_colors.keys(),node_color=node_colors.values(),edgelist=edge_colors.keys(),edge_color=edge_colors.values())# 截图buf = BytesIO()plt.savefig(buf, format='png')buf.seek(0)pil_image = Image.open(buf)snapshots.append(pil_image)ani = FuncAnimation(fig, fig_update, interval=100)def trigger(snapshots):while True:asyncio.run(graph_forward(graph_nodes))# 保存gifsnapshots[1].save("out.gif",save_all=True,append_images=snapshots[2:],duration=500,loop=0)print("Finished")breakt=threading.Thread(target=trigger, args=(snapshots,))t.setDaemon(True)t.start()plt.show()

这篇关于asyncionetworkxFuncAnimation学习--动态显示计算图的运行情况的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/954755

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Java -jar命令如何运行外部依赖JAR包

《Java-jar命令如何运行外部依赖JAR包》在Java应用部署中,java-jar命令是启动可执行JAR包的标准方式,但当应用需要依赖外部JAR文件时,直接使用java-jar会面临类加载困... 目录引言:外部依赖JAR的必要性一、问题本质:类加载机制的限制1. Java -jar的默认行为2. 类加

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

宝塔安装的MySQL无法连接的情况及解决方案

《宝塔安装的MySQL无法连接的情况及解决方案》宝塔面板是一款流行的服务器管理工具,其中集成的MySQL数据库有时会出现连接问题,本文详细介绍两种最常见的MySQL连接错误:“1130-Hostisn... 目录一、错误 1130:Host ‘xxx.xxx.xxx.xxx’ is not allowed

使用nohup和--remove-source-files在后台运行rsync并记录日志方式

《使用nohup和--remove-source-files在后台运行rsync并记录日志方式》:本文主要介绍使用nohup和--remove-source-files在后台运行rsync并记录日... 目录一、什么是 --remove-source-files?二、示例命令三、命令详解1. nohup2.

Java计算经纬度距离的示例代码

《Java计算经纬度距离的示例代码》在Java中计算两个经纬度之间的距离,可以使用多种方法(代码示例均返回米为单位),文中整理了常用的5种方法,感兴趣的小伙伴可以了解一下... 目录1. Haversine公式(中等精度,推荐通用场景)2. 球面余弦定理(简单但精度较低)3. Vincenty公式(高精度,

Spring Boot项目打包和运行的操作方法

《SpringBoot项目打包和运行的操作方法》SpringBoot应用内嵌了Web服务器,所以基于SpringBoot开发的web应用也可以独立运行,无须部署到其他Web服务器中,下面以打包dem... 目录一、打包为JAR包并运行1.打包为可执行的 JAR 包2.运行 JAR 包二、打包为WAR包并运行