def __init__(self, parent, controller, config, dbvar=None, wd=14, ht=7.5): self.widget_name = "graphframe" self.lines_list = [] self.bars_list = [] self.event_polygon_list = [] self.prime_graph_pack = None self.secondary_graph_pack = None super().__init__(parent, controller, config, dbvar=None) self.my_figure = Figure(figsize=(wd, ht), dpi=85) self.my_legend = self.my_figure.legend() self.axis_prime = self.my_figure.add_subplot(1, 1, 1) # self.axis_prime.set_title("No Query Selected") self.axis_secondary = self.my_figure.add_subplot( 111, sharex=self.axis_prime, frameon=False) self.axis_secondary.xaxis.set_visible(False) self.axis_secondary.yaxis.set_label_position("right") self.axis_secondary.yaxis.tick_right() self.canvas = FigureCanvas(self.my_figure, self) self.canvas.draw() # # self.canvas.manager.toolbar.add_tool('zoom', 'foo') # self.toolbar = NavigationToolbar2TkAgg(self.canvas, self) # self.toolbar.update() self.canvas._tkcanvas.pack()
def initiate_canvas(self): # Add the figure to a Canvas self.Canvas = FigureCanvas(self.figure, self.frame_canvas) self.Canvas.get_tk_widget().configure(background=self.root.color['bg']) self.figure.patch.set_facecolor(self.root.color['bg']) self.Canvas.draw() self.widget = self.Canvas.get_tk_widget() if self.direction == "x": self.widget.grid(row=0, column=0, stick='NSEW') if self.direction == "y": self.widget.grid(row=0, column=1, stick='NSEW')
def __init__( self, master=None, title=None, ): super(NetworkPlotTk, self).__init__(matplotlib_figure=matplotlib.figure.Figure(), ) if master is None: master = tk.Tk() master.withdraw() self.master = master #self.master.protocol("WM_DELETE_WINDOW", self.on_closing) # Create a Toplevel widget, which is a child of GUILoom # and contains plots, self.toplevel = tk.Toplevel(master) self.toplevel.wm_title(title) self.toplevel.protocol("WM_DELETE_WINDOW", self.on_closing) self.plot_idx_scale = None self.plot_idx_entry = None self.plot_idx_entry_var = tk.StringVar() self.plot_idx_entry_var.trace('w', self.plot_idx_entry_change) self.canvas = FigureCanvas(self.figure, master=self.toplevel, resize_callback=self.canvas_resize_callback) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar(self.canvas, self.toplevel) toolbar.update() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def addMainFigure(self) : """ Add main figure area """ self.fig = plt.figure(figsize=(5,4), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.set_title('No data') self.fig.canvas.draw() self.canvas = FigureCanvas(self.fig, self) """ Set up callback from canvas draw events, i.e. pan/zoom """ #self.cid1 = self.fig.canvas.mpl_connect('draw_event', self.updateFromCavas) #self.cid1 = self.fig.canvas.mpl_connect('button_release_event', self.updateFromCavas) #TODO animation 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)
def __init__(self, parent, dim): Frame.__init__(self, parent) self.dim = dim self.figure = pyplot.Figure(figsize=(5.5, 3.2), facecolor=(240 / 255, 240 / 255, 237 / 255)) self.figure.subplots_adjust(left=0.15, bottom=0.2) self.canvas = FigureCanvas(self.figure, master=self) self.canvas.get_tk_widget().pack() self.canvas.get_tk_widget().configure(highlightthickness=0) toolbar = CutDownNavigationToolbar(self.canvas, self) toolbar.pack() if dim == 2: self.axes = self.figure.add_subplot(1, 1, 1) elif dim == 3: self.axes = Axes3D(self.figure) else: raise ValueError("Dimension must be either 2 or 3") self.currentLines = []
def __init__(self, master=None, packedHighSpeed=True): self.maxtraces = 5 self.selChan = 0 Tk.Frame.__init__(self,master) # hack to make work in python2 self.pack() self.figure = Figure(figsize=(15,7), dpi=100, facecolor='white') self.canvas = FigureCanvas(self.figure, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar = NaviationToolbar(self.canvas,self) self.toolbar.update() self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.pauseButton = Tk.Button(self,text="Pause",command=self.pause) self.pauseButton.pack(side=Tk.LEFT) self.playButton = Tk.Button(self,text="Play",command=self.play,state=Tk.DISABLED) self.playButton.pack(side=Tk.LEFT) self.prevButton = Tk.Button(self,text="Previous Trace",command=self.prevTrace,state=Tk.DISABLED) self.prevButton.pack(side=Tk.LEFT) self.nextButton = Tk.Button(self,text="Next Trace",command=self.nextTrace,state=Tk.DISABLED) self.nextButton.pack(side=Tk.LEFT) self.packedHighSpeed = packedHighSpeed self.femb = None self.iTrace = -1 self.traces = [] self.timestamps = [] self.reset()
def drawPlot(self, filename=""): scrolledframe = self.builder.get_object("plot_frame") figure = Figure(figsize=(8, 8), dpi=80) axis = figure.add_subplot(111) x, y = calculateValues(self) axis.plot(x, y) if do_zoom: i = 0 last = y[i] for i, _ in enumerate(y): if y[i] > last: break last = y[i] axis.set_ylim(top=y[i:].max() + abs(y[i:].max() * 0.075), bottom=y[i:].min() - abs(y[i:].min() * 0.075)) else: axis.set_ylim(top=y.max() + abs(y.max() * 0.075), bottom=y.min() - abs(y.min() * 0.075)) if do_lambda: axis.set_xlabel("Wellenlänge in m") else: axis.set_xlabel("Glanzinkel in °") if do_persecond: axis.set_ylabel("Zählrahte in 1/s") else: axis.set_ylabel("Zählrahte in 1/" + str(measure_time) + "s") axis.set_title("Röntgenspektrum") canvas = FigureCanvas(figure, master=scrolledframe) canvas.draw() canvas.get_tk_widget().grid(row=0, column=0, sticky="nsew") if filename != "": figure.savefig(filename)
def __init__(self, root, subplots, title=''): ttk.Frame.__init__(self, root) self.signal_mouse_press = Signal() self.signal_mouse_release = Signal() self._fig = Figure() self._subplots = [] self._canvas = FigureCanvas(self._fig, self) self._canvas.get_tk_widget().pack(expand=tk.YES, fill=tk.BOTH) self._canvas.mpl_connect('button_press_event', self.signal_mouse_press) self._canvas.mpl_connect('button_release_event', self.signal_mouse_release) toolbar = NavigationToolbar2Tk(self._canvas, self) toolbar.update() num_rows = len(subplots) num_columns = max(len(graphs) for graphs in subplots) for i in range(num_rows): for j in range(num_columns): subplot = subplots[i][j] if subplot is not None: index = (i * num_columns) + j + 1 ax = self._fig.add_subplot(num_rows, num_columns, index) subplot.set_axis(ax) self._subplots.append(subplot) self._fig.suptitle(title, fontweight='bold', fontsize=self.DEFAULT_TITLE_SIZE) self._fig.subplots_adjust(hspace=.6, wspace=.3)
def __init__(self, window, tracer): self.window = window self.tracer = tracer # PARAMÈTRES DE LA FENÊTRE : window.title(self.tracer.window_title) if self.tracer.x is not None or self.tracer.y is not None: window.geometry('%+i%+i' % (self.tracer.x, self.tracer.y)) window.geometry('%ix%i' % (self.tracer.w, self.tracer.h)) # DÉFINITION DE L'AGENCEMENT : self.canvas = FigureCanvas(self.tracer.fig, self.window) self.toolbar = TracerToolbar(self.canvas, self.window, self.tracer, self.save_window, self.get_band_n_rate) self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # GESTION DES ÉVÉNEMENTS : self.canvas.mpl_connect('key_press_event', self.on_key) def destroy(*args): self.window.quit() self.canvas._tkcanvas.bind("<Destroy>", destroy) self.canvas.draw()
def __init__(self,master,size,dpi,task): Figure.__init__(self,figsize=(size[0]/dpi,size[1]/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=True,linewidth=0) FigureCanvas(self,master=master) self.master = master self._errors = collections.OrderedDict() self._dirty = True self._task = task self.add_subplot(111,axisbg='w')
def __init__(self,master,size,dpi,data,fold): Figure.__init__(self,figsize=(size[0]/dpi,size[1]/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=True,linewidth=0) FigureCanvas(self,master=master) self.master = master self._dirty = True self._fold = fold self._indices = None self._targets = None self._outputs = None self._outshape = data.Yshape self._outrange = data.Yrange self.add_subplot(111,axisbg='w')
def __init__(self,master,size,dpi,get_matrices_fn,percentiles,transposed,ranges=None,title=""): Figure.__init__(self,figsize=(size[0]/dpi,size[1]/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=True,linewidth=0) FigureCanvas(self,master=master) self.master = master self._dirty = True self._get_matrices_fn = get_matrices_fn self._P = [] self._t = percentiles self._ranges = ranges self._title = title self._transposed = transposed self.add_subplot(111,axisbg='w')
def __init__(self, controller): """SuperSID Viewer using Tkinter GUI for standalone and client. Creation of the Frame with menu and graph display using matplotlib """ matplotlib.use('TkAgg') self.version = "1.4 20170920 (tk)" self.controller = controller # previously referred as 'parent' self.tk_root = tk.Tk() self.tk_root.title("supersid @ " + self.controller.config['site_name']) # All Menus creation menubar = tk.Menu(self.tk_root) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="Save Raw buffers", command=lambda: self.save_file('r'),underline=5,accelerator="Ctrl+R") filemenu.add_command(label="Save Filtered buffers", command=lambda: self.save_file('f'),underline=5,accelerator="Ctrl+F") filemenu.add_command(label="Save Extended raw buffers", command=lambda: self.save_file('e'),underline=5,accelerator="Ctrl+E") filemenu.add_command(label="Save filtered as ...", command=lambda: self.save_file('s'),underline=5,accelerator="Ctrl+S") filemenu.add_separator() filemenu.add_command(label="Exit", command=lambda : self.close(force_close=False)) # ,underline=1,accelerator="Ctrl+X") self.tk_root.bind_all("<Control-r>", self.save_file) self.tk_root.bind_all("<Control-f>", self.save_file) self.tk_root.bind_all("<Control-e>", self.save_file) self.tk_root.bind_all("<Control-s>", self.save_file) self.tk_root.protocol("WM_DELETE_WINDOW", lambda : self.close(False)) # user click on the [X] to close the window menubar.add_cascade(label="File", menu=filemenu) helpmenu = tk.Menu(menubar, tearoff=0) helpmenu.add_command(label="About...", command=self.on_about) menubar.add_cascade(label="Help", menu=helpmenu) self.tk_root.config(menu=menubar) # FigureCanvas self.psd_figure = Figure(facecolor='beige') self.canvas = FigureCanvas(self.psd_figure, master=self.tk_root) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.tk_root) self.toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.axes = self.psd_figure.add_subplot(111) self.axes.hold(False) # StatusBar self.statusbar_txt = tk.StringVar() self.label=tk.Label(self.tk_root, bd=1, relief=tk.SUNKEN, anchor=tk.W, textvariable=self.statusbar_txt, font=('arial',12,'normal')) self.statusbar_txt.set('Initialization...') self.label.pack(fill=tk.X)
def __init__(self,master,size,dpi,model,featshape,direction='input'): Figure.__init__(self,figsize=(size[0]/dpi,size[1]/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=True,linewidth=0) FigureCanvas(self,master=master) self.master = master self._dirty = True self._model = model self._feat = None self._featrange = None self._featshape = featshape self._direction = direction self._sorted = True self._update_count = 0 self._ordering = None self.add_subplot(111,axisbg='w')
def __init__(self, master): self.amp_started = False ttk.Frame.__init__(self, master) self.master.title('Mushu') self.pack() self.available_amps = libmushu.get_available_amps() frame = tk.Frame(self) frame.pack(fill=tk.BOTH, expand=1) self.label1 = ttk.Label(frame, text='Select Amplifier') self.label1.grid(column=0, row=0, sticky='we') self.amp_combobox = ttk.Combobox( frame, values=[str(i) for i in self.available_amps]) self.amp_combobox.grid(column=0, row=1, sticky='we') self.amp_combobox.bind("<<ComboboxSelected>>", self.on_amplifier_selected) self.label2 = ttk.Label(frame, text='Select Configuration Preset') self.label2.grid(column=1, row=0, sticky='we') self.config_combobox = ttk.Combobox(frame) self.config_combobox.grid(column=1, row=1, sticky='we') self.config_combobox.bind("<<ComboboxSelected>>", self.onComboboxSelected) self.label3 = ttk.Label(frame, text='Start/Stop Amplifier') self.label3.grid(column=2, row=0, sticky='we') self.start_stop_button = ttk.Button( frame, text='Start', command=self.onStartStopButtonClicked) self.start_stop_button.grid(column=2, row=1, sticky='we') # set up the figure fig = Figure() self.canvas = FigureCanvas(fig, master=self.master) self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.canvas.show() self.axis = fig.add_subplot(111) # self.PAST_POINTS = 256 self.PAST_POINTS = 5000 * 3 self.SCALE = 30000 self.channels = [] self.n_channels = 0 self.init_plot() self.master.after_idle(self.visualizer)
def __init__(self, parent, width=8, height=8, dpi=100, **kwargs): super().__init__(parent) fig = Figure(dpi=dpi, **kwargs) self.image = FigureCanvas(fig, master=self) self.image._tkcanvas.pack(expand=1, fill=tkinter.BOTH) #self.toolbar = NavigationToolbar2TkAgg(self.image, self) #self.toolbar.update() #self.toolbar.pack(expand=0) self.axes = fig.add_subplot(111) self.fig = fig # We want the axes cleared every time plot() is called self.axes.hold(False)
def __init__(self, master=None): self.frame = tkinter.Frame(master) self.frame.pack(padx=15, pady=15) self.fig = matplotlib.figure.Figure(figsize=(6, 4), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.plot(np.linspace(0, 4), np.sin(np.linspace(0, 4))) self.canvas = FigureCanvas(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) self.mpl_toolbar = NavigationToolbar(self.canvas, master) self.mpl_toolbar.update() self.canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def __init__(self, waveforms, metadata, master=None): Tk.Frame.__init__(self, master) # hack to make work in python2 self.pack() self.figure = Figure(figsize=(8, 8), dpi=100) self.axs = [] for iPlot in range(16): self.axs.append(self.figure.add_subplot(4, 4, iPlot + 1)) self.canvas = FigureCanvas(self.figure, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar = NaviationToolbar(self.canvas, self) self.toolbar.update() self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.draw_fft(waveforms, metadata)
def __init__(self,master,size,dpi,layer,xaxis=True): Figure.__init__(self,figsize=(size[0]/dpi,size[1]/dpi),dpi=dpi,facecolor='w',edgecolor='b',frameon=True,linewidth=0) FigureCanvas(self,master=master) self.master = master self.dirty = True self.layer = layer self.xaxis = xaxis self._indices = None self._fold = 'train' self._H = None self._S = None self._timerange = None left = 0.08; width = 0.89-left #left = 0.016; width = 0.89-left bottom = 0.12; height=0.82-bottom rect_plot = [left,bottom,width,height] rect_hist = [left+width+.005,bottom,1-.005-width-left,height] self.plot = self.add_axes(rect_plot,axisbg='w') self.hist = self.add_axes(rect_hist,axisbg='w')
def show_clipped_image(self): # Display the clipped image if self.display.winfo_exists(): self.display.grid_forget() self.display.destroy() self.display = ttk.Frame(self) self.display.grid(row=0, column=2, columnspan=4, rowspan=3, sticky='nsew') frame = self.display fp = self.msfile self.fig = plt.Figure(figsize=(8, 4), dpi=100) self.ax = self.fig.add_subplot(111) self.canvas_preview = FigureCanvas(self.fig, frame) fp = 'OutputImages/' + self.outname.get() + '.tif' self.dataset = gdal.Open(fp) self.band = self.dataset.GetRasterBand(1) self.geotransform = self.dataset.GetGeoTransform() self.arr = self.band.ReadAsArray() self.ax.imshow(self.arr, cmap='terrain') self.ax.axis('equal') self.ax.set(title="", xticks=[], yticks=[]) self.ax.spines["top"].set_visible(False) self.ax.spines["right"].set_visible(False) self.ax.spines["left"].set_visible(False) self.ax.spines["bottom"].set_visible(False) self.canvas_preview.draw() self.fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) #self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand = 1) self.toolbar = NavigationToolbar2Tk(self.canvas_preview, frame) self.toolbar.update() self.canvas_preview.get_tk_widget().pack(side='top', fill='both', expand=1)
def __init__(self, chatbot_name, username, init_emotional_state, init_emotional_history): # initialise variables self.chatbot_name = chatbot_name self.username = username self.user_input = None # initialize all ui elements self.dgm = DiagramManager(init_emotional_state, init_emotional_history) self.root = tk.Tk() self.menubar = tk.Menu() self.file_menu = tk.Menu(tearoff=0) self.debug_menu = tk.Menu(tearoff=0) self.load_menu = tk.Menu(tearoff=0) self.response_menu = tk.Menu(tearoff=0) self.chat_out = tk.Text(self.root, width=40, state="disabled") self.chat_in = tk.Entry(self.root) self.log = tk.Text(self.root, width=40, state="disabled") self.info_label = tk.Label( self.root, text="EIKA v.0.0.1, Marcel Müller, FH Dortmund ") self.send_button = tk.Button( self.root, text="Send", command=lambda: self.forward_user_intent( intent="get_response", user_input=self.chat_in.get())) self.diagram_frame = tk.Frame(self.root) self.diagram_canvas = FigureCanvas(self.dgm.get_diagrams(), master=self.diagram_frame) self.chat_in.bind( sequence='<Return>', func=lambda event: self.forward_user_intent( intent="get_response", user_input=self.chat_in.get())) # create frame and menu self.create_frame(self.chatbot_name) self.pack_widgets() # set subscriber list (implements observer pattern) self.controller = None self.subscribers = set()
def __init__(self, infilename, sampleMax=None, fullADCRange=False, master=None): Tk.Frame.__init__(self, master) # hack to make work in python2 self.pack() self.figure = Figure(figsize=(8, 8), dpi=100) self.axs = [] for iPlot in range(16): self.axs.append(self.figure.add_subplot(4, 4, iPlot + 1)) self.canvas = FigureCanvas(self.figure, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar = NaviationToolbar(self.canvas, self) self.toolbar.update() self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.draw_trace(infilename, sampleMax=sampleMax, fullADCRange=fullADCRange)
def cb2(): L = 10 # Breite der Skala def cs1(val): global ua ua = cs1.get() # Obergrenze für alpha in der Gamma Verteilung ct1.delete('1.0', tk.END) ct1.insert(tk.END, ua) cb2plot() def cs2(val): global ub ub = cs2.get() #Obergrenze für beta in der Gamma Verteilung ct2.delete('1.0', tk.END) ct2.insert(tk.END, ub) cb2plot() def cs3(val): #global Alpha Alpha = cs3.get() ct3.delete('1.0', tk.END) ct3.insert(tk.END, Alpha) cb2plot() def cs4(val): #global Beta Beta = cs4.get() ct4.delete('1.0', tk.END) ct4.insert(tk.END, Beta) cb2plot() def cs5(val): #global Lambda Lambda = cs4.get() ct5.delete('1.0', tk.END) ct5.insert(tk.END, Lambda) cb2plot() # Definieren der Wahrscheinlichkeitsfunktionen def Poisson(k, mu): P = ss.poisson.pmf(k, mu) return P def Gamma(p, al, bet): G = ss.gamma.pdf(p, al) * np.exp(-(bet - 1) * p) * bet**al return G # Bestimmen der Aposteriori-Funktion def Posteriori(x): a = np.arange(0, 100000) Int = integrate.simps(Poisson(a, Lambda) * Gamma(a, Alpha, Beta)) Post = 1 / Int * Poisson(x, Lambda) * Gamma(x, Alpha, Beta) return Post def Maxposteriori(): # Bestimmen des Maximums der Aposteriori global MaxX global MaxY global limit MaxX = 0 MaxY = Posteriori(0) for i in np.arange(0, L + 1): TestY = Posteriori(i) if TestY >= MaxY: MaxX = i MaxY = TestY else: break # Definieren des Wertes, ab dem drei Punkte gefittet werden if MaxX == 0: StartX = 1 elif MaxX == 1: StartX = 1 else: StartX = MaxX - 1 # ein paar Nebensächlichkeiten i = 0 limit = MaxY / 100 # maximaler zugelassener Abstand zwischen Fit und Aposteriori List = [] List2 = [] """ Bestimmen aller Parameter-Kombinationen für Gamma, die auf mindestens zwei von drei ausgewählten Punkten identisch (+/- Toleranz) mit der Aposteriori ist Warnung einfügen Mit eingabe parameter bestimmung evtl. """ while i <= 3: xValue = StartX + i Checker = Posteriori(xValue) if i == 0: for a in np.arange(0.1, ua, 0.1): # Obergrenze alpha posteriori for b in np.arange(0.1, ub, 0.1): #Obergrenze beta posteriori if abs(Gamma(xValue, a, b) - Checker) < limit: List.append((a, b)) else: for item in List: a = item[0] b = item[1] if abs(Gamma(xValue, a, b) - Checker) < i * limit: List2.append(item) i += 1 """ Auswählen der Parameter-Kombination, die die meisten Punkte der Aposteriori schneidet (+/- Toleranz) """ Counter = {} for item in List2: Counter[item] = Counter.get(item, 0) + 1 return Counter def sort(x): Counter = Maxposteriori() return Counter[x] def BestL(): Counter = Maxposteriori() BestList = sorted(Counter, key=sort, reverse=1) for item in BestList: ConjMax = 0 for i in np.arange(MaxX - 1, MaxX + 1, 0.1): TestY = Gamma(i, item[0], item[1]) if TestY >= ConjMax: ConjMax = TestY if abs(ConjMax - MaxY) > limit: BestList.remove(item) Best = BestList[0] return Best def cb2plot(): # Globale Variablen definieren global Lambda global Beta global Alpha global ua global ub Lambda = cs4.get() Beta = cs4.get() Alpha = cs3.get() ua = cs1.get() ub = cs2.get() #Aufrufen der Funktionen Best = BestL() # Plot in der Canvas des aw plt.cla( ) # Löscht die aktuellen Plots aus dem Fenster, lässt dieses aber noch offen ay = fig.add_subplot(111) I = np.linspace(0, L, 10 * L + 1) X = Poisson(I, Lambda) Y = Gamma(I, Best[0], Best[1]) Z = Posteriori(I) ay.plot(I, X, 'b-', label='priori') ay.plot(I, Y, 'g-', label=Best) ay.plot(I, Z, 'r-', label='posteriori') ay.set_xlabel( 'Erfolgswahrscheinlich p') # Axenbeschriftung in x Richtung ay.set_ylabel( 'Wahrscheinlichkeitsdichte') # Axenbeschriftung in y Richtung ay.legend(loc='best') ccb2.draw() cb2w = tk.Tk() # Definition eines Auswahlfensters cb2w.title("Gamma-Poisson Verteilung") # Beschriftung des Fensters cb2w.geometry("1200x600") # Anpassung der Größe # Canvas, Felds für den Plot fig = plt.figure(figsize=(10, 5)) ccb2 = FigureCanvas(fig, master=cb2w) L1 = tk.Label(cb2w, text="Obere Grenze für Alpha : ") L2 = tk.Label(cb2w, text="Obere Grenze für Beta: ") L3 = tk.Label(cb2w, text="Alpha: ") L4 = tk.Label(cb2w, text="Beta: ") L5 = tk.Label(cb2w, text="Lambda: ") # Eingabeslider cs1 = tk.Scale(master=cb2w, from_=0, to=50, orient=HORIZONTAL, command=cs1) # Obere Grenze Alpha cs2 = tk.Scale(master=cb2w, from_=0, to=50, orient=HORIZONTAL, command=cs2) # Obere Grenze Beta cs3 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs3) # Alpha cs4 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs4) # Beta cs5 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs5) # Lambda command #--> cs1-5 neu definieren #Definition von Startwerten cs1.set(5) cs2.set(5) cs3.set(1) cs4.set(1) cs5.set(4) # Textfelder ct1 = tk.Text(master=cb2w, height=1, width=10) ct2 = tk.Text(master=cb2w, height=1, width=10) ct3 = tk.Text(master=cb2w, height=1, width=10) ct4 = tk.Text(master=cb2w, height=1, width=10) ct5 = tk.Text(master=cb2w, height=1, width=10) ccb2._tkcanvas.grid(row=0, column=0, columnspan=4) # Zuweisung der Labels durch .grid() L1.grid(row=2, column=0) L2.grid(row=3, column=0) L3.grid(row=4, column=0) L4.grid(row=5, column=0) L5.grid(row=6, column=0) #Zuweisung der Scale durch .grid() cs1.grid(row=2, column=1) cs2.grid(row=3, column=1) cs3.grid(row=4, column=1) cs4.grid(row=5, column=1) cs5.grid(row=6, column=1) #Zuweisung der Scale durch .grid() ct1.grid(row=2, column=2) ct2.grid(row=3, column=2) ct3.grid(row=4, column=2) ct4.grid(row=5, column=2) ct5.grid(row=6, column=2) #Anfangsplot cb2plot()
def cb1(): def binCo(n, k): r = 1 j = 1 if k > (n / 2): while j <= n - k: r = r * (k + j) j = j + 1 #j+=1 x = r / math.factorial(n - k) else: while j <= k: r = r * ((n - k) + j) j = j + 1 # j+=1 x = r / math.factorial(k) return x def BinDist(p, n, k): P = binCo(n, k) * p**k * (1 - p)**(n - k) return P # Verschiedene apriori Verteilungen def BetaDist(x, p, q): Beta = ss.beta.pdf(x, p, q) return Beta def NorDist(x, m, s): v = -0.5 * ((x - m) / s)**2 N = 1 / (s * np.sqrt(2 * np.pi)) * np.exp(v) return N def ExpDist(x, L): v = -L * x E = L * np.exp(v) return E # Definition eines numerische Integrals def numInt(f, a, b, N): x = np.linspace(a + (b - a) / (2 * N), b - (b - a) / (2 * N), N) fx = f(x) area = np.sum(fx) * (b - a) / N return area # Berechnung der apriori Verteilung (fürs plotten) def konj(alpha1, beta1, HeadCount1, ThrowCount1): alphapost1 = alpha1 + HeadCount1 betapost1 = beta1 + ThrowCount1 - HeadCount return (alphapost1, betapost1) def preDistribution(x, prDist): u = sp.Symbol('u') if prDist == 1: X = BetaDist(x, alpha, beta) elif prDist == 2: X = NorDist(x, mu, sigma) elif prDist == 3: X = ExpDist(x, Lambda) return X # Berechnung der aposteriori Verteilung def Distribution(x, prDist): if prDist == 1: X = BetaDist(x, alphapost, betapost) return X def wplot(): # Globale Variablen definieren global priori global alphapost global betapost z2 = 0.5 #Berechnung der posteriori Größen alphapost, betapost = konj(alpha, beta, HeadCount, ThrowCount) # Plot in der Canvas des aw plt.cla() ax = fig.add_subplot(111) x = np.linspace(0, 1, num=200) y = [preDistribution(i, 1) for i in x] z = [Distribution(i, 1) for i in x] ax.plot(x, y, 'b-', label='priori') ax.plot(x, z, 'r-', label='posteriori') ax.plot(z2, 0, 'g-', label='Median') ax.set_xlabel( 'Erfolgswahrscheinlich p') # Axenbeschriftung in x Richtung ax.set_ylabel( 'Wahrscheinlichkeitsdichte') # Axenbeschriftung in y Richtung ax.legend(loc='best') canvas.draw() def cs1(val): global ThrowCount global s1max s1max = s1.get() ThrowCount = s1max t1.delete('1.0', tk.END) t1.insert(tk.END, ThrowCount) wplot() def cs2(val): global HeadCount HeadCount = s2.get() t2.delete('1.0', tk.END) t2.insert(tk.END, HeadCount) wplot() def cs3(val): global alpha alpha = s3.get() t3.delete('1.0', tk.END) t3.insert(tk.END, alpha) wplot() def cs4(val): global beta beta = s4.get() t4.delete('1.0', tk.END) t4.insert(tk.END, beta) wplot() aw = tk.Tk() # Definition eines Auswahlfensters aw.title("Beta-Verteilung") # Beschriftung des Fensters aw.geometry("1200x600") # Anpassung der Größe # Canvas, Felds für den Plot fig = plt.figure(figsize=(10, 5)) canvas = FigureCanvas(fig, master=aw) L1 = tk.Label(aw, text="Anzahl : ") L2 = tk.Label(aw, text="Anzahl eingetretenes Ereignis: ") L3 = tk.Label(aw, text="Alpha: ") L4 = tk.Label(aw, text="Beta: ") # Eingabeslider s1 = tk.Scale(master=aw, from_=0, to=1000, orient=HORIZONTAL, command=cs1) # Anzahl an Ereignissen s2 = tk.Scale(master=aw, from_=0, to=1000, orient=HORIZONTAL, command=cs2) # Anzahl an eigetretenen Ereignissen s3 = tk.Scale(master=aw, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs3) # Alpha s4 = tk.Scale(master=aw, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs4) # Beta #Definition von Startwerten s1.set(500) s2.set(250) s3.set(0.5) s4.set(0.5) # Textfelder t1 = tk.Text(master=aw, height=1, width=10) t2 = tk.Text(master=aw, height=1, width=10) t3 = tk.Text(master=aw, height=1, width=10) t4 = tk.Text(master=aw, height=1, width=10) canvas._tkcanvas.grid(row=0, column=0, columnspan=4) # Zuweisung der Labels durch .grid() L1.grid(row=2, column=0) L2.grid(row=3, column=0) L3.grid(row=4, column=0) L4.grid(row=5, column=0) #Zuweisung der Scale durch .grid() s1.grid(row=2, column=1) s2.grid(row=3, column=1) s3.grid(row=4, column=1) s4.grid(row=5, column=1) #Zuweisung der Scale durch .grid() t1.grid(row=2, column=2) t2.grid(row=3, column=2) t3.grid(row=4, column=2) t4.grid(row=5, column=2) #Anfangsplot wplot()
def plot_gmpe_group_bias( params ): from numpy import log, loadtxt, array, where from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas freqs = [0.25, 0.5, 1.0, 2.0, 3.0, 5.0] distances = [10, 15, 20, 25, 30] try: # create data structure to hold bias results bias = {} for dist in distances: bias[dist] = [] for freq in freqs: bias[freq] = [] # loop through all the directories for d in os.listdir( params['root_dir'] ): cwd = os.path.join( params['root_dir'], d ) if os.path.isdir( cwd ): for freq in freqs: filename = os.path.join(cwd, 'gmrotD50_%05.2fHz_plot.dat' % freq) data = loadtxt(filename, delimiter=',' ) gmpe_mid = (data[:,2] + data[:,3]) / 2 log_bias = log(data[:,1] / gmpe_mid) bias[freq].append(log_bias) for dist in distances: ind = where(data[:,0] == dist + 0.5) gmpe_mid = (data[ind,2] + data[ind,3]) / 2 log_bias = log(data[ind,1] / gmpe_mid) bias[dist].append(log_bias) # make figure for key in bias.keys(): if key in freqs: # print key fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.set_title( 'log(sim/gmpe) vs. distance @ %s Hz' % key ) ax.set_xlabel('Distance (km)') ax.set_ylabel('log(sim/gmpe)') # plot horizontal line at 0 ax.axhline(y=0, color='black') # plot bias and error bars b = array(bias[key]) avgb = b.mean(axis=0) minb = b.min(axis=0) maxb = b.max(axis=0) ylower = avgb - minb yupper = maxb - avgb ax.errorbar(data[:,0], avgb, yerr=[ylower,yupper], fmt='o', ecolor='g', capthick=2) fig.savefig( os.path.join(params['root_dir'], 'dist_bias_%shz.pdf' % key ) ) if key in distances: fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.set_title('log(sim/gmpe) vs. period @ %s km' % key ) ax.set_xlabel('Period (s)') ax.set_ylabel('log(sim/gmpe)') # plot horizontal line at 0 ax.axhline(y=0, color='black') b = array(bias[key]) b = b.reshape([b.size/len(freqs),len(freqs)]) # plot bias and error bars avgb = b.mean(axis=0) minb = b.min(axis=0) maxb = b.max(axis=0) ylower = avgb - minb yupper = maxb - avgb ax.errorbar(1./array(freqs), avgb, yerr=[ylower,yupper], fmt='o', ecolor='g', capthick=2) fig.savefig(os.path.join(params['root_dir'], 'dist_freq_%skm.pdf' % key) ) except Exception as e: print 'exception: %s' % str(e)
def __plot_gmpe_individual( name ): try: from numpy import loadtxt, exp from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas fig = Figure() canvas = FigureCanvas(fig) data = loadtxt(name, delimiter=',') # read data bin_edges = data[:,0] med_sim = data[:,1] min_med_gmpe = data[:,2] max_med_gmpe = data[:,3] med_sig_gmpe = data[:,4] ax = fig.add_subplot(111) ax.fill_between(bin_edges, min_med_gmpe, max_med_gmpe, color='gray', alpha=0.4) ax.loglog(bin_edges, med_sim, 'b') ax.loglog(bin_edges, max_med_gmpe*exp(med_sig_gmpe), '--k') ax.loglog(bin_edges, min_med_gmpe*exp(-med_sig_gmpe), '--k') ax.set_xlim([1.0,30.0]) ax.set_xlabel( r'$R_{rup} (km) $' ) ax.set_ylabel( 'SA (g)' ) basename = name[:-4] # strip off file extension fig.savefig( basename + '.pdf' ) except Exception as e: print 'Unable to launch job due to error: %s' % e return False return True def __prepare_parameters( self, cwd ): from numpy import fromfile par = {} # read default parameters try: with open(os.path.join(self.params['root_dir'], 'params.txt'), 'r') as file: temp = file.readlines() for line in temp: line = line.split() if line: key = line[0] val = line[1] par[key] = val except IOError: print '\tERROR: unable to read params.txt file.' return False # try reading the magnitude try: mw = self.__read_magnitude( cwd ) par.update(mw) except IOError: print '\tERROR: unable to find magnitude file.' return False # try getting the extent of the fault try: extent = self.__get_fault_extent( cwd, par ) par.update(extent) except IOError: print 'unable to determine fault extent. skipping model...' return False # copy necessary files try: # temporary until i get fortran codes implemented shutil.copy( os.path.join(self.params['script_dir'], 'gmpe_calc.m'), cwd ) shutil.copy( os.path.join(self.params['script_dir'], 'ASK_2014_nga.m'), cwd ) shutil.copy( os.path.join(self.params['script_dir'], 'BSSA_2014_nga.m'), cwd ) shutil.copy( os.path.join(self.params['script_dir'], 'CB_2014_nga.m'), cwd ) shutil.copy( os.path.join(self.params['script_dir'], 'CY_2014_nga.m'), cwd ) except IOError: print 'unable to copy necessary files.' return False # now write the parameters file # when i get fortran routines, no reason to write file anymore try: with open(os.path.join(cwd, 'params.txt'), 'w') as file: for k,v in par.iteritems(): file.write(k + ' ' + str(v) + '\n') except IOError: print 'unable to write to params.txt file' return False # made it through the gauntlet return True def __read_magnitude( self, cwd ): import os from numpy import fromfile, where # try finding that file anywhere in the model directory for root, dirs, files in os.walk( cwd ): for name in files: if name == 'mw': mw = fromfile(os.path.join(root, name),'f')[-1] return { 'mw' : mw } raise IOError def __get_fault_extent( self, cwd, par ): import os from numpy import fromfile, where, floor nx = int(par['fltnx']) nz = int(par['fltnz']) psv = fromfile( os.path.join(cwd, 'out/psv'), 'f' ).reshape([nz,nx]) y,x = where( psv > 1.0 ) # returns inds where condition is true strtx = x.min() endx = x.max() nflt = floor( (endx - strtx) / 2 ) if nflt < 0: print 'negative fault length, something is wrong.' raise ValueError return { 'strtx' : strtx, 'nflt' : nflt }
self._emit('select', self.selected) else: self.selected = None self.fig.canvas.draw_idle() if __name__ == '__main__': ncf = netcdf_file('KTLX_20100510_22Z.nc') data = ncf.variables['Reflectivity'] lats = ncf.variables['lat'] lons = ncf.variables['lon'] stormcells = storm_loader('polygons.shp') win = tk.Tk() fig = Figure() canvas = FigureCanvas(fig, master=win) ax = fig.add_subplot(1, 1, 1) raddisp = RadarDisplay(ax, lats, lons) raddisp.update_display(data[0]) fig.colorbar(raddisp.im) polycolls = Stormcells(ax, stormcells) linecoll = Tracks(ax) # Turn on the first frame's polygons polycolls.toggle_polygons(0, True) ax.autoscale(True) ctrl_sys = ControlSys(fig, raddisp, data, polycolls, linecoll, stormcells) win.wm_title("Embedding with Tk") canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
class PageThree(tk.Frame): """Frame showing Data View and chop capabilities """ def __init__(self, parent, controller, **kwargs): tk.Frame.__init__(self, parent) # call class parent """ Initialize data members """ self.DA = DA self.isSafeToUpdate = False self.numViews = 2 self.deactList = list() self.DVconfig = controller.DVconfig """ Create label for frame """ #label = tk.Label(self, text="Data View", font=LARGE_FONT) #label.pack(pady=10,padx=10) """ Create button to go back to other frame """ #button1 = ttk.Button(self, text="Back to Home", # command=lambda: controller.show_frame(StartPage)) #button1.pack() """ Add menu item to load data """ filemenu = controller.filemenu filemenu.insert_command(index=1,label="Load", command=self.load) self.addMainFigure() # Add main figure area to frame self.addDataWindow() # Add widgets for setting data window self.addDataView() # Add widgets for setting data view self.addChop() # Add chop button self.addStat() # Add stat button def addDeactivateList(self, listLike) : """ Keep a list of deactivate-able widgets """ if isinstance(listLike, list) or isinstance(listLike, tuple) : for item in listLike : self.deactList.append(item) else : self.deactList.append(listLike) def deactivateWidgets(self) : for widget in self.deactList : widget.configure(state='disabled') def activateWidgets(self) : if not self.DA.isLoaded : return DataNotLoaded() for widget in self.deactList : widget.configure(state='normal') def addDataView(self) : """ Add widgets that control the view """ self.viewList = list(('No Data','No Data')) """ Add View Widget Sub-Frames """ self.dataViewSubFrameList = list() # list of "subframes" for frameNum in range(0,self.numViews) : subFrame = viewWidgetGroupFrame(self, label="Data View "+str(frameNum)) subFrame.setEventHandler(self.viewChangeTrace) subFrame.pack() self.dataViewSubFrameList.append(subFrame) """ Data View Index Selection """ self.altIdxSel = tk.StringVar(self) self.altIdxSel.set("No data") # default value """ self.altIdxSelW = tk.OptionMenu(self, self.altIdxSel, "No Data" ) self.altIdxSelW.configure(state="disabled") self.altIdxSelW.pack() self.altIdxSel.trace('w', self.viewChangeTrace) # set up event self.addDeactivateList(self.altIdxSelW) """ def addDataWindow(self) : """ Data Window Size Widget """ self.dataWindowSizeWidgetLabel = tk.Label(self, text='View Size') self.dataWindowSizeWidgetLabel.pack() self.dataWindowSizeWidget = tk.Scale(self, from_=1, to=10, resolution=1, orient="horizontal") self.dataWindowSizeWidget.bind("<ButtonRelease-1>", self.updateEvent) self.dataWindowSizeWidget.bind("<Button1-Motion>", self.updateEvent) self.dataWindowSizeWidget.pack(fill=tk.X,expand=1) """ Data Window Start Widget """ self.dataWindowStartWidgetLabel = tk.Label(self, text='View Start') self.dataWindowStartWidgetLabel.pack() self.dataWindowStartWidget = tk.Scale(self, from_=0, to=10, resolution=1, orient="horizontal") self.dataWindowStartWidget.bind("<ButtonRelease-1>", self.updateEvent) self.dataWindowStartWidget.bind("<Button1-Motion>", self.updateEvent) self.dataWindowStartWidget.pack(fill=tk.X,expand=1) def addMainFigure(self) : """ Add main figure area """ self.fig = plt.figure(figsize=(5,4), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.set_title('No data') self.fig.canvas.draw() self.canvas = FigureCanvas(self.fig, self) """ Set up callback from canvas draw events, i.e. pan/zoom """ #self.cid1 = self.fig.canvas.mpl_connect('draw_event', self.updateFromCavas) #self.cid1 = self.fig.canvas.mpl_connect('button_release_event', self.updateFromCavas) #TODO animation 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) def addChop(self) : chopBW = tk.Button(self, text="Chop", command=self.doChop) chopBW.pack() self.chopButtonW = chopBW def addStat(self) : statBW = tk.Button(self, text="Stats", command=self.doStat) statBW.pack() self.statButtonW = statBW def postLoad(self) : """ Things to run after loading a new DataAnalyser object. """ debug("postLoad: get current view from DA...") viewList = self.DA.getView() # retrieve the default view after load debug("postLoad: get labels from DA...") self.updateLabels() # get new data types from data loaded self.setAltIndex('index') self.setView(viewList) # configure GUI to reflect new data self.isSafeToUpdate = True debug("postLoad: isSafeToUpdate:"+str(self.isSafeToUpdate)) """ now, set the window """ #TODO use data values instead of index values limitDict=self.DA.getIndexLimits() maxSize, minVal = ( limitDict['max'] , limitDict['min'] ) #print( "DEBUG: postLoad: maxSize: "+str(maxSize) ) #print( "DEBUG: postLoad: minValue: "+str(minVal) ) self.setWindow( minVal=minVal, start=0, maxSize=maxSize, size=int(maxSize/2)) # reset the GUI window self.updateEvent(None) # update GUI def setWindow(self, minVal=0, start=0, maxSize=10, size=10) : """ set the GUI values that correspond to the window """ debug("DEBUG: setWindow: %s, start: %s, maxSize: %s, size: %s" ,minVal, start, maxSize, size ) self.dataWindowSizeWidget.config(from_=1, to=maxSize-start+1) self.dataWindowSizeWidget.set(size) self.dataWindowStartWidget.config(from_=minVal, to=maxSize-size+1) self.dataWindowStartWidget.set(start) def load(self, *args, **kwargs) : """ catch all load method Currently, the only implemented mode is CSV file data. """ self.isSafeToUpdate = False name = filedialog.askopenfilename() self.loadFileData(path=name, *args, **kwargs) def loadFileData(self, path=None, *args, **kwargs) : """ Show a dialog to select a file and load it. """ if path is None: raise TypeError("loadFileData: path option is required") print("Got filename:" +path) loadData(path, *args, **kwargs) self.postLoad() def updateLabels(self) : """ Update labels from the DataAnalyser object Call whenever DA is loaded/changed. """ #print("DEBUG: updateLabels: isSafeToUpdate:", self.isSafeToUpdate) if not self.DA.isLoaded : return DataNotLoaded() newLabels = DA.getLabels() #debug("DEBUG: got label list from DA: "+str(newLabels)) for viewSubFrame in self.dataViewSubFrameList: viewSubFrame.setOptionsList(newLabels) """ re-enable widgets """ self.activateWidgets() def updateFromCavas(self, event) : """ Called when view is changed using figure canvas area. """ """ Get the figure axis limits """ figMinX, figMaxX = self.ax.get_xlim() debug('Got interval from MPL axis:'+str((figMinX,figMaxX))) """ Set the current window to match """ #TODO def viewChangeTrace(self, *args): """View is changed, make proper updates downward.""" debug("viewChange: isSafeToUpdate:"+str(self.isSafeToUpdate)) if not self.isSafeToUpdate : #print("DEBUG: viewChangeTrace: not safe, returning") return """Do other updates""" self.updateEvent(None) def setView(self, viewList) : """ Set the GUI representation of the current data view Takes a "view" object and sets the GUI so that it matches. """ self.isSafeToUpdate = False self.viewList = viewList for view,subFrame in zip(viewList,self.dataViewSubFrameList) : debug("DataViewApp: setView: "+str(view)) subFrame.disable() subFrame.setView(view) subFrame.enable() def setAltIndex(self, newIdx): """ Set the GUI presentation of alt index """ self.isSafeToUpdate = False self.altIdxSel.set(newIdx) def updateEvent(self, event): """ Change/Update data view when user requests a change. Call this whenever the user makes a change to view values. """ debug("updateEvent: called, event:"+str(event)) if not self.DA.isLoaded : return DataNotLoaded() DA = self.DA """ Set window from interface settings """ newWinSize = self.dataWindowSizeWidget.get() newWinStart = self.dataWindowStartWidget.get() limitDict=self.DA.getIndexLimits() debug("DEBUG: updateEvent: got limits: "+str(limitDict)) maxSize, minVal = ( limitDict['max'] , limitDict['min'] ) self.setWindow( minVal=minVal, start=newWinStart, maxSize=maxSize, size=newWinSize ) """ Set views from interface settings """ newViewList = list() for subFrame in self.dataViewSubFrameList : newView = subFrame.getView() debug("updateEvent: newView: "+str(newView)) if newView is not None : """If view frame returns None, don't add to list.""" newViewList.append(newView) """ set index """ try : pass #DA.setAltIndexColumn(self.altIdxSel.get()) #TODO except Exception as e: warn('updateEvent: Failed to set altnernate index, ignoring selection') print(e) else : """ just leave it set to index """ pass DA.setView( viewList=newViewList, windowStart=newWinStart, windowSize=newWinSize, windowType='index' ) """Redraw the plot""" dfList = self.DA.getViewData() #print("DEBUG: updateEvent: got updated data:", df.colums.tolist()) ax = self.ax ax.clear() xlabelList, ylabelList = list(), list() for df in dfList : """draw all df data as x,y data""" (xlabel, ylabel) = df.columns.tolist() ax.plot(df[xlabel].values, df[ylabel].values, 'o-') """store labels""" xlabelList.append(xlabel) ylabelList.append(ylabel) """Set labels""" newXlabel, newYlabel = str(), str() xlabelOverride = self.DVconfig.get('xlabel') ylabelOverride = self.DVconfig.get('ylabel') """Remember, configer doesn't hold native objects""" debug("Plotting: xlabelOverride: %s" % xlabelOverride) debug("Plotting: xlabelOverride eq None: %s" % (xlabelOverride == None)) if (xlabelOverride == None) or (ylabelOverride == None) : """Write the labels for all data""" debug("Plotting: Label overrides OFF") sep = "\n" newXlabel = sep.join( xlabelList ) newYlabel = sep.join( ylabelList ) debug("new xlabel: %s" % newXlabel) else : """the labels""" debug("Plotting: Label overrides ON") newXlabel = xlabelOverride newYlabel = ylabelOverride ax.set_xlabel(newXlabel) ax.set_ylabel(newYlabel) self.fig.canvas.draw() """ Show Statistics """ #self.showStats() def showStats(self): """ Get and report statsistics for the current view """ quantiles = self.DVconfig.get('statQuantiles') statsList = self.DA.getStats( quantiles ) dirpath = self.DVconfig.get('saveCDFDir') prefix = self.DVconfig.get('statFilePrefix') for statDF in statsList : fmt = self.DVconfig.get('statFileFmt') cols = ','.join(map(str,statDF.columns)) start,end = self.DA.getStartEnd() filename = prefix + "_{},{}-{}".format(cols,start,end) + fmt pathname = os.path.join( dirpath , filename ) statDF.to_csv(pathname) for stats in statsList: print("Data View Statistics:") print(stats) def doChop(self) : self.saveViewPlot() directory=pathlib.PurePath(os.path.curdir) chopConf = self.DVconfig.get('chopOpts') debug('chopConf:'+str(chopConf)) debug('dict(chopConf):'+str(dict(chopConf))) self.DA.chop(dirpath=directory, **dict(chopConf)) def saveViewPlot(self) : fig = self.fig # Get figure start,end = self.DA.getStartEnd() # Get view range dirpath = self.DVconfig.get('savePlotDir') prefix = self.DVconfig.get('savePlotPrefix') viewList = self.DA.getView() viewStr = ','.join(map(lambda x: ','.join(map(str,x)) if isinstance(x,tuple) else str(x), viewList)) filename = prefix + "_{vl},{start}-{end}".format( start=start,end=end, vl=viewStr ) + ".pdf" pathname = os.path.join( dirpath , filename ) fig.savefig(pathname) # Save plot def doStat(self) : """ Do actions for "stats" button """ # First, show stats on STDOUT self.showStats() # Then, save the current view plot self.saveViewPlot() # Next, make a CDF plot for all the visible data num_bins = self.DVconfig.get('saveCDFbins') cdfInfoLst = self.DA.getCDFall(num_bins=num_bins) # get CDF info from DA prefix = self.DVconfig.get('saveCDFprefix') dirpath = self.DVconfig.get('saveCDFDir') for cdfInfoT in cdfInfoLst : i = cdfInfoLst.index(cdfInfoT) label, cdf, counts, bin_edges = cdfInfoT start,end = self.DA.getStartEnd() filename = prefix +"_{},{}-{},{}.pdf".format(label,start,end,i) pathname = os.path.join( dirpath , filename ) fig = plt.figure() # mk new fig plt.plot(bin_edges[1:], cdf/cdf[-1]) plt.xlabel("{} values".format(label)) plt.ylabel("Normalized Cumulative Sum (CDF)".format()) fig.savefig(pathname)
def cb2(): def cs1(val): global ua ua = cs1.get() # Obergrenze für alpha in der Gamma Verteilung ct1.delete('1.0', tk.END) ct1.insert(tk.END, ua) cb2plot() def cs2(val): global ub ub = cs2.get() #Obergrenze für beta in der Gamma Verteilung ct2.delete('1.0', tk.END) ct2.insert(tk.END, ub) cb2plot() def cs3(val): #global Alpha Alpha = cs3.get() ct3.delete('1.0', tk.END) ct3.insert(tk.END, Alpha) cb2plot() def cs4(val): #global Beta Beta = cs4.get() ct4.delete('1.0', tk.END) ct4.insert(tk.END, Beta) cb2plot() def cs5(val): #global Lambda Lambda = cs5.get() ct5.delete('1.0', tk.END) ct5.insert(tk.END, Lambda) cb2plot() # Definieren der Wahrscheinlichkeitsfunktionen def cb2plot(): # Globale Variablen definieren global Beta global Alpha global ua global ub global Sum global postalpha global postbeta Sum = cs5.get() Beta = cs4.get() Alpha = cs3.get() ua = cs1.get() ub = cs2.get() postalpha = alpha + Sum postbeta = beta + n #Aufrufen der Funktionen Best = BestL() # Plot in der Canvas des aw plt.cla( ) # Löscht die aktuellen Plots aus dem Fenster, lässt dieses aber noch offen ay = fig.add_subplot(111) I = np.linspace(0, L, 10 * L + 1) X = Poisson(I, Lambda) Y = Gamma(I, Best[0], Best[1]) Z = Posteriori(I) ay.plot(I, X, 'b-', label='priori') ay.plot(I, Y, 'g-', label=Best) ay.plot(I, Z, 'r-', label='posteriori') if postalpha > 1: ay.plot((postalpha - 1) / postbeta, 0, '.', markersize=10, label='Modus (Posteriori)') ay.plot(postalpha / postbeta, 0, '.', markersize=10, label="Erwartungswert (Posteriori)") ay.set_xlabel( 'Erfolgswahrscheinlich p') # Axenbeschriftung in x Richtung ay.set_ylabel( 'Wahrscheinlichkeitsdichte') # Axenbeschriftung in y Richtung ay.legend(loc='best') ccb2.draw() cb2w = tk.Tk() # Definition eines Auswahlfensters cb2w.title("Gamma-Poisson Verteilung") # Beschriftung des Fensters cb2w.geometry("1200x600") # Anpassung der Größe # Canvas, Felds für den Plot fig = plt.figure(figsize=(10, 5)) ccb2 = FigureCanvas(fig, master=cb2w) L1 = tk.Label(cb2w, text="Obere Grenze für Alpha : ") L2 = tk.Label(cb2w, text="Obere Grenze für Beta: ") L3 = tk.Label(cb2w, text="Alpha: ") L4 = tk.Label(cb2w, text="Beta: ") L5 = tk.Label(cb2w, text="Lambda: ") # Eingabeslider cs1 = tk.Scale(master=cb2w, from_=0, to=50, orient=HORIZONTAL, command=cs1) # Obere Grenze Alpha cs2 = tk.Scale(master=cb2w, from_=0, to=50, orient=HORIZONTAL, command=cs2) # Obere Grenze Beta cs3 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs3) # Alpha cs4 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs4) # Beta cs5 = tk.Scale(master=cb2w, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs5) # Lambda command #--> cs1-5 neu definieren #Definition von Startwerten cs1.set(10) cs2.set(10) cs3.set(1) cs4.set(1) cs5.set(4) # Textfelder ct1 = tk.Text(master=cb2w, height=1, width=10) ct2 = tk.Text(master=cb2w, height=1, width=10) ct3 = tk.Text(master=cb2w, height=1, width=10) ct4 = tk.Text(master=cb2w, height=1, width=10) ct5 = tk.Text(master=cb2w, height=1, width=10) ccb2._tkcanvas.grid(row=0, column=0, columnspan=4) # Zuweisung der Labels durch .grid() L1.grid(row=2, column=0) L2.grid(row=3, column=0) L3.grid(row=4, column=0) L4.grid(row=5, column=0) L5.grid(row=6, column=0) #Zuweisung der Scale durch .grid() cs1.grid(row=2, column=1) cs2.grid(row=3, column=1) cs3.grid(row=4, column=1) cs4.grid(row=5, column=1) cs5.grid(row=6, column=1) #Zuweisung der Scale durch .grid() ct1.grid(row=2, column=2) ct2.grid(row=3, column=2) ct3.grid(row=4, column=2) ct4.grid(row=5, column=2) ct5.grid(row=6, column=2) #Anfangsplot cb2plot()
def cb1(): def wplot(): # Globale Variablen definieren global priori global alphapost global betapost #Berechnung der posteriori Größen alphapost, betapost = konj(alpha, beta, HeadCount, ThrowCount) # Plot in der Canvas des aw plt.cla() ax = fig.add_subplot(111) x = np.linspace(0, 1, num=200) y = [preDistribution(i, 1) for i in x] z = [Distribution(i, 1) for i in x] ax.plot(x, y, 'b-', label='priori') ax.plot(x, z, 'r-', label='posteriori') if alpha > 1: if beta > 1: ax.plot((alphapost - 1) / (alphapost + betapost - 2), 0, '.', markersize=12, label='Modus (Posteriori)') ax.set_xlabel( 'Erfolgswahrscheinlich p') # Axenbeschriftung in x Richtung ax.set_ylabel( 'Wahrscheinlichkeitsdichte') # Axenbeschriftung in y Richtung ax.legend(loc='best') canvas.draw() def cs1(val): global ThrowCount global s1max s1max = s1.get() ThrowCount = s1max t1.delete('1.0', tk.END) t1.insert(tk.END, ThrowCount) wplot() def cs2(val): global HeadCount HeadCount = s2.get() t2.delete('1.0', tk.END) t2.insert(tk.END, HeadCount) wplot() def cs3(val): global alpha alpha = s3.get() t3.delete('1.0', tk.END) t3.insert(tk.END, alpha) wplot() def cs4(val): global beta beta = s4.get() t4.delete('1.0', tk.END) t4.insert(tk.END, beta) wplot() aw = tk.Tk() # Definition eines Auswahlfensters aw.title("Beta-Verteilung") # Beschriftung des Fensters aw.geometry("1200x600") # Anpassung der Größe # Canvas, Felds für den Plot fig = plt.figure(figsize=(10, 5)) canvas = FigureCanvas(fig, master=aw) L1 = tk.Label(aw, text="Anzahl : ") L2 = tk.Label(aw, text="Anzahl eingetretenes Ereignis: ") L3 = tk.Label(aw, text="Alpha: ") L4 = tk.Label(aw, text="Beta: ") # Eingabeslider s1 = tk.Scale(master=aw, from_=0, to=1000, orient=HORIZONTAL, command=cs1) # Anzahl an Ereignissen s2 = tk.Scale(master=aw, from_=0, to=1000, orient=HORIZONTAL, command=cs2) # Anzahl an eigetretenen Ereignissen s3 = tk.Scale(master=aw, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs3) # Alpha s4 = tk.Scale(master=aw, from_=0, to=5, resolution=0.01, orient=HORIZONTAL, command=cs4) # Beta #Definition von Startwerten s1.set(500) s2.set(250) s3.set(0.5) s4.set(0.5) # Textfelder t1 = tk.Text(master=aw, height=1, width=10) t2 = tk.Text(master=aw, height=1, width=10) t3 = tk.Text(master=aw, height=1, width=10) t4 = tk.Text(master=aw, height=1, width=10) canvas._tkcanvas.grid(row=0, column=0, columnspan=4) # Zuweisung der Labels durch .grid() L1.grid(row=2, column=0) L2.grid(row=3, column=0) L3.grid(row=4, column=0) L4.grid(row=5, column=0) #Zuweisung der Scale durch .grid() s1.grid(row=2, column=1) s2.grid(row=3, column=1) s3.grid(row=4, column=1) s4.grid(row=5, column=1) #Zuweisung der Scale durch .grid() t1.grid(row=2, column=2) t2.grid(row=3, column=2) t3.grid(row=4, column=2) t4.grid(row=5, column=2) #Anfangsplot wplot()
for dimension in sorted( dimensionIndex.keys(), key = dimensionIndex.get ): dimensionCheck[ dimension ] = IntVar() Checkbutton( dimensionFrame, variable = dimensionCheck[ dimension ], fg = 'black' ).grid( row = pos, column = 1, padx = 10 ) Label( dimensionFrame, text = dimensionTranslation[ dimension ] + ':' ).grid( row = pos, column = 2, pady = 10, sticky = E ) dimensionEntry[ dimension ] = Label( dimensionFrame, width = 12, fg = 'black', bg = 'white', justify = CENTER, relief = SUNKEN ) dimensionEntry[ dimension ].grid( row = pos, column = 3, padx = 10, sticky = W ) dimensionScale[ dimension ] = Scale( dimensionFrame, label = 'Escala', from_ = 10, to = 1, length = 30, width = 10, sliderlength = 5, troughcolor = 'white' ) dimensionScale[ dimension ].grid( row = pos, column = 4, sticky = W ) pos += 1 # Canvas para exibição do grafico scroll = ttk.Scrollbar( window, orient = HORIZONTAL ) figure = Figure( dpi = 100, figsize = (5, 4) ) figure.subplots_adjust( left = 0.05, right = 0.9, top = 0.97, bottom = 0.05, hspace = 0.1 ) plotWidth = ( 400, 100 ) mplCanvas = FigureCanvas( figure, master = window ) mplCanvas.show() dataCanvas = mplCanvas.get_tk_widget() # Callback para deslocar o canvas da matplotlib com o slider (não ideal, procurando solução melhor) def move( mode, position, c = UNITS ): if float(position) < 0.0: position = 0.0 if float(position) > 1.0: position = 1.0 width = scroll.get()[1] - scroll.get()[0] space = 1.0 - width scroll.set( float(position) * space, float(position) * space + width ) scroll[ 'command' ] = move dataCanvas.grid( row = 5, column = 2, rowspan = 2, sticky = (N, S, E, W) ) scroll.grid( row = 7, column = 2, pady = 5, sticky = (N, E, W) ) # Espaço para configurações personalizadas