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()
def plot(window_array): #setting preview window parameter window_preview = int(preview_time.get()) #in no of data pointa at 50kHz import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg fig = Figure(figsize=(18,4), dpi=100) a = fig.add_subplot(111) a.plot(window_array[:window_preview,0], window_array[:window_preview,1], 'k-', label='Trace') a.plot(window_array[:window_preview,0], window_array[:window_preview,2], 'r-', label='Baseline Average') a.set_ylim(min(window_array[100:window_preview,1]), max(window_array[100:window_preview,1])) a.set_xlabel('Time (s)') a.set_ylabel('current (nA)') a.legend(loc='best') dataPlot = FigureCanvasTkAgg(fig, master=f5i) dataPlot.draw() dataPlot.show() dataPlot.get_tk_widget().pack(side=TOP)
class MonitorWindow(PanedWindow): def __init__(self, master, skeleton): PanedWindow.__init__(self, master=master, height=400) self.skeleton = skeleton self.figure = Figure(figsize=(5,4), dpi=100) self.subplots = {} nrows = len(self.skeleton.units) ncols = 3 plot_counter = 1 for u in self.skeleton.units.keys(): subplots = [None, None, None] history = self.skeleton.units[u].history() t = range(0, len(history[0])) for a in range(0, 3): subplot = self.figure.add_subplot(nrows, ncols, plot_counter, xlim=[0,200], ylim=[-90,90]) s = history[a] subplot.plot(t,s) plot_counter += 1 subplots[a] = subplot self.subplots[u] = subplots self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side="top", fill="both", expand=1) self.canvas.mpl_connect("key_press_event", self.pressed_key) self.pack(fill="both", expand="yes") def redraw_graph(self): plot_counter = 1 for k, axes in self.subplots.iteritems(): history = self.skeleton.units[k].history() t = range(0, len(history[0])) for a, subplot in enumerate(axes): s = history[a] subplot.plot(t,s) plot_counter += 1 subplot.clear() subplot.plot(t,s) subplot.set_xlim([0, 200]) subplot.set_ylim([-90, 90]) self.canvas.draw() def pressed_key(self, event): if event.key == "r": self.redraw_graph() else: print("Key pressed: %s" % event.key)
class LcdPlot( object ): def __init__( self, rfe, frame ): self.rfe = rfe self.frame = frame self.lcd_data = self.rfe.lcd_data self.figure_lcd = mpl.figure.Figure( figsize=(2,1), dpi=100, frameon=False ) self.canvas_lcd = FigureCanvasTkAgg( self.figure_lcd, master=self.frame ) self.lcd_subplot = self.figure_lcd.add_subplot( '111' ) # style figure self.figure_lcd.patch.set_alpha( 0.0 ) # makes background patch invisible self.figure_lcd.patch.set_visible( False ) # style lcd self.lcd_subplot.set_axis_off() # will show graph only, rest is transparent self.img = self.lcd_subplot.matshow( np.random.random((64*2, 128*2)), cmap='Greys' ) # why does only random work, not zeros or ones? #self.figure_lcd.tight_layout() self.canvas_lcd.show() self.canvas_lcd.get_tk_widget().grid() def update( self ): if not self.lcd_data.empty(): while not self.lcd_data.empty(): lcd = self.lcd_data.get() lcd = np.kron( lcd, np.ones((2,2)) ) # scale by factor 2 self.img.set_array( lcd ) self.canvas_lcd.draw()
class DCanvas(ttk.Frame): '''Drawing the dynamic canvas, as weel as the parspace generator''' fig = matplotlib.figure.Figure() fig_ld = {} def __init__(self, master=None, par=None): ttk.Frame.__init__(self, master) self.pack() # fig.add_subplot(212) self.canvas = FigureCanvasTkAgg(self.fig, master=self.master) self.canvas.show() self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.master) self.toolbar.update() def draw_parspace(self, par=None, s=None): x = par.pars_axs[s][0] y = par.pars_axs[s][1] print x, y #try: #self.fig = self.fig_ld[s].frozen() #print s #except KeyError: #self.fig_ld[s] = matplotlib.figure.Figure() for i in range(0, x * y): # self.fig_ld[s].add_subplot(x, y, i + 1) self.fig.add_subplot(x, y, i + 1) print i #self.fig = self.fig_ld[s].frozen() self.canvas.draw()
class Graph(tk.Frame,object): def __init__(self,master=None,onClick=None,xSize=40,ySize=30): self.onClick=(lambda x,y,z:None) if onClick is None else onClick tk.Frame.__init__(self,master) self.f = Figure(figsize=(4,4), dpi=100) # return a matplotlib.figure.Figure instance, Höhe und Breite in Inches self.a = self.f.add_subplot(111) # Add a subplot with static key "111" and return instance to it self.a.grid(True) # Set the axes grids on self.a.set_xlim((0,ySize)) self.a.set_ylim((0,xSize)) self.canvas = FigureCanvasTkAgg(self.f, master=self) # The Canvas widget provides structured graphics facilities for Tkinter. self.canvas.mpl_connect('button_press_event', self.rawOnClick) self.canvas.show() # Aus matplotlib: display all figures and block until the figures have been closed self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) def addline(self,x,y): self.curline=matplotlib.lines.Line2D([y],[x]) self.a.add_line(self.curline) def append(self,x,y): y0,x0=self.curline.get_data() x0.append(x) y0.append(y) self.curline.set_data(y0,x0) self.canvas.draw() def rawOnClick(self,evt): print evt.key both=True if evt.key=='shift' else False self.onClick(evt.ydata, evt.xdata, both)
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()
def cria_grafi(self): global lista, flag, x, flag_stop ######################################################################## # Criacao do Grafico e Tollbar # ######################################################################## fig = pylab.figure(1) ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.grid(True) ax.set_title("RealTime plot FAPI - CQI INDICATION") ax.set_xlabel("Time") ax.set_ylabel("Amplitude") ax.axis([0,1000,0,100]) line, = pylab.plot(lista) canvas = FigureCanvasTkAgg(fig, master=self.parent) canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) canvas.show() toolbar = NavigationToolbar2TkAgg( canvas, self.parent ) toolbar.update() canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) ######################################################################## # Geracao do grafico # ######################################################################## while flag_stop == False: #for i in range(0,2): #print 'flag graf', flag_stop delete() lista.extendleft(valor_plot) line.set_ydata(lista) canvas.draw()
class App: def __init__(self, master): # 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 = fig.add_subplot(111) self.line, = ax.plot([x / 0.5 for x in range(20)]) self.canvas = FigureCanvasTkAgg(fig, 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 + [cos(xx) for xx in x]) self.canvas.draw() def increase(self): x, y = self.line.get_data() self.line.set_ydata(y + 0.2 * x) self.canvas.draw()
class TkSimulationWindow(object): def __init__(self, root): self.root = root self._init_app() # here we embed the a figure in the Tk GUI def _init_app(self): self.figure = mpl.figure.Figure() self.ax = self.figure.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.figure, self.root) self.toolbar = TkSimulationToolbar(self.canvas, self.root) self.toolbar.update() self.plot_widget = self.canvas.get_tk_widget() self.plot_widget.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas.show() # plot something random def plot(self): # self.axes.hold(False) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.canvas.draw()
class tk_plot: def __init__(self,master,row=0,col=0,rowspan=1,colspan=1,size=(6,6),dpi=100,interval=1000): self.xdata = [] self.ydata = [] self.fig = Figure(figsize=size, dpi=dpi) self.ax = self.fig.add_subplot(111) self.ax.plot(self.xdata,self.ydata) self.canvas = FigureCanvasTkAgg(self.fig, master = master) self.canvas.draw() self.canvas.get_tk_widget().grid(row=row,column=col,rowspan=rowspan,columnspan=colspan,sticky=tk.N+tk.S+tk.E+tk.W) self.ani = animation.FuncAnimation(self.fig, self.plot_loop , interval=interval) def plot_loop(self,i): self.ax.plot(self.xdata, self.ydata) def add_data(self,x,y): self.xdata.append(float(x)) self.ydata.append(float(y)) def get_tk_widget(self): return self.canvas.get_tk_widget() def get_x_data(self): return self.xdata def get_y_data(self): return self.ydata
class Window(): def __init__(self, master): self.frame = tk.Frame(master) self.f = Figure(figsize=(10, 9), dpi=80) self.fig = plt.figure(1) #self.fig.patch.set_facecolor('black') t = np.arange(0.0,0.3,0.01) s = np.sin(np.pi*t) plt.plot(t,s) # self.ax0 = self.f.add_axes((0.05, .05, .50, .50), facecolor=(.75, .75, .75), frameon=False) # self.ax1 = self.f.add_axes((0.05, .55, .90, .45), facecolor=(.75, .75, .75), frameon=False) # self.ax2 = self.f.add_axes((0.55, .05, .50, .50), facecolor=(.75, .75, .75), frameon=False) # # self.ax0.set_xlabel('Time (s)') # self.ax0.set_ylabel('Frequency (Hz)') # self.ax0.plot(np.max(np.random.rand(100, 10) * 10, axis=1), "r-") # self.ax1.plot(np.max(np.random.rand(100, 10) * 10, axis=1), "g-") # self.ax2.pie(np.random.randn(10) * 100) self.frame = tk.Frame(root) self.frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.plot_widget = self.canvas.get_tk_widget()#.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.plot_widget.grid(row=0, column=0) #self.canvas.show() self.canvas.draw()
class TkinterGraph(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.figure = Figure(figsize=(10,10), dpi=50) self.title= self.figure.suptitle('', fontsize=20) self.graph_a = self.figure.add_subplot(111) self.graph_a.set_ylabel('ln(numberof filled boxes)') self.graph_a.set_xlabel('ln(Box size)') self.canvas = FigureCanvasTkAgg(self.figure, self) self.canvas.show() self.canvas._tkcanvas.pack(side=TOP)#,fill=BOTH, expand=1) def change_data(self,data_x,data_y): self.graph_a.clear() #self.graph_a.scatter(data_x,data_y) fit = polyfit(data_x,data_y,1) #DEBUG print fit self.title.set_text('Fractal dimension: %.3f' % fit[0]) fit_fn = poly1d(fit) self.graph_a.plot(data_x,data_y, 'yo', data_x, fit_fn(data_x), '--k') self.canvas.draw()
class App: def __init__(self, master, figure): # Create a container frame = tkinter.Frame(master) # Create 2 buttons self.button_left = tkinter.Button(frame, text="< Decrease Slope", command=self.decrease) self.button_left.pack(side="left") self.button_right = tkinter.Button(frame, text="Increase Slope >", command=self.increase) self.button_right.pack(side="left") # fig = Figure() ax = figure.add_subplot(212) self.line, = ax.plot(range(10)) self.canvas = FigureCanvasTkAgg(figure, master=master) self.canvas.show() self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) frame.pack() def decrease(self): x, y = self.line.get_data() self.line.set_ydata(y - 0.2 * x) self.canvas.draw() def increase(self): x, y = self.line.get_data() self.line.set_ydata(y + 0.2 * x) self.canvas.draw()
class 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)
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()
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)
def __init__(self, master, node_name='', figure_size=(5,4), dpi=100, is_polar=False): super().__init__(node_name=node_name) figure = Figure(figure_size, dpi) canvas = FigureCanvasTkAgg(figure, master=master) canvas.draw() self.__canvas = canvas toolbar = NavigationToolbar2Tk(canvas, master) toolbar.update() canvas.get_tk_widget().pack(side='top', fill='both', expand='yes') toolbar.pack() # canvas.mpl_connect('button_press_event', lambda event:print(event)) # test mpl_connect with self.attribute_lock: # All the properties being set in this block will be locked automatically, # i.e. these properties cannot be replaced. set_attributes(self, figure = figure, line_objects = [], axes = figure.add_subplot(111, polar=is_polar), is_polar = is_polar ) self.indicators = self.Indicators(data_figure=self) self.plot_function = None self.index = None # Used by FigureList self.__major_grid = is_polar self.__minor_grid = False self.__indicatorsMeta = []
class App: def __init__(self, master): # create a container for buttons buttonFrame = Tk.Frame(root) buttonFrame.pack() # create buttons self.buttonGenerate = Tk.Button(master=buttonFrame, text="Generate", command=self.generateMap) self.buttonGenerate.pack(side=Tk.LEFT) self.buttonQuit = Tk.Button(master=buttonFrame, text="Quit", command=root.destroy) self.buttonQuit.pack(side=Tk.LEFT) # create container for text textFrame = Tk.Frame(root) textFrame.pack() # create text self.label = Tk.Label( master=textFrame, text="Pearson correlation:\nSpearman rho:\nKendall tau:", justify=Tk.LEFT ) self.label.pack() # create container for plot plotFrame = Tk.Frame(root) plotFrame.pack(side=Tk.BOTTOM) # create plot f = Figure(figsize=(5, 4), dpi=100) self.ax = f.add_subplot(111) self.ax.set_xlim([-0.2, 1.2]) self.ax.set_ylim([-0.2, 1.2]) self.canvas = FigureCanvasTkAgg(f, master=plotFrame) self.canvas.show() self.canvas.get_tk_widget().pack() def generateMap(self): # generate random line c = np.random.rand() m = np.random.rand() - c # get data points pointCnt = 50 sigma = np.random.rand() x = np.random.rand(pointCnt) y = m * x + c + sigma * np.random.randn(pointCnt) # update text corr = pearsonr(x, y)[0] rho = spearmanr(x, y)[0] tau = kendalltau(x, y)[0] newVals = """Pearson correlation:\t%.2f\nSpearman rho:\t%.2f\nKendall tau:\t%.2f""" % (corr, rho, tau) self.label.config(text=newVals) # plot points self.ax.clear() self.ax.scatter(x, y, marker="s", c="black") self.ax.set_xlim([-0.2, 1.2]) self.canvas.draw()
def showfigs(figs, tabs): clearfigs(tabs) for fig, tab in zip(figs, tabs): canvas = FigureCanvasTkAgg(fig, master=tab) toolbar = NavigationToolbar2TkAgg(canvas, tab) canvas.get_tk_widget().pack(fill=BOTH, expand=True) toolbar.pack() canvas.draw()
class Plot(tk.Frame): """ A frame for storing the plot generated by matplotlib """ def __init__(self, parent): tk.Frame.__init__(self, parent, background="white") self.parent = parent tk.Button(self, text='Refresh Image', command=self.refresh).pack(side=tk.TOP) T = [float(num)/100.0 for num in range(0, 10001)] X = [self.parent.A.get()*np.sin(self.parent.a.get()*t + self.parent.delta.get()) for t in T] Y = [self.parent.B.get()*np.sin(self.parent.b.get()*t) for t in T] #Create plot f = Figure(figsize=(5, 5), dpi=100) plot = f.add_subplot(111) self.graph, = plot.plot(X, Y) self.canvas = FigureCanvasTkAgg(f, self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) self.pack() def refresh(self): T = [float(num)/100.0 for num in range(0, 10001)] X = [self.parent.A.get()*np.sin(self.parent.a.get()*t + self.parent.delta.get()) for t in T] Y = [self.parent.B.get()*np.sin(self.parent.b.get()*t) for t in T] self.graph.set_data(X, Y) ax = self.canvas.figure.axes[0] ax.set_xlim(min(X), max(X)) ax.set_ylim(min(Y), max(Y)) self.canvas.draw() self.play_notes() def play_notes(self): """ Play the selected notes with pyaudio Thanks to stackoverflow ivan_onys for the basis of this code """ sampleA = (np.sin(2*np.pi*np.arange(self.parent.fs*self.parent.duration)*self.parent.a.get()*440/self.parent.fs)).astype(np.float32) sampleB = (np.sin(2*np.pi*np.arange(self.parent.fs*self.parent.duration)*self.parent.b.get()*440/self.parent.fs)).astype(np.float32) stream = self.parent.player.open(format=pyaudio.paFloat32, channels=1, rate=self.parent.fs, output=True) to_play = (sampleA + sampleB)/2 stream.write(self.parent.volume*to_play) stream.stop_stream() stream.close()
class PieChartView(tk.Frame): canvas = None controller = None def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Pie chart", font=LARGE_FONT) label.pack(pady=10, padx=10) labels = 'Positive', 'Neutral', 'Negative' amount = [pos, neut, neg] print(amount) colors = ['green', 'lightskyblue', 'red'] explode = (0, 0.05, 0) # proportion with which to offset each # wedge entry1 = ttk.Entry(self) entry1.pack() button3 = ttk.Button(self, text="Start stream ", command=lambda: controller.start_stream( entry1.get())) button3.pack() piechart.pie(amount, # data explode=explode, # offset parameters labels=labels, # slice labels colors=colors, # array of colours autopct='%1.1f%%', # print the values inside the wedges shadow=True, # enable shadow startangle=70 # starting angle ) piechart.axis('equal') button1 = ttk.Button(self, text="Back to Home", command=lambda: self.stop()) button1.pack() self.canvas = FigureCanvasTkAgg(figure2, self) self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) ''' Roept de stop functie aan op de controller, en gaat terug naar de startpagina ''' def stop(self): self.controller.show_frame(WelcomePage) self.controller.controller.stop_stream() ''' Zorgt ervoor dat de pie chart de nieuwe waarden gebruikt ''' def update(self): piechart.clear() piechart.pie([pos, neut, neg]) self.canvas.draw_idle()
class CorrelationGraphView(BaseResultsView): def __init__(self, parent): tk.Frame.__init__(self, parent) self.figure = Figure(figsize=(4,5), dpi=100) #figure = plt.figure(figsize=(4,5), dpi=100) # ax1 = self.figure.add_subplot(211) # ax1.set_title('Original Trajectory') # ax1.plot([1,2,3,4,5],[5,6,7,8,9]) # ax2 = self.figure.add_subplot(212, sharex=ax1, sharey=ax1) # ax2.set_title('Predicted Trajectory') # ax2.plot([1,2,3,4,5],[5,6,7,8,9]) #plt.tight_layout() #if broke on windows - follow https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/xssOnleIPFw self.canvas = FigureCanvasTkAgg(self.figure, self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.export_button = ttk.Button(self, text="Export Correlation as Nifti", state='disabled', command=lambda: self.export_results()) self.file_opt = options = {} options['filetypes'] = [('nifti files', '.nii')] options['initialfile'] = 'results.nii' options['parent'] = parent def plot_results(self, overlay_data, mri_args): plot_lightbox(overlay=overlay_data, vlim=(-1.0, 1.0), do_stretch_colors=True, fig=self.figure, **mri_args) self.overlay_data = overlay_data toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.canvas.draw() self.export_button.config(state='normal') self.export_button.pack(side="right", padx=5, pady=5) def export_results(self): file_location = filedialog.asksaveasfilename(**self.file_opt) self.overlay_data.to_filename(file_location) print("results saved to " + file_location)
def show_tkagg(figure, title=''): """Create a new matplotlib figure manager instance. """ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg #_focus = windowing.FocusManager() window = Tk.Tk() window.wm_title(title) canvas = FigureCanvasTkAgg(figure, master=window) canvas.draw() canvas.get_tk_widget().pack() Tk.mainloop()
def Plotting(queue): while queue.get() != "Start Plotting Process": wait = "Waiting" timeNow = datetime.time(datetime.now()) time = timeNow.minute + (timeNow.second + timeNow.microsecond/1000000.0)/60.0 lastX = time lastY = 90250 connect = True step = 0 x=[] y=[] mode = "24-Hour-Plot" root = tk.Tk() root.wm_title("PyAmaseis v1.0") root.iconbitmap(r'icons/icon.ico') root.wm_state('zoomed') graphHeightConst = 2500 fig = plt.figure(figsize=(15,10)) fig.set_tight_layout(0.4) ax = fig.add_subplot(1,1,1) ax.set_xlim(0,60) ax.set_ylim(30250,92750) ax.set_xlabel('Time(minutes)') xAxis = [0,60] yAxis = [30250,92750] y1 = (np.arange(min(yAxis), max(yAxis)+1,graphHeightConst)) y2 = calculateYAxisLabels() ax.set_xticks(np.arange(min(xAxis), max(xAxis)+1,1)) plt.yticks(y1, y2) ax.yaxis.grid(color = '#0000FF' ) ax.set_axisbelow(True) line, = ax.plot(x, y, color='k') canvas = FigureCanvasTkAgg(fig, master=root) canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) label = tk.Label(text="") label.pack() background = canvas.copy_from_bbox(ax.bbox) canvas.draw() root.after(0, plotData,queue, fig, ax, canvas, label, root, lastY, lastX, connect, background, line, mode) root.mainloop()
def gui_plotsza(self): 'gui function to plot the solar zenith angle of the flight path' #import tkMessageBox #tkMessageBox.showwarning('Sorry','Feature not yet implemented') #return if not self.noplt: print 'No figure handler, sorry will not work' return from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import Tkinter as tk root = tk.Toplevel() root.wm_title('Solar position vs. Time') root.geometry('800x550') fig = Figure() canvas = FigureCanvasTkAgg(fig, master=root) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) tb = NavigationToolbar2TkAgg(canvas,root) tb.pack(side=tk.BOTTOM) tb.update() canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH,expand=1) ax1 = fig.add_subplot(2,1,1) ax1.plot(self.line.ex.cumlegt,self.line.ex.sza,'x-') ax1.set_title('Solar position along flight track for %s on %s' %(self.line.ex.name,self.line.ex.datestr), y=1.18) fig.subplots_adjust(top=0.85) #ax1.set_xlabel('Flight duration [Hours]') ax1.set_ylabel('SZA [degree]') #ax1.set_xticklabels(['','','','','','']) ax1.grid() axticks = ax1.get_xticks() ax1_up = ax1.twiny() ax1_up.xaxis.tick_top() cum2utc = self.line.ex.utc[0] ax1_up.set_xticks(axticks) utc_label = ['%2.2f'%(u+cum2utc) for u in axticks] ax1_up.set_xticklabels(utc_label) ax1_up.set_xlabel('UTC [Hours]') ax2 = fig.add_subplot(2,1,2,sharex=ax1) ax2.plot(self.line.ex.cumlegt,self.line.ex.azi,'ok',label='Sun PP') ax2.plot(self.line.ex.cumlegt,[a-180 for a in self.line.ex.azi],'o',color='lightgrey',label='Sun anti-PP') ax2.set_ylabel('Azimuth angle [degree]') ax2.set_xlabel('Flight duration [Hours]') ax2.grid() ax2.plot(self.line.ex.cumlegt,self.line.ex.bearing,'xr',label='{} bearing'.format(self.line.ex.name)) box = ax1.get_position() ax1.set_position([box.x0, box.y0, box.width * 0.75, box.height]) ax1_up.set_position([box.x0, box.y0, box.width * 0.75, box.height]) box = ax2.get_position() ax2.set_position([box.x0, box.y0, box.width * 0.75, box.height]) ax2.legend(frameon=True,numpoints=1,bbox_to_anchor=[1.4,0.8]) canvas.draw() return fig
def __init__(self, stream=None, events=None, myargs=None, lock=None, drum_plot=True, trace_ids=None, *args, **kwargs): tkinter.Tk.__init__(self, *args, **kwargs) favicon = tkinter.PhotoImage( file=os.path.join(os.path.dirname(os.path.abspath(__file__)), "favicon.gif")) self.tk.call('wm', 'iconphoto', self._w, favicon) self.wm_title("seedlink-plotter {}".format(myargs.seedlink_server)) self.focus_set() self._bind_keys() args = myargs self.lock = lock ### size and position self.geometry(str(args.x_size) + 'x' + str(args.y_size) + '+' + str( args.x_position) + '+' + str(args.y_position)) w, h, pad = self.winfo_screenwidth(), self.winfo_screenheight(), 3 self._geometry = ("%ix%i+0+0" % (w - pad, h - pad)) # hide the window decoration if args.without_decoration: self.wm_overrideredirect(True) if args.fullscreen: self._toggle_fullscreen(None) # main figure self.figure = Figure() canvas = FigureCanvasTkAgg(self.figure, master=self) if MATPLOTLIB_VERSION[:2] >= [2, 2]: canvas.draw() else: canvas.show() canvas.get_tk_widget().pack(fill=tkinter.BOTH, expand=1) self.backtrace = args.backtrace_time self.canvas = canvas self.scale = args.scale self.args = args self.stream = stream self.events = events self.drum_plot = drum_plot self.ids = trace_ids # Colors if args.rainbow: # Rainbow colors ! self.color = self.rainbow_color_generator( int(args.nb_rainbow_colors)) else: # Regular colors: Black, Red, Blue, Green self.color = ('#000000', '#e50000', '#0000e5', '#448630') self.plot_graph()
def cria_grafi(self): global lista, flag, x, flag_stop, cont_harq, conta_amostras ######################################################################## # Criacao do Grafico e Tollbar # ######################################################################## fig = pylab.figure(1) ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.grid(True) ax.set_title("RealTime plot FAPI - BLER INDICATION") ax.set_xlabel("Tempo (em 0.5 segundos)") ax.set_ylabel("Amplitude(em porcentagem)") ax.axis([0,1000,0,100]) line, = pylab.plot(lista) canvas = FigureCanvasTkAgg(fig, master=self.parent) canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) canvas.show() toolbar = NavigationToolbar2TkAgg( canvas, self.parent ) toolbar.update() canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) ######################################################################## # Geracao do grafico # ######################################################################## while flag_stop == False: #conta_amostras = 50 #cont_harq = randint(300,500) valor_plot_bler = (cont_harq/conta_amostras)*100 print 'Amostras: ', conta_amostras, ' Harq is not 1: ', cont_harq, ' BLER: ', valor_plot_bler #texto_bler = 'Valor de bler:' #ax.text(65, 95, '') #ax.text(85, 95, '') #ax.text(650, 95, texto_bler) #ax.text(850, 95, valor_plot_bler) #texto_amostras = 'Amostras / Harq:' #ax.text(60,90, texto_amostras) #ax.text(85,90, conta_amostras) #ax.text(90,90.1, '/') #ax.text(92,90, cont_harq) delete() lista.appendleft(valor_plot_bler) line.set_ydata(lista) canvas.draw() conta_amostras = 1.0 cont_harq = 0 time.sleep(0.05)
def showfigs(t0, status, figs, tabs): close('all') for fig, tab in zip(figs, tabs): # destroy all widgets in fram/tab and close all figures for widget in tab.winfo_children(): widget.destroy() canvas = FigureCanvasTkAgg(fig, master=tab) toolbar = NavigationToolbar2TkAgg(canvas, tab) canvas.get_tk_widget().pack() toolbar.pack() canvas.draw() timestring = time2str(time() - t0) status.set('finished, elapsed time: ' + timestring)
class Plot2D_Frame(Tk.Frame): def __init__(self,parent,model,var_id,**kwargs): Tk.Frame.__init__(self,parent,**kwargs) self.plotmode = 'scalar' self.plotted_varid = var_id self.model = model self.ymin = None self.ymax = None self.xmin = None self.xmax = None self.x = deque(maxlen=128) self.y = deque(maxlen=128) # self.f = Figure(figsize=(5,4), dpi=100) self.a = self.f.add_subplot(111) self.a.set_xlim([0, 127]) self.a.set_ylim([-255, 255]) self.line1, = self.a.plot([],[]) self.a.set_autoscale_on(True) # self.plotFrame = Tk.Frame(self) self.dataPlot = FigureCanvasTkAgg(self.f, master=self) self.dataPlot.show() self.dataPlot.get_tk_widget().grid(column=0,row=0,sticky='WENS',columnspan=5) self.toolbar = NavigationToolbar2TkAgg(self.dataPlot, self.plotFrame) self.plotFrame.grid(row=1,column=0,columnspan=5,sticky="WENS") self.start_time = timeit.default_timer() self.refresh_last_time = timeit.default_timer() self.refresh_rate = 0.1 # Redraw every hundred millisecond def on_value_received(self,var_id,**kwargs): if not self.plotted_varid == var_id: return t = timeit.default_timer() if t - self.refresh_last_time > self.refresh_rate: self.refresh_last_time = t self.data = self.model.get_buffers_value(self.plotted_varid) self.a.set_xlim([self.data.x[0],self.data.x[-1]]) self.line1.set_data(self.data.x,self.data.y) self.a.relim() self.a.autoscale_view(False,False,True) self.dataPlot.draw()
class mainWin: def __init__(self): self.root = tk.Tk() self.root.title("Collapsator") #whole container self.content = ttk.Frame(self.root) #input files container filesFrame = ttk.LabelFrame(self.content, text="Input files", borderwidth=2) self.inFrame = inFrame(filesFrame) #plot preview container self.plotFrame = tk.Frame(self.content, borderwidth=5, relief="sunken") tk.Frame(self.plotFrame, width=300, height=300, bg='white').pack() self.distLabel = tk.Label(self.content, text="S = ????") #expoent and results frame guesFrame = ttk.Frame(self.content) self.resVal = guessFrame(guesFrame) self.Ninterac = tk.IntVar() self.Ninterac.set(100) self.interacEntry = tk.Entry(self.content, textvariable=self.Ninterac, validate = 'key', validatecommand = (self.content.register(validateInt), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'), width=8, state='disabled') self.approxButt = tk.Button(self.content, text="Approximate", command=self.approximate, state='disabled') self.exportButt = tk.Button(self.content, text='Export', command=self.exportDat, state='disabled') #adding things to the interface self.content.pack() filesFrame.grid(column=0, row=0, columnspan=3, padx=8, pady=8) self.plotFrame.grid(column=0, row=1, rowspan=4, padx=8, pady=4, sticky='nesw') self.loadedFlag = False self.loadButt = tk.Button(self.content, text="Load data", command=self.loadData) self.loadButt.grid(column=1, row=1, padx=8, pady=8) self.replotButt = tk.Button(self.content, text="Replot", state='disabled', command=self.graphReplot) self.replotButt.grid(column=2, row=1, padx=8, pady=8) guesFrame.grid(column=1, row=2, columnspan=2, padx=8, pady=4) self.interacEntry.grid(column=1, row=3, sticky=(tk.E, tk.S)) tk.Label(self.content, text=" interactions").grid(column=2, row=3, sticky=(tk.W, tk.S)) self.approxButt.grid(column=1, columnspan=2, row=4, sticky=(tk.N), pady=4) self.distLabel.grid(column=0, row=5, padx=4, pady=4) self.exportButt.grid(column=1, columnspan=2, row=5, padx=4, pady=4) self.root.mainloop() def loadData(self): def loadFile(path): if isfile(path): try: return np.loadtxt(path, usecols=[0,1]) except ValueError: return messagebox.askyesno("Error", path + " could not be loaded. Do you want to continue without it?") else: return messagebox.askyesno("Error", path + " is not a file. Do you want to continue without it?") if not self.loadedFlag: fileList, preSizes = self.inFrame.fileLocations() dataSet = [] sizes = [] for i in range(len(fileList)): res = loadFile(fileList[i]) if isinstance(res, np.ndarray): if preSizes[i] == '': size = 0 else: size= int(preSizes[i]) if size== 0: if not messagebox.askyesno("Error", "0 is not a valid system size. Do you want to continue without this file?"): del dataSet[:] del sizes[:] return else: dataSet.append(res.transpose()) sizes.append(size) elif not res: del dataSet[:] del sizes[:] return if len(dataSet) > 1: #print(dataSet[0][0]) xmin = dataSet[0][0].min() xmax = dataSet[0][0].max() for xs in dataSet: lmin = xs[0].min() lmax = xs[0].max() if lmin < xmin: xmin = lmin if lmax > xmax: xmax = lmax self.resVal.setDefault([0.0,0.0,0.0],xmin,xmax) self.loadedFlag = True self.loadButt.configure(text="Change files") self.inFrame.disableChilds() self.resVal.enableChilds() self.replotButt.configure(state='normal') self.interacEntry.configure(state='normal') self.approxButt.configure(state='normal') self.exportButt.configure(state='normal') self.plotData = dataSet self.sysSizes = sizes self.graphPlot() else: messagebox.showerror("Error", "You need at least 2 valid data sets.") else: self.loadedFlag = False self.loadButt.configure(text="Load data") self.resVal.disableChilds() self.inFrame.enableChilds() self.replotButt.configure(state='disabled') self.interacEntry.configure(state='disabled') self.approxButt.configure(state='disabled') self.exportButt.configure(state='disabled') def graphPlot(self): #update distance label self.updateDist() for child in self.plotFrame.winfo_children(): child.destroy() f = Figure(figsize=(4,4), dpi=100) self.axis = f.add_subplot(111) for graph in self.plotData: self.axis.plot(graph[0],graph[1], 'o') self.canvas = FigureCanvasTkAgg(f, self.plotFrame) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(self.canvas, self.plotFrame) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) def graphReplot(self): #update info labels self.updateDist() #self.statusLabel.configure(text='') reescaled = reescale(self.resVal.returnVals(),self.sysSizes, self.plotData) xmin = reescaled[0][0].min() xmax = reescaled[0][0].max() ymin = reescaled[0][1].min() ymax = reescaled[0][1].max() for xs in reescaled: lmin = xs[0].min() lmax = xs[0].max() if lmin < xmin: xmin = lmin if lmax > xmax: xmax = lmax lmin = xs[1].min() lmax = xs[1].max() if lmin < ymin: ymin = lmin if lmax > ymax: ymax = lmax self.axis.clear() self.axis.set_xlim(xmin, xmax) self.axis.set_ylim(ymin, ymax) for graph in reescaled: self.axis.plot(graph[0],graph[1], 'o') self.canvas.draw() def exportDat(self): fileName = tk.filedialog.asksaveasfilename(filetypes=[('data','.dat'),('text','.txt')]) if fileName is None: return reescaled = reescale(self.resVal.returnVals(),self.sysSizes, self.plotData) comment = "#a=%lf b=%lf x_c=%lf\n"%tuple(self.resVal.returnVals()) comment += "#" for size in self.sysSizes: comment += "% 8d\t \t"%(size) comment += "\n" bigest = 0 for element in reescaled: if bigest < len(element[0]): bigest = len(element[0]) with open(fileName, 'w') as saida: saida.write(comment) for i in range(bigest): for array in reescaled: if i < len(array[0]): saida.write("%lf\t%lf\t"%(array[0][i],array[1][i])) else: saida.write(" \t \t") saida.write("\n") #for i in range(len(reescaled[0][0])): # for j in range(len(reescaled)): # for k in range(2): # output.write("%lf\t"%(reescaled[j][k][i])) # output.write("\n") def updateDist(self): dist = distCurves(self.resVal.returnVals(),self.sysSizes, self.plotData, self.resVal.xminVar.get(), self.resVal.xmaxVar.get()) self.distLabel.configure(text="S = %g"%(dist)) def approximate(self): guess = self.resVal.returnVals() xmin = self.resVal.xminVar.get() xmax = self.resVal.xmaxVar.get() res = minimize(distCurves, guess , args=(self.sysSizes, self.plotData, xmin, xmax), method='Nelder-Mead', options={'maxiter': self.Ninterac.get()}) self.resVal.setDefault(res['x'],xmin,xmax) #self.distLabel.configure(text="S = %g"%(res['fun'])) self.graphReplot()
class PageCapital(tk.Frame): """ 资金曲线绘制 每日资金记录 """ def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # 该 list 内部存放多个子 list,每个子 list 为 [标注点的坐标, 标注] self.data_notes = [] topFrame = tk.Frame(self) # 创建一个空的 DataFrame self.df_data = pd.DataFrame(columns=['date', 'balance', 'memo']) self.btnMainPage = tk.Button(topFrame, text="主页面", command=self.on_btn_main_page).pack( side=tk.LEFT, padx=4) # 日期选择 # Calendar((x, y), 'ur').selection() 获取日期,x,y为点坐标 date_start_gain = lambda: [ self.date_start.set(date) for date in [CalendarCustom(None, 'ur').selection()] if date ] tk.Button(topFrame, text='日期:', command=date_start_gain).pack(side=tk.LEFT, padx=4) self.date_start = tk.StringVar() ttk.Entry(topFrame, textvariable=self.date_start).pack(side=tk.LEFT) today = datetime.date.today() self.date_start.set(today) tk.Label(topFrame, text="账户余额:").pack(side=tk.LEFT) self.strBalance = tk.StringVar(value='') ttk.Entry(topFrame, width=15, textvariable=self.strBalance).pack(side=tk.LEFT, padx=4) tk.Label(topFrame, text="备注:").pack(side=tk.LEFT) self.strMemo = tk.StringVar(value='') ttk.Entry(topFrame, width=25, textvariable=self.strMemo).pack(side=tk.LEFT, padx=4) tk.Button(topFrame, text="添加", width=10, command=self.on_btn_add).pack(side=tk.LEFT, padx=4) topFrame.pack(side=tk.TOP, fill=tk.BOTH) # 列表框 frameReport = tk.Frame(self) mlbDatasFrame = tk.Frame(frameReport) scrollbarBalance = tk.Scrollbar(mlbDatasFrame, orient=tk.HORIZONTAL) scrollbarBalanceV = tk.Scrollbar(mlbDatasFrame, orient=tk.VERTICAL) self.mlbBalance = treectrl.MultiListbox( mlbDatasFrame, xscrollcommand=scrollbarBalance.set, yscrollcommand=scrollbarBalanceV.set) scrollbarBalance.config(command=self.mlbBalance.xview) scrollbarBalance.pack(side=tk.BOTTOM, fill=tk.X) scrollbarBalanceV.config(command=self.mlbBalance.yview) scrollbarBalanceV.pack(side=tk.RIGHT, fill=tk.Y) self.mlbBalance.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.mlbBalance.focus_set() self.mlbBalance.configure(selectcmd=self.tree_solution_selected, selectmode='single') self.mlbBalance.config(columns=('日期', '余额', '备注')) mlbDatasFrame.pack(side=tk.TOP, fill=tk.BOTH, expand=1) frameReport.pack(side=tk.LEFT, fill=tk.BOTH, expand=0, pady=4) # 显示中文标签 plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示负号 plt.rcParams['axes.unicode_minus'] = False # 有中文使用 u'中文内容' self.draw() self.load_data() def tree_solution_selected(self, selected): print('tree_solution_selected items:', selected) pass def load_data(self): try: self.mlbBalance.delete('all') coll_capital = dbDoc['capital'] records = coll_capital.find({}, { "_id": 0, 'date': 1, 'balance': 1, 'memo': 1 }).sort('date', pymongo.DESCENDING) # 列表显示是降序排列 for data in records: self.mlbBalance.insert( 'end', *map(unicode, (data['date'], data['balance'], data['memo']))) # 绘图是升序排列 records = coll_capital.find({}, { "_id": 0, 'date': 1, 'balance': 1, 'memo': 1 }).sort('date', pymongo.ASCENDING) datas = [] for data in records: datas.append( [data['date'], float(data['balance']), data['memo']]) self.df_data = pd.DataFrame(datas, columns=['date', 'balance', 'memo']) self.df_data['date'] = pd.to_datetime(self.df_data['date'], format='%Y-%m-%d') self.df_data['date'] = self.df_data['date'].dt.date try: self.ax.clear() # x = self.df_data['date'] # y = self.df_data['balance'] # for i in range(len(x)): # # 标注点的坐标 # point_x = x[i] # point_y = y[i] # # # point, = plt.plot(point_x, point_y, 'o', c='darkgreen') # # point, = self.ax.plot(point_x, point_y, marker='o', mec='b', mfc='w') # # # 标注框偏移量 # offset1 = 40 # offset2 = 40 # # 标注框 # bbox1 = dict(boxstyle="round", fc='lightgreen', alpha=0.6) # # 标注箭头 # arrowprops1 = dict(arrowstyle="->", connectionstyle="arc3,rad=0.") # # # 标注 # annotation = plt.annotate('{},{}'.format(point_x, point_y), xy=(x[i], y[i]), # xytext=(-offset1, offset2), # textcoords='offset points', # bbox=bbox1, arrowprops=arrowprops1, size=15) # # # 默认鼠标未指向时不显示标注信息 # annotation.set_visible(False) # self.data_notes.append([point, annotation]) # # point.remove() plt.xticks(range(len(self.df_data['date'])), self.df_data['date'], rotation=30) # rotation表示x轴刻度旋转度数 self.line, = plt.plot(self.df_data['balance'], marker='o', mec='b', mfc='w') locator = matplotlib.dates.AutoDateLocator() self.ax.xaxis.set_major_locator(locator) except Exception as e: import traceback traceback.print_exc() errMsg = traceback.format_exc() # 提示信息 self.log.error("read contour exception." + errMsg) self.ax.autoscale(enable=True, tight=False) self.ax.grid(True, linestyle='-.') except: import traceback traceback.print_exc() errMsg = traceback.format_exc() print(errMsg) pass # 定义鼠标响应函数 def on_move(self, event): visibility_changed = False for point, annotation in self.data_notes: should_be_visible = (point.contains(event)[0] == True) if should_be_visible != annotation.get_visible(): visibility_changed = True annotation.set_visible(should_be_visible) if visibility_changed: plt.draw() def update_annot(self, ind): names = pd.np.array(list("ABCDEFGHIJKLMNO")) x, y = self.line.get_data() print(ind["ind"][0]) print(x[ind["ind"][0]]) self.annot.xy = (40, 40) text = "{}".format(" ".join(list(map(str, ind["ind"])))) self.annot.set_text(text) self.annot.get_bbox_patch().set_alpha(0.4) def hover(self, event): vis = self.annot.get_visible() if event.inaxes == self.ax: cont, ind = self.line.contains(event) if cont: # print(event.) self.update_annot(ind) self.annot.set_visible(True) plt.draw() else: if vis: self.annot.set_visible(False) plt.draw() def draw(self): self.fig = plt.figure(num=1) self.ax = self.fig.add_subplot(111) self.annot = self.ax.annotate("", xy=(0, 0), xytext=(-20, 20), textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) self.annot.set_visible(False) def format_coord(x, y): return 'x=%1.4f, y=%1.4f' % (x, y) self.ax.format_coord = format_coord self.canvas = FigureCanvasTkAgg(self.fig, self) toolbar = NavigationToolbar2Tk(self.canvas, self) toolbar.update() toolbar.pack(side=tk.TOP, fill=tk.BOTH, expand=False) self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) # 鼠标移动事件 on_move_id = self.fig.canvas.mpl_connect('motion_notify_event', self.hover) # self.canvas.mpl_connect('key_press_event', toggle_selector) # self.canvas.mpl_connect('draw_event', self.onZoomCallback) # self.RS.set_active(False) def on_btn_add(self): if len(self.strBalance.get()) == 0: tk.messagebox.showwarning(title='警告', message='缺少余额数据') return coll_capital = dbDoc['capital'] record = coll_capital.find_one({'date': self.date_start.get()}) if record: tk.messagebox.showwarning(title='警告', message='指定日期数据已存在') return result = coll_capital.insert_one({ 'date': self.date_start.get(), 'balance': self.strBalance.get(), 'memo': self.strMemo.get() }) # print(result.inserted_id) self.load_data() pass def on_btn_main_page(self): self.controller.show_frame('PageMain') pass
class From: def __init__(self): self.root = tk.Tk() #创建主窗体 self.canvas = tk.Canvas() #创建一块显示图形的画布 #self.figure=self.create_matplotlib() #返回matplotlib所画图形的figure对象 self.code_index = 0 self.code = codes[self.code_index] self.datas = getData(self.code) self.index = len(self.datas[-1]) - 100 self.figure = drawfig(self.index, self.datas) self.create_form(self.figure) #将figure显示在tkinter窗体上面 #self.root.geometry('600x300') self.root.mainloop() def _getNext(self): """计算index return: bool 是否到结尾 """ #当前code已到结尾或超过设定时间, 那么跳到下一个code while True: self.index += 1 if self.index >= len(self.datas[0]): #go to next code self.code_index += 1 if self.code_index >= len(codes): #go to end return False self.code = codes[self.code_index] self.datas = getData(self.code) self.index = len(self.datas[-1]) - 100 boll_up, boll_mid, boll_low, df, adx = self.datas adx = int(adx[self.index]) bolls = getBolls(boll_up[self.index], boll_mid[self.index], boll_low[self.index]) boll_w = 100 * abs(boll_up[self.index] - boll_low[self.index]) / boll_mid[self.index] close = df.iloc[self.index]['c'] if allow_pos_w_adx(close, bolls, boll_w) and adx > 30: return True return True def create_form(self, figure): #把绘制的图形显示到tkinter窗口上 self.canvas = FigureCanvasTkAgg(figure, self.root) self.canvas.draw( ) #以前的版本使用show()方法,matplotlib 2.2之后不再推荐show()用draw代替,但是用show不会报错,会显示警告 #self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.canvas.get_tk_widget().grid(row=0, column=0, rowspan=7) #添加button x_pos = 300 y_pos = 10 label_adx = tk.Label(self.root, text='ADX= ').place(x=250, y=y_pos) var_adx = tk.StringVar() var_adx.set('0') entry_adx = tk.Entry(self.root, textvariable=var_adx) entry_adx.place(x=300, y=y_pos, width=30) label_bollw = tk.Label(self.root, text='BollW= ').place(x=0, y=y_pos) var_bollw = tk.StringVar() var_bollw.set('0') entry_bollw = tk.Entry(self.root, textvariable=var_bollw) entry_bollw.place(x=60, y=y_pos, width=50) label_four = tk.Label(self.root, text='FOUR= ').place(x=110, y=y_pos) var_four = tk.StringVar() var_four.set('0') entry_four = tk.Entry(self.root, textvariable=var_four) entry_four.place(x=170, y=y_pos, width=50) mylabel = tk.Label(self.root, text='选择状态: ').place(x=340, y=y_pos) var_usr_name = tk.StringVar() var_usr_name.set('0-7') entry_usr_name = tk.Entry(self.root, textvariable=var_usr_name) entry_usr_name.place(x=x_pos + 120, y=y_pos) #加载之前已保存的结果 df_result = DfResult() df_result.clear() def write_result(label): b = self._getNext() #if self.index == 103: #b = False while b: #写结果 df = self.datas[-2] t = str(df.index[self.index]) t1 = t.replace(' ', '_') t1 = t1.replace(':', '_') fname = self.code + '_' + t1 + '.png' print(fname) #判断是否已经保存过 b = False if len(df_result.df) == 0: b = True elif not (df_result.df[2] == fname).any(): b = True if b: u, m, l, df, adx = self.datas #计算显示的指标值 bollw = (u[self.index] - l[self.index]) / m[self.index] * 100 adx = int(adx[self.index]) four = stock.FOUR(df[:self.index]['c']) var_four.set(agl.float_to_2(four[-1] * 100)) var_adx.set(agl.float_to_2(adx)) var_bollw.set(agl.float_to_2(bollw)) fname1 = df_result.dir_img + fname drawfig(self.index, self.datas) self.canvas.draw() plt.savefig(fname1) result = [self.code, t, fname, label] df_result.insert(result) break else: #发现已经录入 b = self._getNext() if not b: #显示已结束 f.clf() f.text(0.5, 0.5, 'its end', color='r') self.canvas.draw() #输出到文件 df_result.save() def button_handle_0(): var_usr_name.set(0) write_result(0) def button_handle_1(): var_usr_name.set(1) write_result(1) def button_handle_2(): var_usr_name.set(2) write_result(2) def button_handle_3(): var_usr_name.set(3) write_result(3) def button_handle_4(): var_usr_name.set(4) write_result(4) def button_handle_5(): var_usr_name.set(5) write_result(5) def button_handle_6(): var_usr_name.set(6) write_result(6) fns = [ button_handle_0, button_handle_1, button_handle_2, button_handle_3, button_handle_4, button_handle_5, button_handle_6 ] def key(event): #print "pressed", repr(event.char) c = event.char if c >= '0' and c <= '6': #var_usr_name.set(event.char) fns[int(c)]() for i in range(7): button = tk.Button(self.root, text=str(i), command=fns[i], width=10, height=2) #button.place(x=170, y=230) button.grid(row=i, column=1) self.root.bind('<Key>', key) def on_closing(): df_result.save() self.root.destroy() self.root.protocol("WM_DELETE_WINDOW", on_closing)
class dataViewer(tk.Tk): def __init__(self, title='', font=font, figsize=figsize, dpi=dpi, fp=fp): super().__init__() self.wm_title('Data Viewer') self.protocol('WM_DELETE_WINDOW', self._quit) self.resizable(width=False, height=False) self.title = title self.font = font self.fp = fp self.figsize = figsize self.dpi = dpi self.btn = {} self.createCanvas() def load_data(self, df, title=''): self.vars = {} self.btn = {} self.df = df self.labels = self.df.axes[1] self.set_color() self.tmp = np.asarray(self.df) self.length = self.tmp.shape[0] self.maximum = np.max(self.tmp) self.maximum = (self.maximum // 500 + 1) * 500 self.minimum = np.min(self.tmp) self.minimum = (self.minimum // 500) * 500 self.title = title self.createWidget() def load_csv(self, path, title=''): df = pd.read_csv(path) self.load_data(df, title) def set_color(self): self.color = {} for i in range(len(self.labels)): self.color[self.labels[i]] = 'C' + str(i) def createCanvas(self): fig = plt.figure(figsize=self.figsize, dpi=self.dpi) self.ax = fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(fig, master=self) self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) #toolbar = NavigationToolbar2TkAgg(self.canvas, self) #toolbar.update() self.rightframe = tk.Frame(master=self) self.rightframe.pack(side=tk.RIGHT) self.btnpanel = tk.Frame(master=self.rightframe) self.btnpanel.pack(side=tk.TOP) tk.Button(master=self.btnpanel, font=self.font['button'], text='打开', command=self.openfile).pack(side=tk.LEFT) tk.Button(master=self.btnpanel, font=self.font['button'], text='退出', command=self._quit).pack(side=tk.LEFT) self.funcpanel = tk.Frame(master=self.rightframe) self.funcpanel.pack(side=tk.TOP) tk.Button(master=self.funcpanel, font=font['button'], text='反选', command=self.reverse).pack(side=tk.LEFT) tk.Button(master=self.funcpanel, font=font['button'], text='全选', command=self.select_all).pack(side=tk.LEFT) def createWidget(self): for key in self.labels: self.vars[key] = tk.IntVar() btn = tk.Checkbutton(master=self.rightframe, text=key, variable=self.vars[key], width=45, onvalue=1, offvalue=0, command=self.draw) self.btn[key] = btn btn.select() btn.config(font=self.font['label']) btn.pack(side=tk.TOP) self.draw() def draw(self): x = np.linspace(0, self.length - 1, self.length) self.ax.clear() for key in self.labels: if self.vars[key].get() > 0: y = np.asarray(self.df.loc[:, [key]]).reshape(-1) self.ax.plot(x, y, label=key, color=self.color[key]) self.ax.set_ylim([self.minimum, self.maximum]) self.ax.set_xlim([0, self.length]) if self.title: self.ax.set_title(self.title) self.ax.legend(prop=ft) self.canvas.draw() def openfile(self): filename = filedialog.askopenfilename(title='打开csv文件', filetypes=[('csv文件', '*.csv'), ('All Files', '*')], initialdir='.') if filename: for key in self.btn: print(self.btn[key]) self.btn[key].destroy() self.load_csv(filename) def reverse(self): for key in self.vars: if self.vars[key].get() == 1: self.btn[key].deselect() else: self.btn[key].select() self.draw() def select_all(self): for key in self.vars: self.btn[key].select() self.draw() def _quit(self): self.quit() self.destroy()
class ConfigWindow(tk.Toplevel): '''Configuration window to generate new projections.''' def __init__(self, parent, main, root, *args, winProperties={}, entryProperties={}, textProperties={}, title='None', **kwargs): ''' Init function. Mandatory parameters -------------------- main : tkinter widget main parent window parent : tkinter widget parent widget root : tkinter widget root object Optional parameters ------------------- entryProperties : dict properties to be passed to the entries Default is an empty dict. textProperties : dict properties to be passed to the Labels. Default is an empty dict. title : str window title. Default is 'None'. winProperties : dict properties to be passed to the Toplevel window. Default is an empty dict. ''' # Setup attributes self.main = main self.parent = parent self.root = root self.name = title self.runState = False self.xres = 720 self.yres = 720 # Dictionnary with flags to know when a value is incorrect before launching the projection routine self.error = {'step' : True, 'res' : False, 'inputFile' : True, 'projectName' : True } # Layout properties self.winProperties = winProperties self.entryProperties = entryProperties self.textProperties = textProperties # Attributes related to the matplotlib graph self.data = None self.canvas = None self.crosshair = None # Allowed file types and file extensions when loading the image self.filetypes = [('PNG', '*.png'), ('JEPG', '*.jpeg'), ('JPG', '*.jpg'), ('GIF', '*.gif')] self.extensions = [i[1].strip('.*').lower() for i in self.filetypes] ################################################ # Default properties # ################################################ if 'bg' not in self.winProperties: self.winProperties['bg'] = self.main.bg if 'font' not in self.textProperties: self.textProperties['font'] = (self.main.font, 11, 'bold') if 'fg' not in self.entryProperties: self.entryProperties['fg'] = 'black' super().__init__(self.root, **winProperties) # Need to handle MAC and Windows cases try: self.wm_attributes('-type', ['dialog']) except: pass self.protocol("WM_DELETE_WINDOW", self.close) self.title(self.name) # Setup window size size = (850, 220) self.geometry('%dx%d+%d+%d' %(size[0], size[1], (self.root.winfo_screenwidth()-size[0])//2, (self.root.winfo_screenheight()-size[1])//2)) ######################################## # Scale properties # ######################################## hoverParams = {'highlightbackground':'RoyalBlue2', 'activebackground':'RoyalBlue2'} normalState = {'troughcolor':'lavender', 'highlightbackground':self.winProperties['bg'], 'cursor':'hand1', 'activebackground':'RoyalBlue2'} errorState = {'troughcolor':'lavender', 'highlightbackground':'firebrick1', 'cursor':'hand1', 'activebackground':'black'} disabledState = {'troughcolor':self.winProperties['bg'], 'highlightbackground':self.winProperties['bg'], 'cursor':'arrow', 'activebackground':'black'} ################################### # Setup widgets # ################################### ''' Master frames ------------- self.masterFrame : main frame containing all the others self.line1 : 1st line frame self.line2 : 2nd line frame self.dposFrame : frame containing the default position widgets self.entryFrame : frame containing the entry widgets on the second column self.line2col2 : frame for the second line of the second column ''' self.masterFrame = tk.Frame( self, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.line1 = tk.Frame( self.masterFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.line2 = tk.Frame( self.masterFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.entryFrame = tk.LabelFrame(self.line1, bg=self.winProperties['bg'], bd=0, highlightthickness=0, text='Project properties', font=self.textProperties['font']) self.line11 = tk.Frame( self.entryFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.dposFrame = tk.LabelFrame(self.line2, bg=self.winProperties['bg'], bd=0, highlightthickness=0, text='Default position', font=self.textProperties['font']) self.line2col2 = tk.Frame( self.line2, bg=self.winProperties['bg'], bd=1, highlightthickness=0) ''' Project name ------------ self.nameFrame : frame containing widgets relative to typing the project name ''' self.nameFrame = tk.Frame(self.line11, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.nameLabel = tk.Label(self.nameFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0, text='Project name', anchor=tk.W, font=(self.main.font, 10)) self.nameEntry = Entry( self.nameFrame, self, self.root, dtype=str, defaultValue='', traceCommand=self.checkName, **entryProperties) self.nameEntry.triggerError() ''' Open rectangular input file --------------------------- self.inputFame : frame containing widgets relative to selecting an input file self.inputFrame1 : frame for the label widget self.inputFrame2 : frame for the entry + button widgets ''' self.inputFrame = tk.Frame(self.entryFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.inputFrame1 = tk.Frame(self.inputFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.inputFrame2 = tk.Frame(self.inputFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.inputLabel = tk.Label(self.inputFrame1, bg=self.winProperties['bg'], bd=0, highlightthickness=0, text='Input file (equirectangular projection)', anchor=tk.W, font=(self.main.font, 10)) self.inputEntry = Entry( self.inputFrame2, self, self.root, dtype=str, defaultValue='', traceCommand=self.loadInput, **entryProperties) self.inputEntry.triggerError() self.inputButton = tk.Button(self.inputFrame2, image=self.main.iconDict['FOLDER_17'], bd=0, bg=self.winProperties['bg'], highlightbackground=self.winProperties['bg'], relief=tk.FLAT, activebackground='black', command=lambda *args, **kwargs: self.askLoad(title='Select a equirectangular surface image...', filetypes=self.filetypes)) # Output resolution widgets self.resFrame = tk.Frame(self.line11, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.resLabel = tk.Label(self.resFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0, text='Output file resolution (widthxheight)', anchor=tk.W, font=(self.main.font, 10)) self.resEntry = Entry(self.resFrame, self, self.root, dtype=str, defaultValue='720x720', traceCommand=self.checkResolution, **entryProperties) ''' Number of threads widgets ------------------------- self.threadAll : frame for all the thread widgets self.thLablFrame : frame for the label of the thread widgets self.threadFrame : frame for the buttons+entry of the thread widgets ''' self.threadAll = tk.Frame( self.line2col2, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.thLablFrame = tk.Frame( self.threadAll, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.threadLabel = tk.Label( self.thLablFrame, text='Number of threads', bg=self.winProperties['bg'], font=(self.main.font, 10), anchor=tk.W) self.threadFrame = tk.Frame( self.threadAll, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.minButton = tk.Button(self.threadFrame, bd=0, bg=self.winProperties['bg'], highlightbackground=self.winProperties['bg'], activebackground='black', state='disabled', text='-', font=('fixed', 10, 'bold'), activeforeground='white', command=lambda *args, **kwargs: None) self.maxButton = tk.Button(self.threadFrame, bd=0, bg=self.winProperties['bg'], highlightbackground=self.winProperties['bg'], activebackground='black', text='+', font=('fixed', 10, 'bold'), activeforeground='white', command=lambda *args, **kwargs: None) self.threadCount = tk.Label( self.threadFrame, width=3, justify=tk.CENTER, fg=self.entryProperties['fg'], bg=self.winProperties['bg'], text=1) ''' Longitude and latitude steps widgets ------------------------------------ self.stepAll : frame for all the step widgets self.stepLblFrame : frame for the label of the step widgets self.stepFrame : frame for the entry of the step widgets ''' self.stepAll = tk.Frame( self.line2col2, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.stepLblFrame = tk.Frame( self.stepAll, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.stepLabel = tk.Label( self.stepLblFrame, bg=self.winProperties['bg'], text='Step (°)', font=(self.main.font, 10), anchor=tk.W) self.stepFrame = tk.Frame( self.stepAll, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.stepEntry = Entry( self.stepFrame, self, self.root, dtype=float, defaultValue=0, width=3, justify=tk.CENTER, **entryProperties, traceCommand=lambda *args, **kwargs: self.updateStep(*args, **kwargs)) self.stepEntry.triggerError() self.stepEntry.configure(fg='firebrick1') # Run widgets self.runButton = tk.Button(self.line2col2, bg=self.winProperties['bg'], bd=0, image=self.parent.iconDict['RUN'], highlightthickness=0, highlightbackground=self.winProperties['bg'], relief=tk.FLAT, activebackground=self.winProperties['bg'], command=self.run) # Default position self.dposLatFrame = tk.Frame(self.dposFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.dposLonFrame = tk.Frame(self.dposFrame, bg=self.winProperties['bg'], bd=0, highlightthickness=0) self.dposLatLabel = tk.Label(self.dposLatFrame, text='Latitude', bg=self.winProperties['bg'], font=(self.main.font, 10), anchor=tk.W) self.dposLonLabel = tk.Label(self.dposLonFrame, text='Longitude', bg=self.winProperties['bg'], font=(self.main.font, 10), anchor=tk.W) self.dposLatScale = Scale( self.dposLatFrame, self, self.root, disable=True, initValue=0, hoverParams=hoverParams, normalStateParams=normalState, errorStateParams=errorState, disabledStateParams=disabledState, length=200, width=12, orient='horizontal', from_=-90, to=90, resolution=0.1, showvalue=False, sliderrelief=tk.FLAT, bg=self.winProperties['bg'], bd=1, highlightthickness=1, highlightbackground=self.winProperties['bg'], troughcolor=self.winProperties['bg'], command=lambda *args, **kwargs: self.sliderUpdate(self.dposLatScale, *args, **kwargs)) self.sliderUpdate(self.dposLatScale) self.dposLonScale = Scale( self.dposLonFrame, self, self.root, disable=True, initValue=0, hoverParams=hoverParams, normalStateParams=normalState, errorStateParams=errorState, disabledStateParams=disabledState, length=200, width=12, orient='horizontal', from_=-180, to=180, resolution=0.1, showvalue=False, sliderrelief=tk.FLAT, bg=self.winProperties['bg'], bd=1, highlightthickness=1, highlightbackground=self.winProperties['bg'], troughcolor=self.winProperties['bg'], command=lambda *args, **kwargs: self.sliderUpdate(self.dposLonScale, *args, **kwargs)) self.sliderUpdate(self.dposLonScale) ####################################################################### # Bindings # ####################################################################### # Buttons bindings self.minButton.bind('<Button-1>', lambda *args, **kwargs: self.decreaseThread(*args, **kwargs) if self.minButton['state'] != 'disabled' else None) self.maxButton.bind('<Button-1>', lambda *args, **kwargs: self.increaseThread(*args, **kwargs) if self.maxButton['state'] != 'disabled' else None) ########################################################## # Drawing frames # ########################################################## # Resolution widgets self.resLabel.pack(side=tk.TOP, fill='x', expand=True) self.resEntry.pack(side=tk.BOTTOM, fill='x', expand=True) self.resFrame.pack(side=tk.LEFT, fill='x', padx=10, pady=12) # Project name widgets self.nameLabel.pack(side=tk.TOP, fill='x', expand=True) self.nameEntry.pack(side=tk.BOTTOM, fill='x', expand=True) self.nameFrame.pack(side=tk.TOP, fill='x', expand=True, padx=10, pady=12) # Open file widgets self.inputLabel.pack( side=tk.LEFT, fill='x', expand=True) self.inputFrame1.pack(side=tk.TOP, fill='x', expand=True) self.inputEntry.pack( side=tk.LEFT, fill='x', expand=True) self.inputButton.pack(side=tk.RIGHT, padx=10) self.inputFrame2.pack(side=tk.BOTTOM, fill='x', expand=True) self.inputFrame.pack( side=tk.BOTTOM, fill='x', padx=10) # Thread widgets self.threadLabel.pack(side=tk.LEFT) self.minButton.pack( side=tk.LEFT) self.threadCount.pack(side=tk.LEFT, padx=5) self.maxButton.pack( side=tk.LEFT) self.thLablFrame.pack(side=tk.TOP) self.threadFrame.pack(side=tk.BOTTOM) self.threadAll.pack( side=tk.LEFT, padx=10, anchor=tk.N+tk.W) # Step widgets self.stepLabel.pack( side=tk.LEFT) self.stepEntry.pack( side=tk.BOTTOM, pady=5) self.stepLblFrame.pack(side=tk.TOP) self.stepFrame.pack( side=tk.BOTTOM) self.stepAll.pack( side=tk.LEFT, padx=10, anchor=tk.N+tk.E) # Run widget self.runButton.pack( side=tk.RIGHT, padx=10, anchor=tk.CENTER) self.runButton.config(state=tk.DISABLED) # Default position widgets self.dposLatLabel.pack(side=tk.TOP, fill='x', expand=True) self.dposLatScale.pack(side=tk.BOTTOM, fill='x', expand=True) self.dposLonLabel.pack(side=tk.TOP, fill='x', expand=True) self.dposLonScale.pack(side=tk.BOTTOM, fill='x', expand=True) self.dposLatFrame.pack(side=tk.LEFT, fill='x', padx=15, pady=10, expand=True) self.dposLonFrame.pack(side=tk.LEFT, fill='x', pady=10, expand=True) # Master frames self.entryFrame.pack( side=tk.LEFT, fill='x', padx=3, expand=True) self.line1.pack( side=tk.TOP, fill='x') self.line11.pack( side=tk.LEFT, fill='x', expand=True) self.dposFrame.pack( side=tk.LEFT, fill='x', padx=3, expand=True) self.line2col2.pack( side=tk.LEFT , fill='x', padx=3, pady=5, anchor=tk.S) self.line2.pack( side=tk.LEFT, fill='x', pady=10, expand=True) self.masterFrame.pack( side=tk.TOP, fill='x', pady=5) return ######################################################## # Resolution widgets interaction # ######################################################## def checkResolution(self, *args, **kwargs): '''Actions taken when the resolution is changed.''' resolution = self.resEntry.value.split('x') # If syntax is not 'n1xn2' trigger error if len(resolution)!=2: self.resEntry.configure(fg='firebrick1') self.resEntry.triggerError() self.error['res'] = True return # If non numeric characters appear, trigger error try: xres = int(resolution[0]) yres = int(resolution[1]) except ValueError: self.resEntry.configure(fg='firebrick1') self.resEntry.triggerError() self.error['res'] = True return # If negative integers, trigger error if xres <= 0 or yres <=0: self.resEntry.configure(fg='firebrick1') self.resEntry.triggerError() self.error['res'] = True return else: self.resEntry.configure(fg=self.entryProperties['fg']) self.xres = xres self.yres = yres self.resEntry.removeError() self.error['res'] = False self.checkRun() return ####################################### # Name interactions # ####################################### def checkName(self, *args, **kwargs): '''Actions taken when the name is changed.''' if self.nameEntry.value != '': self.nameEntry.removeError() self.error['projectName'] = False else: self.nameEntry.triggerError() self.error['projectName'] = True self.checkRun() return ####################################### # Step interactions # ####################################### def updateStep(self, *args, **kwargs): '''Actions taken when the value of the step entry is updated.''' value = self.stepEntry.value if value== '' or float(value)<=0 or float(value)>45: self.stepEntry.triggerError() self.stepEntry.configure(fg='firebrick1') self.error['step'] = True else: self.stepEntry.removeError() self.stepEntry.configure(fg=self.entryProperties['fg']) self.error['step'] = False self.checkRun() return ############################################ # Thread interactions # ############################################ def decreaseThread(self, *args, **kwargs): '''Decrease by 1 the number of threads.''' value = int(self.threadCount.cget('text')) if value > 1: self.threadCount.configure(text=value-1) self.updateThreadButtons() return def increaseThread(self, *args, **kwargs): '''Decrease by 1 the number of threads.''' value = int(self.threadCount.cget('text')) if value < self.main.cpuCount: self.threadCount.configure(text=value+1) self.updateThreadButtons() return def updateThreadButtons(self, *args, **kwargs): '''Update the state of the thread buttons.''' if int(self.threadCount.cget('text')) == 1: self.minButton.config(state='disabled') elif int(self.threadCount.cget('text')) == self.main.cpuCount: self.maxButton.config(state='disabled') else: if self.minButton.cget('state') not in ['normal', 'active']: self.minButton.config(state='normal') if self.maxButton.cget('state') not in ['normal', 'active']: self.maxButton.config(state='normal') return ############################################ # Sliders interactions # ############################################ def sliderUpdate(self, slider, *args, **kwargs): '''Actions taken when the slider is updated.''' value = slider.get() if slider is self.dposLatScale: self.dposLatLabel.configure(text='Latitude: %.1f°' %value) self.updateCrosshair('black') elif slider is self.dposLonScale: self.dposLonLabel.configure(text='Longitude: %.1f°' %value) self.updateCrosshair('black') self.checkRun() return ####################################### # Loading file(s) # ####################################### def askLoad(self, *args, title='', filetypes=('All files', '*.*'), **kwargs): '''Asking which file to open.''' try: # Load YAML file fname = askopenfilename(initialdir=self.main.loadPath, title=title, filetypes=tuple([['All files', '*.*']] + filetypes)) except: print('Failed to open file...') return None if fname == () or fname == '': return None else: self.main.loadPath = opath.dirname(fname) self.inputEntry.var.set(fname) return fname def loadInput(self, *args, **kwargs): '''Load the input file into the matplotlib frame and write its name into the entry widget.''' def okFunction(*args, **kwargs): try: # Change entry text color to ok self.inputEntry.configure(fg=self.entryProperties['fg']) # Change out to error state self.inputEntry.removeError() # Resize window size = (850, 650) self.geometry('%dx%d' %(size[0], size[1])) # Update sliders for widget in [self.dposLatScale, self.dposLonScale]: widget.normalState() # Load graph onto the window self.makeGraph() except: print('An error occured while loading data.') return def errorFunction(*args, **kwargs): # Change entry text color to error self.inputEntry.configure(fg='firebrick1') # Change to error state self.inputEntry.triggerError() # Hide graph in the window self.hideGraph() # Resize window size = (850, 220) self.geometry('%dx%d' %(size[0], size[1])) # Update sliders for widget in [self.dposLatScale, self.dposLonScale]: widget.disabledState() self.checkRun() return # Retrieve name written in Entry fname = self.inputEntry.var.get() # If empty string, set back the default foreground color if fname == '': self.inputEntry.configure(fg=self.entryProperties['fg']) errorFunction() self.error['inputFile'] = True self.checkRun() return # If no file was selected or if an error occured, do nothing elif fname is None: return # Otherwise check whether the file exists and apply the correct function else: self.checkFile(fname, okFunction=okFunction, errorFunction=errorFunction) self.checkRun() return ################################################### # Axis methods # ################################################### def makeAxis(self, *args, **kwargs): '''Creating a new axis.''' self.ax = self.figure.add_subplot(111) self.setAxis() return def updateAxis(self, *args, **kwargs): '''Update the data in the axis.''' self.setAxis() return def updateCrosshair(self, color, *args, **kwargs): '''Update the crosshair.''' if self.data is not None: xpos = self.xlim[0] + (float(self.dposLonScale.get()) + 180)/360 * (self.xlim[1] - self.xlim[0]) ypos = self.ylim[1] - (float(self.dposLatScale.get()) + 90 )/180 * (self.ylim[1] - self.ylim[0]) if self.crosshair is None: self.crosshair = self.ax.plot([xpos], [ypos], marker='x', markersize=15, color=color, markeredgewidth=5)[0] else: self.crosshair.set_xdata([xpos]) self.crosshair.set_ydata([ypos]) self.crosshair.set_color(color) self.canvas.draw_idle() return def setAxis(self, *args, **kwargs): '''Set the axis for a new figure.''' self.ax.autoscale_view(True,True,True) self.ax.clear() self.ax.yaxis.set_ticks_position('none') self.ax.yaxis.set_ticks([]) self.ax.xaxis.set_ticks_position('none') self.ax.xaxis.set_ticks([]) # Default empty image if self.data is None: print('No data loaded...') self.data = [[0]*4]*2 self.im = self.ax.imshow(self.data, cmap='Greys') self.xlim = self.ax.get_xlim() self.ylim = self.ax.get_ylim()[::-1] return ################################################### # Graph methods # ################################################### def hideGraph(self, *args, **kwargs): '''Hide the graph frame if no data is loaded.''' if self.canvas is not None: self.crosshair = None self.figframe.pack_forget() return def makeGraph(self, *args, **kwargs): '''Generate a matplotlib graph with the image loaded.''' # RGB array with image data self.data = plt.imread(self.inputEntry.var.get(), format=opath.splitext(self.inputEntry.var.get())[-1]) if self.canvas is None: # Get background color and convert in matplotlib RGB values color = [i/255**2 for i in self.root.winfo_rgb(self.winProperties['bg'])] self.figure = Figure(figsize=(20, 10), constrained_layout=True, facecolor=color) self.makeAxis() # Canvas holding figure self.figframe = tk.Frame( self, bg='lavender', bd=1, highlightthickness=0) self.canvas = FigureCanvasTkAgg(self.figure, master=self.figframe) self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) else: self.updateAxis() # Draw frame containing the figure self.canvas.draw() self.figframe.pack(side=tk.BOTTOM, fill='x', expand=True) # Set crosshair self.updateCrosshair('black') return ################################################# # Miscellaneous functions # ################################################# def close(self, *args, **kwargs): '''Actions taken when the window is closed.''' self.main.confButton.configure(state=tk.NORMAL) self.withdraw() return True def checkFile(self, file, *args, okFunction=lambda *args, **kwargs: None, errorFunction=lambda *args, **kwargs: None, **kwargs): ''' Check whether a file exists and has the correct type and apply the correct function depending on the result. # Arrays of latitude and longitude where to compute the projections Mandatory parameters -------------------- file : str file to check the existence Optional parameters ------------------- okFunction : function Function to apply when the file exists errorFunction : function Function to apply when the file does not exist Return the value returned by the correct function. ''' if not isinstance(file, str): raise TypeError('File must be a string.') if opath.exists(file) and file.split('.')[-1].lower() in self.extensions: self.error['inputFile'] = False return okFunction() else: self.error['inputFile'] = True return errorFunction() return def checkRun(self, *args, **kwargs): '''Check whether the projection can be run or not.''' if not self.runState: if any(self.error.values()): self.runButton.configure(state=tk.DISABLED) self.runButton.unbind('<Enter>') self.runButton.unbind('<Leave>') else: self.runButton.configure(state=tk.NORMAL) self.runButton.bind( '<Enter>', lambda *args, **kwargs: self.parent.iconDict['RUN'].configure(foreground='black')) self.runButton.bind( '<Leave>', lambda *args, **kwargs: self.parent.iconDict['RUN'].configure(foreground='white')) else: self.runButton.bind( '<Enter>', lambda *args, **kwargs: self.parent.iconDict['CHECK'].configure(foreground='black')) self.runButton.bind( '<Leave>', lambda *args, **kwargs: self.parent.iconDict['CHECK'].configure(foreground='firebrick1')) return def setTitle(self, title, *args, **kwargs): ''' Set a new title for the window. Parameters ---------- title : str the new title ''' if self.name != title: self.name = title self.title(self.name) return ##################################### # Run method # ##################################### def run(self, *args, **kwargs): '''Run the projection.''' if self.runState: self.runState = False for i in self.thread.threads: i.ok = False self.runButton.config(cursor='arrow', image=self.main.iconDict['RUN']) self.checkRun() print('Threads stopped') else: # Setup the function parameters for the projection data = self.data # Generate the file and directory names name = self.nameEntry.value directory = opath.join(opath.dirname(self.inputEntry.value), name) # Check that if directory exists, it only contain config files if opath.isdir(directory): files = [f for f in os.listdir(directory) if opath.isfile(opath.join(directory, f))] if any(['.yaml' not in i for i in files]): ErrorMessage(self, self.root, text='Directory %s is not empty.' %directory) return step = float(self.stepEntry.value) numThreads = int(self.threadCount.cget('text')) # Init pos must be given in grid units, so we must convert the given values to the closest one latInit = self.dposLatScale.get() longInit = self.dposLonScale.get() allLong = np.arange(-180, 180, step) allLat = np.arange(-90, 90+step, step) initPos = [int(np.argmin((allLong-longInit)**2)), int(np.argmin((allLat-latInit)**2))] size = (self.xres, self.yres) # Change button icon first self.config(cursor='watch') self.runState = True self.runButton.config(cursor='arrow', image=self.main.iconDict['CHECK']) self.checkRun() # Run thread self.thread = RunProjection(data, directory, name, step, numThreads, initPos=initPos, allLat=allLat, allLong=allLong, size=size) self.thread.start() self.thread.join() # Set back the icon self.config(cursor='arrow') self.runState = False self.runButton.config(cursor='arrow', image=self.main.iconDict['RUN']) self.checkRun() return
class Application(tk.Frame, object): """Main Class of the application Methods: __init__ -- Set up the UI build -- pass company data to autocompletebox UI component _update -- on update pass input data to build getGraphIncomeAnalysis -- Plot graph for income analysis getGraphExpenseAnalysis -- Plot graph for expense analysis getGraphLiabilityAnalysis --Plot graph for liability analysis """ def __init__(self, *args, **kwargs): super(Application, self).__init__(*args, **kwargs) self.dataPlot = None self.lf = None self.entry = AutocompleteEntry(self) self.build(case_sensitive=False, no_results_message=NO_RESULTS_MESSAGE) self.entry.grid(row=2, column=2, rowspan=1, columnspan=2, padx=10, pady=3) self.nr = tk.StringVar() def _update(self, *args): case_sensitive = False if self.cs.get() == "1": case_sensitive = False no_results_message = self.nr.get() self.build(case_sensitive=case_sensitive, no_results_message=no_results_message) def build(self, *args, **kwargs): self.entry.build( code_dic.keys(), kwargs["case_sensitive"], kwargs["no_results_message"], ) def getGraphIncomeAnalysis(self): self.clearCanvas() company_name = root.children['!autocompleteentry'].selected_value company_tiker = code_dic[company_name].lower() dataAvailable = True try: df = getIncomeAnalysis(company_tiker) except: tk.messagebox.showinfo(title='Information', message='Data partially not available') dataAvailable = False if (df is not None and dataAvailable): self.lf = ttk.Labelframe(root, text='Income Analysis') self.lf.grid(row=3, column=3, columnspan=10, sticky='s', padx=3, pady=3) f = Figure(figsize=(10, 6), dpi=100) ax = f.add_subplot(111) df.plot(kind='line', x='Year', y=['NetIncome', 'TotalRevenue', 'GrossProfit', 'EBIT'], ax=ax) self.dataPlot = FigureCanvasTkAgg(f, master=self.lf) self.dataPlot.get_tk_widget().grid(row=3, column=3, columnspan=10) self.dataPlot.draw() else: tk.messagebox.showinfo(title='Information', message='Service Not Available') def getGraphExpenseAnalysis(self): self.clearCanvas() company_name = root.children['!autocompleteentry'].selected_value company_tiker = code_dic[company_name] dataAvailable = True try: df = getExpenseAnalysis(company_tiker) except: tk.messagebox.showinfo(title='Information', message='Data partially not available') dataAvailable = False if (df is not None and dataAvailable): self.lf = ttk.Labelframe(root, text='Expense Analysis') self.lf.grid(row=3, column=3, columnspan=10, sticky='s', padx=3, pady=3) fig, axes = plt.subplots(nrows=2, ncols=2) for ax, col in zip(axes.flat, df.columns): ax.pie(df[col], labels=df.index, autopct='%.2f') ax.set(title=col, aspect='equal') axes[0, 0].legend(bbox_to_anchor=(0, 0.5)) self.dataPlot = FigureCanvasTkAgg(fig, master=self.lf) self.dataPlot.get_tk_widget().grid(row=3, column=3, columnspan=10) self.dataPlot.draw() else: tk.messagebox.showinfo(title='Information', message='Service Not Available') def getGraphLiabilityAnalysis(self): self.clearCanvas() company_name = root.children['!autocompleteentry'].selected_value company_tiker = code_dic[company_name] dataAvailable = True try: df = getLiabilityAnalysis(company_tiker) except: tk.messagebox.showinfo(title='Information', message='Data partially not available') dataAvailable = False if (df is not None and dataAvailable): self.lf = ttk.Labelframe(root, text='Liability Analysis') self.lf.grid(row=3, column=3, columnspan=10, sticky='s', padx=3, pady=3) f = Figure(figsize=(10, 6), dpi=100) ax = f.add_subplot(111) df.plot(kind='bar', x='Year', ax=ax) self.dataPlot = FigureCanvasTkAgg(f, master=self.lf) self.dataPlot.draw() self.dataPlot.get_tk_widget().grid(row=3, column=3, columnspan=10) self.dataPlot.get_tk_widget().grid(row=3, column=3, columnspan=10) else: tk.messagebox.showinfo(title='Information', message='Service Not Available') def clearCanvas(self): if (self.dataPlot is not None): self.dataPlot.get_tk_widget().destroy() self.lf.destroy() self.dataPlot = None
class DisplaySavedFramesWindow(): """ DisplaySavedFramesWindow Class GUI window for displaying saved frame of a barcode around the clicked point """ def __init__(self, barcode, mouse_x, mouse_y, figsize=(10, 2), dpi=100): self.barcode = barcode # Initialize the window self.window = tkinter.Tk() self.window.wm_title("Display frames") self.window.iconbitmap(resource_path("kalmus_icon.ico")) # Set up the plotted figure self.fig = plt.figure(figsize=figsize, dpi=dpi) displayed_image = self.get_frames_image_for_display(mouse_x, mouse_y) plt.imshow(displayed_image) plt.axis("off") plt.tight_layout() # Set up the canvas for the figure self.canvas = FigureCanvasTkAgg( self.fig, master=self.window) # A tk.DrawingArea. self.canvas.draw() self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) # Initialize the plotting tool bar self.toolbar = NavigationToolbar2Tk(self.canvas, self.window) self.toolbar.update() self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) def get_frames_image_for_display(self, mouse_x, mouse_y): """ Get the frames around the clicked point :param mouse_x: The x position of the clicked point :param mouse_y: The y position of the clicked point :return: The combined sampled frames for displaying """ barcode_shape = self.barcode.get_barcode().shape # Get the middle position of the saved frame cur_pos = (mouse_x * barcode_shape[0] + mouse_y) / (barcode_shape[0] * barcode_shape[1]) frame_pos = round(cur_pos * len(self.barcode.saved_frames)) # Get another four frames around the middle frame # Make sure the frame positions/indexes are valid if frame_pos < 2: frame_pos = 2 if frame_pos > len(self.barcode.saved_frames) - 3: frame_pos = len(self.barcode.saved_frames) - 3 frames = self.barcode.saved_frames[frame_pos - 2:frame_pos + 3] # Get the combined five frames image combine_image = frames[0] for frame in frames[1:]: # Combine the frames into one image combine_image = np.concatenate((combine_image, frame), axis=1) return combine_image
class NewMapWindow(tk.Frame): """ Window for creating new map. """ def __init__(self, parent, main_window, controller): tk.Frame.__init__(self, parent) self.main_window = main_window self.controller = controller # height map self.subplot_height_map = None self.canvas_height_map = None self.height_map_path = "" # texture map self.subplot_texture_map = None self.canvas_texture_map = None self.texture_map_path = "" row = 0 column = 0 self.canvas = tk.Canvas(self, width=main_window.window_width-20, height=main_window.window_height) self.canvas.grid(row=0, column=0, sticky="nsew") scrollbar = tk.Scrollbar(self, command=self.canvas.yview) scrollbar.grid(row=0, column=1, sticky='ns') self.canvas.configure(yscrollcommand=scrollbar.set) # update scrollregion after starting 'mainloop' # when all widgets are in canvas self.canvas.bind('<Configure>', self.on_configure) self.frame = tk.Frame(self.canvas) self.canvas.create_window((0, 0), window=self.frame, anchor='nw') tk.Button(self.frame, text="< Back to maps", command=lambda: main_window.show_frame("MapWindow")).grid(row=row, column=column, pady=10) row += 1 tk.Label(self.frame, text="New map:", font='Helvetica 16 bold').grid(row=row, column=column, pady=10) height = 1 width = 10 column += 1 row += 1 tk.Label(self.frame, text="Name:").grid(row=row, column=column, pady=10) self.new_map_name = tk.Text(self.frame, height=height, width=width) self.new_map_name.grid(row=row, column=column + 1, pady=10) row += 1 tk.Label(self.frame, text="Biom:").grid(row=row, column=column, pady=10) self.biom = tk.ttk.Combobox(self.frame, values=[soil.name for soil in self.controller.bioms.values()]) self.biom.grid(row=row, column=column + 1, pady=10) row += 1 tk.Label(self.frame, text="Height conversion (one unit is how many meter?):").grid(row=row, column=column, pady=10) self.new_map_height_conversion = tk.Text(self.frame, height=height, width=width) self.new_map_height_conversion.grid(row=row, column=column + 1, pady=10) row += 1 tk.Label(self.frame, text="Maximum soil depth (in cm):").grid(row=row, column=column, pady=10) self.new_map_max_soil_depth = tk.Text(self.frame, height=height, width=width) self.new_map_max_soil_depth.grid(row=row, column=column + 1, pady=10) row += 1 tk.Label(self.frame, text="Pixel size (in m):").grid(row=row, column=column, pady=10) self.new_map_pixel_size = tk.Text(self.frame, height=height, width=width) self.new_map_pixel_size.grid(row=row, column=column + 1, pady=10) row += 1 # height map figure_height_map = Figure(figsize=(3, 3)) self.subplot_height_map = figure_height_map.add_subplot() self.subplot_height_map.title.set_text('Height map') self.canvas_height_map = FigureCanvasTkAgg(figure_height_map, master=self.frame) self.canvas_height_map.get_tk_widget().grid(row=row, column=column) tk.Button(self.frame, text="Load height-map", command=self.load_height_map).grid(row=row + 1, column=column) # soil id map figure_texture_map = Figure(figsize=(3, 3)) self.subplot_texture_map = figure_texture_map.add_subplot() self.subplot_texture_map.title.set_text('Soil-IDs map') self.canvas_texture_map = FigureCanvasTkAgg(figure_texture_map, master=self.frame) self.canvas_texture_map.get_tk_widget().grid(row=row, column=column + 1) tk.Button(self.frame, text="Load soil-id-map", command=self.load_texture_map).grid(row=row + 1, column=column + 1) row += 2 tk.Button(self.frame, text="Save map", command=lambda: self.save_map()).grid(row=row, column=column, pady=10, columnspan=2) def save_map(self): name = self.new_map_name.get("1.0", 'end-1c') biom = self.biom.get() height_conversion = float(self.new_map_height_conversion.get("1.0", 'end-1c')) max_soil_depth = float(self.new_map_max_soil_depth.get("1.0", 'end-1c')) pixel_distance = float(self.new_map_pixel_size.get("1.0", 'end-1c')) new_map = Map(name, biom, self.height_map_path, self.texture_map_path, height_conversion, max_soil_depth, pixel_distance) new_map.save_map() self.controller.load_maps() self.main_window.update_frame(ProbabilityCloudWindow) self.main_window.update_frame(MapWindow) def load_height_map(self): rep = askopenfilenames(parent=self, initialdir='/', initialfile='tmp', filetypes=[("Pictures", "*.png")]) if len(rep) > 0: self.height_map_path = rep[0] image_height_map = Image() image_height_map.load_image(self.height_map_path) self.subplot_height_map.imshow(image_height_map.image, cmap='gray') self.canvas_height_map.draw() def load_texture_map(self): rep = askopenfilenames(parent=self, initialdir='/', initialfile='tmp', filetypes=[("Pictures", "*.png")]) if len(rep) > 0: self.texture_map_path = rep[0] soil_ids_map = Image() soil_ids_map.load_image(self.texture_map_path) self.subplot_texture_map.imshow(soil_ids_map.image) self.canvas_texture_map.draw() def on_configure(self, event): self.canvas.configure(scrollregion=self.canvas.bbox(tk.ALL))
class MainForm: def __init__(self): self.root = Tk() self.root.title("Plot") self.root.attributes("-zoomed", True) self.title = "Calculus" # Plot function self.parse = None self.plotFunction = "" self.option = "linear" # Get root information self.root.update() self.width = self.root.winfo_width() self.height = self.root.winfo_height() self.__DPI = 110.0 # Average DPI for most monitor # Justify the plot self.left = -10 self.right = 10 self.seq = 20 self.thresshole = 500 # Loading GUI self.GUI() # Event Handler self.state = False self.root.bind("<F11>", self.toggle_fullscreen) self.root.bind("<Escape>", self.end_fullscreen) def graph(self): self.parse_func() f = open(fn, 'w+') f.write("graph " + self.title + " {\n") f.write('\tnode [ fontname = "Arial"]\n') self.parse.root.toGraph(-1, f) f.write('}') f.close() f = open(fn, 'w+') f.write("graph " + self.title + " derivative {\n") f.write('\tnode [ fontname = "Arial"]\n') self.parse.rootDerivative.toGraph(-1, f) f.write('}') f.close() G = AGraph(fn) G.draw('test.png', prog='dot') messagebox.showinfo("Info", "Success") def plot(self): self.parse_func() # Plot self.a.set_title(self.title, fontsize=16) if (self.option == "linear"): t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) self.a.plot(t, self.function(t, self.plotFunction, h=0.0000000001), color='red') elif (self.option == "fill"): t = numpy.linspace( int(self.left_bound.get()), int(self.right_bound.get()), (numpy.abs(int(self.left_bound.get())) + numpy.abs(int(self.right_bound.get()))) * self.seq + 1) print(self.parse.function) self.a.fill_between(t, 0, self.function(t, self.parse.function), color="green") elif (self.option == "McLaurin"): t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) y = numpy.zeros(len(t)) # allocate y with float elements for i in range(len(t)): try: y[i] = self.getMcLaurinSeries(int(self.a_input.get()), t[i], depth=int( self.depth_input.get())) except: y[i] = numpy.NAN self.a.plot(t, y, color='blue') self.canvas.draw() def parse_func(self): try: self.parse = Parse(self.input.get()) except Exception as e: messagebox.showerror( "Error", "Somethings gone wrong, please check your input again") print(str(e)) return self.lbl_function.set(self.parse.str_function) self.lbl_derivative.set(self.parse.str_function_da) self.lbl_derivative_dq.set(self.parse.str_function_dq) try: self.lbl_riemann.set( self.parse.getRiemannIntegrals(float(self.left_bound.get()), float(self.right_bound.get()))) except Exception as e: messagebox.showerror( "Error", "Somethings gone wrong, please check your input again") print(str(e)) return def function(self, t, str_func, h=0.0000000001): print(str_func) y = numpy.zeros(len(t)) # allocate y with float elements for i in range(len(t)): x = t[i] try: y[i] = eval(str_func) lim = (y[i - 1] + y[i]) / 2 + self.thresshole if (numpy.abs(y[i - 1]) > lim and numpy.abs(y[i]) > lim): if (y[i - 1] > 0): y[i - 1] = numpy.PINF y[i] = numpy.NINF else: y[i - 1] = numpy.NINF y[i] = numpy.PINF except: y[i] = numpy.NAN return y def clearPlot(self): self.a.clear() self.a.grid(True) self.canvas.draw() def on_key_hover(self, event): print("you pressed {}".format(event.key)) key_press_handler(event, self.canvas, self.toolbar) def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.root.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.root.attributes("-fullscreen", False) return "break" def setPlotFunction(self, option="linear", func="0"): if (option == "linear"): self.plotFunction = func self.option = "linear" else: self.option = option def getMcLaurinSeries(self, x, x0, depth=1, h=0.001): S = eval(self.parse.function) for i in range(1, depth): S += (self.parse.getDifferenceQuotion(x, depth=i, h=h) * ((x0 - x)**i)) / numpy.math.factorial(i) return S def GUI(self): # ========================================================================== # Top Frame # ========================================================================== self.topFrame = Frame(self.root, width=self.width, bd=2, relief="raise") self.topFrame.pack(side=TOP, fill=BOTH, expand=True) """ Top Left """ self.topFrameLeft = Frame(self.topFrame, width=self.width / 2) self.topFrameLeft.pack(side=LEFT, expand=True) # Label self.lbl_function = StringVar() self.lbl_function.set("None") self.lbl_derivative = StringVar() self.lbl_derivative.set("None") self.lbl_derivative_dq = StringVar() self.lbl_derivative_dq.set("None") self.lbl_riemann = StringVar() self.lbl_riemann.set("None") Label(self.topFrameLeft, text="Input").grid(row=0, column=0, sticky=W, padx=2) Label(self.topFrameLeft, text="Function:").grid(row=1, column=0, sticky=W, padx=2) Label(self.topFrameLeft, textvariable=self.lbl_function).grid(row=1, column=1, sticky=W, padx=2) Label(self.topFrameLeft, text="Derivative:").grid(row=2, column=0, sticky=W, padx=2) Label(self.topFrameLeft, textvariable=self.lbl_derivative).grid(row=2, column=1, sticky=W, padx=2) Label(self.topFrameLeft, text="Difference quotion:").grid(row=3, column=0, sticky=W, padx=2) Label(self.topFrameLeft, textvariable=self.lbl_derivative_dq).grid(row=3, column=1, sticky=W, padx=2) Label(self.topFrameLeft, text="Riemann quotion:").grid(row=4, column=0, sticky=W, padx=2) Label(self.topFrameLeft, textvariable=self.lbl_riemann).grid(row=4, column=1, sticky=W, padx=2) # Input field self.input = Entry(self.topFrameLeft, width=30) self.input.grid(row=0, column=1, sticky=W, padx=2) # Button Button(self.topFrameLeft, text="Parse", command=self.parse_func).grid(row=0, column=2, sticky=W, padx=2) """ Top Right """ self.topFrameRight = Frame(self.topFrame, width=self.width / 2) self.topFrameRight.pack(side=LEFT, expand=True) ### Right self.frameRightOption = Frame(self.topFrameRight) self.frameRightOption.pack(side=LEFT, expand=True) #Button Button(self.frameRightOption, text="Plot", command=self.plot).grid(row=0, column=0, columnspan=1, rowspan=5, padx=2) # Input self.left_bound = Entry(self.frameRightOption, width=5) self.left_bound.insert(0, self.left) self.left_bound.grid(row=3, column=2, sticky=W, padx=2) self.right_bound = Entry(self.frameRightOption, width=5) self.right_bound.insert(0, self.right) self.right_bound.grid(row=3, column=3, sticky=W, padx=2) self.a_input = Entry(self.frameRightOption, width=5) self.a_input.insert(0, "0") self.a_input.grid(row=4, column=2, sticky=W, padx=2) self.depth_input = Entry(self.frameRightOption, width=5) self.depth_input.insert(0, "8") self.depth_input.grid(row=4, column=3, sticky=W, padx=2) # Ratio button v = IntVar() v.set(0) Radiobutton(self.frameRightOption, text="Parsed function", padx=2, pady=2, command=lambda: self.setPlotFunction(func=("0" if ( self.parse == None) else self.parse.function)), variable=v, value=0).grid(row=0, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Function derivative", padx=2, pady=2, command=lambda: self.setPlotFunction(func=("0" if ( self.parse == None) else self.parse.function_da)), variable=v, value=1).grid(row=1, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Function diferrence quotion", padx=2, pady=2, command=lambda: self.setPlotFunction(func=("0" if ( self.parse == None) else self.parse.function_dq)), variable=v, value=2).grid(row=2, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Riemann integrals", padx=2, pady=2, command=lambda: self.setPlotFunction(option="fill"), variable=v, value=3).grid(row=3, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Mc Laurin series", padx=2, pady=2, command=lambda: self.setPlotFunction(option="McLaurin"), variable=v, value=4).grid(row=4, column=1, padx=2, sticky=W) ### Left self.frameRightButton = Frame(self.topFrameRight) self.frameRightButton.pack(side=LEFT, expand=True, padx=50) # Button Button(self.frameRightButton, text="Export Graph", command=self.graph).grid(row=0, column=0, padx=2, sticky=E) Button(self.frameRightButton, text="Clean Canvas", command=self.clearPlot).grid(row=0, column=1, padx=2, sticky=E) # ========================================================================== # Bottom Frame # ========================================================================== self.bottomFrame = Frame(self.root, width=self.width, bd=2, relief="raise") self.bottomFrame.pack(side=TOP, fill=BOTH, expand=True) """ Ploting """ # Figure fig = Figure(figsize=(self.width / self.__DPI, self.height / self.__DPI - 1)) self.a = fig.add_subplot(111) self.a.set_title("Calculus", fontsize=16) self.a.set_ylabel("Y", fontsize=14) self.a.set_xlabel("X", fontsize=14) self.a.plot([], [], color='red') self.a.grid(True) self.canvas = FigureCanvasTkAgg(fig, master=self.bottomFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(pady=5) # Toolbar self.toolbar = NavigationToolbar2Tk(self.canvas, self.bottomFrame) self.toolbar.update() self.canvas.get_tk_widget().pack()
class EDITOR: ''' Launches the main canvas, widgets and dialogues''' def __init__(self, master, filename=None, exit_mode=None): self.exit_mode = exit_mode self.master = master self.main = tk.Frame(self.master) # GEOJSON structure self.DATA = None self.Nfeatures = 0 # Trajectory info self.Trajectory_name = tk.StringVar() self.Trajectory_length = tk.IntVar() self.Trajectory_name.set('') self.Trajectory_length.set(0) self.Trajectory_read = False self.Trajectory_POINTS = None self.Trajectory_date = None self.Trajectory_lon = None self.Trajectory_lat = None self.Trajectory_time = None self.Trajectory_distance = None self.Trajectory_speed = None self.Trajectory_reject = None # Map info self.Mapxmin = tk.DoubleVar() self.Mapxmax = tk.DoubleVar() self.Mapymin = tk.DoubleVar() self.Mapymax = tk.DoubleVar() self.aspectratio = False self.Deploy_date = tk.StringVar() self.Recover_date = tk.StringVar() self.Deploy_date.set('') self.Recover_date.set('') # Info about the selected stations self.Station_date = tk.StringVar() self.Station_lon = tk.DoubleVar() self.Station_lat = tk.DoubleVar() self.Station_speed = tk.DoubleVar() self.Station_pointer = tk.IntVar() self.Station_reject = tk.IntVar() self.Station_date.set('') self.Station_lon.set(None) self.Station_lat.set(None) self.Station_lon.set(None) self.Station_speed.set(None) self.Station_pointer.set(None) self.Station_reject.set(False) self.map_size = 1.0 # Info about events 0 and 1 self.serial_number = tk.StringVar() self.buoy_name = tk.StringVar() self.source = tk.StringVar() self.owner = tk.StringVar() self.contact = tk.StringVar() self.time_units = tk.StringVar() self.event0_lon = tk.DoubleVar() self.event0_lat = tk.DoubleVar() self.event0_date = tk.StringVar() self.event0_qc = tk.IntVar() self.event1_lon = tk.DoubleVar() self.event1_lat = tk.DoubleVar() self.event1_date = tk.StringVar() self.event1_qc = tk.IntVar() self.serial_number.set(None) self.buoy_name.set(None) self.source.set(None) self.owner.set(None) self.contact.set(None) self.time_units.set(None) self.event0_lon.set(None) self.event0_lat.set(None) self.event0_date.set(None) self.event0_qc.set(None) self.event1_lon.set(None) self.event1_lat.set(None) self.event1_date.set(None) self.event1_qc.set(None) self.event0_lon_orig = None self.event0_lat_orig = None self.event0_date_orig = None self.event0_qc_orig = None self.event1_lon_orig = None self.event1_lat_orig = None self.event1_date_orig = None self.event1_qc_orig = None self.buoy_name_orig = None self.source_orig = None self.owner_orig = None self.contact_orig = None self.time_units_orig = None # ------------------------- # Design of the main window # ------------------------- # Filename frame (top of the window) F0 = ttk.Frame(self.main, padding=5) ttk.Label(F0, text='Filename', padding=5).grid(row=0, column=0, sticky='w') ttk.Entry(F0,textvariable=self.Trajectory_name,justify='left',width=89). \ grid(row=0,column=1,columnspan=10,sticky='ew') ttk.Button(F0,text='Load',state='enabled', \ command=self.open_geojson,padding=3). \ grid(row=0,column=12,sticky='e') F0.grid() F0.grid_columnconfigure(0, weight=0) # Define tabs: self.nb = ttk.Notebook(self.main) self.page1 = ttk.Frame(self.nb) self.page2 = ttk.Frame(self.nb) self.nb.add(self.page1, text='Canvas') self.nb.add(self.page2, text='Attributes') # PAGE 1: CANVAS F1 = ttk.Frame(self.page1) ttk.Label(F1, text='Deployment date = ', padding=3).grid(row=0, column=0, columnspan=2) self.wdeploy = ttk.Entry(F1, textvariable=self.Deploy_date, width=10) self.wdeploy.grid(row=0, column=2, columnspan=2, sticky='ew') self.wdeploy.bind("<Return>", lambda f: self.deploytime()) ttk.Label(F1, text='Recovery date = ').grid(row=1, column=0, columnspan=2) self.wrecover = ttk.Entry(F1, textvariable=self.Recover_date, width=10) self.wrecover.grid(row=1, column=2, columnspan=2, sticky='ew') self.wrecover.bind('<Return>', lambda f: self.recovertime()) ttk.Label(F1, text='West = ', padding=3).grid(row=0, column=4) ttk.Entry(F1, textvariable=self.Mapxmin, width=10).grid(row=0, column=5, columnspan=2, sticky='ew') ttk.Label(F1, text='East = ', padding=3).grid(row=1, column=4) ttk.Entry(F1, textvariable=self.Mapxmax, width=10).grid(row=1, column=5, columnspan=2, sticky='ew') ttk.Label(F1, text='South = ', padding=3).grid(row=0, column=7) ttk.Entry(F1, textvariable=self.Mapymin, width=10).grid(row=0, column=8, columnspan=2, sticky='ew') ttk.Label(F1, text='North = ', padding=3).grid(row=1, column=7) ttk.Entry(F1, textvariable=self.Mapymax, width=10).grid(row=1, column=8, columnspan=2, sticky='ew') ttk.Button(F1, text='Redraw', command=self.redraw, padding=5).grid(row=0, column=10, rowspan=2, padx=3) ttk.Button(F1, text='Zoom in', command=self.zoom_in, padding=5).grid(row=0, column=11, rowspan=2, padx=3) ttk.Button(F1, text='Zoom out', command=self.zoom_out, padding=5).grid(row=0, column=12, rowspan=2, padx=3) ttk.Button(F1, text='Aspect Ratio', command=self.ratio, padding=5).grid(row=0, column=13, rowspan=2, padx=3) ttk.Button(F1, text='Reset', command=self.reset, padding=5).grid(row=0, column=14, rowspan=2, padx=3) F1.grid(sticky='nswe') F1.grid_rowconfigure(0, weight=0) F1.grid_columnconfigure(0, weight=0) self.fig = Figure(dpi=150) self.ax1 = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.fig, master=self.page1) self.canvas.show() self.canvas.get_tk_widget().grid(sticky='nsew') self.canvas._tkcanvas.grid() self.ax1.get_xaxis().set_visible(False) self.ax1.get_yaxis().set_visible(False) # Bottom menu F2 = ttk.Frame(self.page1, padding=5) ttk.Button(F2,text='+',command=self.station_up,padding=3). \ grid(row=0,column=0) ttk.Label(F2, text='station = ', padding=3).grid(row=0, column=1) self.wstat = ttk.Entry(F2, textvariable=self.Station_pointer) self.wstat.grid(row=0, column=2, columnspan=2) self.wstat.bind('<Return>', lambda f: self.station_manual()) ttk.Label(F2, text='/ ', padding=3).grid(row=0, column=4) ttk.Entry(F2, textvariable=self.Trajectory_length).grid(row=0, column=5, columnspan=2) ttk.Checkbutton(F2,text='Reject',command=self.reject_this, \ variable=self.Station_reject).grid(row=0,column=7) ttk.Button(F2,text='Reject stations before this', \ command=self.reject_before).grid(row=0,column=8,columnspan=2) ttk.Button(F2,text='Reject stations after this', \ command=self.reject_after).grid(row=0,column=11,columnspan=2) ttk.Button(F2,text='-',command=self.station_down,padding=3). \ grid(row=1,column=0) ttk.Label(F2, text='Date = ', padding=3).grid(row=1, column=1) ttk.Entry(F2, textvariable=self.Station_date).grid(row=1, column=2, columnspan=2) ttk.Label(F2, text='Longitude = ', padding=3).grid(row=1, column=4) ttk.Entry(F2, textvariable=self.Station_lon).grid(row=1, column=5, columnspan=2) ttk.Label(F2, text='Latitude = ', padding=3).grid(row=1, column=7) ttk.Entry(F2, textvariable=self.Station_lat).grid(row=1, column=8, columnspan=2) ttk.Label(F2, text='Speed = ', padding=3).grid(row=1, column=10) ttk.Entry(F2, textvariable=self.Station_speed).grid(row=1, column=11, columnspan=2) ttk.Button(F2, text='Purge', command=self.purge).grid(row=2, column=10) ttk.Button(F2, text='Save as', command=self.save).grid(row=2, column=11) ttk.Button(F2, text='Close', command=self.close).grid(row=2, column=12) F2.grid(sticky='ew') # PAGE 2: ATTRIBUTES ttk.Label(self.page2, text='Properties', padding=3, font='Helvetical 12 bold').grid(row=0, column=0) ttk.Label(self.page2, text='Serial number', padding=3).grid(row=1, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.serial_number, state='disabled').grid(row=1, column=2, columnspan=3) ttk.Button(self.page2, text='Restore', command=self.restore, padding=3).grid(row=1, column=6, padx=5) ttk.Label(self.page2, text='Name', padding=3).grid(row=2, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.buoy_name).grid(row=2, column=2, columnspan=3) ttk.Label(self.page2, text='Source', padding=3).grid(row=3, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.source).grid(row=3, column=2, columnspan=3) ttk.Label(self.page2, text='Owner', padding=3).grid(row=4, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.owner).grid(row=4, column=2, columnspan=3) ttk.Label(self.page2, text='Contact', padding=3).grid(row=5, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.contact).grid(row=5, column=2, columnspan=3) ttk.Label(self.page2, text="Initial point ('event':0)", padding=3, font='Helvetical 12 bold').grid(row=6, column=0) ttk.Label(self.page2, text='Longitude', padding=3).grid(row=7, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event0_lon).grid(row=7, column=2, columnspan=3) ttk.Button(self.page2, text='Update', command=self.update_event0, padding=3).grid(row=7, column=5, padx=5) ttk.Label(self.page2, text='Latitude', padding=3).grid(row=8, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event0_lat).grid(row=8, column=2, columnspan=3) ttk.Label(self.page2, text='Date', padding=3).grid(row=9, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event0_date).grid(row=9, column=2, columnspan=3) ttk.Label(self.page2, text='Date units', padding=3).grid(row=10, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.time_units).grid(row=10, column=2, columnspan=3) ttk.Label(self.page2, text='Date QC', padding=3).grid(row=11, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event0_qc).grid(row=11, column=2, columnspan=3) ttk.Label(self.page2, text="Final point ('event':1)", padding=3, font='Helvetical 12 bold').grid(row=12, column=0) ttk.Label(self.page2, text='Longitude', padding=3).grid(row=13, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event1_lon).grid(row=13, column=2, columnspan=3) ttk.Button(self.page2, text='Update', command=self.update_event1, padding=3).grid(row=13, column=5, padx=5) ttk.Label(self.page2, text='Latitude', padding=3).grid(row=14, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event1_lat).grid(row=14, column=2, columnspan=3) ttk.Label(self.page2, text='Date', padding=3).grid(row=15, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event1_date).grid(row=15, column=2, columnspan=3) ttk.Label(self.page2, text='Date units', padding=3).grid(row=16, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.time_units).grid(row=16, column=2, columnspan=3) ttk.Label(self.page2, text='Date QC', padding=3).grid(row=17, column=1, padx=5) ttk.Entry(self.page2, textvariable=self.event1_qc).grid(row=17, column=2, columnspan=3) # PACK THE WHOLE THING self.nb.grid() self.main.grid() if filename is None: pass else: self.open_geojson(ask=False, filename=filename) # --------------------- def close(self): # --------------------- if self.exit_mode == 'quit': ''' Closing the main widget ''' messagebox.askquestion('Close', 'Are you sure?', icon='warning') if 'yes': quit() else: self.master.destroy() return # --------------------------------------------- def open_geojson(self, ask=True, filename=None): # --------------------------------------------- ''' Opening geojson file ''' if ask or filename is None: backup = self.Trajectory_name.get() try: nn = filedialog.askopenfile( filetypes=[('GEOJSON', '*.geojson'), ('JSON', '*.json'), ('ALL', '*.*')]) self.Trajectory_name.set(nn.name) except: self.Trajectory_name.set(backup) else: self.Trajectory_name.set(filename) if not empty(self.Trajectory_name.get()): # Read the GEOJSON file using json.load # ::::::::::::::::::::::::::::::::::::: with open(self.Trajectory_name.get()) as data_file: self.DATA = json.load(data_file) # Split the information into LON, LAT, SST, etc # ::::::::::::::::::::::::::::::::::::::::::::: self.Trajectory_read = True self.Nfeatures = len(self.DATA["features"]) for i in range(self.Nfeatures): if self.DATA["features"][i]["geometry"][ "type"] == "LineString": self.Trajectory_POINTS = self.DATA["features"][i][ "geometry"]["coordinates"] self.Trajectory_date = self.DATA["features"][i][ "properties"]["time"]["data"] try: self.Trajectory_temp = self.DATA["features"][i][ "properties"]["sst"]["data"] except: self.Trajectory_temp = [] self.Trajectory_length.set(len(self.Trajectory_date)) self.Trajectory_lon = [ self.Trajectory_POINTS[j][0] for j in range(self.Trajectory_length.get()) ] self.Trajectory_lat = [ self.Trajectory_POINTS[j][1] for j in range(self.Trajectory_length.get()) ] self.Trajectory_seconds = [] for i in range(self.Trajectory_length.get()): tt = dparser.parse(self.Trajectory_date[i]) self.Trajectory_seconds.append(int(tt.strftime('%s'))) # Get travelled distance (in meters) # :::::::::::::::::::::::::::::::::: self.Trajectory_reject = [] self.Trajectory_distance = [] for i in range(self.Trajectory_length.get()): self.Trajectory_reject.append(tk.IntVar()) self.Trajectory_reject[i].set(0) if i == 0: self.Trajectory_distance.append(float(0)) dist = 0 else: dr = haversine(self.Trajectory_POINTS[i], self.Trajectory_POINTS[i - 1]) dist += dr self.Trajectory_distance.append(dist) # Get time between stations self.Trajectory_time = [] for i in range(self.Trajectory_length.get()): if i == 0: self.Trajectory_time.append(float(0)) else: #now = iso8601.parse_date(self.Trajectory_date[i]) #pre = iso8601.parse_date(self.Trajectory_date[i-1]) now = datetime.datetime.strptime( self.Trajectory_date[i][0:18], '%Y-%m-%dT%H:%M:%S') pre = datetime.datetime.strptime( self.Trajectory_date[i - 1][0:18], '%Y-%m-%dT%H:%M:%S') secs = (now - pre).seconds self.Trajectory_time.append(secs) # Speed required to move between stations self.Trajectory_speed = [] self.Trajectory_speed.append(0) # AAA print(self.Trajectory_time) for i in range(1, self.Trajectory_length.get()): if self.Trajectory_time[i] < 1E-3: u = 0 else: u = (self.Trajectory_distance[i] - self.Trajectory_distance[i - 1]) / self.Trajectory_time[i] self.Trajectory_speed.append(u) self.map_size = 1.0 self.data_xmin = min(self.Trajectory_lon) self.data_xmax = max(self.Trajectory_lon) self.data_ymin = min(self.Trajectory_lat) self.data_ymax = max(self.Trajectory_lat) self.data_xsize = self.data_xmax - self.data_xmin self.data_ysize = self.data_ymax - self.data_ymin self.Mapxmin.set(myround(self.data_xmin - \ self.map_size*self.data_xsize,2)) self.Mapxmax.set(myround(self.data_xmax + \ self.map_size*self.data_xsize,2)) self.Mapymin.set(myround(self.data_ymin - \ self.map_size*self.data_ysize,2)) self.Mapymax.set(myround(self.data_ymax + \ self.map_size*self.data_ysize,2)) #self.Mapxmin.set(myround(self.data_xmin-0.5,1)) #self.Mapxmax.set(myround(self.data_xmax+0.5,1)) #self.Mapymin.set(myround(self.data_ymin-0.5,1)) #self.Mapymax.set(myround(self.data_ymax+0.5,1)) self.Station_pointer.set(0) self.Station_date.set(self.Trajectory_date[0]) self.Station_lon.set(self.Trajectory_lon[0]) self.Station_lat.set(self.Trajectory_lat[0]) self.Station_speed.set(self.Trajectory_speed[0]) self.Station_reject.set(self.Trajectory_reject[0].get()) self.Deploy_date.set(self.Trajectory_date[0]) self.Recover_date.set( self.Trajectory_date[self.Trajectory_length.get() - 1]) self.ax1.clear() self.draw_map() self.make_plot() # Scan for info about points: for i in range(self.Nfeatures): if self.DATA["features"][i]["geometry"]["type"] == "Point": #print(self.DATA["features"][i]["properties"]) if self.DATA["features"][i]["properties"]["event"] == 0: self.event0_lon.set(self.DATA["features"][i] ["geometry"]["coordinates"][0]) self.event0_lat.set(self.DATA["features"][i] ["geometry"]["coordinates"][1]) self.serial_number.set( self.DATA["features"][i]["properties"]["code_sn"]) self.buoy_name.set( self.DATA["features"][i]["properties"]["name"]) self.contact.set( self.DATA["features"][i]["properties"]["contact"]) self.source.set( self.DATA["features"][i]["properties"]["source"]) self.owner.set( self.DATA["features"][i]["properties"]["owner"]) self.event0_date.set(self.DATA["features"][i] ["properties"]["time"]["data"][0]) self.event0_qc.set(self.DATA["features"][i] ["properties"]["time"]["qc_data"]) try: a = self.event0_qc.get() except: self.event0_qc.set(0) #self.event0_qc.set(self.DATA["features"][i]["properties"]["qc"]) self.time_units.set(self.DATA["features"][i] ["properties"]["time"]["units"]) if self.DATA["features"][i]["properties"]["event"] == 1: self.event1_lon.set(self.DATA["features"][i] ["geometry"]["coordinates"][0]) self.event1_lat.set(self.DATA["features"][i] ["geometry"]["coordinates"][1]) self.event1_date.set(self.DATA["features"][i] ["properties"]["time"]["data"][0]) self.event1_qc.set(self.DATA["features"][i] ["properties"]["time"]["qc_data"]) try: a = self.event1_qc.get() except: self.event1_qc.set(0) #self.event1_qc.set(self.DATA["features"][i]["properties"]["qc"]) self.buoy_name_orig = self.buoy_name.get() self.source_orig = self.source.get() self.owner_orig = self.owner.get() self.contact_orig = self.contact.get() self.time_units_orig = self.time_units.get() self.event0_lon_orig = self.event0_lon.get() self.event0_lat_orig = self.event0_lat.get() self.event0_date_orig = self.event0_date.get() self.event0_qc_orig = self.event0_qc.get() self.event1_lon_orig = self.event1_lon.get() self.event1_lat_orig = self.event1_lat.get() self.event1_date_orig = self.event0_date.get() self.event1_qc_orig = self.event0_qc.get() else: self.DATA = None self.Trajectory = None self.Trajectory_read = False self.Nfeatures = 0 # -------------- def restore(self): # -------------- '''Restore GEOJSON properties''' self.buoy_name.set(self.buoy_name_orig) self.source.set(self.source_orig) self.owner.set(self.owner_orig) self.contact.set(self.contact_orig) self.time_units.set(self.time_units_orig) self.event0_lon.set(self.event0_lon_orig) self.event0_lat.set(self.event0_lat_orig) self.event0_date.set(self.event0_date_orig) self.event0_qc.set(self.event0_qc_orig) self.event1_lon.set(self.event1_lon_orig) self.event1_lat.set(self.event1_lat_orig) self.event1_date.set(self.event1_date_orig) self.event1_qc.set(self.event1_qc_orig) # -------------- def update_event0(self): # -------------- '''Update coordinates and date of the first point''' self.event0_lon.set(self.Trajectory_lon[0]) self.event0_lat.set(self.Trajectory_lat[0]) self.event0_date.set(self.Trajectory_date[0]) self.event0_qc.set(1) # -------------- def update_event1(self): # -------------- '''Update coordinates and date of the first point''' i = self.Trajectory_length.get() - 1 self.event1_lon.set(self.Trajectory_lon[i]) self.event1_lat.set(self.Trajectory_lat[i]) self.event1_date.set(self.Trajectory_date[i]) self.event1_qc.set(1) # -------------- def purge(self): # -------------- '''Purge rejected stations ''' for i in reversed(range(self.Trajectory_length.get())): if self.Trajectory_reject[i].get() == 1: print('Removing station = ', i) del self.Trajectory_POINTS[i] del self.Trajectory_lon[i] del self.Trajectory_lat[i] del self.Trajectory_date[i] try: del self.Trajectory_temp[i] except: pass self.Trajectory_length.set(len(self.Trajectory_lon)) self.Station_pointer.set(0) # Get travelled distance (in meters) # :::::::::::::::::::::::::::::::::: self.Trajectory_reject = [] self.Trajectory_distance = [] for i in range(self.Trajectory_length.get()): self.Trajectory_reject.append(tk.IntVar()) self.Trajectory_reject[i].set(0) if i == 0: self.Trajectory_distance.append(float(0)) dist = 0 else: dr = haversine(self.Trajectory_POINTS[i], self.Trajectory_POINTS[i - 1]) dist += dr self.Trajectory_distance.append(dist) # Get time between stations self.Trajectory_time = [] for i in range(self.Trajectory_length.get()): if i == 0: self.Trajectory_time.append(float(0)) else: #now = iso8601.parse_date(self.Trajectory_date[i]) #pre = iso8601.parse_date(self.Trajectory_date[i-1]) now = datetime.datetime.strptime(self.Trajectory_date[i][0:18], '%Y-%m-%dT%H:%M:%S') pre = datetime.datetime.strptime( self.Trajectory_date[i - 1][0:18], '%Y-%m-%dT%H:%M:%S') secs = (now - pre).seconds self.Trajectory_time.append(secs) # Speed required to move between stations self.Trajectory_speed = [] self.Trajectory_speed.append(0) for i in range(1, self.Trajectory_length.get()): u = (self.Trajectory_distance[i] - self.Trajectory_distance[i - 1]) / self.Trajectory_time[i] self.Trajectory_speed.append( (self.Trajectory_distance[i] - self.Trajectory_distance[i - 1]) / self.Trajectory_time[i]) self.Station_date.set(self.Trajectory_date[self.Station_pointer.get()]) self.Station_lon.set(self.Trajectory_lon[self.Station_pointer.get()]) self.Station_lat.set(self.Trajectory_lat[self.Station_pointer.get()]) self.Station_speed.set( self.Trajectory_speed[self.Station_pointer.get()]) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.draw_map() self.make_plot() # ------------- def save(self): # ------------- '''Save new file''' nn = filedialog.asksaveasfilename(title='Save', confirmoverwrite=True) if nn is not None: outfile = '%s' % nn # The following values may have changed: POINTS, DATE, TEMP for i in range(self.Nfeatures): if self.DATA["features"][i]["geometry"][ "type"] == "LineString": self.DATA["features"][i]["geometry"][ "coordinates"] = self.Trajectory_POINTS self.DATA["features"][i]["properties"]["time"][ "data"] = self.Trajectory_date if len(self.Trajectory_temp) > 0: self.DATA["features"][i]["properties"]["sst"][ "data"] = self.Trajectory_temp # The following values may have changed: COORDINATES, PROPERTIES for i in range(self.Nfeatures): if self.DATA["features"][i]["geometry"]["type"] == "Point": if self.DATA["features"][i]["properties"]["event"] == 0: self.DATA["features"][i]["geometry"]["coordinates"][ 0] = self.event0_lon.get() self.DATA["features"][i]["geometry"]["coordinates"][ 1] = self.event0_lat.get() self.DATA["features"][i]["properties"][ "name"] = self.buoy_name.get() self.DATA["features"][i]["properties"][ "source"] = self.source.get() self.DATA["features"][i]["properties"][ "owner"] = self.owner.get() self.DATA["features"][i]["properties"][ "contact"] = self.contact.get() self.DATA["features"][i]["properties"]["time"]["data"][ 0] = self.event0_date.get() self.DATA["features"][i]["properties"]["time"][ "units"] = self.time_units.get() self.DATA["features"][i]["properties"]["time"][ "qc_data"] = self.event0_qc.get() if self.DATA["features"][i]["properties"]["event"] == 1: self.DATA["features"][i]["geometry"]["coordinates"][ 0] = self.event1_lon.get() self.DATA["features"][i]["geometry"]["coordinates"][ 1] = self.event1_lat.get() self.DATA["features"][i]["properties"][ "name"] = self.buoy_name.get() self.DATA["features"][i]["properties"][ "source"] = self.source.get() self.DATA["features"][i]["properties"][ "owner"] = self.owner.get() self.DATA["features"][i]["properties"][ "contact"] = self.contact.get() self.DATA["features"][i]["properties"]["time"]["data"][ 0] = self.event1_date.get() self.DATA["features"][i]["properties"]["time"][ "units"] = self.time_units.get() self.DATA["features"][i]["properties"]["time"][ "qc_data"] = self.event1_qc.get() with open(outfile, 'w') as fp: json.dump(self.DATA, fp) print('File %s written' % outfile) # -------------------- def reject_this(self): # -------------------- '''Rejects a station''' if self.Trajectory_read: self.Trajectory_reject[self.Station_pointer.get()].set( self.Station_reject.get()) # ---------------------- def reject_before(self): # ---------------------- '''Rejects a station''' if self.Trajectory_read: for i in range(self.Station_pointer.get()): self.Trajectory_reject[i].set(1) self.make_plot() # ---------------------- def reject_after(self): # ---------------------- '''Rejects a station''' if self.Trajectory_read: for i in range(self.Station_pointer.get() + 1, self.Trajectory_length.get()): self.Trajectory_reject[i].set(1) self.make_plot() # ----------------------- def recovertime(self): # ----------------------- '''Manual selection of the final period''' if self.Trajectory_read: dd = self.wrecover.get() tt = dparser.parse(dd) t0 = int(tt.strftime('%s')) for i in range(self.Trajectory_length.get()): if self.Trajectory_seconds[i] > t0: self.Trajectory_reject[i].set(1) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.make_plot() # ----------------------- def deploytime(self): # ----------------------- '''Manual selection of the initial period''' if self.Trajectory_read: dd = self.wdeploy.get() tt = dparser.parse(dd) t0 = int(tt.strftime('%s')) for i in range(self.Trajectory_length.get()): if self.Trajectory_seconds[i] < t0: self.Trajectory_reject[i].set(1) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.make_plot() # ----------------------- def station_manual(self): # ----------------------- '''Manual selection of an station''' if self.Trajectory_read: num = self.wstat.get() self.Station_pointer.set(num) self.Station_date.set( self.Trajectory_date[self.Station_pointer.get()]) self.Station_lon.set( self.Trajectory_lon[self.Station_pointer.get()]) self.Station_lat.set( self.Trajectory_lat[self.Station_pointer.get()]) self.Station_speed.set( self.Trajectory_speed[self.Station_pointer.get()]) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.make_plot() # ------------------- def station_up(self): # ------------------- '''Moves pointer up one''' if self.Station_pointer.get() < self.Trajectory_length.get() - 1: i = self.Station_pointer.get() if self.Trajectory_reject[i].get() == 1: self.m.plot(self.xx[i], \ self.yy[i],'o',ms=4,color='grey') else: self.m.plot(self.xx[i], \ self.yy[i],'o',ms=4,color='white') self.Station_pointer.set(self.Station_pointer.get() + 1) self.m.plot(self.xx[self.Station_pointer.get()], \ self.yy[self.Station_pointer.get()],'o',ms=4,color='red') self.Station_date.set( self.Trajectory_date[self.Station_pointer.get()]) self.Station_lon.set( self.Trajectory_lon[self.Station_pointer.get()]) self.Station_lat.set( self.Trajectory_lat[self.Station_pointer.get()]) self.Station_speed.set( self.Trajectory_speed[self.Station_pointer.get()]) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.canvas.draw() # -------------------- def station_down(self): # -------------------- '''Moves pointer down one''' if self.Station_pointer.get() > 0: i = self.Station_pointer.get() if self.Trajectory_reject[i].get() == 1: self.m.plot(self.xx[i], \ self.yy[i],'o',ms=4,color='grey') else: self.m.plot(self.xx[i], \ self.yy[i],'o',ms=4,color='white') #self.m.plot(self.xx[self.Station_pointer.get()], \ # self.yy[self.Station_pointer.get()],'o',ms=4,color='white') self.Station_pointer.set(self.Station_pointer.get() - 1) self.m.plot(self.xx[self.Station_pointer.get()], \ self.yy[self.Station_pointer.get()],'o',ms=4,color='red') self.Station_date.set( self.Trajectory_date[self.Station_pointer.get()]) self.Station_lon.set( self.Trajectory_lon[self.Station_pointer.get()]) self.Station_lat.set( self.Trajectory_lat[self.Station_pointer.get()]) self.Station_speed.set( self.Trajectory_speed[self.Station_pointer.get()]) self.Station_reject.set( self.Trajectory_reject[self.Station_pointer.get()].get()) self.canvas.draw() # --------------- def reset(self): # --------------- '''Resets the map limits''' self.map_size = 1.0 self.data_xmin = min(self.Trajectory_lon) self.data_xmax = max(self.Trajectory_lon) self.data_ymin = min(self.Trajectory_lat) self.data_ymax = max(self.Trajectory_lat) self.data_xsize = self.data_xmax - self.data_xmin self.data_ysize = self.data_ymax - self.data_ymin #self.Mapxmin.set(#np.trunc(self.data_xmin - \ # self.map_size*self.data_xsize)) #self.Mapxmax.set(np.trunc(self.data_xmax + \ # self.map_size*self.data_xsize)) #self.Mapymin.set(np.trunc(self.data_ymin - \ # self.map_size*self.data_ysize)) #self.Mapymax.set(np.trunc(self.data_ymax + \ # self.map_size*self.data_ysize)) self.Mapxmin.set(myround(self.data_xmin - \ self.map_size*self.data_xsize,2)) self.Mapxmax.set(myround(self.data_xmax + \ self.map_size*self.data_xsize,2)) self.Mapymin.set(myround(self.data_ymin - \ self.map_size*self.data_ysize,2)) self.Mapymax.set(myround(self.data_ymax + \ self.map_size*self.data_ysize,2)) #self.Mapxmin.set(myround(self.data_xmin-0.5,1)) #self.Mapxmax.set(myround(self.data_xmax+0.5,1)) #self.Mapymin.set(myround(self.data_ymin-0.5,1)) #self.Mapymax.set(myround(self.data_ymax+0.5,1)) self.Deploy_date.set(self.Trajectory_date[0]) self.Recover_date.set( self.Trajectory_date[self.Trajectory_length.get() - 1]) for i in range(self.Trajectory_length.get()): self.Trajectory_reject[i].set(0) self.ax1.clear() self.draw_map() self.make_plot() # --------------- def zoom_in(self): # --------------- '''Zooms in the map''' self.map_size = 0.50 * self.map_size self.Mapxmin.set(self.data_xmin - self.map_size * self.data_xsize) self.Mapxmax.set(self.data_xmax + self.map_size * self.data_xsize) self.Mapymin.set(self.data_ymin - self.map_size * self.data_ysize) self.Mapymax.set(self.data_ymax + self.map_size * self.data_ysize) self.draw_map() self.make_plot() # --------------- def zoom_out(self): # --------------- '''Zooms out the map''' self.map_size = self.map_size / 0.50 self.Mapxmin.set(self.data_xmin - self.map_size * self.data_xsize) self.Mapxmax.set(self.data_xmax + self.map_size * self.data_xsize) self.Mapymin.set(self.data_ymin - self.map_size * self.data_ysize) self.Mapymax.set(self.data_ymax + self.map_size * self.data_ysize) self.draw_map() self.make_plot() def ratio(self): '''Redraws the map''' self.aspectratio = not self.aspectratio self.draw_map() self.make_plot() def redraw(self): '''Redraws the map''' self.draw_map() self.make_plot() def draw_map(self): '''Draws the map''' self.ax1.clear() projection = 'cyl' projection = 'merc' try: self.m = Basemap( \ #projection=projection, \ #resolution='i', \ llcrnrlat=self.Mapymin.get(), \ urcrnrlat=self.Mapymax.get(), \ llcrnrlon=self.Mapxmin.get(), \ urcrnrlon=self.Mapxmax.get(), \ #fix_aspect=self.aspectratio, \ ax=self.ax1) self.m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=700, verbose=False) except: self.m = Basemap( \ projection=projection, \ resolution='i', \ llcrnrlat=self.Mapymin.get(), \ urcrnrlat=self.Mapymax.get(), \ llcrnrlon=self.Mapxmin.get(), \ urcrnrlon=self.Mapxmax.get(), \ ax=self.ax1) self.m.fillcontinents(color='Coral') self.m.drawmapboundary(fill_color='aqua') self.m.drawcoastlines(linewidth=1, color='black') dx = myround((self.Mapxmax.get() - self.Mapxmin.get()) / 5, 1) xw = myround(self.Mapxmin.get() - 15, 0) xe = myround(self.Mapxmax.get() + 15, 0) dy = myround((self.Mapymax.get() - self.Mapymin.get()) / 5, 1) ys = myround(self.Mapymin.get() - 15, 0) yn = myround(self.Mapymax.get() + 15, 0) self.m.drawmeridians(np.arange(xw, xe, dx), labels=[1, 0, 0, 1]) self.m.drawparallels(np.arange(ys, yn, dy), labels=[0, 1, 0, 1]) self.xx, self.yy = self.m(self.Trajectory_lon, self.Trajectory_lat) self.m.plot(self.xx[self.Station_pointer.get()], \ self.yy[self.Station_pointer.get()],'o',ms=4,color='red') def make_plot(self): '''Draws the trajectory over the map''' self.m.plot(self.xx, self.yy, '--', linewidth=0.8, color='grey') #self.m.plot(self.xx,self.yy,'o',ms=4,linewidth=1,color='white') for i in range(self.Trajectory_length.get()): if self.Trajectory_reject[i].get() == 1: self.m.plot(self.xx[i], self.yy[i], 'o', ms=4, linewidth=1, color='grey') else: self.m.plot(self.xx[i], self.yy[i], 'o', ms=4, linewidth=1, color='white') self.m.plot(self.xx[self.Station_pointer.get()], \ self.yy[self.Station_pointer.get()],'o',ms=4,color='red') self.canvas.draw()
class Plotter(tk.Frame): def __init__(self, parent, data, _size=(6, 3)): tk.Frame.__init__(self, master=parent) self.data = data self.time_to_display = 5 self.lines = [] self.base_canvas = tk.Canvas(self) self.figure_bed = plt.figure(figsize=_size) self.axis = self.figure_bed.add_subplot(111) # self.figure_bed.set_facecolor('white') self.canvas = FigureCanvasTkAgg(self.figure_bed, self) self.canvas._tkcanvas.config(highlightthickness=0) toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() self.canvas._tkcanvas.pack(side='top', fill=tk.BOTH, expand=True) self.draw_new_data([0], [[0]], self.time_to_display) self.canvas.draw() def set_time_frame(self, time): self.time_to_display = time def draw_new_data(self, x, y_array, time_display=None): # print('drawing data: ', x[0:10], x[-1], time_display) # self.axis.clear() while self.lines: old_line = self.lines.pop() old_line.remove() del old_line if not time_display: time_display = self.time_to_display for i, y in enumerate(y_array): _line, = self.axis.plot(x, y, label='channel %d' % (i + 1), c=COLORS[i]) self.lines.append(_line) self.axis.set_xlim( [self.data.end_time - time_display, self.data.end_time]) # hackish self.axis.legend(loc=1) self.canvas.draw() def display_data(self): # self.axis.clear() y_data = self.data.y_data_to_display x = self.data.t_data t_end = self.data.end_time for i, y in enumerate(y_data): # self.axis.plot(x, y, label='channel %d' % (i+1)) self.lines[i].set_data(x, y) # print('y data: ', y[:500]) self.axis.set_xlim([t_end - self.time_to_display, t_end]) # self.axis.legend(loc=1) self.axis.relim() self.axis.autoscale_view(True, True, True) self.canvas.draw() def set_num_channels(self, num_channels): diff_channels = len(self.lines) - num_channels if diff_channels < 0: # there are more lines currently displayed than the user chose pass
class wishbone_gui(tk.Tk): def __init__(self, parent): tk.Tk.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.vals = None self.currentPlot = None # set up menu bar self.menubar = tk.Menu(self) self.fileMenu = tk.Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=self.fileMenu) self.fileMenu.add_command(label="Load data", command=self.loadData) self.fileMenu.add_command( label="Save data", state="disabled", command=self.saveData ) self.fileMenu.add_command(label="Exit Wishbone", command=self.quitWB) self.analysisMenu = tk.Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Analysis", menu=self.analysisMenu) self.analysisMenu.add_command( label="Principal component analysis", state="disabled", command=self.runPCA ) self.analysisMenu.add_command( label="tSNE", state="disabled", command=self.runTSNE ) self.analysisMenu.add_command( label="Diffusion map", state="disabled", command=self.runDM ) self.analysisMenu.add_command( label="GSEA", state="disabled", command=self.runGSEA ) self.analysisMenu.add_command( label="Wishbone", state="disabled", command=self.runWishbone ) self.visMenu = tk.Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Visualization", menu=self.visMenu) self.visMenu.add_command( label="Principal component analysis", state="disabled", command=self.plotPCA ) self.visMenu.add_command(label="tSNE", state="disabled", command=self.plotTSNE) self.visMenu.add_command( label="Diffusion map", state="disabled", command=self.plotDM ) self.visMenu.add_command( label="GSEA Results", state="disabled", command=self.showGSEAResults ) self.wishboneMenu = tk.Menu(self) self.visMenu.add_cascade(label="Wishbone", menu=self.wishboneMenu) self.wishboneMenu.add_command( label="On tSNE", state="disabled", command=self.plotWBOnTsne ) self.wishboneMenu.add_command( label="Marker trajectory", state="disabled", command=self.plotWBMarkerTrajectory, ) self.wishboneMenu.add_command( label="Heat map", state="disabled", command=self.plotWBHeatMap ) self.visMenu.add_command( label="Gene expression", state="disabled", command=self.plotGeneExpOntSNE ) self.visMenu.add_command( label="Set gate", state="disabled", command=self.setGate ) self.config(menu=self.menubar) # intro screen tk.Label( self, text=u"Wishbone", font=("Helvetica", 48), fg="black", bg="white", padx=100, pady=50, ).grid(row=0) tk.Label( self, text=u"To get started, select a data file by clicking File > Load Data", fg="black", bg="white", padx=100, pady=25, ).grid(row=1) # update self.protocol("WM_DELETE_WINDOW", self.quitWB) self.grid_columnconfigure(0, weight=1) self.resizable(True, True) self.update() self.geometry(self.geometry()) self.focus_force() def loadData(self): self.dataFileName = filedialog.askopenfilename( title="Load data file", initialdir="~/.wishbone/data" ) if self.dataFileName != "": # pop up data options menu self.fileInfo = tk.Toplevel() self.fileInfo.title("Data options") tk.Label(self.fileInfo, text=u"File name: ").grid(column=0, row=0) tk.Label(self.fileInfo, text=self.dataFileName.split("/")[-1]).grid( column=1, row=0 ) tk.Label(self.fileInfo, text=u"Name:", fg="black", bg="white").grid( column=0, row=1 ) self.fileNameEntryVar = tk.StringVar() tk.Entry(self.fileInfo, textvariable=self.fileNameEntryVar).grid( column=1, row=1 ) if ( self.dataFileName.split(".")[len(self.dataFileName.split(".")) - 1] == "fcs" ): tk.Label(self.fileInfo, text=u"Cofactor:", fg="black", bg="white").grid( column=0, row=2 ) self.cofactorVar = tk.IntVar() self.cofactorVar.set(5) tk.Entry(self.fileInfo, textvariable=self.cofactorVar).grid( column=1, row=2 ) elif ( self.dataFileName.split(".")[len(self.dataFileName.split(".")) - 1] == "csv" ): self.normalizeVar = tk.BooleanVar() tk.Checkbutton( self.fileInfo, text=u"Normalize", variable=self.normalizeVar ).grid(column=0, row=2, columnspan=2) tk.Label( self.fileInfo, text=u"The normalize parameter is used for correcting for library " u"size among cells.", ).grid(column=0, row=3, columnspan=2) tk.Button(self.fileInfo, text="Cancel", command=self.fileInfo.destroy).grid( column=0, row=4 ) tk.Button(self.fileInfo, text="Load", command=self.processData).grid( column=1, row=4 ) self.wait_window(self.fileInfo) def processData(self): # clear intro screen for item in self.grid_slaves(): item.grid_forget() # display file name tk.Label( self, text=u"File name: " + self.fileNameEntryVar.get(), fg="black", bg="white", ).grid(column=0, row=0) # set up canvas for plots self.fig, self.ax = wishbone.wb.get_fig() self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=4, sticky="NSEW" ) tk.Label(self, text=u"Visualizations:", fg="black", bg="white").grid( column=0, row=1 ) # load data based on input type if ( self.dataFileName.split(".")[ len(self.dataFileName.split(".")) - 1] == "fcs" ): # mass cytometry data self.scdata = wishbone.wb.SCData.from_fcs( os.path.expanduser(self.dataFileName), cofactor=self.cofactorVar.get() ) self.wb = None elif ( self.dataFileName.split(".")[ len(self.dataFileName.split(".")) - 1] == "csv" ): # sc-seq data self.scdata = wishbone.wb.SCData.from_csv( os.path.expanduser(self.dataFileName), data_type="sc-seq", normalize=self.normalizeVar.get(), ) self.wb = None else: self.wb = wishbone.wb.Wishbone.load(self.dataFileName) self.scdata = self.wb.scdata # set up buttons based on data type if self.scdata.data_type == "sc-seq": self.PCAButton = tk.Button( self, text=u"PCA", state="disabled", command=self.plotPCA ) self.PCAButton.grid(column=0, row=2) self.tSNEButton = tk.Button( self, text=u"tSNE", state="disabled", command=self.plotTSNE ) self.tSNEButton.grid(column=0, row=3) self.DMButton = tk.Button( self, text=u"Diffusion map", state="disabled", command=self.plotDM ) self.DMButton.grid(column=0, row=4) self.GSEAButton = tk.Button( self, text=u"GSEA Results", state="disabled", command=self.showGSEAResults, ) self.GSEAButton.grid(column=0, row=5) self.WBButton = tk.Button( self, text=u"Wishbone", state="disabled", command=self.plotWBOnTsne ) self.WBButton.grid(column=0, row=6) self.geneExpButton = tk.Button( self, text=u"Gene expression", state="disabled", command=self.plotGeneExpOntSNE, ) self.geneExpButton.grid(column=0, row=7) self.setGateButton = tk.Button( self, text=u"Set gate", state="disabled", command=self.setGate ) self.setGateButton.grid(column=0, row=8) self.saveButton = tk.Button( self, text=u"Save plot", state="disabled", command=self.savePlot ) self.saveButton.grid(column=4, row=0) self.diff_component = tk.StringVar() self.diff_component.set("Component 1") self.component_menu = tk.OptionMenu( self, self.diff_component, "Component 1", "Component 2", "Component 3", "Component 4", "Component 5", "Component 6", "Component 7", "Component 8", "Component 9", ) self.component_menu.config(state="disabled") self.component_menu.grid(row=0, column=2) self.updateButton = tk.Button( self, text=u"Update component", command=self.updateComponent, state="disabled", ) self.updateButton.grid(column=3, row=0) # enable buttons based on current state of scdata object if self.scdata.pca: self.analysisMenu.entryconfig(1, state="normal") self.visMenu.entryconfig(0, state="normal") self.PCAButton.config(state="normal") if isinstance(self.scdata.tsne, pd.DataFrame): self.analysisMenu.entryconfig(2, state="normal") self.visMenu.entryconfig(1, state="normal") self.visMenu.entryconfig(5, state="normal") self.tSNEButton.config(state="normal") self.geneExpButton.config(state="normal") if isinstance(self.scdata.diffusion_eigenvectors, pd.DataFrame): self.analysisMenu.entryconfig(3, state="normal") self.analysisMenu.entryconfig(4, state="normal") self.visMenu.entryconfig(2, state="normal") self.DMButton.config(state="normal") else: self.tSNEButton = tk.Button( self, text=u"tSNE", state="disabled", command=self.plotTSNE ) self.tSNEButton.grid(column=0, row=2) self.DMButton = tk.Button( self, text=u"Diffusion map", state="disabled", command=self.plotDM ) self.DMButton.grid(column=0, row=3) self.WBButton = tk.Button( self, text=u"Wishbone", state="disabled", command=self.plotWBOnTsne ) self.WBButton.grid(column=0, row=4) self.geneExpButton = tk.Button( self, text=u"Gene expression", state="disabled", command=self.plotGeneExpOntSNE, ) self.geneExpButton.grid(column=0, row=5) self.setGateButton = tk.Button( self, text=u"Set gate", state="disabled", command=self.setGate ) self.setGateButton.grid(column=0, row=6) self.saveButton = tk.Button( self, text=u"Save plot", state="disabled", command=self.savePlot ) self.saveButton.grid(column=4, row=0) self.analysisMenu.delete(0) self.analysisMenu.delete(2) self.visMenu.delete(0) self.visMenu.delete(2) self.analysisMenu.entryconfig(1, state="normal") # enable buttons based on current state of scdata object if isinstance(self.scdata.tsne, pd.DataFrame): self.visMenu.entryconfig(0, state="normal") self.visMenu.entryconfig(3, state="normal") self.tSNEButton.config(state="normal") self.geneExpButton.config(state="normal") if isinstance(self.scdata.diffusion_eigenvectors, pd.DataFrame): self.analysisMenu.entryconfig(2, state="normal") self.visMenu.entryconfig(1, state="normal") self.DMButton.config(state="normal") # enable buttons self.analysisMenu.entryconfig(0, state="normal") self.fileMenu.entryconfig(1, state="normal") if self.wb: if isinstance(self.wb.trajectory, pd.Series): self.wishboneMenu.entryconfig(0, state="normal") self.wishboneMenu.entryconfig(1, state="normal") self.wishboneMenu.entryconfig(2, state="normal") self.WBButton.config(state="normal") # get genes self.genes = self.scdata.data.columns.values self.gates = {} self.geometry("800x550") # destroy pop up menu self.fileInfo.destroy() def saveData(self): pickleFileName = filedialog.asksaveasfilename( title="Save Wishbone Data", defaultextension=".p", initialfile=self.fileNameEntryVar.get(), ) if pickleFileName != None: if self.wb != None: self.wb.save(pickleFileName) else: self.scdata.save_as_wishbone(pickleFileName) def runPCA(self): self.scdata.run_pca() # enable buttons self.analysisMenu.entryconfig(1, state="normal") self.visMenu.entryconfig(0, state="normal") self.PCAButton.config(state="normal") def runTSNE(self): # pop up for # components self.tsneOptions = tk.Toplevel() self.tsneOptions.title("tSNE options") if self.scdata.data_type == "sc-seq": tk.Label( self.tsneOptions, text=u"Number of components:", fg="black", bg="white" ).grid(column=0, row=0) self.nCompVar = tk.IntVar() self.nCompVar.set(15) tk.Entry(self.tsneOptions, textvariable=self.nCompVar).grid(column=1, row=0) tk.Label(self.tsneOptions, text=u"Perplexity:", fg="black", bg="white").grid( column=0, row=1 ) self.perplexityVar = tk.IntVar() self.perplexityVar.set(30) tk.Entry(self.tsneOptions, textvariable=self.perplexityVar).grid( column=1, row=1 ) tk.Button(self.tsneOptions, text="Run", command=self._runTSNE).grid( column=1, row=2 ) tk.Button( self.tsneOptions, text="Cancel", command=self.tsneOptions.destroy ).grid(column=0, row=2) self.wait_window(self.tsneOptions) def _runTSNE(self): if self.scdata.data_type == "sc-seq": self.scdata.run_tsne( n_components=self.nCompVar.get(), perplexity=self.perplexityVar.get() ) else: self.scdata.run_tsne(n_components=None, perplexity=self.perplexityVar.get()) self.gates = {} # enable buttons if self.scdata.data_type == "sc-seq": self.analysisMenu.entryconfig(2, state="normal") self.visMenu.entryconfig(1, state="normal") self.visMenu.entryconfig(5, state="normal") else: self.visMenu.entryconfig(0, state="normal") self.visMenu.entryconfig(3, state="normal") self.tSNEButton.config(state="normal") self.geneExpButton.config(state="normal") self.tsneOptions.destroy() def runDM(self): self.scdata.run_diffusion_map() # enable buttons if self.scdata.data_type == "sc-seq": self.analysisMenu.entryconfig(3, state="normal") self.analysisMenu.entryconfig(4, state="normal") self.visMenu.entryconfig(2, state="normal") else: self.analysisMenu.entryconfig(2, state="normal") self.visMenu.entryconfig(1, state="normal") self.DMButton.config(state="normal") def runGSEA(self): self.GSEAFileName = filedialog.askopenfilename( title="Select gmt File", initialdir="~/.wishbone/tools" ) if self.GSEAFileName != "": self.scdata.run_diffusion_map_correlations() self.scdata.data.columns = self.scdata.data.columns.str.upper() self.outputPrefix = filedialog.asksaveasfilename( title="Input file prefix for saving output", initialdir="~/.wishbone/gsea", ) if "mouse" in self.GSEAFileName: gmt_file_type = "mouse" else: gmt_file_type = "human" self.reports = self.scdata.run_gsea( output_stem=os.path.expanduser(self.outputPrefix), gmt_file=(gmt_file_type, self.GSEAFileName.split("/")[-1]), ) # enable buttons self.visMenu.entryconfig(3, state="normal") self.GSEAButton.config(state="normal") def runWishbone(self): # popup menu for wishbone options self.wbOptions = tk.Toplevel() self.wbOptions.title("Wishbone Options") # s tk.Label(self.wbOptions, text=u"Start cell:", fg="black", bg="white").grid( column=0, row=0 ) self.start = tk.StringVar() tk.Entry(self.wbOptions, textvariable=self.start).grid(column=1, row=0) if len(self.gates) > 0: self.cell_gate = tk.StringVar() self.cell_gate.set("Use cell gate") self.gate_menu = tk.OptionMenu( self.wbOptions, self.cell_gate, *list(self.gates.keys()) ) self.gate_menu.grid(row=0, column=2) # k tk.Label(self.wbOptions, text=u"k:", fg="black", bg="white").grid( column=0, row=1 ) self.k = tk.IntVar() tk.Entry(self.wbOptions, textvariable=self.k).grid(column=1, row=1) self.k.set(15) # components list tk.Label(self.wbOptions, text=u"Components list:", fg="black", bg="white").grid( column=0, row=2 ) self.compList = tk.StringVar() tk.Entry(self.wbOptions, textvariable=self.compList).grid(column=1, row=2) self.compList.set("1, 2, 3") # num waypoints tk.Label( self.wbOptions, text=u"Number of waypoints:", fg="black", bg="white" ).grid(column=0, row=3) self.numWaypoints = tk.IntVar() tk.Entry(self.wbOptions, textvariable=self.numWaypoints).grid(column=1, row=3) self.numWaypoints.set(250) # branch self.branch = tk.BooleanVar() self.branch.set(True) tk.Checkbutton(self.wbOptions, text=u"Branch", variable=self.branch).grid( column=0, row=4, columnspan=2 ) tk.Button(self.wbOptions, text="Run", command=self._runWishbone).grid( column=1, row=5 ) tk.Button(self.wbOptions, text="Cancel", command=self.wbOptions.destroy).grid( column=0, row=5 ) self.wait_window(self.wbOptions) def _runWishbone(self): self.wb = wishbone.wb.Wishbone(self.scdata) if self.cell_gate.get() == "Use cell gate": self.wb.run_wishbone( start_cell=self.start.get(), k=self.k.get(), components_list=[int(comp) for comp in self.compList.get().split(",")], num_waypoints=self.numWaypoints.get(), branch=self.branch.get(), ) else: # randomly select start cell in gate print("Using cell gate:") print(self.cell_gate.get()) start_cell = random.sample(list(self.gates[self.cell_gate.get()]), 1)[0] print(start_cell) self.wb.run_wishbone( start_cell=start_cell, k=self.k.get(), components_list=[int(comp) for comp in self.compList.get().split(",")], num_waypoints=self.numWaypoints.get(), branch=self.branch.get(), ) # enable buttons self.wishboneMenu.entryconfig(0, state="normal") self.wishboneMenu.entryconfig(1, state="normal") self.wishboneMenu.entryconfig(2, state="normal") self.WBButton.config(state="normal") self.wbOptions.destroy() def plotPCA(self): self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") # pop up for # components self.PCAOptions = tk.Toplevel() self.PCAOptions.title("PCA Plot Options") tk.Label( self.PCAOptions, text=u"Max variance explained (ylim):", fg="black", bg="white", ).grid(column=0, row=0) self.yLimVar = tk.DoubleVar() self.yLimVar.set(round(self.scdata.pca["eigenvalues"][0][0], 2)) tk.Entry(self.PCAOptions, textvariable=self.yLimVar).grid(column=1, row=0) tk.Label( self.PCAOptions, text=u"Number of components:", fg="black", bg="white" ).grid(column=0, row=1) self.compVar = tk.IntVar() self.compVar.set(15) tk.Entry(self.PCAOptions, textvariable=self.compVar).grid(column=1, row=1) tk.Button(self.PCAOptions, text="Plot", command=self._plotPCA).grid( column=1, row=2 ) tk.Button(self.PCAOptions, text="Cancel", command=self.PCAOptions.destroy).grid( column=0, row=2 ) self.wait_window(self.PCAOptions) def _plotPCA(self): self.resetCanvas() self.fig, self.ax = self.scdata.plot_pca_variance_explained( ylim=(0, self.yLimVar.get()), n_components=self.compVar.get() ) self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=4, sticky="NW" ) self.currentPlot = "pca" # enable buttons self.saveButton.config(state="normal") self.PCAOptions.destroy() def plotTSNE(self): self.saveButton.config(state="normal") self.setGateButton.config(state="normal") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="normal") else: self.visMenu.entryconfig(4, state="normal") self.resetCanvas() self.fig, self.ax = self.scdata.plot_tsne() self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=4, sticky="NW" ) self.currentPlot = "tsne" def plotDM(self): self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") self.geometry("950x550") self.resetCanvas() self.fig, self.ax = self.scdata.plot_diffusion_components() self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=4, sticky="W" ) self.currentPlot = "dm_components" def showGSEAResults(self): self.saveButton.config(state="disabled") self.component_menu.config(state="normal") self.updateButton.config(state="normal") self.setGateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") self.resetCanvas() self.canvas = tk.Canvas(self, width=600, height=300) self.canvas.grid(column=1, row=1, rowspan=17, columnspan=4) self.outputText(1) self.currentPlot = "GSEA_result_" + self.diff_component.get() def updateComponent(self): self.resetCanvas() self.canvas = tk.Canvas(self, width=600, height=300) self.canvas.grid(column=1, row=1, rowspan=17, columnspan=4, sticky="NSEW") self.outputText(int(self.diff_component.get().split(" ")[-1])) self.currentPlot = "GSEA_result_" + self.diff_component.get() def outputText(self, diff_component): pos_text = str(self.reports[diff_component]["pos"]).split("\n") pos_text = pos_text[1: len(pos_text) - 1] pos_text = "\n".join(pos_text) neg_text = str(self.reports[diff_component]["neg"]).split("\n") neg_text = neg_text[1: len(neg_text) - 1] neg_text = "\n".join(neg_text) self.canvas.create_text( 5, 5, anchor="nw", text="Positive correlations:\n\n", font=("Helvetica", 16, "bold"), ) self.canvas.create_text(5, 50, anchor="nw", text=pos_text) self.canvas.create_text( 5, 150, anchor="nw", text="Negative correlations:\n\n", font=("Helvetica", 16, "bold"), ) self.canvas.create_text(5, 200, anchor="nw", text=neg_text) def plotWBOnTsne(self): self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") self.resetCanvas() self.fig, self.ax = self.wb.plot_wishbone_on_tsne() self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid(column=1, row=1, rowspan=10, columnspan=4) self.currentPlot = "wishbone_on_tsne" def plotWBMarkerTrajectory(self): self.getGeneSelection() if len(self.selectedGenes) < 1: print("Error: must select at least one gene") else: self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") self.resetCanvas() self.vals, self.fig, self.ax = self.wb.plot_marker_trajectory( self.selectedGenes ) self.fig.set_size_inches(10, 4, forward=True) self.fig.tight_layout() self.fig.subplots_adjust(right=0.8) self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=5, sticky="W" ) self.currentPlot = "wishbone_marker_trajectory" self.geometry("1050x550") # enable buttons self.wishboneMenu.entryconfig(2, state="normal") def plotWBHeatMap(self): self.getGeneSelection() if len(self.selectedGenes) < 1: print("Error: must select at least one gene") else: self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") self.resetCanvas() self.vals, self.fig, self.ax = self.wb.plot_marker_trajectory( self.selectedGenes ) self.fig, self.ax = self.wb.plot_marker_heatmap(self.vals) self.fig.set_size_inches(10, 4, forward=True) self.fig.tight_layout() self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=5, sticky="W" ) self.currentPlot = "wishbone_marker_heatmap" def plotGeneExpOntSNE(self): self.getGeneSelection() if len(self.selectedGenes) < 1: print("Error: must select at least one gene") else: self.saveButton.config(state="normal") self.setGateButton.config(state="disabled") if self.scdata.data_type == "sc-seq": self.component_menu.config(state="disabled") self.updateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") else: self.visMenu.entryconfig(4, state="disabled") self.resetCanvas() self.fig, self.ax = self.scdata.plot_gene_expression(self.selectedGenes) self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.draw() self.canvas.get_tk_widget().grid( column=1, row=1, rowspan=10, columnspan=4, sticky="W" ) self.currentPlot = "gene_expression_tsne" self.geometry("950x550") def getGeneSelection(self): # popup menu to get selected genes self.geneSelection = tk.Toplevel() self.geneSelection.title("Select Genes") tk.Label(self.geneSelection, text=u"Genes:", fg="black", bg="white").grid(row=0) self.geneInput = wishbone.autocomplete_entry.AutocompleteEntry( self.genes.tolist(), self.geneSelection, listboxLength=6 ) self.geneInput.grid(row=1) self.geneInput.bind("<Return>", self.AddToSelected) self.geneSelectBox = tk.Listbox(self.geneSelection, selectmode=tk.EXTENDED) self.geneSelectBox.grid(row=2, rowspan=10) self.geneSelectBox.bind("<BackSpace>", self.DeleteSelected) self.selectedGenes = [] tk.Button( self.geneSelection, text="Use selected genes", command=self.geneSelection.destroy, ).grid(row=12) tk.Button( self.geneSelection, text="Cancel", command=self.cancelGeneSelection ).grid(row=13) self.wait_window(self.geneSelection) def cancelGeneSelection(self): self.selectedGenes = [] self.geneSelection.destroy() def AddToSelected(self, event): self.selectedGenes.append(self.geneInput.get()) self.geneSelectBox.insert( tk.END, self.selectedGenes[len(self.selectedGenes) - 1] ) def DeleteSelected(self, event): selected = self.geneSelectBox.curselection() pos = 0 for i in selected: idx = int(i) - pos self.geneSelectBox.delete(idx, idx) self.selectedGenes = ( self.selectedGenes[:idx] + self.selectedGenes[idx + 1:] ) pos = pos + 1 def savePlot(self): self.plotFileName = filedialog.asksaveasfilename( title="Save Plot", defaultextension=".png", initialfile=self.fileNameEntryVar.get() + "_" + self.currentPlot, ) if self.plotFileName != None: self.fig.savefig(self.plotFileName) def setGate(self): # pop up for gate name self.gateOptions = tk.Toplevel() self.gateOptions.title("Create gate for start cells") tk.Label(self.gateOptions, text=u"Gate name:", fg="black", bg="white").grid( column=0, row=0 ) self.gateName = tk.StringVar() self.gateName.set("Gate " + str(len(self.gates) + 1)) tk.Entry(self.gateOptions, textvariable=self.gateName).grid(column=1, row=0) tk.Button(self.gateOptions, text="Select gate", command=self._setGate).grid( column=1, row=1 ) tk.Button( self.gateOptions, text="Cancel", command=self.gateOptions.destroy ).grid(column=0, row=1) self.wait_window(self.gateOptions) def _setGate(self): self.gateOptions.destroy() self.buttonPress = self.canvas.mpl_connect( "button_press_event", self._startGate ) self.buttonRelease = self.canvas.mpl_connect( "button_release_event", self._endGate ) self.canvas.get_tk_widget().config(cursor="plus") def _startGate(self, event): self.start_x = event.xdata self.start_y = event.ydata def _endGate(self, event): # draw gate rectangle start_x = self.start_x if self.start_x < event.xdata else event.xdata start_y = self.start_y if self.start_y < event.ydata else event.ydata width = np.absolute(event.xdata - self.start_x) height = np.absolute(event.ydata - self.start_y) rect = Rectangle( (start_x, start_y), width, height, fill=False, ec="black", alpha=1, lw=2 ) self.ax.add_patch(rect) self.canvas.draw() # disable mouse events self.canvas.mpl_disconnect(self.buttonPress) self.canvas.mpl_disconnect(self.buttonRelease) self.canvas.get_tk_widget().config(cursor="arrow") # save cell gate gate = Path( [ [start_x, start_y], [start_x + width, start_y], [start_x + width, start_y + height], [start_x, start_y + height], [start_x, start_y], ] ) gated_cells = self.scdata.tsne.index[gate.contains_points(self.scdata.tsne)] self.gates[self.gateName.get()] = gated_cells # replot tSNE w gate colored self.fig.clf() plt.scatter( self.scdata.tsne["x"], self.scdata.tsne["y"], s=10, edgecolors="none", color="lightgrey", ) plt.scatter( self.scdata.tsne.ix[gated_cells, "x"], self.scdata.tsne.ix[gated_cells, "y"], s=10, edgecolors="none", ) self.canvas.draw() self.setGateButton.config(state="disabled") self.visMenu.entryconfig(6, state="disabled") def resetCanvas(self): self.fig.clf() if type(self.canvas) is FigureCanvasTkAgg: for item in self.canvas.get_tk_widget().find_all(): self.canvas.get_tk_widget().delete(item) else: for item in self.canvas.find_all(): self.canvas.delete(item) def quitWB(self): self.quit() self.destroy()
class App(Tk): def __init__(self): Tk.__init__(self) # container = Frame(self) # container.pack(side="top", fill="both", expand=False) # container.grid_rowconfigure(0, weight=1) # container.grid_columnconfigure(0, weight=1) self.commands = { "shape" : 0, "speed" : 1, "custom" : 2 } self.ld = LineDrawer() self.canvas = FigureCanvasTkAgg(self.ld.fig, self) self.canvas.draw() # self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True) self.canvas.get_tk_widget().grid(row=2, columnspan=4) # Set our events for the interactive plot self.canvas.mpl_connect('button_press_event', self.onclick) if KEYBOARD_EVENTS: self.canvas.mpl_connect('key_press_event', self.press) circleButton = ttk.Button(self, text="Circle", command=self.send_circle) # circleButton.pack(side = BOTTOM) circleButton.grid(row = 0, column = 0) squareButton = ttk.Button(self, text="Square", command=self.send_square) # squareButton.pack(side = BOTTOM) squareButton.grid(row=0, column=1, columnspan=2) triangeButton = ttk.Button(self, text="Triangle", command=self.send_triangle) # triangeButton.pack(side = BOTTOM) triangeButton.grid(row=0, column=4) commit_shapeButton = ttk.Button(self, text="Commit Shape", command=self.commit_shape) # commit_shapeButton.pack(side = BOTTOM, fill = X) commit_shapeButton.grid(row=1, columnspan=2) deleteButton = ttk.Button(self, text="Delete", command=self.delete) # deleteButton.pack(side = BOTTOM, fill = X) deleteButton.grid(row=1, column=2, columnspan=2) # When you press the X out button this should kill the python code not just the gui self.protocol("WM_DELETE_WINDOW", self.on_closing) if DEBUG: self.text_box = Text(self, wrap='word', height=11) # self.text_box.pack(side = BOTTOM, fill = X) self.text_box.grid(row=4, columnspan=4, rowspan=2) sys.stdout = StdoutRedirector(self.text_box) # this should work but doesn't def on_closing(self): self.destroy() sys.exit("Shitty exit") def send_circle(self): self.command = "shape" self.data = [ord("c")] self.send_shit() if SERIAL: ser.write('c'.encode()) x_queue.queue.clear() y_queue.queue.clear() xData = [] yData = [] def send_square(self): self.command = "shape" self.data = [ord("s")] self.send_shit() if SERIAL: ser.write('s'.encode()) x_queue.queue.clear() y_queue.queue.clear() xData = [] yData = [] def send_triangle(self): self.command = "shape" self.data = [ord("t")] self.send_shit() if SERIAL: ser.write('t'.encode()) x_queue.queue.clear() y_queue.queue.clear() xData = [] yData = [] def send_line(self): self.command = "shape" self.data = [ord("l")] self.send_shit() if SERIAL: ser.write('l'.encode()) def press(self, event): self.ld.press(event) self.canvas.draw() def onclick(self, event): self.ld.onclick(event) self.canvas.draw() def commit_shape(self): self.ld.commit_shape() self.canvas.draw() self.command = "custom" self.send_shit() def delete(self): self.ld.delete() self.canvas.draw() def send_shit(self): transmissions = [] if self.command == "shape": transmissions.append(arduino_data_prep(self.commands[self.command], self.data)) elif self.command == "speed": # transmissions.append() pass elif self.command == "custom": laser_angles = [l*3.6 for l in self.ld.cartesian_setpoints["x"]] mirror_angles = [l*3.6 for l in self.ld.cartesian_setpoints["y"]] transmissions.append(arduino_data_prep(self.commands[self.command], laser_angles)) transmissions.append(arduino_data_prep(self.commands[self.command], mirror_angles)) for transmission in transmissions: print("Preparing to send a transmission of {} -> {}".format(self.command, self.commands[self.command])) print("Sending the following string of data: {}".format(transmission)) if SERIAL: ser.write(transmission) bytes = self.ser.read() print(bytes) bytes1 = self.ser.read() print(bytes1) bytes2 = self.ser.read() print(bytes2)
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: for df,index in enumerate(array_df): clear_data(df[month]) self.ax.clear() self.ax.plot(df[month],label=array_csv[index]) self.ax.plot(df[month],label='Jeux de données propre') self.ax.legend() 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
class CurrentMonitorInterface: def __init__(self, master): self.master = master self.master.title("Current monitor") self.master.minsize(width=340, height=200) self.PSU_interface = TtiSerialInterface() self.mode = 0 self.ch1_current = 0 self.ch2_current = 0 self.ch1_current_limit = 0.1 self.ch2_current_limit = 0.1 self.ch_current_limit_reached = 0 self.ch_output_state = 0 self.ch1_history = [0] * 200 self.ch2_history = [0] * 200 self.device0_label = Label(self.master, text="Connected to:") self.device0_label.grid(column=1, row=1, sticky='w', columnspan=6) self.device_label = Label(self.master, text=self.PSU_interface.device_ID) self.device_label.grid(column=1, row=2, sticky='w', columnspan=6) self.data_folder = "/home" self.save_data = 0 self.initialize_plot() # CH1 self.ch1_current_label0 = Label(self.master, text="Current 1:") self.ch1_current_label0.grid(column=1, row=3, sticky='e') self.ch1_current_entry = Entry(self.master, width=6) self.ch1_current_entry.grid(column=2, row=3, sticky='e') self.ch1_current_entry.insert(0, self.ch1_current) self.ch1_current_label = Label(self.master, text="A") self.ch1_current_label.grid(column=3, row=3, sticky='w') self.ch1_state_label = Label(self.master, text="Off") self.ch1_state_label.grid(column=4, row=3, sticky='w') # CH2 self.ch2_current_label0 = Label(self.master, text="Current 2:") self.ch2_current_label0.grid(column=1, row=4, sticky='e') self.ch2_current_entry = Entry(self.master, width=6) self.ch2_current_entry.grid(column=2, row=4, sticky='e') self.ch2_current_entry.insert(0, self.ch2_current) self.ch2_current_label = Label(self.master, text="A") self.ch2_current_label.grid(column=3, row=4, sticky='w') self.ch2_state_label = Label(self.master, text="Off") self.ch2_state_label.grid(column=4, row=4, sticky='w') self.start_button = Button(self.master, text="Start", command=lambda: self.change_mode("start")) self.start_button.grid(column=1, row=5, sticky='e') self.stop_button = Button(self.master, text="Stop", command=lambda: self.change_mode("stop")) self.stop_button.grid(column=2, row=5, sticky='e') self.stop_button = Button(self.master, text="Settings", command=lambda: self.change_settings()) self.stop_button.grid(column=3, row=5, sticky='e') self.state_button = Button( self.master, text="Open channels", command=lambda: self.change_channel_states()) self.state_button.grid(column=4, row=5, sticky='e') self.state_button.config(text="Close channels") self.status_label = Label(self.master, text="") self.status_label.grid(column=1, row=6, sticky='w', columnspan=5) self.quit_button = Button(self.master, text="Exit", command=lambda: self.quit_program()) self.quit_button.grid(column=5, row=8, sticky='e') self.plot_currents() # functions def ask_directory(self): dirtext = "Test" self.data_folder = tkFileDialog.askdirectory(parent=root, initialdir='/home/', title=dirtext) self.data_dir_entry.delete(0, 'end') self.data_dir_entry.insert(0, self.data_folder) def change_settings(self): t = Toplevel(self.master) t.wm_title("Change settings.") device0_label = Label(t, text="Current limit:") device0_label.grid(column=1, row=1, sticky='w', columnspan=6) ch1_current_label0 = Label(t, text="Current 1:") ch1_current_label0.grid(column=1, row=3, sticky='e') self.ch1_current_limit_entry = Entry(t, width=6) self.ch1_current_limit_entry.grid(column=2, row=3, sticky='e') self.ch1_current_limit_entry.insert(0, self.ch1_current_limit) ch1_current_label = Label(t, text="A") ch1_current_label.grid(column=3, row=3, sticky='e') # CH2 ch2_current_label0 = Label(t, text="Current 2:") ch2_current_label0.grid(column=1, row=4, sticky='e') self.ch2_current_limit_entry = Entry(t, width=6) self.ch2_current_limit_entry.grid(column=2, row=4, sticky='e') self.ch2_current_limit_entry.insert(0, self.ch2_current_limit) ch2_current_label = Label(t, text="A") ch2_current_label.grid(column=3, row=4, sticky='e') data_dir_label0 = Label(t, text="Data directory:") data_dir_label0.grid(column=1, row=5, sticky='w') self.data_dir_entry = Entry(t, width=18) self.data_dir_entry.grid(column=1, row=6, sticky='w') self.data_dir_entry.insert(0, self.data_folder) cont_trig_button = Button(t, text="Browse", command=lambda: self.ask_directory(), width=5) cont_trig_button.grid(column=3, row=6, sticky='e', columnspan=2) self.save_data_var = IntVar() self.save_data_var.set(self.save_data) Checkbutton(t, text="Save data", variable=self.save_data_var).grid(column=1, row=7, sticky=W) ok_button = Button(t, text="Ok", command=lambda: self.save_settings(t)) ok_button.grid(column=1, row=8, sticky='e') cancel_button = Button(t, text="Cancel", command=t.destroy) cancel_button.grid(column=2, row=8, sticky='e') def change_mode(self, mode): if mode == "start": self.mode = 1 if self.save_data: self.status_label.config(text="Running. Saving data.") else: self.status_label.config(text="Running.") self.update_currents() if mode == "stop": self.mode = 0 self.status_label.config(text="Stopped.") def change_channel_states(self, state=""): if state == "off": self.PSU_interface.set_outputs_off() self.state_button.config(text="Open channels") elif state == "on": self.PSU_interface.set_outputs_on() self.state_button.config(text="Close channels") elif state == "": if self.ch_output_state == 0: self.PSU_interface.set_outputs_on() self.ch_output_state = 1 self.state_button.config(text="Close channels") elif self.ch_output_state == 1: self.PSU_interface.set_outputs_off() self.ch_output_state = 0 self.state_button.config(text="Open channels") def check_channel_states(self): states = self.PSU_interface.req_output_states() if states[0] == 0: self.ch1_state_label.config(text="Off") elif states[0] == 1: self.ch1_state_label.config(text="On") if states[1] == 0: self.ch2_state_label.config(text="Off") elif states[1] == 1: self.ch2_state_label.config(text="On") def current_limit_reached(self): self.change_channel_states("off") self.ch_current_limit_reached = 1 self.status_label.config(text="Current limit reached.") def update_currents(self): if self.mode == 1: self.master.after(1000, self.update_currents) self.check_channel_states() self.ch1_current = self.PSU_interface.req_ch1_current() if self.ch1_current >= self.ch1_current_limit: self.current_limit_reached() self.ch1_history = self.ch1_history[1:] self.ch1_history.append(self.ch1_current) self.ch1_current_entry.delete(0, 'end') self.ch1_current_entry.insert(0, self.ch1_current) self.ch2_current = self.PSU_interface.req_ch2_current() if self.ch2_current >= self.ch2_current_limit: self.current_limit_reached() self.ch2_history = self.ch2_history[1:] self.ch2_history.append(self.ch2_current) self.ch2_current_entry.delete(0, 'end') self.ch2_current_entry.insert(0, self.ch2_current) ch1_voltage = self.PSU_interface.req_ch1_voltage() ch2_voltage = self.PSU_interface.req_ch2_voltage() if self.save_data: # Save values to a file. timestamp = time.strftime("%Y/%m/%d/%H:%M:%S") filename = "%s/current_data.dat" % self.data_folder if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition print "Unable to create directory" outf = open(filename, "a") outf.write('%s\t%f\t%f\t%f\t%f\n' % (timestamp, ch1_voltage, self.ch1_current, ch2_voltage, self.ch2_current)) outf.close() self.plot_currents() def save_settings(self, t): self.ch1_current_limit = float(self.ch1_current_limit_entry.get()) self.ch2_current_limit = float(self.ch2_current_limit_entry.get()) self.change_mode('stop') self.save_data = self.save_data_var.get() t.destroy() def initialize_plot(self): self.fig = plt.figure(figsize=(4, 3)) self.canvas = FigureCanvasTkAgg(self.fig, master=root) self.canvas.get_tk_widget().grid(column=1, row=7, columnspan=5) def plot_currents(self): plt.clf() self.fig.clear() plt.plot(self.ch1_history, label="ch1") plt.plot(self.ch2_history, label="ch2") plt.legend() plt.xlabel('Time[s]', fontsize=7) plt.ylabel('Current[A]', fontsize=7) plt.grid() plt.tick_params(axis='both', which='major', labelsize=7) self.canvas.draw() def quit_program(self): plt.close("all") self.master.destroy()
def display_explanation_tree(facts, rules, root): """ This function displays an explanation tree in order to explain more clearly the reasoning of the inference engine Args: facts (list[fact]): list of the facts explored (true or false) rules (list[rule]): list of the rules that have been used root (tk.Tk): root window of the result display """ G = nx.DiGraph() fact_names = [] node_colors = [] # We add the facts to the graph for fact in facts: G.add_node(fact.name) fact_names.append(fact.name) # We add the edges according to the rules, with the color depending on the usability of the rule for i in range(len(rules)): if len(rules[i].conditions) > 1: usable = True for fact in rules[i].conditions: if fact not in facts: usable = False G.add_node("AND ({})".format(i)) if usable: for condition in rules[i].conditions: G.add_edge(condition.name, "AND ({})".format(i), color='green') for conclusion in rules[i].conclusions: G.add_edge("AND ({})".format(i), conclusion.name, color='green') else: for condition in rules[i].conditions: G.add_edge(condition.name, "AND ({})".format(i), color='red') for conclusion in rules[i].conclusions: G.add_edge("AND ({})".format(i), conclusion.name, color='red') else: if rules[i].conditions[0] in facts: for conclusion in rules[i].conclusions: G.add_edge(rules[i].conditions[0].name, conclusion.name, color='green') else: for conclusion in rules[i].conclusions: G.add_edge(rules[i].conditions[0].name, conclusion.name, color='red') # The nodes are colorized depending on the veracity of the fact for node in G.nodes(): if node in fact_names: node_colors.append('#03fc10') elif node[:3] == "AND": node_colors.append('white') else: node_colors.append('red') edges = G.edges() edge_colors = [G[u][v]['color'] for u, v in edges] # The graph is displayed in the tkinter window f = plt.figure() a = f.add_subplot(111) plt.axis('off') nx.draw_networkx(G, with_labels=True, node_color=node_colors, edge_color=edge_colors, node_size=1000, font_size=8) canvas = FigureCanvasTkAgg(f, master=root) canvas.draw() canvas.get_tk_widget().grid(row=3, pady=(0, "0.5c"))
class DefaultPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) fig = Figure(figsize=(5, 5), dpi=100) self.canvas = FigureCanvasTkAgg(fig, self) self.label = tk.Label(self, text='Simulation page', font=LARGE_FONT) self.label.pack(pady=10, padx=10) self.btn_run_sim = tk.Button(self, text='Start simulation', command=lambda: self.run_sim(self)) self.btn_run_sim.pack() self.btn_next = tk.Button( self, text='Change parameters', command=lambda: controller.show_frame(ParameterPage)) self.btn_next.pack() self.lbl_income = tk.Label(self, text='Generated income: {}'.format(0)) self.lbl_income.pack() self.lbl_routes = tk.Label(self, text='Generated best routes:') self.lbl_routes.pack() route = load_route_graph_from_file() pos = nx.circular_layout(route) ''' f = Figure(figsize=(5, 5), dpi=100) ax=f.subplots(2) nx.draw_networkx_nodes(route, pos, node_size=600, ax=ax[0]) canvas = FigureCanvasTkAgg(f, self) canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) ''' def refresh_graph(self): #self.fig.clear() #self.canvas.draw() #self.canvas. self.canvas.get_tk_widget().delete('all') self.canvas.get_tk_widget().pack_forget() def visualize_graph(self, route: nx.Graph, best_sol: List): pos = nx.circular_layout(route) self.refresh_graph() bus_lines_edges = [] for bus in best_sol[0]: bus_line_edges = [] for b_stop in range(len(bus) - 1): bus_line_edges.append((bus[b_stop], bus[b_stop + 1])) bus_lines_edges.append(deepcopy(bus_line_edges)) directed_graph_lines = [] for line in bus_lines_edges: directed_graph_lines.append(nx.DiGraph()) directed_graph_lines[-1].add_edges_from(line) if len(directed_graph_lines) > 1: fig = Figure(figsize=(5, 5), dpi=100) ax = fig.subplots(len(directed_graph_lines)) for idx, line_graph in enumerate(directed_graph_lines): nx.draw_networkx_nodes(route, pos, node_size=600, ax=ax[idx]) nx.draw_networkx_edges(route, pos, ax=ax[idx], width=1) nx.draw_networkx_labels(route, pos, font_size=10, ax=ax[idx]) nx.draw_networkx_edges(line_graph, pos, edge_color='r', arrowsize=15, width=2, ax=ax[idx]) ax[idx].set_title('Linia numer {}'.format(idx + 1), fontsize=10) else: fig = Figure(figsize=(5, 5), dpi=100) ax = fig.subplots(2) nx.draw_networkx_nodes(route, pos, node_size=600, ax=ax[0]) nx.draw_networkx_edges(route, pos, width=1, ax=ax[0]) nx.draw_networkx_labels(route, pos, font_size=10, ax=ax[0]) nx.draw_networkx_edges(directed_graph_lines[0], pos, edge_color='r', arrowsize=15, width=2, ax=ax[0]) #plt.title('Linia numer {}'.format(1), fontsize=10) self.canvas = FigureCanvasTkAgg(fig, self) self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) @staticmethod def run_sim(self): global nobjfun global mut global pop_size global par_size global sel_coef global graph_size global ticket global fuel global line route_graph = load_route_graph_from_file() mat = load_dest_mat_from_file() best_sol = simulate_EA(route_graph, pop_size, mat, mut, nobjfun, sel_coef, par_size, ticket, fuel, line) print(best_sol) self.lbl_income.config(text='Generated income: {}'.format(best_sol[1])) routes_str = '' for route in best_sol[0]: routes_str += '\n' routes_str += str(route) self.lbl_routes.config(text='Generated best routes:' + routes_str) self.visualize_graph(route_graph, best_sol) visualize_best_parent_stats()
def new_import(): folder=fd.askdirectory() fls=[] for root, dirs, fle in os.walk(folder): for files in fle: if files.endswith('.csv'): fls.append(files) if fls==[] or None: msg.showerror('Error', 'No csv files found in current directory') else: df_mcx=[] for data in fls: mcx=pd.read_csv(folder+'/'+data) if list(mcx.columns.values)[0]=='Date': df_mcx.append(mcx) else: mcx=pd.read_csv(folder+'/'+data, sep='\t',parse_dates=['Expiry Date']) df_mcx.append(mcx) df_mcx=pd.concat(df_mcx, axis=0, ignore_index=True, sort=False) df_mcx['Expiry Date']=pd.to_datetime(df_mcx['Expiry Date']) df_mcx['Date']=pd.to_datetime(df_mcx['Date']) df_mcx.sort_values(by='Date', ascending=True, inplace=True) root=tk.Toplevel(win) figm=Figure(figsize=(6, 5), dpi=100) axm=figm.add_subplot(111) hsm, =axm.plot([], [],marker='.') annm=axm.annotate('', xy=(0, 0)) ann_listm=[]#annotation address #frames chart_frame_mcx=tk.Frame(root) widget_frame_mcx=tk.Frame(root, bg='white') #ends chart_frame_mcx.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True, padx=6, pady=6) widget_frame_mcx.pack(side=tk.TOP, fill=tk.BOTH) #functioning widget stock_frame_mcx=tk.Frame(widget_frame_mcx, bg='white') stock_frame_mcx.grid(column=2, row=0) stock_mcx=tk.StringVar(root) labelm1=ttk.Label(stock_frame_mcx, text='Stock:') labelm1.pack() stck_select_mcx=ttk.Combobox(stock_frame_mcx, width=12, textvariable=stock_mcx, state='readonly') stck_select_mcx.pack(padx=1, pady=0) stc_mcx=df_mcx.loc[(df_mcx['Symbol'].notnull())&(df_mcx['Instrument Name']=='FUTCOM'), 'Symbol'] stck_lst_mcx=list(set(list(stc_mcx))) stck_select_mcx['values']=sorted(stck_lst_mcx) #expiry frame exp_frame_mcx=tk.Frame(widget_frame_mcx, bg='white') exp_frame_mcx.grid(column=3, row=0) labelm2=ttk.Label(exp_frame_mcx, text='Expiry date:') labelm2.pack() exp_date_mcx=tk.StringVar(root) exp_selection_mcx=ttk.Combobox(exp_frame_mcx, width=12, textvariable=exp_date_mcx, state='readonly') exp_selection_mcx.pack() def redefine_exp_mcx(event): daef_mcx=df_mcx.loc[(df_mcx['Expiry Date'].notnull())&(df_mcx.Symbol==stck_select_mcx.get())&(df_mcx['Instrument Name']=='FUTCOM'), 'Expiry Date'] exp_lst_mcx=list(set(list(daef_mcx))) exp_lst_mcx.sort() exp_lst_mcx=[i.strftime('%d-%m-%Y') for i in exp_lst_mcx] exp_selection_mcx['values']=exp_lst_mcx stck_select_mcx.bind("<<ComboboxSelected>>", redefine_exp_mcx) def draw_on_click_mcx(): for anot in ann_listm: try: anot.remove() except: pass expi_mcx=exp_selection_mcx.get() stck_mcx=stck_select_mcx.get() if ((expi_mcx=='' or None) or (stck_mcx=='' or None)): msg.showwarning('Warning!', "Not all values were entered! Please enter all values to analyze your selected stock.") else: expi_mcx=datetime.datetime.strptime(expi_mcx, '%d-%m-%Y') #expi=expi.strftime('%m/%d/%Y').lstrip("0").replace(" 0", " ") localm=df_mcx.loc[(df_mcx.Symbol==stck_mcx)&(df_mcx['Expiry Date']==expi_mcx)&(df_mcx['Instrument Name']=='FUTCOM'), 'Close'] localm2=df_mcx.loc[(df_mcx.Symbol==stck_mcx)&(df_mcx['Expiry Date']==expi_mcx)&(df_mcx['Instrument Name']=='FUTCOM'), ['Close', 'Date']] print(localm2) axm.set_autoscale_on(True) xm=np.arange(len(localm)) hsm.set_data(xm, localm) for i, j in zip(xm, localm): annm=axm.annotate(str(j), xy=(i, j)) ann_listm.append(annm) figm.suptitle(stck_select_mcx.get(), fontsize=15) axm.relim() axm.autoscale_view(True, True, True) figm.canvas.draw() butt_frame_mcx=tk.Frame(widget_frame_mcx, bg='white') butt_frame_mcx.grid(column=4, row=0) button_mcx=ttk.Button(butt_frame_mcx, text='Submit', command=draw_on_click_mcx) button_mcx.grid(column=0, row=1) canvas_mcx=FigureCanvasTkAgg(figm, master=chart_frame_mcx) canvas_mcx.draw() canvas_mcx.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) figm.subplots_adjust(top=1, bottom=0.04, left=0.04, right=0.99) toolbar_mcx=NavigationToolbar2Tk(canvas_mcx, chart_frame_mcx) toolbar_mcx.update() canvas_mcx._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
class MainAppView(tk.Frame): """Encapsulates of all the GUI logic. Attributes: master: where to open the Frame, by deafult root window title: Main Label one: Button two: Button three: Button """ width = 100 height = 200 def start_gui(self, ok=True): """Starts the GUI, if everything ok , to change """ if ok: self.mainloop() else: self.master.destroy() def serial_ports(self): ports = serial.tools.list_ports.comports() for port in ports: print port return serial.tools.list_ports.comports() # on change dropdown value def change_dropdown(self, *args): print(self.FPGA_port.get()) def init_attributes(self): self.upArrowImage = Image.open("up_arrow.jpg") self.upArrowPhoto = ImageTk.PhotoImage(self.upArrowImage) def createWidgets(self): """Create the set of initial widgets. """ #create Window Geometry #self.geometry("170x200") # Create Font because Python is dumb sometimes # Create the labels # Title self.title = tk.Label(self, text="iota Biosciences: Dust Development") self.title.grid(row=0, column=0, columnspan=50, sticky=tk.E + tk.W) # Transmit Parameters self.parameter_frame = tk.Frame(self) self.parameter_frame.grid(row=1, column=0, sticky=tk.N) self.transmit_banner = tk.Label(self.parameter_frame, text="Transmit Parameters") self.transmit_banner.grid(row=0, sticky=tk.E + tk.W) f_underline = tkFont.Font(self.transmit_banner, self.transmit_banner.cget("font")) f_underline.configure(underline=True) self.transmit_banner.configure(font=f_underline) # Transmit Frequency self.f_pulse_banner = tk.Label(self.parameter_frame, text="Transmit Frequency") self.f_pulse_banner.grid(row=1, column=0) self.f_pulse_entry = tk.Entry(self.parameter_frame) self.f_pulse_entry.grid(row=1, column=1) self.f_pulse_entry.insert(10, "2.25e6") # Pulse Repition Frequency self.f_repition_banner = tk.Label(self.parameter_frame, text="Pulse Repition Frequency") self.f_repition_banner.grid(row=2, column=0) self.f_repition_entry = tk.Entry(self.parameter_frame) self.f_repition_entry.grid(row=2, column=1) self.f_repition_entry.insert(10, "1e3") # N Pulses Frequency self.pulses_banner = tk.Label(self.parameter_frame, text="Number of Pulses") self.pulses_banner.grid(row=3, column=0) self.pulses_entry = tk.Entry(self.parameter_frame) self.pulses_entry.grid(row=3, column=1) self.pulses_entry.insert(10, "5") # Serial Port Drop Down Menu self.FPGA_port_banner = tk.Label(self.parameter_frame, text="FPGA Port") self.FPGA_port_banner.grid(row=4, column=0) # frame to combine FPGA port info inside frame_parameter self.FPGA_frame = tk.Frame(self.parameter_frame) self.FPGA_frame.grid(row=4, column=1, sticky=tk.E + tk.W) availablePorts = self.serial_ports() self.FPGA_port = tk.StringVar(self) self.FPGA_port.set("Choose Port") self.FPGA_port_menu = tk.OptionMenu(self.FPGA_frame, self.FPGA_port, *availablePorts) self.FPGA_port_menu.grid(row=0, column=0) self.FPGA_port.trace('w', self.change_dropdown) self.FPGA_connect = tk.Button(self.FPGA_frame) self.FPGA_connect["text"] = "Connect" self.FPGA_connect.grid(row=0, column=1) # Create the three buttons button_row = 5 self.sendTx = tk.Button(self.parameter_frame) self.sendTx["text"] = "Send Tx" self.sendTx.grid(row=button_row, column=0) self.stop = tk.Button(self.parameter_frame) self.stop["text"] = "Stop" self.stop.grid(row=button_row, column=1) self.three = tk.Button(self.parameter_frame) self.three["text"] = "1" self.three.grid(row=button_row, column=2) self.four = tk.Button(self.parameter_frame) self.four["text"] = "2" self.four.grid(row=button_row, column=3) # Up arrow button for positioning system self.upArrow = tk.Button(self.parameter_frame, compound=tk.TOP, width=155, height=55, image=self.upArrowPhoto) self.upArrow.grid(row=6, sticky=tk.E + tk.W) # Plot Canvas self.plot_frame = tk.Frame(self) self.plot_frame.grid(row=1, column=2) self.data_figure = Figure(figsize=(5, 5), dpi=100) self.data_figure_subplot = self.data_figure.add_subplot(111) self.data_figure_subplot.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5]) self.data_canvas = FigureCanvasTkAgg(self.data_figure, self.plot_frame) self.data_canvas.draw() self.data_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg(self.data_canvas, self.plot_frame) self.toolbar.update() self.data_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid() # option is needed to put the main label in the window self.init_attributes() self.createWidgets()
class mclass: def __init__(self, window_1): global options, var, options_start, options_end, var_s, var_e self.window_1 = window_1 frame = tk.Frame(self.window_1) frame.pack() parameter_label = tk.Label(frame, text="Choose a parameter:") parameter_label.pack(side='left') self.drop = ttk.Combobox(frame, width=65, textvariable=var) self.drop['values'] = options self.drop.pack(side='left', fill='x', expand=True, pady=10) self.drop.current(1) #Getting start and end times frame_1 = tk.Frame(self.window_1) frame_1.pack(padx=10, pady=10) start_time_label = tk.Label(frame_1, text="Choose Start Time:") start_time_label.pack(side='left', fill='x', expand=True) self.start_time = ttk.Combobox(frame_1, width=20, textvariable=var_s) self.start_time['values'] = options_start self.start_time.pack(side='left', fill='x', expand=True, padx=10) self.start_time.current(0) end_time_label = tk.Label(frame_1, text="Choose End Time:") end_time_label.pack(side='left', fill='x', expand=True, padx=10) self.end_time = ttk.Combobox(frame_1, width=20, textvariable=var_e) self.end_time['values'] = options_end self.end_time.pack(side='left', fill='x', expand=True) self.end_time.current(0) # Functionality buttons frame_2 = tk.Frame(self.window_1) frame_2.pack(pady=10) self.button_1 = ttk.Button(frame_2, text="Generate Run-Chart", command=self.plot) self.button_1.pack(side='left', fill='x', expand=True, padx=0) self.button_2 = ttk.Button(frame_2, text="Clear Plot", width=10, command=self.clr) self.button_2.pack(side='left', fill='x', expand=True, padx=60) self.button_3 = ttk.Button(frame_2, text="Export Report As PDF", command=self.save_file) self.button_3.pack(anchor='nw', side='right', fill='x', expand=True, padx=0) def plot(self): global var, var_s, var_e, df1 column_index = df1.columns.get_loc(var.get()) row_start = int(df1[df1['d_and_t'] == var_s.get()].iloc[0, 0]) - 1 row_end = int(df1[df1['d_and_t'] == var_e.get()].iloc[0, 0]) parameter_1 = df1.iloc[row_start:row_end, column_index] avg = parameter_1.mean() std = parameter_1.std() y_label = var.get() df = df1.iloc[row_start:row_end].copy() df['avg'] = avg number = df[' Time'] upper_1 = avg + std * 1 upper_2 = avg + std * 2 upper_3 = avg + std * 3 lower_1 = avg - std * 1 lower_2 = avg - std * 2 lower_3 = avg - std * 3 df['upper_1'] = upper_1 df['upper_2'] = upper_2 df['upper_3'] = upper_3 df['lower_1'] = lower_1 df['lower_2'] = lower_2 df['lower_3'] = lower_3 self.frame_top = tk.Frame(self.window_1) self.frame_top.pack(fill='both', expand=True) fig_1 = Figure(figsize=(10, 6)) a = fig_1.add_subplot(111) a.plot(number, parameter_1, color='b', marker='o') a.plot(number, df['avg'], linestyle='solid', linewidth=3, color='g') a.plot(number, df['upper_1'], linestyle='dashed', linewidth=3, color='r') a.plot(number, df['upper_2'], linestyle='dashed', linewidth=3, color='r') a.plot(number, df['upper_3'], linestyle='dashed', linewidth=3, color='r') a.plot(number, df['lower_1'], linestyle='dashed', linewidth=3, color='r') a.plot(number, df['lower_2'], linestyle='dashed', linewidth=3, color='r') a.plot(number, df['lower_3'], linestyle='dashed', linewidth=3, color='r') a.set_xlabel('Time', fontsize=14) a.set_ylabel('{}'.format(y_label), fontsize=14) a.set_title('X-Bar Run Chart', fontsize=16) for label in a.get_xticklabels(): label.set_rotation(90) self.canvas = FigureCanvasTkAgg(fig_1, master=self.frame_top) self.canvas.get_tk_widget().pack(fill='both', expand=True) self.canvas.draw() toolbar = NavigationToolbar2Tk(self.canvas, self.frame_top) toolbar.update() self.results() def results(self): global var, var_s, var_e column_index = df1.columns.get_loc(var.get()) row_start = int(df1[df1['d_and_t'] == var_s.get()].iloc[0, 0]) row_end = int(df1[df1['d_and_t'] == var_e.get()].iloc[0, 0]) parameter_1 = df1.iloc[row_start:row_end + 1, column_index] avg = parameter_1.mean() std = parameter_1.std() target = avg tolerance = std # defining the zones and limits upper_1 = avg + std * 1 upper_2 = avg + std * 2 upper_3 = avg + std * 3 lower_1 = avg - std * 1 lower_2 = avg - std * 2 lower_3 = avg - std * 3 # checking for special cause variations self.errors = set() self.errors.clear differentials_to_target = parameter_1 - target differentials_to_avg = parameter_1 - avg first_differences = np.ediff1d(parameter_1) #tolerances if np.max(np.absolute(differentials_to_target)) > tolerance: self.errors.add("Dimensions are out of tolerance") #beyond limit absolute_differentials = np.absolute(differentials_to_avg) if np.max(absolute_differentials) > upper_3: self.errors.add("Outliers Exist") #outer region or Zone A for index, i in enumerate(absolute_differentials): if index < 2: continue count = np.count_nonzero( absolute_differentials[index - 2:index + 1] > (std * 2)) if count >= 2: self.errors.add("Outer Zone Clusters") #middle regions or Zone B for index, i in enumerate(absolute_differentials): if index < 4: continue count = np.count_nonzero( absolute_differentials[index - 4:index + 1] > (std * 1)) if count >= 4: self.errors.add("Middle Zone Clusters") #inner region or Zone C for index, i in enumerate(absolute_differentials): if index < 6: continue count = np.count_nonzero( differentials_to_avg[index - 6:index + 1] > 0) if count >= 7: self.errors.add("Inner Zone Clusters") count = np.count_nonzero( differentials_to_avg[index - 6:index + 1] < 0) if count >= 7: self.errors.add("Inner Zone Clusters") #trends for index, i in enumerate(first_differences): if index < 6: continue count = np.count_nonzero( first_differences[index - 5:index + 1] > 0) if count >= 7: self.errors.add("Trending Data is Present") count = np.count_nonzero( first_differences[index - 5:index + 1] < 0) if count >= 7: self.errors.add("Trending Data is Present") #mixture for index, i in enumerate(absolute_differentials): if index < 8: continue count = np.count_nonzero( absolute_differentials[index - 8:index + 1] > upper_3) if count == 0: self.errors.add("No Mixture") else: self.errors.add("Mixture") #stratification for index, i in enumerate(absolute_differentials): if index < 15: continue count = np.count_nonzero( absolute_differentials[index - 15:index + 1] > upper_1) if count == 0: self.errors.add("No Stratification") #over control def sign_change(x, y): if x > 0 and y > 0: return 0 elif x < 0 and y < 0: return 0 else: return 1 changes = [] for index, i in enumerate(first_differences): if index == 0: continue change = sign_change(first_differences[index], first_differences[index - 1]) changes.append(change) for index, i in enumerate(changes): if index < 14: continue if np.array(changes[index - 14:index + 1]).sum() >= 15: self.errors.add("Over Control") self.frame_bottom_1 = tk.Frame(window_1) self.frame_bottom_1.pack(fill='x') tk.Label(self.frame_bottom_1, text="Errors:").pack(side='left', fill='x') entry1 = ttk.Entry(self.frame_bottom_1, width=100, font=('Helvetica', 10)) entry1.pack(side='left', fill='x', expand=True) entry1.insert(0, repr(self.errors)) self.cause() def cause(self): # Possible causes self.causes = set() for ele in self.errors: if ele == "Dimensions are out of tolerance": self.causes.add( "Process not proper, leading to dimensional variation") elif ele == "Outliers Exist" or ele == "Outer Zone Clusters": self.causes.add( "New person doing the job, Wrong setup, Measurement error, Process step skipped, Process step not completed, Power failure, Equipment breakdown" ) elif ele == "Middle Zone Clusters" or ele == "Inner Zone Clusters": self.causes.add( "Raw material change, Change in work instruction, Different measurement device/calibration, Different shift, Person gains greater skills in doing the job, Change in maintenance program, Change in setup procedure" ) elif ele == "Trending data is present": self.causes.add( "Tooling wear or Temperature effects (cooling, heating)") elif ele == "Mixture" or ele == "Stratification": self.causes.add( "More than one process present (e.g. shifts, machines, raw material.)" ) elif ele == "Over Control": self.causes.add( "Tampering by operator or Alternating raw materials") self.frame_bottom_2 = tk.Frame(window_1) self.frame_bottom_2.pack(fill='x') tk.Label(self.frame_bottom_2, text="Possible\nCauses:").pack(side='left', fill='x') entry1 = tk.Text(self.frame_bottom_2, height=3, width=5, font=('Helvetica', 10), bg='white', borderwidth=3) entry1.pack(side='left', fill='x', expand=True, pady=4) lst = repr(self.causes).split("',") for ele in lst: entry1.insert(tk.END, str(ele) + "\n") def save_file(self): # create a new PDF with Reportlab can = canvas.Canvas("Report.pdf", pagesize=letter) # exporting plot as PDF global var, var_s, var_e, df1 column_index = df1.columns.get_loc(var.get()) row_start = int(df1[df1['d_and_t'] == var_s.get()].iloc[0, 0]) - 1 row_end = int(df1[df1['d_and_t'] == var_e.get()].iloc[0, 0]) parameter_1 = df1.iloc[row_start:row_end, column_index] avg = parameter_1.mean() std = parameter_1.std() y_label = var.get() df = df1.iloc[row_start:row_end].copy() df['avg'] = avg number = df[' Time'] upper_1 = avg + std * 1 upper_2 = avg + std * 2 upper_3 = avg + std * 3 lower_1 = avg - std * 1 lower_2 = avg - std * 2 lower_3 = avg - std * 3 df['upper_1'] = upper_1 df['upper_2'] = upper_2 df['upper_3'] = upper_3 df['lower_1'] = lower_1 df['lower_2'] = lower_2 df['lower_3'] = lower_3 #with PdfPages('C:\\Users\\M SAI JASWANTH\\Report.pdf') as export_pdf: plt.plot(number, parameter_1, color='b', marker='o') plt.plot(number, df['avg'], linestyle='solid', linewidth=3, color='g') plt.plot(number, df['upper_1'], linestyle='dashed', linewidth=3, color='r') plt.plot(number, df['upper_2'], linestyle='dashed', linewidth=3, color='r') plt.plot(number, df['upper_3'], linestyle='dashed', linewidth=3, color='r') plt.plot(number, df['lower_1'], linestyle='dashed', linewidth=3, color='r') plt.plot(number, df['lower_2'], linestyle='dashed', linewidth=3, color='r') plt.plot(number, df['lower_3'], linestyle='dashed', linewidth=3, color='r') plt.xlabel('Time', fontsize=10) plt.ylabel('{}'.format(y_label), fontsize=10) plt.title('X-Bar Run Chart', fontsize=12) plt.xticks(rotation=90) plt.grid(True) plt.savefig('plot.png') plt.close() # errors and causes to PDF can.drawImage("Lear_Logo.png", 10, 710, width=200, height=75, mask=None) can.drawImage("plot.png", 15, 300, width=600, height=400, mask=None) can.drawString(65, 250, "Errors:") can.drawString(65, 230, repr(self.errors)) can.drawString(65, 180, "Possible Causes:") lst = repr(self.causes).split("',") y = 140 for i in range(len(lst)): ele = str(lst[i]) print(ele) if len(str(ele)) > 90: can.drawString(65, y + 15, ele[:90]) can.drawString(65, y, ele[90:180]) can.drawString(65, y - 15, ele[180:270]) can.drawString(65, y - 30, ele[270:]) else: can.drawString(65, y - 15, ele) y -= 15 can.save() def clr(self): self.frame_top.destroy() self.frame_bottom_1.destroy() self.frame_bottom_2.destroy()
class InverseProgressWindow(tk.Toplevel): def __init__(self, mainapp, init_soln, init_sse, init_aLm): tk.Toplevel.__init__(self, mainapp) self.config(bg=mainapp.Background1) self.title('Inverse solver progress window') # Make current solutions plot frame1 = tk.Frame(self, relief='solid', borderwidth=3) self.fig1 = Figure() self.fig1.suptitle('Inverse Solution', weight='bold') self.ax1 = self.fig1.add_subplot(111) self.ax1.set_xlabel('Time (m.y.)') self.ax1.set_ylabel('Temperature (C') self.line11 = self.ax1.plot(init_soln[:, 0], init_soln[:, 1], 'b-', label='Current')[0] self.line12 = self.ax1.plot(init_soln[:, 0], init_soln[:, 1], 'bs')[0] self.line13 = self.ax1.plot(init_soln[:, 0], init_soln[:, 1], 'k--', label='Initial') self.ax1.legend() self.canvas1 = FigureCanvasTkAgg(self.fig1, frame1) self.canvas1.draw() self.canvas1.get_tk_widget().pack(side='top', fill='both', expand=1) self.canvas1._tkcanvas.pack(side='top', fill='both', expand=1) frame1.grid(row=2, column=0, padx=(10, 10), pady=(5, 10)) # Make bar plot of objective values frame2 = tk.Frame(self, relief='solid', borderwidth=3) self.fig2 = Figure() self.fig2.suptitle('Model Fit', weight='bold') self.ax2 = self.fig2.add_subplot(111) self.ax2.set_xlabel('LM Iteration') self.bar1 = self.ax2.bar(range(30), [init_sse + init_aLm] + 29 * [0], color='#373f47', label='Total objective value') self.bar2 = self.ax2.bar(range(30), [init_sse] + 29 * [0], color='#6c91c2', label='Weighted SSE') self.ax2.legend() self.canvas2 = FigureCanvasTkAgg(self.fig2, frame2) self.canvas2.draw() self.canvas2.get_tk_widget().pack(side='top', fill='both', expand=1) self.canvas2._tkcanvas.pack(side='top', fill='both', expand=1) frame2.grid(row=2, column=1, padx=(10, 10), pady=(5, 10)) # Add text labels for current initial solution and derivative self.calc_var = tk.StringVar(self) self.calc_var.set("") self.calc_lab = tk.Label(self, textvariable=self.calc_var, font=mainapp.font_sections, bg=mainapp.Background1) self.calc_lab.grid(row=1, column=0, sticky='w', pady=(5, 0), padx=(8, 0)) self.init_var = tk.StringVar(self) self.init_var.set("") self.init_lab = tk.Label(self, textvariable=self.init_var, font=mainapp.font_large, bg=mainapp.Background1) self.init_lab.grid(row=0, column=0, columnspan=2, sticky='nswe', pady=(15, 15)) self.update()
d_label.grid(row=7, columnspan=3) d_info.grid(row=8, column=1) #wordcloud wordc = plt.figure(figsize=(5, 4), dpi=100) wordc.patch.set_facecolor('xkcd:mint green') #image coloring plt.imshow(CHAT.wordcloud, interpolation="bilinear") canvas = FigureCanvasTkAgg(wordc, ctr_right) canvas.get_tk_widget().pack(fill='x') plt.tight_layout(pad=0) plt.axis("off") plt.margins(x=0, y=0) plt.title("WordCloud") canvas.draw() #plt.savefig('gui/images/www.png', bbox_inches='tight') #graphs my_colors = ['#A7226E', '#EC2049', '#F26B38', '#F7DB4F'] graph_font_size = 'x-small' #BAR figure2 = plt.Figure(figsize=(4, 4), dpi=100) figure2.patch.set_facecolor(btm_frame.cget("bg")) ax2 = figure2.add_subplot(111) line2 = FigureCanvasTkAgg(figure2, btm_frame) line2.get_tk_widget().pack(side=LEFT, fill='x') CHAT.top_10_sorted_total_word_count_grouped_by_sender.plot(kind='bar', ax=ax2, color=my_colors,
class LeftFrame: def __init__(self, root, master, debug_print_flag=False): self.master = master self.root = root self.xmin = 0 self.xmax = 1000 self.ymin = 0 self.ymax = 100 self.input_dimension = 2 #learning rate self.alpha = 0.1 #weight regularization self.lambda_regularizer = 0.01 #number of iterations self.epochs = 10 #number of nodes in the hidden layer self.number_of_nodes = 100 #number of data samples self.number_of_samples = 200 #number of classes in data self.number_of_classes = 4 #type of data generated self.type_of_data = "s_curve" #activation function to be used on hidden layer self.activation_type = "Relu" #create weight matrix with random numbers between -0.001 to 0.001 #Size of weight matrix depends on the number of nodes in the hidden layer => everytime no. of nodes changes, weights of hidden layer are reinitialzed #And the no. of nodes also determines the size of weights in output layer => everytime no. of nodes changes, weights of output layer also needs to be reset #reinitialize the weights also when a new no. of classes, as the no. of nodes in output layer changes self.initialize_weights_and_bias() # generate input data samples based on the : no_of_samples, no_of_samples, data_sample_category #variables to hold input data samples and their corresponding class self.input_data, self.input_labels = generate_data_samples_with_classes( self.type_of_data, self.number_of_samples, self.number_of_classes) master.rowconfigure(0, weight=10, minsize=200) master.columnconfigure(0, weight=2) self.plot_frame = tk.Frame(self.master, borderwidth=10, relief=tk.SUNKEN) self.plot_frame.grid(row=0, column=0, columnspan=1, sticky=tk.N + tk.E + tk.S + tk.W) #actual plotting of the graph self.figure = plt.figure(figsize=(20, 10)) #setting the size of the plot #self.figure = plt.figure("") self.axes = self.figure.add_axes([0.15, 0.15, 0.6, 0.6], autoscaley_on=True) # self.axes = self.figure.gca() self.axes.set_xlabel('X') #setting label for x-axis self.axes.set_ylabel('Y') #setting label for y-axis self.axes.set_title(self.type_of_data) plt.xlim(self.xmin, self.xmax) plt.ylim(self.ymin, self.ymax) self.canvas = FigureCanvasTkAgg(self.figure, master=self.plot_frame) self.plot_widget = self.canvas.get_tk_widget() self.plot_widget.grid(row=0, column=0, sticky=tk.N + tk.E + tk.S + tk.W) # Create a frame to contain all the controls such as sliders, buttons, ... self.controls_frame = tk.Frame(self.master) self.controls_frame.grid(row=2, column=0, sticky=tk.N + tk.E + tk.S + tk.W) ######################################################################### # Set up the control widgets such as sliders and selection boxes ######################################################################### # slider 1 : learning rate - alpha slider self.alpha_slider = tk.Scale( self.controls_frame, variable=tk.DoubleVar(), orient=tk.HORIZONTAL, from_=0, to_=1.0, resolution=0.001, bg="#DDDDDD", activebackground="#FF0000", highlightcolor="#00FFFF", label="Alpha(learning rate)", command=lambda event: self.alpha_slider_callback()) self.alpha_slider.set(self.alpha) self.alpha_slider.grid(row=0, column=0, sticky=tk.N + tk.E + tk.S + tk.W) # slider 2 : weight regularization self.lambda_slider = tk.Scale( self.controls_frame, variable=tk.DoubleVar(), orient=tk.HORIZONTAL, from_=0, to_=1.0, resolution=0.01, bg="#DDDDDD", activebackground="#FF0000", highlightcolor="#00FFFF", label="Lambda", command=lambda event: self.lambda_slider_callback()) self.lambda_slider.set(self.lambda_regularizer) self.lambda_slider.grid(row=0, column=1, sticky=tk.N + tk.E + tk.S + tk.W) # slider 3 : Number of nodes in hidden layer self.nodes_slider = tk.Scale( self.controls_frame, variable=tk.DoubleVar(), orient=tk.HORIZONTAL, from_=1, to_=500, resolution=1, bg="#DDDDDD", activebackground="#FF0000", highlightcolor="#00FFFF", label="Num. of Nodes in Hidden Layer", command=lambda event: self.nodes_slider_callback()) self.nodes_slider.set(self.number_of_nodes) self.nodes_slider.grid(row=0, column=2, sticky=tk.N + tk.E + tk.S + tk.W) # slider 4 : Number of samples in input data self.number_of_samples_slider = tk.Scale( self.controls_frame, variable=tk.DoubleVar(), orient=tk.HORIZONTAL, from_=4, to_=1000, resolution=1, bg="#DDDDDD", activebackground="#FF0000", highlightcolor="#00FFFF", label="Number of Samples", command=lambda event: self.number_of_samples_slider_callback()) self.number_of_samples_slider.set(self.number_of_samples) self.number_of_samples_slider.grid(row=0, column=3, sticky=tk.N + tk.E + tk.S + tk.W) # slider 5 : Number of Classes in input data self.number_of_classes_slider = tk.Scale( self.controls_frame, variable=tk.DoubleVar(), orient=tk.HORIZONTAL, from_=2, to_=10, resolution=1, bg="#DDDDDD", activebackground="#FF0000", highlightcolor="#00FFFF", label="Number of Classes", command=lambda event: self.number_of_classes_slider_callback()) self.number_of_classes_slider.set(self.number_of_classes) self.number_of_classes_slider.grid(row=0, column=4, sticky=tk.N + tk.E + tk.S + tk.W) # button 1 - When this button is pushed train the model on the data and get the weights and plots should be displayed self.adjust_weight_button = tk.Button(self.controls_frame, text="Adjust Weight(Train)", fg="red", command=self.train_data) self.adjust_weight_button.grid(row=0, column=5) # button 2 - When this button is pushed all the weights and biases should be initialized between -0.001 and +0.001 self.init_weight_button = tk.Button( self.controls_frame, text="Reset Weights", fg="blue", command=self.initialize_weights_and_bias) self.init_weight_button.grid(row=0, column=6) # Drop down 1 - to Select Hidden Layer Transfer Function self.label_for_activation_function = tk.Label( self.controls_frame, text="Activation Function Type:", justify="center") self.label_for_activation_function.grid(row=0, column=7, sticky=tk.N + tk.E + tk.S + tk.W) self.activation_function_variable = tk.StringVar() self.activation_function_dropdown = tk.OptionMenu( self.controls_frame, self.activation_function_variable, "Relu", "Sigmoid", command=lambda event: self.activation_function_dropdown_callback()) self.activation_function_variable.set("Relu") self.activation_function_dropdown.grid(row=0, column=7, sticky=tk.N + tk.E + tk.S + tk.W) # Drop down 2 - to Select Type of generated data self.label_for_type_of_data = tk.Label(self.controls_frame, text="Type of generated data:", justify="center") self.label_for_type_of_data.grid(row=0, column=8, sticky=tk.N + tk.E + tk.S + tk.W) self.type_of_data_variable = tk.StringVar() self.type_of_data_dropdown = tk.OptionMenu( self.controls_frame, self.type_of_data_variable, "s_curve", "blobs", "swiss_roll", "moons", command=lambda event: self.type_of_data_dropdown_callback()) self.type_of_data_variable.set("s_curve") self.type_of_data_dropdown.grid(row=0, column=8, sticky=tk.N + tk.E + tk.S + tk.W) def alpha_slider_callback(self): self.alpha = np.float(self.alpha_slider.get()) def lambda_slider_callback(self): self.lambda_regularizer = np.float(self.lambda_slider.get()) def nodes_slider_callback(self): self.number_of_nodes = np.int_(self.nodes_slider.get()) self.initialize_weights_and_bias() def number_of_samples_slider_callback(self): self.number_of_samples = self.number_of_samples_slider.get() self.input_data, self.input_labels = generate_data_samples_with_classes( self.type_of_data, self.number_of_samples, self.number_of_classes) self.display_points() def number_of_classes_slider_callback(self): self.number_of_classes = self.number_of_classes_slider.get() self.initialize_weights_and_bias() self.input_data, self.input_labels = generate_data_samples_with_classes( self.type_of_data, self.number_of_samples, self.number_of_classes) self.display_points() def initialize_weights_and_bias(self): print("weights and bias initialized.") self.Weights_hidden_layer = np.random.uniform( -0.001, 0.001, self.input_dimension * self.number_of_nodes) self.Weights_hidden_layer = self.Weights_hidden_layer.reshape( self.input_dimension, self.number_of_nodes) self.Bias_hidden_layer = np.random.uniform(-0.001, 0.001, self.number_of_nodes) print("shape of hidden layer weights and biases :: ", self.Weights_hidden_layer.size, self.Bias_hidden_layer.size) self.Weights_output_layer = np.random.uniform( -0.001, 0.001, self.number_of_nodes * self.number_of_classes) self.Weights_output_layer = self.Weights_output_layer.reshape( self.number_of_nodes, self.number_of_classes) self.Bias_output_layer = np.random.uniform(-0.001, 0.001, self.number_of_classes) print("shape of Output layer weights and biases :: ", self.Weights_output_layer.size, self.Bias_output_layer.size) def train_data(self): print("Training the model on the data.") input_data = self.input_data input_labels = self.input_labels training_epochs = 10 lambda_regularizer = self.lambda_regularizer num_of_nodes_hidden_layer = self.number_of_nodes input_dimension = self.input_dimension num_of_nodes_output_layer = self.number_of_classes labels_onehot = np.zeros( (input_data.shape[0], num_of_nodes_output_layer)) labels_onehot_encoded = one_hot_encoding_of_input_labels( labels_onehot, input_labels) # build the model.... tensorflow graph input learning_rate = tf.Variable(self.alpha, dtype=tf.float32) x = tf.placeholder('float', [None, input_dimension]) y = tf.placeholder('float', [None, num_of_nodes_output_layer]) weights_hidden_layer = tf.Variable(self.Weights_hidden_layer, dtype=tf.float32) bias_hidden_layer = tf.Variable(self.Bias_hidden_layer, dtype=tf.float32) net_hidden = tf.add(tf.matmul(x, weights_hidden_layer), bias_hidden_layer) if (self.activation_type == "Relu"): output_hidden_layer = tf.nn.relu(net_hidden) elif (self.activation_type == "Sigmoid"): output_hidden_layer = tf.nn.sigmoid(net_hidden) weights_output_layer = tf.Variable(self.Weights_output_layer, dtype=tf.float32) bias_output_layer = tf.Variable(self.Bias_output_layer, dtype=tf.float32) output_output_layer = tf.matmul( output_hidden_layer, weights_output_layer) + bias_output_layer cross_entropy_loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2( logits=output_output_layer, labels=y)) regularizers = tf.nn.l2_loss(weights_hidden_layer) + tf.nn.l2_loss( weights_output_layer) cost = tf.reduce_mean(cross_entropy_loss + lambda_regularizer * tf.cast(regularizers, tf.float32)) optimizer = tf.train.AdamOptimizer( learning_rate=learning_rate).minimize(cost) actuals = tf.argmax(output_output_layer, 1) targets = tf.argmax(y, 1) # For each index, equal() determines if the element in the first tensor equals the one in the second. We get an array of bools (True and False) num_of_correct_prediction = tf.equal(tf.argmax(output_output_layer, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(num_of_correct_prediction, 'float')) # initialize variables # init = tf.initialize_all_variables() init = tf.global_variables_initializer() # launch graph with tf.Session() as sess: sess.run(init) # define training cycle for epoch in range(10): batch_x, batch_y = input_data, labels_onehot_encoded _cost_, _cross_entropy_loss, _actuals_, _accuracy, _optimizer_, _weights_hidden_layer_, _bias_hidden_layer_, _weights_output_layer_, _bias_output_layer_ = sess.run( [ cost, cross_entropy_loss, actuals, accuracy, optimizer, weights_hidden_layer, bias_hidden_layer, weights_output_layer, bias_output_layer ], feed_dict={ x: batch_x, y: batch_y }) self.Weights_hidden_layer = _weights_hidden_layer_ self.Bias_hidden_layer = _bias_hidden_layer_ self.Weights_output_layer = _weights_output_layer_ self.Bias_output_layer = _bias_output_layer_ print("Cost ::::: ", _cost_, " , cross_entropy_loss :: ", _cross_entropy_loss) print(" Accuracy :: ", _accuracy) self.display_line() print('Training finished for 10 epochs') def prediction_for_points(self, data_points): x = tf.placeholder('float', [None, self.input_dimension]) weights_hidden_layer = tf.Variable(self.Weights_hidden_layer, dtype=tf.float32) bias_hidden_layer = tf.Variable(self.Bias_hidden_layer, dtype=tf.float32) net_hidden = tf.add(tf.matmul(x, weights_hidden_layer), bias_hidden_layer) if (self.activation_type == "Relu"): output_hidden_layer = tf.nn.relu(net_hidden) elif (self.activation_type == "Sigmoid"): output_hidden_layer = tf.nn.sigmoid(net_hidden) weights_output_layer = tf.Variable(self.Weights_output_layer, dtype=tf.float32) bias_output_layer = tf.Variable(self.Bias_output_layer, dtype=tf.float32) output_output_layer = tf.matmul( output_hidden_layer, weights_output_layer) + bias_output_layer actuals = tf.argmax(output_output_layer, 1) init = tf.global_variables_initializer() # launch graph with tf.Session() as sess: sess.run(init) _x_, _actuals_ = sess.run([x, actuals], feed_dict={x: data_points}) return _actuals_ def display_line(self): self.axes.cla() self.axes.set_xlabel('Input') self.axes.set_ylabel('Output') resolution = 100 xs = np.linspace( np.amin(self.input_data[:, 0]) - 0.5, np.amax(self.input_data[:, 0]) + 0.5, resolution) ys = np.linspace( np.amin(self.input_data[:, 1]) - 0.5, np.amax(self.input_data[:, 1]) + 0.5, resolution) xx, yy = np.meshgrid(xs, ys) count = 0 data_points = np.zeros((resolution**2, 2)) for i in range(resolution): for j in range(resolution): data_points[count, 0] = xx[i, j] data_points[count, 1] = yy[i, j] count += 1 zz = self.prediction_for_points(data_points) zz = np.reshape(zz, (resolution, resolution)) self.axes.pcolormesh(xx, yy, zz, cmap="Accent", zorder=1) self.axes.scatter(self.input_data[:, 0], self.input_data[:, 1], c=self.input_labels, zorder=2) self.axes.xaxis.set_visible(True) self.canvas.draw() def activation_function_dropdown_callback(self): self.activation_type = self.activation_function_variable.get() print("Activation Function chosen :: ", self.activation_type) def type_of_data_dropdown_callback(self): self.type_of_data = self.type_of_data_variable.get() self.initialize_weights_and_bias() self.input_data, self.input_labels = generate_data_samples_with_classes( self.type_of_data, self.number_of_samples, self.number_of_classes) self.display_points() def display_points(self): self.axes.cla() self.axes.set_title(self.type_of_data) self.axes.set_xlabel('X') self.axes.set_ylabel('Y') self.axes.scatter(self.input_data[:, 0], self.input_data[:, 1], c=self.input_labels) self.axes.xaxis.set_visible(True) self.canvas.draw()
def init_result_window(self, vector_list): self.title("Расчеты") self.resizable(False, False) self.grab_set() self.focus_set() self.geometry('600x550+{}+{}'.format(400, 100)) wait_lab = tk.Label( self, text="Идет расчёт результатов, это может занять немного времени") wait_lab.pack() self.update() calc_obj = Calc.Calculate() calc_obj.calc_dist(vector_list, self) min_dist = calc_obj.get_min_distans() max_dist = calc_obj.get_max_distans() wait_lab.destroy() min_labl = tk.Label(self, text=("Минимальное расстояние: " + str(min_dist[2]))) max_labl = tk.Label(self, text=("Максимальное расстояние: " + str(max_dist[2]))) frame1 = tk.Frame(self) frame2 = tk.Frame(self) lbox_min = tk.Listbox(frame1, width=100, height=2) lbox_max = tk.Listbox(frame2, width=100, height=2) for i in range(2): lbox_min.insert(i, ("Вектор №" + str(min_dist[i] + 1) + " " + str(vector_list[min_dist[i]]))) lbox_max.insert(i, ("Вектор №" + str(max_dist[i] + 1) + " " + str(vector_list[max_dist[i]]))) scroll_min = tk.Scrollbar(frame1, orient='horizontal', command=lbox_min.xview) scroll_max = tk.Scrollbar(frame2, orient='horizontal', command=lbox_max.xview) lbox_min.config(xscrollcommand=scroll_min.set) lbox_max.config(xscrollcommand=scroll_max.set) # Отображает пары векторов с минимальным и максимальным расстояниям. frame1.pack() lbox_min.pack() scroll_min.pack(side='bottom', fill='x') min_labl.pack() frame2.pack() lbox_max.pack() scroll_max.pack(side='bottom', fill='x') max_labl.pack() # Рисует гистограмму. fig = Figure(figsize=(6, 6)) ax = fig.add_subplot(111) ax.set_title("Гистограмма распределения расстояний векторов") ax.grid(zorder=0) ax.bar(calc_obj.get_dist_bins(), calc_obj.get_dist_values(), 0.10, edgecolor='black', zorder=3) ax.set_xticks( np.arange(round(min_dist[2], 1), round(max_dist[2], 1), step=0.3)) ax.set_xlabel('Расстояние') ax.set_ylabel('Частота') canvas = FigureCanvasTkAgg(fig, master=self) canvas.get_tk_widget().pack() canvas.draw()
root = tkinter.Tk() # 创建tkinter的主窗口 root.title("在tkinter中使用matplotlib") f = Figure(figsize=(5, 4), dpi=100) a = f.add_subplot(111) # 添加子图:1行1列第1个 # 生成用于绘sin图的数据 x = np.arange(0, 3, 0.01) y = np.sin(2 * np.pi * x) # 在前面得到的子图上绘图 a.plot(x, y) # 将绘制的图形显示到tkinter:创建属于root的canvas画布,并将图f置于画布上 canvas = FigureCanvasTkAgg(f, master=root) canvas.draw() # 注意show方法已经过时了,这里改用draw canvas.get_tk_widget().pack( side=tkinter.TOP, # 上对齐 fill=tkinter.BOTH, # 填充方式 expand=tkinter.YES) # 随窗口大小调整而调整 # matplotlib的导航工具栏显示上来(默认是不会显示它的) toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() canvas._tkcanvas.pack( side=tkinter.TOP, # get_tk_widget()得到的就是_tkcanvas fill=tkinter.BOTH, expand=tkinter.YES) def on_key_event(event):
class Application(Tk.Frame): def __init__(self, master = None): Tk.Frame.__init__(self, master) self.master = master self.initialize() def initialize(self): self.grid() self.createWidgets() self.entryVariable1 = Tk.StringVar() self.entry1 = Tk.Entry(self, textvariable=self.entryVariable1) self.entry1.grid(column=1,row=0,sticky='EW') self.labelVariable1 = Tk.StringVar() label1 = Tk.Label(self,textvariable=self.labelVariable1, anchor="w",fg="black",bg="yellow") label1.grid(column=0,row=0,columnspan=1 ,sticky='EW') self.labelVariable1.set( "Car_pollution" ) self.entryVariable2 = Tk.StringVar() self.entry2 = Tk.Entry(self,textvariable=self.entryVariable2) self.entry2.grid(column=1,row=1,sticky='EW') self.labelVariable2 = Tk.StringVar() label2 = Tk.Label(self,textvariable=self.labelVariable2, anchor="w",fg="black",bg="yellow") label2.grid(column=0,row=1,columnspan=1 ,sticky='EW') self.labelVariable2.set( "Car amount" ) self.entryVariable3 = Tk.StringVar() self.entry3 = Tk.Entry(self,textvariable=self.entryVariable3) self.entry3.grid(column=1,row=2,sticky='EW') self.labelVariable3 = Tk.StringVar() label3 = Tk.Label(self,textvariable=self.labelVariable3, anchor="w",fg="black",bg="yellow") label3.grid(column=0,row=2,columnspan=1 ,sticky='EW') self.labelVariable3.set( "Fund" ) self.entryVariable4 = Tk.StringVar() self.entry4 = Tk.Entry(self,textvariable=self.entryVariable4) self.entry4.grid(column=1,row=3,sticky='EW') self.labelVariable4 = Tk.StringVar() label4 = Tk.Label(self,textvariable=self.labelVariable4, anchor="w",fg="black",bg="yellow") label4.grid(column=0,row=3,columnspan=1 ,sticky='EW') self.labelVariable4.set( "filter_cost") self.entryVariable5 = Tk.StringVar() self.entry5 = Tk.Entry(self,textvariable=self.entryVariable5) self.entry5.grid(column=1,row=4,sticky='EW') self.labelVariable5 = Tk.StringVar() label5 = Tk.Label(self,textvariable=self.labelVariable5, anchor="w",fg="black",bg="yellow") label5.grid(column=0,row=4,columnspan=1 ,sticky='EW') self.labelVariable5.set( "fee") self.entryVariable6 = Tk.StringVar() self.entry6 = Tk.Entry(self,textvariable=self.entryVariable6) self.entry6.grid(column=1,row=5,sticky='EW') self.labelVariable6 = Tk.StringVar() label6 = Tk.Label(self,textvariable=self.labelVariable6, anchor="w",fg="black",bg="yellow") label6.grid(column=0,row=5,columnspan=1 ,sticky='EW') self.labelVariable6.set( "critical pollution") self.entryVariable7 = Tk.StringVar() self.entry7 = Tk.Entry(self,textvariable=self.entryVariable7) self.entry7.grid(column=1,row=6,sticky='EW') self.labelVariable7 = Tk.StringVar() label7 = Tk.Label(self,textvariable=self.labelVariable7, anchor="w",fg="black",bg="yellow") label7.grid(column=0,row=6,columnspan=1 ,sticky='EW') self.labelVariable7.set( "wind power") self.entry1.bind("<Return>", self.OnPressEnter) self.entry2.bind("<Return>", self.OnPressEnter) self.entry3.bind("<Return>", self.OnPressEnter) self.entry4.bind("<Return>", self.OnPressEnter) self.entry5.bind("<Return>", self.OnPressEnter) self.entry6.bind("<Return>", self.OnPressEnter) self.entry7.bind("<Return>", self.OnPressEnter) self.labelVariable = Tk.StringVar() label = Tk.Label(self,textvariable=self.labelVariable, anchor="w",fg="white",bg="blue") label.grid(column=0,row=7,columnspan=2,sticky='EW') self.grid_columnconfigure(0,weight=1) #self.resizable(True,False) self.update() #self.geometry(self.geometry())#TODO def createWidgets(self): self.fig = plt.Figure() self.canvas = FigureCanvasTkAgg(self.fig, master=self.master) self.canvas.get_tk_widget().grid(column=0,row=5) self.ax = self.fig.add_subplot(111) self.ax.set_xticks(()) self.ax.set_yticks(()) def OnPressEnter(self,event): n1 = self.entryVariable1.get() n2 = self.entryVariable2.get() n3 = self.entryVariable3.get() n4 = self.entryVariable4.get() n5 = self.entryVariable5.get() n6 = self.entryVariable6.get() n7 = self.entryVariable7.get() if (n1 == '') or (n2 == '') or (n3 == '') or (n4 == '') or (n5 == '') or (n6 == '') or (n7 == ''): self.labelVariable.set("You need to enter every value") return self.manager = Manager(int(n1), int(n2), int(n3), int(n4), int(n5), int(n6), int(n7))#TODO text = dict() percent = dict() pollution = dict() Pollution = dict() for i in range(25): Control = Control_data(self) self.master.wait_window(Control.top) self.manager.main() if (i == 0): man = self.manager self.x = np.linspace(0, int(man.Town.Area[0]), 100) self.y = np.linspace(0, int(man.Town.Area[1]), 100).reshape(-1, 1) im = self.ax.imshow(f(self.x, self.y, man.Town.Companies, man.Town.residual_pollution), cmap='YlOrRd', vmin = 0, vmax = 10, animated=False) for company in self.manager.Town.Companies: x, y = company.location size = company.size self.ax.add_patch( patches.Rectangle( (x, y), # (x,y) size/2, # width size/2, # height hatch='\\', fill=False )) self.ax.text(x, y, company.name, style='italic') text[company] = self.ax.text(5 + x, 5 + y, "filters: %d" %(company.filters), style='italic') percent[company] = self.ax.text(10 + x, 10 + y, "%" + "%d" %(round(company.day_count * (100.0/7))), style='italic') pollution[company] = self.ax.text(10 + x, 15 + y, "pollution: %.2f" %(company.daily_pollution), style='italic') Fund = self.ax.text(30, 30, "Fund: %d" %(self.manager.Town.Fund)) count = 0 for point in self.manager.Town.points: c1, c2 = point Pollution[point] = self.ax.text(c1, c2, "Pollution: %.2f" %(self.manager.Town.Pollution[count])) count += 1 else: im.set_array(f(self.x, self.y, self.manager.Town.Companies, self.manager.Town.residual_pollution)) for company in self.manager.Town.Companies: text[company].set_text("filters: %d" %(company.filters)) percent[company].set_text("%" + "%d" %(round(company.day_count * (100.0/7)))) pollution[company].set_text("pollution: %.2f" %(company.daily_pollution)) Fund.set_text("Fund: %d" %(self.manager.Town.Fund)) count = 0 for point in self.manager.Town.points: Pollution[point].set_text("Pollution: %.2f" %(self.manager.Town.Pollution[count])) count += 1 self.canvas.draw()
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
def add_plot(self, i): fig = Figure(figsize=(5, 4), dpi=100) fig.add_subplot(111).scatter(self.p[i].x, self.p[i].y, s=5) canvas = FigureCanvasTkAgg(fig, master=self.p[i]) canvas.draw() canvas.get_tk_widget().grid(column=0, row=2)
class appclass: def __init__(self, window, companies, dataFile): self.companies = companies self.dataFile = dataFile self.cmap = plt.cm.prism # creating the root window of 720 x 980 self.window = window self.window.geometry("720x980") self.window.title("Analysis Visualization") # title of the screen # Placing the widgets mainlabel = Label(window, text="WELCOME!!") mainlabel.config(font=("comic sans ms", 44, "bold")) mainlabel.place(relx=0.05, rely=0.05, relwidth=0.9) labelTop = Label(window, text="Choose Company") labelTop.config(font=("fixedsys", 14)) labelTop.place(relx=0.05, rely=0.45, relwidth=0.9) self.combo = ttk.Combobox(window, values=companies) self.combo.place(relx=0.1, rely=0.5, height=50, relwidth=0.7) button = Button(window, text="OK", command=self.open_new) button.place(relx=0.8, rely=0.5, height=50, relwidth=0.05) # Function to extract the data from excel sheet def data_extractor(self, compName): data = self.dataFile.parse( compName) # reading the relevant sheet of company categories = {} map_cat = {} self.cat_names = [] self.cat_scores = [] ref_no = data["WBS"].tolist( ) # level number to differentiate cat and sub-cat scores = data["Score"].tolist( ) # scores given (read as decimal values) areas = data["Area of Assessment"].tolist() # area of assessment for id in range(len(ref_no)): # loop through to get the data wbs_n = ref_no[id] floored = np.floor(wbs_n) if floored == wbs_n: categories[wbs_n] = { } # for each category, identify sub-cat and their score map_cat[areas[id]] = wbs_n # mapping dict for later purposes self.cat_names.append(areas[id]) self.cat_scores.append(scores[id]) else: categories[floored][areas[id]] = scores[id] return categories, map_cat # Function to open a new window when the company name is selected def open_new(self): self.window2 = Toplevel(height=980, width=720) #print(self.combo.current()) if self.combo.current( ) < 0: # if None is selected in the drop down menu, -1 will be returned. Handling exceptions self.window2.destroy() else: self.compName = self.companies[ self.combo.current()] # company name selected self.window2.title( self.compName ) # title of new window opened set to company name selected self.plot() # plot pie chart for main categories # Function to plot the main category split def plot(self): _, _ = self.data_extractor( self.compName ) # calling this function assigns cat names and scores explode = np.ones(len(self.cat_names)) * 0.1 # variables for pie chart colors = self.cmap(np.linspace(0, 1, len( self.cat_names))) # variables for pie chart self.fig = Figure(figsize=(5, 5)) # set figure size ax = self.fig.add_subplot(111) # https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.pie.html wedges, plt_labels, _ = ax.pie(self.cat_scores, explode=explode, colors=colors, center=(0, 20), textprops=dict(weight="bold"), wedgeprops=dict(width=0.5, linewidth=4), startangle=-40, autopct='%1.1f%%', labels=self.cat_names, pctdistance=0.7, labeldistance=1.1) ax.axis('equal') ax.set_title(self.compName + " - Main Categories", fontsize=18, weight="bold", pad=1.0, color='darkred') self.canvas = FigureCanvasTkAgg( self.fig, master=self.window2) # initiaitng the canvas on the opened window2 self.canvas.get_tk_widget().place(relx=0.05, rely=0.15) self.canvas.draw() # drawing the plot on the canvas self.canvas._tkcanvas.pack( padx=10, pady=10, fill=BOTH, expand=True) # placing the canvas on window2 self.toolbar = NavigationToolbar2Tk( self.canvas, self.window2 ) # navigational toolbar to save images and move it around self.toolbar.update() self.exit = Button( self.window2, text="Exit", command=self.window2.destroy ) # exit button. When pressed the opened window2 will close self.exit.place(relx=0.9, rely=0.945, height=30, relwidth=0.08) self.make_picker( wedges ) # call a function to check whether any event happens on the shown graph # Funtion to return the plot from sub-cat to main cat plot def returnplot(self): self.clearPlotPage() self.plot() # Function to clear the current canvas. may occur a glitch due to the lag in plotting next plot def clearPlotPage(self): self.canvas._tkcanvas.destroy() self.toolbar.destroy() # Function to plot the sub categories of selected category def make_picker(self, wedges): def plot_subplot(area): categ, mapping = self.data_extractor(self.compName) scores = list( categ[mapping[area]].values()) # scores of sub categories subcat = list( categ[mapping[area]].keys()) # lables of sub catgories explode = np.ones(len(subcat)) * 0.1 colors = self.cmap(np.linspace(0, 1, len(subcat))) self.fig = Figure(figsize=(5, 5)) ax = self.fig.add_subplot(111) wedges, plt_labels, _ = ax.pie(scores, explode=explode, colors=colors, wedgeprops=dict(linewidth=4), autopct='%1.1f%%', labels=subcat, textprops=dict(weight="bold", fontsize=9), pctdistance=0.7, labeldistance=0.94) ax.axis('equal') ax.set_title("{}: {} Sub Categories".format(self.compName, area), fontsize=14, weight="bold", pad=1.0, color='navy') self.canvas = FigureCanvasTkAgg( self.fig, master=self.window2 ) # drawing the new figure on the opened window2 self.canvas.get_tk_widget().place(relx=0.05, rely=0.15) self.canvas._tkcanvas.pack(padx=10, pady=10, fill=BOTH, expand=True) self.canvas.draw() self.toolbar = NavigationToolbar2Tk(self.canvas, self.window2) self.toolbar.update() self.back = Button(self.window2, text="Back", command=self.returnplot ) # back button to go back to main catgory site self.back.place(relx=0.9, rely=0.94, height=20, relwidth=0.08) def on_pick(event): self.clearPlotPage() # clears current canvas wedge = event.artist # get the wedge of the pie chart where a click happens label = wedge.get_label() # get the label of the wedge plot_subplot( label ) # pass that label to plot the sub-catgories of that category selected for wedge in wedges: wedge.set_picker(True) self.fig.canvas.mpl_connect('pick_event', on_pick)
class App(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.running = False self.ani = None self.traces = dict() self.parent = parent #self.parent.grid_rowconfigure(0, weight=1) #self.parent.grid_columnconfigure(0, weight=1) self.parent.geometry("1360x750") self.frame = ttk.Frame(self.parent) #self.frame.grid(row=0, column=0, padx=40, pady=40) self.frame.pack(side=tk.TOP, anchor='nw', padx=40, pady=40) self.frame2 = ttk.Frame(self.parent) self.frame2.pack(side=tk.TOP, anchor='w', padx=40) self.frame3 = ttk.Frame(self.parent) self.frame3.pack(side=tk.TOP, anchor='w', padx=40) self.queue = Queue.Queue() self.thread = SerialThread(self.queue, 100) self.thread.start() self.widgets() def get_data(self): y = list(self.thread.deque) y += [0] * (self.thread.deque.maxlen - len(y)) x = xrange(len(y)) return x, y def savefile(self): try: path = self.savedirinput.get() os.lstat(path) self.savedata(path, 5) except OSError: file = tkFileDialog.asksaveasfilename(initialdir="/home/robert", title="Select file") self.savedirinput['text'] = file self.savedata(file, 5) print(file) def savedata(self, filename, savetime): now = time.time() while (time.time() - now) < savetime: with open(filename, 'w') as f: f.write( str(time.time() - now) + ',' + self.thread.queue.get() + '\n') f.flush() def widgets(self): self.avgtxt = tk.Label(self.frame2, text="", font=LARGE_FONT, anchor='w') self.stdtxt = tk.Label(self.frame2, text="", font=LARGE_FONT, anchor='w') self.instxt = tk.Label(self.frame2, text="", font=LARGE_FONT, anchor='w') self.exitbutton = tk.Button(self.frame, text='Close', command=lambda: self.closeall(), width=10, height=3) self.dequescale = tk.Entry(self.frame) self.dequescalebutton = tk.Button( self.frame, text="Filter Size:", command=lambda: self.changedequesize()) self.savebutton = tk.Button(self.frame3, text="Save", command=lambda: self.savefile()) self.savedirinput = tk.Entry(self.frame3) self.exitbutton.pack(side=tk.LEFT, padx=10, anchor='nw') self.dequescalebutton.pack(side=tk.LEFT) self.dequescale.pack(side=tk.LEFT) self.instxt.pack(side=tk.TOP, anchor='w') self.avgtxt.pack(side=tk.TOP, anchor='w') self.stdtxt.pack(side=tk.TOP, anchor='w') self.savebutton.pack(side=tk.LEFT) self.savedirinput.pack(side=tk.LEFT) # self.exitbutton.grid(row=0, column=0, columnspan=2, sticky='w') # self.instxt.grid(row=1, column=0, sticky='w', columnspan=4) # self.avgtxt.grid(row=2, column=0, sticky='w', columnspan=3) # self.stdtxt.grid(row=3, column=0, sticky='w', columnspan=3) # self.dequescale.grid(row=0, column=2, sticky='W', columnspan=1) # self.dequescalebutton.grid(row=0, column=1, sticky='E') # self.savebutton.grid(row=4, column=0, sticky='W') # self.savedirinput.grid(row=4, column=1, columnspan=2, sticky='W') #self.graph() self.process_serial() def graph(self): self.fig = Figure(dpi=100) self.subplt = self.fig.add_subplot(111) self.line, = self.subplt.plot([], []) self.canvas = FigureCanvasTkAgg(self.fig, master=self.parent) #self.canvas.get_tk_widget().grid(row=3, column=1) self.canvas.get_tk_widget().pack(side=tk.RIGHT) self.canvas.show() self.process_serial() def animate(self, name, dataset_x, dataset_y): if name in self.traces: self.line.set_data(dataset_x, dataset_y) else: self.traces[name] = True self.line, = self.subplt.plot(dataset_x, dataset_y) self.canvas.draw() def changedequesize(self): try: val = int(self.dequescale.get()) self.thread.deque = deque([], val) except ValueError: pass def closeall(self): self.after_cancel(self.parent) self.parent.destroy() def process_serial(self): while self.queue.qsize(): try: self.instxt["text"] = "Instantaneous: {0:.2f}".format( self.thread.getinstant()) self.avgtxt["text"] = "Average: {0:.2f}".format( self.thread.getaverage()) self.stdtxt["text"] = "Deviation: {0:.2f}".format( self.thread.getstd()) self.queue.get() except Queue.Empty: pass #self.animate("data", *self.get_data()) self.after(10, self.process_serial)