示例#1
0
def Video():
    image1 = video.read(0)[1]
    axis1.imshow(image1)
    canvas1 = FigureCanvasTkAgg(videoFigure, master=window)
    canvas1.show()
    canvas1.get_tk_widget().pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)
    canvas1._tkcanvas.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)
def _plot(self, x,y):
	root = Tk.Tk()
	root.wm_title("")


	f = Figure(figsize=(6,6), dpi=100)
	a = f.add_subplot(111)
	t = arange(0.0,3.0,0.01)
	s = sin(2*pi*t)

	a.plot(t,s)


	# a tk.DrawingArea
	canvas = FigureCanvasTkAgg(f, master=root)
	canvas.show()
	canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

	toolbar = NavigationToolbar2TkAgg( canvas, root )
	toolbar.update()
	canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

	def _quit():
    	root.quit()     # stops mainloop
    	root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

	button = Tk.Button(master=root, text='Quit', command=_quit)
	button.pack(side=Tk.BOTTOM)

	Tk.mainloop()
	# If you put root.destroy() here, it will cause an error if
	# the window is closed with the window manager.
示例#3
0
    def __init__(self, x, y):
        f = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
        # f = matplotlib.figure.Figure(dpi=100)
        ax = f.add_subplot(111)
        canvas = ax.figure.canvas

        line, = p.plot(x, y, animated=True, lw=2)

        canvas = FigureCanvasTkAgg(f, master=root)
        canvas.show()

        canvas.get_tk_widget().grid()

        toolbar = NavigationToolbar2TkAgg(canvas, root)
        toolbar.update()

        canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        p.subplots_adjust(left=-0.1, bottom=0.0)
        manager = p.get_current_fig_manager()
        manager.window.after(100, self.run)

        self.canvas = canvas
        self.ax = ax
        self.line = line
        self.x = x
        self.y = y
示例#4
0
    def DrawImagePlot(rootApp,
                      imageSource,
                      name="SourcePlot",
                      text="SourceImage",
                      position=(10, 10),
                      padX=0, padY=0,
                      sticky=(tk.W, tk.E), columnSpan=1, rowSpan=1,
                      owner=None):

        if owner == None:
            owner = rootApp

        fig = plt.figure(num=name, figsize=(2.5, 2.5))
        ax = fig.add_subplot(1, 1, 1)

        ax.imshow(imageSource)
        ax.set_title(text)
        canvas = FigureCanvasTkAgg(fig, master=owner)
        canvas.get_tk_widget().grid(row=position[0], column=position[1],
                                    padx=padX, pady=padY,
                                    columnspan=columnSpan, rowspan=rowSpan,
                                    sticky=sticky)

        canvas.show()
        rootApp.controls[name] = canvas.get_tk_widget()
  def __init__(self,parent,controller):
    
    tk.Frame.__init__(self,parent)
    label = tk.Label(self, text="Graph Page", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button1 = ttk.Button(self,text="Back to Home",
        command=lambda: controller.show_frame(StartPage))

    button1.pack()

    button2 = tk.Button(self,text="Page One",
        command=lambda: controller.show_frame(PageOne))

    button2.pack()

    button3 = tk.Button(self,text="Page Two",
        command=lambda: controller.show_frame(PageTwo))

    button3.pack()

    canvas = FigureCanvasTkAgg(f, self)
    canvas.show()
    canvas.get_tk_widget().pack(side=tk.TOP,fill=tk.BOTH, expand = True)

    toolbar = NavigationToolbar2TkAgg(canvas, self)
    toolbar.update()
    canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH, expand = True)
示例#6
0
class TriGUI:

	def __init__(self,root,canvas_width,canvas_height):
		self.root=root
		self.canvas_width = canvas_width
		self.canvas_height = canvas_height

		self.moduli_space = {'vertices':np.array([[0.,0.],[1.,0.],[0.5,np.sqrt(3.)/2.]]),'triangles':[0,1,2]}

		self.fig, self.ax = mpl.pyplot.subplots()
		self.ax.clear()
		self.ax.autoscale(enable=False)
		self.ax.axis('off')
		self.canvas = FigureCanvasTkAgg(self.fig,master=root)
		self.canvas.show()
		self.canvas.get_tk_widget().pack()

		X = self.moduli_space['vertices'][:,0]
		Y = self.moduli_space['vertices'][:,1]
		outline = tri.Triangulation(X,Y)
		self.ax.triplot(outline)

		#self.canvas.mpl_connect("button_press_event", self.setVertex)

	def quite(self):
		self.root.destroy()
    def cria_grafi_cqi(self):
        global lista_cqi, flag_plot_cqi, flag_stop, x_linha
        fig2 = pylab.figure(2)
        ax2 = fig2.add_axes([0.1,0.1,0.8,0.8])
        ax2.grid(True)
        ax2.set_title("RealTime plot FAPI - CQI INDICATION")
        ax2.set_xlabel("Time")
        ax2.set_ylabel("Amplitude")
        ax2.axis([0,1000,0,100])
        line2, = pylab.plot(lista_cqi)

        canvas2 = FigureCanvasTkAgg(fig2, master=self.parent)
        canvas2.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
        canvas2.show()
        toolbar2 = NavigationToolbar2TkAgg( canvas2, self.parent)
        toolbar2.update()
        canvas2._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
        ########################################################################
        #                         Geracao do grafico                           #
        ########################################################################
        while flag_stop == False:

            delete_cqi()
            lista_cqi.extendleft(valor_plot_cqi)
            line2.set_ydata(lista_cqi)
            canvas2.draw()
示例#8
0
    def __init__(self, parent, controller):
        time.sleep(2)
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text='Before we begin, lets have a quick tutorial! \n\n'
               'This simulation is designed to mimic that of the decline in real life, which is effecting us in ways '
               'we can\'t understand today...\n ', font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        f = Figure(figsize=(10,5), dpi=100)
        a = f.add_subplot(111)
        a.plot([1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960,
                1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976,
                1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992,
                1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
                2009, 2010],
               [5500000, 5500000, 5430000, 5420000, 5425032, 5433200, 5503020, 5500030,
                5435476, 5365343, 5322342, 5433454, 5762638, 5626379, 5533450, 5505032,
                5325374, 5229382, 5332534, 5442435, 5632436, 5225356, 5354252, 5543344,
                5544345, 5533453, 5433453, 5335344, 5345473, 5222223, 5199872, 5203002,
                5102293, 5100330, 5093929, 5022332, 4999221, 4922322, 4822828, 4789800,
                4733723, 4636364, 4444323, 4478779, 4422302, 4122321, 3999212, 4002293,
                3888182, 3772373, 3642069, 3444333, 3220032, 3002230, 2883292, 2992283,
                3322332, 3441422, 3322332, 2993828, 2777283, 2633543, 2339862, 2122039,
                2100293, 2003993], 'g')

        title = "Bee Population Decline Since 1945 (Bee Hives In Millions)"
        a.set_title(title)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        button1 = tk.Button(self, text="Next", command=lambda:controller.show_frame(TutorialThree))
        button1.pack()
示例#9
0
文件: main.py 项目: cuixiongyi/RBE595
class Application(tk.Frame):
    def __init__(self, master=None):
        matplotlib.use('TkAgg')
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()



    def createWidgets(self):

        self.fig = Figure(figsize=(5,4), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, self)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0, columnspan=3)
        sim = Simulator.Simulator.Simulator(self.fig, self.canvas)
        # sim.run()
        self.timer = Periodic(0.3, sim.run)
        self.timer.start()



        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.grid(row=2)
示例#10
0
class TelescopeEventView(tk.Frame, object):
    """ A frame showing the camera view of a single telescope """

    def __init__(self, root, telescope, data=None, *args, **kwargs):
        self.telescope = telescope
        super(TelescopeEventView, self).__init__(root)
        self.figure = Figure(figsize=(5, 5), facecolor='none')
        self.ax = Axes(self.figure, [0, 0, 1, 1], aspect=1)
        self.ax.set_axis_off()
        self.figure.add_axes(self.ax)
        self.camera_plot = CameraPlot(telescope, self.ax, data, *args, **kwargs)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        self.canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
        self.canvas._tkcanvas.config(highlightthickness=0)

    @property
    def data(self):
        return self.camera_plot.data

    @data.setter
    def data(self, value):
        self.camera_plot.data = value
        self.canvas.draw()
示例#11
0
 def __init__(self, root, controller):
     f = Figure()
     ax = f.add_subplot(111)
     ax.set_xticks([])
     ax.set_yticks([])
     ax.set_xlim((x_min, x_max))
     ax.set_ylim((y_min, y_max))
     canvas = FigureCanvasTkAgg(f, master=root)
     canvas.show()
     canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     canvas.mpl_connect('key_press_event', self.onkeypress)
     canvas.mpl_connect('key_release_event', self.onkeyrelease)
     canvas.mpl_connect('button_press_event', self.onclick)
     toolbar = NavigationToolbar2TkAgg(canvas, root)
     toolbar.update()
     self.shift_down = False
     self.controllbar = ControllBar(root, controller)
     self.f = f
     self.ax = ax
     self.canvas = canvas
     self.controller = controller
     self.contours = []
     self.c_labels = None
     self.plot_kernels()
示例#12
0
class App:
    def __init__(self, master, figure):
        # Create a container
        frame = tkinter.Frame(master)
        # Create 2 buttons
        self.button_left = tkinter.Button(frame, text="< Decrease Slope",
                                          command=self.decrease)
        self.button_left.pack(side="left")
        self.button_right = tkinter.Button(frame, text="Increase Slope >",
                                           command=self.increase)
        self.button_right.pack(side="left")

        # fig = Figure()
        ax = figure.add_subplot(212)
        self.line, = ax.plot(range(10))

        self.canvas = FigureCanvasTkAgg(figure, master=master)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        frame.pack()

    def decrease(self):
        x, y = self.line.get_data()
        self.line.set_ydata(y - 0.2 * x)
        self.canvas.draw()

    def increase(self):
        x, y = self.line.get_data()
        self.line.set_ydata(y + 0.2 * x)
        self.canvas.draw()
class PlotClass:
    def __init__(self,master=[]):
        
        self.master=master
 
        #Erstellen des Fensters mit Rahmen und Canvas
        self.figure = Figure(figsize=(7,7), dpi=100)
        self.frame_c=Frame(relief = GROOVE,bd = 2)
        self.frame_c.pack(fill=BOTH, expand=1,)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.frame_c)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=1)

        #Erstellen der Toolbar unten
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame_c)
        self.toolbar.update()
        self.canvas._tkcanvas.pack( fill=BOTH, expand=1)

    def make_erg_plot(self,kegelst):
        self.plot1 = self.figure.add_subplot(111)
        self.plot1.set_title("Kegelstumpf Abwicklung")

        self.plot1.hold(True)

        for geo in kegelst.geo:
            geo.plot2plot(self.plot1)
示例#14
0
class GUI_graph_frame(tk.Frame):
    
    def __init__(self, parent, controller):
        # register with controller
        self.name = "graph_frame"
        self.controller = controller
        self.controller.register(self, self.name)                
        tk.Frame.__init__(self, parent, bd=2, relief=tk.FLAT, background="grey")
        
        # create pyplot figure
        self.fig = pyplot.figure()
        self.fig.subplots_adjust(hspace=0.8)
        
        # draw figure and control bar on canvas
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        toolbar = NavigationToolbar2TkAgg( self.canvas, self )
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        
    def plot_data(self, solar_data, sample_stride, title, xlabel, ylabel, xdata, ydata, xfunction=solar_graph.nop, yfunction=solar_graph.nop):                
        self.ax = pyplot.subplot(111)   
        self.solar_graph = solar_graph.graph(self.fig, self.ax, solar_data, sample_stride, title, xlabel, ylabel, xdata, ydata, xfunction, yfunction)          
        self.canvas.show()
示例#15
0
 def __init__(self, parent, controller):
     tk.Frame.__init__(self, parent)
     
     canvas = FigureCanvasTkAgg(f, self)
     canvas.show()
     canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
     canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
示例#16
0
	def plotBERcurve(self):
		row = 0
		berCurveFrame = Tk.Frame(root, borderwidth=2, relief="raised", pady= 15, padx=10)
		berCurveFrame.grid(row = row, column = 4, rowspan = 9, columnspan = 2, sticky = (Tk.N, Tk.W, Tk.E, Tk.S))

		self.calculate = Tk.IntVar()
		self.calculate.set(0)
		calculate = Tk.Checkbutton(berCurveFrame, text="  Calculate", font=("Helvetica", 12), variable = self.calculate).grid(row = 2, column = 21, columnspan = 2, sticky=(Tk.W, Tk.E))

		self.hold = Tk.IntVar()
		self.hold.set(0)
		hold = Tk.Checkbutton(berCurveFrame, text="Hold", font=("Helvetica", 12), variable = self.hold).grid(row = 3, column = 21, columnspan = 2, sticky=(Tk.W, Tk.E))

		f = Figure(figsize=(4.5, 4.5), dpi=100)
		a = f.add_subplot(111)
		t = (1, 2, 3, 4)
		s = (1, 2, 3, 4)
		canvas = FigureCanvasTkAgg(f, berCurveFrame)
		canvas.show()
		canvas.get_tk_widget().grid(row= 1,column = 0,rowspan = 6, columnspan = 6, sticky = (Tk.N, Tk.W, Tk.E, Tk.S))
		a.plot(t, s)
		a.set_title('BER Curve')
		a.set_xlabel('Eb/Nq')
		a.set_ylabel('BER')

		save = Tk.Button(berCurveFrame, text="Save", command = lambda: self.savePlotBER(f), bg = "cyan").grid(row=4, column = 21, columnspan = 2, padx = 15, sticky=(Tk.W, Tk.E))

		clear = Tk.Button(berCurveFrame, text="Clear", command = lambda: self.clearPlot(f), bg = "cyan").grid(row=5, column = 21, columnspan = 2, padx = 15, sticky=(Tk.W, Tk.E))	
示例#17
0
 def attach_figure(figure, frame):
     canvas = FigureCanvasTkAgg(figure, master=frame)  # 内嵌散点图到UI
     canvas.show()
     canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     toolbar = NavigationToolbar2TkAgg(canvas, frame)  # 内嵌散点图工具栏到UI
     toolbar.update()
     canvas.tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
示例#18
0
class Plotter:
    
    __fig = 1
    __splot = 1
    __canvas = 1
    __toolbar = 1

    def __init__(self,tk_root):
        self.__fig = Figure(figsize=(5,5), dpi=100);
        self.__splot = self.__fig.add_subplot(111)
        self.__splot.grid()

        self.__canvas = FigureCanvasTkAgg(self.__fig, master=tk_root)
        self.__canvas.show()
        self.__canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
        self.__toolbar = NavigationToolbar2TkAgg(self.__canvas, tk_root)
        self.__toolbar.update()
        self.__canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def add_to_plot(self,x,y,legend):
        self.__splot.plot(x,y,'.-',label=legend)
        self.__splot.legend()
        self.__canvas.draw()

    def plot_hist(self,data,bins):
        self.__splot.hist(data,bins)
        self.__canvas.draw()
    def plot(self,x,y):
        self.__splot.clear();
        self.__splot.grid()
        self.__splot.plot(x,y)
        self.__canvas.draw()
示例#19
0
    def _layout(self, figure):
        canvas = FigureCanvasTkAgg(figure, master=self)
        canvas.show()
        canvas.get_tk_widget().grid(row=1, column=1)

#       quit_button = Tk.Button(master=self, text="Quit", command=self.quit)
#       quit_button.grid(row=2, column=1)

        coord_frame = Tk.Frame(master=self) 

        p_label = Tk.Label(coord_frame, text="Pressure:")
        t_label = Tk.Label(coord_frame, text="Temperature:")
        self._p_coord = Tk.Label(coord_frame, text="-999.0 hPa", width=10)
        self._t_coord = Tk.Label(coord_frame, text="-999.0 C", width=10)

        p_label.grid(row=1, column=1)
        t_label.grid(row=2, column=1)
        self._p_coord.grid(row=1, column=2)
        self._t_coord.grid(row=2, column=2)

        coord_frame.grid(row=1, column=2)

        canvas.get_tk_widget().bind("<Motion>", self._mouseMove)
        canvas.get_tk_widget().bind("<Button-1>", self._mousePress)
        canvas.get_tk_widget().bind("<ButtonRelease-1>", self._mouseRelease)

        self._buildMenu()
        return
示例#20
0
文件: sobtc_app.py 项目: arante/pyloc
    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="Page three")
        label.pack(padx=10, pady=10)

        button = ttk.Button(self, text="Home",
                command=lambda: controller.show_frame(StartPage))
        button.pack()

        # Data to plot
        #f = Figure(figsize=(5, 5), dpi=100)
        #a = f.add_subplot(111)
        #a.plot([0,1,2,3,4,5,6,7,8], [0,2,7,3,5,1,7,8,2])

        # Create a simple canvas
        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # Navigation bar
        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def PlotGraph(xValues, yValues, labelString):
    ## setup window
    root = Tk()
    root.wm_title("Graphed Projectile")

    ## setup frame
    frame = Frame(root)
    frame.pack()

    label = Label(root, text=labelString, font=("Verdana", 12))
    label.pack(pady=10, padx=10)

    f = Figure(figsize=(5, 5), dpi=100)
    a = f.add_subplot(111)
    a.plot(xValues, yValues)

    canvas = FigureCanvasTkAgg(f, root)
    canvas.show()
    canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

    toolbar = NavigationToolbar2TkAgg(canvas, root)
    toolbar.update()
    canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)

    DataGrid(xValues, yValues)

    root.mainloop()
示例#22
0
def drawFFTAndPath(frame, x, y, freq, amp, titleCoP, titleFFT):
    f = Figure()

    gs = gridspec.GridSpec(1,2,width_ratios=[1,1],height_ratios=[1,1])

    a = f.add_subplot(gs[0])
    img = imread("Images/Wii.JPG")
    a.imshow(img, zorder=0, extent=[-216 - 26, 216 + 26, -114 - 26, 114 + 26])
    a.plot(x, y)
    a.set_title(titleCoP, fontsize=13)
    a.set_xlim([-216 - 30, 216 + 30])
    a.set_ylim([-114 - 30, 114 + 30])
    a.set_ylim([-114 - 30, 114 + 30])
    a.set_xlabel("CoPx (mm)", fontsize=12)
    a.set_ylabel("CoPy (mm)", fontsize=12)

    if amp[0] == 0:
        titleFFT = titleFFT + ' (0Hz filtered)'
    b = f.add_subplot(gs[1])
    b.plot(freq, amp)
    ttl = b.title
    ttl.set_position([.5, 1.05])
    b.set_title(titleFFT, fontsize=12)
    b.set_xlabel("Frequency (Hz)", fontsize=12)
    b.set_ylabel("Amplitude", fontsize=12)

    canvas = FigureCanvasTkAgg(f, frame)
    toolbar = NavigationToolbar2TkAgg(canvas, frame)
    canvas.show()
    canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)
    toolbar.update()
    canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)
 def __init__(self, root, f):
     Tk.Frame.__init__(self, root)
     
     # a tk.DrawingArea
     canvas = FigureCanvasTkAgg(f, root)
     canvas.show()
     canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     
     toolbar = NavigationToolbar2TkAgg(canvas, root)
     toolbar.update()
     canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     
     
     def on_key_event(event):
         print('you pressed %s' % event.key)
         key_press_handler(event, canvas, toolbar)
     
     canvas.mpl_connect('key_press_event', on_key_event)
     
     
     def _quit():
         root.quit()     # stops mainloop
         root.destroy()  # this is necessary on Windows to prevent
                         # Fatal Python Error: PyEval_RestoreThread: NULL tstate
     
     button = Tk.Button(root, text='Quit', command=_quit)
     button.pack(side=Tk.BOTTOM)
示例#24
0
def makeplottk(targetdata):
	from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
	from matplotlib.backend_bases import key_press_handler
	from matplotlib.figure import Figure
	for i in range(0,len(targetdata)):
		targetdata[i]['data'][0]=[(j-2400000) for j in targetdata[i]['data'][0]]
	numplots=len(targetdata)
#this is where its different thatn makeplot, we need to set up the tk enviornment etc
	root=Tk()
	root.wm_title(targetdata[0]['name'])
	f=Figure(figsize=(10,8))
	for i in range(0,numplots):
		a=f.add_subplot(numplots,1,i+1)
		a.plot(targetdata[i]['data'][0],targetdata[i]['data'][1], 'ro')
		a.axes.invert_yaxis()
		a.legend(targetdata[i]['flt'])
	canvas=FigureCanvasTkAgg(f, master=root)
	canvas.show()
	canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
#now to add the cool widget bar
	toolbar = NavigationToolbar2TkAgg( canvas, root )
	toolbar.update()
	canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
	mainloop()
	return
示例#25
0
    def __init__(self, graph_frame, graph_config, graph_values):
        """
        graph_frame: tk frame to hold the graph_frame
        graph_config: configuration that was set from xml config parse
        graph_values: values that were generated as a result of graph config
        """ 
        self.logger = logging.getLogger('RT_Plot')
        self.logger.debug('__init__')


        # Create Line
        self.data_line = Line2D([],[])

        # Create plot
        self.plot_holder = Figure(figsize=(graph_values['x'], graph_values['y']), dpi=graph_values['dpi']) 
        self.rt_plot = self.plot_holder.add_subplot(111)
        self.rt_plot.add_line(self.data_line)
        
        # Set Title Configuration
        self.rt_plot.set_ylabel(graph_config['y_title']) 
        self.rt_plot.set_xlabel(graph_config['x_title']) 
        self.plot_holder.suptitle(graph_config['main_title'], fontsize=16)

        # Autoscale on unknown axis 
        self.rt_plot.set_autoscaley_on(True)
        self.rt_plot.set_autoscalex_on(True)
        # Set x limits?

        # Create canvas
        canvas = FigureCanvasTkAgg(self.plot_holder, master=graph_frame)
        canvas.show()
        # Attach canvas to graph frame
        canvas.get_tk_widget().grid(row=0, column=0)
示例#26
0
    def DrawAxisArray(rootApp, name="SourcePlot",
                      text="Signal View'",
                      xLabel="time (s)",
                      yLabel="voltage (mV)",
                      position=(10, 10),
                      padX=0, padY=0,
                      sticky=(tk.S, tk.W), columnSpan=1, rowSpan=1,nrows = 2, ncols = 2,
                      owner=None):
        if owner == None:
            owner = rootApp
        fig, axis_array = plt.subplots(nrows, ncols)
        plt.tight_layout()

        for i in range(nrows):
            for j in range(ncols):
                axis_array[i, j].grid('on')
                axis_array[i, j].set(
                    title='AX [{0},{1}] - Not Initialized!'.format(i, j))
        axis_array[0, 0].set(title='Workspace Signals')
        canvas = FigureCanvasTkAgg(fig, master=owner)
        canvas.get_tk_widget().grid(row=position[0], column=position[1],
                                    padx=padX, pady=padY,
                                    columnspan=columnSpan, rowspan=rowSpan,
                                    sticky=sticky)

        canvas.show()
        rootApp.signalPlotters[name] = (axis_array, canvas, fig)
        rootApp.controls[name] = canvas.get_tk_widget()
示例#27
0
class PlotWindow(Frame):
    """

    """

    def __init__(self, parent, figure, plotType=None):
        """
        Constructor

        @param parent:
        @param figure:
        @param plotType:
        @return
        """
        Frame.__init__(self, parent)

        # a tk.DrawingAre
        self.plotType = plotType
        self.canvas = FigureCanvasTkAgg(figure, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
        self.canvas.mpl_connect('key_press_event', self.on_key_event)

    def getPlotType(self):
        """

        @return
        """
        return self.plotType

    def updateFigure(self, figure):
        """

        @param figure:
        @return
        """

        self.canvas._tkcanvas.pack_forget()

        self.canvas = FigureCanvasTkAgg(figure, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.canvas.mpl_connect('key_press_event', self.on_key_event)

    def on_key_event(self, event):
        """

        @param event:
        @return
        """
        print('you pressed %s' % event.key)
        key_press_handler(event, self.canvas, self.toolbar)
示例#28
0
def viewdata():
	graph = Toplevel()
	global SampleNos
	global Temperature
	graph.wm_title("Downloaded Data")
	graph.wm_iconbitmap(bitmap = "@/home/pi/meter.xbm")
	menubar = Menu(graph)
	filemenu = Menu(menubar, tearoff=0)
	filemenu.add_command(label="Open", command=openl)
	filemenu.add_command(label="Save", command=hello)
	filemenu.add_separator()
	filemenu.add_command(label="Exit", command=root.quit)
	menubar.add_cascade(label="File", menu=filemenu)
	graph.config(menu=menubar)
	f = Figure(figsize=(5, 4), dpi=100)
	a = f.add_subplot(111)
	t = arange(0.0, 3.0, 0.01)
	s = sin(2*pi*t)
	a.plot(SampleNos,Temperature, 'bo')
	canvas = FigureCanvasTkAgg(f, master=graph)
	canvas.show()
	canvas.get_tk_widget().pack()
	toolbar = NavigationToolbar2TkAgg(canvas, graph)
	toolbar.update()
	canvas._tkcanvas.pack()
示例#29
0
    def DrawSignalPlot(rootApp,
                       signalData,
                       name="SourcePlot",
                       text="Signal View'",
                       xLabel="time (s)",
                       yLabel="voltage (mV)",
                       position=(10, 10),
                       padX=0, padY=0,
                       sticky=(tk.S, tk.W), columnSpan=1, rowSpan=1,
                       owner=None):

        if owner == None:
            owner = rootApp
        fig, ax = plt.subplots()

        plt.tight_layout(rect=[.01, .2, .72, 1])
        ax.set(xlabel=xLabel, ylabel=yLabel,
               title=text)
        ax.grid('on')

        canvas = FigureCanvasTkAgg(fig, master=owner)
        canvas.get_tk_widget().grid(row=position[0], column=position[1],
                                    padx=padX, pady=padY,
                                    columnspan=columnSpan, rowspan=rowSpan,
                                    sticky=sticky)

        canvas.show()
        rootApp.signalPlotters[name] = (ax, canvas, fig)
        rootApp.controls[name] = canvas.get_tk_widget()
示例#30
0
class GraghFigure:
	def __init__(self, figFrame, figsizeX, figsizeY):

		self.fig = pylab.figure(dpi=fig_dpi, figsize=(figsizeX,figsizeY))
		self.canvas = FigureCanvasTkAgg(self.fig, master=figFrame)
		self.ax = self.fig.add_subplot(111)

		self.canvas.show()
		self.canvas.get_tk_widget().pack()
		self.ax.grid(True)
		self.line=[]
		self.line_num=-1

	def setAchse(self, xLabel, yLabel):
		self.xAchse=xAchse
		self.yAchse=yAchse
		self.ax.set_xlabel(xLabel)
		self.ax.set_ylabel(yLabel)

	def setAxis(self, x0,x1,y0,y1):
		self.ax.axis([x0,x1 ,y0,y1])

	def addplot(self, style):
		self.line.append(self.ax.plot(self.xAchse, self.yAchse, style, lw=3))
		#self.line = self.ax.plot(xAchse, yAchse, style)
		self.line_num = self.line_num + 1
		return self.line_num

	def plot(self, index, data_x, data_y):
		self.line[index][0].set_data(data_x, pylab.array(data_y))
class fluke8808a_control_frame(tk.Frame):
    def __init__(self, master, controller, root, usbswitch, fluke8808a,
                 keithley):
        tk.Frame.__init__(self, master)
        self.grid_rowconfigure(1, weight=1)  #mess with frames
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

        self.master = master
        self.controller = controller
        self.root = root
        self.usbswitch = usbswitch
        self.fluke8808a = fluke8808a
        self.keithley = keithley

        self.running = False
        self.ani = None
        self.stopgraph_event = threading.Event()

        self.measurement_running = False
        self.plot_running = False
        self.callback = None

        #datalists
        self.primarylist_time = np.array([])
        self.primarylist_data = np.array([])
        self.secondarylist_time = np.array([])
        self.secondarylist_data = np.array([])

        self.usbswitchframe = usbswitch_diagram_frame(self, controller,
                                                      self.usbswitch)
        self.usbswitchframe.config(borderwidth=5, relief=tk.GROOVE)
        self.usbswitchframe.grid(row=0, column=0, sticky='nsew')

        #Frame to configure Fluke Primary and Secondary Displays
        self.configframe = tk.Frame(self, borderwidth=5, relief=tk.GROOVE)
        self.configframe.grid(row=1, column=0, sticky='nsew')
        for k in range(0, 4):
            self.configframe.grid_rowconfigure(k, weight=1)
        self.configframe.grid_columnconfigure(0, weight=1)
        self.configframe.grid_columnconfigure(1, weight=1)

        self.primarylbl = tk.Label(self.configframe,
                                   text="Primary Display",
                                   font=("tkDefaultFont", 18))
        self.primarylbl.grid(row=0, column=0, sticky='nw')
        self.primary_str = tk.StringVar()
        self.primary_list = ["DC Voltage", "DC Current", "Resistance"]
        self.primary_str.set(self.primary_list[0])
        self.primarymenu = ttk.OptionMenu(self.configframe, self.primary_str,
                                          self.primary_list[0],
                                          *self.primary_list)
        self.primarymenu.grid(row=1, column=0, sticky='nsew')
        self.primaryconfigbtn = ttk.Button(
            self.configframe,
            text='Config',
            command=lambda: self.configPrimaryDisplay())
        self.primaryconfigbtn.grid(row=0, column=1, rowspan=2, sticky='nsew')

        self.primaryvallbl = tk.Label(self.configframe,
                                      text="Primary Raw Value",
                                      font=("tkDefaultFont", 18))
        self.primaryvallbl.grid(row=0, column=2, sticky='nw')
        self.primaryvalstr = tk.StringVar()
        self.primaryvalstr.set('INF')
        self.primaryval = tk.Label(self.configframe,
                                   textvariable=self.primaryvalstr,
                                   font=("tkDefaultFont", 16),
                                   background='white')
        self.primaryval.grid(row=1, column=2, sticky='nsew')

        self.secondarylbl = tk.Label(self.configframe,
                                     text="Secondary Display",
                                     font=("tkDefaultFont", 18))
        self.secondarylbl.grid(row=2, column=0, sticky='nw')
        self.secondary_str = tk.StringVar()
        self.secondary_list = ["DC Voltage", "DC Current", "Resistance"]
        self.secondary_str.set(self.secondary_list[0])
        self.secondarymenu = ttk.OptionMenu(self.configframe,
                                            self.secondary_str,
                                            self.secondary_list[0],
                                            *self.secondary_list)
        self.secondarymenu.grid(row=3, column=0, sticky='nsew')
        self.secondaryconfigbtn = ttk.Button(
            self.configframe,
            text='Config',
            command=lambda: self.configSecondaryDisplay())
        self.secondaryconfigbtn.grid(row=2, column=1, rowspan=2, sticky='nsew')

        self.secondaryvallbl = tk.Label(self.configframe,
                                        text="Secondary Raw Value",
                                        font=("tkDefaultFont", 18))
        self.secondaryvallbl.grid(row=2, column=2, sticky='nw')
        self.secondaryvalstr = tk.StringVar()
        self.secondaryvalstr.set('INF')
        self.secondaryval = tk.Label(self.configframe,
                                     textvariable=self.secondaryvalstr,
                                     font=("tkDefaultFont", 18),
                                     background='white')
        self.secondaryval.grid(row=3, column=2, sticky='nsew')
        #get individual reading
        self.primarybtn = ttk.Button(self.configframe,
                                     text="Instant Reading",
                                     command=lambda: self.getPrimaryReading())
        self.primarybtn.grid(row=0, column=3, rowspan=2, sticky='nsew')
        self.secondarybtn = ttk.Button(
            self.configframe,
            text="Instant Reading",
            command=lambda: self.getSecondaryReading())
        self.secondarybtn.grid(row=2, column=3, rowspan=2, sticky='nsew')

        #setup measurement frame
        self.switchsetupframe = tk.Frame(self.configframe)
        self.switchsetupframe.grid(row=4,
                                   column=0,
                                   columnspan=4,
                                   sticky='nsew')
        for k in range(0, 4):
            self.switchsetupframe.grid_columnconfigure(k, weight=1)
        self.r1btn = ttk.Button(self.switchsetupframe,
                                text="Resistance 1",
                                command=lambda: self.setUSBRes1())
        self.r1btn.grid(row=0, column=0, sticky='nsew')
        self.r2btn = ttk.Button(self.switchsetupframe,
                                text="Resistance 2",
                                command=lambda: self.setUSBRes2())
        self.r2btn.grid(row=0, column=1, sticky='nsew')
        self.vbtn = ttk.Button(self.switchsetupframe,
                               text="Voltage",
                               command=lambda: self.setUSBVoltage())
        self.vbtn.grid(row=0, column=2, sticky='nsew')
        self.ibtn = ttk.Button(self.switchsetupframe,
                               text="Current",
                               command=lambda: self.setUSBCurrent())
        self.ibtn.grid(row=0, column=3, sticky='nsew')

        #####################
        ## Start 5/30 by defining these functions

        #Plotting
        #self.plotframe = fluke8808a_plot_subframe(self,self.fluke8808a)
        #self.plotframe.grid(row = 0, column = 1, sticky = 'nsew')
        self.plotframe = tk.Frame(self, borderwidth=5, relief=tk.GROOVE)
        self.plotframe.grid_rowconfigure(1, weight=1)
        self.plotframe.grid_rowconfigure(2, weight=1)
        self.plotframe.grid_columnconfigure(0, weight=1)
        self.plotframe.grid(row=0, column=1, rowspan=2, sticky='nsew')

        self.primarypltframe = tk.Frame(self.plotframe)
        self.primarypltframe.grid(row=1, column=0, sticky='nsew')
        self.primarypltframe.grid_rowconfigure(0, weight=1)
        self.primarypltframe.grid_columnconfigure(0, weight=1)
        self.fig1 = plt.Figure()
        self.ax1 = self.fig1.add_subplot(1, 1, 1)
        self.line1, = self.ax1.plot([], [], lw=2, color='r')
        self.ax1.set_title('Primary Display:')
        self.canvas1 = FigureCanvasTkAgg(self.fig1, self.primarypltframe)
        self.canvas1.show()
        self.canvas1.get_tk_widget().pack(side=tk.TOP,
                                          fill=tk.BOTH,
                                          expand=True)
        self.canvas1._tkcanvas.grid(
            row=0, column=0,
            sticky='nsew')  #pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        self.secondarypltframe = tk.Frame(self.plotframe)
        self.secondarypltframe.grid(row=2, column=0, sticky='nsew')
        self.secondarypltframe.grid_rowconfigure(0, weight=1)
        self.secondarypltframe.grid_columnconfigure(0, weight=1)
        self.fig2 = plt.Figure()
        self.ax2 = self.fig2.add_subplot(1, 1, 1)
        self.ax2.set_title('Secondary Display:')
        self.line2, = self.ax2.plot([], [], lw=2, color='r')
        self.canvas2 = FigureCanvasTkAgg(self.fig2, self.secondarypltframe)
        self.canvas2.show()
        self.canvas2.get_tk_widget().pack(side=tk.TOP,
                                          fill=tk.BOTH,
                                          expand=True)
        self.canvas2._tkcanvas.grid(
            row=0, column=0,
            sticky='nsew')  #pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        #Header frame that includes all controls
        self.headerframe = tk.Frame(self.plotframe,
                                    borderwidth=5,
                                    relief=tk.GROOVE)
        self.headerframe.grid(row=0, column=0, sticky='nsew')
        self.headerframe.grid_rowconfigure(0, weight=1)
        #self.headerframe.grid_columnconfigure(3,weight=1)
        #self.headerframe.grid_columnconfigure(4,weight=1)
        self.headerframe.grid_columnconfigure(5, weight=1)
        #canvas for indicator
        self.indicator_canvas = tk.Canvas(self.headerframe,
                                          width=50,
                                          height=50)
        self.indicator_canvas.grid(row=0, column=0, sticky='ns')
        self.indicator = self.indicator_canvas.create_oval(5,
                                                           5,
                                                           40,
                                                           40,
                                                           fill='red4')
        self.indicatorstr = tk.StringVar()
        self.indicatorstr.set('Not Measuring')
        self.indicatorlbl = tk.Label(self.headerframe,
                                     textvariable=self.indicatorstr,
                                     font=('tkDefaultFont', 12),
                                     width=14)
        self.indicatorlbl.grid(row=0, column=1, sticky='nsew')
        #Time interval
        self.intervalframe = tk.Frame(self.headerframe, borderwidth=5)
        self.intervalframe.grid(row=0, column=2, sticky='nsew')
        self.intervalframe.grid_rowconfigure(0, weight=1)
        self.intervalframe.grid_columnconfigure(0, weight=1)
        self.interval_lbl = tk.Label(self.intervalframe, text='Time Step (s)')
        self.interval_lbl.grid(row=0, column=0)
        self.intervalstr = tk.StringVar()
        self.intervalstr.set('1')
        self.interval = tk.Entry(self.intervalframe,
                                 textvariable=self.intervalstr,
                                 width=5)
        self.interval.grid(row=1, column=0, sticky='nsew')
        #Measure Button
        self.measure_btn = ttk.Button(self.headerframe,
                                      text='Start Measurement',
                                      command=lambda: self.measure_click(),
                                      width=25)
        self.measure_btn.grid(row=0, column=3, sticky='nsew')
        #Plot Button
        self.measure_and_plot_btn = ttk.Button(
            self.headerframe,
            text='Start Measurement & Plot',
            command=lambda: self.measure_and_plot_click(),
            width=25)
        self.measure_and_plot_btn.grid(row=0, column=4, sticky='nsew')
        #Reset Plot Button
        self.resetbtn = ttk.Button(
            self.headerframe,
            text='Reset Graphs',
            command=lambda: self.reset_graphs())  #, width = 22)
        self.resetbtn.grid(row=0, column=5, sticky='nsew')

        #Keithley Control
        self.keithley_control_frame = keithley_control_subframe(
            self, self.controller, self.root, self.keithley)
        self.keithley_control_frame.grid(row=0,
                                         column=2,
                                         rowspan=2,
                                         sticky='nsew')

    #Click Methods

    def measure_click(self):
        if self.measurement_running:  #then user wants to stop the Measurement
            self.stop_instrument()
            self.stop_graph()  #stopping the measurement also stops the graph
        else:  #then user wants to start the measurement without running the graph
            self.start_instrument()

    def measure_and_plot_click(self):
        if self.measurement_running and not self.plot_running:  #then user has started measuring and wants to graph
            self.start_graph()
        elif self.measurement_running and self.plot_running:  #then user wants to stop the graph but keep the measurement going
            self.stop_graph()
        elif not self.measurement_running and not self.plot_running:  #then user wants to start the measurement and start the graph
            self.start_instrument()
            self.start_graph()
        #note the user cannot stop the measurement from the measure_and_plot button. To stop the Measurement, the user must click the measure_btn

    def start_instrument(self):
        self.fluke8808a.measureBothDisplays(float(self.intervalstr.get()))
        #change indicator
        self.indicator_canvas.itemconfig(self.indicator, fill="green2")
        self.indicatorstr.set('Measuring...')
        #change measurement button
        self.measure_btn.config(text='Stop Measurement & Plot')
        #change measurement running state
        self.measurement_running = True

    def stop_instrument(self):
        self.fluke8808a.stop_event.set()
        #change indicator
        self.indicator_canvas.itemconfig(self.indicator, fill="red4")
        self.indicatorstr.set('Not Measuring')
        #change measurement button
        self.measure_btn.config(text='Start Measurement')
        while self.fluke8808a.thread_active:
            time.sleep(0.002)  #wait for the measurement to stop
        #clear the measurement queue
        self.fluke8808a.clear_queues()
        #change measurement running state
        self.measurement_running = False

    def start_graph(self):
        #change plot running state
        self.plot_running = True
        #change measure and plot button
        self.measure_and_plot_btn.config(text='Stop Plot')
        #disable reset button
        self.resetbtn.config(state=tk.DISABLED)
        #update the graph
        self.update_graph()

    def stop_graph(self):
        #change plot running state
        self.plot_running = False
        #change measure and plot button
        self.measure_and_plot_btn.config(text='Start Measurement & Plot')
        #enable reset button
        self.resetbtn.config(state=tk.NORMAL)
        if self.callback is not None:
            self.after_cancel(self.callback)

    def update_graph(self):
        #try:
        def totalseconds(x):
            return (x - datetime.datetime(1970, 1, 1)).total_seconds()

        totalseconds = np.vectorize(totalseconds)
        #update temperature graph
        while not (self.fluke8808a.primaryq.empty()):
            primarydata = self.fluke8808a.primaryq.get()
            timeprimary = primarydata[0]
            tempprimary = primarydata[1]
            unitprimary = primarydata[2]
            self.primarylist_time = np.append(self.primarylist_time,
                                              timeprimary)
            self.primarylist_data = np.append(self.primarylist_data,
                                              tempprimary)
            self.line1.set_data(totalseconds(self.primarylist_time),
                                self.primarylist_data)
            self.ax1.relim()
            self.ax1.autoscale_view()
            #change axes
            if self.primarylist_time.size > 0 and self.primarylist_data.size > 0:
                self.ax1.set_title('Primary Display: %g%s ' %
                                   (self.primarylist_data[-1], unitprimary))
        while not (self.fluke8808a.secondaryq.empty()):
            secondarydata = self.fluke8808a.secondaryq.get()
            timesecondary = secondarydata[0]
            tempsecondary = secondarydata[1]
            unitsecondary = secondarydata[2]
            self.secondarylist_time = np.append(self.secondarylist_time,
                                                timesecondary)
            self.secondarylist_data = np.append(self.secondarylist_data,
                                                tempsecondary)
            self.line2.set_data(totalseconds(self.secondarylist_time),
                                self.secondarylist_data)
            self.ax2.relim()
            self.ax2.autoscale_view()
            #change axes
            if self.secondarylist_time.size > 0 and self.secondarylist_data.size > 0:
                self.ax2.set_title(
                    'Secondary Display: %g%s ' %
                    (self.secondarylist_data[-1], unitsecondary))
        self.canvas1.draw_idle()
        self.canvas2.draw_idle()
        self.callback = self.after(100, self.update_graph)

    #def update_graph(self):
    #    xlist1 = []
    #    ylist1 = []
    #    xlist2 = []
    #    ylist2 = []
    #    for elem1 in self.fluke8808a.list1:
    #        xlist1.append((elem1['datetime'] - datetime.datetime(1970,1,1)).total_seconds())
    #        #need to interpet the units
    #        ylist1.append(elem1['data'])
    #    self.line1.set_data(xlist1,ylist1)
    #    for elem2 in self.fluke8808a.list2:
    #        xlist2.append((elem2['datetime'] - datetime.datetime(1970,1,1)).total_seconds())
    #        ylist2.append(elem2['data'])
    #    self.line2.set_data(xlist2,ylist2)
    #    #adjust axes
    #    if xlist1 and ylist1:
    #        self.ax1.set_ylim(min(ylist1), max(ylist1))
    #        self.ax1.set_xlim(min(xlist1), max(xlist1))
    #        self.ax1.set_title('Primary Display: %s' % elem1['unit'])
    #    if xlist2 and ylist2:
    #        self.ax2.set_ylim(min(ylist2), max(ylist2))
    #        self.ax2.set_xlim(min(xlist2), max(xlist2))
    #        self.ax2.set_title('Secondary Display: %s' % elem2['unit'])
    #    self.canvas1.draw_idle()
    #    self.canvas2.draw_idle()

    def reset_graphs(self):
        self.primarylist_time = np.array([])
        self.primarylist_data = np.array([])
        self.secondarylist_time = np.array([])
        self.secondarylist_data = np.array([])

        self.line1.set_data(self.primarylist_time, self.primarylist_data)
        self.line2.set_data(self.secondarylist_time, self.secondarylist_data)

        self.canvas1.draw_idle()
        self.canvas2.draw_idle()

    def configPrimaryDisplay(self):
        #setup measure routine, so it can be interrupted to change configuration
        self.primaryconfigbtn.config(state=tk.DISABLED)
        self.secondaryconfigbtn.config(state=tk.DISABLED)
        if self.running:  #need to stop running by running "on_click"
            self.on_click()
            while self.fluke8808a.thread_active:
                #ask if the thread has truly stopped
                time.sleep(0.002)
            #config
            self.fluke8808a.configPrimaryDisplay(self.primary_str.get())
            self.on_click()  #start run again
        else:
            time.sleep(0.002)
            self.fluke8808a.configPrimaryDisplay(self.primary_str.get())
        self.primaryconfigbtn.config(state=tk.NORMAL)
        self.secondaryconfigbtn.config(state=tk.NORMAL)

    def configSecondaryDisplay(self):
        #setup measure routine, so it can be interrupted to change configuration
        self.primaryconfigbtn.config(state=tk.DISABLED)
        self.secondaryconfigbtn.config(state=tk.DISABLED)
        if self.running:  #need to stop running by running "on_click"
            self.on_click()
            while self.fluke8808a.thread_active:
                #ask if the thread has truly stopped
                time.sleep(0.002)
            #config
            self.fluke8808a.configSecondaryDisplay(self.secondary_str.get())
            self.on_click()  #start run again
        else:
            time.sleep(0.002)
            self.fluke8808a.configSecondaryDisplay(self.secondary_str.get())
        self.primaryconfigbtn.config(state=tk.NORMAL)
        self.secondaryconfigbtn.config(state=tk.NORMAL)

    def getPrimaryReading(self):
        self.primarybtn.config(state=tk.DISABLED)
        if self.running:  #need to stop running by running "on_click"
            self.on_click()
            while self.fluke8808a.thread_active:
                #ask if the thread has truly stopped
                time.sleep(0.002)
            #config
            self.fluke8808a.singlePrimaryDisplay()
            self.on_click()  #start run again
        else:
            time.sleep(0.002)
            self.fluke8808a.singlePrimaryDisplay()
        self.primaryvalstr.set(
            '%g %s' %
            (self.fluke8808a.single1['data'], self.fluke8808a.single1['unit']))
        self.primarybtn.config(state=tk.NORMAL)

    def getSecondaryReading(self):
        self.secondarybtn.config(state=tk.DISABLED)
        if self.running:  #need to stop running by running "on_click"
            self.on_click()
            while self.fluke8808a.thread_active:
                #ask if the thread has truly stopped
                time.sleep(0.002)
            #config
            self.fluke8808a.singleSecondaryDisplay()
            self.on_click()  #start run again
        else:
            time.sleep(0.002)
            self.fluke8808a.singleSecondaryDisplay()
        self.secondaryvalstr.set(
            '%g %s' %
            (self.fluke8808a.single2['data'], self.fluke8808a.single2['unit']))
        self.secondarybtn.config(state=tk.NORMAL)

    def setUSBGeneral(self, relay1, relay2, type):
        #configure usbswitch to open relays1 and relay2 and close all others and configure fluke primary display to measure type
        self.usbswitch.turnOffAllRelays()
        for k in range(0, 8):
            self.usbswitchframe.relaybtns[k].updateState()
        time.sleep(0.1)
        self.usbswitchframe.relaybtns[relay1].change_state()
        time.sleep(0.1)
        self.usbswitchframe.relaybtns[relay2].change_state()

        #now configure fluke to measure type at primary display
        self.primary_str.set(type)
        self.configPrimaryDisplay()

    def setUSBRes1(self):
        self.setUSBGeneral(0, 4, "Resistance")

    def setUSBRes2(self):
        self.setUSBGeneral(1, 5, "Resistance")

    def setUSBVoltage(self):
        self.setUSBGeneral(2, 6, "DC Voltage")

    def setUSBCurrent(
        self
    ):  #need to edit this so that primary display is voltage and secondary is current
        #set voltage for primary display
        self.setUSBVoltage()
        #current will go on the secondary display and only needs switch 8.
        if not self.usbswitchframe.relaybtns[7].relay.status:
            #then relay 8 is closed and should be kept open
            self.usbswitchframe.relaybtns[7].change_state()
        #now configure fluke to measure current at secondary display
        self.secondary_str.set("DC Current")
        self.configSecondaryDisplay()
示例#32
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
示例#33
0
class Main():
    def __init__(self):
        rospy.init_node('para_tune', anonymous=True)
        self.state_changer = rospy.Publisher('/AUVmanage/state',
                                             Int32,
                                             queue_size=1)
        self.call_param_dump = rospy.Publisher('/AUVmanage/dumpparam',
                                               Int32,
                                               queue_size=1)
        win = tk.Tk()
        win.title('Dummy motor')
        win.wm_geometry("3000x2000")
        scale_frame = tk.Frame(win)
        scale_frame.grid(row=1, column=1)
        graph = tk.Frame(win)
        graph.grid(row=1, column=2)
        start_frame = tk.Frame(win)
        start_frame.grid(row=1, column=3)
        ################################################################################
        #                               depth PID                                      #
        ################################################################################
        depth_PID = rospy.get_param('/PIDpara/depth')
        depth_PID_digit = []
        depth_PID_num = []
        for i in depth_PID:
            a, b = get_digit(i)
            depth_PID_digit.append(a)
            depth_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='depth_P').grid(row=1, column=0)
        self.s_d_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_P.set(depth_PID_num[0])
        self.s_d_P.grid(row=1, column=1)
        self.combo_d_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_P.current(depth_PID_digit[0] + 5)
        self.combo_d_P.grid(row=1, column=2)
        tk.Label(scale_frame, text='depth_I').grid(row=2, column=0)
        self.s_d_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_I.set(depth_PID_num[1])
        self.s_d_I.grid(row=2, column=1)
        self.combo_d_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_I.current(depth_PID_digit[1] + 5)
        self.combo_d_I.grid(row=2, column=2)
        tk.Label(scale_frame, text='depth_D').grid(row=3, column=0)
        self.s_d_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_D.set(depth_PID_num[2])
        self.s_d_D.grid(row=3, column=1)
        self.combo_d_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_D.current(depth_PID_digit[2] + 5)
        self.combo_d_D.grid(row=3, column=2)
        tk.Button(scale_frame, text='set depth param',
                  command=self.set_depth).grid(row=1, column=5)
        tk.Button(scale_frame,
                  text='dump depth param',
                  command=self.dump_depth).grid(row=2, column=5)

        ################################################################################
        #                               altitude PID                                   #
        ################################################################################
        altitude_PID = rospy.get_param('/PIDpara/altitude')
        altitude_PID_digit = []
        altitude_PID_num = []
        for i in altitude_PID:
            a, b = get_digit(i)
            altitude_PID_digit.append(a)
            altitude_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='altitude_P').grid(row=4, column=0)
        self.s_a_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_P.set(altitude_PID_num[0])
        self.s_a_P.grid(row=4, column=1)
        self.combo_a_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_P.current(altitude_PID_digit[0] + 5)
        self.combo_a_P.grid(row=4, column=2)
        tk.Label(scale_frame, text='altitude_I').grid(row=5, column=0)
        self.s_a_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_I.set(altitude_PID_num[1])
        self.s_a_I.grid(row=5, column=1)
        self.combo_a_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_I.current(altitude_PID_digit[1] + 5)
        self.combo_a_I.grid(row=5, column=2)
        tk.Label(scale_frame, text='altitude_D').grid(row=6, column=0)
        self.s_a_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_D.set(altitude_PID_num[2])
        self.s_a_D.grid(row=6, column=1)
        self.combo_a_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_D.current(altitude_PID_digit[2] + 5)
        self.combo_a_D.grid(row=6, column=2)
        tk.Button(scale_frame,
                  text='set altitude param',
                  command=self.set_altitude).grid(row=4, column=5)
        tk.Button(scale_frame,
                  text='dump altitude param',
                  command=self.dump_altitude).grid(row=5, column=5)

        ################################################################################
        #                               yaw tune                                   #
        ################################################################################
        yaw = rospy.get_param('/PIDpara/yaw')
        if yaw[0] >= 0:
            yaw_digit, yaw_num = get_digit(yaw[0])
        else:
            yaw_digit, yaw_num = get_digit(-yaw[0])
            yaw_num = -yaw_num
        yaw_PID_digit = []
        yaw_PID_num = []
        for i in yaw[1:]:
            a, b = get_digit(i)
            yaw_PID_digit.append(a)
            yaw_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='yaw tune').grid(row=7, column=0)
        self.s_y = tk.Scale(scale_frame,
                            from_=-10,
                            to=10,
                            orient=tk.HORIZONTAL,
                            length=200,
                            showvalue=1,
                            tickinterval=5,
                            resolution=0.01,
                            command=print_selec_value)
        self.s_y.set(yaw_num)
        self.s_y.grid(row=7, column=1)
        self.combo_y = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y.current(yaw_digit + 5)
        self.combo_y.grid(row=7, column=2)

        tk.Label(scale_frame, text='yaw_P').grid(row=8, column=0)
        self.s_y_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_P.set(yaw_PID_num[0])
        self.s_y_P.grid(row=8, column=1)
        self.combo_y_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_P.current(yaw_PID_digit[0] + 5)
        self.combo_y_P.grid(row=8, column=2)
        tk.Label(scale_frame, text='yaw_I').grid(row=9, column=0)
        self.s_y_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_I.set(yaw_PID_num[1])
        self.s_y_I.grid(row=9, column=1)
        self.combo_y_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_I.current(altitude_PID_digit[1] + 5)
        self.combo_y_I.grid(row=9, column=2)
        tk.Label(scale_frame, text='yaw_D').grid(row=10, column=0)
        self.s_y_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_D.set(altitude_PID_num[2])
        self.s_y_D.grid(row=10, column=1)
        self.combo_y_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_D.current(altitude_PID_digit[2] + 5)
        self.combo_y_D.grid(row=10, column=2)

        tk.Button(scale_frame, text='set yaw tune param',
                  command=self.set_yaw).grid(row=7, column=5)
        tk.Button(scale_frame,
                  text='dump yaw tune param',
                  command=self.dump_yaw).grid(row=8, column=5)
        ################################################################################
        #                               matplotlib graph                               #
        ################################################################################
        #===============      for depth  ====================#
        self.x_count = 0
        self.depth_x = np.arange(0, 100)
        self.ddata = np.zeros(100)
        self.depth_fig = Figure(figsize=(5, 3), dpi=100)
        self.depth_ax = self.depth_fig.add_subplot(111)
        self.depth_ax.set_ylim((0, 2))
        self.depth_ax.invert_yaxis()
        self.depth_ax.set_title("depth")
        self.canvas_d = FigureCanvasTkAgg(self.depth_fig, master=graph)
        self.canvas_d.show()
        self.canvas_d.get_tk_widget().pack(side=tk.TOP, fill="both")
        rospy.Subscriber("/depth", Float32, self.depth_back, queue_size=1)
        ################################################################################
        #                               kill bottom                                    #
        ################################################################################
        self.countdowner = rospy.Publisher('/AUVmanage/countdowner',
                                           Int32MultiArray,
                                           queue_size=1)
        self.e = tk.Entry(start_frame)
        self.e.grid(row=1, column=1)
        self.cd_remaining = 0
        self.countdown_label = tk.Label(start_frame, text="", width=10)
        self.countdown_label.grid(row=1, column=2)
        self.coutdown_var = 0
        self.start_button = tk.Button(start_frame,
                                      text='Press to start',
                                      command=self.state2one).grid(row=2,
                                                                   column=1)
        self.stop_button = tk.Button(start_frame,
                                     text='Press to stop',
                                     command=self.state2zero).grid(row=2,
                                                                   column=2)
        self.stop_button = tk.Button(start_frame,
                                     text='stop but count',
                                     command=self.state2two).grid(row=2,
                                                                  column=3)
        self.stop_button = tk.Button(start_frame,
                                     text='go forward',
                                     command=self.state2three).grid(row=2,
                                                                    column=4)
        win.mainloop()

    def set_depth(self):
        data = []
        data.append(self.s_d_P.get() * 10**float(self.combo_d_P.get()))
        data.append(self.s_d_I.get() * 10**float(self.combo_d_I.get()))
        data.append(self.s_d_D.get() * 10**float(self.combo_d_D.get()))
        print data
        rosparam.set_param('/PIDpara/depth', str(data))

    def set_altitude(self):
        data = []
        data.append(self.s_a_P.get() * 10**float(self.combo_a_P.get()))
        data.append(self.s_a_I.get() * 10**float(self.combo_a_I.get()))
        data.append(self.s_a_D.get() * 10**float(self.combo_a_D.get()))
        print data
        rosparam.set_param('/PIDpara/altitude', str(data))

    def set_yaw(self):
        data = []
        data.append(self.s_y.get() * 10**float(self.combo_y.get()))
        data.append(self.s_y_P.get() * 10**float(self.combo_a_P.get()))
        data.append(self.s_y_I.get() * 10**float(self.combo_a_I.get()))
        data.append(self.s_y_D.get() * 10**float(self.combo_a_D.get()))

        print data
        rosparam.set_param('/PIDpara/yaw', str(data))

    def dump_depth(self):
        self.call_param_dump.publish(Int32(data=1))
        '''
        data = []
        data.append(self.s_d_P.get()*10**float(self.combo_d_P.get()))
        data.append(self.s_d_I.get()*10**float(self.combo_d_I.get()))
        data.append(self.s_d_D.get()*10**float(self.combo_d_D.get()))
        dict_data = {'/PIDpara/depth':data}
        print dict_data
        with open(r'/home/eason/catkin_ws/src/auv_control/config/depth.yaml','w+') as f:
            print yaml.dump(dict_data,f, default_flow_style = False)
        '''

    def dump_altitude(self):
        self.call_param_dump.publish(Int32(data=0))
        '''
        data = []
        data.append(self.s_a_P.get()*10**float(self.combo_a_P.get()))
        data.append(self.s_a_I.get()*10**float(self.combo_a_I.get()))
        data.append(self.s_a_D.get()*10**float(self.combo_a_D.get()))
        dict_data = {'/PIDpara/altitude':data}
        print dict_data
        with open(r'/home/eason/catkin_ws/src/auv_control/config/altitude.yaml','w+') as f:
            print yaml.dump(dict_data,f, default_flow_style = False)
        '''

    def dump_yaw(self):
        self.call_param_dump.publish(Int32(data=2))
        '''
        data=self.s_y.get()*10**float(self.combo_y.get())
        print data
        dict_data = {'/tune/yaw':data}
        print dict_data
        with open(r'/home/eason/catkin_ws/src/auv_control/config/yaw_tune.yaml','w+') as f:
            print yaml.dump(dict_data,f, default_flow_style = False)
        '''

    def depth_back(self, data):
        #print(data.data)
        if self.x_count > 99:
            self.x_count += 1
            self.ddata = np.roll(self.ddata, -1)
            self.ddata[99] = data.data
            self.depth_x = np.roll(self.depth_x, -1)
            self.depth_x[99] = self.depth_x[98] + 1
            self.depth_ax.cla()
            self.depth_ax.set_xlim((self.depth_x[0], self.depth_x[99]))
            self.depth_ax.set_ylim((0, 2))
            self.depth_ax.invert_yaxis()
            self.depth_ax.plot(self.depth_x, self.ddata)
            #print(self.depth_x[99])
        else:
            self.ddata[self.x_count] = data.data
            self.x_count += 1
            self.depth_ax.cla()
            self.depth_ax.set_ylim((0, 2))
            self.depth_ax.invert_yaxis()
            self.depth_ax.plot(self.depth_x, self.ddata)
        self.depth_ax.set_title("depth")
        self.canvas_d.draw()

    def state2one(self):
        var = int(self.e.get())
        self.countdowner.publish(Int32MultiArray(data=[1, var]))
        self.countdown(var)

    def state2zero(self):
        self.state_changer.publish(Int32(data=0))

    def state2two(self):
        self.state_changer.publish(Int32(data=2))

    def state2three(self):
        var = int(self.e.get())
        self.countdowner.publish(Int32MultiArray(data=[3, var]))
        self.countdown(var)

    def countdown(self, remaining=None):
        if remaining is not None:
            self.cd_remaining = remaining
        if self.cd_remaining <= 0.1:
            self.countdown_label.configure(text="time's up!")
        else:
            self.countdown_label.configure(text=str(self.cd_remaining))
            self.cd_remaining = self.cd_remaining - 0.1
            self.countdown_label.after(100, self.countdown)
示例#34
0
    def do_plot(self):
        if self.plate != int(self.e1.get()) or self.mjd != int(self.e2.get()):
            self.plate = int(self.e1.get())
            self.mjd = int(self.e2.get())
            self.fiber = int(self.e3.get())
            self.znum = int(self.e5.get())
            self.platepath = join(environ['BOSS_SPECTRO_REDUX'],
                                  environ['RUN2D'], '%s' % self.plate,
                                  'spPlate-%s-%s.fits' % (self.plate, self.mjd))
            hdu = fits.open(self.platepath)
            self.specs = hdu[0].data
            self.wave = 10**(hdu[0].header['COEFF0'] +
                             n.arange(hdu[0].header['NAXIS1']) *
                             hdu[0].header['COEFF1'])
            self.models = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[2].data
            self.fiberid = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                          environ['RUN2D'], '%s' % self.plate,
                                          environ['RUN1D'],
                                          'redmonster-%s-%s.fits' %
                                          (self.plate,
                                           self.mjd)))[1].data.FIBERID
            self.type1 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS1
            self.type2 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS2
            self.type3 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS3
            self.type4 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS4
            self.type5 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS5
            self.z = n.zeros((self.fiberid.shape[0],5))
            self.z[:,0] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z1
            self.z[:,1] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z2
            self.z[:,2] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z3
            self.z[:,3] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z4
            self.z[:,4] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z5
            self.zwarning = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                           environ['RUN2D'], '%s' % self.plate,
                                           environ['RUN1D'],
                                           'redmonster-%s-%s.fits' %
                                           (self.plate,
                                            self.mjd)))[1].data.ZWARNING
        else:
            self.fiber = int(self.e3.get())
        f = Figure(figsize=(10,6), dpi=100)
        a = f.add_subplot(111)
        loc = n.where(self.fiberid == self.fiber)[0]
        if self.znum == 1:
            z = self.z[loc[0],0]
            thistype = self.type1[loc[0]]
        elif self.znum == 2:
            z = self.z[loc[0],1]
            thistype = self.type2[loc[0]]
        elif self.znum == 3:
            z = self.z[loc[0],2]
            thistype = self.type3[loc[0]]
        elif self.znum == 4:
            z = self.z[loc[0],3]
            thistype = self.type4[loc[0]]
        elif self.znum == 5:
            z = self.z[loc[0],4]
            thistype = self.type5[loc[0]]
        if self.var.get() == 0:
            if self.restframe.get() == 0:
                a.plot(self.wave, self.specs[self.fiber], color='black')
            elif self.restframe.get() == 1:
                a.plot(self.wave/(1+self.z[loc][0]), self.specs[self.fiber],
                       color='black')
        elif self.var.get() == 1:
            smooth = self.e4.get()
            if smooth is '':
                if self.restframe.get() == 0:
                    a.plot(self.wave, self.specs[self.fiber], color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.specs[self.fiber],
                           color='black')
            else:
                if self.restframe.get() == 0:
                    a.plot(self.wave, convolve(self.specs[self.fiber],
                                               Box1DKernel(int(smooth))),
                           color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), convolve(self.specs[self.fiber],
                                                     Box1DKernel(int(smooth))),
                           color='black')
            # Overplot model
            if len(loc) is not 0:
                if self.restframe.get() == 0:
                    #a.plot(self.wave, self.models[loc[0]], color='black')
                    # This for when multiple models are in redmonster file
                    a.plot(self.wave, self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if ((line*(1+z) > self.wave[0]) &
                                    (line*(1+z) < self.wave[-1])):
                                a.axvline(line*(1+z), color='blue',
                                          linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line*(1+z) > self.wave[0]) & (line*(1+z) < \
                                                              self.wave[-1]):
                                a.axvline(line*(1+z), color='red',
                                          linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='blue', linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='red', linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                a.set_title('Plate %s Fiber %s: z=%s class=%s zwarning=%s' %
                            (self.plate, self.fiber, z, thistype,
                             self.zwarning[loc[0]]))
            else:
                print('Fiber %s is not in redmonster-%s-%s.fits' % \
                        (self.fiber, self.plate, self.mjd))
                a.set_title('Plate %s Fiber %s' % (self.plate, self.fiber))

        if self.restframe.get() == 1:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]/(1+z)-100,self.wave[-1]/(1+z)+100,
                    lower_data,upper_data])
        elif self.restframe.get() == 0:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]-100,self.wave[-1]+100,lower_data,upper_data])
        a.set_xlabel('Wavelength ($\AA$)')
        a.set_ylabel('Flux ($10^{-17} erg\ cm^2 s^{-1} \AA^{-1}$)')
        canvas = FigureCanvasTkAgg(f, master=self.root)
        canvas.get_tk_widget().grid(row=0, column=5, rowspan=20)
        toolbar_frame = Frame(self.root)
        toolbar_frame.grid(row=20,column=5)
        toolbar = NavigationToolbar2TkAgg( canvas, toolbar_frame )
        canvas.show()
示例#35
0
    def on_trace_change(self, _name, _index, _mode):
        """Updates the number of plans with options dependent on number of benefits input."""
        for group in self.groups:
            group.grid_forget()
            group.destroy()
        self.groups = []
        rad_labels = [
            "Exact", "Gaussian", "Triangular", "Rectangular", "Discrete"
        ]
        figs = [
            none_dist(),
            gauss_dist(),
            tri_dist(),
            rect_dist(),
            disc_dist()
        ]
        self.choices = [[tk.StringVar() for ben in plan.bens.indiv]
                        for plan in self.data_cont.plan_list]
        rads = []
        self.ranges = []
        self.labels = []
        for plan in self.data_cont.plan_list:
            r_idx = 0
            self.groups.append(ttk.LabelFrame(self, text=plan.name))
            self.groups[-1].grid(row=4 + plan.num,
                                 sticky="ew",
                                 padx=FIELDX_PADDING,
                                 pady=FIELDY_PADDING)
            rads.append([])
            self.ranges.append([])
            self.labels.append([])
            for ben in plan.bens.indiv:
                choice = plan.bens.indiv.index(ben)
                self.choices[plan.num][choice].set(ben.dist)
                titles = ttk.Label(self.groups[-1],
                                   text=ben.title + " - $" +
                                   '{:,.2f}'.format(ben.amount),
                                   font=SMALL_FONT)
                titles.grid(row=r_idx,
                            column=0,
                            sticky="w",
                            padx=FIELDX_PADDING,
                            pady=FIELDY_PADDING)
                var = self.choices[plan.num][choice]
                rads[plan.num].append([
                    tk.Radiobutton(self.groups[-1], variable=var,
                                   value="none"),
                    tk.Radiobutton(self.groups[-1],
                                   variable=var,
                                   value="gauss"),
                    tk.Radiobutton(self.groups[-1], variable=var, value="tri"),
                    tk.Radiobutton(self.groups[-1], variable=var,
                                   value="rect"),
                    tk.Radiobutton(self.groups[-1],
                                   variable=var,
                                   value="discrete")
                ])
                self.ranges[plan.num].append([
                    tk.Entry(self.groups[-1],
                             width=int(ENTRY_WIDTH / 2),
                             font=SMALL_FONT) for i in range(6)
                ])
                self.labels[plan.num].append([])
                for col in range(5):
                    fig_label = ttk.Label(self.groups[-1])
                    fig_label.grid(row=r_idx + 1, column=col)
                    fig = figs[col]
                    canvas = FigureCanvasTkAgg(fig, master=fig_label)
                    canvas.get_tk_widget().grid(row=1, column=col + 1)
                    canvas.show()
                    rads[plan.num][choice][col].grid(row=r_idx + 3, column=col)
                    rad_label = ttk.Label(self.groups[-1],
                                          text=rad_labels[col],
                                          font=SMALL_FONT)
                    rad_label.grid(row=r_idx + 2, column=col)

                if self.choices[plan.num][choice].get() == "none":
                    r_idx += 4
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                elif self.choices[plan.num][choice].get() == "gauss":
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1],
                                 text="Standard Deviation ($)")
                    ]
                    self.labels[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=0)
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                    self.ranges[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=1)
                    r_idx += 5
                elif self.choices[plan.num][choice].get() == "discrete":
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1], text="Lowest Amount ($)"),
                        tk.Label(self.groups[-1], text="Middle Amount ($)"),
                        tk.Label(self.groups[-1], text="Highest Amount ($)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Lowest Amount (%)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Middle Amount (%)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Highest Amount (%)")
                    ]
                    for label in self.labels[plan.num][choice][0:3]:
                        label.grid(row=r_idx +
                                   self.labels[plan.num][choice].index(label) +
                                   5,
                                   column=0)
                    for label in self.labels[plan.num][choice][3:6]:
                        label.grid(row=r_idx +
                                   self.labels[plan.num][choice].index(label) +
                                   2,
                                   column=2)
                    for entry in self.ranges[plan.num][choice][0:3]:
                        entry.grid(row=r_idx +
                                   self.ranges[plan.num][choice].index(entry) +
                                   5,
                                   column=1,
                                   padx=FIELDX_PADDING,
                                   pady=FIELDY_PADDING)
                    for entry in self.ranges[plan.num][choice][3:6]:
                        entry.grid(row=r_idx +
                                   self.ranges[plan.num][choice].index(entry) +
                                   2,
                                   column=3,
                                   padx=FIELDX_PADDING,
                                   pady=FIELDY_PADDING)
                    r_idx += 8
                else:
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1], text="Lower Bound ($)"),
                        tk.Label(self.groups[-1], text="Upper Bound ($)")
                    ]
                    self.labels[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=0)
                    self.labels[plan.num][choice][1].grid(row=r_idx + 4,
                                                          column=2)
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                    self.ranges[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=1)
                    self.ranges[plan.num][choice][1].grid(row=r_idx + 4,
                                                          column=3)
                    r_idx += 5
                for entry in self.ranges[plan.num][choice]:
                    try:
                        text = ben.range[self.ranges[plan.num][choice].index(
                            entry)]
                        text = '{:,.2f}'.format(float(text))
                    except ValueError:
                        text = ben.range[self.ranges[plan.num][choice].index(
                            entry)]
                    entry.insert(tk.END, text)
示例#36
0
class DemoApp(Frame):
    def __init__(self, master=None, audio_output="0,0", do_blelight=False, do_headset=False):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()
        self.output_fields = [self.sttField, self.healthField, self.bleligthField, self.bluetoothField]
        self.audio_output = audio_output
        self.do_blelight = do_blelight
        self.do_headset = do_headset
        self.row = 1
        self.pltimg = None
        self.health_cfg = ConfigParser.ConfigParser()
        self.health_cfg.read("healthrecord.ini")
        self.lang_idx = 0
        # matplotlib
        self.fig = Figure(figsize=(5,4))
        self.ax1 = self.fig.add_subplot(311)
        self.ax2 = self.fig.add_subplot(312)
        self.ax3 = self.fig.add_subplot(313)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.healthRecord)
        matplotlib.rcParams.update({'font.size': 9})

    def get_bw_list(self, who):
        str_list = list(self.health_cfg.get(who, 'body_weight', "").split(','))
        int_list = map(int, str_list)
        return int_list

    def get_bp_list(self, who):
        str_list = list(self.health_cfg.get(who, 'blood_pressure', "").split(','))
        int_list = map(int, str_list)
        return int_list

    def get_bs_list(self, who):
        str_list = list(self.health_cfg.get(who, 'blood_sugar', "").split(','))
        int_list = map(int, str_list)
        return int_list

    def status_handler(self, status):
        if status == 1: # ready
            self.sttText["text"] = "Voice(%s)" % ("CH" if self.lang_idx == 0 else "EN")
            self.output_fields[0].delete("1.0", END)
            self.row = 1
        else:
            self.sttText["text"] = "Voice(...)"

    def blelight_done(self):
        self.bleligthText["text"] = "BLE Light"
        
    def speak(self, spk_str):
        cmd = "/usr/bin/espeak -vzh+f5 %s --stdout | aplay -D plughw:%s" % (spk_str, self.audio_output)
        subprocess.Popen(cmd, shell=True)

    def show_health_plot(self, val):
        idx = val & 0x0F
        who = 'small_white' if idx==0x00 else 'small_black'
        who_zh = u'小白' if idx==0x00 else u'小黑'
        who_bw = health_record[who_zh + u'体重']
        who_bp = health_record[who_zh + u'血压']
        who_bs = health_record[who_zh + u'血糖']

        self.ax1.clear()
        self.ax2.clear()
        self.ax3.clear()

        self.ax1.set_title(u'Whity' if idx==0x00 else u'Black')
        self.ax1.plot(self.get_bw_list(who) + ([who_bw] if who_bw != 0 else []), 'ro-', label='body weight')
        self.ax1.set_ylim([30,100])
        self.ax1.legend(loc=2)
        self.ax1.text(15,  80, r'avg=%.2f, today=%d' % (numpy.mean(self.get_bw_list(who) + [who_bw]), who_bw), fontsize=9)

        self.ax2.plot(self.get_bp_list(who) + ([who_bp] if who_bp != 0 else []), 'go-', label='blood pressure')
        self.ax2.set_ylim([60,220])
        self.ax2.legend(loc=2)
        self.ax2.text(15, 180, r'avg=%.2f, today=%d' % (numpy.mean(self.get_bp_list(who) + [who_bp]), who_bp), fontsize=9)

        self.ax3.plot(self.get_bs_list(who) + ([who_bs] if who_bs != 0 else []), 'bo-', label='blood sugar')
        self.ax3.set_ylim([50,200])
        self.ax3.legend(loc=2)
        self.ax3.text(15, 160, r'avg=%.2f, today=%d' % (numpy.mean(self.get_bs_list(who) + [who_bs]), who_bs), fontsize=9)

        self.canvas.show()
        self.canvas.get_tk_widget().pack()

    def stt_handler(self, msg):
        if msg.has_key('results') and len(msg['results']) > 0:
            # vars
            event_type = 0 # 0: stt, 1: health, 2: blelight, 3: headset
            event_key = None
            event_data = None
            confidence = 0.0

            # get transcript
            bFinal = msg['results'][0]['final']
            if bFinal:
                confidence = msg['results'][0]['alternatives'][0]['confidence']
                #print confidence
            transcript = unicode(msg['results'][0]['alternatives'][0]['transcript'])
            if self.is_chinese(transcript):
                transcript = transcript.replace(u' ', '')

            # test if health (1)
            if bFinal:
                for key in health_patterns.keys():
                    if key in transcript:
                        val = self.text_to_number(transcript[4:])
                        if val != 0 or u'记录' in transcript:
                            event_type = 1
                            event_key  = key
                            event_data = val
                            break
            # test if blelight (2)
            if bFinal:
                for key in blelight_patterns.keys():
                    if key in transcript:
                        event_type = 2
                        event_key  = key
                        break
            # test if headset (3)
            if bFinal:
                for key in headset_patterns.keys():
                    if key in transcript:
                        event_type = 3
                        event_key  = key
                        event_data = headset_patterns[key]
                        break

            # test if language switch command ?
            if bFinal:
                for key in change_lang_patterns.keys():
                    if key in transcript:
                        event_type = 4
                        event_key  = key
                        event_data = change_lang_patterns[key]
                        self.lang_idx = (1 if self.lang_idx == 0 else 0)
                        break

            # show transcript in corresponding field
            self.output_fields[0].delete("%s.0"%(self.row), "%s.1024"%(self.row))
            self.output_fields[0].insert("%s.0"%(self.row), transcript)
            self.output_fields[0].see("end")
            if bFinal == True:
                self.output_fields[0].insert(END, '\n')
                if event_type != 0 and event_type < 4:
                    self.output_fields[event_type].insert(END, transcript + '\n')
                    self.output_fields[event_type].see("end")
                self.row = self.row + 1

            # do health
            if event_type == 1 and bFinal == True:
                val = health_patterns[event_key]
                if (val & 0x80) == 0x80:    # it's show-record command
                    self.show_health_plot(val)
                else:                       # it's data, save it to health_record and show plot
                    self.speak(transcript)
                    health_record[event_key] = event_data
                    self.show_health_plot(val)
            # do blelight
            elif event_type == 2 and self.do_blelight == True and blelights != None:
                for val in blelight_patterns[event_key]:
                    blelights.control(val[0], val[1])
            # do headset
            elif event_type == 3 and self.do_headset == True and csr8670 != None:
                csr8670.do_func(event_data)

            # do language switch
            elif event_type == 4:
                stt_client.change_lang(event_data)

    def text_to_number(self, txt):
        ttn_patterns = {u'九':9, u'八':8, u'七':7, u'六':6, u'五':5, u'四':4, u'三':3, u'二':2, u'一':1,}
        sum = 0
        if u'百' in txt :
            idx = txt.index(u'百')
            txt_digit = txt[idx - 1]
            digit = ttn_patterns[txt_digit]
            sum += digit * 100

        if u'十' in txt :
            idx = txt.index(u'十')
            txt_digit = txt[idx - 1]
            digit = ttn_patterns[txt_digit]
            sum += digit * 10
            if len(txt) > idx + 1:
                txt_digit = txt[idx + 1]
                try:
                    sum += ttn_patterns[txt_digit]
                except:
                    pass

        return sum

    def clear_all_fileds(self):
        if hasattr(self, 'output_fields'):
            for f in self.output_fields:
                f.delete('1.0', END)
            self.row = 1

    def is_chinese(self, string):
        for uchar in string:
            if ord(uchar) in [0x20, 0x0D, 0x0A]:
                continue
            if not (uchar >= u'\u4e00' and uchar <= u'\u9fa5'):
                return False
        return True

    def test_function(self):
        self.sttText["text"] = "*Voice*"
        stt_client.change_lang('en-US_BroadbandModel')

    def createWidgets(self):
        # Watson STT
        self.sttText = Label(self)
        self.sttText["text"] = "*Voice*"
        self.sttText.grid(row=0, column=0)
        self.sttField = Text(self, height=4, width=56, font=(None, 12))
        self.sttField.grid(row=0, column=1, columnspan=6, sticky=W)

        # health
        self.healthText = Label(self)
        self.healthText["text"] = "Health"
        self.healthText.grid(row=1, column=0)
        self.healthField = Text(self, height=4, width=16, font=(None, 12))
        self.healthField.grid(row=1, column=1, columnspan=2, sticky=W)
        self.healthRecord = Canvas(self, width=400, height=320)
        self.healthRecord.grid(row=1, column=3, rowspan=3, columnspan=4)

        # blelight
        self.bleligthText = Label(self)
        self.bleligthText["text"] = "*BLE Light*"
        self.bleligthText.grid(row=2, column=0)
        self.bleligthField = Text(self, height=4, width=16, font=(None, 12))
        self.bleligthField.grid(row=2, column=1, columnspan=2, sticky=W)

        # headset
        self.bluetoothText = Label(self)
        self.bluetoothText["text"] = "*HeadSet*"
        self.bluetoothText.grid(row=3, column=0)
        self.bluetoothField = Text(self, height=4, width=16, font=(None, 12))
        self.bluetoothField.grid(row=3, column=1, columnspan=2, sticky=W)

        # buttons
        #self.testBtn = Button(self, text = "Test", command = self.test_function)
        #self.testBtn.grid(row=4, column=4)
        self.clearBtn = Button(self, text = "Clear", command = self.clear_all_fileds)
        self.clearBtn.grid(row=4, column=5)
        self.exitBtn = Button(self, text = "Exit", command = lambda:root.destroy())
        self.exitBtn.grid(row=4, column=6)
示例#37
0
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
matplotlib.use('TkAgg')
root = Tk.Tk()
root.title("脚本之家测试 - matplotlib in TK")
#设置图形尺寸与质量
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3, 0.01)
s = sin(2 * pi * t)
#绘制图形
a.plot(t, s)
#把绘制的图形显示到tkinter窗口上
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
#把matplotlib绘制图形的导航工具栏显示到tkinter窗口上
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)


#定义并绑定键盘事件处理函数
def on_key_event(event):
    print('you pressed %s' % event.key)
    key_press_handler(event, canvas, toolbar)
    canvas.mpl_connect('key_press_event', on_key_event)


#按钮单击事件处理函数
示例#38
0
class WaveformFrame (ttk.Frame):
    def __init__(self, parent, row, col):
        ttk.Frame.__init__(self, parent, padding = "3 3 12 12")
        self.parent = parent
        self.grid(row=row, column=col, columnspan=2,
                  sticky=(tk.E, tk.W, tk.N, tk.S))
   

        self.runbutton = tk.Button(self, 
                                   text='Ejecutar',
                                   command=self.runwaveform)
        self.runbutton.grid(row = 1, column = 0, sticky = tk.E)
        
        self.stopbutton = tk.Button(self, 
                                   text='Stop',
                                   command=self.stopwaveform)
        self.stopbutton.grid(row = 1, column = 1, sticky = tk.W)
        self.running_mode(False)
        
        self.helpbutton = tk.Button(self, 
                                   text='Ayuda',
                                   command=self.show_help)
        self.helpbutton.grid(row = 1, column = 3, sticky = tk.E)
        
        self.running_mode(False)
        self.update()
            
    def update(self):
        
        xs = self.parent.ts
        ys = self.parent.vs
        
        f = Figure(figsize=(6, 2), dpi=100, facecolor='none',
                   tight_layout=True)
        
        plt = f.add_subplot(111)
        plt.step(xs, ys, '-', where='post')
        plt.set_xlabel('Tiempo (s)')
        if self.parent.progframe.get('currentmode'):
            plt.set_ylabel('Corriente (A)')
        else:
            plt.set_ylabel('Voltage (V)')
        
        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas._tkcanvas.grid(row=0,column=0, columnspan=4,
                                   sticky = tk.E)
        
    def runwaveform(self):
        self.parent.runwaveform()
        
    def stopwaveform(self):
        self.parent.stopwaveform()
        
    def show_help(self):
        
        text = """
Sleep time es el tiempo que el programa esperará entre el envío de dos comandos consecutivos. Si no se espera el tiempo suficiente es posible que la fuente ignore el segundo comando. El programa utilizarà este comando para crear las rampas a partir del archivo CSV, si se utiliza esta opción. Si en el archivo se especifican intervalos de tiempo más cortos que el sleep time es posible que se pierdan puntos del perfil.

Los campos PV syntax y PC syntax deben contener la síntaxis que debe seguir el programa para programar tensión y corriente, en forma de string formateable por Python.
Por ejemplo, PV {:06.3f} enviará comandos formados por los carácteres PV, un espacio y el valor de tensión o corriente usando 6 carácteres, 3 de ellos dedicados a la parte decimal, de manera que el programa utilizará el comando PV 05.000 para programar 5 V.

Los comandos de setup se ejecutarán antes de cada perfil. Puede usarse esta opción para enviar comandos que configuren la fuente en modo remoto, o configurar la corriente antes de programar un perfil en tensión o viceversa.

Consultar el manual de la fuente para encontrar los parámetros adecuados.
"""
        helpwindow = InfoDialog(self, text, title="Ayuda")
        self.parent.wait_window(helpwindow)
        
    def running_mode(self, running = False):
        self.running = running
        if running:
            self.runbutton.config(state=tk.DISABLED)
            self.stopbutton.config(state=tk.NORMAL)
        else:
            self.runbutton.config(state=tk.NORMAL)
            self.stopbutton.config(state=tk.DISABLED)
示例#39
0
class mclass:
    def __init__(self, window):
        self.window = window
        self.window.resizable(width=False, height=False)

        self.fig = Figure(figsize=(7.2, 7.2))
        self.ax = self.fig.add_subplot(111, projection='polar')

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.window)
        self.canvas.get_tk_widget().pack(side=RIGHT, padx=0, pady=0)
        self.canvas.show()

        self.statusCanvas = Canvas(self.window)
        self.statusCanvas.pack(side=LEFT,
                               padx=5,
                               pady=5,
                               fill=BOTH,
                               expand=True)
        self.label = Label(
            self.statusCanvas,
            text="LAT = 50.3633 \n LON = 30.4961 \n alt = 211.8")
        self.label.pack(side=LEFT, padx=5, pady=5)

        self.plot()

    def plot(self):
        self.window.title("Sky Safety Manager >>>>>> UTC: " +
                          datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))

        with open("current_status", 'r') as status_file:
            status = status_file.readline()
        self.statusLable = self.statusCanvas.create_rectangle(
            0, 0, 120, 300, fill='red' if status == "Danger" else "green")

        self.ax.clear()
        self.ax.set_theta_zero_location('S')
        self.ax.set_theta_direction(-1)
        self.ax.set_rmax(90)
        self.ax.set_rticks(np.arange(0, 91, 10))  # less radial ticks
        self.ax.set_yticklabels(self.ax.get_yticks()[::-1])
        self.ax.set_rlabel_position(0)
        self.ax.grid(True)

        r = np.arange(0, 90, 1)
        theta = r

        positions = []
        with open("current_positions.csv") as csv_file:
            read = csv.reader(csv_file, delimiter=',')
            for row in read:
                row[2] = Decimal(row[2])
                row[3] = Decimal(row[3])
                positions.append(row[0:])
        # sat_positions = [["sat1", 30, 0], ["sat2", 60, 90], ["sat3", 30, 180], ["sat4", 50, 270]]
        for (type, PRN, Az, E) in positions:
            if type == "SAT":
                self.ax.annotate(
                    str(PRN),
                    xy=(radians(Az), r2el(E)),  # theta, radius
                    bbox=dict(boxstyle="circle", fc='red', alpha=0.3,
                              pad=1.25),
                    horizontalalignment='center',
                    verticalalignment='center')
            else:
                self.ax.annotate(str(hex(int(PRN)))[2:],
                                 xy=(radians(Az), r2el(E)))
            self.ax.plot(radians(Az), r2el(E), '.')

        self.ax.plot(d2r(theta), r2el(r), linewidth=0)
        self.fig.tight_layout()
        self.canvas.draw()

        window.after(1200, self.plot)
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.configure(background='white')
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        xunit = w / 1000
        yunit = h / 1000

        label = tk.Label(self,
                         text="PID Controller\nand\nMonitering\n\nGROUP 5",
                         font=LARGE_FONT,
                         background='white')
        label.place(x=xunit * 20, y=yunit * 20)

        self.KpLabel = tk.Label(self, text="Kp:", background='white')
        self.KpLabel.place(x=xunit * 10, y=yunit * 325)
        self.KiLabel = tk.Label(self, text="Ki:", background='white')
        self.KiLabel.place(x=xunit * 10, y=yunit * 375)
        self.KdLabel = tk.Label(self, text="Kd:", background='white')
        self.KdLabel.place(x=xunit * 10, y=yunit * 425)
        self.Setpoint = tk.Label(self, text="Sp:", background='white')
        self.Setpoint.place(x=xunit * 10, y=yunit * 475)

        CurrentKp = tk.Label(self, text="Current Kp:", background='white')
        CurrentKp.place(x=xunit * 10, y=yunit * 625)
        self.CurrentKp = tk.Label(self,
                                  text=str(PID_datahouse.Kp),
                                  background='white')
        self.CurrentKp.place(x=xunit * 85, y=yunit * 625)

        CurrentKi = tk.Label(self, text="Current Ki:", background='white')
        CurrentKi.place(x=xunit * 10, y=yunit * 675)
        self.CurrentKi = tk.Label(self,
                                  text=str(PID_datahouse.Ki),
                                  background='white')
        self.CurrentKi.place(x=xunit * 85, y=yunit * 675)

        CurrentKd = tk.Label(self, text="Current Kd:", background='white')
        CurrentKd.place(x=xunit * 10, y=yunit * 725)
        self.CurrentKd = tk.Label(self,
                                  text=str(PID_datahouse.Kd),
                                  background='white')
        self.CurrentKd.place(x=xunit * 85, y=yunit * 725)

        CurrentSetpoint = tk.Label(self,
                                   text="Current Setpoint: ",
                                   background='white')
        CurrentSetpoint.place(x=xunit * 10, y=yunit * 775)
        self.CurrentSetpoint = tk.Label(self,
                                        text=str(PID_datahouse.Sp),
                                        background='white')
        self.CurrentSetpoint.place(x=xunit * 85, y=yunit * 775)

        self.KpEntry = ttk.Entry(self)
        self.KpEntry.place(x=xunit * 30, y=yunit * 325)
        self.KiEntry = ttk.Entry(self)
        self.KiEntry.place(x=xunit * 30, y=yunit * 375)
        self.KdEntry = ttk.Entry(self)
        self.KdEntry.place(x=xunit * 30, y=yunit * 425)
        self.SpEntry = ttk.Entry(self)
        self.SpEntry.place(x=xunit * 30, y=yunit * 475)

        button1 = ttk.Button(self,
                             text='Connect',
                             command=lambda: self.connectingFunc())
        button1.place(x=xunit * 30, y=yunit * 200)

        button2 = ttk.Button(self,
                             text='Disconnect',
                             command=lambda: self.disconnectingFunc())
        button2.place(x=xunit * 30, y=yunit * 250)

        button3 = ttk.Button(self,
                             text='Update',
                             command=lambda: self.updateFromEntry())
        button3.place(x=xunit * 30, y=yunit * 525)

        button3 = ttk.Button(self,
                             text='Quit',
                             command=lambda: self.quitFunc(controller))
        button3.place(x=xunit * 30, y=yunit * 875)

        self.ErrorValue = tk.Label(self,
                                   text="No Error",
                                   background='Green',
                                   width=15,
                                   anchor='w')
        self.ErrorValue.place(x=xunit * 100, y=yunit * 526)

        self.ErrorConnect = tk.Label(self,
                                     text="Not Connected",
                                     background='red',
                                     width=15,
                                     anchor='w')
        self.ErrorConnect.place(x=xunit * 100, y=yunit * 200)

        canvas = FigureCanvasTkAgg(PID_datahouse.graph, self)
        canvas.show()

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.place(x=xunit * 250, y=00)
示例#41
0
#!/usr/apps/Python/bin/python
import matplotlib, sys

matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from Tkinter import *

master = Tk()
master.title("Hello World!")
#-------------------------------------------------------------------------------

f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)
a.plot(t, s)

dataPlot = FigureCanvasTkAgg(f, master=master)
dataPlot.show()
dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
#-------------------------------------------------------------------------------
master.mainloop()
示例#42
0
class PyAbel:  #(tk.Tk):
    def __init__(self, parent):
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.fn = None
        self.old_fn = None
        self.old_method = None
        self.old_fi = None
        self.AIM = None
        self.rmx = (368, 393)

        # matplotlib figure
        self.f = Figure(figsize=(2, 6))
        self.gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
        self.gs.update(wspace=0.2, hspace=0.2)

        self.plt = []
        self.plt.append(self.f.add_subplot(self.gs[0]))
        self.plt.append(self.f.add_subplot(self.gs[1]))
        self.plt.append(
            self.f.add_subplot(self.gs[2],
                               sharex=self.plt[0],
                               sharey=self.plt[0]))
        self.plt.append(self.f.add_subplot(self.gs[3]))
        for i in [0, 2]:
            self.plt[i].set_adjustable('box-forced')

        # hide until have data
        for i in range(4):
            self.plt[i].axis("off")

        # tkinter
        # set default font size for buttons
        self.font = tkFont.Font(size=11)
        self.fontB = tkFont.Font(size=12, weight='bold')

        #frames top (buttons), text, matplotlib (canvas)
        self.main_container = tk.Frame(self.parent, height=10, width=100)
        self.main_container.pack(side="top", fill="both", expand=True)

        self.button_frame = tk.Frame(self.main_container)
        #self.info_frame = tk.Frame(self.main_container)
        self.matplotlib_frame = tk.Frame(self.main_container)

        self.button_frame.pack(side="top", fill="x", expand=True)
        #self.info_frame.pack(side="top", fill="x", expand=True)
        self.matplotlib_frame.pack(side="top", fill="both", expand=True)

        self._menus()
        self._button_area()
        self._plot_canvas()
        self._text_info_box()

    def _button_frame(self):
        self.button_frame = tk.Frame(self.main_container)
        self.button_frame.pack(side="top", fill="x", expand=True)
        self._menus()

    def _menus(self):
        # menus with callback ----------------
        # duplicates the button interface
        self.menubar = tk.Menu(self.parent)
        self.transform_method = tk.IntVar()
        self.center_method = tk.IntVar()

        # File - menu
        self.filemenu = tk.Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Load image file",
                                  command=self._loadimage)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self._quit)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        # Process - menu
        self.processmenu = tk.Menu(self.menubar, tearoff=0)
        #self.processmenu.add_command(label="Center image", command=self._center)

        self.subcent = tk.Menu(self.processmenu)
        for cent in center_methods:
            self.subcent.add_radiobutton(label=cent,
                                         var=self.center_method,
                                         val=center_methods.index(cent),
                                         command=self._center)
        self.processmenu.add_cascade(label="Center image",
                                     menu=self.subcent,
                                     underline=0)

        self.submenu = tk.Menu(self.processmenu)
        for method in Abel_methods:
            self.submenu.add_radiobutton(label=method,
                                         var=self.transform_method,
                                         val=Abel_methods.index(method),
                                         command=self._transform)
        self.processmenu.add_cascade(label="Inverse Abel transform",
                                     menu=self.submenu,
                                     underline=0)

        self.processmenu.add_command(label="Speed distribution",
                                     command=self._speed)
        self.processmenu.add_command(label="Angular distribution",
                                     command=self._anisotropy)
        self.angmenu = tk.Menu(self.processmenu)
        self.menubar.add_cascade(label="Processing", menu=self.processmenu)

        # view - menu
        self.viewmenu = tk.Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label="Raw image", command=self._display)
        self.viewmenu.add_command(label="Inverse Abel transformed image",
                                  command=self._transform)
        self.viewmenu.add_command(label="view buttons",
                                  command=self._on_buttons)
        self.menubar.add_cascade(label="View", menu=self.viewmenu)

    def _button_area(self):
        # grid layout
        # make expandable
        for col in range(5):
            self.button_frame.columnconfigure(col, weight=1)
            self.button_frame.rowconfigure(col, weight=1)

        # column 0 ---------
        # load image file button
        self.load = tk.Button(master=self.button_frame,
                              text="load image",
                              font=self.fontB,
                              fg="dark blue",
                              command=self._loadimage)
        self.load.grid(row=0, column=0, sticky=tk.W, padx=(5, 10), pady=(5, 0))
        self.sample_image = ttk.Combobox(master=self.button_frame,
                                         font=self.font,
                                         values=[
                                             "from file", "from transform",
                                             "sample dribinski",
                                             "sample Ominus"
                                         ],
                                         width=14,
                                         height=4)
        self.sample_image.current(0)
        self.sample_image.grid(row=1, column=0, padx=(5, 10))

        # quit
        self.quit = tk.Button(master=self.button_frame,
                              text="Quit",
                              font=self.fontB,
                              fg="dark red",
                              command=self._quit)
        self.quit.grid(row=3, column=0, sticky=tk.W, padx=(5, 10), pady=(0, 5))

        # column 1 -----------
        # center image
        self.center = tk.Button(master=self.button_frame,
                                text="center image",
                                anchor=tk.W,
                                font=self.fontB,
                                fg="dark blue",
                                command=self._center)
        self.center.grid(row=0, column=1, padx=(0, 20), pady=(5, 0))
        self.center_method = ttk.Combobox(master=self.button_frame,
                                          font=self.font,
                                          values=center_methods,
                                          width=11,
                                          height=4)
        self.center_method.current(1)
        self.center_method.grid(row=1, column=1, padx=(0, 20))

        # column 2 -----------
        # Abel transform image
        self.recond = tk.Button(master=self.button_frame,
                                text="Abel transform image",
                                font=self.fontB,
                                fg="dark blue",
                                command=self._transform)
        self.recond.grid(row=0, column=2, padx=(0, 10), pady=(5, 0))

        self.transform = ttk.Combobox(master=self.button_frame,
                                      values=Abel_methods,
                                      font=self.font,
                                      width=10,
                                      height=len(Abel_methods))
        self.transform.current(2)
        self.transform.grid(row=1, column=2, padx=(0, 20))

        self.direction = ttk.Combobox(master=self.button_frame,
                                      values=["inverse", "forward"],
                                      font=self.font,
                                      width=8,
                                      height=2)
        self.direction.current(0)
        self.direction.grid(row=2, column=2, padx=(0, 20))

        # column 3 -----------
        # speed button
        self.speed = tk.Button(master=self.button_frame,
                               text="speed",
                               font=self.fontB,
                               fg="dark blue",
                               command=self._speed)
        self.speed.grid(row=0, column=5, padx=20, pady=(5, 0))

        self.speedclr = tk.Button(master=self.button_frame,
                                  text="clear plot",
                                  font=self.font,
                                  command=self._speed_clr)
        self.speedclr.grid(row=1, column=5, padx=20)

        # column 4 -----------
        # anisotropy button
        self.aniso = tk.Button(master=self.button_frame,
                               text="anisotropy",
                               font=self.fontB,
                               fg="dark blue",
                               command=self._anisotropy)
        self.aniso.grid(row=0, column=6, pady=(5, 0))

        self.subframe = tk.Frame(self.button_frame)
        self.subframe.grid(row=1, column=6)
        self.rmin = tk.Entry(master=self.subframe,
                             text='rmin',
                             width=3,
                             font=self.font)
        self.rmin.grid(row=0, column=0)
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.lbl = tk.Label(master=self.subframe, text="to", font=self.font)
        self.lbl.grid(row=0, column=1)
        self.rmax = tk.Entry(master=self.subframe,
                             text='rmax',
                             width=3,
                             font=self.font)
        self.rmax.grid(row=0, column=2)
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])

        # turn off button interface
        self.hide_buttons = tk.Button(master=self.button_frame,
                                      text="hide buttons",
                                      font=self.fontB,
                                      fg='grey',
                                      command=self._hide_buttons)
        self.hide_buttons.grid(row=3, column=6, sticky=tk.E, pady=(0, 20))

    def _text_info_box(self):
        # text info box ---------------------
        self.text = ScrolledText(master=self.button_frame,
                                 height=6,
                                 fg="mediumblue",
                                 bd=1,
                                 relief=tk.SUNKEN)
        self.text.insert(
            tk.END, "Work in progress, some features may"
            " be incomplete ...\n")
        self.text.insert(
            tk.END, "To start: load an image data file using"
            " e.g. data/O2-ANU1024.txt.bz2\n"
            " (1) load image button (or file menu)\n"
            " (2) center image\n"
            " (3) Abel transform\n"
            " (4) speed\n"
            " (5) anisotropy\n"
            " (6) Abel transform <- change\n"
            " (:) repeat\n")
        self.text.grid(row=3, column=1, columnspan=3, padx=5)

    def _plot_canvas(self):
        # matplotlib canvas --------------------------
        self.canvas = FigureCanvasTkAgg(self.f, master=self.matplotlib_frame)
        #self.cid = self.canvas.mpl_connect('button_press_event', self._onclick)

        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.parent)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(anchor=tk.W,
                                   side=tk.TOP,
                                   fill=tk.BOTH,
                                   expand=1)

    def _onclick(self, event):
        print('button={:d}, x={:f}, y={:f}, xdata={:f}, ydata={:f}'.format(
            event.button, event.x, event.y, event.xdata, event.ydata))

    # call back functions -----------------------
    def _display(self):
        if self.fn is None:
            self._loadimage()

        # display image
        self.plt[0].imshow(self.IM, vmin=0)
        #rows, cols = self.IM.shape
        #r2 = rows/2
        #c2 = cols/2
        #self.a.plot((r2, r2), (0, cols), 'r--', lw=0.1)
        #self.a.plot((0, rows), (c2, c2),'r--', lw=0.1)
        #self.f.colorbar(self.a.get_children()[2], ax=self.f.gca())
        self.plt[0].set_title("raw image", fontsize=10)
        self.canvas.show()

    def _loadimage(self):

        if self.fn is not None:
            # clear old plot
            for i in range(4):
                self._clr_plt(i)
                self.plt[i].axis("off")

        self.fn = self.sample_image.get()
        # update what is occurring text box
        self.text.insert(tk.END, "\nloading image file {:s}".format(self.fn))
        self.text.see(tk.END)
        self.canvas.show()

        if self.fn == "from file":
            self.fn = askopenfilename()
            # read image file
            if ".txt" in self.fn:
                self.IM = np.loadtxt(self.fn)
            else:
                self.IM = imread(self.fn)
        elif self.fn == "from transform":
            self.IM = self.AIM
            self.AIM = None
            for i in range(1, 4):
                self._clr_plt(i)
                self.plt[i].axis("off")
            self.direction.current(0)
        else:
            self.fn = self.fn.split(' ')[-1]
            self.IM = abel.tools.analytical.SampleImage(n=1001,
                                                        name=self.fn).image
            self.direction.current(1)  # raw images require 'forward' transform
            self.text.insert(tk.END,
                             "\nsample image: (1) Abel transform 'forward', ")
            self.text.insert(tk.END,
                             "              (2) load 'from transform', ")
            self.text.insert(tk.END,
                             "              (3) Abel transform 'inverse', ")
            self.text.insert(tk.END, "              (4) Speed")
            self.text.see(tk.END)

        # if even size image, make odd
        if self.IM.shape[0] % 2 == 0:
            self.IM = shift(self.IM, (-0.5, -0.5))[:-1, :-1]

        self.old_method = None
        self.AIM = None
        self.action = "file"
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])

        # show the image
        self._display()

    def _center(self):
        self.action = "center"

        center_method = self.center_method.get()
        # update information text box
        self.text.insert(tk.END, "\ncentering image using {:s}".\
                         format(center_method))
        self.canvas.show()

        # center image via chosen method
        self.IM = abel.tools.center.center_image(self.IM,
                                                 center=center_method,
                                                 odd_size=True)
        #self.text.insert(tk.END, "\ncenter offset = {:}".format(self.offset))
        self.text.see(tk.END)

        self._display()

    def _transform(self):
        #self.method = Abel_methods[self.transform_method.get()]
        self.method = self.transform.get()
        self.fi = self.direction.get()

        if self.method != self.old_method or self.fi != self.old_fi:
            # Abel transform of whole image
            self.text.insert(tk.END,"\n{:s} {:s} Abel transform:".\
                             format(self.method, self.fi))
            if self.method == "basex":
                self.text.insert(
                    tk.END, "\nbasex: first time calculation of the basis"
                    " functions may take a while ...")
            elif self.method == "direct":
                self.text.insert(
                    tk.END,
                    "\ndirect: calculation is slowed if Cython unavailable ..."
                )
            self.canvas.show()

            if self.method == 'linbasex':
                self.AIM = abel.Transform(
                    self.IM,
                    method=self.method,
                    direction=self.fi,
                    transform_options=dict(return_Beta=True))
            else:
                self.AIM = abel.Transform(
                    self.IM,
                    method=self.method,
                    direction=self.fi,
                    transform_options=dict(basis_dir='bases'),
                    symmetry_axis=None)
            self.rmin.delete(0, tk.END)
            self.rmin.insert(0, self.rmx[0])
            self.rmax.delete(0, tk.END)
            self.rmax.insert(0, self.rmx[1])

        if self.old_method != self.method or self.fi != self.old_fi or\
           self.action not in ["speed", "anisotropy"]:
            self.plt[2].set_title(self.method +
                                  " {:s} Abel transform".format(self.fi),
                                  fontsize=10)
            self.plt[2].imshow(self.AIM.transform,
                               vmin=0,
                               vmax=self.AIM.transform.max() / 5.0)
            #self.f.colorbar(self.c.get_children()[2], ax=self.f.gca())
            #self.text.insert(tk.END, "{:s} inverse Abel transformed image".format(self.method))

        self.text.see(tk.END)
        self.old_method = self.method
        self.old_fi = self.fi
        self.canvas.show()

    def _speed(self):
        self.action = "speed"
        # inverse Abel transform
        self._transform()
        # update text box in case something breaks
        self.text.insert(tk.END, "\nspeed distribution")
        self.text.see(tk.END)
        self.canvas.show()

        if self.method == 'linbasex':
            self.speed_dist = self.AIM.Beta[0]
            self.radial = self.AIM.radial
        else:
            # speed distribution
            self.radial, self.speed_dist = abel.tools.vmi.angular_integration(
                self.AIM.transform)

        self.plt[1].axis("on")
        self.plt[1].plot(self.radial,
                         self.speed_dist / self.speed_dist[10:].max(),
                         label=self.method)
        # make O2- look nice
        if self.fn.find('O2-ANU1024') > -1:
            self.plt[1].axis(xmax=500, ymin=-0.05)
        elif self.fn.find('VMI_art1') > -1:
            self.plt[1].axis(xmax=260, ymin=-0.05)

        self.plt[1].set_xlabel("radius (pixels)", fontsize=9)
        self.plt[1].set_ylabel("normalized intensity")
        self.plt[1].set_title("radial speed distribution", fontsize=12)
        self.plt[1].legend(fontsize=9, loc=0, frameon=False)

        self.action = None
        self.canvas.show()

    def _speed_clr(self):
        self._clr_plt(1)

    def _clr_plt(self, i):
        self.f.delaxes(self.plt[i])
        self.plt[i] = self.f.add_subplot(self.gs[i])
        self.canvas.show()

    def _anisotropy(self):
        def P2(x):  # 2nd order Legendre polynomial
            return (3 * x * x - 1) / 2

        def PAD(theta, beta, amp):
            return amp * (1 + beta * P2(np.cos(theta)))

        self.action = "anisotropy"
        self._transform()

        if self.method == 'linbasex':
            self.text.insert(tk.END,
                        "\nanisotropy parameter pixel range 0 to {}: "\
                        .format(self.rmx[1]))
        else:
            # radial range over which to follow the intensity variation with angle
            self.rmx = (int(self.rmin.get()), int(self.rmax.get()))
            self.text.insert(tk.END,
                        "\nanisotropy parameter pixel range {:} to {:}: "\
                        .format(*self.rmx))
        self.canvas.show()

        # inverse Abel transform
        self._transform()

        if self.method == 'linbasex':
            self.beta = self.AIM.Beta[1]
            self.radial = self.AIM.radial
            self._clr_plt(3)
            self.plt[3].axis("on")
            self.plt[3].plot(self.radial, self.beta, 'r-')
            self.plt[3].set_title("anisotropy", fontsize=12)
            self.plt[3].set_xlabel("radius", fontsize=9)
            self.plt[3].set_ylabel("anisotropy parameter")
            # make O2- look nice
            if self.fn.find('O2-ANU1024') > -1:
                self.plt[3].axis(xmax=500, ymin=-1.1, ymax=0.1)
            elif self.fn.find('VMI_art1') > -1:
                self.plt[3].axis(xmax=260, ymin=-1.1, ymax=2)
        else:
            # intensity vs angle
            self.beta, self.amp, self.rad, self.intensity, self.theta =\
               abel.tools.vmi.radial_integration(self.AIM.transform,\
                                                 radial_ranges=[self.rmx,])

            self.text.insert(tk.END,
                             " beta = {:g}+-{:g}".format(*self.beta[0]))

            self._clr_plt(3)
            self.plt[3].axis("on")

            self.plt[3].plot(self.theta, self.intensity[0], 'r-')
            self.plt[3].plot(self.theta,
                             PAD(self.theta, self.beta[0][0], self.amp[0][0]),
                             'b-',
                             lw=2)
            self.plt[3].annotate(
                "$\\beta({:d},{:d})={:.2g}\pm{:.2g}$".format(*self.rmx +
                                                             self.beta[0]),
                (-3, self.intensity[0].min() / 0.8))
            self.plt[3].set_title("anisotropy", fontsize=12)
            self.plt[3].set_xlabel("angle", fontsize=9)
            self.plt[3].set_ylabel("intensity")

        self.action = None
        self.canvas.show()

    def _hide_buttons(self):
        self.button_frame.destroy()

    def _on_buttons(self):
        self._button_frame()

    def _quit(self):
        self.parent.quit()  # stops mainloop
        self.parent.destroy()  # this is necessary on Windows to prevent
示例#43
0
class ViewWidget(object):
    """
        Draws images using the datasets recorded in the HDF5 file.  Also
        provides widgets to pick which dataset is displayed.
    """
    def __init__(self, f, master):

        self.f = f

        self.mainframe = tk.Frame(master=master)
        self.lbutton = tk.Button(self.mainframe,
                                 text="<= Back",
                                 command=self.back)
        self.rbutton = tk.Button(self.mainframe,
                                 text="Next =>",
                                 command=self.forward)
        self.loclabel = tk.Label(
            self.mainframe, text='To start, enter values and click "compute"')
        self.infolabel = tk.Label(
            self.mainframe,
            text='Or, click the "suggest" button for interesting locations')

        self.fig = Figure(figsize=(5, 5), dpi=100)
        self.plot = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.mainframe)
        self.canvas.show()

        self.loclabel.grid(row=0, column=1)
        self.infolabel.grid(row=1, column=1)
        self.lbutton.grid(row=2, column=0)
        self.canvas.get_tk_widget().grid(row=2, column=1)
        self.rbutton.grid(row=2, column=2)

        self.index = 0

        self.jumptolast()

    def draw_fractal(self):
        """ Read a dataset from the HDF5 file and display it """

        with file_lock:
            name = self.f.keys()[self.index]
            dset = self.f[name]
            arr = dset[...]
            start = dset.attrs['start']
            extent = dset.attrs['extent']
            self.loclabel["text"] = 'Displaying dataset "%s" (%d of %d)' % (
                dset.name, self.index + 1, len(self.f))
            self.infolabel[
                "text"] = "%(shape)s pixels, starts at %(start)s, extent %(extent)s" % dset.attrs

        self.plot.clear()
        self.plot.imshow(arr.transpose(),
                         cmap='jet',
                         aspect='auto',
                         origin='lower',
                         extent=(start.real, (start.real + extent.real),
                                 start.imag, (start.imag + extent.imag)))
        self.canvas.show()

    def back(self):
        """ Go to the previous dataset (in ASCII order) """
        if self.index == 0:
            print "Can't go back"
            return
        self.index -= 1
        self.draw_fractal()

    def forward(self):
        """ Go to the next dataset (in ASCII order) """
        if self.index == (len(self.f) - 1):
            print "Can't go forward"
            return
        self.index += 1
        self.draw_fractal()

    def jumptolast(self, *args):
        """ Jump to the last (ASCII order) dataset and display it """
        with file_lock:
            if len(self.f) == 0:
                print "can't jump to last (no datasets)"
                return
            index = len(self.f) - 1
        self.index = index
        self.draw_fractal()
示例#44
0
class PanelTool(Tkinter.Toplevel):
    def __init__(self, experiment=None):
        Tkinter.Toplevel.__init__(self)

        self.experiment = experiment
        self.n_panels = experiment.panel_n

        self.all_polygons = []
        self.press = None
        self.cur_xlim = None
        self.cur_ylim = None
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.xpress = None
        self.ypress = None
        self.last_down_time = None
        self.pts = []
        self.ax_points = []
        self.ax_lines = []
        self.curr_pt = None
        self.last_pt = None

        self.title("Panel tool")
        self.resizable(width=False, height=False)
        self.iconbitmap('logo.ico')

        self.fig = plt.Figure(figsize=(8., 8.))
        self.ax = self.fig.add_subplot(111)
        self.default_xlim = self.ax.get_xlim()
        self.default_ylim = self.ax.get_ylim()

        self.tk_fig_canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.tk_fig_canvas.show()
        self.tk_fig_canvas_widget = self.tk_fig_canvas.get_tk_widget()

        self.canvas = self.fig.canvas

        for tic in self.ax.xaxis.get_major_ticks():
            tic.tick1On = tic.tick2On = False
            tic.label1On = tic.label2On = False

        for tic in self.ax.yaxis.get_major_ticks():
            tic.tick1On = tic.tick2On = False
            tic.label1On = tic.label2On = False

        img_path = os.path.join(
            "../../data/",
            "5022_Test_Rep4_CAM01_ID-01_Date-3-7-2015_14-41.jpg")
        img = imread(img_path)
        self.ax.imshow(img)

        self.right_frame = Tkinter.Frame(master=self)

        self.pan_btns = []
        self.cur_btn = 0
        self.curr_poly = None

        for i in range(self.n_panels):
            pan_txt = "Panel %d" % (i + 1)
            self.pan_btns.append(
                Tkinter.Button(master=self.right_frame,
                               text=pan_txt,
                               command=lambda i=i: self.panel_btns(i)))
            self.pan_btns[-1].pack()

        self.pan_btns[0].config(relief=Tkinter.SUNKEN)

        self._zoom_init(base_scale=1.1)
        self._pan_init()
        self._labelling_init()

        self.tk_fig_canvas_widget.grid(
            in_=self,
            column=1,
            row=1,
            #columnspan=3,
            sticky='news')
        self.right_frame.grid(in_=self, column=2, row=1, sticky='news')

    def panel_btns(self, idx):
        # if idx == cur_btn:
        #     return

        self.pan_btns[self.cur_btn].config(relief=Tkinter.RAISED)

        self.pan_btns[idx].config(relief=Tkinter.SUNKEN)
        self.old_poly = self.all_polygons[self.cur_btn]
        # zp.update_poly_vals(old_poly)

        cur_btn = idx
        curr_poly = self.all_polygons[idx]
        #zp.set_new_poly(curr_poly)
        print(cur_btn)

    def _zoom_init(self, base_scale=2.0):
        def zoom(event):
            if event.inaxes != self.ax:
                return

            cur_xlim = self.ax.get_xlim()
            cur_ylim = self.ax.get_ylim()

            xdata = event.xdata  # get event x location
            ydata = event.ydata  # get event y location

            if event.button == 'up':
                # deal with zoom in
                scale_factor = 1 / base_scale
            elif event.button == 'down':
                # deal with zoom out
                scale_factor = base_scale
            else:
                # deal with something that should never happen
                scale_factor = 1
                print(event.button)

            new_width = (cur_xlim[1] - cur_xlim[0]) * scale_factor
            new_height = (cur_ylim[1] - cur_ylim[0]) * scale_factor

            relx = (cur_xlim[1] - xdata) / (cur_xlim[1] - cur_xlim[0])
            rely = (cur_ylim[1] - ydata) / (cur_ylim[1] - cur_ylim[0])

            x_low = xdata - new_width * (1 - relx)
            x_high = xdata + new_width * (relx)
            y_low = ydata - new_height * (1 - rely)
            y_high = ydata + new_height * (rely)

            if x_low < self.default_xlim[0]:
                x_low = self.default_xlim[0]
            if x_high > self.default_xlim[1]:
                x_high = self.default_xlim[1]

            # y upper and lower reversed as image not plot and coordinate
            # system is different
            if y_low > self.default_ylim[0]:
                y_low = self.default_ylim[0]
            if y_high < self.default_ylim[1]:
                y_high = self.default_ylim[1]

            self.ax.set_xlim([x_low, x_high])
            self.ax.set_ylim([y_low, y_high])
            self.canvas.draw()

        self.canvas.mpl_connect('scroll_event', zoom)

        return zoom

    def _pan_init(self):
        def onPress(event):
            if event.inaxes != self.ax:
                return
            self.cur_xlim = self.ax.get_xlim()
            self.cur_ylim = self.ax.get_ylim()
            self.press = self.x0, self.y0, event.xdata, event.ydata
            self.x0, self.y0, self.xpress, self.ypress = self.press

        def onRelease(event):
            self.press = None
            self.canvas.draw()

        def onMotion(event):
            if self.press is None:
                return
            if event.inaxes != self.ax:
                return
            dx = event.xdata - self.xpress
            dy = event.ydata - self.ypress
            self.cur_xlim -= dx
            self.cur_ylim -= dy

            #            if self.cur_xlim[0] < self.default_xlim[0]:
            #                self.cur_xlim[0] = self.default_xlim[0]
            #            if self.cur_xlim[1] > self.default_xlim[1]:
            #                self.cur_xlim[1] = self.default_xlim[1]
            #
            #            # y upper and lower reversed as image not plot and coordinate
            #            # system is different
            #            if self.cur_ylim[0] > self.default_ylim[0]:
            #                self.cur_ylim[0] = self.default_ylim[0]
            #            if self.cur_ylim[1] < self.default_ylim[1]:
            #                self.cur_ylim[1] = self.default_ylim[1]

            self.ax.set_xlim(self.cur_xlim)
            self.ax.set_ylim(self.cur_ylim)

            self.canvas.draw()

        # attach the call back
        self.canvas.mpl_connect('button_press_event', onPress)
        self.canvas.mpl_connect('button_release_event', onRelease)
        self.canvas.mpl_connect('motion_notify_event', onMotion)

        #return the function
        return onMotion

    def _labelling_init(self):
        def onPress(event):
            self.last_down_time = time.time()

        def onRelease(event):
            xdata, ydata = event.xdata, event.ydata
            self.cur_xlim = self.ax.get_xlim()
            self.cur_ylim = self.ax.get_ylim()

            if event.button == 3:
                if self.ax.lines:
                    line = self.ax_lines[-1][0]
                    del_idx = self.ax.lines.index(line)
                    del self.ax_lines[-1]
                    del self.ax.lines[del_idx]

                if self.ax.collections:
                    pt = self.ax_points[-1]
                    del_idx = self.ax.collections.index(pt)
                    del self.ax_points[-1]
                    del self.ax.collections[del_idx]

                if self.pts:
                    del self.pts[-1]

                if self.pts:
                    self.last_pt = self.pts[-1]
                else:
                    self.last_pt = None

                self.canvas.draw()
                return

            if xdata is None and ydata is None:
                return

            if time.time() - self.last_down_time > 0.12:
                self.last_down_time = None
                return

            self.last_down_time = None

            self.ax_points.append(self.ax.scatter(xdata, ydata))
            self.ax.set_xlim(self.cur_xlim)
            self.ax.set_ylim(self.cur_ylim)
            self.canvas.draw()

            self.curr_pt = (xdata, ydata)
            self.pts.append(self.curr_pt)

            if len(self.pts) == 1:
                self.last_pt = self.curr_pt
                return

            xs = [self.last_pt[0], self.curr_pt[0]]
            ys = [self.last_pt[1], self.curr_pt[1]]

            self.ax_lines.append(self.ax.plot(xs, ys, 'r'))

            self.last_pt = self.curr_pt

            self.canvas.draw()

        # attach the call back
        self.canvas.mpl_connect('button_press_event', onPress)
        self.canvas.mpl_connect('button_release_event', onRelease)
示例#45
0
class guiclass:
    def __init__(self, master):
        classes = find_classes()

        self.master = master
        master.title("Class builder")

        self.toolbar = tk.Frame(self.master)
        self.quit = tk.Button(self.toolbar, text="Close", command=master.quit)
        self.quit.pack(side="left")  # left side of parent, the toolbar frame

        self.next = tk.Button(self.toolbar,
                              text="Next",
                              command=self.update_image)
        self.next.pack(side="right")  # left side of parent, the toolbar frame

        self.choice = StringVar(self.master)
        self.choice.set(classes[0])
        self.w = OptionMenu(self.toolbar, self.choice, *classes)
        self.w.pack(side='right')

        #self.build_buttons(classes)
        #        self.other = tk.Button(self.toolbar,
        #                text="Other",command=self.other)
        #        self.other.pack(side="left") # left side of parent, the toolbar frame
        #
        #        self.copepod = tk.Button(self.toolbar,
        #                text="Copepod",command=self.copepod)
        #        self.copepod.pack(side="left") # left side of parent, the toolbar frame
        #
        #        self.diatom_chain = tk.Button(self.toolbar,
        #                text="Diatom chain",command=self.diatom_chain)
        #        self.diatom_chain.pack(side="left") # left side of parent, the toolbar frame

        f, self.a = plt.subplots(1, 1, figsize=(5, 5), dpi=100)
        self.dataPlot = FigureCanvasTkAgg(f, master=self.master)

        self.pgen = particle_generator()
        self.im, self.imfilepath, self.imfilename = next(self.pgen)
        plt.sca(self.a)
        plt.imshow(self.im)
        plt.axis('off')

        self.X_blank = np.zeros([1, 32, 32, 3], dtype='uint8')
        self.X = np.zeros([0, 32, 32, 3], dtype='uint8')
        self.Y = np.zeros((0, 3), dtype='uint8')

        self.toolbar.pack(side=TOP,
                          fill="x")  # top of parent, the master window
        self.dataPlot.show()
        self.dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

    def update_image(self):
        self.dump_data()
        plt.sca(self.a)
        plt.cla()
        self.im, self.imfilepath, self.imfilename = next(self.pgen)
        plt.imshow(self.im)
        plt.axis('off')
        self.dataPlot.show()

    def dump_data(self):
        choice = self.choice.get()
        print('from:')
        print(os.path.join(self.imfilepath, self.imfilename))
        print('to:')
        print(os.path.join(DATABASE_PATH, choice, self.imfilename))
        copyfile(os.path.join(self.imfilepath, self.imfilename),
                 os.path.join(DATABASE_PATH, choice, self.imfilename))

        return
示例#46
0
def mpBDisplay(Q, conf, mode=0, size=1, name='SignalSize'):
    '''effective Voltage of data passed via multiprocessing.Queue
    Args:
      conf: picoConfig object
      Q:    multiprocessing.Queue()   
  '''

    # Generator to provide data to animation
    def yieldEvt_fromQ():
        # random consumer of Buffer Manager, receives an event copy
        # via a Queue from package mutiprocessing

        cnt = 0
        try:
            while True:
                while not Q.qsize():
                    time.sleep(0.1)
                vals = Q.get()
                cnt += 1
                yield vals
        except:
            print('*==* yieldData_fromQ: termination signal received')
            return

    def yield_test():
        try:
            while True:
                time.sleep(np.random.rand())
                vals = np.random.rand(3)
                yield vals
        except:
            print('*==* yield_test: termination signal received')
            return


# ------- executable part --------
#  print(' -> mpBDisplay starting')

    try:
        while True:
            BD = BarDisplay(conf, mode, size)
            figBD = BD.fig
            #      print(' -> PanelMeter initialized')

            # generate a simple window for graphics display as a tk.DrawingArea
            root = Tk.Tk()
            root.wm_title(name)
            canvas = FigureCanvasTkAgg(figBD, master=root)
            canvas.show()
            canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
            canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
            button = Tk.Button(master=root, text='Quit', command=sys.exit)
            button.pack(side=Tk.BOTTOM)

            # set up matplotlib animation
            interval = 1
            BDAnim = anim.FuncAnimation(figBD,
                                        BD,
                                        yieldEvt_fromQ,
                                        interval=interval,
                                        init_func=BD.init,
                                        blit=True,
                                        fargs=None,
                                        repeat=True,
                                        save_count=None)
            # save_count=None is a (temporary) work-around
            #     to fix memory leak in animate
            Tk.mainloop()

    except:
        print('*==* mpBDisplay: termination signal recieved')
    sys.exit()
示例#47
0
class Scissor:
    def __init__(self, master):
        # Create a container
        frame = Tkinter.Frame(master)
        self.root = master
        self.curPath = os.getcwd()
        # Create 2 buttons
        self.button_img_open = Tkinter.Button(frame,
                                              text="open file",
                                              command=self.fileOpen)
        self.button_img_open.pack(side="left")
        #
        self.button_save_contour = Tkinter.Button(frame,
                                                  text="save_contour",
                                                  command=self.save_contour)
        self.button_save_contour.pack(side="left")

        self.button_loadContour = Tkinter.Button(frame,
                                                 text="load contour",
                                                 command=self.loadContour)
        self.button_loadContour.pack(side="left")

        self.button_img_only = Tkinter.Button(frame,
                                              text="Hide Contour",
                                              command=self.hidden_contour)
        self.button_img_only.pack(side="left")

        self.button_img_only = Tkinter.Button(frame,
                                              text="show contour drawn before",
                                              command=self.show_contour)
        self.button_img_only.pack(side="left")

        self.button_draw_contour = Tkinter.Button(frame,
                                                  text="draw contour",
                                                  command=self.draw_contour)
        self.button_draw_contour.pack(side="left")

        self.button_stop_contour = Tkinter.Button(frame,
                                                  text="stop drawing",
                                                  command=self.stop_contour)
        self.button_stop_contour.pack(side="left")

        self.button_remove_old_contour = Tkinter.Button(
            frame, text="remove old contour", command=self.remove_old_contour)
        self.button_remove_old_contour.pack(side="left")
        #
        self.button_cropImage = Tkinter.Button(frame,
                                               text="cropImage",
                                               command=self.cropImage)
        self.button_cropImage.pack(side="left")
        #
        self.button_saveCropped = Tkinter.Button(frame,
                                                 text="Save Cropped Image",
                                                 command=self.saveCropped)
        self.button_saveCropped.pack(side="left")

        # self.button_scaleDown = Tkinter.Button(frame, text="Scale Down Image",
        #                                          command=self.saveCropped)
        # self.button_scaleDown.pack(side="left")
        #

        #
        # self.button_pathTree = Tkinter.Button(frame, text="Path Tree",
        #                                        command=self.pathTree)
        # self.button_pathTree.pack(side="left")
        # #
        # self.button_minPath = Tkinter.Button(frame, text="Minimal Path",
        #                                        command=self.minPath)
        # self.button_minPath.pack(side="left")

        self.imgPath = None
        self.imgFileName = None
        self.img = None

        self.contour = []
        self.imgTk = None
        self.imgPIL = None
        self.grayImgNp = None
        self.colorImgNp = None
        self.croppedImage = None

        self.fig1 = Figure()
        self.ax1 = self.fig1.add_subplot(131)
        self.ax1.set_axis_off()
        # pixelNode
        self.ax2 = self.fig1.add_subplot(132)
        self.ax2.set_axis_off()
        # CostGraph
        self.ax3 = self.fig1.add_subplot(133)
        self.ax3.set_axis_off()
        self.canvas = FigureCanvasTkAgg(self.fig1, master=master)
        self.canvas.mpl_connect('button_press_event', self.on_click)
        self.mouseEvent = self.canvas.mpl_connect('motion_notify_event',
                                                  self.get_cursor_position)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)

        self.startDrawContour = False
        self.shownContour = False
        self.firstpt = True
        self.currentPath = []
        self.lastClickPt = None
        self.savedClicked = []
        self.pixelGraphTemplate = None
        self.pixelGraphSP = None
        self.ann_cross = []
        self.ann_line = []
        self.gettingPath = False
        self.testPt = []
        self.temp_line = []
        self.colorbar = []
        self.cropped = False
        frame.pack()

    def reInit(self):
        self.cropped = False
        self.startDrawContour = False
        self.shownContour = False
        self.firstpt = True
        self.currentPath = []
        self.lastClickPt = None
        self.savedClicked = []
        self.pixelGraphTemplate = None
        self.pixelGraphSP = None
        self.ann_cross = []
        self.ann_line = []
        self.gettingPath = False
        self.testPt = []
        self.temp_line = []
        for bar in self.colorbar:
            bar.remove()
        self.colorbar = []
        # self.ax2.clear()
        # self.ax3.clear()

    def closeContour(self):
        if self.contour[0][0] != self.contour[-1][0] or self.contour[0][
                1] != self.contour[-1][1]:
            if len(self.temp_line) > 0:
                self.temp_line[-1].remove()
            else:
                print len(self.temp_line)
            self.pixelGraphSP = self.Pixelgraph(self.grayImgNp,
                                                self.colorImgNp)
            self.pixelGraphSP.buildMST(self.contour[-1][0],
                                       self.contour[-1][1])
            y, x = self.contour[0][1], self.contour[0][0]
            self.currentPath = self.pixelGraphSP.findShortestPath(x, y)
            self.contour = self.contour + self.currentPath
            self.ax1.hold('on')
            line, = self.ax1.plot([pt[1] for pt in self.currentPath],
                                  [pt[0] for pt in self.currentPath],
                                  color='blue')
            self.temp_line.append(line)
            self.canvas.draw()

    def cropImage(self):
        if self.cropped is False:
            self.closeContour()
            mask = np.zeros(self.grayImgNp.shape)
            tempContour = np.array(self.contour)
            tempContour[:, [0, 1]] = tempContour[:, [1, 0]]
            cv2.drawContours(mask, [tempContour], 0, 255, -1)

            self.croppedImage = np.ones(self.colorImgNp.shape) * 255
            self.croppedImage[mask == 255, :] = self.colorImgNp[mask == 255, :]
            self.croppedImage = self.croppedImage.astype('uint8')

            self.ax1.clear()
            self.ax1.imshow(self.croppedImage)
            self.ax1.set_axis_off()
            self.temp_line = []
            self.canvas.draw()
            self.cropped = True

    def saveCropped(self):
        self.cropImage()
        imgFilenameList = self.imgFileName.split('.')
        initialfile = imgFilenameList[0].split(
            '/')[-1] + '_cropped.' + imgFilenameList[-1]
        filename = tkFileDialog.asksaveasfilename(initialdir=self.imgPath,
                                                  initialfile=initialfile,
                                                  title="Save file")
        cv2.imwrite(filename, cv2.cvtColor(self.croppedImage,
                                           cv2.COLOR_BGR2RGB))

    # def readtestPt(self):
    #     csvFile = 'test.csv'
    #     self.testPt = []
    #     with open(csvFile, 'r') as csvin:
    #         csvreader = csv.reader(csvin, delimiter=',')
    #         for line in csvreader:
    #             self.testPt.append((int(line[0]), int(line[1])))
    def loadContour(self):
        if self.imgPath is not None:
            filename = tkFileDialog.askopenfilename(
                initialdir=self.imgPath,
                title="Select Contour File",
                filetypes=(("csv files", "*.csv"), ("all files", "*.*")))
            self.contour = np.loadtxt(filename)
            self.ax1.plot([pt[1] for pt in self.contour],
                          [pt[0] for pt in self.contour],
                          color='blue')

    def pathTree(self):
        print 'pathTree'

    def minPath(self):
        print 'minPath'

    def draw_contour(self):
        self.startDrawContour = True

    def stop_contour(self):
        print 'stop drawing'
        self.startDrawContour = False

    def hidden_contour(self):
        print 'hidden contour'
        if self.startDrawContour is False:
            if self.shownContour is True:
                for cross in self.ann_cross:
                    cross.set_visible(not cross.get_visible())
                for line in self.ann_line:
                    line.set_visible(not line.get_visible())
                self.canvas.draw()
                self.shownContour = False

    def show_contour(self):
        if self.shownContour is False:
            for cross in self.ann_cross:
                cross.set_visible(not cross.get_visible())
            for line in self.ann_line:
                line.set_visible(not line.get_visible())
            self.canvas.draw()
            self.shownContour = True

        self.canvas.draw()

    def remove_old_contour(self):
        self.contour = []
        self.startDrawContour = False
        self.currentPath = []
        self.savedClicked = []
        self.lastClickPt = None
        self.pixelGraphSP = None
        self.shownContour = False
        for cross in self.ann_cross:
            cross.remove()
        for line in self.ann_line:
            line.remove()
        self.canvas.draw()

    def on_click(self, event):
        if event.dblclick:
            # end drawing
            print 'end drawing'
            if event.inaxes is not None:
                self.startDrawContour = False
        else:
            if event.inaxes is not None:
                if self.startDrawContour:
                    self.shownContour = True
                    print 'start drawing'
                    y, x = int(event.xdata), int(event.ydata)
                    print x, y
                    for bar in self.colorbar:
                        bar.remove()
                    self.colorbar = []
                    self.pixelGraphSP = self.Pixelgraph(
                        self.grayImgNp, self.colorImgNp)
                    self.pixelGraphSP.buildMST(x, y)
                    # print self.contour
                    # print self.currentPath
                    self.contour = self.contour + self.currentPath
                    self.currentPath = []
                    cross, = self.ax1.plot(y, x, '+', color='red')
                    costMap = self.pixelGraphSP.costMap()
                    im = self.ax3.imshow(costMap)
                    bar = self.fig1.colorbar(im)

                    self.ax2.clear()
                    neighborMap = self.pixelGraphSP.nodeNeighbor(x, y)
                    self.ax2.imshow(neighborMap)
                    self.ax2.set_title('Node and cost')
                    self.ax2.set_axis_off()
                    # self.ax2.grid(True)
                    # self.ax2.grid(which='minor', color='black', linestyle='-', linewidth=2)

                    self.colorbar.append(bar)
                    self.ax3.set_title('Cost to each pixel')
                    self.ax3.set_axis_off()
                    self.canvas.draw()
                    self.lastClickPt = (x, y)
                    self.ann_cross.append(cross)
                    self.savedClicked.append([y, x])
                    self.ann_line.append(self.temp_line[-1])
                    self.temp_line = []
                    self.canvas.draw()
                    # self.ann_cross.append(cross)
                    # self.ax2.imshow(self.pixelGraphSP.costMap())
                    # self.fig1.colorbar(im)
                    # self.canvas.draw()
            else:
                print 'Clicked ouside axes bounds but inside plot window'

    #
    # def update_plot(self):
    #     v = self.servo.getVelocity()
    #     t = self.servo.getTorque()
    #     self.add_point(self.velocity_line, v)
    #     self.add_point(self.torque_line, t)
    #     self.after(100, self.update_plot)

    # def draw_test(self):
    #     self.readtestPt()
    #     msttimeList = []
    #     pathtimeList = []
    #     for idx, pt in enumerate(self.testPt):
    #         nextpt = None
    #         if idx == (len(self.testPt) - 1):
    #             nextpt = self.testPt[0]
    #         else:
    #             nextpt = self.testPt[idx + 1]
    #         print idx, pt
    #         mstTime, pathTime = self.plotPt(pt, nextpt)
    #         msttimeList.append(mstTime)
    #         pathtimeList.append(pathTime)
    #     print 'MST time'
    #     print msttimeList
    #     print 'Path time'
    #     print pathtimeList

    # def plotPt(self, pt, nextpt):
    #     print 'start drawing'
    #     # if self.lastClickPt is None:
    #     self.pixelGraphSP = copy.deepcopy(self.pixelGraphTemplate)
    #     mstT0 = time.time()
    #     self.pixelGraphSP.buildMST(pt[0],pt[1])
    #     mstTime = time.time()-mstT0
    #     print self.currentPath
    #     pathT0 = time.time()
    #     self.currentPath = self.pixelGraphSP.findShortestPath(nextpt[0], nextpt[1])
    #     pathTime = time.time()-pathT0
    #     self.contour = self.contour + self.currentPath
    #     cross = self.ax1.plot(nextpt[1], nextpt[0], '+', c='red')
    #     line = self.ax1.plot([p[1] for p in self.currentPath], [p[0] for p in self.currentPath], c='blue')
    #     self.canvas.draw()
    #     time.sleep(10)
    #
    #     return mstTime, pathTime

    def get_cursor_position(self, event):
        if self.startDrawContour:
            if self.lastClickPt is not None:
                if event.inaxes is not None:
                    if self.gettingPath is False:
                        self.gettingPath = True
                        if len(self.temp_line) > 0:
                            self.temp_line[-1].remove()
                        else:
                            print len(self.temp_line)
                        print 'cursor:'
                        y, x = int(event.xdata), int(event.ydata)
                        self.currentPath = self.pixelGraphSP.findShortestPath(
                            x, y)
                        self.ax1.hold('on')
                        line, = self.ax1.plot(
                            [pt[1] for pt in self.currentPath],
                            [pt[0] for pt in self.currentPath],
                            color='blue')
                        self.temp_line.append(line)

                        self.canvas.draw()
                        self.gettingPath = False
                else:
                    print 'Cursor ouside axes bounds but inside plot window'

    def pil2cv(self):
        self.grayImgNp = np.array(self.imgPIL.convert('L'))
        self.colorImgNp = np.array(self.imgPIL.convert('RGB'))

    def fileOpen(self):
        self.reInit()
        filename = tkFileDialog.askopenfilename(initialdir=self.curPath,
                                                title="Select file")
        print filename
        path, fname = os.path.split(os.path.abspath(filename))
        self.imgPath = path
        self.imgFileName = filename
        # print self.imgFileName
        self.imgPIL = Image.open(filename)
        self.imgTk = ImageTk.PhotoImage(self.imgPIL)
        self.pil2cv()
        # self.pixelGraphTemplate = self.Pixelgraph(self.grayImgNp, self.colorImgNp)
        # self.tkImg = PhotoImage(filename=filename)
        # print self.img
        self.show_img_only()
        self.showEdgeMap = False

    #
    # def tkimFromCv2(self, img):
    #     if len(img.shape) == 3 and img.shape[2] == 3:
    #         img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    #     img = Image.fromarray(img)
    #     img = ImageTk.PhotoImage(img)
    #     self.tkImg = img
    # #
    # #
    # class pixel_Graph:
    # #     def __init__(self, img):
    # def LiveWireDP(self, x, y):
    #     pixelGraph = self.pixelGraph(self.grayImgNp)
    #
    #     self.canvas.draw()

    def inBoundary(self, x, y):
        size = self.grayImgNp.shape
        if x > size[0] or x < 0:
            return False
        elif y > size[1] or y < 0:
            return False
        return True

    def save_contour(self):
        initialfile = self.imgFileName.split('.')[0].split(
            '/')[-1] + '_contour.csv'
        filename = tkFileDialog.asksaveasfilename(initialdir=self.imgPath,
                                                  initialfile=initialfile,
                                                  title="Save file")
        print filename
        np.savetxt(filename, self.contour, dtype=int)

    def show_img_only(self):
        # self.ax1.clear()
        # print self.img.shape
        # self.tkImg = self.tkimFromCv2(self.img)
        self.ax1.clear()
        # if self.grayImgNp.shape[0] * self.grayImgNp.shape[1] > (300*300):
        #     if self.grayImgNp.shape[1] > self.grayImgNp.shape[0]:
        #         self.grayImgNp = np.array(cv2.resize(self.grayImgNp, (300, self.grayImgNp.shape[1]*300/self.grayImgNp.shape[0])))
        #         self.colorImgNp = np.array(cv2.resize(self.colorImgNp,
        #                                    (300, self.grayImgNp.shape[1] * 300 / self.grayImgNp.shape[0])))
        #     else:
        #         self.grayImgNp = np.array(cv2.resize(self.grayImgNp,
        #                                               (self.grayImgNp.shape[0] * 300 / self.grayImgNp.shape[1], 300)))
        #         self.colorImgNp = np.array(cv2.resize(self.colorImgNp,
        #                                     (self.grayImgNp.shape[0] * 300 / self.grayImgNp.shape[1], 300)))
        self.ax1.imshow(self.colorImgNp, 'gray', interpolation="nearest")
        self.ax1.set_axis_off()
        self.canvas.draw()

        # self.canvas.create_image(50, 10, image=self.tkImg, anchor=NW)
        # self.canvas.draw()
        # self.canvas.create_image(20,20, anchor=NW, image=self.imgTk)

    class Pixelgraph:
        class pixelNode:
            def __init__(self, x, y):
                self.x = x
                self.y = y
                self.neighbors = None
                # state: -1 = initial
                #         0 = expanded
                #         1 = active
                self.state = -1
                self.totalCost = 0
                self.prevNode = None
                self.drawn = False

        def __init__(self, grayimg, colorimg):
            self.grayimg = grayimg
            self.colorimg = colorimg
            self.pixelNodeList2D = {}
            self.startpt = None
            self.built_MST = False
            self.noNeighbor = 8
            edgeDetectorList = np.array([
                # (-1,-1)
                [
                    [[0, 1, 0], [-1, 0, 0], [0, 0, 0]],
                    # (-1,0)
                    [[1, 0, -1], [1, 0, -1], [0, 0, 0]],
                    # (-1,1)
                    [[0, 1, 0], [0, 0, -1], [0, 0, 0]]
                ],
                # (0,-1)
                [
                    [[1, 1, 0], [0, 0, 0], [-1, -1, 0]],
                    #  (0,0)
                    [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
                    #  (0,1)
                    [[0, 1, 1], [0, 0, 0], [0, -1, -1]]
                ],
                # (1,-1)
                [
                    [[0, 0, 0], [1, 0, 0], [0, -1, 0]],
                    # (1,0)
                    [[0, 0, 0], [1, 0, -1], [1, 0, -1]],
                    # (1,1)
                    [[0, 0, 0], [0, 0, 1], [0, -1, 0]]
                ]
            ]).astype('float')

            # edgeDetectorListOrth = np.array([
            #                                 # (-1,-1)
            #                                 [[[1, 0, 0],
            #                                   [0, -1, 0],
            #                                   [0, 0, 0]],
            #                                  # (-1,0)
            #                                  [[1, 1, 1],
            #                                   [-1, -1, -1],
            #                                   [0, 0, 0]],
            #                                  # (-1,1)
            #                                  [[0, 0, 1],
            #                                   [0, -1, 0],
            #                                   [0, 0, 0]]],
            #                                 # (0,-1)
            #                                 [[[1, -1, 0],
            #                                   [1, -1, 0],
            #                                   [1, -1, 0]],
            #                                  #  (0,0)
            #                                  [[1, 1, 1],
            #                                   [1, 1, 1],
            #                                   [1, 1, 1]],
            #                                  #  (0,1)
            #                                  [[0, 1, -1],
            #                                   [0, 1, -1],
            #                                   [0, 1, -1]]],
            #                                 # (1,-1)
            #                                 [[[0, 0, 0],
            #                                   [0, -1, 0],
            #                                   [1, 0, 0]],
            #                                  # (1,0)
            #                                  [[0, 0, 0],
            #                                   [1, 1, 1],
            #                                   [-1,-1, -1]],
            #                                  # (1,1)
            #                                  [[0, 0, 0],
            #                                   [0, 1, 0],
            #                                   [0, 0, -1]]]]).astype('float')

            def normalizationOfFilter(filter):
                sumOfFilter = 0
                for r in filter:
                    for c in r:
                        sumOfFilter += abs(c)
                normalized = filter * (1 / sumOfFilter)
                # print normalized
                return normalized

            def multipleLength(filters):
                result = []
                for r in range(3):
                    tempEdgeList = []
                    for c in range(3):
                        if abs(r - c) % 2 == 0:
                            tempEdgeList.append(
                                normalizationOfFilter(filters[r, c]) *
                                np.sqrt(2))
                        else:
                            tempEdgeList.append(
                                normalizationOfFilter(filters[r, c]))
                    result.append(tempEdgeList)
                return np.array(result)

            self.edgeDetector = multipleLength(
                normalizationOfFilter(edgeDetectorList))
            # self.edgeDetectorOrth = multipleLength(normalizationOfFilter(edgeDetectorListOrth))

            self.edgeMap = []
            for r in range(3):
                tempEdgeList = []
                for c in range(3):
                    edgeCost = np.zeros(self.grayimg.shape)
                    for color in range(3):
                        convEdge = np.abs(
                            signal.convolve2d(colorimg[:, :, color],
                                              self.edgeDetector[r, c],
                                              boundary='symm',
                                              mode='same'))
                        edgeCost += (max(convEdge.ravel()) - convEdge)
                        # convEdgeOrth = np.abs(signal.convolve2d(colorimg[:,:,color], self.edgeDetectorOrth[r,c], boundary='symm', mode='same'))
                        # edgeCost += convEdgeOrth
                    tempEdgeList.append(edgeCost / 3)
                self.edgeMap.append(tempEdgeList)

            self.edgeMap = np.array(self.edgeMap)
            # print self.edgeMap.shape

            for i in range(grayimg.shape[0]):
                for j in range(grayimg.shape[1]):
                    pixelNode = self.pixelNode(i, j)
                    pixelNode.neighbors = self.buildNeighbor(i, j)
                    self.pixelNodeList2D[(i, j)] = pixelNode

        def buildNeighbor(self, i, j):
            neighbor = {}
            for r in range(3):
                x = i + r - 1
                for c in range(3):
                    y = j + c - 1
                    if not (r == 1 and c == 1):
                        if self.inBoundary(x, y):
                            neighbor[(x, y)] = self.edgeMap[r, c, i, j]
            return neighbor

        # using heapdict
        # def buildMST(self, startx, starty):
        #     print 'building MST'
        #     mstT0 = time.time()
        #     heap = heapdict()
        #     self.startpt = (startx, starty)
        #     # entry_finder = {}
        #     # REMOVED = '<removed-task>'
        #     # counter = itertools.count()
        #     #
        #     # def remove_task(task):
        #     #     'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        #     #     entry = entry_finder.pop(task)
        #     #     entry[-1] = REMOVED
        #     #
        #     # def add_task(task, priority=0):
        #     #     'Add a new task or update the priority of an existing task'
        #     #     if task in entry_finder:
        #     #         remove_task(task)
        #     #     count = next(counter)
        #     #     entry = [priority, count, task]
        #     #     entry_finder[task] = entry
        #     #     heappush(pq, entry)
        #     for neighCoor, neighCost in self.pixelNodeList2D[self.startpt].neighbors.iteritems():
        #         heap[neighCoor] = neighCost
        #         self.pixelNodeList2D[neighCoor].totalCost = neighCost
        #         self.pixelNodeList2D[neighCoor].prevNode = self.startpt
        #
        #     while len(heap) > 0:
        #         # print 'deq'
        #         # deqt0 = time.time()
        #         qCoor, qCost = heap.popitem()
        #         # mark q as EXPANDED (state = 0)
        #         self.pixelNodeList2D[qCoor].state = 0
        #         self.pixelNodeList2D[qCoor].totalCost = qCost
        #         for rCoor, rCost in self.pixelNodeList2D[qCoor].neighbors.iteritems():
        #             rState = self.pixelNodeList2D[rCoor].state
        #             if rState != 0:
        #                 if rState == -1:
        #                     self.pixelNodeList2D[rCoor].prevNode = qCoor
        #                     self.pixelNodeList2D[rCoor].totalCost = qCost + rCost
        #                     heap[rCoor] = qCost + rCost
        #                     self.pixelNodeList2D[rCoor].state = 1
        #                 else:
        #                     if self.pixelNodeList2D[rCoor].totalCost > (self.pixelNodeList2D[qCoor].totalCost + rCost):
        #                         self.pixelNodeList2D[rCoor].prevNode = qCoor
        #                         self.pixelNodeList2D[rCoor].totalCost = qCost + rCost
        #                         heap[rCoor] = qCost + rCost
        #         # deqTime = time.time() - deqt0
        #         # print deqTime
        #     self.pixelNodeList2D[self.startpt].prevNode = None
        #     mstTime = time.time() - mstT0
        #     print mstTime
        #     self.built_MST = True

        def buildMST(self, startx, starty):
            print 'building MST'
            mstT0 = time.time()
            heap = Fibonacci_heap()
            self.startpt = (startx, starty)
            heapTempGraph = {}
            for neighCoor, neighCost in self.pixelNodeList2D[
                    self.startpt].neighbors.iteritems():
                heapTempGraph[neighCoor] = heap.enqueue(value=neighCoor,
                                                        priority=neighCost)
                self.pixelNodeList2D[neighCoor].totalCost = neighCost
                self.pixelNodeList2D[neighCoor].prevNode = self.startpt

            while heap.m_size != 0:
                # print 'deq'
                # deqt0 = time.time()
                q = heap.dequeue_min()
                # mark q as EXPANDED (state = 0)
                self.pixelNodeList2D[q.m_elem].state = 0
                self.pixelNodeList2D[q.m_elem].totalCost = q.m_priority
                for rCoor, rCost in self.pixelNodeList2D[
                        q.m_elem].neighbors.iteritems():
                    rState = self.pixelNodeList2D[rCoor].state
                    if rState != 0:
                        if rState == -1:
                            self.pixelNodeList2D[rCoor].prevNode = q.m_elem
                            self.pixelNodeList2D[
                                rCoor].totalCost = self.pixelNodeList2D[
                                    q.m_elem].totalCost + rCost
                            heapTempGraph[rCoor] = heap.enqueue(
                                value=rCoor,
                                priority=self.pixelNodeList2D[rCoor].totalCost)
                            self.pixelNodeList2D[rCoor].state = 1
                        else:
                            if self.pixelNodeList2D[
                                    rCoor].totalCost > self.pixelNodeList2D[
                                        q.m_elem].totalCost + rCost:
                                self.pixelNodeList2D[rCoor].prevNode = q.m_elem
                                self.pixelNodeList2D[
                                    rCoor].totalCost = self.pixelNodeList2D[
                                        q.m_elem].totalCost + rCost
                                heap.decrease_key(
                                    heapTempGraph[rCoor],
                                    self.pixelNodeList2D[rCoor].totalCost)
                # deqTime = time.time() - deqt0
                # print deqTime
            self.pixelNodeList2D[self.startpt].prevNode = None
            mstTime = time.time() - mstT0
            print mstTime
            self.built_MST = True

        # def buildMST(self, startx, starty):
        #     print 'building MST'
        #     mstT0 = time.time()
        #     heap = FibonacciHeap()
        #     self.startpt = (startx, starty)
        #     for neighCoor, neighCost in self.pixelNodeList2D[self.startpt].neighbors.iteritems():
        #         print neighCoor, neighCost
        #         heap.insert(key=neighCost, value=neighCoor)
        #         self.pixelNodeList2D[neighCoor].totalCost = neighCost
        #         self.pixelNodeList2D[neighCoor].prevNode = self.startpt
        #
        #
        #     while heap is not None:
        #         q = heap.extract_min()
        #         # mark q as EXPANDED (state = 0)
        #         self.pixelNodeList2D[q.value].state = 0
        #         self.pixelNodeList2D[q.value].totalCost = q.key
        #         print 'q:'
        #         print q.value, q.key
        #         for rCoor, rCost in self.pixelNodeList2D[q.value].neighbors.iteritems():
        #             rState = self.pixelNodeList2D[rCoor].state
        #             print 'r'
        #             print rCoor, rCost
        #             if rState != 0:
        #                 if rState == -1:
        #                     self.pixelNodeList2D[rCoor].prevNode = q.value
        #                     self.pixelNodeList2D[rCoor].totalCost = self.pixelNodeList2D[q.value].totalCost + rCost
        #                     heap.insert(key=self.pixelNodeList2D[rCoor].totalCost, value=rCoor)
        #                     self.pixelNodeList2D[rCoor].state = 1
        #                 else:
        #                     if self.pixelNodeList2D[rCoor].totalCost > self.pixelNodeList2D[q.value].totalCost + rCost:
        #                         self.pixelNodeList2D[rCoor].prevNode = q.value
        #                         self.pixelNodeList2D[rCoor].totalCost = self.pixelNodeList2D[q.value].totalCost + rCost
        #                         heap.updateByValue(rCoor, self.pixelNodeList2D[rCoor].totalCost)
        #     mstTime = time.time() - mstT0
        #     print mstTime
        #     self.built_MST = True

        def findShortestPath(self, endx, endy):
            print 'Time for Shortest Path:'
            t0 = time.time()
            if self.built_MST:
                endpt = (endx, endy)
                nextpt = endpt
                pathTemp = []
                numOfpt = 0
                while (nextpt[0] != self.startpt[0]
                       or nextpt[1] != self.startpt[1]):
                    nextpt = self.pixelNodeList2D[nextpt].prevNode
                    pathTemp.append(nextpt)
                    numOfpt += 1
                    if nextpt is None:
                        break
                path = []
                while len(pathTemp) != 0:
                    path.append(pathTemp.pop())
                timeUsed = time.time() - t0
                print timeUsed
                return path

        def costMap(self):
            costImg = np.zeros(self.grayimg.shape)
            for i in range(self.grayimg.shape[0]):
                for j in range(self.grayimg.shape[1]):
                    costImg[i, j] = self.pixelNodeList2D[(i, j)].totalCost
            return costImg

        #
        # def neighborNode(self, x, y):
        #     print 'test'
        #     neighborImg = np.zeros((9,9,3))
        #     for i in range(9):
        #         xq = i / 3 - 1
        #         for j in range(9):
        #             yq = j / 3 - 1
        #             if i % 3 == 1 and j % 3 == 1:
        #                 neighborImg[i,j] = self.colorimg[x+xq,y+yq,:]
        #             else:
        #                 xr = i % 3 - 1
        #                 yr = j % 3 - 1
        #                 edge = self.pixelNodeList2D[(x+xq,y+yq)].neighbors[(x+xr, y+yr)]
        #                 neighborImg[i,j] = np.repeat(edge, 3)
        #     return neighborImg

        def nodeNeighbor(self, x, y):
            neighborImg = np.zeros((9, 9, 3))
            for i in range(9):
                for j in range(9):
                    if i % 3 == 1 and j % 3 == 1:
                        neighborImg[i, j] = self.colorimg[(x - (i / 3) - 1),
                                                          (y - (j / 3) - 1), :]
                    else:
                        neighborImg[i, j] = (
                            self.edgeMap[i % 3, j % 3, (x - (i / 3) - 1),
                                         (y - (j / 3) - 1)] * 255 /
                            max(self.edgeMap[i % 3, j % 3].ravel()) * np.ones(
                                (3, )))
            return neighborImg.astype('uint8')

        def inBoundary(self, x, y):
            size = self.grayimg.shape
            if x >= size[0] or x < 0:
                return False
            elif y >= size[1] or y < 0:
                return False
            return True
示例#48
0
class labelManager():
    def __init__(self):
        self.startLoc = 0
        self.endLoc = 0
        self.thresholdLoc = 0
        self.fileIndex = 0
        self.smoothing = False
        self.edge_det_window = 101
        self.smoothing_window = 301
        self.smoothing_var = 51
        self.data_list = [[]]
        self.file_list = ['None']

        self.root = Tk()
        self.root.title('Label data checker')
        self.root.iconbitmap("peakLabelManager.ico")

        self.menu_bar = Menu(self.root)

        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(
            label="Load genomic segments (Training set)",
            command=self.selectSegments)
        self.file_menu.add_command(label="Load bam alignment",
                                   command=self.selectBam)
        self.menu_bar.add_cascade(label="New file", menu=self.file_menu)

        self.option_menu = Menu(self.menu_bar, tearoff=0)
        self.option_menu.add_command(label="Smoothing intensity",
                                     command=self.smoothingSetting)
        self.menu_bar.add_cascade(label="Options", menu=self.option_menu)

        self.fig = Figure(figsize=(4, 4), dpi=100)
        self.peak_plot = self.fig.add_subplot(111)

        self.prev_button = Button(self.root,
                                  text="Prev(Q)",
                                  command=self.prevData)
        self.prev_button.grid(row=0, column=1, sticky=W + E + N + S)
        self.next_button = Button(self.root,
                                  text="Next(W)",
                                  command=self.nextData)
        self.next_button.grid(row=0, column=2, sticky=W + E + N + S)
        self.drop_button = Button(self.root,
                                  text="Drop(E)",
                                  command=self.dropLabels)
        self.drop_button.grid(row=1,
                              column=1,
                              columnspan=2,
                              sticky=W + E + N + S)
        self.noPeak_button = Button(
            self.root,
            text="noPeak(A)",
            command=lambda: self.adjustData(peak=False, criteria='region'))
        self.noPeak_button.grid(row=5,
                                column=1,
                                columnspan=2,
                                sticky=W + E + N + S)
        self.peak_region_button = Button(
            self.root,
            text="peak = region(S)",
            command=lambda: self.adjustData(peak=True, criteria='region'))
        self.peak_region_button.grid(row=6, column=1, sticky=W + E + N + S)
        self.peak_threshold_button = Button(
            self.root,
            text="peak > threshold(D)",
            command=lambda: self.adjustData(peak=True, criteria='threshold'))
        self.peak_threshold_button.grid(row=6, column=2, sticky=W + E + N + S)

        self.smooth_button = Button(self.root,
                                    text="Smoothing",
                                    command=self.smoothingDepth)
        self.smooth_button.grid(row=7,
                                column=1,
                                columnspan=2,
                                sticky=W + E + N + S)

        self.moveFileLabel = Label(self.root,
                                   text=" {}/{} ` th label.".format(
                                       self.fileIndex + 1,
                                       len(self.data_list[0])))
        self.moveFileLabel.grid(row=2, column=2)
        self.moveFileEntry = Entry(self.root, width=12)
        self.moveFileEntry.bind("<Return>", self.moveFile)
        self.moveFileEntry.grid(row=2, column=1)

        self.startLabel = Label(self.root, text="Start point :")
        self.startLabel.grid(row=3, column=1)
        self.startAxis = Text(self.root, height=2, width=12)
        self.startAxis.insert(END, self.startLoc)
        self.startAxis.grid(row=3, column=2)

        self.endLabel = Label(self.root, text="End point   :")
        self.endLabel.grid(row=4, column=1)
        self.endAxis = Text(self.root, height=2, width=12)
        self.endAxis.insert(END, self.endLoc)
        self.endAxis.grid(row=4, column=2)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0,
                                         column=0,
                                         rowspan=8,
                                         sticky=W + E + N + S,
                                         padx=20,
                                         pady=20)

        ### Mouse drag events for region selection
        self.fig.canvas.mpl_connect('button_press_event', self.dragStart)
        self.fig.canvas.mpl_connect('button_release_event', self.dragEnd)

        ### Keyboard events
        self.root.bind('<Key>', self.keyPressed)
        self.root.config(menu=self.menu_bar)
        self.root.mainloop()

    def keyPressed(self, event):
        if event.char == 'q':
            self.prevData()
        elif event.char == 'w':
            self.nextData()
        elif event.char.lower() == 'a':
            self.adjustData(peak=False, criteria='region')
        elif event.char.lower() == 's':
            self.adjustData(peak=True, criteria='region')
        elif event.char.lower() == 'd':
            self.adjustData(peak=True, criteria='threshold')
        elif event.char.lower() == 'e':
            self.dropLabels()
        else:
            pass

    def moveFile(self, event):
        self.fileIndex = int(self.moveFileEntry.get())
        self.moveFileLabel.focus_set()
        self.drawPlot()

    def smoothingDepth(self):
        self.smoothing = not self.smoothing
        self.moveFileLabel.focus_set()
        self.drawPlot()

    def dragStart(self, event):
        self.startLoc = int(event.xdata)
        self.thresholdLoc = float(event.ydata)
        self.startAxis.delete('1.0', END)
        self.startAxis.insert(END, self.startLoc)

    def dragEnd(self, event):
        self.endLoc = int(event.xdata)
        self.endAxis.delete('1.0', END)
        self.endAxis.insert(END, self.endLoc)
        self.drawPlot()

    def dropLabels(self):
        os.remove(self.file_list[2][self.fileIndex])
        os.remove(self.file_list[1][self.fileIndex])
        os.remove(self.file_list[0][self.fileIndex])

        print("<{}> is removed ".format(self.file_list[1][self.fileIndex]))

        self.file_list[0].pop(self.fileIndex)
        self.file_list[1].pop(self.fileIndex)
        self.file_list[2].pop(self.fileIndex)

        self.data_list[0].pop(self.fileIndex)
        self.data_list[1].pop(self.fileIndex)
        self.data_list[2].pop(self.fileIndex)

        if self.fileIndex > len(self.data_list[0]):
            self.fileIndex -= 1
        self.drawPlot()

    def nextData(self):
        if (len(self.data_list[0]) - 1 < self.fileIndex + 1):
            print("next_index")
            messagebox.showinfo(
                "Announce", "It is end of the label. [{}/{}]".format(
                    len(self.data_list[0]), len(self.data_list[0])))
        else:
            self.fileIndex += 1
            self.drawPlot()

    def prevData(self):
        if (0 > self.fileIndex - 1):
            print("prev_index")
            messagebox.showinfo(
                "Announce", "It is start of the label. [1/{}]".format(
                    len(self.data_list[0])))
        else:
            self.fileIndex -= 1
            self.drawPlot()

    def adjustData(self, peak=True, criteria=None):
        filename = self.file_list[2][self.fileIndex]
        length = len(self.data_list[2][self.fileIndex])

        if criteria == 'region':
            start = min(int(self.startAxis.get('1.0', END)),
                        int(self.endAxis.get('1.0', END)))
            end = max(int(self.startAxis.get('1.0', END)),
                      int(self.endAxis.get('1.0', END)))
            if start < 0:
                start = 0
            elif end >= length:
                end = length - 1
            while start < end:
                if peak:
                    self.data_list[2][self.fileIndex][start] = 1
                else:
                    self.data_list[2][self.fileIndex][start] = 0
                start += 1
            self.drawPlot()

        elif criteria == 'threshold':
            if self.smoothing:
                read_depth = self.smoothingInput()
            else:
                read_depth = self.data_list[0][self.fileIndex]

            for i in range(len(read_depth)):
                if read_depth[i] >= self.thresholdLoc:
                    self.data_list[2][self.fileIndex][i] = 1
            self.drawPlot()

        compressed_label = []

        ###### Save new label ########
        for i in range(length):
            if i % 5 == 0:
                compressed_label.append(self.data_list[2][self.fileIndex][i])

        noPeakColumn = []
        for i in range(length // 5):
            if compressed_label[i] == 1:
                noPeakColumn.append(0)
            else:
                noPeakColumn.append(1)

        new_label_df = pd.DataFrame(
            {
                'peak': compressed_label,
                'noPeak': noPeakColumn
            },
            dtype=int,
            index=range(length // 5))
        print(new_label_df)

        os.remove(filename)
        new_label_df.to_csv(filename)
        print("{} saved.".format(filename))

    def drawPlot(self):
        self.peak_plot.cla()

        ### Draw read input data
        if self.smoothing:
            read_depth = self.smoothingInput()
            ##final_depth = (final_depth - final_depth.mean())/(final_depth.std() + 0.0001)
            self.peak_plot.plot(read_depth, 'k', markersize=2, linewidth=1)
        else:
            self.peak_plot.plot(self.data_list[0][self.fileIndex],
                                'k',
                                markersize=2,
                                linewidth=1)

        ### Draw peak label by highlighting
        onPositive = False
        start = 0
        end = 0
        for i in range(len(self.data_list[2][self.fileIndex])):
            if self.data_list[2][self.fileIndex][i] == 1 and not onPositive:
                start = i
                onPositive = True
            elif (self.data_list[2][self.fileIndex][i] == 0 or i == len(
                    self.data_list[2][self.fileIndex])) and onPositive:
                end = i
                onPositive = False
                self.peak_plot.axvspan(start, end, color='red', alpha=0.3)

        ### Draw refSeq
        refSeq_index = []
        for i in range(len(self.data_list[1][self.fileIndex])):
            if self.data_list[1][self.fileIndex][i] == 1:
                refSeq_index.append(i)
        self.peak_plot.plot(refSeq_index,
                            [0 for x in range(len(refSeq_index))],
                            'b|',
                            markersize=8)

        ### Draw Threshold setting
        height = self.thresholdLoc
        self.peak_plot.plot([0, len(self.data_list[0][self.fileIndex])],
                            [height, height], 'y--')

        self.moveFileLabel.configure(
            text="{}/{} ` th label.".format(self.fileIndex +
                                            1, len(self.data_list[0])))
        self.moveFileLabel.focus_set()
        self.canvas.show()

    def smoothingInput(self):
        print(self.edge_det_window, self.smoothing_window, self.smoothing_var)
        depths = np.array(self.data_list[0][self.fileIndex])
        smoothing_filter = gaussian(self.smoothing_window, self.smoothing_var) / \
                           np.sum(gaussian(self.smoothing_window, self.smoothing_var))
        union_depths = maximum_filter1d(
            depths, self.edge_det_window)  ## MAX POOL to extract boarder lines
        final_depth = np.convolve(union_depths, smoothing_filter,
                                  mode='same')  ## Smoothing boarder lines
        return final_depth

    def segmentLoad(self, dir_name, num_grid=12000):
        PATH = os.path.abspath(dir_name)
        dir_list = os.listdir(PATH)

        for dir in dir_list:
            dir = os.path.join(PATH, dir)

        input_list = {}
        for dir in dir_list:
            dir = os.path.join(PATH, dir)
            input_list[dir] = extractChrClass(dir)

        data_list = []
        ref_list = []
        label_list = []

        input_file_list = []
        ref_file_list = []
        label_file_list = []

        for dir in input_list:
            for chr in input_list[dir]:
                for cls in input_list[dir][chr]:
                    input_file_name = os.path.join(
                        dir, "{}_{}_grid{}.ct".format(chr, cls, num_grid))
                    ref_file_name = os.path.join(
                        dir, "ref_{}_{}_grid{}.ref".format(chr, cls, num_grid))
                    label_file_name = os.path.join(
                        dir,
                        "label_{}_{}_grid{}.lb".format(chr, cls, num_grid))

                    input_file_list.append(input_file_name)
                    ref_file_list.append(ref_file_name)
                    label_file_list.append(label_file_name)

                    reads = (pd.read_csv(input_file_name)
                             )['readCount'].values.reshape(num_grid)
                    refs = (pd.read_csv(ref_file_name)
                            )['refGeneCount'].values.reshape(num_grid)
                    label = (pd.read_csv(label_file_name)
                             )['peak'].values.transpose()
                    label = expandingPrediction(label)

                    data_list.append(reads)
                    label_list.append(label)
                    ref_list.append(refs)

        return {
            'data': (data_list, ref_list, label_list),
            'file_name': (input_file_list, ref_file_list, label_file_list)
        }

    def selectSegments(self):
        dirPath = askdirectory(title="Select Your Directory")
        dirPath = os.path.abspath(dirPath)

        loads = self.segmentLoad(dirPath)

        self.data_list = loads['data']
        self.file_list = loads['file_name']

        self.drawPlot()

    def selectBam(self):
        bam_file_name = askopenfilename(title="Select Your File")
        bam_path = os.path.abspath(bam_file_name)
        bam_index_path = bam_path + ".bai"
        print(bam_path, bam_index_path)
        self.bam = bs.AlignmentFile(bam_path, filepath_index=bam_index_path)
        print(self.bam.header)
        print(self.bam.head(n=5))

    def smoothingSetting(self):
        smoothingSettingFrame = Toplevel(self.root)
        smoothingSettingFrame.title('Smoothing configuration')
        smoothingSettingFrame.iconbitmap("peakLabelManager.ico")

        pickingEdge_label = Label(smoothingSettingFrame,
                                  text="Picking edge width")
        pickingEdge_label.grid(row=0, column=0, sticky=W + E + N + S)
        smoothing_label = Label(smoothingSettingFrame, text="Smoothing width")
        smoothing_label.grid(row=1, column=0, sticky=W + E + N + S)
        smoothingVar_label = Label(smoothingSettingFrame,
                                   text="Smoothing intensity")
        smoothingVar_label.grid(row=2, column=0, sticky=W + E + N + S)

        pickingEdge = Text(smoothingSettingFrame, height=2, width=12)
        pickingEdge.grid(row=0, column=1, sticky=W + E + N + S)
        pickingEdge.insert(END, self.edge_det_window)
        smoothing = Text(smoothingSettingFrame, height=2, width=12)
        smoothing.grid(row=1, column=1, sticky=W + E + N + S)
        smoothing.insert(END, self.smoothing_window)
        smoothingVar = Text(smoothingSettingFrame, height=2, width=12)
        smoothingVar.grid(row=2, column=1, sticky=W + E + N + S)
        smoothingVar.insert(END, self.smoothing_var)

        def changeVal():
            self.edge_det_window = int(pickingEdge.get('1.0', END))
            self.smoothing_window = int(smoothing.get('1.0', END))
            self.smoothing_var = int(smoothingVar.get('1.0', END))
            smoothingSettingFrame.destroy()

        adapt = Button(smoothingSettingFrame, text="OK", command=changeVal)
        adapt.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)

        cancle = Button(smoothingSettingFrame,
                        text="Cancel",
                        command=smoothingSettingFrame.destroy)
        cancle.grid(row=4, column=0, columnspan=2, sticky=W + E + N + S)

        smoothingSettingFrame.mainloop()
class Car(tk.Tk, object):
    def __init__(self, time, cycle_time, cycle_speed, cycle_round, cycle_dt,
                 cycle_total_step_number, vehicle_name, fc_map_spd, fc_map_trq,
                 fc_fuel_map, fc_max_trq, min_fuel_consum_line_spd,
                 min_fuel_consum_line_trq, mg2_map_spd, mg2_map_trq,
                 mg2_eff_map, mg2_max_trq, mg2_max_gen_trq):
        super(Car, self).__init__()
        self.vehicle_name = vehicle_name
        print('vehicle type: ' + self.vehicle_name)
        self.time = time
        self.cycle_time = cycle_time
        self.cycle_speed = cycle_speed
        self.cycle_round = cycle_round
        self.cycle_dt = cycle_dt
        self.cycle_total_step_number = cycle_total_step_number
        self.fc_map_spd = fc_map_spd
        self.fc_map_trq = fc_map_trq
        self.fc_fuel_map = fc_fuel_map
        self.fc_max_trq = fc_max_trq
        self.mg2_map_spd = mg2_map_spd
        self.mg2_map_trq = mg2_map_trq
        self.mg2_eff_map = mg2_eff_map
        self.mg2_max_trq = mg2_max_trq
        self.mg2_max_gen_trq = mg2_max_gen_trq
        self.min_fuel_consum_line_spd = min_fuel_consum_line_spd
        self.min_fuel_consum_line_trq = min_fuel_consum_line_trq
        self.n_actions = 11
        self.n_features = 10
        self.i_CVT_ratio_max = 3
        self.i_CVT_ratio_min = 1 / self.i_CVT_ratio_max
        self.i_CVT_ratio = self.i_CVT_ratio_max
        self.W_ice = 0
        self.T_ice = 0
        self.kW_ice = 0
        self.W_mg2 = 0
        self.T_mg2 = 0
        self.kW_mg2 = 0
        self.T_brake = 0
        self.fuel_accumulate = 0
        self.total_resis_torque = 0
        self.W_wheel = 0
        self.v_vehicle = 0
        self.v_vehicle_kmh = 0
        self.cycle_iteration = 0
        self.initial_soc = 0.6
        self.soc = self.initial_soc
        self.reward_acum = 0
        self.time_array = []
        self.action_array = []
        self.W_ice_array = []
        self.T_ice_array = []
        self.kW_ice_array = []
        self.W_mg2_array = []
        self.T_mg2_array = []
        self.kW_mg2_array = []
        self.v_vehicle_array = []
        self.v_vehicle_kmh_array = []
        self.T_brake_array = []
        self.i_CVT_ratio_array = []
        self.fuel_instant_array = []
        self.fuel_accumulate_array = []
        self.battery_charge_array = []
        self.battery_soc_array = []
        self.reward_array = []
        self.reward_acum_array = []
        self.cycle_iteration_array = []
        self.ave_cyc_reward_array = []
        self.speed_difference_kmh_array = []
        self.cyc_fuel_accumulate_array = []
        self.ave_cyc_speed_difference_kmh_array = []

        self.geometry('1200x700+1950-175')
        self.title('IPS DQN')
        self._build_plot()

    def _build_plot(self):

        # Creat figure
        # self.f = Figure(figsize=(200,10), dpi=100)
        self.f = plt.figure(figsize=(25, 6), dpi=100)
        plt.suptitle(self.vehicle_name, fontsize=10)
        self.f.subplots_adjust(hspace=0.8, wspace=0.2)
        self.canvas2 = FigureCanvasTkAgg(self.f, self)
        self.canvas2.show()
        self.canvas2._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # Cycle
        self.cycle = plt.subplot2grid((5, 5), (0, 0))
        # Gear
        self.gear = plt.subplot2grid((5, 5), (1, 0))
        # Brake
        self.brake = plt.subplot2grid((5, 5), (2, 0))
        # Action
        self.action = plt.subplot2grid((5, 5), (3, 0), rowspan=2)

        # ICE Fuel Consumption Map
        self.fuel = plt.subplot2grid((5, 5), (0, 1))
        # BSFC
        self.bsfc = plt.subplot2grid((5, 5), (0, 1))
        # W_ice figure
        self.w_ice = plt.subplot2grid((5, 5), (1, 1))
        # T_ice figure
        self.t_ice = plt.subplot2grid((5, 5), (2, 1))
        # kW_ice figure
        self.fig_kW_ice = plt.subplot2grid((5, 5), (3, 1))
        # Accumulated Fuel Consumption
        self.fig_accumulated_fuel = plt.subplot2grid((5, 5), (4, 1))
        # Instance Fuel Consumption
        self.fig_instant_fuel = plt.subplot2grid((5, 5), (4, 1))

        # MG2 Map
        self.mg2_map = plt.subplot2grid((5, 5), (0, 2))
        # W_mg2
        self.w_mg2 = plt.subplot2grid((5, 5), (1, 2))
        # T_mg2
        self.t_mg2 = plt.subplot2grid((5, 5), (2, 2))
        # kW_mg2
        self.fig_kW_mg2 = plt.subplot2grid((5, 5), (3, 2))
        # Battery Charge
        self.fig_battery_charge = plt.subplot2grid((5, 5), (4, 2))

        # Battery SOC
        self.fig_battery_soc = plt.subplot2grid((5, 5), (4, 2))

        # Instant Reward
        self.fig_reward = plt.subplot2grid((5, 5), (0, 3))

        # Learning Curve (Average Reward / Iteration)
        self.fig_learning_curve = plt.subplot2grid((5, 5), (0, 4))
        # Speed Error / Iteration
        self.d_speed = plt.subplot2grid((5, 5), (1, 4), rowspan=1)
        # Fuel Consumption / Iteration
        self.cyc_fuel = plt.subplot2grid((5, 5), (2, 4), rowspan=1)

    def cycle_reset(self):
        self.T_ice = 0
        self.W_ice = 0
        self.T_mg2 = 0
        self.W_mg2 = 0
        self.W_wheel = 0
        self.T_brake = 0
        self.total_resis_torque = 0
        self.v_vehicle = 0
        self.v_vehicle_kmh = 0
        self.i_CVT_ratio = self.i_CVT_ratio_max
        self.fuel_accumulate = 0
        self.soc = self.initial_soc
        self.reward_acum = 0

        self.time_array = []
        self.action_array = []
        self.W_ice_array = []
        self.T_ice_array = []
        self.kW_ice_array = []
        self.W_mg2_array = []
        self.T_mg2_array = []
        self.kW_mg2_array = []
        self.v_vehicle_array = []
        self.v_vehicle_kmh_array = []
        self.T_brake_array = []
        self.i_CVT_ratio_array = []
        self.fuel_instant_array = []
        self.fuel_accumulate_array = []
        self.battery_charge_array = []
        self.battery_soc_array = []
        self.reward_array = []
        self.reward_acum_array = []
        self.speed_difference_kmh_array = []

    def reset(self, current_cycle_target_speed, next_cycle_target_speed):
        self.update()
        self.current_cycle_target_speed = current_cycle_target_speed
        self.next_cycle_target_speed = next_cycle_target_speed

        s = np.array([
            self.W_ice, self.T_ice, self.W_mg2, self.T_mg2, self.i_CVT_ratio,
            self.T_brake, self.soc, self.v_vehicle_kmh,
            current_cycle_target_speed, next_cycle_target_speed
        ])

        # return observation
        return s

    def cycle_plot(self, cycle_time, cycle_speed, cycle_name, cycle_round,
                   last_time_iteration, max_cycle_reward):
        set_title_fontsize = 10
        set_label_fontsize = 9
        set_tick_fontsize = 8

        #################################################################################
        #################################################################################
        ###########################
        self.cycle.plot(cycle_time, cycle_speed, 'b-')
        self.cycle.plot(self.time_array,
                        self.v_vehicle_kmh_array,
                        "o",
                        color='C1',
                        markersize=2)

        self.cycle.set_title(cycle_name, fontsize=set_title_fontsize)
        self.cycle.set_xlabel('', fontsize=set_label_fontsize)
        self.cycle.set_ylabel('km/h', fontsize=set_label_fontsize)
        self.cycle.tick_params(labelsize=set_tick_fontsize)
        self.cycle.set(xlim=[0, max(cycle_time)])
        self.cycle.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.gear.plot([0, max(cycle_time)],
                       [self.i_CVT_ratio_min, self.i_CVT_ratio_min], 'c--')
        self.gear.plot([0, max(cycle_time)],
                       [self.i_CVT_ratio_max, self.i_CVT_ratio_max], 'c--')
        self.gear.plot(self.time_array,
                       self.i_CVT_ratio_array,
                       "o",
                       color='C1',
                       markersize=2)

        self.gear.set_title('CVT Ratio', fontsize=set_title_fontsize)
        self.gear.set_xlabel('', fontsize=set_label_fontsize)
        self.gear.set_ylabel('', fontsize=set_label_fontsize)
        self.gear.tick_params(labelsize=set_tick_fontsize)
        self.gear.set(
            xlim=[0, max(cycle_time)],
            ylim=[self.i_CVT_ratio_min - 0.2, self.i_CVT_ratio_max + 0.2])
        self.gear.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.brake.plot(self.time_array,
                        self.T_brake_array,
                        "o",
                        color='C1',
                        markersize=2)

        self.brake.set_title('Brake Torque', fontsize=set_title_fontsize)
        self.brake.set_xlabel('', fontsize=set_label_fontsize)
        self.brake.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.brake.tick_params(labelsize=set_tick_fontsize)
        self.brake.set(xlim=[0, max(cycle_time)])
        self.brake.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################

        for i in range(0, self.n_actions):
            self.action.plot([0, max(cycle_time)], [i, i], 'c-')
        self.action.plot(self.time_array,
                         self.action_array,
                         "o",
                         color='C1',
                         markersize=2)

        self.action.set_title('Action', fontsize=set_title_fontsize)
        self.action.set_xlabel('time (s)', fontsize=set_label_fontsize)
        self.action.set_ylabel('', fontsize=set_label_fontsize)
        self.action.tick_params(labelsize=set_tick_fontsize)
        self.action.set(xlim=[0, max(cycle_time)])
        self.action.grid(color='gray', linestyle='-', linewidth=0.5)

        #################################################################################
        #################################################################################
        ###########################
        X, Y = np.meshgrid(self.fc_map_spd * rads2rpm, self.fc_map_trq)
        C_fuel = self.fuel.contour(X,
                                   Y,
                                   self.fc_fuel_map.T,
                                   10,
                                   alpha=.75,
                                   cmap=plt.cm.hot)
        self.fuel.plot([i * rads2rpm for i in self.W_ice_array],
                       self.T_ice_array,
                       "o",
                       color='C2',
                       markersize=2)
        self.fuel.plot([i * rads2rpm for i in self.min_fuel_consum_line_spd],
                       self.min_fuel_consum_line_trq,
                       '-',
                       color='gold',
                       linewidth=3)
        self.fuel.plot(self.fc_map_spd * rads2rpm,
                       self.fc_max_trq,
                       '--',
                       color='red',
                       linewidth=3)
        self.fuel.clabel(C_fuel, inline=False, fontsize=set_label_fontsize)

        self.fuel.set_title('Fuel Comsumption (g/s)',
                            fontsize=set_title_fontsize)
        self.fuel.set_xlabel('rpm', fontsize=set_label_fontsize)
        self.fuel.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.fuel.tick_params(labelsize=set_tick_fontsize)
        self.fuel.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        X, Y = np.meshgrid(self.fc_map_spd * rads2rpm, self.fc_map_trq)
        kW_map = np.multiply(X, Y) / 1000
        C_bsfc = self.bsfc.contour(X,
                                   Y,
                                   self.fc_fuel_map.T / kW_map,
                                   30,
                                   alpha=.75,
                                   cmap=plt.cm.hot)
        self.bsfc.plot([i * rads2rpm for i in self.W_ice_array],
                       self.T_ice_array,
                       "o",
                       color='C2',
                       markersize=2)
        self.bsfc.plot([i * rads2rpm for i in self.min_fuel_consum_line_spd],
                       self.min_fuel_consum_line_trq,
                       '-',
                       color='gold',
                       linewidth=3)
        self.bsfc.plot(self.fc_map_spd * rads2rpm,
                       self.fc_max_trq,
                       '--',
                       color='red',
                       linewidth=3)
        self.bsfc.clabel(C_bsfc, inline=False, fontsize=1)

        self.bsfc.set_title('BSFC (g/kWh)', fontsize=set_title_fontsize)
        self.bsfc.set_xlabel('rpm ', fontsize=set_label_fontsize)
        self.bsfc.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.bsfc.tick_params(labelsize=set_tick_fontsize)
        self.bsfc.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.w_ice.plot(self.time_array,
                        [i * rads2rpm for i in self.W_ice_array],
                        "o",
                        color='C1',
                        markersize=2)

        self.w_ice.set_title('ICE Speed', fontsize=set_title_fontsize)
        self.w_ice.set_xlabel('', fontsize=set_label_fontsize)
        self.w_ice.set_ylabel('rpm', fontsize=set_label_fontsize)
        self.w_ice.tick_params(labelsize=set_tick_fontsize)
        self.w_ice.set(xlim=[0, max(cycle_time)])
        self.w_ice.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.t_ice.grid(color='gray', linestyle='-', linewidth=0.5)
        self.t_ice.set(xlim=[0, max(cycle_time)],
                       ylabel='ICE Torque (Nm)',
                       xlabel='')
        self.t_ice.plot(self.time_array,
                        self.T_ice_array,
                        "o",
                        color='C1',
                        markersize=2)

        self.t_ice.set_title('ICE Torque', fontsize=set_title_fontsize)
        self.t_ice.set_xlabel('', fontsize=set_label_fontsize)
        self.t_ice.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.t_ice.tick_params(labelsize=set_tick_fontsize)
        self.t_ice.set(xlim=[0, max(cycle_time)])
        self.t_ice.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.fig_kW_ice.plot(self.time_array,
                             self.kW_ice_array,
                             "o",
                             color='C1',
                             markersize=2)

        self.fig_kW_ice.set_title('ICE Power', fontsize=set_title_fontsize)
        self.fig_kW_ice.set_xlabel('', fontsize=set_label_fontsize)
        self.fig_kW_ice.set_ylabel('kW', fontsize=set_label_fontsize)
        self.fig_kW_ice.tick_params(labelsize=set_tick_fontsize)
        self.fig_kW_ice.set(xlim=[0, max(cycle_time)])
        self.fig_kW_ice.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.fig_instant_fuel.plot(self.time_array,
                                   self.fuel_instant_array,
                                   "o",
                                   color='C1',
                                   markersize=2)

        self.fig_instant_fuel.set_title('Instant Fuel Consumption',
                                        fontsize=set_title_fontsize)
        self.fig_instant_fuel.set_xlabel('time (s)',
                                         fontsize=set_label_fontsize)
        self.fig_instant_fuel.set_ylabel('g/s', fontsize=set_label_fontsize)
        self.fig_instant_fuel.tick_params(labelsize=set_tick_fontsize)
        self.fig_instant_fuel.set(xlim=[0, max(cycle_time)])
        self.fig_instant_fuel.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.fig_accumulated_fuel.plot(self.time_array,
                                       self.fuel_accumulate_array,
                                       "o",
                                       color='C1',
                                       markersize=2)

        self.fig_accumulated_fuel.set_title('Accumulated Fuel Consumption',
                                            fontsize=set_title_fontsize)
        self.fig_accumulated_fuel.set_xlabel('time (s)',
                                             fontsize=set_label_fontsize)
        self.fig_accumulated_fuel.set_ylabel('g', fontsize=set_label_fontsize)
        self.fig_accumulated_fuel.tick_params(labelsize=set_tick_fontsize)
        self.fig_accumulated_fuel.set(xlim=[0, max(cycle_time)])
        self.fig_accumulated_fuel.grid(color='gray',
                                       linestyle='-',
                                       linewidth=0.5)

        #################################################################################
        #################################################################################
        ###########################
        X, Y = np.meshgrid(self.mg2_map_spd * rads2rpm, self.mg2_map_trq)
        C_eff = self.mg2_map.contour(X,
                                     Y,
                                     self.mg2_eff_map.T,
                                     10,
                                     alpha=.75,
                                     cmap=plt.cm.hot)
        for ii in range(len(self.T_mg2_array)):
            if self.T_mg2_array[ii] < 0:
                self.mg2_map.plot(self.W_mg2_array[ii] * rads2rpm,
                                  self.T_mg2_array[ii],
                                  "o",
                                  color='purple',
                                  markersize=2)
            else:
                self.mg2_map.plot(self.W_mg2_array[ii] * rads2rpm,
                                  self.T_mg2_array[ii],
                                  "o",
                                  color='C2',
                                  markersize=2)
        self.mg2_map.plot(self.mg2_map_spd * rads2rpm,
                          self.mg2_max_trq,
                          '--',
                          color='red',
                          linewidth=3)
        self.mg2_map.plot(self.mg2_map_spd * rads2rpm,
                          self.mg2_max_gen_trq,
                          '--',
                          color='red',
                          linewidth=3)
        self.mg2_map.clabel(C_eff, inline=False, fontsize=set_tick_fontsize)

        self.mg2_map.set_title('MG2 Efficiency', fontsize=set_title_fontsize)
        self.mg2_map.set_xlabel('rpm', fontsize=set_label_fontsize)
        self.mg2_map.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.mg2_map.tick_params(labelsize=set_tick_fontsize)
        self.mg2_map.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.w_mg2.plot(self.time_array,
                        [i * rads2rpm for i in self.W_mg2_array],
                        "o",
                        color='C1',
                        markersize=2)

        self.w_mg2.set_title('MG2 Speed', fontsize=set_title_fontsize)
        self.w_mg2.set_xlabel('', fontsize=set_label_fontsize)
        self.w_mg2.set_ylabel('rpm', fontsize=set_label_fontsize)
        self.w_mg2.tick_params(labelsize=set_tick_fontsize)
        self.w_mg2.set(xlim=[0, max(cycle_time)])
        self.w_mg2.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.t_mg2.plot(self.time_array,
                        np.minimum(self.T_mg2_array, 0),
                        "o",
                        color='purple',
                        markersize=2)
        self.t_mg2.plot(self.time_array,
                        np.maximum(self.T_mg2_array, 0),
                        "o",
                        color='C1',
                        markersize=2)
        self.t_mg2.plot([0, max(cycle_time)], [0, 0], 'black', linewidth=2)

        self.t_mg2.set_title('MG2 Torque', fontsize=set_title_fontsize)
        self.t_mg2.set_xlabel('', fontsize=set_label_fontsize)
        self.t_mg2.set_ylabel('Nm', fontsize=set_label_fontsize)
        self.t_mg2.tick_params(labelsize=set_tick_fontsize)
        self.t_mg2.set(xlim=[0, max(cycle_time)])
        self.t_mg2.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.fig_kW_mg2.plot(self.time_array,
                             np.minimum(self.kW_mg2_array, 0),
                             "o",
                             color='purple',
                             markersize=2)
        self.fig_kW_mg2.plot(self.time_array,
                             np.maximum(self.kW_mg2_array, 0),
                             "o",
                             color='C1',
                             markersize=2)
        self.fig_kW_mg2.plot([0, max(cycle_time)], [0, 0],
                             'black',
                             linewidth=2)

        self.fig_kW_mg2.set_title('MG2 Power', fontsize=set_title_fontsize)
        self.fig_kW_mg2.set_xlabel('', fontsize=set_label_fontsize)
        self.fig_kW_mg2.set_ylabel('kW', fontsize=set_label_fontsize)
        self.fig_kW_mg2.tick_params(labelsize=set_tick_fontsize)
        self.fig_kW_mg2.set(xlim=[0, max(cycle_time)])
        self.fig_kW_mg2.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.fig_battery_charge.plot(self.time_array,
                                     np.minimum(self.battery_charge_array, 0),
                                     "o",
                                     color='purple',
                                     markersize=2)
        self.fig_battery_charge.plot(self.time_array,
                                     np.maximum(self.battery_charge_array, 0),
                                     "o",
                                     color='C1',
                                     markersize=2)

        self.fig_battery_charge.set_title('Battery Charge',
                                          fontsize=set_title_fontsize)
        self.fig_battery_charge.set_xlabel('', fontsize=set_label_fontsize)
        self.fig_battery_charge.set_ylabel('kW', fontsize=set_label_fontsize)
        self.fig_battery_charge.tick_params(labelsize=set_tick_fontsize)
        self.fig_battery_charge.set(xlim=[0, max(cycle_time)])
        self.fig_battery_charge.grid(color='gray',
                                     linestyle='-',
                                     linewidth=0.5)

        ############################
        self.fig_battery_soc.plot(self.time_array,
                                  self.battery_soc_array,
                                  "o",
                                  color='C1',
                                  markersize=2)

        self.fig_battery_soc.set_title('Battery SOC',
                                       fontsize=set_title_fontsize)
        self.fig_battery_soc.set_xlabel('time (s)',
                                        fontsize=set_label_fontsize)
        self.fig_battery_soc.set_ylabel('', fontsize=set_label_fontsize)
        self.fig_battery_soc.tick_params(labelsize=set_tick_fontsize)
        self.fig_battery_soc.set(xlim=[0, max(cycle_time)],
                                 ylim=[self.soc_min, self.soc_max])
        self.fig_battery_soc.grid(color='gray', linestyle='-', linewidth=0.5)

        #################################################################################
        #################################################################################
        ###########################
        self.fig_reward.plot(self.time_array,
                             self.reward_array,
                             "o",
                             color='C1',
                             markersize=2)

        self.fig_reward.set_title('Instant Reward',
                                  fontsize=set_title_fontsize)
        self.fig_reward.set_xlabel('time (s)', fontsize=set_label_fontsize)
        self.fig_reward.set_ylabel('', fontsize=set_label_fontsize)
        self.fig_reward.tick_params(labelsize=set_tick_fontsize)
        self.fig_reward.set(xlim=[0, max(cycle_time)], ylim=[0, 100])
        self.fig_reward.grid(color='gray', linestyle='-', linewidth=0.5)

        #################################################################################
        #################################################################################
        ###########################
        self.fig_learning_curve.plot(
            [i + last_time_iteration - 1 for i in self.cycle_iteration_array],
            self.ave_cyc_reward_array,
            "-",
            color='C2',
            markersize=2)

        self.fig_learning_curve.set_title('Learning Curve',
                                          fontsize=set_title_fontsize)
        self.fig_learning_curve.set_xlabel('', fontsize=set_label_fontsize)
        self.fig_learning_curve.set_ylabel('Average Reward',
                                           fontsize=set_label_fontsize)
        self.fig_learning_curve.tick_params(labelsize=set_tick_fontsize)
        self.fig_learning_curve.set(xlim=[
            last_time_iteration,
            max(self.cycle_iteration_array) + last_time_iteration - 1
        ],
                                    ylim=[0, 100])
        self.fig_learning_curve.grid(color='gray',
                                     linestyle='-',
                                     linewidth=0.5)

        # print('average cycle reward:', self.reward_acum_array[-1]/self.cycle_total_step_number)

        ###########################
        self.d_speed.plot(
            [i + last_time_iteration - 1 for i in self.cycle_iteration_array],
            self.ave_cyc_speed_difference_kmh_array,
            "-",
            color='C2',
            markersize=2)

        self.d_speed.set_title('Average Speed Error',
                               fontsize=set_title_fontsize)
        self.d_speed.set_xlabel('', fontsize=set_label_fontsize)
        self.d_speed.set_ylabel('km/h', fontsize=set_label_fontsize)
        self.d_speed.tick_params(labelsize=set_tick_fontsize)
        self.d_speed.set(xlim=[
            last_time_iteration,
            max(self.cycle_iteration_array) + last_time_iteration - 1
        ])
        self.d_speed.grid(color='gray', linestyle='-', linewidth=0.5)

        ###########################
        self.cyc_fuel.plot(
            [i + last_time_iteration - 1 for i in self.cycle_iteration_array],
            self.cyc_fuel_accumulate_array,
            "-",
            color='C2',
            markersize=2)

        self.cyc_fuel.set_title('Average Fuel Consumption',
                                fontsize=set_title_fontsize)
        self.cyc_fuel.set_xlabel('iteration', fontsize=set_label_fontsize)
        self.cyc_fuel.set_ylabel('g/s', fontsize=set_label_fontsize)
        self.cyc_fuel.tick_params(labelsize=set_tick_fontsize)
        self.cyc_fuel.set(xlim=[
            last_time_iteration,
            max(self.cycle_iteration_array) + last_time_iteration - 1
        ])
        self.cyc_fuel.grid(color='gray', linestyle='-', linewidth=0.5)

        #################################################################################
        #################################################################################
        #################################################################################
        self.canvas2.draw()
        self.f.savefig('result_figure/' + self.vehicle_name + '/iteration_' +
                       str(last_time_iteration + cycle_round) + '_' +
                       str(cycle_name) + '_reward-' +
                       str(round(max_cycle_reward, 2)) + '.png',
                       format="png",
                       dpi=100)
        scipy.io.savemat(
            'result_data/' + self.vehicle_name + '/iteration_' +
            str(last_time_iteration + cycle_round) + '_' + str(cycle_name) +
            '_reward-' + str(round(max_cycle_reward, 2)) + '.mat', {
                'sim_t_dqn': self.time_array,
                'sim_action_dqn': self.action_array,
                'sim_W_ice_dqn': self.W_ice_array,
                'sim_T_ice_dqn': self.T_ice_array,
                'sim_P_ice_dqn': self.kW_ice_array,
                'sim_W_mg2_dqn': self.W_mg2_array,
                'sim_T_mg2_dqn': self.T_mg2_array,
                'sim_P_mg2_dqn': self.kW_mg2_array,
                'sim_car_kph_dqn': self.v_vehicle_kmh_array,
                'sim_T_brake_dqn': self.T_brake_array,
                'sim_CVT_ratio_dqn': self.i_CVT_ratio_array,
                'sim_fuel_accumulate_dqn': self.fuel_accumulate_array,
                'sim_fuel_instant_dqn': self.fuel_instant_array,
                'sim_battery_charge_dqn': self.battery_charge_array,
                'sim_battery_soc_dqn': self.battery_soc_array,
                'sim_reward_dqn': self.reward_array,
                'sim_acum_reward_dqn': self.reward_acum_array,
                'cycle_iteration_dqn': self.cycle_iteration_array,
                'ave_cyc_reward_dqn': self.ave_cyc_reward_array,
                'cyc_fuel_accumulate_dqn': self.cyc_fuel_accumulate_array,
                'ave_cyc_speed_difference_kmh_dqn':
                self.ave_cyc_speed_difference_kmh_array,
                'speed_difference_kmh_dqn': self.speed_difference_kmh_array
            })

    def clear_figure(self):
        self.cycle.cla()
        self.gear.cla()
        self.brake.cla()
        self.action.cla()
        self.bsfc.cla()
        self.fuel.cla()
        self.w_ice.cla()
        self.t_ice.cla()
        self.fig_kW_ice.cla()
        self.fig_instant_fuel.cla()
        self.fig_accumulated_fuel.cla()
        self.mg2_map.cla()
        self.w_mg2.cla()
        self.t_mg2.cla()
        self.fig_kW_mg2.cla()
        self.fig_battery_charge.cla()
        self.fig_battery_soc.cla()
        self.fig_reward.cla()
        self.d_speed.cla()

    def vehicle_powertrain(self, action, time, cycle_end_time,
                           next_cycle_target_speed, next2_cycle_target_speed):
        self.i_f_gear_ratio = 3.21
        self.d_i_CVT_ratio = 0.1  # for CVT

        self.d_T_ice = 10
        self.T_ice_max = np.interp(self.W_ice, self.fc_map_spd,
                                   self.fc_max_trq)
        self.T_ice_min = 0
        self.W_ice_idle_spd_rs = 73.4  # % idle speed is 701 rpm = 73.4 rad/s
        self.I_ice = 0.18

        self.d_T_mg2 = 20
        self.T_mg2_max = np.interp(self.W_mg2, self.mg2_map_spd,
                                   self.mg2_max_trq)
        self.T_mg2_min = np.interp(self.W_mg2, self.mg2_map_spd,
                                   self.mg2_max_gen_trq)
        self.I_mg2 = 0.2

        self.d_T_brake = 50
        self.T_brake_max = 2000

        self.m_vehicle_kg = 1400  # vehicle mass kg
        self.m_equ_vehicle_kg = 1600  # vehicle equivalent mass kg (effective mass of the vehicle)
        self.r_wheel = 0.28  # m

        self.batt_kWh = 1.3  # battery capacity watt hour Toyota Prius III: 1.3 kWh
        self.batt_J = self.batt_kWh * 1000 * 60 * 60
        self.soc_max = 0.8
        self.soc_min = 0.2

        gravity = 9.81
        rho_air = 1.2  # Air density (kg/m^3)
        a_front_m2 = 2.3  # frontal area (m^2)
        c_d = 0.3  # Aerodynamic drag coefficient
        c_r = 0.009  # Rolling resistance coefficient

        # execute action
        if action == 0:  # no action
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 1:  # increase ICE torque
            if self.T_ice + self.d_T_ice > self.T_ice_max:
                self.T_ice = self.T_ice_max
            else:
                self.T_ice = self.T_ice + self.d_T_ice
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 2:  # decrease ICE torque
            if self.T_ice - self.d_T_ice < self.T_ice_min:
                self.T_ice = self.T_ice_min
            else:
                self.T_ice = self.T_ice - self.d_T_ice
            self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 3:  # increase Motor torque
            if self.T_mg2 < 0:
                self.T_mg2 = 0
            if self.T_mg2 + self.d_T_mg2 > self.T_mg2_max:
                self.mg2 = self.T_mg2_max
            else:
                self.T_mg2 = self.T_mg2 + self.d_T_mg2
            if self.W_mg2 > max(self.mg2_map_spd):
                self.T_mg2 = 0
            self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 4:  # decrease Motor torque
            if self.T_mg2 < 0:
                self.T_mg2 = 0
            if self.T_mg2 - self.d_T_mg2 < 0:
                self.T_mg2 = 0
            else:
                self.T_mg2 = self.T_mg2 - self.d_T_mg2
            self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 5:  # increase Generator torque
            if self.T_mg2 > 0:
                self.T_mg2 = 0
            if self.T_mg2 - self.d_T_mg2 < self.T_mg2_min:
                self.T_mg2 = self.T_mg2_min
            else:
                self.T_mg2 = self.T_mg2 - self.d_T_mg2
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 6:  # decrease Generator torque
            if self.T_mg2 > 0:
                self.T_mg2 = 0
            if self.T_mg2 + self.d_T_mg2 > 0:
                self.mg2 = 0
            else:
                self.T_mg2 = self.T_mg2 + self.d_T_mg2
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 7:  # shift up one gear
            if self.i_CVT_ratio + self.d_i_CVT_ratio > self.i_CVT_ratio_max:
                self.i_CVT_ratio = self.i_CVT_ratio_max
            else:
                self.i_CVT_ratio = self.i_CVT_ratio + self.d_i_CVT_ratio
            # self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 8:  # shift down one gear
            if self.i_CVT_ratio - self.d_i_CVT_ratio < self.i_CVT_ratio_min:
                self.i_CVT_ratio = self.i_CVT_ratio_min
            else:
                self.i_CVT_ratio = self.i_CVT_ratio - self.d_i_CVT_ratio
            # self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 9:  # increase Brake torque
            if self.T_brake + self.d_T_brake > self.T_brake_max:
                self.T_brake = self.T_brake_max
            else:
                self.T_brake = self.T_brake + self.d_T_brake
            if self.W_wheel < 0:
                self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0
        elif action == 10:  # decrease Brake torque
            if self.T_brake + self.d_T_brake < 0:
                self.T_brake = 0
            else:
                self.T_brake = self.T_brake - self.d_T_brake
            if self.W_wheel < 0:
                self.T_brake = 0
            if self.W_ice > max(self.fc_map_spd):
                self.T_ice = 0
            if abs(self.W_mg2) > max(self.mg2_map_spd):
                self.T_mg2 = 0

        ### Constraints & Punishment ###
        punishment = 0

        if self.T_ice > self.T_ice_max:
            self.T_ice = self.T_ice_max
            punishment = punishment + 10
        if self.T_ice < self.T_ice_min:
            self.T_ice = 0
            punishment = punishment + 10
        if self.W_ice > max(self.fc_map_spd):
            self.T_ice = 0
            punishment = punishment + 100

        if self.T_mg2 > self.T_mg2_max:
            self.T_mg2 = self.T_mg2_max
            punishment = punishment + 10
        if self.T_mg2 < self.T_mg2_min:
            self.T_mg2 = 0
            punishment = punishment + 10
        if self.W_mg2 > max(self.mg2_map_spd):
            self.T_mg2 = 0
            punishment = punishment + 10
        if self.W_mg2 < 0:
            self.T_mg2 = 0
            punishment = punishment + 10
        if self.soc < self.soc_min and self.T_mg2 > 0:
            self.T_mg2 = 0
            punishment = punishment + 10
        if self.soc > self.soc_max and self.T_mg2 < 0:
            self.T_mg2 = 0
            punishment = punishment + 10

        if self.T_brake > self.T_brake_max:
            self.T_brake = self.T_brake_max
            punishment = punishment + 10
        if self.T_brake < 0:
            self.T_brake = 0
            punishment = punishment + 10

        if self.soc < self.soc_min:
            punishment = punishment + 100
        if self.soc > self.soc_max:
            punishment = punishment + 100

        # calculate resistance
        if self.v_vehicle < 0:
            self.total_resis_torque = 0
        else:
            self.resis_roll = self.m_vehicle_kg * gravity * c_r
            self.resis_aero = 1 / 2 * c_d * rho_air * a_front_m2 * self.v_vehicle**2
            self.total_resis = self.resis_roll + self.resis_aero
            self.total_resis_torque = self.total_resis * self.r_wheel

        ### Powertrain Dynamics ###
        self.dW_wheel = \
        (self.T_ice*self.i_CVT_ratio*self.i_f_gear_ratio \
        +self.T_mg2*self.i_CVT_ratio*self.i_f_gear_ratio \
        -self.T_brake \
        -self.total_resis_torque) \
        /((self.r_wheel**2*self.m_equ_vehicle_kg) \
        +self.I_mg2*(self.i_CVT_ratio**2)*(self.i_f_gear_ratio**2) \
        +self.I_ice*(self.i_CVT_ratio**2)*(self.i_f_gear_ratio**2))

        # calculate speed
        self.W_wheel = self.W_wheel + self.dW_wheel  # rad/s
        self.W_mg2 = self.W_wheel * self.i_CVT_ratio * self.i_f_gear_ratio
        self.W_ice = self.W_wheel * self.i_CVT_ratio * self.i_f_gear_ratio
        if self.W_ice < self.W_ice_idle_spd_rs and self.W_ice > 0:
            self.W_ice = self.W_ice_idle_spd_rs
        if self.W_ice < self.W_ice_idle_spd_rs and self.T_ice > 0:
            self.W_ice = self.W_ice_idle_spd_rs

        self.v_vehicle = self.W_wheel * self.r_wheel  # m/s
        self.v_vehicle_kmh = self.v_vehicle * 60 * 60 / 1000  #km/h

        # speed constraints to avoid negative speed caused by numerical issue
        if self.W_wheel < 0 or self.W_mg2 < 0 or self.W_ice < 0 or self.v_vehicle < 0 or self.v_vehicle_kmh < 0:
            self.W_wheel = 0
            self.W_mg2 = 0
            self.W_ice = 0
            self.v_vehicle = 0
            self.v_vehicle_kmh = 0
            punishment = punishment + 1000

        self.kW_ice = self.W_ice * self.T_ice / 1000
        self.kW_mg2 = self.W_mg2 * self.T_mg2 / 1000

        # calculate ice fuel consumption
        fuel_map = interpolate.interp2d(self.fc_map_trq,
                                        self.fc_map_spd,
                                        self.fc_fuel_map,
                                        kind='cubic')
        self.ICE_fuel_consum = fuel_map(self.T_ice, self.W_ice)[0]
        if self.W_ice < self.W_ice_idle_spd_rs:
            self.ICE_fuel_consum = 0
        self.fuel_instant = self.ICE_fuel_consum * self.cycle_dt
        self.fuel_accumulate = self.fuel_accumulate + self.fuel_instant

        # calculate mg2 efficiency
        mg2_map = interpolate.interp2d(self.mg2_map_trq,
                                       self.mg2_map_spd,
                                       self.mg2_eff_map,
                                       kind='cubic')
        self.mg2_eff = mg2_map(self.T_mg2, self.W_mg2)[0]

        # calculate battery soc
        self.W_batt_c = self.kW_mg2 / self.mg2_eff * 1000  # +: discharge; -: charge
        self.J_batt_c = self.W_batt_c * self.cycle_dt  # J
        self.dsoc = -self.J_batt_c / self.batt_J
        self.soc = (self.soc + self.dsoc)

        reward = (1/1)*(70*0.95**(abs(self.current_cycle_target_speed-self.v_vehicle_kmh))  \
        +10*0.5**(self.ICE_fuel_consum) \
        +10*0.95**(100*abs(self.soc-0.6)) \
        +10*0.97**(punishment))

        if time == 0:
            self.reward_acum = 0
        else:
            self.reward_acum = self.reward_acum + reward

        self.time_array.append(time)
        self.action_array.append(action)
        self.W_ice_array.append(self.W_ice)
        self.T_ice_array.append(self.T_ice)
        self.kW_ice_array.append(self.kW_ice)
        self.W_mg2_array.append(self.W_mg2)
        self.T_mg2_array.append(self.T_mg2)
        self.kW_mg2_array.append(self.kW_mg2)
        self.v_vehicle_array.append(self.v_vehicle)
        self.v_vehicle_kmh_array.append(self.v_vehicle_kmh)
        self.T_brake_array.append(self.T_brake)
        self.i_CVT_ratio_array.append(self.i_CVT_ratio)
        self.fuel_instant_array.append(self.fuel_instant)
        self.fuel_accumulate_array.append(self.fuel_accumulate)
        self.battery_charge_array.append(self.W_batt_c)
        self.battery_soc_array.append(self.soc)
        self.reward_array.append(reward)
        self.reward_acum_array.append(self.reward_acum)
        self.speed_difference_kmh_array.append(
            abs(self.current_cycle_target_speed - self.v_vehicle_kmh))
        if time == cycle_end_time:
            self.cycle_iteration = self.cycle_iteration + 1
            self.cycle_iteration_array.append(self.cycle_iteration)
            self.ave_cyc_reward_array.append(
                self.reward_acum_array[-1] /
                self.cycle_total_step_number)  # average cycle reward
            self.cyc_fuel_accumulate_array.append(
                self.fuel_accumulate_array[-1])
            self.ave_cyc_speed_difference_kmh_array.append(
                sum(self.speed_difference_kmh_array) /
                self.cycle_total_step_number)
            self.speed_difference_kmh_array = []

        s_ = np.array([
            self.W_ice, self.T_ice, self.W_mg2, self.T_mg2, self.i_CVT_ratio,
            self.T_brake, self.soc, self.v_vehicle_kmh,
            next_cycle_target_speed, next2_cycle_target_speed
        ])

        return s_, reward, self.cycle_iteration_array, self.ave_cyc_reward_array

    def render(self):
        self.update()
示例#50
0
class Display(object):
    def __init__(self, db_name):

        self.root = Tk.Tk()
        self.root.wm_title("Viewer")

        self.f = plt.figure(dpi=100, figsize=(12, 6), facecolor='white')
        self.canvas = FigureCanvasTkAgg(self.f, master=self.root)
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.options_frame = Tk.Frame(self.root)
        self.options_frame.pack()

        toolbar = NavigationToolbar2TkAgg(self.canvas, self.root)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.ax = plt.subplot2grid((4, 8), (0, 0),
                                   rowspan=4,
                                   colspan=4,
                                   projection='3d')

        self.num_iters = 0
        self.db_name = db_name
        self.show_wing = True
        self.show_tube = True
        self.curr_pos = 0
        self.old_n = 0

        self.load_db()

        if self.show_wing and not self.show_tube:
            self.ax2 = plt.subplot2grid((4, 8), (0, 4), rowspan=2, colspan=4)
            self.ax3 = plt.subplot2grid((4, 8), (2, 4), rowspan=2, colspan=4)
        if self.show_tube and not self.show_wing:
            self.ax4 = plt.subplot2grid((4, 8), (0, 4), rowspan=2, colspan=4)
            self.ax5 = plt.subplot2grid((4, 8), (2, 4), rowspan=2, colspan=4)
        if self.show_wing and self.show_tube:
            self.ax2 = plt.subplot2grid((4, 8), (0, 4), colspan=4)
            self.ax3 = plt.subplot2grid((4, 8), (1, 4), colspan=4)
            self.ax4 = plt.subplot2grid((4, 8), (2, 4), colspan=4)
            self.ax5 = plt.subplot2grid((4, 8), (3, 4), colspan=4)

    def load_db(self):
        # Change for future versions of OpenMDAO, still in progress
        # self.db_metadata = sqlitedict.SqliteDict(self.db_name, 'metadata')
        # self.db = sqlitedict.SqliteDict(self.db_name, 'iterations')

        self.db = sqlitedict.SqliteDict(self.db_name, 'openmdao')

        self.twist = []
        self.mesh = []
        self.def_mesh = []
        self.r = []
        self.t = []
        sec_forces = []
        normals = []
        widths = []
        self.lift = []
        self.lift_ell = []
        self.vonmises = []
        alpha = []
        rho = []
        v = []
        self.CL = []
        self.AR = []
        self.S_ref = []
        self.obj = []

        # Change for future versions of OpenMDAO
        # for tag in self.db_metadata:
        #     try:
        #         for item in self.db_metadata[tag]:
        #             for flag in self.db_metadata[tag][item]:
        #                 if 'is_objective' in flag:
        #                     self.obj_key = item
        #
        # except:
        #     pass

        for tag in self.db['metadata']:
            for item in self.db['metadata'][tag]:
                for flag in self.db['metadata'][tag][item]:
                    if 'is_objective' in flag:
                        self.obj_key = item

        for case_name, case_data in self.db.iteritems():
            if "metadata" in case_name or "derivs" in case_name or "Driver" in case_name:
                continue  # don't plot these cases
            names = []
            for key in case_data['Unknowns'].keys():
                if 'mesh' in key and 'def_mesh' not in key:
                    names.append(key.split('_')[:-1][0] + '_')
            self.names = names
            n_names = len(names)
            self.obj.append(case_data['Unknowns'][self.obj_key])

            for name in names:
                self.mesh.append(case_data['Unknowns'][name + 'mesh'])

                try:
                    self.r.append(case_data['Unknowns'][name + 'r'])
                    self.t.append(case_data['Unknowns'][name + 'thickness'])
                    self.vonmises.append(
                        numpy.max(case_data['Unknowns'][name + 'vonmises'],
                                  axis=1))
                    self.show_tube = True
                except:
                    self.show_tube = False
                try:
                    self.def_mesh.append(case_data['Unknowns'][name +
                                                               'def_mesh'])
                    self.twist.append(case_data['Unknowns'][name + 'twist'])
                    normals.append(case_data['Unknowns'][name + 'normals'])
                    widths.append(case_data['Unknowns'][name + 'widths'])
                    sec_forces.append(case_data['Unknowns'][name +
                                                            'sec_forces'])
                    self.CL.append(case_data['Unknowns'][name + 'CL1'])
                    self.S_ref.append(case_data['Unknowns'][name + 'S_ref'])
                    self.show_wing = True
                except:
                    self.show_wing = False

            if self.show_wing:
                alpha.append(case_data['Unknowns']['alpha'] * numpy.pi / 180.)
                rho.append(case_data['Unknowns']['rho'])
                v.append(case_data['Unknowns']['v'])

        self.num_iters = numpy.max([int(len(self.mesh) / n_names) - 1, 1])

        symm_count = 0
        for mesh in self.mesh:
            if numpy.all(mesh[:, :, 1] >= -1e-8) or numpy.all(
                    mesh[:, :, 1] <= 1e-8):
                symm_count += 1
        if symm_count == len(self.mesh):
            self.symmetry = True
        else:
            self.symmetry = False

        if self.show_wing:
            for i in range(self.num_iters + 1):
                for j, name in enumerate(names):
                    m_vals = self.mesh[i + j].copy()
                    cvec = m_vals[0, :, :] - m_vals[-1, :, :]
                    chords = numpy.sqrt(numpy.sum(cvec**2, axis=1))
                    chords = 0.5 * (chords[1:] + chords[:-1])
                    a = alpha[i]
                    cosa = numpy.cos(a)
                    sina = numpy.sin(a)
                    forces = numpy.sum(sec_forces[i + j], axis=0)
                    widths_ = numpy.mean(widths[i + j], axis=0)

                    lift = (-forces[:, 0] * sina + forces[:, 2] * cosa) / \
                        widths_/0.5/rho[i]/v[i]**2
                    # lift = (-forces[:, 0] * sina + forces[:, 2] * cosa)/chords/0.5/rho[i]/v[i]**2
                    # lift = (-forces[:, 0] * sina + forces[:, 2] * cosa)*chords/0.5/rho[i]/v[i]**2

                    if self.symmetry:
                        span = (m_vals[0, :, 1] /
                                (m_vals[0, -1, 1] - m_vals[0, 0, 1]))
                        span = numpy.hstack((span[:-1], -span[::-1]))

                        lift = numpy.hstack((lift, lift[::-1]))

                        lift_area = numpy.sum(lift * (span[1:] - span[:-1]))

                        lift_ell = 2 * lift_area / numpy.pi * \
                            numpy.sqrt(1 - span**2)

                    else:
                        span = (m_vals[0, :, 1] /
                                (m_vals[0, -1, 1] - m_vals[0, 0, 1]))
                        span = span - (span[0] + .5)

                        lift_area = numpy.sum(lift * (span[1:] - span[:-1]))

                        lift_ell = 4 * lift_area / numpy.pi * \
                            numpy.sqrt(1 - (2*span)**2)

                    self.lift.append(lift)
                    self.lift_ell.append(lift_ell)

                    wingspan = numpy.abs(m_vals[0, -1, 1] - m_vals[0, 0, 1])
                    self.AR.append(wingspan**2 / self.S_ref[i + j])

            # recenter def_mesh points for better viewing
            for i in range(self.num_iters + 1):
                center = numpy.mean(self.mesh[i * n_names:i * n_names +
                                              n_names],
                                    axis=(0, 1, 2))
                self.def_mesh[i * n_names:i * n_names +
                              n_names] = self.def_mesh[i *
                                                       n_names:i * n_names +
                                                       n_names] - center

        # recenter mesh points for better viewing
        for i in range(self.num_iters + 1):
            # center defined as the average of all nodal points
            center = numpy.mean(self.mesh[i * n_names:i * n_names + n_names],
                                axis=(0, 1, 2))
            # center defined as the mean of the min and max in each direction
            # center = (numpy.max(self.mesh[i], axis=0) + numpy.min(self.mesh[i], axis=0)) / 2
            self.mesh[i * n_names:i * n_names +
                      n_names] = self.mesh[i * n_names:i * n_names +
                                           n_names] - center

        if self.show_wing:
            self.min_twist, self.max_twist = numpy.min(self.twist), numpy.max(
                self.twist)
            diff = (self.max_twist - self.min_twist) * 0.05
            self.min_twist -= diff
            self.max_twist += diff
            self.min_l, self.max_l = numpy.min(self.lift), numpy.max(self.lift)
            self.min_le, self.max_le = numpy.min(self.lift_ell), numpy.max(
                self.lift_ell)
            self.min_l, self.max_l = min(self.min_l, self.min_le), max(
                self.max_l, self.max_le)
            diff = (self.max_l - self.min_l) * 0.05
            self.min_l -= diff
            self.max_l += diff
        if self.show_tube:
            self.min_t, self.max_t = numpy.min(self.t), numpy.max(self.t)
            diff = (self.max_t - self.min_t) * 0.05
            self.min_t -= diff
            self.max_t += diff
            self.min_vm, self.max_vm = numpy.min(self.vonmises), numpy.max(
                self.vonmises)
            diff = (self.max_vm - self.min_vm) * 0.05
            self.min_vm -= diff
            self.max_vm += diff

    def plot_sides(self):

        if self.show_wing:

            self.ax2.cla()
            self.ax2.locator_params(axis='y', nbins=5)
            self.ax2.locator_params(axis='x', nbins=3)
            self.ax2.set_ylim([self.min_twist, self.max_twist])
            self.ax2.set_xlim([-1, 1])
            self.ax2.set_ylabel('twist', rotation="horizontal", ha="right")

            self.ax3.cla()
            self.ax3.text(0.05,
                          0.8,
                          'elliptical',
                          transform=self.ax3.transAxes,
                          color='g')
            self.ax3.locator_params(axis='y', nbins=4)
            self.ax3.locator_params(axis='x', nbins=3)
            self.ax3.set_ylim([self.min_l, self.max_l])
            self.ax3.set_xlim([-1, 1])
            self.ax3.set_ylabel('lift', rotation="horizontal", ha="right")

        if self.show_tube:

            self.ax4.cla()
            self.ax4.locator_params(axis='y', nbins=4)
            self.ax4.locator_params(axis='x', nbins=3)
            self.ax4.set_ylim([self.min_t, self.max_t])
            self.ax4.set_xlim([-1, 1])
            self.ax4.set_ylabel('thickness', rotation="horizontal", ha="right")

            self.ax5.cla()
            self.ax5.locator_params(axis='y', nbins=4)
            self.ax5.locator_params(axis='x', nbins=3)
            self.ax5.set_ylim([self.min_vm, self.max_vm])
            self.ax5.set_ylim([0, 25e6])
            self.ax5.set_xlim([-1, 1])
            self.ax5.set_ylabel('von mises', rotation="horizontal", ha="right")
            self.ax5.axhline(aluminum.stress, c='r', lw=2, ls='--')
            self.ax5.text(0.05,
                          0.85,
                          'failure limit',
                          transform=self.ax5.transAxes,
                          color='r')

        for j, name in enumerate(self.names):
            m_vals = self.mesh[self.curr_pos + j].copy()
            span = m_vals[0, -1, 1] - m_vals[0, 0, 1]
            if self.symmetry:
                rel_span = (m_vals[0, :, 1] - m_vals[0, 0, 1]) / span - 1
                rel_span = numpy.hstack((rel_span[:-1], -rel_span[::-1]))
                span_diff = ((m_vals[0, :-1, 1] + m_vals[0, 1:, 1]) / 2 -
                             m_vals[0, 0, 1]) / span - 1
                span_diff = numpy.hstack((span_diff, -span_diff[::-1]))
            else:
                rel_span = (m_vals[0, :, 1] - m_vals[0, 0, 1]) * 2 / span - 1
                span_diff = ((m_vals[0, :-1, 1] + m_vals[0, 1:, 1]) / 2 -
                             m_vals[0, 0, 1]) * 2 / span - 1

            if self.show_wing:
                t_vals = self.twist[self.curr_pos + j]
                l_vals = self.lift[self.curr_pos + j]
                le_vals = self.lift_ell[self.curr_pos + j]

                if self.symmetry:
                    t_vals = numpy.hstack((t_vals[:-1], t_vals[::-1]))

                self.ax2.plot(rel_span, t_vals, lw=2, c='b')
                self.ax3.plot(rel_span, le_vals, '--', lw=2, c='g')
                self.ax3.plot(span_diff, l_vals, lw=2, c='b')

            if self.show_tube:
                thick_vals = self.t[self.curr_pos + j]
                vm_vals = self.vonmises[self.curr_pos + j]

                if self.symmetry:
                    thick_vals = numpy.hstack((thick_vals, thick_vals[::-1]))
                    vm_vals = numpy.hstack((vm_vals, vm_vals[::-1]))

                self.ax4.plot(span_diff, thick_vals, lw=2, c='b')
                self.ax5.plot(span_diff, vm_vals, lw=2, c='b')

    def plot_wing(self):

        n_names = len(self.names)
        self.ax.cla()
        az = self.ax.azim
        el = self.ax.elev
        dist = self.ax.dist

        for j, name in enumerate(self.names):
            mesh0 = self.mesh[self.curr_pos + j].copy()

            self.ax.set_axis_off()

            if self.show_wing:
                def_mesh0 = self.def_mesh[self.curr_pos + j]
                x = mesh0[:, :, 0]
                y = mesh0[:, :, 1]
                z = mesh0[:, :, 2]

                try:  # show deformed mesh option may not be available
                    if self.show_def_mesh.get():
                        x_def = def_mesh0[:, :, 0]
                        y_def = def_mesh0[:, :, 1]
                        z_def = def_mesh0[:, :, 2]

                        self.c2.grid(row=0, column=3, padx=5, sticky=Tk.W)
                        if self.ex_def.get():
                            z_def = (z_def - z) * 10 + z_def
                            def_mesh0 = (def_mesh0 - mesh0) * 30 + def_mesh0
                        else:
                            def_mesh0 = (def_mesh0 - mesh0) * 2 + def_mesh0
                        self.ax.plot_wireframe(x_def,
                                               y_def,
                                               z_def,
                                               rstride=1,
                                               cstride=1,
                                               color='k')
                        self.ax.plot_wireframe(x,
                                               y,
                                               z,
                                               rstride=1,
                                               cstride=1,
                                               color='k',
                                               alpha=.3)
                    else:
                        self.ax.plot_wireframe(x,
                                               y,
                                               z,
                                               rstride=1,
                                               cstride=1,
                                               color='k')
                        self.c2.grid_forget()
                except:
                    self.ax.plot_wireframe(x,
                                           y,
                                           z,
                                           rstride=1,
                                           cstride=1,
                                           color='k')

            if self.show_tube:
                r0 = self.r[self.curr_pos + j]
                t0 = self.t[self.curr_pos + j]
                colors = t0
                colors = colors / numpy.max(colors)
                num_circ = 12
                fem_origin = 0.35
                n = mesh0.shape[1]
                p = numpy.linspace(0, 2 * numpy.pi, num_circ)
                if self.show_wing:
                    if self.show_def_mesh.get():
                        mesh0[:, :, 2] = def_mesh0[:, :, 2]
                for i, thick in enumerate(t0):
                    r = numpy.array((r0[i], r0[i]))
                    R, P = numpy.meshgrid(r, p)
                    X, Z = R * numpy.cos(P), R * numpy.sin(P)
                    chords = mesh0[-1, :, 0] - mesh0[0, :, 0]
                    comp = fem_origin * chords + mesh0[0, :, 0]
                    X[:, 0] += comp[i]
                    X[:, 1] += comp[i + 1]
                    Z[:, 0] += fem_origin * (mesh0[-1, i, 2] -
                                             mesh0[0, i, 2]) + mesh0[0, i, 2]
                    Z[:,
                      1] += fem_origin * (mesh0[-1, i + 1, 2] -
                                          mesh0[0, i + 1, 2]) + mesh0[0, i + 1,
                                                                      2]
                    Y = numpy.empty(X.shape)
                    Y[:] = numpy.linspace(mesh0[0, i, 1], mesh0[0, i + 1, 1],
                                          2)
                    col = numpy.zeros(X.shape)
                    col[:] = colors[i]
                    try:
                        self.ax.plot_surface(X,
                                             Y,
                                             Z,
                                             rstride=1,
                                             cstride=1,
                                             facecolors=cm.viridis(col),
                                             linewidth=0)
                    except:
                        self.ax.plot_surface(X,
                                             Y,
                                             Z,
                                             rstride=1,
                                             cstride=1,
                                             facecolors=cm.coolwarm(col),
                                             linewidth=0)

        lim = numpy.max(self.mesh[self.curr_pos *
                                  n_names:self.curr_pos * n_names + n_names],
                        axis=(0, 1, 2)) / float(zoom_scale)
        self.ax.auto_scale_xyz([-lim, lim], [-lim, lim], [-lim, lim])
        self.ax.set_title("Major Iteration: {}".format(self.curr_pos))

        round_to_n = lambda x, n: round(
            x, -int(numpy.floor(numpy.log10(abs(x)))) + (n - 1))
        obj_val = round_to_n(self.obj[self.curr_pos], 7)
        self.ax.text2D(.55,
                       .05,
                       self.obj_key + ': {}'.format(obj_val),
                       transform=self.ax.transAxes,
                       color='k')

        # if self.show_wing and not self.show_tube:
        #     span_eff = self.CL[self.curr_pos+j]**2 / numpy.pi / self.AR[self.curr_pos+j] / obj_val
        #     self.ax.text2D(.55, .0, 'e: {}'.format(round_to_n(span_eff, 7)),
        #         transform=self.ax.transAxes, color='k')

        self.ax.view_init(elev=el, azim=az)  # Reproduce view
        self.ax.dist = dist

    def save_video(self):
        FFMpegWriter = manimation.writers['ffmpeg']
        metadata = dict(title='Movie', artist='Matplotlib')
        writer = FFMpegWriter(fps=5, metadata=metadata, bitrate=3000)

        with writer.saving(self.f, "movie.mp4", 100):
            self.curr_pos = 0
            self.update_graphs()
            self.f.canvas.draw()
            plt.draw()
            for i in range(10):
                writer.grab_frame()

            for i in range(self.num_iters):
                self.curr_pos = i
                self.update_graphs()
                self.f.canvas.draw()
                plt.draw()
                writer.grab_frame()

            self.curr_pos = self.num_iters
            self.update_graphs()
            self.f.canvas.draw()
            plt.draw()
            for i in range(20):
                writer.grab_frame()

    def update_graphs(self, e=None):
        if e is not None:
            self.curr_pos = int(e)
            self.curr_pos = self.curr_pos % (self.num_iters + 1)

        self.plot_wing()
        self.plot_sides()
        self.canvas.show()

    def check_length(self):
        db = sqlitedict.SqliteDict(self.db_name, 'iterations')
        n = 0
        for case_name, case_data in db.iteritems():
            n += 1
        self.num_iters = n

    def auto_ref(self):
        """
        Automatically refreshes the history file, which is
        useful if examining a running optimization.
        """
        if self.var_ref.get():
            self.root.after(800, self.auto_ref)
            self.check_length()
            self.update_graphs()

            if self.num_iters > self.old_n:
                self.load_db()
                self.old_n = self.num_iters
                self.draw_slider()

    def save_image(self):
        fname = 'fig' + '.png'
        plt.savefig(fname)

    def quit(self):
        """
        Destroy GUI window cleanly if quit button pressed.
        """
        self.root.quit()
        self.root.destroy()

    def draw_slider(self):
        # scale to choose iteration to view
        self.w = Tk.Scale(self.options_frame,
                          from_=0,
                          to=self.num_iters,
                          orient=Tk.HORIZONTAL,
                          resolution=1,
                          font=tkFont.Font(family="Helvetica", size=10),
                          command=self.update_graphs,
                          length=200)

        if self.curr_pos == self.num_iters - 1 or self.curr_pos == 0:
            self.curr_pos = self.num_iters
        self.w.set(self.curr_pos)
        self.w.grid(row=0, column=1, padx=5, sticky=Tk.W)

    def draw_GUI(self):
        """
        Create the frames and widgets in the bottom section of the canvas.
        """
        font = tkFont.Font(family="Helvetica", size=10)

        lab_font = Tk.Label(self.options_frame,
                            text="Iteration number:",
                            font=font)
        lab_font.grid(row=0, column=0, sticky=Tk.S)

        self.draw_slider()

        if self.show_wing and self.show_tube:
            # checkbox to show deformed mesh
            self.show_def_mesh = Tk.IntVar()
            c1 = Tk.Checkbutton(self.options_frame,
                                text="Show deformed mesh",
                                variable=self.show_def_mesh,
                                command=self.update_graphs,
                                font=font)
            c1.grid(row=0, column=2, padx=5, sticky=Tk.W)

            # checkbox to exaggerate deformed mesh
            self.ex_def = Tk.IntVar()
            self.c2 = Tk.Checkbutton(self.options_frame,
                                     text="Exaggerate deformations",
                                     variable=self.ex_def,
                                     command=self.update_graphs,
                                     font=font)
            self.c2.grid(row=0, column=3, padx=5, sticky=Tk.W)

        # Option to automatically refresh history file
        # especially useful for currently running optimizations
        self.var_ref = Tk.IntVar()
        # self.var_ref.set(1)
        c11 = Tk.Checkbutton(self.options_frame,
                             text="Automatically refresh",
                             variable=self.var_ref,
                             command=self.auto_ref,
                             font=font)
        c11.grid(row=0, column=4, sticky=Tk.W, pady=6)

        button = Tk.Button(self.options_frame,
                           text='Save video',
                           command=self.save_video,
                           font=font)
        button.grid(row=0, column=5, padx=5, sticky=Tk.W)

        button4 = Tk.Button(self.options_frame,
                            text='Save image',
                            command=self.save_image,
                            font=font)
        button4.grid(row=0, column=6, padx=5, sticky=Tk.W)

        button5 = Tk.Button(self.options_frame,
                            text='Quit',
                            command=self.quit,
                            font=font)
        button5.grid(row=0, column=7, padx=5, sticky=Tk.W)

        self.auto_ref()
示例#51
0
class MainPage(tk.Frame):

    CanClose = 0

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Main Page", font=Large_Font)
        label.pack(padx=10, pady=10)

        button1 = ttk.Button(self,
                             text="Open Trend File",
                             command=lambda: self.RetrFileName())
        button1.pack()

        button2 = ttk.Button(self,
                             text="Close Graph",
                             command=lambda: self.CloseGraph())
        button2.pack()

    def RetrFileName(self):
        fname = getname(initialdir="C:/Users/Zibit/Desktop/",
                        filetypes=(("RA CSV File", "*.csv"), ("All Files",
                                                              "*.*")),
                        title="Load a Trend")

        fname = fname.replace("\\", "/")

        data = np.genfromtxt(fname,
                             delimiter=",",
                             dtype=(str, str, "U40", float, float, float),
                             names=["a", "b", "c", "d", "e", "f"])

        x = [datetime.strptime(i, "%H:%M:%S;%f") for i in data["c"]]
        y = data["d"]

        ToDateFmt = mdates.DateFormatter("%M:%S:%f")

        self.f = Figure(figsize=(8, 5), dpi=96)
        self.a = self.f.add_subplot(111)
        self.a.xaxis.set_major_formatter(ToDateFmt)
        self.a.plot(x, y, label="Carriage Current Output")
        plt.setp(self.a.get_xticklabels(), rotation=15)
        '''
        
        plt.xlabel("Time")
        plt.ylabel("Amps")
        plt.title("RA Trend Grapher")
        plt.legend()
        
        '''

        self.canvas = FigureCanvasTkAgg(self.f, self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM,
                                         fill=tk.BOTH,
                                         expand=True)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        self.toolbar.update()

        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        self.CanClose = 1

    def CloseGraph(self):
        if self.CanClose == 1:
            self.canvas.get_tk_widget().destroy()
            self.toolbar.destroy()
        else:
            self.CanClose = 0
示例#52
0
class BehaviorLabeler(KeyHandler, Interface, Utils):
    def __init__(self, *args, **kwargs):
        # basic variables
        self.video_path = None
        self.trajectory_path = None
        self.__video__ = None
        self.__trajectory__ = None  # 被標記過的位置結果
        self.__obj_name__ = None  # 被標記過的狀態
        self.__results_dict__ = dict()
        self.width = 1280
        self.height = 720
        self.fps = None
        self.resolution = None
        self.total_frame = None
        self.dist_df = None

        self.stop_ind = 1
        self.n_frame = 1
        self.__drew_n_frame__ = None
        self.__frame__ = None
        self.__orig_frame__ = None
        self.__image__ = None
        self.var_n_frame = None
        self.scale_n_frame = None
        self.label_n_frame = None
        self.label_n_frame_right = None
        self.k1 = None
        self.k2 = None
        self.lines = []  # for matplotlib distance plot
        self.vlines = []

        self.init_f_focus_id = None
        self.end_f_focus_id = None

        # UI
        self.parent = tk.Tk()
        if os.name == 'nt':
            self.parent.iconbitmap('icons/title.ico')
        self.parent.title('Burying Beetle Behavior Labeler')
        self.parent.protocol('WM_DELETE_WINDOW', self.on_close)
        self.parent.option_add('*tearOff', False)
        self.set_all_grid_rowconfigure(self.parent, 0, 1)
        self.set_all_grid_columnconfigure(self.parent, 0, 1)
        LOGGER.info('Initial - window')

        style = ttk.Style()
        style.configure("Treeview.Heading", font=('Georgia', 14))
        style.configure("Treeview", font=('Georgia', 12))

        self.create_ui()

        # update
        self.update_display()
        self.update_label()
        self.update_distance()

        # display label ratio relative to whole window
        self.parent.update_idletasks()
        self._r_height = self.__frame__.shape[0] / self.parent.winfo_reqheight(
        )
        self._r_width = self.__frame__.shape[1] / self.parent.winfo_reqwidth()

        # maximize the window
        if os.name == 'nt':
            self.parent.state('zoomed')
        else:
            self.parent.attributes('-zoomed', True)

        self.parent.mainloop()

    # set grid all column configure
    def set_all_grid_columnconfigure(self, widget, *cols):
        for col in cols:
            widget.grid_columnconfigure(col, weight=1)

    # set grid all row comfigure
    def set_all_grid_rowconfigure(self, widget, *rows):
        for row in rows:
            widget.grid_rowconfigure(row, weight=1)

    # 更新 self.dist_df: 計算兩兩 label 之間的距離
    def calc_dist(self):
        obj_name = self.__obj_name__
        traj = self.__trajectory__

        df = pd.DataFrame()
        for k in sorted(obj_name.keys(),
                        key=lambda x: obj_name[x]['display_name']):
            path = traj[k]['path']
            f_ind = traj[k]['n_frame']
            tmp_df = pd.DataFrame({
                'n_frame': f_ind,
                obj_name[k]['display_name']: path
            })
            if df.shape[0] == 0:
                df = tmp_df
            else:
                df = pd.merge(df, tmp_df, how='outer', on='n_frame')

        column_nm = sorted(
            [obj_name[k]['display_name'] for k in obj_name.keys()])
        dist_df = pd.DataFrame()
        for k1, k2 in combinations(column_nm, 2):
            tmp_df = df[["n_frame", k1, k2]].dropna()
            tmp_dist = np.linalg.norm(np.array(tmp_df[k1].tolist()) -
                                      np.array(tmp_df[k2].tolist()),
                                      axis=1)
            tmp_dist_df = pd.DataFrame({
                "n_frame": tmp_df.n_frame,
                "%s - %s" % (k1, k2): tmp_dist
            })
            if dist_df.shape[0] == 0:
                dist_df = tmp_dist_df
            else:
                dist_df = pd.merge(dist_df,
                                   tmp_dist_df,
                                   how='outer',
                                   on='n_frame')

        dist_df.set_index("n_frame", inplace=True)
        dist_df.sort_index(inplace=True)

        self.dist_df = dist_df

    def update_distance(self):

        if self.dist_df is not None:
            if self.__drew_n_frame__ is None or self.__drew_n_frame__ != self.n_frame:
                # self.start_f = 0
                # self.end_f = min(500, max(self.dist_df.index))

                if len(self.lines) != 0:
                    for i in range(self.dist_df.shape[1]):
                        x = self.dist_df.index[:min(self.n_frame +
                                                    N_MAX_PLOT, self.dist_df.
                                                    shape[0] - 1)]
                        y = self.dist_df.iloc[:min(self.n_frame +
                                                   N_MAX_PLOT, self.dist_df.
                                                   shape[0] - 1), i]
                        self.lines[i].set_data(x, y)
                        self.vlines[i].set_xdata(self.n_frame)

                        try:
                            ax = self.canvas.figure.axes[i]
                        except Exception as e:
                            ax = self.canvas.figure.axes[0]
                            LOGGER.exception(e)

                        ax.set_xlim(x.min(), x.max())
                        ax.set_yscale('log')
                        ax.set_yticklabels([])
                        try:
                            ax.set_ylim(0, 1480)
                        except Exception as e:
                            ax.set_ylim(0, 50)
                            LOGGER.exception(e)

                    # ax.set_xlabel("frame index", fontsize='large')
                elif len(self.lines) == 0:
                    for i in range(1, self.dist_df.shape[1] + 1):
                        x = self.dist_df.index[:min(self.n_frame +
                                                    N_MAX_PLOT, self.dist_df.
                                                    shape[0] - 1)]
                        y = self.dist_df.iloc[:min(self.n_frame +
                                                   N_MAX_PLOT, self.dist_df.
                                                   shape[0] - 1), i - 1]

                        ax = self.fig.add_subplot(self.dist_df.shape[1], 1, i)
                        X, = ax.plot(x,
                                     y,
                                     color='#008000',
                                     label=self.dist_df.columns[i - 1],
                                     lw=1.5)
                        ax.set_xlim(x.min(), x.max())
                        ax.set_yscale('log')
                        ax.set_yticklabels([])
                        try:
                            ax.set_ylim(0, 1480)
                        except Exception as e:
                            if self.dist_df.columns[i - 1] == "A - x":
                                LOGGER.exception(e)
                            ax.set_ylim(0, 0)
                        # ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())

                        # ax = self.fig.add_subplot(1, 1, 1)
                        # X, = ax.plot(x, y, label=self.dist_df.columns[i-1])

                        vX = ax.axvline(x=self.n_frame,
                                        linestyle="--",
                                        lw='2',
                                        color='r')
                        hY = ax.axhline(y=30,
                                        linestyle="--",
                                        lw='1.25',
                                        color='black')
                        ax.legend(loc="upper right",
                                  bbox_to_anchor=(1.05, 1),
                                  fontsize='x-small')
                        if i < self.dist_df.shape[1]:
                            plt.setp(ax.get_xticklabels(), visible=False)
                        self.lines.append(X)
                        self.vlines.append(vX)
                self.fig.tight_layout()
                self.fig.subplots_adjust(right=0.95)
                self.canvas.draw()
                self.__drew_n_frame__ = self.n_frame
        self.parent.after(10, self.update_distance)

    def update_display(self):
        if self.video_path is not None:
            self.update_frame()
        try:
            self.draw()
            self.disply_l.update()
            resize_w, resize_h = self.parent.winfo_width(
            ) // 2, self.parent.winfo_height() // 2
            image = Image.fromarray(self.__frame__).resize(
                (resize_w, resize_h), Image.ANTIALIAS)
            self.__image__ = ImageTk.PhotoImage(image)
            self.disply_l.configure(image=self.__image__)
        except Exception as e:
            LOGGER.exception(e)

        self.disply_l.after(20, self.update_display)

    def update_frame(self):
        self.__video__.set(cv2.CAP_PROP_POS_FRAMES, self.n_frame - 1)
        ok, self.__frame__ = self.__video__.read()
        self.__orig_frame__ = self.__frame__.copy()

    def update_label(self):
        if self.video_path is not None:
            try:
                self.var_n_frame.set(self.n_frame)
                self.scale_n_frame.set(self.n_frame)
                self.label_n_frame.config(text='%s/%s' %
                                          (self.n_frame, self.total_frame))

                text_video_name = self.video_path.split('/')[-1]
                sec = round(self.n_frame / self.fps, 2)
                m, s = divmod(sec, 60)
                h, m = divmod(m, 60)
                text_time = "%d:%02d:%02d" % (h, m, s)

                self.label_video_name.configure(text=text_video_name)
                self.label_time.configure(text=text_time)
            except Exception as e:
                LOGGER.exception(e)

        self.disply_l.after(10, self.update_label)

    def get_focus_entry(self, event=None):
        if self.init_f_focus_id is None:
            self.init_f_focus_id = self.init_f.focus_get()

    def get_focus_entry2(self, event=None):
        if self.end_f_focus_id is None:
            self.end_f_focus_id = self.end_f.focus_get()

    def init_video(self):
        self.__video__ = cv2.VideoCapture(self.video_path)
        self.width = int(self.__video__.get(3))
        self.height = int(self.__video__.get(4))
        self.fps = int(self.__video__.get(5))
        self.resolution = (self.width, self.height)
        self.total_frame = int(self.__video__.get(cv2.CAP_PROP_FRAME_COUNT))
        self.__drew_n_frame = None
        # self.lines, self.vlines = [], []

    def create_menu(self):
        menu = tk.Menu(self.parent)
        self.parent.config(menu=menu)

        file = tk.Menu(menu)
        file.add_command(label='載入新影像', command=self.on_load)
        file.add_command(label='儲存操作', command=self.on_save)
        menu.add_cascade(label='File', menu=file)
        LOGGER.info('Initial - menu')

    def create_op(self):
        # display frame > operation frame > input frame
        input_frame = tk.Frame(self.op_frame)
        input_frame.grid(row=0, column=0)
        self.set_all_grid_rowconfigure(input_frame, 0)
        self.set_all_grid_columnconfigure(input_frame, 0)

        tk.Label(input_frame, text='起始幀數:',
                 font=("Georgia", 14)).grid(row=0,
                                            column=0,
                                            padx=10,
                                            sticky='w')
        tk.Label(input_frame, text='結束幀數:',
                 font=("Georgia", 14)).grid(row=0,
                                            column=2,
                                            padx=10,
                                            sticky='w')
        tk.Label(input_frame, text='Object 1:',
                 font=("Georgia", 14)).grid(row=0,
                                            column=4,
                                            padx=10,
                                            sticky='w')
        tk.Label(input_frame, text='行為:',
                 font=("Georgia", 14)).grid(row=0,
                                            column=6,
                                            padx=10,
                                            sticky='w')
        tk.Label(input_frame, text='Object 2:',
                 font=("Georgia", 14)).grid(row=0,
                                            column=8,
                                            padx=10,
                                            sticky='w')

        self.init_f = ttk.Entry(input_frame, width=8)
        self.init_f.insert(0, 0)
        self.init_f.grid(row=0, column=1, padx=10, sticky='w')

        self.end_f = ttk.Entry(input_frame, width=8)
        self.end_f.insert(0, 0)
        self.end_f.grid(row=0, column=3, padx=10, sticky='w')

        name = sorted(["x", "A", "o", "="])
        self.obj_a = ttk.Combobox(input_frame,
                                  values=name,
                                  width=5,
                                  state="readonly")
        self.obj_a.current(0)
        self.obj_a.grid(row=0, column=5, padx=10, sticky='w')

        bev = ['Attack', 'Wrestle', 'Chase']
        self.actions = ttk.Combobox(input_frame,
                                    values=bev,
                                    width=5,
                                    state="readonly")
        self.actions.current(0)
        self.actions.grid(row=0, column=7, padx=10, sticky='w')

        self.obj_b = ttk.Combobox(input_frame,
                                  values=name,
                                  width=5,
                                  state="readonly")
        self.obj_b.current(1)
        self.obj_b.grid(row=0, column=9, padx=10, sticky='w')

        # display frame > operation frame > button frame
        buttons = []
        button_frame = tk.Frame(self.op_frame)
        button_frame.grid(row=1, column=0)
        # self.set_all_grid_rowconfigure(button_frame, 0)
        # self.set_all_grid_columnconfigure(button_frame, 0, 1, 2, 3, 4, 5, 6)
        return_img = ImageTk.PhotoImage(file='icons/return.png')
        next_img = ImageTk.PhotoImage(file='icons/next.png')
        next2_img = ImageTk.PhotoImage(file='icons/down.png')
        prev_img = ImageTk.PhotoImage(file='icons/prev.png')
        prev2_img = ImageTk.PhotoImage(file='icons/up.png')
        add_img = ImageTk.PhotoImage(file='icons/add.png')
        delete_img = ImageTk.PhotoImage(file='icons/delete.png')

        b_prev2 = ttk.Button(button_frame,
                             image=prev2_img,
                             command=self.on_prev)
        b_prev2.image = prev2_img
        buttons.append(b_prev2)
        b_prev = ttk.Button(button_frame, image=prev_img, command=self.on_left)
        b_prev.image = prev_img
        buttons.append(b_prev)
        b_return = ttk.Button(button_frame,
                              image=return_img,
                              command=self.on_return)
        b_return.image = return_img
        buttons.append(b_return)
        b_next = ttk.Button(button_frame,
                            image=next_img,
                            command=self.on_right)
        b_next.image = next_img
        buttons.append(b_next)
        b_next2 = ttk.Button(button_frame,
                             image=next2_img,
                             command=self.on_next)
        b_next2.image = next2_img
        buttons.append(b_next2)
        b_add = ttk.Button(button_frame, image=add_img, command=self.on_add)
        b_add.image = add_img
        buttons.append(b_add)
        b_delete = ttk.Button(button_frame,
                              image=delete_img,
                              command=self.on_delete)
        b_delete.image = delete_img
        buttons.append(b_delete)
        for i, b in enumerate(buttons):
            b.grid(row=0, column=i, sticky='news', padx=10, pady=10)
            b.config(cursor='hand2')

        vcmd = (self.parent.register(self.validate), '%d', '%i', '%P', '%s',
                '%S', '%v', '%V', '%W')

        # display frame > operation frame > scale frame
        self.var_n_frame = tk.IntVar()
        scale_frame = tk.Frame(self.op_frame)
        scale_frame.grid(row=2, column=0, sticky='news')
        self.set_all_grid_rowconfigure(scale_frame, 0)
        self.set_all_grid_columnconfigure(scale_frame, 0, 1, 2)

        # self.label_n_frame = ttk.Entry(scale_frame, textvariable=self.var_n_frame, width=10, justify='right', vcmd=vcmd, validate='key')
        # self.label_n_frame.bind('<Return>', self.set_n_frame_2)
        # self.label_n_frame = ttk.Label(scale_frame, textvariable=self.var_n_frame)
        self.label_n_frame = ttk.Label(scale_frame,
                                       text='%s/%s' %
                                       (self.n_frame, self.total_frame))
        self.label_n_frame.grid(row=0, column=0, pady=5)
        self.scale_n_frame = ttk.Scale(scale_frame,
                                       from_=1,
                                       to_=self.total_frame,
                                       length=1250,
                                       command=self.set_n_frame)
        self.scale_n_frame.set(self.n_frame)
        self.scale_n_frame.state(['disabled'])
        self.scale_n_frame.grid(row=1, column=0, padx=10)
        LOGGER.info('Initial - operation frame')

    def create_info(self):
        text_video_name = '-----'
        text_time = '--:--:--'

        info_label_frame = ttk.LabelFrame(self.info_frame, text='影像信息')
        info_label_frame.grid(row=0, column=0, columnspan=2, sticky='news')

        label_video_name = ttk.Label(info_label_frame, text='影像檔名: ')
        label_video_name.grid(row=0, column=0, sticky='w')
        self.label_video_name = ttk.Label(info_label_frame,
                                          text=text_video_name)
        self.label_video_name.grid(row=0, column=1, sticky='w')
        label_time = ttk.Label(info_label_frame, text='影像時間: ')
        label_time.grid(row=1, column=0, sticky='w')
        self.label_time = ttk.Label(info_label_frame, text=text_time)
        self.label_time.grid(row=1, column=1, sticky='w')

    def create_potential_treeview(self):
        self.pot_tv = ttk.Treeview(self.info_frame, height=3)
        self.pot_tv['columns'] = ('sf', 'ef')
        self.pot_tv.heading('#0', text='', anchor='center')
        self.pot_tv.column('#0', anchor='w', width=0)
        self.pot_tv.heading('sf', text="start_f")
        self.pot_tv.column('sf', anchor='center', width=160)
        self.pot_tv.heading('ef', text='end_f')
        self.pot_tv.column('ef', anchor='center', width=160)
        self.pot_tv.grid(row=1, column=0, sticky='news', pady=10)

        vsb = ttk.Scrollbar(self.info_frame,
                            orient="vertical",
                            command=self.pot_tv.yview)
        vsb.grid(row=1, column=1, sticky='news', pady=10)

        self.pot_tv.configure(yscrollcommand=vsb.set)

    def create_res_treeview(self):
        self.tv = ttk.Treeview(self.info_frame, height=30)
        self.tv['columns'] = ('sf', 'ef', 'obja', 'bev', 'objb')
        self.tv.heading('#0', text='', anchor='center')
        self.tv.column('#0', anchor='w', width=0)
        self.tv.heading('sf', text="start_f")
        self.tv.column('sf', anchor='center', width=70)
        self.tv.heading('ef', text='end_f')
        self.tv.column('ef', anchor='center', width=70)
        self.tv.heading('obja', text='obj_1')
        self.tv.column('obja', anchor='center', width=80)
        self.tv.heading('bev', text='behav')
        self.tv.column('bev', anchor='center', width=80)
        self.tv.heading('objb', text='obj_2')
        self.tv.column('objb', anchor='center', width=80)

        self.tv.grid(row=1, column=0, rowspan=1, sticky='news', pady=10)

        vsb = ttk.Scrollbar(self.info_frame,
                            orient="vertical",
                            command=self.tv.yview)
        vsb.grid(row=1, column=1, rowspan=1, sticky='news', pady=10)

        self.tv.configure(yscrollcommand=vsb.set)
        self.tv.bind('<Double-Button-1>', self.tvitem_click)

    def create_ui(self):

        self.create_menu()

        # display label
        self.__frame__ = np.zeros((int(720 / 2), int(1280 / 2), 3),
                                  dtype='uint8')
        self.__orig_frame__ = self.__frame__.copy()
        self.__image__ = ImageTk.PhotoImage(Image.fromarray(self.__frame__))

        # display frame
        self.display_frame = tk.Frame(self.parent)
        self.display_frame.grid(row=0, column=0, padx=10, pady=10)
        self.set_all_grid_rowconfigure(self.display_frame, 1, 2)
        self.set_all_grid_columnconfigure(self.display_frame, 0)

        # display frame > canvas
        figsize = (1, 4)
        self.fig = Figure(figsize=figsize)
        self.fig.subplots_adjust(left=0.01, right=0.95, bottom=0, top=0.98)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.display_frame)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0, column=0, sticky='news')

        # display frame > operation frame
        self.op_frame = tk.Frame(self.display_frame)
        self.op_frame.grid(row=1, column=0, sticky='news', padx=10, pady=10)
        self.set_all_grid_rowconfigure(self.op_frame, 0, 1)
        self.set_all_grid_columnconfigure(self.op_frame, 0)
        self.create_op()

        # display frame > display label
        self.disply_l = ttk.Label(self.display_frame, image=self.__image__)
        self.disply_l.grid(row=2, column=0, padx=10, pady=10)

        # info frame
        self.info_frame = tk.Frame(self.parent)
        self.info_frame.grid(row=0,
                             column=1,
                             rowspan=3,
                             sticky='news',
                             pady=10)
        self.set_all_grid_rowconfigure(self.info_frame, 1)
        self.set_all_grid_columnconfigure(self.info_frame, 0, 1)
        self.create_info()

        # display info
        # self.create_potential_treeview()
        # record operation frame
        self.create_res_treeview()

        self.parent.bind('<Escape>', self.on_close)
        self.parent.bind('<Control-Left>',
                         lambda event: self.on_left(event, n=1))
        self.parent.bind('<Control-Right>',
                         lambda event: self.on_right(event, n=1))
        self.parent.bind('<Left>', lambda event: self.on_left(event))
        self.parent.bind('<Right>', lambda event: self.on_right(event))
        self.parent.bind('<Return>', self.on_return)
        self.parent.bind('<Down>', self.on_next)
        self.parent.bind('<Up>', self.on_prev)
        self.parent.bind('<space>', self.on_add)
        self.parent.bind('<Delete>', self.on_delete)
        self.tv.bind('<Control-a>', self.on_select_all)
        self.parent.bind('<d>', self.on_delete)
        self.parent.bind('<j>', self.jump_frame)
        self.init_f.bind('<FocusIn>', self.get_focus_entry)
        self.end_f.bind('<FocusIn>', self.get_focus_entry2)

        # key bind for input
        for k in ['q', 'w', 'e', 'r', 'a', 's', 'd', 'f']:
            self.parent.bind(k.join('<>'), self.on_key)
        for k in ['1', '2', '3']:
            self.parent.bind(k, self.on_key)

        LOGGER.info('Initial - basic UI')
示例#53
0
class Gui(ttk.Frame):

    def __init__(self, master):
        self.amp_started = False

        ttk.Frame.__init__(self, master)
        self.master.title('Mushu')
        self.pack()

        self.available_amps = libmushu.get_available_amps()

        frame = tk.Frame(self)
        frame.pack(fill=tk.BOTH, expand=1)

        self.label1 = ttk.Label(frame, text='Select Amplifier')
        self.label1.grid(column=0, row=0, sticky='we')
        self.amp_combobox = ttk.Combobox(frame, values=[str(i) for i in self.available_amps])
        self.amp_combobox.grid(column=0, row=1, sticky='we')
        self.amp_combobox.bind("<<ComboboxSelected>>", self.on_amplifier_selected)

        self.label2 = ttk.Label(frame, text='Select Configuration Preset')
        self.label2.grid(column=1, row=0, sticky='we')
        self.config_combobox = ttk.Combobox(frame)
        self.config_combobox.grid(column=1, row=1, sticky='we')
        self.config_combobox.bind("<<ComboboxSelected>>", self.onComboboxSelected)

        self.label3 = ttk.Label(frame, text='Start/Stop Amplifier')
        self.label3.grid(column=2, row=0, sticky='we')
        self.start_stop_button = ttk.Button(frame, text='Start', command=self.onStartStopButtonClicked)
        self.start_stop_button.grid(column=2, row=1, sticky='we')

        # set up the figure
        fig = Figure()
        self.canvas = FigureCanvas(fig, master=self.master)
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.canvas.show()
        self.axis = fig.add_subplot(111)

        self.PAST_POINTS = 256
        self.SCALE = 30000

        self.channels = []
        self.n_channels = 0

        self.init_plot()
        self.master.after_idle(self.visualizer)

    def onStartStopButtonClicked(self):
        logger.debug('Start.')
        if self.amp_started:
            logger.debug('Stop.')
            self.amp.stop()
            self.start_stop_button.config(text='Start')
            self.amp_started = False
        else:
            logger.debug('Start.')
            self.amp.start()
            self.start_stop_button.config(text='Stop')
            self.amp_started = True

    def onComboboxSelected(self, event):
        idx = event.widget.current()
        cfg = self.amp.presets[idx][1]
        self.amp.configure(**cfg)

    def init_plot(self):
        self.axis.lines = []
        for i in range(self.n_channels):
            self.axis.plot(0)
        self.canvas.draw()
        if self.n_channels == 0:
            self.data = np.array([]).reshape(-1, 1)
        else:
            self.data = np.array([]).reshape(-1, self.n_channels)
        self.data_buffer = []
        self.t2 = time.time()
        self.k = 0
        self.nsamples = 0

    def on_amplifier_selected(self, event):
        idx = event.widget.current()
        ampstr = self.available_amps[idx]
        amp = libmushu.get_amp(ampstr)
        self.set_amplifier(amp)

    def set_amplifier(self, amp):
        self.config_combobox.configure(values = [txt for txt, _ in amp.presets])
        self.amp = amp
        self.channels = amp.get_channels()
        self.n_channels = len(self.channels)

    def visualizer(self):
        if self.amp_started:
            tmp, marker = self.amp.get_data()
            # display #samples / second
            if tmp is not None:
                self.nsamples += tmp.shape[0]
                self.k += 1
                if self.k == 100:
                    sps = self.nsamples / (time.time() - self.t2)
                    logger.debug('%.2f samples / second\r' % sps)
                    self.t2 = time.time()
                    self.nsamples = 0
                    self.k = 0
            # check if nr of channels has changed since the last probe
            if tmp.shape[1] != self.data.shape[1]:
                logger.debug('Number of channels has changed, re-initializing the plot.')
                self.channels = self.amp.get_channels()
                self.n_channels = len(self.channels)
                self.init_plot()
            # append the new data
            new_data = tmp
            self.data = np.concatenate([self.data, new_data])
            self.data = self.data[-self.PAST_POINTS:]
            # plot the data
            data_clean = self.normalize(self.data)
            dmin = data_clean.min()
            dmax = data_clean.max()
            dr = (dmax - dmin) * 0.7
            SCALE = dr
            ticklocs = []
            x = [i for i in range(len(self.data))]
            for j, line in enumerate(self.axis.lines):
                line.set_xdata(x)
                #line.set_ydata(self.data[:, j] + j * SCALE)
                line.set_ydata(data_clean[:, j] + j * SCALE)
                ticklocs.append(j * SCALE)
            self.axis.set_ylim(-SCALE, self.n_channels * SCALE)
            #self.axis.set_xlim(i - self.PAST_POINTS, i)
            self.axis.set_xlim(len(x)- self.PAST_POINTS, len(x) )
            self.axis.set_yticks(ticklocs)
            self.axis.set_yticklabels(self.channels)
            self.canvas.draw()
            #logger.debug('%.2f FPS' % (1 / (time.time() - t)))
        self.master.after(10, self.visualizer)

    def normalize(self, data):
        return data - np.average(data)
示例#54
0
class SpectrumViewer(object, ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.root = master
        self._ms_file_name = None
        self.reader = None
        self.scan = None
        self.configure_toolbar()
        self.configure_canvas()
        self.configure_treeview()
        self.configure_display_row()
        self.populate()
        self.draw_plot()

    @property
    def ms_file_name(self):
        return self._ms_file_name

    @ms_file_name.setter
    def ms_file_name(self, value):
        if value not in (None, '') and os.path.exists(value):
            print("Loading %r" % value)
            self._ms_file_name = value
            self.reader = ms_deisotope.MSFileLoader(self.ms_file_name)
            self.populate()

    def set_ms_file(self, value, populate=True):
        self._ms_file_name = value
        self.reader = ms_deisotope.MSFileLoader(self.ms_file_name)
        if populate:
            self.populate()

    def select_ms_file(self):
        file_name = tkfiledialog.askopenfilename()
        if file_name is not None and file_name != '':
            self.ms_file_name = file_name

    def do_layout(self):
        self.grid(sticky=tk.N + tk.W + tk.E + tk.S)
        tk.Grid.rowconfigure(self, 0, weight=1)
        tk.Grid.columnconfigure(self, 0, weight=1)

    def configure_canvas(self):
        self.figure = Figure(dpi=100)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self)
        self.axis = self.figure.add_subplot(111)
        self.canvas.show()
        canvas_widget = self.canvas.get_tk_widget()
        canvas_widget.grid(row=0, column=0, sticky=tk.N + tk.W + tk.E + tk.S)
        self.canvas_cursor = Cursor(self.axis, tk.StringVar(master=self.root))
        self.canvas.mpl_connect('motion_notify_event',
                                self.canvas_cursor.mouse_move)
        self.span = SpanSelector(self.axis,
                                 self.zoom,
                                 'horizontal',
                                 useblit=True,
                                 rectprops=dict(alpha=0.5, facecolor='red'))
        self.mz_span = None
        self.scan = None
        self.annotations = []
        self.canvas.show()

    def configure_toolbar(self):
        self.toolbar = tk.Menu(self)
        self.toolbar.add_command(label='Open', command=self.select_ms_file)
        self.toolbar.add_command(
            label='Interact',
            command=lambda: interactive_console(**{'self': self}))
        self.root.config(menu=self.toolbar)

    def _zoom_in(self, min_mz, max_mz):
        arrays = self.scan.arrays
        subset = arrays.between_mz(min_mz, max_mz).intensity
        if len(subset) > 0 and subset.max() > 0 and subset.min() < subset.max(
        ):
            most_intense = np.max(subset)
            y_cap = most_intense * 1.2
            self.mz_span = (min_mz, max_mz)
            self.axis.set_xlim(min_mz, max_mz)
            self.axis.set_ylim(0, y_cap)
            self.annotate_plot(min_mz, max_mz)
            self.figure.canvas.draw()

    def zoom(self, xmin, xmax):
        # If the bounds are not close, we're zooming in
        if not self.scan:
            return
        arrays = self.scan.arrays
        if (xmax - xmin) <= 1:
            min_peak = 0
            max_peak = len(arrays[0]) - 1
            self.mz_span = None
            xmin, xmax = arrays.mz[min_peak], arrays.mz[max_peak]
        self._zoom_in(xmin, xmax)

    def clear_annotations(self):
        for anno in self.annotations:
            try:
                anno.remove()
            except ValueError:
                break
        self.annotations = []

    def annotate_plot(self, min_mz=None, max_mz=None):
        self.clear_annotations()
        if min_mz is None:
            min_mz = 0
        if max_mz is None:
            max_mz = self.scan.arrays.mz[-1]
        subset = self.scan.deconvoluted_peak_set.between(min_mz,
                                                         max_mz,
                                                         use_mz=True)
        if not subset:
            return
        threshold = 0.0
        threshold_list = ([
            max(i.intensity for i in p.envelope) for p in subset
        ])
        if threshold_list:
            threshold = np.mean(threshold_list)
        threshold_list = ([
            max(i.intensity for i in p.envelope) for p in subset
            if max(i.intensity for i in p.envelope) > threshold
        ])
        if threshold_list:
            threshold = np.mean(threshold_list)
        for peak in subset:
            if peak.intensity > threshold:
                label = '%0.2f (%d)' % (peak.neutral_mass, peak.charge)
                pt = max(peak.envelope, key=lambda x: x.intensity)
                y = pt.intensity * 1.05
                x = np.average([p.mz for p in peak.envelope],
                               weights=[p.intensity for p in peak.envelope])
                self.annotations.append(
                    self.axis.text(x,
                                   y,
                                   label,
                                   ha='center',
                                   clip_on=True,
                                   fontsize=10))

    def _process_scan(self):
        self.scan.pick_peaks(signal_to_noise_threshold=1.5)
        if self.scan.ms_level == 1:
            averagine_value = self.ms1_averagine_combobox.get()
            averagine_value = averagine_label_map[averagine_value]
            truncate_after = 0.95
            scorer = ms_deisotope.PenalizedMSDeconVFitter(20., 2.)
        else:
            averagine_value = self.msn_averagine_combobox.get()
            averagine_value = averagine_label_map[averagine_value]
            truncate_after = 0.8
            scorer = ms_deisotope.MSDeconVFitter(10.)
        self.scan.deconvolute(averagine=averagine_value,
                              scorer=scorer,
                              truncate_after=truncate_after)

    def draw_plot(self, scan=None, children=None):
        if children is None:
            children = []
        if scan is None or scan.arrays.mz.shape[0] == 0:
            return
        self.axis.clear()
        self.scan = scan
        self.children_scans = children
        if scan.ms_level == 1:
            if scan.arrays.mz.shape[0] > 1:
                self.scan = scan.average(3)
            self.scan = scan.denoise(4)
        self._process_scan()
        scan = self.scan
        if scan.is_profile:
            draw_raw(*scan.arrays, ax=self.axis, color='black', lw=0.75)
        self.axis.set_xlim(0, max(self.axis.get_xlim()))
        draw_peaklist(
            [i for p in scan.deconvoluted_peak_set for i in p.envelope],
            ax=self.axis,
            alpha=0.6,
            lw=0.5,
            color='orange')
        draw_peaklist([
            p.envelope[0]
            for p in scan.deconvoluted_peak_set if p.envelope[0].intensity > 0
        ],
                      ax=self.axis,
                      alpha=0.6,
                      lw=1,
                      color='red')
        draw_peaklist([
            EnvelopePair(p.mz, p.intensity / len(self.envelope))
            for p in scan.deconvoluted_peak_set
            if not (p.envelope[0].intensity > 0)
        ],
                      ax=self.axis,
                      alpha=0.6,
                      lw=0.5,
                      color='red',
                      linestyle='--')
        # draw isolation window and instrument reported precursor
        if children:
            ylim = scan.arrays.intensity.max()
            for child in children:
                if child.isolation_window and not child.isolation_window.is_empty(
                ):
                    self.axis.vlines([
                        child.isolation_window.lower_bound,
                        child.isolation_window.upper_bound
                    ],
                                     0,
                                     ylim,
                                     linestyle='--',
                                     color='skyblue',
                                     lw=0.5)
                self.axis.vlines(child.precursor_information.mz,
                                 0,
                                 ylim,
                                 linestyle='--',
                                 color='black',
                                 lw=0.5)
        if self.scan.precursor_information:
            ylim = scan.arrays.intensity.max()
            self.axis.vlines(self.scan.precursor_information.mz,
                             0,
                             ylim,
                             linestyle='-.',
                             color='orange')
        if self.mz_span is not None:
            self._zoom_in(*self.mz_span)
        else:
            self.annotate_plot(None, None)
        self.canvas.draw()

    def on_row_click(self, event):
        selection = self.treeview.focus()
        item = self.treeview.item(selection)
        index = item['text']

        if self.reader is not None:
            scan = self.reader.get_scan_by_index(index)
            if scan.ms_level == 1:
                bunch = next(self.reader.start_from_scan(scan.id))
                if not isinstance(bunch, ScanBunch):
                    children = []
                else:
                    children = bunch.products
            else:
                children = []
            self.draw_plot(scan, children)
        else:
            self.draw_plot(None)

    def configure_display_row(self):
        self.display_row = ttk.Frame(self)
        self.display_row.grid(row=1, column=0, sticky=tk.W + tk.S + tk.E)
        self.cursor_label = ttk.Label(self.display_row, text=" " * 20)
        self.cursor_label.grid(row=0, padx=(10, 10))

        def update_label(*args, **kwargs):
            self.cursor_label['text'] = self.canvas_cursor.binding.get()

        self.canvas_cursor.binding.trace('w', update_label)

        self.ms1_averagine_combobox = ttk.Combobox(self.display_row,
                                                   values=[
                                                       "peptide",
                                                       "glycan",
                                                       "glycopeptide",
                                                       "heparan sulfate",
                                                   ])
        self.ms1_averagine_combobox.set("glycopeptide")
        self.ms1_averagine_combobox_label = ttk.Label(self.display_row,
                                                      text="MS1 Averagine:")
        self.ms1_averagine_combobox_label.grid(row=0, column=1, padx=(10, 0))
        self.ms1_averagine_combobox.grid(row=0, column=2, padx=(1, 10))

        self.msn_averagine_combobox = ttk.Combobox(self.display_row,
                                                   values=[
                                                       "peptide",
                                                       "glycan",
                                                       "glycopeptide",
                                                       "heparan sulfate",
                                                   ])
        self.msn_averagine_combobox.set("peptide")
        self.msn_averagine_combobox_label = ttk.Label(self.display_row,
                                                      text="MSn Averagine:")
        self.msn_averagine_combobox_label.grid(row=0, column=3, padx=(10, 0))
        self.msn_averagine_combobox.grid(row=0, column=4, padx=(1, 10))

    def configure_treeview(self):
        self.treeview = ttk.Treeview(self)
        self.treeview['columns'] = [
            "id", "time", 'ms_level', 'precursor_mz', 'precursor_charge',
            'activation'
        ]
        self.treeview.grid(row=2, column=0, sticky=tk.S + tk.W + tk.E + tk.N)

        self.treeview_scrollbar = ttk.Scrollbar(self,
                                                orient="vertical",
                                                command=self.treeview.yview)
        self.treeview_scrollbar.grid(row=2,
                                     column=0,
                                     sticky=tk.S + tk.E + tk.N)
        self.treeview.configure(yscrollcommand=self.treeview_scrollbar.set)

        self.treeview.heading('id', text="Scan ID")
        self.treeview.heading('#0', text='Index')
        self.treeview.heading("time", text='Time (min)')
        self.treeview.heading("ms_level", text='MS Level')
        self.treeview.heading("precursor_mz", text='Precursor M/Z')
        self.treeview.heading("precursor_charge", text='Precursor Z')
        self.treeview.heading("activation", text='Activation')
        self.treeview.column("#0", width=75)
        self.treeview.column("ms_level", width=75)
        self.treeview.column("time", width=75)
        self.treeview.column("precursor_mz", width=100)
        self.treeview.column("precursor_charge", width=100)
        self.treeview.bind("<<TreeviewSelect>>", self.on_row_click)

    def clear_treeview(self):
        children = self.treeview.get_children()
        if children:
            self.treeview.delete(*children)

    def _populate_range(self, start, stop):
        print("populate range", start, stop)
        scans = []
        ended = False
        for i in range(start, stop):
            try:
                scan = self.reader[i]
            except Exception:
                ended = True
                break
            if scan.index % 5000 == 0:
                print(scan)
            i = scan.index
            values = [scan.id, "%0.4f" % scan.scan_time, scan.ms_level]
            if scan.ms_level > 1:
                values.extend([
                    scan.precursor_information.mz,
                    scan.precursor_information.charge,
                    str(scan.activation)
                ])
            else:
                values.extend(['-', '-', '-'])
            scans.append(values)
        for values in scans:
            self.treeview.insert('', 'end', values=values, text=i)
        if not ended:
            self.after(100, self._populate_range, stop, stop + 500)

    def populate(self, clear=True):
        if clear:
            self.clear_treeview()
        if self.reader is not None:
            self.reader.make_iterator(grouped=False)
            for scan in self.reader:
                if scan.index % 5000 == 0:
                    print(scan)
                i = scan.index
                values = [scan.id, "%0.4f" % scan.scan_time, scan.ms_level]
                if scan.ms_level > 1:
                    values.extend([
                        scan.precursor_information.mz,
                        scan.precursor_information.charge,
                        str(scan.activation)
                    ])
                else:
                    values.extend(['-', '-', '-'])
                self.treeview.insert('', 'end', values=values, text=i)
            self.reader.reset()
示例#55
0
class Application(tk.Frame):
    ABOUT_TEXT = """Instructions for use:

    This software can be used to select a source function
    and deconvolve datasets."""

    DISCLAIMER = "Author: Conor Bacon"

    # Initialise counter
    clickCounter = 0

    # Initialise storage for clicks
    sourceWindow = False

    # Filter frequencies
    fmin = 0.
    fmax = 0.

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        # Initialise variables
        self.name = StringVar()
        self.dataType = IntVar()
        self.freqBand = IntVar()
        self.deconType = IntVar()

        self.dataType.set(1)
        self.freqBand.set(1)
        self.deconType.set(2)

        self.value = IntVar()
        self.clickCounter = IntVar()

        self.freqMin = DoubleVar()
        self.freqMax = DoubleVar()

        self.waterLevel = DoubleVar()
        self.maxBumps = DoubleVar()

        self.createWidgets()

    def createWidgets(self):
        # Create menu
        menubar = Menu(root)
        menubar.add_command(label="Instructions",
                            command=lambda: self.instructions())
        menubar.add_command(label="Exit", command=root.quit)
        root.config(menu=menubar)

        # Create frames and populate with widgets
        # Mainframe
        mainFrame = ttk.Frame(root, padding="3 3 3 3")
        mainFrame.grid(column=0, row=0, sticky=(N, W, E, S))
        mainFrame.columnconfigure(0, weight=1)
        mainFrame.rowconfigure(0, weight=1)

        # Name and processing button frame
        nameFrame = ttk.Frame(mainFrame, padding="12 12 12 12", relief=RAISED)
        nameFrame.grid(column=0,
                       row=0,
                       columnspan=1,
                       rowspan=16,
                       sticky=(N, W, E, S))
        nameFrame.columnconfigure(0, weight=1)
        nameFrame.rowconfigure(0, weight=1)

        # Name entry box
        ttk.Label(nameFrame, text="Name").pack(anchor=W)
        ttk.Entry(nameFrame, textvariable=self.name).pack(anchor=W)

        # Data type radiobuttons
        Radiobutton(master=nameFrame,
                    text="Real data",
                    variable=self.dataType,
                    value=1).pack(anchor=W)
        Radiobutton(master=nameFrame,
                    text="CSEM",
                    variable=self.dataType,
                    value=2).pack(anchor=W)
        Radiobutton(master=nameFrame,
                    text="AxiSEM",
                    variable=self.dataType,
                    value=3).pack(anchor=W)

        ttk.Button(
            master=nameFrame,
            text="Load",
            command=lambda: self.loadData(distCanvas, distAx)).pack(anchor=W)

        # Frequency options and update button
        Radiobutton(master=nameFrame,
                    text="10-30s",
                    variable=self.freqBand,
                    value=1).pack(anchor=W)
        Radiobutton(master=nameFrame,
                    text="10-20s",
                    variable=self.freqBand,
                    value=2).pack(anchor=W)
        Radiobutton(master=nameFrame,
                    text="Custom",
                    variable=self.freqBand,
                    value=3).pack(anchor=W)
        ttk.Label(master=nameFrame, text="Min. Period").pack(anchor=W)
        ttk.Entry(master=nameFrame, textvariable=self.freqMax).pack(anchor=W)
        ttk.Label(master=nameFrame, text="Max. Period").pack(anchor=W)
        ttk.Entry(master=nameFrame, textvariable=self.freqMin).pack(anchor=W)

        ttk.Button(
            master=nameFrame,
            text="Update",
            command=lambda: self.updateFreqBand(distCanvas, distAx)).pack(
                anchor=W)

        # Add some padding to all widgets in this frame
        for child in nameFrame.winfo_children():
            child.pack_configure(padx=5, pady=5)

        # Create frame for deconvolution options
        nameFrame2 = ttk.Frame(mainFrame, padding="12 12 12 12", relief=RAISED)
        nameFrame2.grid(column=1,
                        row=0,
                        columnspan=1,
                        rowspan=16,
                        sticky=(N, W, E, S))
        nameFrame2.columnconfigure(0, weight=1)
        nameFrame2.rowconfigure(0, weight=1)

        ttk.Label(nameFrame2, text="Deconvolution options").pack(anchor=W)

        # Data type radiobuttons
        Radiobutton(master=nameFrame2,
                    text="Iterative",
                    variable=self.deconType,
                    value=2).pack(anchor=W)
        Radiobutton(master=nameFrame2,
                    text="Water level",
                    variable=self.deconType,
                    value=1).pack(anchor=W)

        ttk.Label(master=nameFrame2, text="Water level").pack(anchor=W)
        ttk.Entry(master=nameFrame2,
                  textvariable=self.waterLevel).pack(anchor=W)
        ttk.Label(master=nameFrame2, text="Max. Bumps").pack(anchor=W)
        ttk.Entry(master=nameFrame2, textvariable=self.maxBumps).pack(anchor=W)

        ttk.Button(master=nameFrame2,
                   text="Deconvolve",
                   command=lambda: self.deconvolve()).pack(anchor=W)

        # Add some padding to all widgets in this frame
        for child in nameFrame2.winfo_children():
            child.pack_configure(padx=5, pady=5)

        # Create frame for source plot

        # Create frame for listbox
        listFrame = ttk.Frame(mainFrame, padding="12 12 12 12", relief=RAISED)
        listFrame.grid(column=2,
                       row=0,
                       columnspan=1,
                       rowspan=22,
                       stick=(N, W, E, S))
        listFrame.columnconfigure(0, weight=1)
        listFrame.rowconfigure(0, weight=1)

        scrollBar = Scrollbar(listFrame)
        scrollBar.pack(side=RIGHT, fill=Y)
        self.listBox = Listbox(listFrame, selectmode=SINGLE)
        self.listBox.pack(side=LEFT, fill=Y)
        scrollBar.config(command=self.listBox.yview)
        self.listBox.config(yscrollcommand=scrollBar.set)

        self.listBox.bind('<Double-Button-1>', self.onDouble)

        # Create canvas for distance plot
        #distFig = plt.figure(figsize=(5,9), dpi=100)
        #self.distAx  = distFig.add_axes([0.1, 0.1, 0.8, 0.8])
        #self.distCanvas = FigureCanvasTkAgg(distFig, master=mainFrame)
        #self.distCanvas.get_tk_widget().grid(row=0, column=9, rowspan=22, columnspan=2)
        #self.distCanvas.show()

        # Create canvas for source plot
        sourceFig = plt.figure(figsize=(10, 5), dpi=100)
        self.sourceAx = sourceFig.add_axes([0.1, 0.1, 0.8, 0.8])
        self.sourceCanvas = FigureCanvasTkAgg(sourceFig, master=mainFrame)
        self.sourceCanvas.get_tk_widget().grid(row=0,
                                               column=4,
                                               rowspan=16,
                                               columnspan=8)
        self.sourceCanvas.show()

        root.bind("<Return>", lambda _: self.loadData())

    def loadData(self):
        dataType = self.dataType.get()
        dir = 'Data/' + str(self.name.get())
        if (dataType == 1):
            self.dir = dir + '/RealData/'
        if (dataType == 2):
            self.dir = dir + '/CSEM/'
        if (dataType == 3):
            # Need to move AxiSEM data into directory and create folder
            pass
            #self.dir = dir + '/AxiSEM/'

        dirLength = len(self.dir)

        self.seislist = glob.glob(self.dir + '*PICKLE')

        stationList = []
        for x in range(len(self.seislist)):
            station = self.seislist[x]
            station = station[dirLength:]
            station = station[:(len(station) - 7)]
            stationList.append(station)

        print(stationList)

        self.insertSeisList(stationList)

    def labelUpdate(self):
        self.distance.set(str(round(self.dist, 3)))

    def insertSeisList(self, seislist):
        for item in seislist:
            self.listBox.insert(END, item)

    def updateFreqBand(self, canvas, ax):
        freqBand = self.freqBand.get()
        if (freqBand == 1):
            self.fmin = 0.033
            self.fmax = 0.1
        if (freqBand == 2):
            self.fmin = 0.05
            self.fmax = 0.1
        if (freqBand == 3):
            self.fmin = 1 / self.freqMin.get()
            self.fmax = 1 / self.freqMax.get()

        self.plot(canvas, ax)

    def plot(self, canvas, ax):
        # Clear current plot
        ax.clear()

        # Get current data
        seis = read(self.seislist[int(self.index)], format='PICKLE')

        seis.filter('highpass', freq=self.fmin, corners=2, zerophase=True)
        seis.filter('lowpass', freq=self.fmax, corners=2, zerophase=True)

        self.tshift = seis[0].stats['starttime'] - seis[0].stats['eventtime']

        self.seisT = seis.select(channel='BHT')[0]

        self.seisT.data = np.gradient(self.seisT.data, self.seisT.stats.delta)

        norm = np.max(abs(self.seisT.data))
        self.seisT.data = self.seisT.data / norm

        self.seisT.times = self.seisT.times(
        ) + self.tshift - seis[0].stats.traveltimes['S']

        ax.plot(self.seisT.times, self.seisT.data, 'k', linewidth=2)

        ax.set_title('Distance : %.2f' % (seis[0].stats['dist']), loc='left')

        ax.set_ylim([-1.1, 1.1])
        ax.set_xlim([-50, 100])

        if (self.sourceWindow):
            #canvas.create_rectangle(self.x1, 1, self.x2, -1)
            self.sourceWindow = False

        cid = canvas.mpl_connect('button_press_event', self.__onclick__)

        canvas.draw()

    def deconvolve(self):
        if (self.idx1 == 0):
            print("You need to select a source first")
        else:
            deconvolve_data(self.dataType.get(), self.name.get(), self.value,
                            self.idx1, self.idx2, self.deconType.get())

    def selectSource(self, name, idx1, idx2):

        xArr = self.seisT.times
        array = self.seisT.data

        windowTimes = xArr[idx1:idx2]
        windowData = array[idx1:idx2]

        sourceData = open(self.dir + 'sourceData_' + name + '.txt', 'w')
        sourceData.write("%s \n" % name)
        sourceData.write("%s \n" % idx1)
        sourceData.write("%s \n" % idx2)
        sourceData.close()

        self.sourceWindow = True

        self.updateFreqBand(self.sourceCanvas, self.sourceAx)

    def onDouble(self, event):
        # Note here that Tkinter passes an event object to onselect()
        widget = event.widget
        self.index = int(widget.curselection()[0])
        self.value = widget.get(self.index)
        self.clickCounter = 0

        self.updateFreqBand(self.sourceCanvas, self.sourceAx)

    def __onclick__(self, click):
        print('Click!')
        self.clickCounter += 1
        self.point = (click.xdata, click.ydata)
        xArr = self.seisT.times
        array = self.seisT.data

        # Find the index of the click in the time array
        if (self.clickCounter == 1):
            self.idx1 = (np.abs(xArr - click.xdata)).argmin()
            self.x1 = click.xdata
            print("Click!", self.idx1, self.x1)

        if (self.clickCounter == 2):
            self.idx2 = (np.abs(xArr - click.xdata)).argmin()
            self.x2 = click.xdata
            print("Click!", self.idx2, self.x2)
            # Window the source
            self.selectSource(self.value, self.idx1, self.idx2)

    def instructions(self):
        toplevel = Toplevel()
        label1 = Label(toplevel, text=self.ABOUT_TEXT, height=0, width=100)
        label1.pack(anchor=W)
        label2 = Label(toplevel, text=self.DISCLAIMER, height=0, width=100)
        label2.pack()
示例#56
0
class App(tk.Frame):

    def __init__(self):
        self.root = tk.Tk()
        self.root.wm_title('Robotics Project')

        tk.Frame.__init__(self, master=self.root, takefocus=True)
        self.pack()

        self.get_args()

        # hand_draw canvas
        self.drw_canvas = tk.Canvas(self, width=400, height=400)
        self.drw_canvas.pack(side='right')
        self.drawer = hand_draw.Drawer({}, self.drw_canvas)

        # plot canvas
        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.subplt = self.fig.add_subplot(111)
        self.plt_canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.plt_canvas.show()
        self.plt_canvas.get_tk_widget().pack(side='left', fill=tk.BOTH, expand=1)
        self.plt_canvas._tkcanvas.pack(side='left', fill=tk.BOTH, expand=1)

        # buttons
        self.btn_update = tk.Button(self, text='update')
        self.btn_update.pack(side='bottom')
        self.btn_update.bind('<Button-1>', self.update_ui)

        # labels
        self.lbl_torq3 = tk.Label(self)
        self.lbl_torq3.pack(side='bottom')
        tk.Label(self, text='torque3').pack(side='bottom')

        self.lbl_torq2 = tk.Label(self)
        self.lbl_torq2.pack(side='bottom')
        tk.Label(self, text='torque2').pack(side='bottom')

        self.lbl_torq1 = tk.Label(self)
        self.lbl_torq1.pack(side='bottom')
        tk.Label(self, text='torque1').pack(side='bottom')

        self.lbl_b = tk.Label(self)
        self.lbl_b.pack(side='bottom')
        tk.Label(self, text='b').pack(side='bottom')

        self.lbl_a = tk.Label(self)
        self.lbl_a.pack(side='bottom')
        tk.Label(self, text='a').pack(side='bottom')

        # update once
        self.update_ui(None)

    def update_ui(self, event):
        self.robot = read_file(self.args.input_file)
        self.robot = calc_all(robot=self.robot, step=self.args.step)

        self._update_hand()
        thr.Thread(target=self._update_labels).start()
        thr.Thread(target=self._update_plot).start()

    def _update_plot(self):
        self.fig.clear()
        self.subplt = self.fig.add_subplot(111)

        x, y = self.robot['work_area']
        self.subplt.plot(x, y, 'g.')
        self.plt_canvas.draw()

    def _update_hand(self):
        self.drawer.robot = self.robot
        self.drawer.draw()

    def _update_labels(self):
        self.lbl_torq1['text'] = self.robot['torque'][0, 0]
        self.lbl_torq2['text'] = self.robot['torque'][1, 0]
        self.lbl_torq3['text'] = self.robot['torque'][2, 0]

        self.lbl_a['text'] = self.robot['a']
        self.lbl_b['text'] = self.robot['b']

    def get_args(self):
        parser = argparse.ArgumentParser()

        parser.add_argument('input_file', nargs='?', default=Conf.input_file)
        parser.add_argument('-s', '--step', nargs='?',
                            default=Conf.step, type=int)

        self.args = parser.parse_args()
示例#57
0
class FFModelExplorerList:
    """
    Adapt model interactively.

    Parameters
    ----------
    odf : Instance of OneDFit
        The model to be adapted.
    plotter : Instance of FFModelPlotFit or custom
        Class instance managing the actual plotting.
    """
    def __init__(self, odf, plotter):
        self.f = Figure()

        # Save reference to the model
        self.odf = odf
        # Save reference to the plotter
        self.plotter = plotter

        self.leftMask = None
        self.rightMask = None
        self.activeLine = None

        self.root = tk.Tk()
        self.root.wm_title("PyA Model Explorer")
        # Make the widgets expand/shrink as window size changes
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # Bind the mouse wheel
        if platform.system() == "Linux":
            self.root.bind("<Button-4>", self._mouseWheel)
            self.root.bind("<Button-5>", self._mouseWheel)
        elif platform.system() == "Darwin":
            self.root.bind("<MouseWheel>", self._onWheel)  # for OS X

        # A frame containing the mpl plot
        self.plotFrame = tk.Frame()
        self.plotFrame.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
        self.canvas = FigureCanvasTkAgg(self.f, master=self.plotFrame)

        # A frame containing the box with selected points
        # and control buttons
        self.controlFrame = tk.Frame(self.root)
        self.controlFrame.pack(side=tk.RIGHT, expand=False, fill=tk.BOTH)
        self.selectedPar = tk.StringVar(self.controlFrame)

        # Get parameters of model
        ps = list(self.odf.parameters().keys())
        # Set default modification properties
        # Saves these properties for all parameters
        self.modProps = {}
        for p in ps:
            self.modProps[p] = {
                "modus": "mul",
                "modValMul": 1.02,
                "modValAdd": 0.01
            }

        # Frame containing all parameters
        self.parameterFrame = tk.Frame(self.controlFrame,
                                       height=2,
                                       bd=1,
                                       relief=tk.SUNKEN)

        # Dictionaries holding the specific information for each parameter
        self.singleParameterFrames = {}
        self.singleParameterEntry = {}
        self.singleParameterVar = {}
        # knows whether the parameter is free (value=True) or frozen (=False)
        self.singleParameterFree = {}

        # Closures around the functions adapting thaw/freeze
        def frozenChanged(k):
            def change():
                if self.singleParameterFree[k].get() == True:
                    self.odf.thaw(k)
                else:
                    self.odf.freeze(k)
                self._updateDof()

            return change

        # define what happens when a value is set to the entered parameter (closures)
        def hitReturn(k):
            def change(*args):
                self.selectedPar.set(k)
                self.odf[k] = float(self.singleParameterVar[k].get())
                self._parameterValueChanged()

            return change

        # defines what happens when a parameter's value is changed, but not set yet, i.e., not current (closures)
        def parameterValueChanged(k):
            def valueChanged(*args):
                pp, ll = str(self.singleParameterVar[k].get()).find("."), len(
                    str(self.singleParameterVar[k].get()))
                if round(self.odf[k], ll - pp - 1) != round(
                        self.singleParameterVar[k].get(), ll - pp - 1):
                    self.singleParameterEntry[k].configure(bg="red")
                else:
                    self.singleParameterEntry[k].configure(bg="white")

            return valueChanged

        # Create an entry for each parameter
        # Create a scrollable region
        # Check maximum number of characters for parameter names:
        maxParamLen = 0
        for k in sorted(self.odf.parameters().keys()):
            if len(k) > maxParamLen:
                maxParamLen = len(k)
            # Create an entry for each parameter
        for k in sorted(self.odf.parameters().keys()):
            x = tk.Frame(self.parameterFrame,
                         height=2,
                         bd=2,
                         relief=tk.SUNKEN,
                         pady=2)
            self.singleParameterFrames[k] = x
            y0 = tk.Radiobutton(x,
                                text=k,
                                variable=self.selectedPar,
                                value=k,
                                width=maxParamLen + 1,
                                indicatoron=0)
            y0.pack(side=tk.LEFT)
            #y1 = tk.StringVar()
            y1 = tk.DoubleVar()
            y1.set(self.odf[k])
            y2 = tk.Entry(x, textvariable=y1, width=8)
            y2.bind('<Return>', hitReturn(k))
            self.singleParameterVar[k] = y1
            self.singleParameterVar[k].trace('w', parameterValueChanged(k))
            self.singleParameterEntry[k] = y2
            y2.pack(side=tk.LEFT)
            self.singleParameterFrames[k].pack()
            modModus = tk.StringVar()
            modModus.set(self.modProps[k]["modus"])
            self.singleParameterFree[k] = tk.BooleanVar()
            self.singleParameterFree[k].set(k in self.odf.freeParamNames())
            y3 = tk.Radiobutton(x,
                                text="Thawed",
                                value=True,
                                variable=self.singleParameterFree[k],
                                command=frozenChanged(k))
            y4 = tk.Radiobutton(x,
                                text="Frozen",
                                value=False,
                                variable=self.singleParameterFree[k],
                                command=frozenChanged(k))
            y3.pack(side=tk.RIGHT)
            y4.pack(side=tk.RIGHT)
            self.parameterFrame.pack(fill=tk.X, expand=False)

        # Set of the menu to select the current parameter
        self.selectedPar.set(ps[0])

        # Chi2 frame:
        # , relief=tk.SUNKEN)
        self.chi2Frame = tk.Frame(self.controlFrame, borderwidth=10)
        self.chi2value = tk.DoubleVar()
        self.chi2value.set(self.plotter.chi2)
        self.dofValue = tk.IntVar()
        # self.dofValue.set(len(self.plotter.fitIdx))
        # self.dofValue.set(100)
        self.dofValue.set(
            len(self.plotter.x) - len(self.odf.freeParameters()) - 1)
        self.chi2Label = tk.Label(self.chi2Frame, text="Chi2: ")
        self.dofLabel = tk.Label(self.chi2Frame, text="dof: ")
        self.chi2Entry = tk.Entry(self.chi2Frame,
                                  textvariable=self.chi2value,
                                  bd=2,
                                  width=10)
        self.dofEntry = tk.Entry(self.chi2Frame,
                                 textvariable=self.dofValue,
                                 bd=2,
                                 width=10)
        self.chi2Label.pack(side=tk.LEFT)
        self.chi2Entry.pack(side=tk.LEFT)
        self.dofLabel.pack(side=tk.LEFT)
        self.dofEntry.pack(side=tk.LEFT)
        self.chi2Frame.pack()

        # Frame to bundle mouse-wheel inputs
        self.mouseWheelFrame = tk.Frame(self.controlFrame,
                                        height=2,
                                        bd=3,
                                        relief=tk.SUNKEN)
        self.mwmLabel = tk.Label(self.mouseWheelFrame,
                                 text="Mouse wheel manipulation")
        self.mwmLabel.pack()
        # Modify by multiplication or addition (modModus)
        self.modModus = tk.StringVar()
        self.modModus.set("mul")
        # Entry field and radiobutton to specify factor to be used
        self.factorFrame = tk.Frame(self.mouseWheelFrame)
        self.modEntryTextMul = tk.StringVar()
        self.modEntryFactor = tk.Entry(self.factorFrame,
                                       textvariable=self.modEntryTextMul,
                                       width=6)
        self.modEntryFactor.pack(side=tk.LEFT)
        self.radioMultipli = tk.Radiobutton(self.factorFrame,
                                            text="Multiply",
                                            value="mul",
                                            variable=self.modModus)
        self.radioMultipli.pack(side=tk.LEFT)
        self.factorFrame.pack(fill=tk.BOTH)
        # Entry field and radiobutton to specify step (delta) to be used
        self.addFrame = tk.Frame(self.mouseWheelFrame)
        self.modEntryTextAdd = tk.StringVar()
        self.modEntryAdd = tk.Entry(self.addFrame,
                                    textvariable=self.modEntryTextAdd,
                                    width=6)
        self.modEntryAdd.pack(side=tk.LEFT)
        self.radioAdd = tk.Radiobutton(self.addFrame,
                                       text="Add",
                                       value="add",
                                       variable=self.modModus)
        self.radioAdd.pack(side=tk.LEFT)
        self.addFrame.pack(fill=tk.BOTH)
        # Set text fields for modification factor/step to default
        self.modEntryTextMul.set(
            self.modProps[self.selectedPar.get()]["modValMul"])
        self.modEntryTextAdd.set(
            self.modProps[self.selectedPar.get()]["modValAdd"])
        self.modEntryTextAdd.trace("w", self._modModeChangedAdd)
        self.modEntryTextMul.trace("w", self._modModeChangedMul)
        # Show the frame
        #     self.mouseWheelFrame.grid(row=4, column=0, columnspan=3, pady=10)
        self.mouseWheelFrame.pack()

        # React to change in modify Modus
        self.modModus.trace('w', self._modModusChanged)
        # React to a change in the active parameter
        self.selectedPar.trace("w", self._activeParameterChanged)

        dummyLabel = tk.Label(self.controlFrame)
        dummyLabel.pack()

        # Fit button and fit ranges
        self.fitRangeFrame = tk.Frame(self.controlFrame,
                                      bd=3,
                                      relief=tk.SUNKEN)
        self.fit_lo = tk.DoubleVar()
        self.fit_hi = tk.DoubleVar()
        self.fit_lo.set(min(plotter.x))
        self.fit_hi.set(max(plotter.x))
        self.fitRangeLoLim = tk.Entry(self.fitRangeFrame,
                                      textvariable=self.fit_lo,
                                      width=9,
                                      bd=2)
        self.fitRangeHiLim = tk.Entry(self.fitRangeFrame,
                                      textvariable=self.fit_hi,
                                      width=9,
                                      bd=2)
        self.fitRangeLabel = tk.Label(self.fitRangeFrame, text="Fit range:")
        self.fitButton = tk.Button(self.fitRangeFrame,
                                   text="Fit",
                                   command=self._fitClicked)
        self.fitButton.pack(side=tk.BOTTOM, fill=tk.X)
        self.fitRangeLabel.pack(side=tk.LEFT, fill=tk.X)
        self.fitRangeHiLim.pack(side=tk.RIGHT)
        self.fitRangeLoLim.pack(side=tk.RIGHT)
        self.fitRangeFrame.pack(fill=tk.X)
        #self.fitRangeLoLim.bind('<Return>', self._fitRangeChanged())
        self.fit_lo.trace("w", self._fitRangeChanged)
        self.fit_hi.trace("w", self._fitRangeChanged)
        self.numberClicked = 0
        #self.modModus.trace('w', self._modModusChanged)
        #self.modModus.trace('w', self._modModusChanged)

        dummyLabel = tk.Label(self.controlFrame)
        dummyLabel.pack()

        # , relief=tk.SUNKEN)
        self.showFrame = tk.Frame(self.controlFrame, bd=3)
        self.showFrame.pack(side=tk.TOP)

        self.parSumButton = tk.Button(self.showFrame,
                                      text="Parameter summary",
                                      command=self._parameterSummaryClicked)
        self.parSumButton.pack(side=tk.LEFT)

        self.valSetButton = tk.Button(self.showFrame,
                                      text="Value set code",
                                      command=self._valueSetClicked)
        #     self.valSetButton.grid(row=7, column=2)
        self.valSetButton.pack(side=tk.RIGHT)

        # a tk.DrawingArea
        #     self.canvas.get_tk_widget().grid(column=0, columnspan=7, row=0, rowspan=10)
        self.canvas.get_tk_widget().pack()
        self.cid = self.f.canvas.mpl_connect('button_press_event',
                                             self._mouseButtonClicked)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.plotFrame)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        def _quit():
            # stops main loop
            self.root.quit()
            # this is necessary on Windows to prevent
            # Fatal Python Error: PyEval_RestoreThread: NULL tstate
            self.root.destroy()

        self.quitButton = tk.Button(master=self.controlFrame,
                                    text='Quit',
                                    command=_quit)
        self.quitButton.pack(side=tk.BOTTOM)

        # Plot the model for the first time
        self._parameterValueChanged()

        # Whether or not parameter summary exists
        self.root.parSumWin = None

        if platform.system() == "Darwin":
            self.root.bind("<MouseWheel>", self._onWheel)  # for OS X

    def _parameterActivated(self, *args):
        print(args)

    def _mouseButtonClicked(self, event):
        # print "mouse Button Clicked: ",event
        if event.button != 2:
            return
        # Check whether click occurred on plot axes.
        if event.inaxes is not self.plotter.a:
            # print "not in axis"
            # print event.inaxes, self.plotter.a
            return
        else:
            # print event.xdata, event.ydata
            xrng = self.plotter.a.get_xlim()
            # print
            digits = int(numpy.log10(1. / ((xrng[1] - xrng[0]) / 1000.)) + 2)
            # print digits
            if self.numberClicked == 0:
                self.fit_lo.set(round(event.xdata, digits))
                self.numberClicked = 1
            else:
                self.fit_hi.set(round(event.xdata, digits))
                self.numberClicked = 0
            self.plotter.plot(self.f, self.odf)

            self._fitRangeChanged()

    def _fitRangeChanged(self, *args):
        # print "fitRangeChanged", args
        # print self.fit_lo.get(), self.fit_hi.get()

        if self.leftMask:
            self.plotter.a.collections.remove(self.leftMask)
        if self.rightMask:
            self.plotter.a.collections.remove(self.rightMask)
        if self.activeLine:
            self.activeLine[0].remove()
        try:
            y0, y1 = self.plotter.a.get_ylim()
            y0, y1 = y0 * 10, y1 * 10
            if y0 > 0:
                y0 = 0
            if y1 < 0:
                y1 = 0.
            self.leftMask = self.plotter.a.fill_between(
                [min(self.plotter.x), self.fit_lo.get()], [y0, y0],
                y2=[y1, y1],
                alpha=0.2)
            self.rightMask = self.plotter.a.fill_between(
                [self.fit_hi.get(), max(self.plotter.x)], [y0, y0],
                y2=[y1, y1],
                alpha=0.2)
        except:
            pass
        # self._parameterValueChanged()
        self.plotter.chi2 = self.plotter.get_chi2(
            self.odf, lims=[self.fit_lo.get(),
                            self.fit_hi.get()])
        self._updateChi2()
        self._updateDof()
        # print self.chi2value.get(), self.fit_lo.get(), self.fit_hi.get()
        self.f.canvas.draw()

    def _updateDof(self):
        self.dofValue.set(
            len(self.plotter.fitIdx) - len(self.odf.freeParameters()) - 1)

    def _updateChi2(self):
        try:
            if self.plotter.chi2 > 1e-3 and self.plotter.chi2 < 1e4:
                self.chi2value.set("%8.3f" % self.plotter.chi2)
            else:
                self.chi2value.set("%8.3e" % self.plotter.chi2)
        except:
            self.chi2value.set("N/A")

    def _parameterSummaryClicked(self, *args):
        """
        """
        if self.root.parSumWin is None:
            self.root.parSumWin = ShowParameterSummary(self.root, self.odf)
        self.root.parSumWin.updateInfo(self.odf)

    def _valueSetClicked(self, *args):
        """
        """
        if self.root.parSumWin is None:
            self.root.parSumWin = ValueSetSummary(self.root, self.odf)
        self.root.parSumWin.updateInfo(self.odf)

    def _modModusChanged(self, *args):
        """
        Modus for modification changed (multiply or add)
        """
        self.modProps[self.selectedPar.get()]["modus"] = self.modModus.get()

    def _thawFrozenChange(self, *args):
        """
        Called on click to freeze/thaw radiobuttons
        """
        if self.parIsFree.get() == True:
            self.odf.thaw(self.selectedPar.get())
        else:
            self.odf.freeze(self.selectedPar.get())
        self._updateDof()

    def _setToClicked(self):
        """
        Called when "Set to" button is hit
        """
        x = SetToDialog(self.root, self.odf[self.selectedPar.get()],
                        self.selectedPar.get())
        if x.newVal is not None:
            self.odf[self.selectedPar.get()] = x.newVal
            self._parameterValueChanged()

    def _fitClicked(self):
        """
        """
        self.plotter.fit(self.odf, lims=[self.fit_lo.get(), self.fit_hi.get()])
        self._parameterValueChanged(allFree=True)

    def _modModeChangedAdd(self, *args):
        self.modProps[
            self.selectedPar.get()]["modValAdd"] = self.modEntryTextAdd.get()
        self.modProps[self.selectedPar.get()]["modus"] = "add"
        self.modModus.set("add")

    def _modModeChangedMul(self, *args):
        self.modProps[
            self.selectedPar.get()]["modValMul"] = self.modEntryTextMul.get()
        self.modProps[self.selectedPar.get()]["modus"] = "mul"
        self.modModus.set("mul")

    def _modModeChanged(self, *args):
        """
        Called when mode of modification (add/mul)  is changed
        """
        self.modProps[
            self.selectedPar.get()]["modValAdd"] = self.modEntryTextAdd.get()
        self.modProps[
            self.selectedPar.get()]["modValMul"] = self.modEntryTextMul.get()

    def _activeParameterChanged(self, *args):
        """
        Called when the currently active parameter (not its value) is changed.
        """
        # Set the control panels back to that parameter's settings
        pname = self.selectedPar.get()
        newText = "Value:  % g" % (self.odf[pname])
        self.modModus.set(self.modProps[pname]["modus"])
        # Take care of multiply/add radiobuttons
        tmp = self.modProps[pname]["modus"]
        self.modEntryTextAdd.set(self.modProps[pname]["modValAdd"])
        self.modEntryTextMul.set(self.modProps[pname]["modValMul"])
        self.modModus.set(tmp)
        if self.modModus.get() == "mul":
            self.radioMultipli.select()
        else:
            self.radioAdd.select()
        # print

    def _parameterValueChanged(self, allFree=False):
        """
        Called when the value of the current parameter is changed.
        """
        # Update value in label and plot new model
        if not allFree:
            newText = "% g" % (self.odf[self.selectedPar.get()])
            # self.valLabel.config(text=newText)
            # print self.selectedPar.get()
            # print "selected Par: ",self.selectedPar.get()," value: ",self.odf[self.selectedPar.get()]
            self.singleParameterVar[self.selectedPar.get()].set(newText)
        else:
            for p in self.odf.freeParamNames():
                newText = "% g" % (self.odf[p])
                self.singleParameterVar[p].set(newText)

        self.plotter.plot(self.f, self.odf)
        # print self.plotter.chi2
        self._updateChi2()
        self.f.canvas.draw()

    def _onWheel(self, event):
        val = self.odf[self.selectedPar.get()]
        pname = self.selectedPar.get()
        try:
            if self.modModus.get() == "add":
                mf = float(self.modEntryTextAdd.get())
            elif self.modModus.get() == "mul":
                mf = float(self.modEntryTextMul.get())
        except ValueError:
            tkMessageBox.showwarning(
                "Invalid float", "Cannot convert " + self.modEntry.get() +
                " to float." + " Make it a valid value to proceed.")
            return
        if self.modModus.get() == "mul":
            if event.delta > 0:
                self.odf[pname] = val * mf
            else:
                self.odf[pname] = val / mf
        else:
            self.odf[pname] = val + mf * event.delta / 2.
        self._parameterValueChanged()

    def _mouseWheel(self, event):
        """
        Mouse wheel moved
        """
        # event.num == 4 -> up
        # event.num == 5 -> down
        # print "mouse wheel  ",event
        val = self.odf[self.selectedPar.get()]
        pname = self.selectedPar.get()
        try:
            if self.modModus.get() == "add":
                mf = float(self.modEntryTextAdd.get())
            elif self.modModus.get() == "mul":
                mf = float(self.modEntryTextMul.get())
        except ValueError:
            tkMessageBox.showwarning(
                "Invalid float", "Cannot convert " + self.modEntry.get() +
                " to float." + " Make it a valid value to proceed.")
            return
        if event.num == 4:
            if self.modModus.get() == "mul":
                self.odf[pname] = val * mf
            else:
                self.odf[pname] = val + mf
        elif event.num == 5:
            if self.modModus.get() == "mul":
                self.odf[pname] = val / mf
            else:
                self.odf[pname] = val - mf
        self._parameterValueChanged()

    def show(self):
        """
        Show the GUI.
        """
        try:
            self.canvas.show()
        except AttributeError:
            self.canvas.draw()
        tk.mainloop()
示例#58
0
class PlotterGUI:
    def __init__(self, parent):

        self.parent = parent

        myfont = tkFont.Font(size=14)

        self.frame_function = Tk.Frame(self.parent)
        self.frame_function.pack(fill=Tk.BOTH, expand=1)

        self.label = Tk.Label(self.frame_function, text="f(x) = ", font=myfont)
        self.label.grid(row=0, column=0, sticky=Tk.W)
        self.v = Tk.StringVar()
        self.func = Tk.Entry(self.frame_function,
                             textvariable=self.v,
                             font=myfont)
        self.func.grid(row=0, column=1, sticky=Tk.W)

        self.frame_extrema = Tk.Frame(self.parent)
        self.frame_extrema.pack(fill=Tk.BOTH, expand=1)

        self.xmin_label = Tk.Label(self.frame_extrema,
                                   text="xmin: ",
                                   font=myfont)
        self.xmin_label.grid(row=0, column=0, sticky=Tk.W)
        self.xmin_v = Tk.StringVar()
        self.xmin = Tk.Entry(self.frame_extrema,
                             textvariable=self.xmin_v,
                             font=myfont)
        self.xmin_v.set("0.0")
        self.xmin.grid(row=0, column=1, sticky=Tk.W)

        self.xmax_label = Tk.Label(self.frame_extrema,
                                   text="xmax: ",
                                   font=myfont)
        self.xmax_label.grid(row=0, column=2, sticky=Tk.W)
        self.xmax_v = Tk.StringVar()
        self.xmax = Tk.Entry(self.frame_extrema,
                             textvariable=self.xmax_v,
                             font=myfont)
        self.xmax_v.set("1.0")
        self.xmax.grid(row=0, column=3, sticky=Tk.W)

        # a tk.DrawingArea
        self.f = Figure(figsize=(6, 5), dpi=100)
        self.a = self.f.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.f, master=self.parent)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        #toolbar = NavigationToolbar2TkAgg( canvas, root )
        #toolbar.update()
        #canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.frame_buttons = Tk.Frame(root)
        self.frame_buttons.pack(fill=Tk.BOTH, expand=1)

        self.plot_button = Tk.Button(self.frame_buttons,
                                     text='Plot',
                                     command=self._plot,
                                     font=myfont)
        self.plot_button.pack(side=Tk.BOTTOM)

        self.clear_button = Tk.Button(self.frame_buttons,
                                      text='Clear',
                                      command=self._clear,
                                      font=myfont)
        self.clear_button.pack(side=Tk.BOTTOM)

        self.quit_button = Tk.Button(self.frame_buttons,
                                     text='Quit',
                                     command=self._quit,
                                     font=myfont)
        self.quit_button.pack(side=Tk.BOTTOM)

        self.plot_button.pack(side=Tk.LEFT, padx=5, pady=5)
        self.clear_button.pack(side=Tk.LEFT, padx=5, pady=5)
        self.quit_button.pack(side=Tk.RIGHT)

        self.func.bind('<Return>', self._plot)
        self.xmin.bind('<Return>', self._plot)
        self.xmax.bind('<Return>', self._plot)
        # this allows the use of the enter key to plot the function as well
        # while the cursor is in any one of the three text-entry fields

    def _plot(self, event=None):
        f_str = self.func.get()
        f = str_to_f(f_str)

        xm = float(self.xmin.get())
        xM = float(self.xmax.get())

        xv = np.linspace(xm, xM, 1000)
        fv = f(xv)

        self.a.plot(xv, fv)
        self.a.set_xlim([xm, xM])
        self.canvas.show()

    def _clear(self):
        self.a.clear()
        self.canvas.draw()

    def _quit(self):
        self.parent.quit()  # stops mainloop

        # this is necessary on Windows to prevent Fatal Python Error:
        # PyEval_RestoreThread: NULL tstate
        self.parent.destroy()
示例#59
0
class v_collector(Base_Applet):

    info = {
        # View revision author
        'author': 'KKENNEDY',
        # View version
        'version': '1.0',
        # Revision date of View version
        'date': '2015-02-11',
        # Description
        'description': 'Collector test view',

        # List of compatible Models
        'validModels': ['models.Test.m_test']
    }

    lastTime = 0.0
    data = []
    max_samples = 100
    sample_time = 0.10

    sampling = False

    def run(self):
        self.wm_title("Collector Test")

        # Initialize Data
        # self.time_axis = [x/self.sample_time for x in xrange(0, self.max_samples)]
        self.time_axis = np.arange(0.0, self.max_samples * self.sample_time,
                                   self.sample_time)
        self.data = [0.0] * self.max_samples

        # GUI Elements
        # Figure
        self.fig = matplotlib.figure.Figure(figsize=(5, 4))
        self.subplot_1 = self.fig.add_subplot(111)
        self.dataset_1 = self.subplot_1.plot(self.time_axis, self.data)
        self.subplot_1.grid(True)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=2)

        # Buttons
        self.btnStart = Tk.Button(self, text="Start", command=self.cb_start)
        self.btnStart.grid(row=1, column=0)
        self.btnStop = Tk.Button(self, text="Stop", command=self.cb_stop)
        self.btnStop.grid(row=1, column=1)

        # Update plot
        self.event_update()

    def cb_start(self):
        self.model.startCollector('doCos', self.sample_time, self.max_samples)
        self.sampling = True

    def cb_stop(self):
        self.model.stopCollector('doCos')
        self.sampling = False

    def event_update(self):

        if self.sampling:
            try:
                new_data = self.model.getCollector('doCos', self.lastTime)

                for timestamp, sample in new_data:
                    self.lastTime = timestamp
                    self.data.append(sample)

                if len(self.data) > self.max_samples:
                    self.data = self.data[(-1 * self.max_samples):]

                #self.data = np.sin(2*np.pi*t)

                # Update plot data
                self.dataset_1[0].set_data(self.time_axis, self.data)

                # Autoscale axis
                self.subplot_1.axis([
                    0, self.sample_time * self.max_samples,
                    min(self.data) * 1.10,
                    max(self.data) * 1.10
                ])

                self.canvas.draw()

            except Exception as e:
                print 'exception'

        self.after(250, self.event_update)
示例#60
0
class vw_Plot(vw_Base):
    """
    Plotting Widget using matplotlib.
    """
    def __init__(self, master, **kwargs):
        """
        :param master: Tkinter master element
        :type master: object
        :param sample_interval: Sample interval in seconds
        :type sample_interval: float
        :param sample_depth: Number of samples to display
        :type sample_depth: int
        :param update_interval: Update interval in milliseconds
        :type update_interval: int
        :param start: Enable sampling immediately
        :type start: bool
        :param title: Plot title
        :type title: str
        """
        vw_Base.__init__(self, master, 8, 1)

        # Plot parameters
        self.max_samples = kwargs.get('sample_depth', 100)
        self.sample_time = kwargs.get('sample_interval', 0.1)
        self.update_interval = int(kwargs.get('update_interval', 1.0) * 1000)
        self.sampling = kwargs.get('start', False)
        self.title = kwargs.get('title', 'Generic Plot')

        self.plot_lock = threading.Lock()
        self.sample_thread = None

        self.plots = {}
        self.nextID = 0

        try:
            # Dependent Imports
            #import numpy as np

            import matplotlib
            matplotlib.use('TkAgg')
            from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
            from matplotlib.backend_bases import key_press_handler

            # Initialize Data
            self.time_axis = [
                x / self.sample_time for x in xrange(0, self.max_samples)
            ]
            #self.time_axis = np.arange(0.0, self.max_samples * self.sample_time, self.sample_time)
            self.data = [0.0] * self.max_samples

            #===================================================================
            # GUI Elements
            #===================================================================
            # Figure
            self.fig = matplotlib.figure.Figure(frameon=False,
                                                figsize=(4, 3),
                                                facecolor='w')
            self.subplot_1 = self.fig.add_subplot(1, 1, 1)
            self.subplot_1.grid(True)
            self.fig.suptitle(self.title)
            self.canvas = FigureCanvasTkAgg(self.fig, master=self)
            self.canvas.show()
            self.canvas.get_tk_widget().grid(row=0, column=0)

            #===================================================================
            # Buttons
            #===================================================================
            self.frame_control = Tk.Frame(self)
            # Start/Stop
            self.txt_btnRun = Tk.StringVar()
            self.txt_btnRun.set('Start')
            self.sampling = False
            self.btnRun = Tk.Button(self.frame_control,
                                    textvariable=self.txt_btnRun,
                                    command=self.cb_run)
            self.btnRun.pack()
            # Export
            # TODO
            # Options
            # TODO
            self.frame_control.grid(row=0, column=1)

            # Update plot
            self._schedule_update()

        except ImportError:
            Tk.Label(self, text="Missing Dependencies!").pack()

    def __del__(self):
        self.stopSampling()

    def addPlot(self, name, method):
        """
        Add an object and method to the plot
        
        :param name: Dataset name
        :type name: str
        :param method: Data method
        :type method: str
        """
        with self.plot_lock:
            ret = {}

            ret['method'] = method
            ret['data'] = [0.0] * self.max_samples
            ret['dataset'] = self.subplot_1.plot(self.time_axis, ret['data'])
            ret['samples'] = self.max_samples
            ret['time'] = 0

            self.plots[name] = ret
            self.nextID = self.nextID + 1

    def addCollectorPlot(self, name, obj, method):
        """
        Add an object and method to the plot using a collector
        
        :param name: Dataset name
        :type name: str
        :param obj: Instrument object
        :type obj: object
        :param method: Y-Axis data method name
        :type method: str
        """
        with self.plot_lock:
            ret = {}

            ret['type'] = 'collector'
            ret['object'] = obj
            ret['method'] = method
            ret['dataset'] = self.subplot_1.plot(self.time_axis, self.data)
            ret['data'] = []
            ret['time'] = 0

            self.plots[self.nextID] = ret
            self.nextID = self.nextID + 1

    def removePlot(self, name):
        """
        Remove a data set from the plot
        
        :param name: Dataset name
        :type name: str
        """
        with self.plot_lock:
            plot = self.plots.pop(name)

            if plot.get('type') == 'collector':
                obj = plot.get('object')
                method = plot.get('method')

                obj.stopCollector(method)

    def startSampling(self):
        """
        Start sampling and updating the plot
        """
        for plot_name, plot_attr in self.plots.items():
            if plot_attr.get('type') == 'collector':
                obj = plot_attr.get('object')
                method = plot_attr.get('method')

                obj.startCollector(method, self.sample_time, self.max_samples)

        self.sampling = True

        if self.sample_thread is None:
            self.sample_thread = self.sampleThread(self)
            self.sample_thread.start()

    def stopSampling(self):
        """
        Stop sampling and updating the plot
        """
        self.sampling = False

        for plot_name, plot_attr in self.plots.items():
            if plot_attr.get('type') == 'collector':
                obj = plot_attr.get('object')
                method = plot_attr.get('method')

                obj.stopCollector(method)

        if self.sample_thread is not None:
            self.sample_thread.shutdown()
            self.sample_thread = None

    def cb_run(self):
        if self.sampling == False:
            self.startSampling()
            self.txt_btnRun.set('Stop')

        else:
            self.stopSampling()
            self.txt_btnRun.set('Start')

    def cb_update(self):
        if self.sampling:
            for plot_name, plot_attr in self.plots.items():
                dataset = plot_attr.get('dataset')
                data = plot_attr.get('data')
                last_time = plot_attr.get('time')

                with (self.plot_lock):
                    try:
                        # Update data
                        dataset[0].set_data(self.time_axis, data)

                        # Autoscale axis
                        self.subplot_1.axis([
                            self.time_axis[0], self.time_axis[-1],
                            min(data) * 0.9,
                            max(data) * 1.10
                        ])

                        self.canvas.draw()

                    except Exception as e:
                        self.stopSampling()
                        print e.message

    class sampleThread(threading.Thread):
        def __init__(self, plot_object):
            threading.Thread.__init__(self)

            self.plot_object = plot_object

            self.e_alive = threading.Event()
            self.e_alive.set()

        def run(self):
            while (self.e_alive.is_set()):
                # Iterate through all plots
                for plot_name, plot_attr in self.plot_object.plots.items():
                    dataset = plot_attr.get('dataset')
                    data = plot_attr.get('data')
                    last_time = plot_attr.get('time')
                    samples = plot_attr.get('samples', 100)

                    try:
                        if plot_attr.get('type') == 'collector':
                            obj = plot_attr.get('object')
                            method = plot_attr.get('method')
                            new_data = obj.getCollector(method, last_time)
                        else:
                            method = plot_attr.get('method')
                            new_data = [(time.time(), method())]

                        # Get lock to update all plots
                        with (self.plot_object.plot_lock):
                            for timestamp, sample in new_data:
                                plot_attr['time'] = timestamp
                                data.append(sample)
                                data.pop(0)

                    except Exception as e:
                        pass

                time.sleep(self.plot_object.sample_time)

        def shutdown(self):
            self.e_alive.clear()