# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/09_plotting.ipynb.

# %% auto 0
__all__ = ['SubPlotter', 'run_hpct_animation']

# %% ../nbs/09_plotting.ipynb 3
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from random import random

# %% ../nbs/09_plotting.ipynb 4
class SubPlotter(object):

  def __init__(self, width, height, title, plotsconfig=[["title", "xlabel", "ylabel", 1, 0, 111, ['line1']]], 
               linewidth=2, legend_fontsize=8):
    self.linewidth=linewidth
    self.legend_fontsize=legend_fontsize
    style.use('fivethirtyeight')
    self.fig = plt.figure(figsize=[width, height])
    #self.fig.canvas.set_window_title(title)
    
    self.plots=[]
    self.colors=['b',  'r', 'g', 'c', 'm', 'y', 'k', 'w']

    for plotconfig in plotsconfig:
        #print(plotconfig)
        ys=[]
        for line in range(plotconfig[3]):
            ys.append([])
            
        plot = dict([("title", plotconfig[0]), ("xlabel", plotconfig[1]), 
                     ("ylabel", plotconfig[2]), ("window", plotconfig[4]), 
                     ("subplot", plt.subplot(plotconfig[5])), ("x", []), ("ys", ys),
                     ("lines", plotconfig[6])])

        self.plots.append(plot)
    
  def add_data(self, index, x, ys):
    #print(ys)
    plot= self.plots[index]
    plot["x"].append(x)
    for i in range(len(ys)):
        plot["ys"][i].append(ys[i])
    window = plot["window"]
    if window > 0:
        if x > window:
            plot["x"].pop(0)
            for i in range(len(ys)):
                plot["ys"][i].pop(0)
            
  def add_history_data(self, x, data):
    for index, plot in enumerate(self.plots):
        yvals = []
        for line in plot["lines"]:
            y = data[line][-1]
            yvals.append(y)
        self.add_data(index, x, yvals)

  def show(self):
    plt.show()
        
  def draw(self):
    for plot in self.plots:
        plot["subplot"].clear()
        #print(plot["ys"])
        ctr=0
        for y, line in zip(plot["ys"], plot["lines"]):
            plot["subplot"].plot(plot["x"], y, self.colors[ctr], label=line, linewidth=self.linewidth)
            ctr+=1
        plot["subplot"].set_title(plot["title"])
        plot["subplot"].set_xlabel(plot["xlabel"])
        plot["subplot"].set_ylabel(plot["ylabel"])
        plot["subplot"].legend(fontsize=self.legend_fontsize)

    plt.tight_layout()

# %% ../nbs/09_plotting.ipynb 5
def run_hpct_animation(hpct, counter=None, plotter=None, interval=1, verbose=False):
    anim_running = True
    
    def onClick(event):
            nonlocal anim_running
            if anim_running:
                anim.event_source.stop()
                anim_running = False

            else:
                anim.event_source.start()
                anim_running = True
                
    
    def animate(epoch):
        nonlocal anim_running
        if epoch>0:
            if epoch <= counter.get_limit():
                counter()
                if counter.pause and counter.get() % counter.display == 0:
                    #print(counter.get(), counter.display)
                    anim_running = False
                    anim.event_source.stop()
                else:
                    x = counter.get()
                    hpct.run(steps=1, verbose=verbose)                    
                    history = hpct.get_history_data()
                    plotter.add_history_data(x, history)
                    plotter.draw()
        else:
            pass#print("init here", epoch)
    
    plotter.fig.canvas.mpl_connect('button_press_event', onClick)
 
    anim = animation.FuncAnimation(plotter.fig, animate, interval=interval, repeat=False)
