"""Embeddable diagram window for Python 3 Tkinter
Class Plotwindow()
    Inst.: 
        pw=Plotwindow(master,(width,height))
        width, height in mm
    Methods:
        plotxy(x,y)     x,y as numpy vectors
        clearplot()     clear data curves, leave coordinates untouched
        settext(title, xlabel, ylabel)
Class Generatetestdata() 
    Methods:
        x,y=getxy()     get a new set of x,y vectors 

version 0.1  14.11.2018 by jean-claude.feltes@education.lu        
"""
#-------------------------------------------------------------------------------------


import tkinter as tk

# Tkinter backend for matplotlib:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg      ##, NavigationToolbar2TkAgg

# implement the default mpl key bindings:
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

import numpy as np


      
#-------------------------------------------------------------------
class Plotwindow():
    def __init__(self, masterframe, size): 
        """Create diagram window with size = (width, height) in mm"""
        
        (w,h)=size    
        inchsize=(w/25.4, h/25.4)
        self.figure = Figure(inchsize)
        self.axes = self.figure.add_subplot(111)
        
        # create canvas as matplotlib drawing area
        self.canvas = FigureCanvasTkAgg(self.figure, master=masterframe)
        self.canvas.get_tk_widget().pack()
        
    def plotxy(self, x, y):
        """Plot vectors y=f(x)"""
        self.axes.plot(x,y)
        self.canvas.draw()    
        
    def clearplot(self):
        """Clear plotted curves"""
        self.axes.cla()
        self.canvas.draw()  
        
    def settext(self, title, xlabel, ylabel):
        """ set title and labels for x and y"""
        self.axes.set_title(title)
        self.axes.set_xlabel(xlabel)
        self.axes.set_ylabel(ylabel)
        self.canvas.draw()     
#-----------------------------------------------------------------------

class Generatetestdata():
    """Generates a new set of test data each time the getxy function is called"""
    def __init__(self):
        """Create test data generator with properties
            .index = index of getxy function call
            .xmin, .xmax = limits x
            .nbvalues = number of data points
            .xinc = increment of xmax each time getxy is called
        """    
        self.index=1        # 
        self.xmin=0.0
        self.xmax=10.0
        self.nbvalues=500
        self.xinc=0
        
    def getxy(self):
        """returns x,y as numpy vectors 
           Damped sine wave with increased damping every time
           the getxy function is called
        """   
        n=self.index
        x=np.linspace(self.xmin, self.xmax, self.nbvalues)
        y=np.sin(4*x)*np.exp(-n*x/10)
        self.index+=1   
        self.xmax+=self.xinc
        return x,y            
#-------------------------------------------------------------------

""" TEST PROGRAM """
    
def plotdata():
    x,y=datgen.getxy()
    pw.plotxy(x,y)
    
def clear():
    pw.clearplot()
        
if __name__ == "__main__":  
   
    datgen = Generatetestdata()
    
    root = tk.Tk()
    
    mf= tk.Frame()
    pw=Plotwindow(mf,(200,150))
    pw.settext("Damped sine wave", "X", "Y")
    mf.pack()
      
    
    bf=tk.Frame()
    b1=tk.Button(bf,text="Plot", command=plotdata)
    b1.pack(side=tk.LEFT)
    b2=tk.Button(bf,text="Clear", command=clear)
    b2.pack(side=tk.LEFT)
    bf.pack()
    
    plotdata()
    
    root.mainloop()
        
        
