Example #1
1
    def build_graph(self):
        """ Update the plot area with loss values and cycle through to
        animate """
        self.ax1.set_xlabel('Iterations')
        self.ax1.set_ylabel('Loss')
        self.ax1.set_ylim(0.00, 0.01)
        self.ax1.set_xlim(0, 1)

        losslbls = [lbl.replace('_', ' ').title() for lbl in self.losskeys]
        for idx, linecol in enumerate(['blue', 'red']):
            self.losslines.extend(self.ax1.plot(0, 0,
                                                color=linecol,
                                                linewidth=1,
                                                label=losslbls[idx]))
        for idx, linecol in enumerate(['navy', 'firebrick']):
            lbl = losslbls[idx]
            lbl = 'Trend{}'.format(lbl[lbl.rfind(' '):])
            self.trndlines.extend(self.ax1.plot(0, 0,
                                                color=linecol,
                                                linewidth=2,
                                                label=lbl))

        self.ax1.legend(loc='upper right')

        plt.subplots_adjust(left=0.075, bottom=0.075, right=0.95, top=0.95,
                            wspace=0.2, hspace=0.2)

        plotcanvas = FigureCanvasTkAgg(self.fig, self.frame)
        plotcanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        ani = animation.FuncAnimation(self.fig, self.animate, interval=2000, blit=False)
        plotcanvas.draw()
Example #2
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 _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.
Example #4
0
    def update_saida(self):

        
        global canvas_latex,canvas_plots,latex_fig,plot_fig
        try:

            if(float(self.in_a2.get())==0):
                self.in_dy0.configure(state="disabled")

            if(float(self.in_a2.get())!=0):
                self.in_dy0.configure(state="normal")

            ##Log de texto setando
            self.saida_log_txt.delete(1.0, END)
            self.saida_log_txt.insert(END,log_print())


            canvas_plots.get_tk_widget().destroy()
            canvas_latex.get_tk_widget().destroy()

            latex_fig.clear()
            plot_fig.clear()

            latex_fig = print_latex()
            plot_fig  = show_plots()


            canvas_plots = FigureCanvasTkAgg(plot_fig,self.frame_plot)
            canvas_latex = FigureCanvasTkAgg(latex_fig,self.frame_latex)
            canvas_latex.get_tk_widget().pack(side = TOP,fill = BOTH, expand = 1)
            canvas_plots.get_tk_widget().pack(side = TOP,fill = BOTH, expand = 1)

        except:
            pass
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))
Example #6
0
class RSSIPlot(object):

    def __init__(self, device_mac):
        self.device_mac = device_mac
        self.receiver_plots = dict()

        self.window = Tk.Toplevel()

        self.figure = Figure()
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.window)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        
        

    def plot_point(self, packet):
        if not packet.receiver_mac in self.receiver_plots:
            i = len(self.receiver_plots) + 1
            ax = self.figure.add_subplot(7, 1, i)
            line, = ax.plot(range(10), range(10), animated=True, lw=2)
            self.receiver_plots[packet.receiver_mac] = (ax, line, [], [])
            self.canvas.draw()

        ax, line, xdata, ydata = self.receiver_plots[packet.receiver_mac]
        xdata.append(packet.timestamp[0])
        ydata.append(packet.rssi)
        line.set_data(xdata, ydata)

        #ax.draw_artist(line)
        self.figure.canvas.blit(ax.bbox)
Example #7
0
class Preview(tk.Frame):
    #def __init__(self, parent, dim, dpi=36, label=None):
    def __init__(self, parent, dim, dpi=36, label=None, col=0, row=0):
        tk.Frame.__init__(self, parent)
        self.dim = dim
        self.bg = np.zeros((int(dim), int(dim)), float)
        ddim = dim/dpi
        self.figure = Figure(figsize=(ddim, ddim), dpi=dpi, frameon=False)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self)
        self.canvas.get_tk_widget().grid(column=0, row=0)#, sticky=(N, W, E, S))
        if label:
            tk.Label(self, text=label).grid(column=0, row=1)
        self._createAxes()
        
    def setWindowTitle(self,title):
        """ Set window title"""
        self.canvas.set_window_title(title)

    def _createAxes(self):
        """ Should be implemented in subclasses. """
        pass
    
    def _update(self):
        """ Should be implemented in subclasses. """
        pass
    
    def clear(self):
        self._update(self.bg)
        
    def updateData(self, Z):
        self.clear()
        self._update(Z)
  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)
    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()
Example #10
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
Example #11
0
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)
Example #12
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()
Example #13
0
    def insert_frame(self, name, parent_frame_name, idx, frame_type=None, **kwargs):
        parent_frame = self.frames[parent_frame_name]
        frame = Frame(parent_frame)

        # add frame to list of frames
        self.frames[name] = frame

        # pre-fill the frame
        if frame_type is None:
            pass
        elif frame_type == 'plot':
            # generate canvas
            dim = kwargs['shape']
            f = Figure(figsize=dim, dpi=113  )
            a = f.add_subplot(111)
            canvas = FigureCanvasTkAgg(f, master=frame)
            
            # Commit the canvas to the gui
            canvas.get_tk_widget().pack()

            # save canvas data for later access
            self.mpl_data[name] = {}
            self.frame_data['plot'] = {'mpl_canvas':canvas}

        # commit the frame to workspace
        frame.grid(row=idx[0], column=idx[1])
Example #14
0
File: read.py Project: zoidy/puq
class PlotFrame:
    def __init__(self, parent):
        self.parent = parent
        # TOP FRAME - CANVAS
        self.f = plt.figure(figsize=(5, 5))
        self.a = self.f.add_subplot(111)
        self.a.grid(True)
        #self.a.set_xlabel(self.description)
        self.a.set_ylabel("Probability")
        self.canvas = FigureCanvasTkAgg(self.f, master=parent)
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)

    def update(self):
        self.canvas.draw()

    def get_plot(self):
        return self.a

    def plot(self, ext):
        from tkFileDialog import asksaveasfilename
        name = 'puq-plot'
        filename = asksaveasfilename(title="Plot to file...",
                                     initialfile=name,
                                     defaultextension='.%s' % ext,
                                     filetypes=[(ext.upper(), '*.%s' % ext)])
        if not filename:
            return
        self.canvas.print_figure(filename)
Example #15
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()
Example #16
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()
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)
Example #18
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()
Example #19
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)
Example #20
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()
 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)
Example #22
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()
def graphic(): 
  appears = varien*boltzmann*6e3
  f = plt.figure(figsize=(20,20))
  gs = plt.GridSpec(3, 2)
  mean1, o1, comp1 = analysis(snowblind, varien, "good", 0, gs)
  mean2, o2, comp2 = analysis(snowblind, appears, "month", 1, gs)
  burn = Tk()
  def another():
    burn.destroy()
  def andother():
    burn.destroy()
    sys.exit()
  burn.protocol('WM_DELETE_WINDOW', andother)
  burn.wm_title("Stadistic")
  canvas = FigureCanvasTkAgg(f, master = burn)
  toolbar = NavigationToolbar2TkAgg(canvas, burn)
  L1 = Label(burn, text="Your Mean is %s %s and your Mean Deviation is %s %s"%(str(mean1), str(comp1), str(o1), str(comp1)))
  L2 = Label(burn, text="Your Mean is %s %s and your Mean Deviation is %s %s"%(str(mean2), str(comp2), str(o2), str(comp2)))
  L3 = Label(burn, text="Your observation started in %s and finished in %s %s (UT) "%(timein, timeout, mirai[0]))
  B1 = Button(burn, text="Quit", bg="red", fg="white" ,command=andother)
  B2 = Button(burn, text="Another File", bg="blue", fg="white", command=another)
  L1.grid(columnspan=2)
  L2.grid(columnspan=2)
  L3.grid(columnspan=2)
  burn.grid_columnconfigure(1, weight=1)
  B1.grid(row=3, sticky=E)
  B2.grid(row=3, column=1, sticky=W)
  burn.grid_columnconfigure(0, weight=1)
  burn.grid_rowconfigure(4, weight=1)
  canvas.get_tk_widget().grid(row=4, columnspan=2, sticky=W)
  toolbar.grid(columnspan=2)
  burn.mainloop()
    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)

        #add a button to navigate to a different page
        button1 = ttk.Button(self, text='Back to Home', 
                            command=lambda: controller.show_frame(StartPage))
        #lambda creates a function on the fly so you can pass parameters
        button1.pack()

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

        

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

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
Example #25
0
    def update_saida(self):

        
        global canvas_latex,canvas_plots,latex_fig,plot_fig
        try:
            ##Log de texto setando
            self.saida_log_txt.delete(1.0, END)
            self.saida_log_txt.insert(END,log_print())


            canvas_plots.get_tk_widget().destroy()
            canvas_latex.get_tk_widget().destroy()

            latex_fig.clear()
            plot_fig.clear()

            latex_fig = print_latex()
            plot_fig  = show_plots()


            canvas_plots = FigureCanvasTkAgg(plot_fig,self.frame_plot)
            canvas_latex = FigureCanvasTkAgg(latex_fig,self.frame_latex)
            canvas_latex.get_tk_widget().pack(side = TOP,fill = BOTH, expand = 1)
            canvas_plots.get_tk_widget().pack(side = TOP,fill = BOTH, expand = 1)

        except:
            pass
Example #26
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.master.title("Grid Manager")

        for r in range(6):
            self.master.rowconfigure(r, weight=1)    
        for c in range(5):
            self.master.columnconfigure(c, weight=1)
            Button(master, text="Button {0}".format(c)).grid(row=6,column=c,sticky=E+W)

        Frame1 = Frame(master, bg="red")
        Frame1.grid(row = 0, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S) 
        Frame2 = Frame(master, bg="blue")
        Frame2.grid(row = 3, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
        Frame3 = Frame(master, bg="green")
        Frame3.grid(row = 0, column = 2, rowspan = 6, columnspan = 3, sticky = W+E+N+S)

        self.fig = plt.figure(figsize=(10,10))
        # ax=fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
        self.gs = GridSpec(3,1)
        ax = self.fig.add_subplot(self.gs[0:2,:])
        # self.im = ax.imshow(-np.random.random([128,128]), origin = 'upper', cmap=plt.cm.RdYlGn, interpolation = 'nearest', vmax=0, vmin=-400000)
        #
        self.canvas = FigureCanvasTkAgg(self.fig, master=Frame3)
        # self.canvas.show()
        # self.canvas.get_tk_widget().grid(side='top', fill='both', expand=1)
        self.canvas.get_tk_widget().grid()
Example #27
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()
Example #28
0
    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()
Example #30
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))	
Example #31
0
class Watchman_data():
    def __init__(self, master):
        # Global variable
        self.master = master
        self.UDP_IP = '192.168.1.10'
        self.UDP_PORT = 8
        self.category_1 = ('CH0', 'CH1', 'CH2', 'CH3', 'CH4', 'CH5', 'CH6',
                           'CH7', 'CH8', 'CH9', 'CH10', 'CH11', 'CH12', 'CH13',
                           'CH14', 'CH15')
        self.y_pos_1 = np.arange(len(self.category_1))
        self.nbr_hit = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.category_2 = ('1', '2', '3', '4', '5')
        self.y_pos_2 = np.arange(len(self.category_2))
        self.amplitude = []
        for i in range(16):
            self.amplitude.append([0, 0, 0, 0, 0])
        self.category_3 = ('1', '2', '3', '4', 'to long')
        self.y_pos_3 = np.arange(len(self.category_3))
        self.time = []
        for i in range(16):
            self.time.append([0, 0, 0, 0, 0])
        self.i = 0
        self.combolist = [
            "CH0", "CH1", "CH2", "CH3", "CH4", "CH5", "CH6", "CH7", "CH8",
            "CH9", "CH10", "CH11", "CH12", "CH13", "CH14", "CH15"
        ]
        self.ch_selected = 0
        self.count = 0
        self.lostcnt = 0
        self.data = []
        self.adress = []
        self.count_recv = 0
        self.init_window()
        self.init_UDP_connection()
        self.open_file()
        self.run_flag = True
        self.lock_graph = Lock()
        self.thread_list = []
        t = Thread(target=self.recv_data, args=())
        t.start()
        print("recv_data thread : ", t, file=sys.stderr)
        self.thread_list.append(t)
        """t=Thread(target=self.plot_int, args=())
        t.start()
        print("plot_int thread : ",t, file=sys.stderr)
        self.thread_list.append(t)"""
        self.master.after(1000, self.plot_int)

    def plot_int(self):
        if (self.run_flag):
            with self.lock_graph:
                start = time.time()
                for k in range(len(self.nbr_hit)):
                    self.graph_hit.patches[k].set_height(self.nbr_hit[k])
                self.spt_hit.set_ylim([0, max(max(self.nbr_hit) * 1.1, 1)])
                for k in range(len(self.amplitude[self.ch_selected])):
                    self.graph_amp.patches[k].set_height(
                        self.amplitude[self.ch_selected][k])
                self.spt_amp.set_ylim(
                    [0, max(max(self.amplitude[self.ch_selected]) * 1.1, 1)])
                self.spt_amp.set_title(self.combolist[self.ch_selected])
                for k in range(len(self.time[self.ch_selected])):
                    self.graph_time.patches[k].set_height(
                        self.time[self.ch_selected][k])
                self.spt_time.set_ylim(
                    [0, max(max(self.time[self.ch_selected]) * 1.1, 1)])
                self.spt_time.set_title(self.combolist[self.ch_selected])
                self.canvas.draw()
                self.canvas.get_tk_widget().update_idletasks()
                end = time.time()

            print("frame received : " + str(self.count) +
                  " | thread engaged : " + str(len(self.thread_list)) +
                  " | time : " + str(end - start))
            length = len(self.thread_list)
            k = 0
            while (k < length):
                if (not self.thread_list[k].is_alive()):
                    del self.thread_list[k]
                    length -= 1
                else:
                    k += 1
            self.master.after(1000, self.plot_int)
        #print("end of thread 10", file=sys.stderr)
        else:
            print("end of plot int.", file=sys.stderr)

    def recv_data(self):
        cnt_timer = 0
        while self.run_flag:
            d = bytearray()
            try:
                d, a = self.sock.recvfrom(4300)
                self.data.append(d)
                self.adress.append(a)
                self.count_recv += 1
                if (self.count_recv >= 100):
                    t = Thread(target=self.data_int,
                               args=(self.data, self.adress))
                    t.start()
                    self.thread_list.append(t)
                    del self.data[:]
                    del self.adress[:]
                    self.count_recv = 0
                cnt_timer = 0
            except socket.timeout:
                time.sleep(0.1)
                cnt_timer += 1
                dummy = 0  # dummy execution just to use try without trouble
            except socket.error:
                dummy = 0
            if ((cnt_timer >= 2) and (self.count_recv > 0)):
                t = Thread(target=self.data_int, args=(self.data, self.adress))
                t.start()
                self.thread_list.append(t)
                del self.data[:]
                del self.adress[:]
                self.count_recv = 0
        if (self.count_recv > 0):
            t = Thread(target=self.data_int, args=(self.data, self.adress))
            t.start()
            self.thread_list.append(t)
            del self.data[:]
            del self.adress[:]
            self.count_recv = 0

    def data_int(self, *args):
        list_data = list(args[0])
        list_adress = list(args[1])
        for r in range(0, len(list_data)):
            data = list_data[r]
            adress = list_adress[r]
            if (adress[0] == self.UDP_IP):
                if (len(data) >= 2):
                    if ((data[0] == int("0x55", 0))
                            and (data[1] == int("0xAA", 0))):
                        length = data[2] * 256 + data[3]
                        if ((length >= 4) and (length <= len(data))):
                            if ((data[length - 2] == int("0x33", 0))
                                    and (data[length - 1] == int("0xCC", 0))):
                                flag = True
                                index = 4
                                i = 0
                                amp = 0
                                time = 0
                                frame_type = 0
                                channel = 0
                                while (i < 16 and flag):
                                    channel = data[index]
                                    index += 1
                                    if (channel < 16):
                                        frame_type = data[index]
                                        index += 1
                                        if (
                                                frame_type == 0
                                        ):  # payload=0, no hit on this channel
                                            dummy = 0
                                        else:
                                            with self.lock_graph:
                                                if (frame_type == 1):
                                                    self.nbr_hit[
                                                        channel] += 1  # Pedestal
                                                    amp = data[
                                                        index] * 256 + data[
                                                            index + 1]
                                                    self.amplitude[channel][
                                                        amp //
                                                        13108] += 1  #65535 / 5 = 13107 -> 13108
                                                    index += 2
                                                    time = data[
                                                        index] * 256 + data[
                                                            index + 1]
                                                    self.time[channel][
                                                        time //
                                                        16384] += 1  #65535 / 4 = 16383.75 -> 16384
                                                    index += 2
                                                else:
                                                    if (frame_type == 2):
                                                        self.nbr_hit[
                                                            channel] += 1  # Full Wave
                                                        self.time[channel][
                                                            4] += 1
                                                        index += 256
                                                    else:
                                                        flag = False
                                                        print(
                                                            "frame type fail -> "
                                                            + str(frame_type),
                                                            file=sys.stderr)
                                    else:
                                        flag = False
                                        print("channel fail -> " +
                                              str(channel),
                                              file=sys.stderr)
                                    i += 1
                                if (flag):
                                    self.file.write(data)
                                    self.count += 1
                                else:
                                    self.lostcnt += 1
                            else:
                                print("end code not found", file=sys.stderr)
                                self.lostcnt += 1
                        else:
                            print("length =" + str(length) + " / len(data)=" +
                                  str(len(data)))
                            self.lostcnt += 1
                    else:
                        print("start code not found", file=sys.stderr)
                        self.lostcnt += 1
        del list_data[:]
        del list_adress[:]

    def init_window(self):
        self.master.title(
            "Watchman - data")  # when use close window with the red cross
        self.master.resizable(width=FALSE, height=FALSE)
        self.master.geometry("1600x800+250+150")
        self.figure = plt.figure()
        self.combo = ttk.Combobox(self.master, values=self.combolist)
        self.combo.bind("<<ComboboxSelected>>", self.combo_callback)
        self.combo.current(0)
        self.combo.pack()
        self.spt_hit = self.figure.add_subplot(122)
        self.graph_hit = self.spt_hit.bar(self.y_pos_1,
                                          self.nbr_hit,
                                          align='center',
                                          alpha=0.5)
        self.spt_hit.set_xticks(self.y_pos_1)
        self.spt_hit.set_xticklabels(self.category_1)
        self.spt_hit.set_ylabel('Hits')
        self.spt_hit.set_title('Hitmap')
        self.spt_amp = self.figure.add_subplot(221)
        self.graph_amp = self.spt_amp.bar(self.y_pos_2,
                                          self.amplitude[0],
                                          align='center',
                                          alpha=0.5)
        self.spt_amp.set_xticks(self.y_pos_2)
        self.spt_amp.set_xticklabels(self.category_2)
        self.spt_amp.set_xlabel('Amplitude [V]')
        self.spt_amp.set_title('CH0')
        self.spt_time = self.figure.add_subplot(223)
        self.graph_time = self.spt_time.bar(self.y_pos_3,
                                            self.time[0],
                                            align='center',
                                            alpha=0.5)
        self.spt_time.set_xticks(self.y_pos_3)
        self.spt_time.set_xticklabels(self.category_3)
        self.spt_time.set_xlabel('Time [ns]')
        self.spt_time.set_title('CH0')
        plt.subplots_adjust(left=0.05,
                            bottom=0.075,
                            right=0.95,
                            top=0.95,
                            wspace=0.1,
                            hspace=0.25)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.master)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

    def combo_callback(self, event):
        self.ch_selected = self.combo.current()

    #Creates the socket
    def init_UDP_connection(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        #self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2097152)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 131072)
        print("sock buz:",
              self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))
        self.sock.bind(('', self.UDP_PORT))
        self.sock.settimeout(0.1)

    def open_file(self):
        self.file = open("data.bin", "wb")

    def exit_prog(self):
        self.run_flag = False
        cnt_thread = len(self.thread_list)
        print("number of thread = " + str(cnt_thread), file=sys.stderr)
        for t in self.thread_list:
            t.join()
            print("STOP : ", t)
        """k=0
        while(cnt_thread > 0):
            if(self.thread_list[k].is_alive()):
                print("Thread alive : ", self.thread_list[k], file=sys.stderr)
                time.sleep(1)
            else:
                print("Join thread : ", self.thread_list[k], file=sys.stderr)
                self.thread_list[k].join()
                print("STOP thread : ", self.thread_list[k], file=sys.stderr)
                del self.thread_list[k]
                cnt_thread -= 1
            k+=1
            if(k >= cnt_thread):
                k=0"""

        self.sock.close()
        self.file.close()
        self.master.destroy()
        print("toplevel destroy", file=sys.stderr)
Example #32
0
class graph:
    def __init__(self, coin, parent, navigation_frame) -> None:
        self.coin = coin
        self.current_period = 'd'
        self.parent = parent
        self.navigation_frame = navigation_frame
        self.fig, self.axes = plt.subplots(figsize=(9, 4))
        self.fig.set_facecolor('#6E6E6E')
        self.axes.plot(self.coin.get_day_data().index,
                       coin.get_day_data()['Close'],
                       color="blue")
        self.axes.set(xlabel="Date", ylabel="Price($)", title=coin.tickers)
        plt.grid(b=True, which='major', axis='both')

        plt.subplots_adjust(left=0.088, right=0.97, top=0.94, bottom=0.083)
        self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
        self.canvas.draw()
        self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)
        self.toolbar = NavigationToolbar2Tk(self.canvas, self.navigation_frame)
        self.toolbar.update()
        self.current_type = 'line'
        self.c_axes = []

    def start_ani(self):
        ani = animation.FuncAnimation(self.fig,
                                      self.update_period,
                                      interval=10000)

    def update_period(self):  # 매게변수로 d,w,y 중 하나를 받는다.
        if self.current_type == 'line':
            self.axes.clear()
            if self.current_period == 'd':
                self.axes.plot(self.coin.get_day_data().index,
                               self.coin.get_day_data()['Close'],
                               color="blue")
            elif self.current_period == 'w':
                self.axes.plot(self.coin.get_weekly_data().index,
                               self.coin.get_weekly_data()['Close'],
                               color="blue")
            elif self.current_period == 'y':
                self.axes.plot(self.coin.get_monthly_data().index,
                               self.coin.get_monthly_data()['Close'],
                               color="blue")

            self.axes.set(xlabel="Date",
                          ylabel="Price($)",
                          title=self.coin.tickers)

            plt.grid(b=True, which='major', axis='both')
            self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
            self.canvas.draw()
            self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)

        elif self.current_type == 'candle':
            self.c_axes.clear()
            gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
            self.c_axes = []
            self.c_axes.append(plt.subplot(gs[0]))
            self.c_axes.append(plt.subplot(gs[1], sharex=self.c_axes[0]))
            self.c_axes[0].get_xaxis().set_visible(False)
            if self.current_period == 'd':
                x = np.arange(len(self.coin.get_day_data().index))
                ohlc = self.coin.get_day_data()[[
                    'Open', 'High', 'Low', 'Close'
                ]].astype(float).values
                dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
                self.c_axes[1].bar(x,
                                   self.coin.get_day_data().Volume,
                                   color='k',
                                   width=0.6,
                                   align='center')
            elif self.current_period == 'w':
                x = np.arange(len(self.coin.get_weekly_data().index))
                ohlc = self.coin.get_weekly_data()[[
                    'Open', 'High', 'Low', 'Close'
                ]].astype(float).values
                dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
                self.c_axes[1].bar(x,
                                   self.coin.get_weekly_data().Volume,
                                   color='k',
                                   width=0.6,
                                   align='center')
            elif self.current_period == 'y':
                x = np.arange(len(self.coin.get_monthly_data().index))
                ohlc = self.coin.get_monthly_data()[[
                    'Open', 'High', 'Low', 'Close'
                ]].astype(float).values
                dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
                self.c_axes[1].bar(x,
                                   self.coin.get_monthly_data().Volume,
                                   color='k',
                                   width=0.6,
                                   align='center')

            candlestick_ohlc(self.c_axes[0],
                             dohlc,
                             width=0.5,
                             colorup='r',
                             colordown='b')

            self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
            self.canvas.draw()
            self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)

    def candle_chart(self):
        self.current_type = 'candle'
        self.c_axes.clear()
        self.fig.set_facecolor('w')
        gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
        self.c_axes = []
        self.c_axes.append(plt.subplot(gs[0]))
        self.c_axes.append(plt.subplot(gs[1], sharex=self.c_axes[0]))
        self.c_axes[0].get_xaxis().set_visible(False)

        if self.current_period == 'd':
            x = np.arange(len(self.coin.get_day_data().index))
            ohlc = self.coin.get_day_data()[['Open', 'High', 'Low',
                                             'Close']].astype(float).values
            dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
            self.c_axes[1].bar(x,
                               self.coin.get_day_data().Volume,
                               color='k',
                               width=0.6,
                               align='center')

        elif self.current_period == 'w':
            x = np.arange(len(self.coin.get_weekly_data().index))
            ohlc = self.coin.get_weekly_data()[[
                'Open', 'High', 'Low', 'Close'
            ]].astype(float).values
            dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
            self.c_axes[1].bar(x,
                               self.coin.get_weekly_data().Volume,
                               color='k',
                               width=0.6,
                               align='center')
        elif self.current_period == 'y':
            x = np.arange(len(self.coin.get_monthly_data().index))
            ohlc = self.coin.get_monthly_data()[[
                'Open', 'High', 'Low', 'Close'
            ]].astype(float).values
            dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
            self.c_axes[1].bar(x,
                               self.coin.get_monthly_data().Volume,
                               color='k',
                               width=0.6,
                               align='center')

        # 봉차트
        candlestick_ohlc(self.c_axes[0],
                         dohlc,
                         width=0.5,
                         colorup='r',
                         colordown='b')

        # 거래량 차트
        # axes[1].bar(x, self.coin.data.Volume, color='k',
        #             width=0.6, align='center')

        # line_axes=self.fig.add_axes(self.coin.data.index,self.coin.data['Close'])
        plt.tight_layout()

        self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
        self.canvas.draw()
        self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)

    def line_chart(self):
        self.current_type = 'line'
        self.axes = plt.axes()
        self.c_axes.clear()
        self.fig.clear()
        self.fig.add_axes(self.axes)
        if self.current_type == 'candle':
            self.current_type = 'line'
            self.axes = plt.axes()
            self.c_axes.clear()
            self.fig.clear()
            self.fig.add_axes(self.axes)

        if self.current_period == 'd':
            self.axes.clear()
            self.axes.plot(self.coin.get_day_data().index,
                           self.coin.get_day_data()['Close'],
                           color="blue")
            self.axes.set(xlabel="Date",
                          ylabel="Price($)",
                          title=self.coin.tickers)
            plt.grid(b=True, which='major', axis='both')

            plt.subplots_adjust(left=0.088, right=0.97, top=0.94, bottom=0.083)
            self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
            self.canvas.draw()
            self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)
        elif self.current_period == 'w':
            self.axes.clear()
            self.axes.plot(self.coin.get_weekly_data().index,
                           self.coin.get_weekly_data()['Close'],
                           color="blue")
            self.axes.set(xlabel="Date",
                          ylabel="Price($)",
                          title=self.coin.tickers)
            plt.subplots_adjust(left=0.088, right=0.97, top=0.94, bottom=0.083)
            plt.grid(b=True, which='major', axis='both')
            self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
            self.canvas.draw()
            self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)
        elif self.current_period == 'y':
            self.axes.plot(self.coin.get_monthly_data().index,
                           self.coin.get_monthly_data()['Close'],
                           color="blue")
            self.axes.set(xlabel="Date",
                          ylabel="Price($)",
                          title=self.coin.tickers)
            plt.subplots_adjust(left=0.088, right=0.97, top=0.94, bottom=0.083)
            plt.grid(b=True, which='major', axis='both')
            self.canvas = FigureCanvasTkAgg(self.fig, self.parent)
            self.canvas.draw()
            self.canvas.get_tk_widget().place(x=0, y=0, width=900, height=570)
Example #33
0
# degeri gösterecek olan alan 
valueLabel = tkinter.Label(titleFrame, bg = themeColor, fg = systemColor, font = 18, text = valueText.get())
valueLabel.pack()

# baslat tusu
StartButton = tkinter.Button(sideFrame, bg = themeColor, fg = systemColor, text = "Start", font = 24, width = 15, height = 3, command = StartCalculation)
StartButton.pack(side = tkinter.TOP)

# Canvas grafikler için
canvas = tkinter.Canvas(rightSideFrame, bg = themeColor, height = 500, width = 800)
canvas.pack()

figure = plt.Figure(figsize=(5,4), dpi=100, facecolor = themeColor)

#rect = figure.patch
#rect.set_facecolor(themeColor)

#ax = figure.add_subplot(111)
line = FigureCanvasTkAgg(figure, canvas)
line.get_tk_widget().pack()
#df = df[['Dates', 'Values']].groupby('Dates').sum()
#df.plot(kind='line', legend=True, ax=ax,color='r',marker='o',fontsize=10)
#ax.set_title('Values')

Start()

tkinter.mainloop()

    
Example #34
0
class Plots():
    def __init__(self, root, trials):
        self.root = root #???Jack
        self.names = trials[0].channels_chosen
        self.namesgiven = trials[0].channel_names
        
        self.plotterwindow(trials, 0)
        
    # Called from plotterwindow    
    def multiplot(self, fig, emgs, lims, strikes, footoff):
        '''
        Plots multiple EMG traces as subplots on a tkinter canvas
        '''
        x_seconds = [float(n)/2000 for n in range(self.emg_range[0], self.emg_range[1])]
        self.limits = lims
        
        for index, emg in enumerate(emgs):
            ax = fig.add_subplot(self.nofplots, 1, index+1)
            y = [n*1e6 for n in emg[self.emg_range[0] : self.emg_range[1]]]

            ax.plot(x_seconds,y,self.colour)
            plt.axis('tight')
            print(str('strikes: '+str(strikes)+' footoff: '+str(footoff)))
            for n in strikes:
                plt.axvline(x=n, color='k', linewidth=2)
            for n in footoff:
                plt.axvline(x=n, color='k', linewidth=2, linestyle='--')
            
            ax.set_ylim(-lims[index], lims[index])
            ax.set_ylabel(str(self.namesgiven[index]) + r' $\mu$V')
            if index == 0:
                ax.set_title('EMG')
            if index == len(emgs)-1:
                ax.set_xlabel('seconds')
        self.canvas.draw()
        
    def leave(self, fig, trialnumber, trials):
        fig.set_size_inches(12, 3*self.nofplots)
        fig.savefig(str('emg-plot-'+str(trialnumber)+'.png'), dpi=250)
        pdf_maker(trialnumber, trials[0].patientname, trials[0].footer)
        root.destroy()
        
    def nextwindow(self, fig, trialnumber):
        fig.set_size_inches(12, 3*self.nofplots)
        fig.savefig(str('emg-plot-'+str(trialnumber)+'.png'), dpi=250)
        self.plotterframe.destroy()
        self.plotterwindow(trials, trialnumber+1)
        print('nextwindow ran')
    
    def plotterwindow(self, trials, trialnumber):
        print('trial number: '+ str(trialnumber))
        self.emg = emg_glommer(trials[trialnumber].allchannels, 
                               trials[trialnumber].channels_chosen, 
                               trials[trialnumber].allemg)
        self.emg_range = [int(n)*20 for n in trials[trialnumber].start_end]
        
        self.axis_entry = []
        self.axes = []
        self.labels = []
        self.emgplot = []  
        
        if trials[trialnumber].side == 'Left':
            self.colour = 'r'
            trials[trialnumber].strikes = [float(n)/100 for n in trials[trialnumber].strikes[0]]
            trials[trialnumber].footoff = [float(n)/100 for n in trials[trialnumber].footoff[0]]
        elif trials[trialnumber].side == 'Right':
            self.colour = 'g'
            trials[trialnumber].strikes = [float(n)/100 for n in trials[trialnumber].strikes[1]]
            trials[trialnumber].footoff = [float(n)/100 for n in trials[trialnumber].footoff[1]]
        else:
            self.colour='k'
        
        #https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_sgskip.html
        self.plotterframe = tk.Frame(root)
        self.plotterframe.grid(row=0, column=0)
        self.nofplots = len(self.names)
        self.limits = [int(n*200) for n in np.ones(self.nofplots)]
        fig = plt.figure(figsize=[8,2*self.nofplots])
        self.canvas = FigureCanvasTkAgg(fig, self.plotterframe)
        
        for index, chan in enumerate(self.names):
            self.labels.append(tk.Label(self.plotterframe, text=str(self.namesgiven[index])+' axis limits:-'))
            self.labels[index].grid(row=2*index, column=0, sticky='SW')
            
            self.axes.append(tk.IntVar())
            self.axes[index].set(200)
            self.axis_entry.append(tk.Entry(self.plotterframe, textvariable=self.axes[index]))
            self.axis_entry[index].grid(row=(2*index)+1, column=0, sticky='N')
          
        self.multiplot(fig, self.emg, self.limits, trials[trialnumber].strikes, trials[trialnumber].footoff)
        
        self.canvas.get_tk_widget().grid(row=0, column=1, rowspan=2*len(self.names))
     
        self.replot = tk.Button(self.plotterframe, 
                                text="Replot", 
                                command=lambda: self.multiplot(fig, 
                                                               self.emg, 
                                                               [n.get() for n in self.axes], 
                                                                trials[trialnumber].strikes, 
                                                                trials[trialnumber].footoff))
        self.replot.grid(row=(2*self.nofplots)+3, column=0)
        
        if trialnumber < len(trials)-1:
            print(trialnumber)
            self.gotonext = tk.Button(self.plotterframe, 
                                      text="Next",
                                      command=lambda: self.nextwindow(fig, trialnumber))  #https://mail.python.org/pipermail/tutor/2005-February/035669.html
            self.gotonext.grid(row=(2*self.nofplots)+3, column=1)        
        else:
            print(str('finish'+str(trialnumber)))
            self.quit = tk.Button(self.plotterframe, 
                              text="Finish",
                              command=lambda: self.leave(fig, trialnumber, trials)) 
            self.quit.grid(row=(2*self.nofplots)+3, column=1)
Example #35
0
class Page3_Graph(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.t0 = time.time()
        self.paused = False

        self.f = Figure(figsize=(5, 5), dpi=90)
        self.p1 = self.f.add_subplot(111)

        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.anim = matplotlib.animation.FuncAnimation(
            self.f,
            lambda frame, page, *other: page.animate(),
            fargs=(self, ),
            interval=50)

        me = self
        backButton = ttk.Button(self,
                                text="BACK",
                                command=lambda: me.go_back(controller))
        backButton.pack(pady=10, padx=10, side=tk.LEFT)

        self.pauseText = tk.StringVar()
        pauseButton = ttk.Button(self,
                                 textvariable=self.pauseText,
                                 command=lambda: me.pause_resume())
        self.pauseText.set("PAUSE")
        pauseButton.pack(pady=10, padx=10, side=tk.LEFT)

    def pause_resume(self):
        self.paused = not self.paused
        if self.paused:
            self.pauseText.set("RESUME")
        else:
            self.pauseText.set("PAUSE")

    def animate(self):
        while isPointAvailable():
            readPoint()
        if self.paused:
            return
        self.draw_plots(getArduinoPoints(vs1), getArduinoPoints(vs2),
                        getArduinoPoints(vsC))

    def draw_plots(self, xy_data_1, xy_data_2, xy_data_C):
        self.p1.clear()
        self.p1.set_xlabel("Time (s)")
        self.p1.set_ylabel("Voltage (V)")
        self.p1.set_ylim([0, 4])
        self.p1.plot(*xy_data_1)
        self.p1.plot(*xy_data_2)
        self.p1.plot(*xy_data_C)
        self.p1.legend(["In 1", "In 2", "CV Out"])

    def go_back(self, controller):
        controller.show_frame(StartPage)
Example #36
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        # change 'figure_width': 1920, 'figure_height': 1080 =(19.2,10.8)
        f = Figure(figsize=(8, 6))
        a = f.add_subplot(111)
        f.subplots_adjust(left=0, bottom=0.005, right=1, top=1)
        a.get_xaxis().set_visible(False)
        a.get_yaxis().set_visible(False)

        # add axes for sliders
        ax_norma = f.add_axes([0.81, 0.1, 0.15, 0.025])
        ax_contr = f.add_axes([0.81, 0.05, 0.15, 0.025])

        hdu_list = fits.open(sky_image)
        hdu_list.info()
        img = hdu_list[0].data

        # interval = MinMaxInterval()
        contrast = image_contrast
        interval = ZScaleInterval(contrast=contrast)
        vmin, vmax = interval.get_limits(img)

        norm = ImageNormalize(vmin=vmin,
                              vmax=vmax,
                              stretch=PowerStretch(power_normalise))

        a.imshow(img, origin='lower', norm=norm,
                 cmap='cividis')  #, vmax=max_saturation)

        # Embedding In Tk
        canvas = FigureCanvasTkAgg(f, self)
        # import code; code.interact(local=dict(globals(), **locals()))
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # Show ToolBar
        toolbar = NavigationToolbar(canvas, self)
        toolbar.update()
        # Activate Zoom
        toolbar.zoom(self)
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        delta_f = 0.1

        # add sliders
        s_norma = Slider(ax_norma,
                         'Normalise',
                         0.1,
                         5.0,
                         valinit=power_normalise,
                         valstep=delta_f)
        s_contr = Slider(ax_contr, 'Contrast', 0.1, 1.0, valinit=contrast)

        def update(val):
            n_norma = s_norma.val
            n_contr = s_contr.val
            # assign new values to contrast and normalise
            interval = ZScaleInterval(contrast=n_contr)
            vmin, vmax = interval.get_limits(img)
            norm = ImageNormalize(vmin=vmin,
                                  vmax=vmax,
                                  stretch=PowerStretch(n_norma))
            a.imshow(img, origin='lower', norm=norm, cmap='cividis')
            # saving data to json file
            SaveJson(n_norma, n_contr)
            canvas.draw_idle()

        s_norma.on_changed(update)
        s_contr.on_changed(update)

        hdu_list.close()
Example #37
0
f = Frame(root, bd=2)
ft = Frame(root, bd=2)
ft.pack()
f.pack()
VarsToPlot = OptionMenu(ft,
                        var,
                        *sorted(set(variablelist)),
                        command=updateplot).grid(column=1, row=0, sticky=W)
Plotlabel = Label(ft, text='Variable to plot:',
                  font=('12' + 'bold')).grid(column=0,
                                             row=0,
                                             pady=10,
                                             sticky=E)

aniplot = FigureCanvasTkAgg(figure, master=f)
aniplot.get_tk_widget().grid(column=0, row=1, padx=10, columnspan=3)

pause = False
pausebutton = Button(f,
                     text=u"\u2016",
                     font=('bold'),
                     bg='RED',
                     command=pauseorplay)
pausebutton.config(height=2, width=5)
pausebutton.grid(column=1, row=3, pady=10)

rewindbutton = Button(f, text=u"\u23EA", font=('bold'), command=rewind)
rewindbutton.config(height=1, width=3)
rewindbutton.grid(column=0, row=3)

ffbutton = rewindbutton = Button(f,
Example #38
0
def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
    return figure_canvas_agg
Example #39
0
    def graficar(self, lg):
        """
        Graficamos la funcion con ayuda de matplotlib
        """

        # Limpiamos la ventana
        for widget in self.graph.winfo_children():
            widget.destroy()

        self.graph.deiconify()

        f = Figure(figsize=(5, 5), dpi=100)
        a = f.add_subplot(111)
        # Valores del eje X que toma el gráfico.
        _x = range(-100, 100)
        # Graficar la funcion
        for ec in lg.ecuaciones:
            a.plot(_x, [lg.f(ec, i) for i in _x], label="f(x)=" + str(ec))
            # graficamos la linea de tendencia np.finfo(float).eps
            #print str(inter.ec) +"+"+ str(np.finfo(float).eps)
            #a.plot(_x, [inter.f(str(inter.ec) +"+"+ str(np.finfo(float).eps), i) for i in _x], label='Tendencia')
            # Graficamos los puntos
        lines = []
        for i in range(1, len(self.dato1)):
            a.scatter(self.dato2[i].get(), self.dato1[i].get(), marker='o')
            p = [(self.dato2[i].get(), self.dato1[i].get()),
                 (self.dato2[i].get(), 0)]
            lines.append(p)
            p = [(self.dato2[i].get(), self.dato1[i].get()),
                 (0, self.dato1[i].get())]
            lines.append(p)

        lc = mc.LineCollection(lines,
                               colors='red',
                               linewidths=1,
                               linestyle='dotted')
        a.add_collection(lc)
        # Colocamos las legendas
        a.legend(loc="upper left")
        # Establecer el color de los ejes.
        a.axhline(0, color="black")
        a.axvline(0, color="black")
        # Limitar los valores de los ejes.
        a.set_xlim(-10, 10)
        a.set_ylim(-50, 50)
        # Etiquetas de los ejes
        a.set_xlabel('X')
        a.set_ylabel('Y')
        a.set_title('Graficacion de funciones')
        a.grid(True)

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

        btnClose = tk.Button(self.graph,
                             text="Cerrar",
                             command=lambda: self.close())
        btnClose.config(font=self.font)
        btnClose.pack(side=tk.BOTTOM, fill=tk.X)

        toolbar = NavigationToolbar2TkAgg(canvas, self.graph)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP)
Example #40
0
def glutamine(self):
    ch_min = [0, 0, 40]
    ch_max = [-20, 30, 70]

    cn_min = [0, 0, 40]
    cn_max = [-45, 40, 10]

    cc1_min = [0, 0, 40]
    cc1_max = [45, -40, 10]

    co_min = [45, -40, 10]
    co_max = [60, -40, -50]

    nh_min = [-45, 40, 10]
    nh_max = [-50, 40, -50]

    cc_min = [0, 0, 40]
    cc_max = [40, -20, 70]

    ccc_min = [40, -20, 70]
    ccc_max = [80, -45, 60]

    ccch1_min = [80, -45, 60]
    ccch1_max = [70, -20, 40]

    ccch2_min = [80, -45, 60]
    ccch2_max = [110, -40, 70]

    cccc_min = [80, -45, 60]
    cccc_max = [125, -70, 100]

    ccccn1_min = [125, -70, 100]
    ccccn1_max = [175, -85, 80]

    ccccnh1_min = [175, -85, 80]
    ccccnh1_max = [145, -130, 40]

    ccccnh2_min = [175, -85, 80]
    ccccnh2_max = [185, -110, 40]

    cccco_min = [125, -70, 100]
    cccco_max = [145, -45, 80]

    cch2_min = [40, -20, 70]
    cch2_max = [50, -50, 100]

    cch3_min = [40, -20, 70]
    cch3_max = [25, 10, 100]

    fig = Figure(figsize=(10, 6), dpi=100, facecolor='black')
    canvas = FigureCanvasTkAgg(fig, self)
    canvas.draw()
    ax = fig.add_subplot(111, projection="3d")
    ax.set_axis_bgcolor("black")

    ch = ax.plot([ch_max[0], ch_min[0]], [ch_max[1], ch_min[1]],
                 [ch_max[2], ch_min[2]],
                 linewidth=5,
                 color=ch_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    cn = ax.plot([cn_max[0], cn_min[0]], [cn_max[1], cn_min[1]],
                 [cn_max[2], cn_min[2]],
                 linewidth=5,
                 color=cn_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    ccl = ax.plot([cc1_max[0], cc1_min[0]], [cc1_max[1], cc1_min[1]],
                  [cc1_max[2], cc1_min[2]],
                  linewidth=5,
                  color=cc_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    co = ax.plot([co_max[0], co_min[0]], [co_max[1], co_min[1]],
                 [co_max[2], co_min[2]],
                 linewidth=5,
                 color=co_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    nh = ax.plot([nh_max[0], nh_min[0]], [nh_max[1], nh_min[1]],
                 [nh_max[2], nh_min[2]],
                 linewidth=5,
                 color=nh_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    cc = ax.plot([cc_max[0], cc_min[0]], [cc_max[1], cc_min[1]],
                 [cc_max[2], cc_min[2]],
                 linewidth=5,
                 color=cc_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)

    cch2 = ax.plot([cch2_max[0], cch2_min[0]], [cch2_max[1], cch2_min[1]],
                   [cch2_max[2], cch2_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    cch3 = ax.plot([cch3_max[0], cch3_min[0]], [cch3_max[1], cch3_min[1]],
                   [cch3_max[2], cch3_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)

    ccc = ax.plot([ccc_max[0], ccc_min[0]], [ccc_max[1], ccc_min[1]],
                  [ccc_max[2], ccc_min[2]],
                  linewidth=5,
                  color=cc_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    ccch1 = ax.plot([ccch1_max[0], ccch1_min[0]], [ccch1_max[1], ccch1_min[1]],
                    [ccch1_max[2], ccch1_min[2]],
                    linewidth=5,
                    color=ch_color,
                    marker='o',
                    markerfacecolor='orange',
                    markersize=12)
    ccch2 = ax.plot([ccch2_max[0], ccch2_min[0]], [ccch2_max[1], ccch2_min[1]],
                    [ccch2_max[2], ccch2_min[2]],
                    linewidth=5,
                    color=ch_color,
                    marker='o',
                    markerfacecolor='orange',
                    markersize=12)

    cccc = ax.plot([cccc_max[0], cccc_min[0]], [cccc_max[1], cccc_min[1]],
                   [cccc_max[2], cccc_min[2]],
                   linewidth=5,
                   color=cc_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)

    ccccn1 = ax.plot([ccccn1_max[0], ccccn1_min[0]],
                     [ccccn1_max[1], ccccn1_min[1]],
                     [ccccn1_max[2], ccccn1_min[2]],
                     linewidth=5,
                     color=cn_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    ccccnh1 = ax.plot([ccccnh1_max[0], ccccnh1_min[0]],
                      [ccccnh1_max[1], ccccnh1_min[1]],
                      [ccccnh1_max[2], ccccnh1_min[2]],
                      linewidth=5,
                      color=nh_color,
                      marker='o',
                      markerfacecolor='orange',
                      markersize=12)
    ccccnh2 = ax.plot([ccccnh2_max[0], ccccnh2_min[0]],
                      [ccccnh2_max[1], ccccnh2_min[1]],
                      [ccccnh2_max[2], ccccnh2_min[2]],
                      linewidth=5,
                      color=nh_color,
                      marker='o',
                      markerfacecolor='orange',
                      markersize=12)
    cccco = ax.plot([cccco_max[0], cccco_min[0]], [cccco_max[1], cccco_min[1]],
                    [cccco_max[2], cccco_min[2]],
                    linewidth=5,
                    color=co_color,
                    marker='o',
                    markerfacecolor='orange',
                    markersize=12)
    tch = plt.Rectangle((0, 0), 1, 1, fc=ch_color)
    tch1 = plt.Rectangle((0, 0), 1, 1, fc=ch_color)
    tcn = plt.Rectangle((0, 0), 1, 1, fc=cn_color)
    tcc = plt.Rectangle((0, 0), 1, 1, fc=cc_color)
    tbco = plt.Rectangle((0, 0), 1, 1, fc=co_color)
    tbnh = plt.Rectangle((0, 0), 1, 1, fc=nh_color)

    ax.legend([tch, tcn, tcc, tbco, tbnh], ['ch', 'cn', 'cc', 'co', 'nh'])

    ax.axis("off")
    toolbarFrame = Frame(self)
    toolbarFrame.grid(row=6, column=7)
    toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)
    canvas.get_tk_widget().grid(row=4, column=7)
Example #41
0
class matplotlibSwitchGraphs:
    def __init__(self, master):
        self.master = master
        self.frame = Frame(self.master)
        self.fig, self.ax = config_plot()
        self.graphIndex = 0
        self.canvas = FigureCanvasTkAgg(self.fig, self.master)
        self.config_window()
        self.draw_graph('janvier')
        self.frame.pack(expand=YES, fill=BOTH)

    def config_window(self):
        self.canvas.mpl_connect("key_press_event", self.on_key_press)
        toolbar = NavigationToolbar2Tk(self.canvas, self.master)
        toolbar.update()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        self.button = Button(self.master, text="Quit", command=self._quit)
        self.button.pack(side=BOTTOM)
        self.button_back = Button(self.master,
                                  text="Graphique précédent",
                                  command=self.back_graph)
        self.button_back.pack(side=BOTTOM)
        self.button_next = Button(self.master,
                                  text="Graphique suivant",
                                  command=self.next_graph)
        self.button_next.pack(side=BOTTOM)

    def draw_graph(self, month):

        if (month == 'année'):
            df_temp = pd.DataFrame(columns=['Température'])
            df_temp_error = pd.DataFrame(columns=['Température'])
            for column in df:
                for value in df[column]:
                    df_temp = df_temp.append({'Température': value},
                                             ignore_index=True)

            for column in df_error:
                for value in df_error[column]:
                    df_temp_error = df_temp_error.append(
                        {'Température': value}, ignore_index=True)

            df_temp.dropna()
            df_temp_error.dropna()

            self.ax.clear()
            self.ax.plot(df_temp['Température'])
            self.ax.plot(df_temp_error['Température'])
            self.ax.set(title='Année')
            self.canvas.draw()
        else:
            self.ax.clear()
            self.ax.plot(df[month])
            clear_data(df[month])
            self.ax.set(title=month)
            self.canvas.draw()

    def on_key_press(event):
        key_press_handler(event, self.canvas, toolbar)

    def _quit(self):
        self.master.quit()

    def next_graph(self):
        if self.graphIndex == 0:
            self.draw_graph('février')
            self.graphIndex = 1
        elif self.graphIndex == 1:
            self.draw_graph('mars')
            self.graphIndex = 2
        elif self.graphIndex == 2:
            self.draw_graph('avril')
            self.graphIndex = 3
        elif self.graphIndex == 3:
            self.draw_graph('mai')
            self.graphIndex = 4
        elif self.graphIndex == 4:
            self.draw_graph('juin')
            self.graphIndex = 5
        elif self.graphIndex == 5:
            self.draw_graph('juillet')
            self.graphIndex = 6
        elif self.graphIndex == 6:
            self.draw_graph('août')
            self.graphIndex = 7
        elif self.graphIndex == 7:
            self.draw_graph('septembre')
            self.graphIndex = 8
        elif self.graphIndex == 8:
            self.draw_graph('octobre')
            self.graphIndex = 9
        elif self.graphIndex == 9:
            self.draw_graph('novembre')
            self.graphIndex = 10
        elif self.graphIndex == 10:
            self.draw_graph('décembre')
            self.graphIndex = 11
        elif self.graphIndex == 11:
            self.draw_graph('janvier')
            self.graphIndex = 12
        elif self.graphIndex == 12:
            self.draw_graph('année')
            self.graphIndex = 0

    def back_graph(self):
        if self.graphIndex == 0:
            self.draw_graph('décembre')
            self.graphIndex = 11
        elif self.graphIndex == 11:
            self.draw_graph('novembre')
            self.graphIndex = 10
        elif self.graphIndex == 10:
            self.draw_graph('octobre')
            self.graphIndex = 9
        elif self.graphIndex == 9:
            self.draw_graph('septembre')
            self.graphIndex = 8
        elif self.graphIndex == 8:
            self.draw_graph('août')
            self.graphIndex = 7
        elif self.graphIndex == 7:
            self.draw_graph('juillet')
            self.graphIndex = 6
        elif self.graphIndex == 6:
            self.draw_graph('juin')
            self.graphIndex = 5
        elif self.graphIndex == 5:
            self.draw_graph('mai')
            self.graphIndex = 4
        elif self.graphIndex == 4:
            self.draw_graph('avril')
            self.graphIndex = 3
        elif self.graphIndex == 3:
            self.draw_graph('mars')
            self.graphIndex = 2
        elif self.graphIndex == 2:
            self.draw_graph('février')
            self.graphIndex = 1
        elif self.graphIndex == 1:
            self.draw_graph('janvier')
            self.graphIndex = 12
        elif self.graphIndex == 12:
            self.draw_graph('année')
            self.graphIndex = 0
Example #42
0
File: main.py Project: ifrithd/tsp
class Window:
    def __init__(self):
        self.cities = []
        self.read_cities()

        # 使得可以显示中文
        mpl.rcParams['font.sans-serif'] = ['SimHei']

        self.root = Tk()
        self.root.title('TSP')
        self.root.resizable(width=False, height=False)

        # 画布控件 位于最上方
        figure = Figure(figsize=(6.5, 3.5))
        self.f = figure.add_subplot(1, 1, 1)
        self.canvas = FigureCanvasTkAgg(figure, self.root)
        self.canvas.get_tk_widget().pack()
        self.clean_canvas()

        tk.Label(self.root, text='请选择要经过的城市:').pack()

        # 复选框部分
        self.v = []
        r, c = 0, 0
        sep = Frame()
        sep.pack()
        for i in range(len(self.cities)):
            self.v.append(tk.IntVar())
            b = tk.Checkbutton(sep,
                               text=str(i) + self.cities[i].name,
                               variable=self.v[-1])
            b.grid(row=r, column=c)
            if (i + 1) % 6 == 0:
                r, c = r + 1, 0
            else:
                r, c = r, c + 1
        self.v.append(tk.IntVar())
        b = tk.Checkbutton(sep, text='全选', variable=self.v[-1])
        b.grid(row=r, column=c)

        # 输入框部分
        sep = Frame()
        sep.pack()
        tk.Label(sep, text='请输入初始城市编号:').pack()
        self.textStr = tk.StringVar()
        textEntry = tk.Entry(sep, textvariable=self.textStr)
        self.textStr.set("")
        textEntry.pack()

        # 运行按钮
        tk.Button(sep, text="Run!", command=self._run).pack()

        self.show_dis = tk.Label(sep, text="")
        self.show_dis.pack()
        mainloop()

    def read_cities(self):
        with open('data.txt') as f:
            for line in f:
                self.cities.append(City(*line.split(',')))

    def clean_canvas(self, start_cities=None):
        self.f.clear()
        for i in range(len(self.cities)):
            if start_cities is not None and i == start_cities:
                self.f.scatter(self.cities[i].x,
                               self.cities[i].y,
                               color='b',
                               marker='*')
            else:
                self.f.scatter(self.cities[i].x,
                               self.cities[i].y,
                               color='g',
                               marker='.',
                               alpha=0.4)
            self.f.text(self.cities[i].x,
                        self.cities[i].y,
                        self.cities[i].name,
                        fontsize=7)
        self.canvas.draw()

    def _run(self):
        # 读出选择的城市与起始城市
        selected = [item.get() for item in self.v]
        if selected[-1]:
            selected = [1] * (len(selected) - 1)
        else:
            del selected[-1]
        try:
            start_city = int(self.textStr.get())
        except ValueError:
            start_city = -1

        if sum(selected) <= 2:
            self.show_dis['text'] = 'Error: 城市数过少'
            return

        input_cities = []
        for i in range(len(self.cities)):
            if selected[i]:
                input_cities.append(self.cities[i])
                if start_city == -1:
                    start_city = i

        # 计算并绘制图像
        self.clean_canvas(start_city)
        self.show_dis['text'] = '计算中'
        self.root.update()
        ans = tsp(input_cities)
        self.draw_ans(input_cities, ans.dna)
        self.show_dis['text'] = 'distance: {}'.format(ans.distance)

    def draw_ans(self, cities, ans):
        for i in range(len(ans)):
            cityA = cities[ans[i]]
            cityB = cities[ans[(i + 1) % len(ans)]]
            self.f.plot([cityA.x, cityB.x], [cityA.y, cityB.y], color='r')
        self.canvas.draw()
class Program:
    def __init__(self, master):

        #laver et vindue
        frame = tkinter.Frame(master)

        #Laver 3 knapper der har hver sin funktion, de bruges til at sætte kvaliteten på 3D modellen
        self.button_1 = tkinter.Button(frame,
                                       text="Lav kvalitet",
                                       command=self.lavere)
        self.button_1.pack(side="left")
        self.button_2 = tkinter.Button(frame,
                                       text="Standard kvalitet",
                                       command=self.standard)
        self.button_2.pack(side="left")
        self.button_3 = tkinter.Button(frame,
                                       text="Høj kvalitet",
                                       command=self.højere)
        self.button_3.pack(side="left")

        #tekst box og knap til radius
        self.textbox = tkinter.Text(frame, height=1, width=10)
        self.textbox.pack()
        self.buttonsend = Button(frame,
                                 text="Enter radius",
                                 command=lambda: self.radius())
        self.buttonsend.pack()

        #Dette får matplotlib til at vise sig i Tkinter
        self.canvas = FigureCanvasTkAgg(fig, master=master)
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)

        #Bruges senere i programmet, det fortæller at for eksempel "u" er lig med værdier fra 0 til 12 med 12/60 (0.2) imellem hver værdi.
        self.u = np.linspace(0, 12, 60)
        self.v = np.linspace(0, 2 * np.pi, 60)
        self.U, self.V = np.meshgrid(self.u, self.v)
        self.u1 = np.linspace(12, 26, 60)
        self.v1 = np.linspace(0, 2 * np.pi, 60)
        self.U1, self.V1 = np.meshgrid(self.u1, self.v1)
        self.u2 = np.linspace(26, 32, 60)
        self.v2 = np.linspace(0, 2 * np.pi, 60)
        self.U2, self.V2 = np.meshgrid(self.u2, self.v2)
        self.X = self.U
        self.X1 = self.U1
        self.X2 = self.U2

        #Bruger vi senere i koden
        self.integer = 1

        #".pack()" får tingene til at vise sig i tkinter.
        frame.pack()

    def radius(self):
        self.inputvalue = self.textbox.get("1.0", "end-1c")
        self.integer = int(self.inputvalue)
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        self.Y1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.cos(
            self.V) * self.integer
        self.Z1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.sin(
            self.V) * self.integer
        self.Y2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.cos(self.V1) * self.integer
        self.Z2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.sin(self.V1) * self.integer

        self.Y3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.cos(self.V2) * self.integer
        self.Z3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.sin(self.V2) * self.integer
        ax.plot_surface(self.X,
                        self.Y1,
                        self.Z1,
                        alpha=1,
                        color='red',
                        rstride=10,
                        cstride=10)
        ax.plot_surface(self.X1,
                        self.Y2,
                        self.Z2,
                        alpha=1,
                        color='blue',
                        rstride=10,
                        cstride=10)
        ax.plot_surface(self.X2,
                        self.Y3,
                        self.Z3,
                        alpha=1,
                        color='green',
                        rstride=10,
                        cstride=10)
        self.canvas.draw()

    def lavere(self):
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        self.Y1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.cos(
            self.V) * self.integer
        self.Z1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.sin(
            self.V) * self.integer
        self.Y2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.cos(self.V1) * self.integer
        self.Z2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.sin(self.V1) * self.integer

        self.Y3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.cos(self.V2) * self.integer
        self.Z3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.sin(self.V2) * self.integer
        ax.plot_surface(self.X,
                        self.Y1,
                        self.Z1,
                        alpha=1,
                        color='red',
                        rstride=15,
                        cstride=15)
        ax.plot_surface(self.X1,
                        self.Y2,
                        self.Z2,
                        alpha=1,
                        color='blue',
                        rstride=15,
                        cstride=15)
        ax.plot_surface(self.X2,
                        self.Y3,
                        self.Z3,
                        alpha=1,
                        color='green',
                        rstride=15,
                        cstride=15)
        self.canvas.draw()

    def standard(self):
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        self.Y1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.cos(
            self.V) * self.integer
        self.Z1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.sin(
            self.V) * self.integer
        self.Y2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.cos(self.V1) * self.integer
        self.Z2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.sin(self.V1) * self.integer

        self.Y3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.cos(self.V2) * self.integer
        self.Z3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.sin(self.V2) * self.integer
        ax.plot_surface(self.X,
                        self.Y1,
                        self.Z1,
                        alpha=1,
                        color='red',
                        rstride=10,
                        cstride=10)
        ax.plot_surface(self.X1,
                        self.Y2,
                        self.Z2,
                        alpha=1,
                        color='blue',
                        rstride=10,
                        cstride=10)
        ax.plot_surface(self.X2,
                        self.Y3,
                        self.Z3,
                        alpha=1,
                        color='green',
                        rstride=10,
                        cstride=10)
        self.canvas.draw()

    def højere(self):
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        self.Y1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.cos(
            self.V) * self.integer
        self.Z1 = (1.49 * np.cos(0.34 * self.U) + 7.85) * np.sin(
            self.V) * self.integer
        self.Y2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.cos(self.V1) * self.integer
        self.Z2 = (((-21599 / 302702400) * self.U1**6) +
                   ((71843 / 8648640) * self.U1**5) -
                   ((39878297 / 100900800) * self.U1**4) +
                   ((118897967 / 12108096) * self.U1**3) -
                   ((2903465249 / 21621600) * self.U1**2) +
                   (268899149 / 280280) * self.U1 -
                   (16145189 / 5775)) * np.sin(self.V1) * self.integer

        self.Y3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.cos(self.V2) * self.integer
        self.Z3 = (
            ((0.23671) * self.U2**2) -
            (13.7463 * self.U2) + 207.391) * np.sin(self.V2) * self.integer
        ax.plot_surface(self.X,
                        self.Y1,
                        self.Z1,
                        alpha=1,
                        color='red',
                        rstride=5,
                        cstride=5)
        ax.plot_surface(self.X1,
                        self.Y2,
                        self.Z2,
                        alpha=1,
                        color='blue',
                        rstride=5,
                        cstride=5)
        ax.plot_surface(self.X2,
                        self.Y3,
                        self.Z3,
                        alpha=1,
                        color='green',
                        rstride=5,
                        cstride=5)
        self.canvas.draw()
Example #44
0
def output(self, date1, date2, tick, currency, sugestion, signal_span,
           slow_span, fast_span):

    root = self

    t = np.arange(0, 7000, 1)

    data = MT5Import(date1, date2, currency, tick)
    closep = []
    highp = []
    lowp = []
    openp = []
    time = []
    for val in data:
        time.append(val[0])
        closep.append(val[1])
        highp.append(val[2])
        lowp.append(val[3])
        openp.append(val[4])
    trading_days = (date2.year - date1.year) * 365 + (
        date2.month - date1.month) * 30 + (date2.day - date1.day)
    annual_volatility = st.stdev(closep) * np.sqrt(trading_days) * 100

    candles = graph_data_ohlc(closep, highp, lowp, openp, time)

    cenka = pd.DataFrame(data=closep)
    ema26 = cenka.ewm(span=slow_span).mean()
    ema12 = cenka.ewm(span=fast_span).mean()
    macd = []
    for i in range(0, len(ema26)):
        macd.append(ema12.values[i] - ema26.values[i])
    sygnal = pd.DataFrame(data=macd)
    sig = sygnal.ewm(span=signal_span).mean()

    values = []
    points = []
    tactic = str()
    for i in range(0, len(macd), 1):
        values.append(macd[i] - sig.values[i])
        if i > 0:
            if (values[i] >= 0 and values[i - 1] < 0):
                points.append(My_point(t[i], macd[i], True))
            elif (values[i - 1] >= 0 and values[i] < 0):
                points.append(My_point(t[i], macd[i], False))

    data_to_return = []
    data_to_return.append(closep)
    data_to_return.append(points)

    last_pos = points[len(points) - 1]
    if last_pos.Buy == True:
        tactic = "Position: Buy"
    else:
        tactic = "Position: Sell"

    anual_vol = "Annualised Volatility: " + str(annual_volatility) + "%"
    sugestion.delete('1.0', tkinter.END)
    sugestion.insert(tkinter.INSERT, tactic + "\n" + anual_vol)
    fig1 = plt2.figure(figsize=[5.0, 3.0])
    xax = [1] * len(values)
    for i in range(0, len(values)):
        values[i] = values[i][0]

    ax1 = plt2.subplot2grid((1, 1), (0, 0))
    ax1.xaxis.set_major_locator(ticker.MaxNLocator(10))

    def mydate(x, pos):
        try:
            return time[int(x)]
        except IndexError:
            return ''

    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(5)
    ax1.grid(True)

    plt2.plot(sig, 'b')
    plt2.plot(macd, 'y')

    plt2.title('MACD')

    #Punkty kup/sprzedaj
    for i in range(0, len(points), 1):
        if points[i].Buy == True:
            plt2.plot(points[i].X, points[i].Y, 'go')
        if points[i].Buy == False:
            plt2.plot(points[i].X, points[i].Y, 'ro')

    #Reszta z tworzenia GUI
    canvas = FigureCanvasTkAgg(candles, master=root)  #A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

    canvas = FigureCanvasTkAgg(fig1, master=root)  #A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

    return data_to_return
Example #45
0
class NVIDIA_MEM_GUI():
    def __init__(self, history_length=100):

        self.history_length = history_length

        self.root = Tk.Tk()
        self.root.wm_title("GPU MEMORY DISPLAY")
        self.root.protocol('WM_DELETE_WINDOW', self.quit_button_cb)

        fig = plt.figure(figsize=(8, 3))

        self.subplot = plt.subplot(211)
        plt.gca().invert_xaxis()

        self.canvas = FigureCanvasTkAgg(fig, master=self.root)

        self.max_gpu_mem = None
        self.current_gpu_mem = None
        self.mem_data = [0] * self.history_length
        self.mem_range = list(reversed(range(self.history_length)))

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

        self.update()

        Tk.mainloop()

    def quit_button_cb(self, *args):

        self.root.quit()
        self.root.destroy()

    def update(self):
        self.draw()

        r = check_output(["nvidia-smi"])

        mem_string = re.findall("\d+MiB \/\s+\d+MiB", str(r))
        sizes = list(map(float, re.findall("\d+", mem_string[0])))
        self.max_gpu_mem = sizes[1]
        self.current_gpu_mem = sizes[0]

        self.mem_data.pop(0)
        self.mem_data.append(100.0 * self.current_gpu_mem / self.max_gpu_mem)

        self.show_plot()
        self.root.after(1000, self.update)

    def show_plot(self):

        self.subplot.clear()

        self.subplot.set_ylabel("Percent in use.")
        self.subplot.set_xlabel("Seconds Past")

        plt.xlim((self.history_length, 0))
        plt.ylim((0, 100))

        plt.title("GPU Memory in use: " + str(self.current_gpu_mem) + " / " +
                  str(self.max_gpu_mem) + "MiB; " +
                  "{0:.2f}".format(self.mem_data[-1]) + "%")

        plt.plot(self.mem_range, self.mem_data)

    def draw(self):
        self.root.update()
        self.canvas.draw()
Example #46
0
# draw the figure
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(211)
x = np.linspace(-50,50,100)
y = [math.cos(z) for z in x]
a.plot(x,y)
a.set_xlabel('x')
a.set_ylabel('y')

b = f.add_subplot(212)
b.bar(x,y)
b.set_xlabel('x')
b.set_ylabel('y')
f.tight_layout()

# show this figure on this canvas
canvas = FigureCanvasTkAgg(f, root)
canvas.show()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

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


root.mainloop()
try:
    root.destroy()
except:
    pass
Example #47
0
class Module_1:
    def __init__(self, master):
        global settings_file
        self.root = master
        self.root.title("ESS System Interface")
        full_screen = True
        if full_screen:
            self.root.attributes('-fullscreen',
                                 True)  # fullscreen on touchscreen
        else:
            self.root.geometry('800x480')  # actual size of RPi touchscreen
        #self.root.attributes('-fullscreen',True)
        self.root.configure(bg="sky blue")
        self.root.minsize(800, 480)  # min size the window can be dragged to

        self.open_loop_stop = None  # control open Loop button

        # module message/label
        battery_font = tkFont.Font(family="Lucida Grande", size=9)
        label_font = tkFont.Font(family="Lucida Grande", size=12)
        warning_font = tkFont.Font(family="Lucida Grande", size=24)
        self.battery_array = []
        self.percent = 0
        self.charging = False

        # parameters for buttons and frames

        #create all the buttons onto to the main window
        button_width = 10
        button_big_height = 8
        button_small_height = 3
        sticky_to = 'nsew'  # allows all buttons to resize

        # setup Serial port-
        ## Graphing Frame and fake plot
        self.graph_frame = Frame(self.root, background="white")
        self.graph_frame.grid(row=2,
                              column=0,
                              columnspan=8,
                              padx=1,
                              pady=3,
                              sticky=sticky_to)

        #initalize figure
        self.fig = plt.figure()
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('ADC Counts')
        plt.xlim(300, 900)
        plt.ylim(0, 66500)
        plt.subplots_adjust(bottom=0.14, right=0.95, top=0.96)

        #initalize canvas for plotting
        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.graph_frame)  # A tk.DrawingArea.
        # create toolbar for canvas
        toolbar = NavigationToolbar2Tk(self.canvas, self.graph_frame)
        toolbar.update()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)

        # create function object for calling functions
        settings_func = _Settings(settings_file)

        try:
            settings_func.create_settings()
        except:
            pass

        #(self.settings, self.wavelength) = settings_func.settings_read()
        self.func = functions(self.root, self.canvas, self.fig)
        self.func.home()

        module_button = Button(self.root,
                               text="Module 1: Scanning ESS",
                               bg='sky blue',
                               bd=0,
                               highlightthickness=0,
                               width=button_width,
                               height=7)
        module_button.grid(row=0,
                           column=0,
                           columnspan=7,
                           padx=1,
                           sticky=sticky_to)

        # with all their corresponding functions (command)
        self.quit_button = Button(self.root,
                                  text="Quit",
                                  fg='Red',
                                  command=self.quit_button,
                                  width=button_width,
                                  height=button_big_height)
        self.quit_button.grid(row=1,
                              column=6,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.help_button = Button(self.root,
                                  text="Help",
                                  fg='black',
                                  command=self.func.plot_selected,
                                  width=button_width,
                                  height=button_big_height)
        self.help_button.grid(row=1,
                              column=5,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.settings_button = Button(
            self.root,
            text="Settings",
            fg='black',
            command=lambda: self.window_popup(self.root),
            width=button_width,
            height=button_big_height)
        self.settings_button.grid(row=1,
                                  column=4,
                                  padx=1,
                                  pady=1,
                                  sticky=sticky_to)

        self.save_reference_button = Button(
            self.root,
            text="Save as Reference",
            wraplength=80,
            fg='black',
            command=self.func.save_scan_reference,
            width=button_width,
            height=button_big_height)
        self.save_reference_button.grid(row=1,
                                        column=3,
                                        padx=1,
                                        pady=1,
                                        sticky=sticky_to)

        self.acquire_button = Button(
            self.root,
            text="Acquire",
            wraplength=80,
            fg='black',
            command=lambda: self.func.acquire(save=False),
            width=button_width,
            height=button_big_height)
        self.acquire_button.grid(row=1,
                                 column=2,
                                 pady=1,
                                 padx=1,
                                 sticky=sticky_to)

        self.scan_button = Button(self.root,
                                  text="Scan",
                                  fg='black',
                                  wraplength=80,
                                  command=self.func.scan,
                                  width=button_width,
                                  height=button_big_height)

        self.scan_button.grid(row=1,
                              column=1,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.open_scan_file_button = Button(self.root,
                                            text='Create Scan File',
                                            fg='black',
                                            wraplength=80,
                                            command=self.func.new_scan,
                                            width=button_width,
                                            height=button_big_height)
        self.open_scan_file_button.grid(row=1,
                                        column=0,
                                        padx=1,
                                        pady=1,
                                        sticky=sticky_to)

        # allow buttons and frames to resize with the resizing of the root window
        self.root.grid_columnconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1)
        self.root.grid_rowconfigure((0, 1, 2), weight=1)

        self.battery_frame = Frame(self.root, bg='sky blue', width=4)
        self.battery_frame.grid(row=1,
                                column=7,
                                padx=(0, 1),
                                pady=1,
                                sticky='nsew')

        battery_width = 8

        self.battery_label_1 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_1.grid(row=0, column=0, padx=1, sticky='nsew')

        self.battery_label_2 = Label(self.battery_frame,
                                     text="%",
                                     font=battery_font,
                                     height=2,
                                     bg="green",
                                     width=battery_width)
        self.battery_label_2.grid(row=1, column=0, padx=1, sticky='nsew')

        self.battery_label_3 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_3.grid(row=2, column=0, padx=1, sticky='nsew')

        self.battery_label_4 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_4.grid(row=3, column=0, padx=1, sticky='nsew')

        self.battery_frame.grid_rowconfigure((0, 1, 2, 3), weight=1)
        self.battery_frame.grid_columnconfigure((0), weight=1)

        # show module connected
        #messagebox.showinfo('Module #','Module 0: Base ESS System connected (No attachments)')

        # check battery percent from arduino
        def battery_percent_check():
            self.percent = self.func.battery_check()
            self.charging = False
            # check for charging and then add percent to array for averaging
            if int(self.percent) == 1000:
                self.charging = True
            self.battery_array.append(int(self.percent))
            if len(self.battery_array) > 10:
                del self.battery_array[0]

            #average battery_array
            self.percent = int(
                sum(self.battery_array) / (len(self.battery_array)))

            if self.charging:
                self.battery_label_1.configure(bg='green')
                self.battery_label_2.configure(font=battery_font,
                                               text="Charging",
                                               bg='green')
                self.battery_label_3.configure(bg='green')
                self.battery_label_4.configure(bg='green')
            else:
                if int(self.percent) >= 75:
                    self.battery_label_1.configure(bg='green')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 75 and int(self.percent) >= 50:
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 50 and int(self.percent) >= 25:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 25 and int(self.percent) >= 15:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='yellow')
                else:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text="LOW",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='red')

                    error_top = Toplevel(self.root, bg="red")
                    message = Label(
                        error_top,
                        bg="white",
                        text="Low Battery! Plug In device and Save Data",
                        font=warning_font,
                        wraplength=250)
                    message.grid(row=0, column=0, padx=10, pady=10)
                    error_top.title("Warning")
                    error_top.lift()

                    error_top.after(3000, error_top.destroy)

            try:
                self.root.after(10000, battery_percent_check)
            except:
                pass

        battery_percent_check()

        # show module connected
        #messagebox.showinfo('Module #','Module 1: ESS Scanning Module Connected')

    # allows for popup of settings window
    def window_popup(self, master):
        self.popup_window = Toplevel(master)
        self.sett_popup = settings_window.settings_popup_window(
            self.popup_window, master)

    def quit_button(self):
        self.root.destroy()
        self.root.quit()
Example #48
0
def draw_sample_figure(canvas, figure):
    '''Create the sample figure on the GUI's front page'''
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
    return figure_canvas_agg
def small_angles(t, a, b, fps=90, view_graph=True):

    #take fft of alpha and beta
    a_fourier = abs(np.fft.rfft(a))
    b_fourier = abs(np.fft.rfft(b))
    N = len(a_fourier)
    freq = [i / N * fps / 2 for i in range(N)]
    df = fps / N

    a, b, c = [0, 0], [0, 0], [0, 0]

    for n, y in enumerate([a_fourier, b_fourier]):
        i = np.argmax(y)
        a[n] = (y[i + 1] - 2 * y[i] + y[i - 1]) / (2 * df * df)
        b[n] = (y[i + 1] - y[i - 1]) / (2 * df) - 2 * a[n] * freq[i]
        c[n] = y[i] - a[n] * freq[i]**2 - b[n] * freq[i]
    print('a: {}\nb: {}\nc: {}\ni: {}'.format(a, b, c, i))

    fpeak, ypeak = [0, 0], [0, 0]
    for i in [0, 1]:
        fpeak[i] = -b[i] / (2 * a[i])
        ypeak[i] = a[i] * fpeak[i]**2 + b[i] * fpeak[i] + c[i]

    print('fpeak is {}'.format(fpeak))
    print('ypeak is {}'.format(ypeak))

    if view_graph:
        #setup graph for fourier
        fig = plt.figure()
        ax1 = fig.add_subplot(2, 1, 1)
        ax2 = fig.add_subplot(2, 1, 2)
        #~ ax1.set_ylim([-180,180])						#set y limits
        #~ ax2.set_ylim([-180,180])
        #~ ax1.set_xlim(left=0, auto=True)
        #~ ax1.yaxis.set_ticks(np.arange(-180, 181, 90))	#format x axis labels.
        #~ ax2.yaxis.set_ticks(np.arange(-180, 181, 90))
        ax1.grid(linestyle='--', which='both')  #format gridlines
        ax2.grid(linestyle='--', which='both')
        ax1.set_ylabel(
            '\u03b1 response'
        )  #axis labels: 03b1 is alpha, 03b2 is beta, 00b0 is degree
        ax2.set_ylabel('\u03b2 response')
        ax2.set_xlabel('Frequency [Hz]')
        ax1.grid(
            True
        )  #remove the numbers from the x axis of the top plot for neatness
        ax1.xaxis.set_ticklabels([])
        ln1, = ax1.plot(freq, a_fourier)  #, label=legend_a)
        ln2, = ax2.plot(freq, b_fourier)  #, label=legend_b)

        ax1.plot(fpeak[0], ypeak[0], 'rx')  #, label=legend_a)
        ax2.plot(fpeak[1], ypeak[1], 'rx')  #, label=legend_b)

        fig.tight_layout()

        #display graph
        root_small_angle = tk.Toplevel()
        root_small_angle.title('Fourier Transform of alpha and beta')
        canvas = FigureCanvasTkAgg(fig, master=root_small_angle)
        canvas.get_tk_widget().pack(side='top', fill='both', expand=1)

        toolbar = NavigationToolbar2TkAgg(canvas, root_small_angle)
        toolbar.update()
        canvas._tkcanvas.pack(side='top', fill='both', expand=1)

        canvas.draw()

    #modeshape
    modeshape = ypeak[0] / ypeak[1]
    resonance = (fpeak[0] + fpeak[1]) / 2

    return modeshape, resonance
class SignalResponse(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.parent = parent

        self.title = tk.Label(self,
                              height=1,
                              width=50,
                              text="Signal Response",
                              font=Config.LARGE_FONT,
                              background="#ffccd5")
        self.title.pack(side=tk.TOP, fill=tk.BOTH, pady=0)

        self.H = ss.TransferFunction([1], [1])
        self.getTransf()

        self.f = Figure(figsize=(5, 3), dpi=100)

        self.ax1 = self.f.add_subplot(211)

        self.ax2 = self.f.add_subplot(212)

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

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

        self.backButton = tk.Button(self,
                                    height=2,
                                    width=50,
                                    text="Back to Mode",
                                    font=Config.SMALL_FONT,
                                    background="#cfffd5",
                                    command=self.goBack)
        self.backButton.pack(side=tk.TOP, fill=tk.BOTH)

    def getTransf(self):
        pass

    def goBack(self):
        # evitamos dependencias circulares, importamos solo cuando es necesario
        from Menus.MenuMode import MenuMode
        self.controller.showFrame(MenuMode)

    def focus(self):
        Vin = [1]
        Vout = [1]

        xinput = userInput.get("inputFunction")
        amp = userInput.get("inputAmplitude")
        finput = userInput.get("inputFreq")

        order = userInput.get("order")
        filterType = userInput.get("type")
        f0 = userInput.get("frequency")
        f1 = userInput.get("frequency2")
        k = userInput.get("gain")
        epsilon = userInput.get("epsilon")
        p1 = userInput.get("p1")
        z1 = userInput.get("z1")
        p2 = userInput.get("p2")
        z2 = userInput.get("z2")

        print("Order ", order, "Type ", filterType, "Freq ", f0, "Gain", k,
              "Eps ", epsilon)

        if order == 1:

            if filterType == "low":
                Vout = [k]
                Vin = [1 / f0, 1]
            elif filterType == "high":
                Vout = [k, 0]
                Vin = [1 / f0, 1]
            elif filterType == "all":
                Vout = [k / f0, -k]
                Vin = [1 / f0, +1]
            elif filterType == "guess":
                if z1 is None:
                    Vout = [1]
                else:
                    Vout = [1, -z1]

                Vin = [1, -p1]

        elif order == 2:

            if filterType == "low":
                Vout = [k]
                Vin = [pow(1 / f0, 2), 2 * epsilon / f0, 1]
            elif filterType == "high":
                Vout = [k, 0, 0]
                Vin = [pow(1 / f0, 2), 2 * epsilon / f0, 1]
            elif filterType == "all":
                Vout = [k * pow(1 / f0, 2), -2 * k * epsilon / f0, k]
                Vin = [pow(1 / f0, 2), 2 * epsilon / f0, 1]
            elif filterType == "band":
                Vout = [k, 0]
                Vin = [pow(1 / f0, 2), 2 * epsilon / f0, 1]
            elif filterType == "notch":
                Vout = [k * pow(1 / f0, 2), 0, k]
                Vin = [pow(1 / f0, 2), 2 * epsilon / f0, 1]
            elif filterType == "guess":
                if (z1 or z2) is None:
                    if (z1 and z2) is None:
                        Vout = [1]
                        if p1 == None:
                            Vin = [1, -p2]
                        if p2 == None:
                            Vin = [1, -p1]
                        else:
                            Vin = [
                                pow(1 / sqrt(p1 * p2), 2),
                                (-p1 - p2) / (p1 * p2), 1
                            ]
                    elif z1 == None:
                        Vout = [1, -z2]
                        if p1 == None:
                            Vin = [1, -p2]
                        if p2 == None:
                            Vin = [1, -p1]
                        else:
                            Vin = [
                                pow(1 / sqrt(p1 * p2), 2),
                                (-p1 - p2) / (p1 * p2), 1
                            ]
                    elif z2 == None:
                        Vout = [1, -z1]
                        if p1 == None:
                            Vin = [1, -p2]
                        if p2 == None:
                            Vin = [1, -p1]
                        else:
                            Vin = [
                                pow(1 / sqrt(p1 * p2), 2),
                                (-p1 - p2) / (p1 * p2), 1
                            ]
                else:
                    Vout = [
                        pow(1 / sqrt(z1 * z2), 2), (-z1 - z2) / (z1 * z2), 1
                    ]
                    Vin = [
                        pow(1 / sqrt(p1 * p2), 2), (-p1 - p2) / (p1 * p2), 1
                    ]

        self.H = ss.TransferFunction(Vout, Vin)

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

        if xinput == "Sine":

            t = linspace(0, 1, num=1000)
            u = amp * sin(2 * pi * finput * t)
            tout, yout, xout = ss.lsim(self.H, U=u, T=t)

            self.ax1.plot(t, u, color='r', linewidth=0.5)
            self.ax1.minorticks_on()
            self.ax1.grid(which='major',
                          color='black',
                          linewidth=0.8,
                          linestyle='--')
            self.ax1.grid(which='minor',
                          color='black',
                          linewidth=0.4,
                          linestyle=':')
            # Sets figure data.
            self.ax1.set_title('Sinusoidal input signal')
            self.ax1.set_ylabel('Amplitude [V]')

            self.ax2.plot(tout, yout, color='b', linewidth=0.5)
            self.ax2.minorticks_on()
            self.ax2.grid(which='major',
                          color='black',
                          linewidth=0.8,
                          linestyle='--')
            self.ax2.grid(which='minor',
                          color='black',
                          linewidth=0.4,
                          linestyle=':')
            # Sets figure data.
            self.ax2.set_title('Output signal')
            self.ax2.set_xlabel('Time [s]')
            self.ax2.set_ylabel('Amplitude [V]')

        elif xinput == "Step":

            t, Step = ss.step(self.H)

            self.ax1.plot(t, amp * heaviside(t, 0.5), color='b')
            self.ax1.minorticks_on()
            self.ax1.grid(which='major',
                          color='black',
                          linewidth=0.8,
                          linestyle='--')
            self.ax1.grid(which='minor',
                          color='black',
                          linewidth=0.4,
                          linestyle=':')
            # Sets figure data.
            self.ax1.set_title('A*u(t) input signal')
            self.ax1.set_ylabel('Amplitude [V]')

            self.ax2.plot(t, amp * Step, color='r')
            self.ax2.minorticks_on()
            self.ax2.grid(which='major',
                          color='black',
                          linewidth=0.8,
                          linestyle='--')
            self.ax2.grid(which='minor',
                          color='black',
                          linewidth=0.4,
                          linestyle=':')
            # Sets figure data.
            self.ax2.set_title('Output signal')
            self.ax2.set_xlabel('Time [s]')
            self.ax2.set_ylabel('Amplitude [V]')

        self.canvas.draw()

        pass
Example #51
0
class WinRes:
    def __init__(self, root, title, fname, const):
        self.root = root
        self.root.geometry("+150+50")
        self.fname = fname
        self.const = const
        self.title = title
        self.root.wm_title(self.title)
        self.sMin1 = StringVar()
        self.sMin1.set("-999")
        self.sMax1 = StringVar()
        self.sMax1.set("999")

        frame = Frame(self.root, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)
        frameD1 = Frame(self.root)
        frameD1.pack(fill=X, expand=True)
        frameD2 = Frame(self.root)
        frameD2.pack(fill=X, expand=True)

        self.frame1 = Frame(frame)
        self.frame1.pack(fill=BOTH)
        self.fig = Figure(figsize=(7, 6), dpi=100)

        dd = Res(self.fname,
                 [float(self.sMin1.get()),
                  float(self.sMax1.get())])

        if 'MetalCover' in fname:
            b = fname.split("MetalCover")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/MetalCover_flute3_VdP_img" + b + ".pdf"
        if 'n+' in fname:
            b = fname.split("n+")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/n+_VdP_img" + b + ".pdf"
        if 'Poly' in fname:
            b = fname.split("Poly")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/Poly_flute1_VdP_img" + b + ".pdf"
        if 'pstop' in fname:
            b = fname.split("pstop")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/pstop_flute1_VdP_img" + b + ".pdf"
        if 'PolyMeander' in fname:
            b = fname.split("PolyMeander")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/PolyMenader_flute2_img" + b + ".pdf"
        if 'p+Cross' in fname:
            b = fname.split("p+Cross")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/p+Cross_flute3_VdP_img" + b + ".pdf"
        if 'BulckCross' in fname:
            b = fname.split("BulckCross")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/BulkCross_flute3_VdP_img" + b + ".pdf"
        if 'n+CBKR' in fname:
            b = fname.split("n+CBKR")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/n+CBKR_flute4_VdP_img" + b + ".pdf"
        if 'polyCBKR' in fname:
            b = fname.split("polyCBKR")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/polyCBKR_flute4_VdP_img" + b + ".pdf"
        if 'p+Bridge' in fname:
            b = fname.split("p+Bridge")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/p+Bridge_flute3_VdP_img" + b + ".pdf"
        if 'Poly_Chain' in fname:
            b = fname.split("Poly_Chain")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/PolyChain_flute4_VdP_img" + b + ".pdf"
        if 'n+_Chain' in fname:
            b = fname.split("n+_Chain")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/n+Chain_flute4_VdP_img" + b + ".pdf"
        if 'p+_Chain' in fname:
            b = fname.split("p+_Chain")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/p+Chain_flute4_VdP_img" + b + ".pdf"
        if 'Metal_Meander_Chain' in fname:
            b = fname.split("Metal_Meander_Chain")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/MetalMeanderChain_flute3_VdP_img" + b + ".pdf"
        if 'n+_linewidth' in fname:
            b = fname.split("n+_linewidth")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/n+Linewidth_flute2_VdP_img" + b + ".pdf"
        if 'pstopLinewidth' in fname:
            b = fname.split("pstopLinewidth")[1].split(".t")[0]
            dirD = os.path.dirname(os.path.abspath(fname))
            self.img = dirD + "/pstopLinewidth_flute2_VdP_img" + b + ".pdf"

        self.result = []
        self.result.append(self.title)
        self.result.append(1e-3 / dd[2][0] * self.const)
        self.result.append(self.const * 1e-3 * dd[3][0] /
                           np.power(dd[2][0], 2))
        self.result.append(self.const)

        line1 = np.poly1d(dd[2])
        x1 = np.linspace(dd[0][0], dd[0][-1], 100)

        self.ax = self.fig.add_subplot(111)
        self.ax.plot(dd[0], dd[1], ".", x1, line1(x1))
        self.ax.ticklabel_format(axis='y',
                                 style='sci',
                                 scilimits=(-1, 2),
                                 useOffset=True,
                                 useMathText=True)
        self.ax.set_title(self.title)
        self.ax.xaxis.get_offset_text().set_position((1, 0.1))
        self.ax.xaxis.get_offset_text().set_rotation(-90)
        self.ax.set_xlabel("Voltage [mV]", loc='right')
        self.ax.set_ylabel("Current [A]", loc='top')
        if "MetalCover" in self.title:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.4f$\pm$%.4f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })
        elif "n+" in self.title and (not "CBKR" in self.title) and (
                not "Chain" in self.title):
            self.ax.text(0.3,
                         0.7, ("Result:\n%.3f$\pm$%.3f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })
        elif "MetalMeanderChain" in self.title:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.3f$\pm$%.3f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })
        else:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.1f$\pm$%.1f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })

        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.frame1)  # A tk.DrawingArea.
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tkinter.TOP,
                                         fill=tkinter.BOTH,
                                         expand=1)

        self.toolbar = NavigationToolbar2Tk(self.canvas, self.frame1)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(side=tkinter.TOP,
                                         fill=tkinter.BOTH,
                                         expand=1)

        self.lem1 = Label(frameD1,
                          text="Min1:",
                          anchor=W,
                          justify=LEFT,
                          width=6)
        self.lem1.pack(side=LEFT, padx=5, pady=5)
        self.em1 = Entry(frameD1, textvariable=self.sMin1, width=10)
        self.em1.pack(side=LEFT)  #, padx=5, pady=5)

        self.leM1 = Label(frameD1,
                          text="Max1:",
                          anchor=W,
                          justify=RIGHT,
                          width=6)
        self.leM1.pack(side=LEFT, padx=5, pady=5)
        self.eM1 = Entry(frameD1, textvariable=self.sMax1, width=10)
        self.eM1.pack(side=LEFT)  #, padx=5, pady=5)

        self.b3 = Button(self.root, text='Next', command=self.closeExt)
        self.b3.pack(side=RIGHT, padx=5, pady=5)
        self.b2 = Button(self.root, text='Update', command=self.UpdateRes)
        self.b2.pack(side=RIGHT)

        self.root.wait_window(self.root)

    def closeExt(self):
        self.fig.savefig(self.img)
        self.root.destroy()

    def UpdateRes(self):
        dd = Res(self.fname,
                 [float(self.sMin1.get()),
                  float(self.sMax1.get())])

        self.result = []
        self.result.append(self.title)
        self.result.append(1e-3 / dd[2][0] * self.const)
        self.result.append(self.const * 1e-3 * dd[3][0] /
                           np.power(dd[2][0], 2))
        self.result.append(self.const)
        line1 = np.poly1d(dd[2])
        x1 = np.linspace(max(dd[0][0], float(self.sMin1.get())),
                         min(dd[0][-1], float(self.sMax1.get())), 100)
        self.ax.clear()

        self.ax.plot(dd[0], dd[1], ".", x1, line1(x1))
        self.ax.ticklabel_format(axis='y',
                                 style='sci',
                                 scilimits=(-1, 2),
                                 useOffset=True,
                                 useMathText=True)
        self.ax.ticklabel_format(axis='x',
                                 style='sci',
                                 scilimits=(0, 2),
                                 useOffset=True,
                                 useMathText=True)
        self.ax.set_title(self.title)
        self.ax.set_xlabel("Voltage [mV]", loc='right')
        self.ax.set_ylabel("Current [A]", loc='top')
        if "MetalCover" in self.title:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.4f$\pm$%.4f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })
        elif "n+" in self.title and not "CBKR" in self.title and not "linewidth" in self.title:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.3f$\pm$%.3f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })
        else:
            self.ax.text(0.3,
                         0.7, ("Result:\n%.1f$\pm$%.1f [$\Omega$]" %
                               (1e-3 / dd[2][0] * self.const, self.const *
                                1e-3 * dd[3][0] / np.power(dd[2][0], 2))),
                         fontsize=10,
                         horizontalalignment='center',
                         style='normal',
                         transform=self.ax.transAxes,
                         bbox={
                             'facecolor': 'red',
                             'alpha': 0.5,
                             'pad': 5
                         })

        self.canvas.draw()
        self.toolbar.update()
def angle_vs_time(total_frames, centre, rotation, cap, fps, show_video,
                  show_graph):
    '''
	create a list of angles a and b at respective times and plot them
	Args:
		total_frames(int):
			total no. of frames
		centre(x,y):
			position of centre point
		rotation(float):
			angle to rotate to real vertical
	Return:

	'''
    #create window on which to show the video of detected dots
    experiment_video_window = tk.Toplevel()

    #~ photo = tk.PhotoImage(file="STOP.png") # a nice stop sign, but a little unclear
    #~ cancel_button = tk.ttk.Button(experiment_window, text='Abort!',
    #~ command=lambda:cancel_function(experiment_video_window))
    #~ image = photo
    experiment_video_window.update()
    video_canvas = tk.Canvas(experiment_video_window)
    graph_frame = tk.Frame(experiment_video_window)

    #~ cancel_button.grid(row=9)
    video_canvas.grid(row=1, column=0)
    graph_frame.grid(row=1, column=1)
    #~ experiment_video_window.protocol("WM_DELETE_WINDOW", cancel_function(experiment_video_window))

    dot1 = np.zeros((total_frames, 2))
    dot2 = np.zeros((total_frames, 2))
    detector = setup_blob_detector()
    a_deg = np.zeros(total_frames)
    b_deg = np.zeros(total_frames)
    frametest = np.zeros(total_frames)
    previous_frame = -1
    if show_graph:

        fig_anim = plt.figure()
        ax1_anim = fig_anim.add_subplot(2, 1, 1)
        ax2_anim = fig_anim.add_subplot(2, 1, 2)
        ax1_anim.set_xlim([0, total_frames / fps])
        ax1_anim.set_ylim([-180, 180])
        ax2_anim.set_xlim([0, total_frames / fps])
        ax2_anim.set_ylim([-180, 180])

        ln1_anim, = ax1_anim.plot([], [])
        ln2_anim, = ax2_anim.plot([], [])

        #~ # Shrink current axis by 20%
        #~ box = ax1.get_position()
        #~ ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
        #~ box = ax2.get_position()
        #~ ax2.set_position([box.x0, box.y0, box.width * 0.8, box.height])

        #~ #set position
        #~ w = 1200
        #~ h = 300
        #~ x = 0
        #~ y = 400
        #~ fig_anim.canvas.manager.window.wm_geometry("%dx%d+%d+%d" % (w, h, x, y))

        def update(frame):
            nonlocal dot1, dot2, a_deg, b_deg, time, previous_frame, experiment_video_window, video_canvas

            if frame == previous_frame + 1:  #the funcanimation repeats frame 0 a few times before
                #getting started, so use this if to make sure the function
                #is only called once per frame; otherwise the frame analysed
                #doesn't line up with the one expected.
                a_deg, b_deg, dot1, dot2 = track_dots(cap, frame, detector,
                                                      centre, a_deg, b_deg,
                                                      dot1, dot2, rotation,
                                                      total_frames, show_video,
                                                      experiment_video_window,
                                                      video_canvas)
            previous_frame = frame

            x = range(frame + 1)
            time = [i / fps for i in x]  #convert to time
            ln1_anim.set_data(time, a_deg[0:frame + 1])
            ln2_anim.set_data(time, b_deg[0:frame + 1])

            if frame == total_frames - 1:
                nonlocal pause_here
                pause_here = 0

            experiment_video_window.update()
            global cancel
            if cancel == True:
                cancel = False
                ani.event_source.stop()
                experiment_video_window.destroy()
                #~ cv2.destroyAllWindows()

            return ln1_anim, ln2_anim

        graph_canvas = FigureCanvasTkAgg(
            fig_anim, master=graph_frame
        )  #plot the graph on a canvas within the graph_frame
        graph_canvas.get_tk_widget().pack()

        pause_here = 1

        ani = anim.FuncAnimation(fig_anim,
                                 update,
                                 frames=total_frames,
                                 interval=1,
                                 blit=True,
                                 repeat=False)

        experiment_video_window.update()
        while pause_here:
            experiment_video_window.update()
        experiment_video_window.destroy()

    else:
        for frame in range(total_frames):
            a_deg, b_deg, dot1, dot2 = track_dots(cap, frame, detector, centre,
                                                  a_deg, b_deg, dot1, dot2,
                                                  rotation, total_frames,
                                                  show_video,
                                                  experiment_video_window,
                                                  video_canvas)

            experiment_video_window.update()
            global cancel
            if cancel == True:
                cancel = False
                break

            frametest[frame] = 6

    x = range(len(a_deg))
    time = [i / fps for i in x]  #convert to time

    #~ cv2.destroyAllWindows()
    experiment_video_window.destroy()

    return time, a_deg, b_deg
class windowClass:
    def __init__(self, window):
        self.canvas = None
        self.window = window
        self.box = Entry(window)
        self.labelForFile = Label(window,
                                  text="No file chosen . . .",
                                  bg="white",
                                  height=1,
                                  width=50,
                                  anchor="e",
                                  font=("Helvetica", 11))
        self.buttonChooseFile = Button(window,
                                       text="Choose Fle",
                                       command=self.openFileDialog,
                                       font=("Helvetica", 11))
        self.buttonPerceptron = Button(window,
                                       text="Perceptron Algorithm",
                                       command=self.plotPerceptron,
                                       height=1,
                                       width=50,
                                       font=("Helvetica", 11))
        self.buttonLogisticRegression = Button(
            window,
            text="Logistic Regression Algorithm",
            command=self.plotLogisticRegression,
            height=1,
            width=50,
            font=("Helvetica", 11))
        self.buttonPassiveAggressive = Button(
            window,
            text="Passive Aggressive Algorithm",
            command=self.plotPassiveAggressive,
            height=1,
            width=50,
            font=("Helvetica", 11))
        self.buttonMulticlassOneVsAllPerceptron = Button(
            window,
            text="One Vs All - Perceptron Algorithm",
            command=self.plotMulticlassOneVsAllPerceptron,
            height=1,
            width=50,
            font=("Helvetica", 11))
        self.buttonMulticlassOneVsAllLogisticRegression = Button(
            window,
            text="One Vs All - Logistic Regression algorithm",
            command=self.plotMulticlassOneVsAllLogisticRegression,
            height=1,
            width=50,
            font=("Helvetica", 11))
        self.buttonPassiveAggressiveOneVsAllLogisticRegression = Button(
            window,
            text="One Vs All - Passive Aggressive algorithm",
            command=self.plotMulticlassOneVsAllPassiveAggressive,
            height=1,
            width=50,
            font=("Helvetica", 11))
        self.labelTitle = Label(window,
                                text="",
                                bg="white",
                                font=("Helvetica", 14),
                                pady=5)

        # Pozicije u grid-u
        self.labelForFile.grid(row=0, column=0)
        self.buttonChooseFile.grid(row=0, column=1, sticky=W)
        self.buttonPerceptron.grid(row=1, column=0)
        self.buttonLogisticRegression.grid(row=2, column=0)
        self.buttonPassiveAggressive.grid(row=3, column=0)
        self.buttonMulticlassOneVsAllPerceptron.grid(row=1, column=1)
        self.buttonMulticlassOneVsAllLogisticRegression.grid(row=2, column=1)
        self.buttonPassiveAggressiveOneVsAllLogisticRegression.grid(row=3,
                                                                    column=1)
        self.labelTitle.grid(row=4, columnspan=2)

    def openFileDialog(self):
        self.filename = filedialog.askopenfilename(
            initialdir="/",
            title="Select file",
            filetypes=(("txt files", "*.txt"), ("all files", "*.*")))
        self.labelForFile['text'] = self.filename

    def drawFigure(self, fig):
        if self.canvas is not None:
            self.canvas.get_tk_widget().destroy()
        self.canvas = FigureCanvasTkAgg(fig, master=self.window)
        self.canvas.get_tk_widget().grid(row=5, columnspan=2)
        self.canvas.draw()
        PlotInWindow.fig = Figure()

    def plotPerceptron(self):
        PlotInWindow.fig = Figure()
        self.labelTitle["text"] = "Perceptron Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "perceptron")
        fig = Perceptron.perceptronPlotInWindow(file)
        self.drawFigure(fig)

    def plotLogisticRegression(self):
        PlotInWindow.fig = Figure()
        self.labelTitle["text"] = "Logistic Regression Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "logistic")
        fig = LogisticRegression.logisticRegressionPlotInWindow(file)
        self.drawFigure(fig)

    def plotPassiveAggressive(self):
        PlotInWindow.fig = Figure()
        self.labelTitle["text"] = "Passive Aggresive Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "passiveAggressive")
        fig = PassiveAggressiveAlgorithm.passiveAggressivePlotInWindow(file)
        self.drawFigure(fig)

    def plotMulticlassOneVsAllPerceptron(self):
        PlotInWindow.fig = Figure()
        self.labelTitle[
            "text"] = "Multiclass One Vs ALL - Perceptron Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "multiclassPerceptron")
        fig = MulticlassOneVsAll.oneVsAllPerceptronExample(file)
        canvas = FigureCanvasTkAgg(fig, master=self.window)
        canvas.get_tk_widget().grid(row=5, columnspan=2)
        canvas.draw()

    def plotMulticlassOneVsAllLogisticRegression(self):
        PlotInWindow.fig = Figure()
        self.labelTitle[
            "text"] = "Multiclass One Vs ALL -Logistic Regression Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "multiclassLogistic")
        fig = MulticlassOneVsAll.oneVsAllLogisticRegressionExample(file)
        canvas = FigureCanvasTkAgg(fig, master=self.window)
        canvas.get_tk_widget().grid(row=5, columnspan=2)
        canvas.draw()

    def plotMulticlassOneVsAllPassiveAggressive(self):
        PlotInWindow.fig = Figure()
        self.labelTitle[
            "text"] = "Multiclass One Vs ALL -Logistic Regression Algorithm"
        file = self.labelForFile["text"]
        file = ReadingFromFile.checkFile(file, "multiclassPassiveAggressive")
        fig = MulticlassOneVsAll.oneVsAllPassiveAggressiveExample(file)
        canvas = FigureCanvasTkAgg(fig, master=self.window)
        canvas.get_tk_widget().grid(row=5, columnspan=2)
        canvas.draw()
Example #54
0
    def init_window(self):
        self.master.title("Main Window")
        screenWidth = self.master.winfo_screenwidth()
        screenHeight = self.master.winfo_screenheight()
        self.master.geometry("{0}x{1}".format(screenWidth, screenHeight))

        canvasWidth = 900
        stdHeight = 60
        stdWidth = 200
        stdFont = "TkDefaultFont"
        userFont = 24
        btnFont = 20

        fileManager.checkConfig()
        self.coffeePrice, self.milkPrice, self.adminHash, isDefault = fileManager.readConfig(
        )
        if isinstance(self.coffeePrice, str):
            self.coffeePrice = int(self.coffeePrice)
        if isinstance(self.milkPrice, str):
            self.milkPrice = int(self.milkPrice)
        if isinstance(self.adminHash, str):
            self.adminHash = int(self.adminHash)

        def addName():
            dialog = keyboard.KeyboardGUI(self, app, "user")
            root.wait_window(dialog)
            if len(self.newUser) > 0:
                updateList(self, self.newUser)
            self.newUser = ""
            fileManager.backup(self.memberDict, self.milkDict)

        def addAmount():
            dialog = numPad.NumPad(self, app, "user")
            root.wait_window(dialog)
            if self.newVal != None:
                updateLabel(self, self.newVal, self.selectedUser)
            self.newVal = None
            self.selectedUser = ""
            fileManager.backup(self.memberDict, self.milkDict)

        def drawPlot():
            plotterObject.update_values()
            coffees = plotterObject.coffees
            hours = plotterObject.hours
            plotFigure = plotter.makePlot(coffees, hours)
            barChartCanvas = FigureCanvasTkAgg(plotFigure, master=root)
            barChartCanvas.draw()
            barChartCanvas.get_tk_widget().place(height=figHeightPx,
                                                 width=figWidthPx,
                                                 anchor='se',
                                                 relx=1.0,
                                                 rely=0.8)

        def getFigWidth():
            figWidthPx = round((screenWidth - canvasWidth) * 0.8, 0)
            mmPerPx = self.master.winfo_screenmmwidth() / screenWidth
            inPer_mm = 0.039
            figWidthInches = round(figWidthPx * mmPerPx * inPer_mm, 1)
            return figWidthInches

        def getCanvasX():
            return round((screenWidth - canvasWidth) * 0.1, 0)

        def initScrollableCanvas():
            container = ttk.Frame(root)
            canvas = tk.Canvas(container)
            scrollbar = ttk.Scrollbar(container,
                                      orient="vertical",
                                      command=canvas.yview)
            scrollable_frame = ttk.Frame(canvas)
            scrollable_frame.bind(
                "<Configure>",
                lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

            canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
            canvas.configure(yscrollcommand=scrollbar.set)
            canvas.pack(side="left", fill="both", expand="True")
            scrollbar.pack(side="right", fill="y")
            upperCorner = getCanvasX()
            container.place(relheight=0.85,
                            width=canvasWidth,
                            anchor="nw",
                            x=upperCorner,
                            y=10)
            return canvas, scrollable_frame, scrollbar

        def initAnimation():
            animationFrames = [
                tk.PhotoImage(file='coffeeAnimation2.gif',
                              format='gif -index {0}'.format(i))
                for i in range(4)
            ]
            animationLabel = tk.Label(root)
            animationLabel.place(height=250,
                                 width=200,
                                 anchor='ne',
                                 relx=1.0,
                                 rely=0)
            return animationFrames, animationLabel

        def openAdminWindow():
            isAdmin = checkAdminPassword()
            #isAdmin=True #for testing
            if isAdmin:
                dialog = AdminWindow(self, app)
                root.wait_window(dialog)
                if self.adminPass != "":
                    self.adminHash = passHash(self.adminPass)
                    self.adminPass = ""
                fileManager.updateConfig(coffeePrice=self.coffeePrice,
                                         milkPrice=self.milkPrice,
                                         adminPass=self.adminHash)
            else:
                tk.messagebox.showinfo("Info", "Incorrect password")

        def checkAdminPassword():
            dialog = keyboard.KeyboardGUI(self, app, "admin")
            root.wait_window(dialog)
            isAdmin = (passHash(self.adminPass) == self.adminHash)
            self.adminPass = ""
            return isAdmin

        def buyCoffee(name):
            balance = self.memberDict.get(name)
            milk = self.milkDict.get(name)
            if balance != None:
                balance = balance - self.coffeePrice - self.milkPrice * milk
                self.memberDict[name] = balance
                getattr(self, 'balance_{0}'.format(name)).configure(
                    text='{:.2f}'.format(balance / 100))
            self.backupCounter = (self.backupCounter + 1) % 15
            if self.backupCounter == 0:
                fileManager.backup(self.memberDict, self.milkDict)
            drawPlot()

        def updateMilk(name):
            milkVal = self.milkDict[name]
            newVal = (milkVal + 1) % 2
            self.milkDict[name] = newVal

        def makeNameLabel(name):
            nameLabel = tk.Label(root, text="")
            nameLabel.configure(text="{0}".format(name),
                                font=(stdFont, userFont))
            return nameLabel

        def makeBalanceLabel(name):
            balanceLabel = tk.Label(root, text="")
            balanceLabel.configure(text='{:.2f}'.format(self.memberDict[name] /
                                                        100))
            balanceLabel.configure(font=(stdFont, userFont))
            setattr(self, 'balance_{0}'.format(name), balanceLabel)
            return balanceLabel

        def makeMilkCheck(name):
            milkCheck = tk.Checkbutton(
                root,
                text="with milk",
                command=lambda milkName=name: updateMilk(milkName))
            if self.milkDict[name] == 1:
                milkCheck.toggle()
            milkCheck.configure(font=(stdFont, btnFont))
            return milkCheck

        def makeBuyBtn(name):
            buy_btn = tk.Button(
                root,
                text="Buy a coffee",
                command=lambda nameVal=name: buyCoffee(nameVal))
            buy_btn.configure(font=(stdFont, btnFont))
            return buy_btn

        def updateList(self, newName):
            if newName != None:
                self.memberDict[str(newName)] = 0
                self.milkDict[str(newName)] = 0
            orderedList = sorted(self.memberDict)
            yOffset = 0
            button_x = 600
            canvas.delete("all")
            canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
            for name in orderedList:
                nameLabel = makeNameLabel(name)
                nameLabel_window = canvas.create_window((0, yOffset),
                                                        anchor="nw",
                                                        window=nameLabel)
                balanceLabel = makeBalanceLabel(name)
                balance_window = canvas.create_window((2 * stdWidth, yOffset),
                                                      anchor="nw",
                                                      window=balanceLabel)
                milkCheck = makeMilkCheck(name)
                milkCheck_window = canvas.create_window((button_x, yOffset),
                                                        anchor="nw",
                                                        window=milkCheck)
                buy_btn = makeBuyBtn(name)
                buy_btn_window = canvas.create_window(
                    (button_x, yOffset + stdHeight),
                    anchor="nw",
                    window=buy_btn)
                if yOffset != 0:
                    lineY = yOffset - 10
                    canvas.create_line(0, lineY, 800, lineY, fill="blue")
                yOffset += 2 * stdHeight
            canvas.configure(yscrollcommand=scrollbar.set)

        def updateLabel(self, amount, name):
            balance = self.memberDict.get(name)
            if balance != None:
                balance += amount
                self.memberDict[name] = balance
                getattr(self, 'balance_{0}'.format(name)).configure(
                    text='{:.2f}'.format(balance / 100))

        def removeUser():
            if len(self.memberDict) == 0:
                msg = "No users to remove!"
                tk.messagebox.showinfo("Error!", msg)
            else:
                dialog = delUserWindow.DelUserWindow(self, app)
                root.wait_window(dialog)
                if len(self.selectedUser) != 0:
                    del self.memberDict[self.selectedUser]
                    updateList(self, None)
                    self.selectedUser = ""

        def animate(index):
            index = index % 4
            frame = animationFrames[index]
            animationLabel.configure(image=frame)
            root.after(200, animate, index + 1)

        def export():
            fileManager.export(self.memberDict, self.milkDict)
            root.destroy()

        figWidth = getFigWidth()
        figHeight = round(figWidth / 1.6, 1)
        self.plotFigure = Figure(figsize=(figWidth, figHeight))
        plotterObject = plotter.Plotter()
        coffees = plotterObject.coffees
        hours = plotterObject.hours
        plotFigure = plotter.makePlot(coffees, hours)
        barChartCanvas = FigureCanvasTkAgg(plotFigure, master=root)
        barChartCanvas.draw()
        figWidthPx = round((screenWidth - canvasWidth) * 0.8, 1)
        figHeightPx = round((figWidthPx / 1.6), 1)
        barChartCanvas.get_tk_widget().place(height=figHeightPx,
                                             width=figWidthPx,
                                             anchor='se',
                                             relx=1.0,
                                             rely=0.8)

        canvas, scrollable_frame, scrollbar = initScrollableCanvas()
        animationFrames, animationLabel = initAnimation()

        nameBtn = tk.Button(root, text="Add User", command=addName)
        nameBtn.configure(font=(stdFont, btnFont))
        nameBtn.place(height=stdHeight,
                      width=stdWidth,
                      anchor="sw",
                      x=10,
                      rely=0.98)

        removeBtn = tk.Button(root, text="Remove User", command=removeUser)
        removeBtn.configure(font=(stdFont, btnFont))
        removeBtn.place(height=stdHeight,
                        width=stdWidth,
                        anchor="sw",
                        x=stdWidth + 40,
                        rely=0.98)

        paymentBtn = tk.Button(root, text="Make Payment", command=addAmount)
        paymentBtn.configure(font=(stdFont, btnFont))
        paymentBtn.place(height=stdHeight,
                         width=stdWidth + 20,
                         anchor="sw",
                         x=2 * stdWidth + 70,
                         rely=0.98)

        adminBtn = tk.Button(root, text="Admin...", command=openAdminWindow)
        adminBtn.configure(font=(stdFont, btnFont))
        adminBtn.place(height=stdHeight,
                       width=stdWidth,
                       anchor="se",
                       relx=0.98,
                       rely=0.98)

        try:
            self.memberDict, self.milkDict = fileManager.openList()
            updateList(self, None)
        except IOError as e:
            tk.messagebox.showinfo("Warning", "Did not find list to read from")
            self.memberDict = {}
            self.milkDict = {}

        if isDefault:
            msg = "Welcome to the coffee list! You are currently using the default admin password 'coffeeTime!'. \nYou can change the password in the 'Admin' dialog."
            tk.messagebox.showinfo("Info", msg)

        root.after(200, animate, 0)
        root.protocol("WM_DELETE_WINDOW", export)
Example #55
0

def stop_ani():
    global stoppage
    if not stoppage:
        stoppage = True
        ani.event_source.stop()
    else:
        stoppage = False
        ani.event_source.start()


root = Tk.Tk()

label = Tk.Label(root, text="SHM Simulation").grid(column=0, row=0)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=0, row=1)

ax = fig.add_subplot(111)
line, = ax.plot(x, np.sin(x))
ani = animation.FuncAnimation(fig,
                              animate,
                              np.arange(1, 200),
                              interval=25,
                              blit=False)

button = Tk.Button(root, text='stop', command=stop_ani)
button.grid(row=2, column=0)

Tk.mainloop()
    def __init__(self, top=None, goatData=[]):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9'  # X11 color: 'gray85'
        _ana1color = '#d9d9d9'  # X11 color: 'gray85'
        _ana2color = '#ececec'  # Closest X11 color: 'gray92'
        font10 = "-family {Segoe UI} -size 13"
        font12 = "-family {Segoe UI} -size 16 -weight bold"
        font13 = "-family {Segoe UI Semibold} -size 13 -weight bold"
        font9 = "-family {Segoe UI} -size 20 -weight bold"

        top.geometry("1300x760+20+20")
        top.minsize(800, 500)
        top.maxsize(1800, 850)
        top.resizable(1, 1)
        top.title("View")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.goatData = goatData
        self.db = DataBase()

        self.Button0 = tk.Button(top, command=destroy_Toplevel1)
        self.Button0.place(x=10, y=8, height=33, width=56)
        self.Button0.configure(activebackground="#ececec")
        self.Button0.configure(activeforeground="#000000")
        self.Button0.configure(background="#d9d9d9")
        self.Button0.configure(disabledforeground="#a3a3a3")
        self.Button0.configure(foreground="#000000")
        self.Button0.configure(highlightbackground="#d9d9d9")
        self.Button0.configure(highlightcolor="black")
        self.Button0.configure(pady="0")
        self.Button0.configure(text='''< Back''')

        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.416, rely=0.0, height=52, width=173)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(font=font9)
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''About Goat''')

        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.051, rely=0.017, height=52, width=112)
        self.Label2.configure(activebackground="#f9f9f9")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(font=("font10", 10))
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#d9d9d9")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text='''Goat ID''')

        self.Label2_1 = tk.Label(top)
        self.Label2_1.place(relx=0.051, rely=0.072, height=52, width=112)
        self.Label2_1.configure(activebackground="#f9f9f9")
        self.Label2_1.configure(activeforeground="black")
        self.Label2_1.configure(background="#d9d9d9")
        self.Label2_1.configure(disabledforeground="#a3a3a3")
        self.Label2_1.configure(font=("font10", 10))
        self.Label2_1.configure(foreground="#000000")
        self.Label2_1.configure(highlightbackground="#d9d9d9")
        self.Label2_1.configure(highlightcolor="black")
        self.Label2_1.configure(text='''Breed''')

        self.Label2_2 = tk.Label(top)
        self.Label2_2.place(relx=0.051, rely=0.134, height=40, width=112)
        self.Label2_2.configure(activebackground="#f9f9f9")
        self.Label2_2.configure(activeforeground="black")
        self.Label2_2.configure(background="#d9d9d9")
        self.Label2_2.configure(disabledforeground="#a3a3a3")
        self.Label2_2.configure(font=("font10", 10))
        self.Label2_2.configure(foreground="#000000")
        self.Label2_2.configure(highlightbackground="#d9d9d9")
        self.Label2_2.configure(highlightcolor="black")
        self.Label2_2.configure(text='''DOB''')

        self.Label2_3 = tk.Label(top)
        self.Label2_3.place(relx=0.051, rely=0.177, height=53, width=112)
        self.Label2_3.configure(activebackground="#f9f9f9")
        self.Label2_3.configure(activeforeground="black")
        self.Label2_3.configure(background="#d9d9d9")
        self.Label2_3.configure(disabledforeground="#a3a3a3")
        self.Label2_3.configure(font=("font10", 10))
        self.Label2_3.configure(foreground="#000000")
        self.Label2_3.configure(highlightbackground="#d9d9d9")
        self.Label2_3.configure(highlightcolor="black")
        self.Label2_3.configure(text='''Gender''')

        self.Label2_4 = tk.Label(top)
        self.Label2_4.place(relx=0.071, rely=0.300, height=52, width=266)
        self.Label2_4.configure(activebackground="#f9f9f9")
        self.Label2_4.configure(activeforeground="black")
        self.Label2_4.configure(background="#d9d9d9")
        self.Label2_4.configure(disabledforeground="#a3a3a3")
        self.Label2_4.configure(font=font12)
        self.Label2_4.configure(foreground="#000000")
        self.Label2_4.configure(highlightbackground="#d9d9d9")
        self.Label2_4.configure(highlightcolor="black")
        self.Label2_4.configure(text='''Last Vaccinated Date''')

        self.Text1 = tk.Text(top)
        self.Text1.place(relx=0.152,
                         rely=0.025,
                         relheight=0.036,
                         relwidth=0.139)
        self.Text1.configure(background="white")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="#c4c4c4")
        self.Text1.configure(selectforeground="black")
        self.Text1.configure(wrap="word")

        self.Text1_12 = tk.Text(top)
        self.Text1_12.place(relx=0.152,
                            rely=0.080,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_12.configure(background="white")
        self.Text1_12.configure(font="TkTextFont")
        self.Text1_12.configure(foreground="black")
        self.Text1_12.configure(highlightbackground="#d9d9d9")
        self.Text1_12.configure(highlightcolor="black")
        self.Text1_12.configure(insertbackground="black")
        self.Text1_12.configure(selectbackground="#c4c4c4")
        self.Text1_12.configure(selectforeground="black")
        self.Text1_12.configure(wrap="word")

        self.Text1_12.insert(END, self.goatData[4])

        self.Text1_13 = tk.Text(top)
        self.Text1_13.place(relx=0.152,
                            rely=0.137,
                            relheight=0.035,
                            relwidth=0.139)
        self.Text1_13.configure(background="white")
        self.Text1_13.configure(font="TkTextFont")
        self.Text1_13.configure(foreground="black")
        self.Text1_13.configure(highlightbackground="#d9d9d9")
        self.Text1_13.configure(highlightcolor="black")
        self.Text1_13.configure(insertbackground="black")
        self.Text1_13.configure(selectbackground="#c4c4c4")
        self.Text1_13.configure(selectforeground="black")
        self.Text1_13.configure(wrap="word")

        self.Text1_13.insert(END, self.goatData[2])

        self.Text1_14 = tk.Text(top)
        self.Text1_14.place(relx=0.152,
                            rely=0.190,
                            relheight=0.035,
                            relwidth=0.139)
        self.Text1_14.configure(background="white")
        self.Text1_14.configure(font="TkTextFont")
        self.Text1_14.configure(foreground="black")
        self.Text1_14.configure(highlightbackground="#d9d9d9")
        self.Text1_14.configure(highlightcolor="black")
        self.Text1_14.configure(insertbackground="black")
        self.Text1_14.configure(selectbackground="#c4c4c4")
        self.Text1_14.configure(selectforeground="black")
        self.Text1_14.configure(wrap="word")

        self.Text1_14.insert(END, self.goatData[3])

        self.Text1_15 = tk.Text(top)
        self.Text1_15.place(relx=0.159,
                            rely=0.405,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_15.configure(background="white")
        self.Text1_15.configure(font="TkTextFont")
        self.Text1_15.configure(foreground="black")
        self.Text1_15.configure(highlightbackground="#d9d9d9")
        self.Text1_15.configure(highlightcolor="black")
        self.Text1_15.configure(insertbackground="black")
        self.Text1_15.configure(selectbackground="#c4c4c4")
        self.Text1_15.configure(selectforeground="black")
        self.Text1_15.configure(wrap="word")

        self.Text1_15.insert(END, self.goatData[11])

        self.Text1_16 = tk.Text(top)
        self.Text1_16.place(relx=0.159,
                            rely=0.475,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_16.configure(background="white")
        self.Text1_16.configure(font="TkTextFont")
        self.Text1_16.configure(foreground="black")
        self.Text1_16.configure(highlightbackground="#d9d9d9")
        self.Text1_16.configure(highlightcolor="black")
        self.Text1_16.configure(insertbackground="black")
        self.Text1_16.configure(selectbackground="#c4c4c4")
        self.Text1_16.configure(selectforeground="black")
        self.Text1_16.configure(wrap="word")

        self.Text1_16.insert(END, self.goatData[12])

        self.Text1_17 = tk.Text(top)
        self.Text1_17.place(relx=0.159,
                            rely=0.540,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_17.configure(background="white")
        self.Text1_17.configure(font="TkTextFont")
        self.Text1_17.configure(foreground="black")
        self.Text1_17.configure(highlightbackground="#d9d9d9")
        self.Text1_17.configure(highlightcolor="black")
        self.Text1_17.configure(insertbackground="black")
        self.Text1_17.configure(selectbackground="#c4c4c4")
        self.Text1_17.configure(selectforeground="black")
        self.Text1_17.configure(wrap="word")

        self.Text1_17.insert(END, self.goatData[13])

        self.Text1_18 = tk.Text(top)
        self.Text1_18.place(relx=0.159,
                            rely=0.600,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_18.configure(background="white")
        self.Text1_18.configure(font="TkTextFont")
        self.Text1_18.configure(foreground="black")
        self.Text1_18.configure(highlightbackground="#d9d9d9")
        self.Text1_18.configure(highlightcolor="black")
        self.Text1_18.configure(insertbackground="black")
        self.Text1_18.configure(selectbackground="#c4c4c4")
        self.Text1_18.configure(selectforeground="black")
        self.Text1_18.configure(wrap="word")

        self.Text1_18.insert(END, self.goatData[14])

        self.Text1_19 = tk.Text(top)
        self.Text1_19.place(relx=0.159,
                            rely=0.665,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_19.configure(background="white")
        self.Text1_19.configure(font="TkTextFont")
        self.Text1_19.configure(foreground="black")
        self.Text1_19.configure(highlightbackground="#d9d9d9")
        self.Text1_19.configure(highlightcolor="black")
        self.Text1_19.configure(insertbackground="black")
        self.Text1_19.configure(selectbackground="#c4c4c4")
        self.Text1_19.configure(selectforeground="black")
        self.Text1_19.configure(wrap="word")

        self.Text1_19.insert(END, self.goatData[15])

        self.Text1_20 = tk.Text(top)
        self.Text1_20.place(relx=0.159,
                            rely=0.730,
                            relheight=0.036,
                            relwidth=0.139)
        self.Text1_20.configure(background="white")
        self.Text1_20.configure(font="TkTextFont")
        self.Text1_20.configure(foreground="black")
        self.Text1_20.configure(highlightbackground="#d9d9d9")
        self.Text1_20.configure(highlightcolor="black")
        self.Text1_20.configure(insertbackground="black")
        self.Text1_20.configure(selectbackground="#c4c4c4")
        self.Text1_20.configure(selectforeground="black")
        self.Text1_20.configure(wrap="word")
        self.Text1_20.insert(END, self.goatData[16])

        self.Text205 = tk.Text(top)
        self.Text205.place(relx=0.159,
                           rely=0.800,
                           relheight=0.036,
                           relwidth=0.139)
        self.Text205.configure(background="white")
        self.Text205.configure(font="TkTextFont")
        self.Text205.configure(foreground="black")
        self.Text205.configure(highlightbackground="#d9d9d9")
        self.Text205.configure(highlightcolor="black")
        self.Text205.configure(insertbackground="black")
        self.Text205.configure(selectbackground="#c4c4c4")
        self.Text205.configure(selectforeground="black")
        self.Text205.configure(wrap="word")
        self.Text205.insert(END, self.goatData[17])

        self.Text305 = tk.Text(top)
        self.Text305.place(relx=0.159,
                           rely=0.865,
                           relheight=0.036,
                           relwidth=0.139)
        self.Text305.configure(background="white")
        self.Text305.configure(font="TkTextFont")
        self.Text305.configure(foreground="black")
        self.Text305.configure(highlightbackground="#d9d9d9")
        self.Text305.configure(highlightcolor="black")
        self.Text305.configure(insertbackground="black")
        self.Text305.configure(selectbackground="#c4c4c4")
        self.Text305.configure(selectforeground="black")
        self.Text305.configure(wrap="word")
        self.Text305.insert(END, self.goatData[18])

        self.Canvas1 = tk.Text(top)
        self.Canvas1.place(relx=0.159,
                           rely=0.927,
                           relheight=0.049,
                           relwidth=0.138)
        self.Canvas1.configure(background="white")
        self.Canvas1.configure(font="TkTextFont")
        self.Canvas1.configure(foreground="black")
        self.Canvas1.configure(highlightbackground="#d9d9d9")
        self.Canvas1.configure(highlightcolor="black")
        self.Canvas1.configure(insertbackground="black")
        self.Canvas1.configure(selectbackground="#c4c4c4")
        self.Canvas1.configure(selectforeground="black")
        self.Canvas1.configure(wrap="word")

        self.Frame2 = tk.Frame(top)
        self.Frame2.place(relx=0.599,
                          rely=0.075,
                          relheight=0.92,
                          relwidth=0.39)
        self.Frame2.configure(relief='groove')
        self.Frame2.configure(borderwidth="2")
        self.Frame2.configure(relief="groove")
        self.Frame2.configure(background="#d9d9d9")
        self.Frame2.configure(highlightbackground="#d9d9d9")
        self.Frame2.configure(highlightcolor="black")

        self.Label2_00 = tk.Label(self.Frame2)
        self.Label2_00.place(relx=0.1, rely=0.066, height=52, width=141)
        self.Label2_00.configure(activebackground="#f9f9f9")
        self.Label2_00.configure(activeforeground="black")
        self.Label2_00.configure(background="#d9d9d9")
        self.Label2_00.configure(disabledforeground="#a3a3a3")
        self.Label2_00.configure(font=font10)
        self.Label2_00.configure(foreground="#000000")
        self.Label2_00.configure(highlightbackground="#d9d9d9")
        self.Label2_00.configure(highlightcolor="black")
        self.Label2_00.configure(text='''Pregnant''')

        self.Canvas2 = tk.Text(self.Frame2)
        self.Canvas2.place(relx=0.469,
                           rely=0.066,
                           relheight=0.055,
                           relwidth=0.346)
        self.Canvas2.configure(background="white")
        self.Canvas2.configure(font="TkTextFont")
        self.Canvas2.configure(foreground="black")
        self.Canvas2.configure(highlightbackground="#d9d9d9")
        self.Canvas2.configure(highlightcolor="black")
        self.Canvas2.configure(insertbackground="black")
        self.Canvas2.configure(selectbackground="#c4c4c4")
        self.Canvas2.configure(selectforeground="black")
        self.Canvas2.configure(wrap="word")

        self.Label2_7 = tk.Label(self.Frame2)
        self.Label2_7.place(relx=0.25, rely=0.15, height=51, width=174)
        self.Label2_7.configure(activebackground="#f9f9f9")
        self.Label2_7.configure(activeforeground="black")
        self.Label2_7.configure(background="#d9d9d9")
        self.Label2_7.configure(disabledforeground="#a3a3a3")
        self.Label2_7.configure(font=font13)
        self.Label2_7.configure(foreground="#000000")
        self.Label2_7.configure(highlightbackground="#d9d9d9")
        self.Label2_7.configure(highlightcolor="black")
        self.Label2_7.configure(text='''Kid Details''')

        self.Label2_8 = tk.Label(self.Frame2)
        self.Label2_8.place(relx=0.1, rely=0.24, height=50, width=140)
        self.Label2_8.configure(activebackground="#f9f9f9")
        self.Label2_8.configure(activeforeground="black")
        self.Label2_8.configure(background="#d9d9d9")
        self.Label2_8.configure(disabledforeground="#a3a3a3")
        self.Label2_8.configure(font=font10)
        self.Label2_8.configure(foreground="#000000")
        self.Label2_8.configure(highlightbackground="#d9d9d9")
        self.Label2_8.configure(highlightcolor="black")
        self.Label2_8.configure(text='''No of Male Kids''')

        self.Text2_9 = tk.Text(self.Frame2)
        self.Text2_9.place(relx=0.469,
                           rely=0.25,
                           relheight=0.055,
                           relwidth=0.346)
        self.Text2_9.configure(background="white")
        self.Text2_9.configure(font="TkTextFont")
        self.Text2_9.configure(foreground="black")
        self.Text2_9.configure(highlightbackground="#d9d9d9")
        self.Text2_9.configure(highlightcolor="black")
        self.Text2_9.configure(insertbackground="black")
        self.Text2_9.configure(selectbackground="#c4c4c4")
        self.Text2_9.configure(selectforeground="black")
        self.Text2_9.configure(wrap="word")
        self.Text2_9.insert(END, self.goatData[8])

        self.Label2_6 = tk.Label(self.Frame2)
        self.Label2_6.place(relx=0.1, rely=0.34, height=50, width=141)
        self.Label2_6.configure(activebackground="#f9f9f9")
        self.Label2_6.configure(activeforeground="black")
        self.Label2_6.configure(background="#d9d9d9")
        self.Label2_6.configure(disabledforeground="#a3a3a3")
        self.Label2_6.configure(font=font10)
        self.Label2_6.configure(foreground="#000000")
        self.Label2_6.configure(highlightbackground="#d9d9d9")
        self.Label2_6.configure(highlightcolor="black")
        self.Label2_6.configure(text='''No of Female Kids''')

        self.Text2 = tk.Text(self.Frame2)
        self.Text2.place(relx=0.469,
                         rely=0.35,
                         relheight=0.055,
                         relwidth=0.346)
        self.Text2.configure(background="white")
        self.Text2.configure(font="TkTextFont")
        self.Text2.configure(foreground="black")
        self.Text2.configure(highlightbackground="#d9d9d9")
        self.Text2.configure(highlightcolor="black")
        self.Text2.configure(insertbackground="black")
        self.Text2.configure(selectbackground="#c4c4c4")
        self.Text2.configure(selectforeground="black")
        self.Text2.configure(wrap="word")
        self.Text2.insert(END, self.goatData[9])

        self.Frame3 = tk.Frame(self.Frame2)
        self.Frame3.place(relx=0.234,
                          rely=0.525,
                          relheight=0.442,
                          relwidth=0.612)
        self.Frame3.configure(relief='groove')
        self.Frame3.configure(borderwidth="2")
        self.Frame3.configure(relief="groove")
        self.Frame3.configure(background="#d9d9d9")

        self.tree3 = ttk.Treeview(self.Frame3)
        self.tree3.place(relx=0.00, rely=0.00, height=300, width=310)
        self.tree3["columns"] = ("#0", "#1", "#2", "#3")
        self.tree3.column("#0", width=50, stretch=True, anchor='center')
        self.tree3.column("#1", width=80, stretch=True, anchor='center')
        self.tree3.column("#2", width=80, stretch=True, anchor='center')
        self.tree3.column("#3", width=80, stretch=True, anchor='center')
        self.tree3.heading("#0", text="S.NO")
        self.tree3.heading("#1", text="MOTHER ID")
        self.tree3.heading("#2", text="KID ID")
        self.tree3.heading("#3", text="GENDER")

        self.Label2_1 = tk.Label(top)
        self.Label2_1.place(relx=0.041, rely=0.390, height=53, width=113)
        self.Label2_1.configure(activebackground="#f9f9f9")
        self.Label2_1.configure(activeforeground="black")
        self.Label2_1.configure(background="#d9d9d9")
        self.Label2_1.configure(disabledforeground="#a3a3a3")
        self.Label2_1.configure(font=("font10", 10))
        self.Label2_1.configure(foreground="#000000")
        self.Label2_1.configure(highlightbackground="#d9d9d9")
        self.Label2_1.configure(highlightcolor="black")
        self.Label2_1.configure(text='''Anthrax''')

        self.Label2_2 = tk.Label(top)
        self.Label2_2.place(relx=0.011, rely=0.460, height=52, width=195)
        self.Label2_2.configure(activebackground="#f9f9f9")
        self.Label2_2.configure(activeforeground="black")
        self.Label2_2.configure(background="#d9d9d9")
        self.Label2_2.configure(disabledforeground="#a3a3a3")
        self.Label2_2.configure(font=("font10", 10))
        self.Label2_2.configure(foreground="#000000")
        self.Label2_2.configure(highlightbackground="#d9d9d9")
        self.Label2_2.configure(highlightcolor="black")
        self.Label2_2.configure(text='''Haemorrhagic Septicemia(H.S)''')

        self.Label2_3 = tk.Label(top)
        self.Label2_3.place(relx=0.041, rely=0.530, height=53, width=113)
        self.Label2_3.configure(activebackground="#f9f9f9")
        self.Label2_3.configure(activeforeground="black")
        self.Label2_3.configure(background="#d9d9d9")
        self.Label2_3.configure(disabledforeground="#a3a3a3")
        self.Label2_3.configure(font=("font10", 10))
        self.Label2_3.configure(foreground="#000000")
        self.Label2_3.configure(highlightbackground="#d9d9d9")
        self.Label2_3.configure(highlightcolor="black")
        self.Label2_3.configure(text='''Enterotoxaemia''')

        self.Label2_5 = tk.Label(top)
        self.Label2_5.place(relx=0.041, rely=0.590, height=52, width=114)
        self.Label2_5.configure(activebackground="#f9f9f9")
        self.Label2_5.configure(activeforeground="black")
        self.Label2_5.configure(background="#d9d9d9")
        self.Label2_5.configure(disabledforeground="#a3a3a3")
        self.Label2_5.configure(font=("font10", 10))
        self.Label2_5.configure(foreground="#000000")
        self.Label2_5.configure(highlightbackground="#d9d9d9")
        self.Label2_5.configure(highlightcolor="black")
        self.Label2_5.configure(text='''Black Quarter''')

        self.Label2_5 = tk.Label(top)
        self.Label2_5.place(relx=0.011, rely=0.655, height=52, width=195)
        self.Label2_5.configure(activebackground="#f9f9f9")
        self.Label2_5.configure(activeforeground="black")
        self.Label2_5.configure(background="#d9d9d9")
        self.Label2_5.configure(disabledforeground="#a3a3a3")
        self.Label2_5.configure(font=("font10", 10))
        self.Label2_5.configure(foreground="#000000")
        self.Label2_5.configure(highlightbackground="#d9d9d9")
        self.Label2_5.configure(highlightcolor="black")
        self.Label2_5.configure(text='''P.P.R.''')

        self.Label2_5 = tk.Label(top)
        self.Label2_5.place(relx=0.011, rely=0.720, height=52, width=180)
        self.Label2_5.configure(activebackground="#f9f9f9")
        self.Label2_5.configure(activeforeground="black")
        self.Label2_5.configure(background="#d9d9d9")
        self.Label2_5.configure(disabledforeground="#a3a3a3")
        self.Label2_5.configure(font=("font10", 10))
        self.Label2_5.configure(foreground="#000000")
        self.Label2_5.configure(highlightbackground="#d9d9d9")
        self.Label2_5.configure(highlightcolor="black")
        self.Label2_5.configure(text='''Foot and Mouth Disease''')

        self.label205 = tk.Label(top)
        self.label205.place(relx=0.041, rely=0.790, height=52, width=113)
        self.label205.configure(activebackground="#f9f9f9")
        self.label205.configure(activeforeground="black")
        self.label205.configure(background="#d9d9d9")
        self.label205.configure(disabledforeground="#a3a3a3")
        self.label205.configure(font=("font10", 10))
        self.label205.configure(foreground="#000000")
        self.label205.configure(highlightbackground="#d9d9d9")
        self.label205.configure(highlightcolor="black")
        self.label205.configure(text='''Goat Pox''')

        self.label305 = tk.Label(top)
        self.label305.place(relx=0.041, rely=0.860, height=52, width=113)
        self.label305.configure(activebackground="#f9f9f9")
        self.label305.configure(activeforeground="black")
        self.label305.configure(background="#d9d9d9")
        self.label305.configure(disabledforeground="#a3a3a3")
        self.label305.configure(font=("font10", 10))
        self.label305.configure(foreground="#000000")
        self.label305.configure(highlightbackground="#d9d9d9")
        self.label305.configure(highlightcolor="black")
        self.label305.configure(text='''C.C.P.P''')

        self.Label2_5 = tk.Label(top)
        self.Label2_5.place(relx=0.051, rely=0.923, height=52, width=93)
        self.Label2_5.configure(activebackground="#f9f9f9")
        self.Label2_5.configure(activeforeground="black")
        self.Label2_5.configure(background="#d9d9d9")
        self.Label2_5.configure(disabledforeground="#a3a3a3")
        self.Label2_5.configure(font=font13)
        self.Label2_5.configure(foreground="#000000")
        self.Label2_5.configure(highlightbackground="#d9d9d9")
        self.Label2_5.configure(highlightcolor="black")
        self.Label2_5.configure(text='''Mortality''')

        self.Label2_5 = tk.Label(top)
        self.Label2_5.place(relx=0.051, rely=0.238, height=52, width=113)
        self.Label2_5.configure(activebackground="#f9f9f9")
        self.Label2_5.configure(activeforeground="black")
        self.Label2_5.configure(background="#d9d9d9")
        self.Label2_5.configure(disabledforeground="#a3a3a3")
        self.Label2_5.configure(font=("font10", 10))
        self.Label2_5.configure(foreground="#000000")
        self.Label2_5.configure(highlightbackground="#d9d9d9")
        self.Label2_5.configure(highlightcolor="black")
        self.Label2_5.configure(text='''Weight''')

        self.Text1_5 = tk.Text(top)
        self.Text1_5.place(relx=0.152,
                           rely=0.250,
                           relheight=0.036,
                           relwidth=0.139)
        self.Text1_5.configure(background="white")
        self.Text1_5.configure(font="TkTextFont")
        self.Text1_5.configure(foreground="black")
        self.Text1_5.configure(highlightbackground="#d9d9d9")
        self.Text1_5.configure(highlightcolor="black")
        self.Text1_5.configure(insertbackground="black")
        self.Text1_5.configure(selectbackground="#c4c4c4")
        self.Text1_5.configure(selectforeground="black")
        self.Text1_5.configure(wrap="word")

        self.Text1_5.insert(END, self.goatData[5])

        self.Text1.insert(END, self.goatData[0])

        self.isAlive = self.goatData[10]
        self.Canvas1.insert(END, self.isAlive)

        self.isPregnant = self.goatData[4]
        self.Canvas2.insert(END, self.isPregnant)

        if goatData[3] == 'm':
            self.Frame2.place_forget()

        self.populateTree()

        counter = 0

        self.Frame1 = tk.Frame(top)
        self.Frame1.place(relx=0.325,
                          rely=0.512,
                          relheight=0.45,
                          relwidth=0.237)
        self.Frame1.configure(relief='groove')
        self.Frame1.configure(borderwidth="2")
        self.Frame1.configure(relief="groove")
        self.Frame1.configure(background="#d9d9d9")
        self.Frame1.configure(highlightbackground="#d9d9d9")
        self.Frame1.configure(highlightcolor="black")

        # Weight graph
        data1 = self.db.getWeightRecords(goatData[0])
        dataColumns1 = self.db.getWeightColumnNames(goatData[0])
        df = pd.DataFrame(data1, columns=dataColumns1)

        figure = plt.Figure(figsize=(6, 7), dpi=50)
        ax1 = figure.add_subplot(111)
        line2 = FigureCanvasTkAgg(figure, self.Frame1)
        line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.NONE, padx=2)
        df.plot(kind='line',
                legend=True,
                ax=ax1,
                color='r',
                marker='o',
                fontsize=15)
        ax1.set_title('Chart of Growth')
        ax1.set_xlabel('Date_checked')
        ax1.set_xticks(np.arange(df.shape[0]) + 0.5, minor=False)
        ax1.set_xticklabels(df.date_checked, rotation=45, fontsize=10)
Example #57
0
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

import numpy as np

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)


def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)


canvas.mpl_connect("key_press_event", on_key_press)


def _quit():
Example #58
0
class Window(Interface):

    # window size
    _width = 1920
    _width_button = 8
    _height = 1080
    _height_button = 2

    def __init__(self, datasets=None):
        # check
        if not isinstance(datasets, dict):
            raise TypeError
        # init gui
        Interface.__init__(self,
                           title="Deictic",
                           width=self._width,
                           height=self._height)
        # fonts
        self._medium_font = Font(root=self,
                                 family='Helvetica',
                                 size=10,
                                 weight='bold')
        self._large_font = Font(root=self,
                                family='Helvetica',
                                size=14,
                                weight='bold')

        # panel image #
        self._left_frame = Frame(self._master,
                                 width=self._width - self._width / 6,
                                 height=self._height,
                                 background="bisque")
        self._left_frame.pack(side=LEFT)
        # define a canvas and a fig which will be show in the canvas
        self._fig = Figure(figsize=(16, 18))
        self._ax = self._fig.add_subplot(111)
        self._ax.scatter([], [])
        self._canvas = FigureCanvasTkAgg(self._fig, master=self._left_frame)
        self._fig.canvas.mpl_connect('key_press_event', self._keyPress)
        self._canvas.get_tk_widget().pack()

        # panel summary primitives #
        self._right_frame = Frame(self._master,
                                  width=self._width / 6,
                                  height=self._height)
        self._right_frame.pack(side=RIGHT)
        _top_frame_right = Frame(self._right_frame)
        _top_frame_right.pack(side=TOP, fill=BOTH, expand=1)
        _bottom_frame_right = Frame(self._right_frame)
        _bottom_frame_right.pack(side=BOTTOM, fill=BOTH, expand=1)

        # labels
        self._feedback = Label(_top_frame_right, text="")
        self._feedback.grid(row=0, column=0, padx=(10, 10), pady=(25, 25))
        self._info = Label(_top_frame_right, text="")
        self._info.grid(row=1, column=0, padx=(10, 10), pady=(25, 25))
        self._filename = Label(_top_frame_right, text="")
        self._filename.grid(row=2, column=0, padx=(10, 10), pady=(25, 25))
        # listbox primitives
        self._list_box = Listbox(_top_frame_right,
                                 width=35,
                                 height=15,
                                 font=self._medium_font,
                                 selectmode="multiple")
        self._list_box.grid(row=3, column=0, padx=(30, 30))
        # input
        frame_input = Frame(_top_frame_right)
        frame_input.grid(row=4, column=0, padx=(30, 30))
        self._input = Entry(frame_input)
        self._input.grid(row=0, column=0)
        self._input_button = Button(frame_input,
                                    text="Insert",
                                    fg="black",
                                    command=self._newItem,
                                    height=self._height_button,
                                    width=self._width_button)
        self._input_button.grid(row=0, column=1)

        # button next
        self._next_button = Button(_bottom_frame_right,
                                   text="Next Image",
                                   fg="black",
                                   command=self._next,
                                   height=self._height_button,
                                   width=self._width_button)
        self._next_button.grid(row=0, column=0, padx=(20, 0), pady=(50, 50))
        # button save
        self._save_button = Button(_bottom_frame_right,
                                   text="Save",
                                   fg="green",
                                   state="disabled",
                                   command=self._save,
                                   height=self._height_button,
                                   width=self._width_button)
        self._save_button.grid(row=0, column=1, pady=(50, 50))
        # remove button is used to manage primitives
        self._remove_button = Button(_bottom_frame_right,
                                     text="Remove",
                                     fg="red",
                                     state="disabled",
                                     command=self._remove,
                                     height=self._height_button,
                                     width=self._width_button)
        self._remove_button.grid(row=0, column=2, padx=(0, 20), pady=(50, 50))
        #  start application
        self._datasets = datasets
        self._dataset = None
        self._next()
        self.mainloop()

    def _next(self):
        # save
        self._save()
        # delete old listbox
        for i in range(self._list_box.size()):
            self._delete(index=0)
        # plot file, if it is avaiable
        if self._findNextFile():
            self._plot()
            return
        # otherwise change datatet, if available
        if self._datasets:
            next_dataset = self._datasets.popitem() if len(
                self._datasets) > 0 else None
            self._gesture_label = next_dataset[0]
            self._dataset = sum(
                [set.readDataset() for set in next_dataset[1][1]],
                []) if next_dataset != None else None
            self._num_primtivies = (next_dataset[1][0]
                                    if next_dataset != None else None)
            return
        # all files have been showed
        self._next_button.config(state="disabled")

    def _findNextFile(self):
        # find the next image
        if self._dataset != None and len(self._dataset) > 0:
            self._sequence = self._dataset.pop(0)
            # get sequence
            return True if not os.path.isfile(Config.baseDir+'deictic/1dollar-dataset/primitives/'+
                                          self._gesture_label+"/"+self._sequence.filename) \
                else self._findNextFile()
        return False

    def _newItem(self):
        """
            this handler manages the input recieved from entry widget. On one hand, it provides to split and verify input,
            and in the other hand to update the list of primitives.
        :return:
        """
        # check
        if len(self._input.get()) > 0:
            try:
                new_primitive = Primitive(num_primitive=self._list_box.size(),
                                          num_frame=int(self._input.get()))
                #num_frame = int(self._input.get()) #[int(item) for item in self._input.get().split(" ")]
                #new_primitive = Primitive(values[0],values[1])
            except:
                print("Error! Insert two integers in the entry widget!")
                return
            # clear input
            self._input.delete(0, 'end')
            # update list and figure
            self._insert(new_primitive)
            self._change_point(index=new_primitive.num_frame,
                               style_to_plot="ro")

    def _remove(self):
        # remove the selected elements then update plot and lists #
        # get selected elements and create a new Primitive array
        #elements = reversed([Primitive(int(item[0]),int(item[1])) for item in
        #            [element.split(": ") for element in
        #            [self._list_box.get(index) for index in self._list_box.curselection()]]])

        #for element in elements:
        # delete selected element
        #    self._delete(element.num_primitive)
        # delete highlighted point
        #    self._change_point(element.num_frame, "co")
        # and update list
        #    for index in range(element.num_primitive,self._list_box.size()):
        #        temp_item = self._list_box.get(index).split(': ')
        #        update_item = Primitive(int(temp_item[0])-1,int(temp_item[1]))
        #        self._delete(index)
        #        self._insert(item=update_item)
        #if not self._list_box.size() > 0:
        #    self._config_button(buttons=[self._remove_button,self._save_button],states=["disabled","disabled"])

        for i in range(self._list_box.size()):
            element = self._list_box.get(END).split(": ")
            self._change_point(int(element[1]), "co")
            self._list_box.delete(END)

    def _delete(self, index):
        """
            delete an item, with the specify index, from the listbox widget.
        :param index:
        :return:
        """
        # check
        if isinstance(index, str):
            index = int(index)
        try:
            self._list_box.delete(index)
        except:
            print("Index out of boundary")

    def _insert(self, item):
        """
            provide to insert a new item in the listbox widget
        :param item:
        :return:
        """
        # check input
        if not isinstance(item, Primitive):
            raise TypeError("Item must be a Primitive object")
        # check whether the new item has been just inserted #
        # get latest item
        if self._list_box.size() > 0:
            old_item = Primitive(num_primitive=-1,
                                 num_frame=int(
                                     self._list_box.get(END).split(" ")[-1]))
            if item.num_frame <= old_item.num_frame:
                return
        # insert new item
        self._list_box.insert(
            item.num_primitive,
            str(item.num_primitive) + ": " + str(item.num_frame))
        # check buttons state
        if self._remove_button['state'] == 'disabled':
            self._config_button(
                buttons=[self._remove_button, self._save_button],
                states=["normal", "normal"])

    def _save(self):
        """
            get from the widget the list of primitives and add to the file the references about primitives then save it.
        :return:
        """
        if self._list_box.size() > 0:
            if self._list_box.size() + 1 == self._num_primtivies:
                self._insert(
                    item=Primitive(self._list_box.size(),
                                   len(self._sequence.getPoints()) - 1))
            if self._list_box.size() < self._num_primtivies:
                raise Exception("You must select " +
                                str(self._num_primtivies) + " primitives.")

            try:
                # get inserted values
                inserted_values = [
                    Primitive(int(item[0]),
                              int(item[1]) + 1) for item in [
                                  element.split(": ")
                                  for element in self._list_box.get(0, END)
                              ]
                ]
                # determine the lenght of each primitive (t.num_frame - t-1.num_frame)
                temp = deepcopy(inserted_values)
                for a, b in zip(inserted_values[1:], temp):
                    a.num_frame = a.num_frame - b.num_frame
                # add new column which describes primitives
                new_column = np.concatenate([
                    np.full(shape=(item.num_frame, 1),
                            fill_value=item.num_primitive)
                    for item in inserted_values
                ])
                self._sequence.points = np.column_stack(
                    [self._sequence.getPoints(), new_column])
                # save file
                self._sequence.save(output_dir=Config.baseDir +
                                    'deictic/1dollar-dataset/primitives/' +
                                    self._gesture_label + '/')
                message = " has been saved"
                color = "green"
            except ValueError as e:
                message = " has not been saved"
                color = "red"
                print(e)

            # notify to user save result
            self._feedback.config(text=(self._sequence.filename + message),
                                  font=self._medium_font,
                                  fg=color)

    def _plot(self):
        print(self._sequence.filename + " is showed - " +
              str(len(self._sequence.getPoints())))
        # get points
        points = self._sequence.getPoints(columns=[0, 1])
        # plot and show selected file
        self._fig.tight_layout()
        self._ax.clear()
        self._ax.plot(points[:, 0],
                      points[:, 1],
                      'o-',
                      picker=self._line_picker)
        for i in range(0, len(points)):
            self._ax.annotate(str(i), (points[i, 0], points[i, 1]))
        # show name of the plotted file
        self._filename.config(text=("File: " + self._sequence.filename),
                              font=self._large_font)
        # show how many files require user intervation
        self._info.config(text=("Label: " + self._gesture_label + " - size: " +
                                str(len(self._dataset)) + "\nLenght: " +
                                str(len(points) - 1)),
                          font=self._medium_font)
        self._canvas.draw()

    def _line_picker(self, line, mouseevent):
        """

        :param line:
        :param mouseevent:
        :return:
        """
        # check
        if mouseevent.xdata is None:
            return False, {}
        # find the closest point to the mouseevent
        b = np.array([mouseevent.xdata, mouseevent.ydata])
        distances = ([
            SelectedPoint(index, point, np.linalg.norm(point - b))
            for index, point in enumerate(
                zip(line.get_xdata(), line.get_ydata()))
        ])
        selected_point = min(distances, key=lambda t: t.distance_from_click)
        self._update(selected_point)
        # throw onclick_event (is necessary)
        return True, {'point': selected_point}

    def _update(self, selected_point):
        # higlight point on figure
        self._change_point(selected_point.index, "ro")
        # insert the selected point in the listbox #
        self._insert(
            item=Primitive(self._list_box.size(), selected_point.index))
        # re-instate remove button
        if self._remove_button['state'] == 'disabled':
            self._config_button(
                buttons=[self._remove_button, self._save_button],
                states=["normal", "normal"])

    def _keyPress(self, event):
        if event.key == " ":
            self._next()

    def _change_point(self, index, style_to_plot):
        point = self._sequence.getPoints(columns=[0, 1])[index]
        self._ax.plot(point[0], point[1], style_to_plot)
        self._canvas.draw()

    @staticmethod
    def _config_button(buttons=[], states=[]):
        # check
        if not isinstance(buttons, list) and all(
            [isinstance(button, Button) for button in buttons]):
            raise TypeError
        if not isinstance(states, list) and all(
            [state in ["normal", "disabled"] for state in states]):
            raise TypeError
        if not len(buttons) == len(states):
            raise TypeError
        # set new states
        for button, state in zip(buttons, states):
            button.config(state=state)
class Layout(object):
    def __init__(self, root, title, size=5):
        fig = Figure(figsize=(7, 7), dpi=100)
        self.weights = None
        self.has_been_trained = False
        self.ax = fig.add_subplot(111)
        self.ax.set_title(title)

        # Makes the plot fixed (prevents from resizing)
        self.ax.set(xlim=(-size, size), ylim=(-size, size))
        # Adds guide lines
        self.ax.axhline(y=0, color="black")
        self.ax.axvline(x=0, color="black")
        # Draw arrow points
        self.ax.scatter(0, size - .1, marker='^', color='black')
        self.ax.scatter(size - .1, 0, marker='>', color='black')
        self.ax.scatter(0, -size + .1, marker='v', color='black')
        self.ax.scatter(-size + .1, 0, marker='<', color='black')

        # Connect the plot with the GUI interface
        self.canvas = FigureCanvasTkAgg(fig, master=root)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.canvas.mpl_connect("button_press_event", self.on_click)

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

    # Left click -> Class with 0s
    # Right click -> Class with 1s
    def on_click(self, event):
        ix, iy = event.xdata, event.ydata
        if (self.has_been_trained):
            point = {'coord': None, 'class': None, 'color': 'red'}
            point['coord'] = [-1, round(ix, 2), round(iy, 2)]
            point['class'] = 0
            if (np.dot(self.weights, np.array(point['coord'])) >= 0):
                point['class'] = 1
                point['color'] = 'green'

            self.ax.scatter(point['coord'][1],
                            point['coord'][2],
                            color=point['color'])
            self.ax.annotate('Class {}'.format(point['class']),
                             (point['coord'][1] + .5, point['coord'][2]))
            self.canvas.draw()  # Refreshes the canvas
        else:
            if (ix != None):
                point = {'coord': None, 'expected': None}
                color = 'orange'
                point['expected'] = 0
                if (event.button == 3):
                    point['expected'] = 1
                    color = 'purple'
                # The round operation on the coords is to prevent a slow convergence of the algorithm,
                # the plot detects a very precise coord of almost 10 decimal places and it is harder for
                # the algorithm to process those values
                point['coord'] = [-1, round(ix, 2), round(iy, 2)]
                self.ax.scatter(point['coord'][1],
                                point['coord'][2],
                                color=color)
                self.canvas.draw()  # Refreshes the canvas
                # Open the file, then read it to append new points in active session
                with open('bulk_data.json', 'r+') as file:
                    data = json.load(file)
                    data.append(point)
                    file.seek(0)
                    json.dump(data, file)
Example #60
0
class SGraphMLTK:
    """
        Diese Klasse steht für die Darstellung trinierter Daten. Die Methoden ähneln sich von
        dieser in dem Module normal.py, aber sie werden noch mehrere Optionsparameter anbieten
        """
    def __init__(self, col, row, px, py, master_lf=None):
        """

        :param col:
        :param row:
        :param px:
        :param py:
        :param master_lf:
        """
        self.gmaster = master_lf  # Hauptframe: wird von einer anderen Klasse (Frame) bestimmt
        self.gmaster.grid(column=col, row=row, padx=px, pady=py)
        self.intern_frame = Frame(
            master=self.gmaster)  # innere Frame für einzelnen Graphen
        self.intern_frame.grid(column=col, row=row, padx=px, pady=py)

        self.canvas = None
        self.frame = None
        pass

    def draw(self,
             x,
             y,
             x1=None,
             y1=None,
             x2=None,
             y2=None,
             pred=None,
             algo_name=None):
        """

        :param x:
        :param y:
        :param x1:
        :param y1:
        :param x2:
        :param y2:
        :param pred:
        :param algo_name:
        :return: fig
        """
        fig = plt.Figure(figsize=(4.4, 2.7),
                         dpi=80,
                         facecolor='white',
                         constrained_layout=True)
        ax = fig.add_subplot(111)
        ax.scatter(x=x, y=y, c='white', edgecolors='k', label='Stromverbrauch')
        ax.scatter(x=x1, y=y1, c='red', label='Outliers')
        if pred == -1:
            if y2 > 4019.59:
                ax.scatter(x=x2, y=y2, c='red', s=100, label='Neuer Eintrag')
            else:
                ax.scatter(x=x2, y=y2, c='blue', s=100, label='Neuer Eintrag')
        else:
            ax.scatter(x=x2, y=y2, c='green', s=80, label='Neuer Eintrag')

        ax.set_xlabel('Tage (in Integer)')
        ax.set_ylabel('Stromverbrauch (in w min)')
        ax.set_title(algo_name)
        ax.legend(loc='best')

        return fig

    def put_graph_on_canvas(self, fig):  #
        self.canvas = FigureCanvasTkAgg(fig, master=self.intern_frame)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(column=0, row=0, padx=5, pady=5)
        self.intern_frame.update()

    def on_update_canvas(self, fig):
        self.canvas = None
        self.put_graph_on_canvas(fig)