I wish to run a simulation while at the same time output its progress in a plot. I've been looking through a lot of examples of threading and multiprocessing, but they are all pretty complex. So I thought with Python's new asyncio library this should be easier.
I found an example (How to use 'yield' inside async function?) and modified it for my cause:
import matplotlib.pyplot as plt import asyncio import numpy as np class DataAnalysis(): def __init__(self): # asyncio so we can plot data and run simulation in parallel loop = asyncio.get_event_loop() try: loop.run_until_complete(self.plot_reward()) finally: loop.run_until_complete( loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.shutdown_asyncgens loop.close() async def async_generator(self): for i in range(3): await asyncio.sleep(.4) yield i * i async def plot_reward(self): # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') #plt.show() # add lines to plot async for i in self.async_generator(): print(i) # Show the plot plt.show() if __name__ == '__main__': DataAnalysis() Question
I added a simple plt.show() and the program still freezes. I thought with asyncio I could run it in parallel? Obviously my knowledge is still lacking. An example that does the following would be really helpful:
- Add a line to a plot (of
matplotlib) everytimeasync_generatorreturns a value.