NREL / PVcircuit

optoelectronic models for tandem/multijunction solar cells
BSD 3-Clause "New" or "Revised" License
14 stars 4 forks source link

Like to make very interactive plotting to fit parameters of real data #4

Open jgeisz opened 2 years ago

jbuencuerpo commented 2 years ago

I have been checking how to solve that. I think the best approach is to use async calls[1], as the simulation to do the fitting typically it won't be less than hundred of ms.

This is the code for the notebook

import matplotlib.pyplot as plt
import numpy as np
import asyncio
import time
%matplotlib widget
from ipywidgets import interact, interactive
def quick_plot(p):
    x = np.linspace(0, 2*np.pi, 200)
    y = np.sin(x/(p))
    time.sleep(0.01) # imagingary thing takes 10 ms

    loop = asyncio.get_event_loop()
    loop.create_task(update(x, y));

fig = plt.figure(figsize=(5,3))
async def update(x, y):
        await asyncio.sleep(0.0)
        plt.clf()
        plt.plot(x, y)
        fig.canvas.draw()
ui = interactive(quick_plot,p=(0.01,2,0.01))
display(ui)

The other option to do it even faster is to use blit to avoid re-draw[2]-[3]. But instead of going that route, what I think it will be better is to encapsulate this on a class or similar for future use.

[1]https://stackoverflow.com/questions/63384326/how-to-update-interactive-figure-in-loop-with-jupyterlab/63517891#63517891 [2] https://stackoverflow.com/questions/40126176/fast-live-plotting-in-matplotlib-pyplot [3]https://matplotlib.org/stable/tutorials/advanced/blitting.html

jbuencuerpo commented 2 years ago

Or maybe check this library, that apparently does that for different types of plots.

mpl-interactions

jgeisz commented 2 years ago

I made the Multi2T plots interactive with controls. Didn't need to use asyncio, just replaced the data in each line after recalculating. These examples helped me better understand matplotlib. Thanks Jero!

jgeisz commented 2 years ago

Tandem3T plots are also now interactive with controls. Fast fit calculations are performed as controls are changed. Slower fit calculations are only performed when button is pushed. I did not use asyncio yet, but this may help smooth plot changes and prevent making changes during long calculations. Please try it out and let me know if it works for you.