class Plotter(gtk.VBox): def __init__(self, xlabel, ylabel, width=500, height=500, dpi=75): """ :type xlabel: str :type ylabel: str :type width: int :type height: int :type dpi: int """ gtk.VBox.__init__(self) figure = Figure(figsize=(width, height), dpi=dpi) self.axes = figure.add_subplot(111, xlabel=xlabel, ylabel=ylabel) """ :type: matplotlib.axes.Axes """ self.axes.hold(False) self.canvas = FigureCanvas(figure) #self.canvas.mpl_connect('button_press_event', self.klick) nav = NavigationToolbar(self.canvas, self) self.pack_start(nav, False, False) self.pack_start(self.canvas) def leeren(self): self.axes.hold(False) def plot(self, x, y, **args): self.axes.plot(x, y, antialiased=True, **args) self.axes.hold(True) def draw(self): self.canvas.draw() """def klick(self, evt):
class Display: """ This class is responsible for rendering the graph in the upper portion of the window. The data in the graph is taken from a Simulation object, which is accessed through the main Interface object. """ # This is a color I chose to perfectly match the background of the rest of # the interface. It might only work on my computer. # Malingo: Yes, it only works on your computer. It depends on what gtk # theme the user has chosen. background = "#edecea" def __init__(self, main): self.main = main pi = numpy.pi self.abscissa = numpy.arange(-pi - .25, pi + 0.25, 0.01) self.curve = None self.canvas = None def setup(self, layout): """ This method creates the graph that is displayed on the top half of the user interface. Currently, the axes are completely hard-coded in this method and cannot be changed on-the-fly. """ figure = Figure(facecolor=Display.background) axes = figure.add_subplot(111) # In order to create a line object, a dummy line needs to be plotted. # This line will get replaced before the GUI is shown to the user. pi = numpy.pi x = y = self.abscissa self.curve = axes.plot(x, y)[0] self.canvas = FigureCanvasGTKAgg(figure) # The tick labels are formatted using LaTeX. This makes it possible # to use symbols like pi. axes.set_xticks((-pi, 0, pi)) axes.set_xticklabels((r"-\pi", "0", r"\pi")) axes.set_xlim(-pi - 0.25, pi + 0.25) axes.set_yticks((0, 1)) axes.set_yticklabels(("0", "1")) axes.set_ylim((-0.1, 1.1)) layout.pack_start(self.canvas) def update(self): """ This method updates the graph using the new ordinate values returned by the simulation. """ main = self.main simulation = main.simulation ordinate = simulation.plot(self.abscissa) self.curve.set_ydata(ordinate) self.canvas.draw()
class aacxGui: def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("aacx.ui") self.window = self.builder.get_object("window1") self.status = self.builder.get_object("statusbar1") self.frmadj = self.builder.get_object("frame_adj") self.about = gtk.AboutDialog() self.about.set_name("AACX") self.about.set_version("0.0.1") self.about.set_copyright(u'Copyright © 2010 Alex Converse') self.about.set_website("http://github.com/aconverse/aacx") self.about.set_license("GPLv2+") self.window.connect("destroy", gtk.main_quit) signals = { "on_file_quit_activate": gtk.main_quit, "on_help_about_activate": self.show_about, "on_frame_adj_value_changed": self.spinback, } self.builder.connect_signals(signals) self.set_status_here("xxx") self.hasplot = 0 def addplot(self, fig): self.canvas = FigureCanvasGTKAgg(fig) self.canvas.show() v = self.builder.get_object("vbox1") v.pack_start(self.canvas) self.hasplot = 1 def redraw(self): self.canvas.draw() def show(self): self.window.show() def show_about(self, data): self.about.run() self.about.hide() def set_status_here(self, text): self.status.push(0, text) def spinback(self, data): spinback(int(data.get_value()), int(data.get_upper())+1) def set_spinner(self, n): self.frmadj.set_value(n) def set_num_frames(self, n): self.frmadj.set_upper(n-1)
def __init__(self, toolBoxWidgets=None, title="GTK Gui Plot", scaling=True, *args, **kwargs): if not toolBoxWidgets: toolBoxWidgets = [] super(GuiWithCanvasAndToolbar, self).__init__(*args, **kwargs) self.connect("destroy", lambda x: gtk.main_quit()) self.set_default_size(1100, 600) self.set_title(title) table = gtk.Table(1, 2, False) self.figures = [] self.y_max = float("-inf") self.x_max = float("-inf") self.y_min = float("inf") self.x_min = float("inf") self.fig = Figure(figsize=(8, 6), dpi=100) self.ax = self.fig.add_subplot(111) canvas = FigureCanvas(self.fig) canvas.set_size_request(800, 600) canvas.mpl_connect('button_press_event', self.handle_click) table.attach(canvas, 0, 1, 0, 1) toolbox = gtk.Table(len(toolBoxWidgets) + 1, 1, False) i = 0 for widget in toolBoxWidgets: toolbox.attach(widget, 0, 1, i, i + 1) i += 1 label = gtk.Label("SimGUI") toolbox.attach(label, 0, 1, i, i + 1) table.attach(toolbox, 1, 2, 0, 1) self.canvas = canvas canvas.draw() self.update_figures() self.add(table) self.scaling = scaling
class GTKFacePlot (gtk.Window): def __init__(self): gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL) self.set_title("MixedEmotions") self.set_border_width(10) self.fig = Figure(figsize=(3,1), dpi=100) self.ax = self.fig.add_subplot(111) self.x = arange(0,2*pi,0.01) # x-array self.lines = self.ax.plot(self.x,sin(self.x)) self.canvas = FigureCanvas(self.fig) self.add(self.canvas) self.figcount = 0 gtk.timeout_add(100, self.updatePlot) def updatePlot(self): self.figcount += 1 self.lines[0].set_ydata(sin(self.x+self.figcount/10.0)) self.canvas.draw() return gtk.TRUE
class Reader(object): def __init__(self,win_size, win_loc, title,subplot_dim=[1,1]): self.top = gtk.Window() self.top.connect('delete-event', gtk.main_quit) self.top.set_title(title) self.top.set_position(gtk.WIN_POS_CENTER) self.top.set_default_size(*win_size) self.fig = Figure() self.axs = [self.fig.add_subplot(subplot_dim[0], subplot_dim[1], i+1) for i in range(np.prod(subplot_dim))] self.canvas = FigureCanvas(self.fig) self.top.add(self.canvas) self.top.show_all() self.update_background() if len(self.axs) == 1: self.ax = self.axs[0] def update_background(self): self.canvas.draw() self.backgrounds = [self.canvas.copy_from_bbox(ax.bbox) for ax in self.axs] if len(self.backgrounds) == 1: self.background = self.backgrounds[0] return def draw(self): raise Exception('Not implemented.') def read(self): raise Exception('Not implemented yet.')
class LoggerPlot (gtk.VBox): def __init__ (self): gtk.VBox.__init__ (self) self.figure = Figure(figsize=(5,4), dpi=100) self.canvas = FigureCanvas (self.figure) self.toolbar = NavigationToolbar (self.canvas, None) self.pack_start (self.canvas) self.pack_start (self.toolbar, False, False) #FigureCanvas.__init__ (self, self.figure) def plot (self, title, x, y): self.figure.clear() a = self.figure.add_subplot(111) a.set_title (title) a.grid(True) a.plot(x,y) self.canvas.draw() def clear (self): self.figure.clear() self.canvas.draw()
def make_fig(title = None): ''' Create a figure window with a single set of axes and a single main subplot. Returns the axes of the main subplot ''' global all_sub_figures if title == None: title = "Untitled Figure {0}".format(len(all_sub_figures)+1) dialog = gtk.Dialog(title, win, gtk.DIALOG_DESTROY_WITH_PARENT) dialog.set_default_size(500,400) fig = matplotlib.figure.Figure() axes = fig.add_subplot(111) #axes.invert_yaxis() #axes.autoscale() canvas = FigureCanvasGTKAgg(fig) # a gtk.DrawingArea canvas.set_size_request(300,300) dialog.vbox.pack_start(canvas, expand=True) toolbar = NavigationToolbar2GTKAgg(canvas, dialog) dialog.vbox.pack_start(toolbar, False, False) dialog.show_all() canvas.draw() fig.prev_child_count = 0 all_sub_figures.append(fig) return axes
class GraphPlot(object): # glade file to load ui_filename = "GraphPlot.ui" # widgets to load from the glade file. Each one of these is added to 'self' after # you call 'initialize_from_xml' ui_widgets = ['window', 'graphImage', 'toolbar'] HISTORY = 3 def __init__(self, NetworkTable): util.initialize_from_xml(self) self.dead = False self.plots = [] self.count = 0 self.netTable = NetworkTable self.netTable.PutBoolean('EnableTuning', True) self.figure = Figure(figsize=(5, 4), dpi=100) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.graphImage = util.replace_widget(self.graphImage, self.canvas) self.toolbar = util.replace_widget( self.toolbar, NavigationToolbar(self.canvas, self.window)) self.window.show_all() # listen to network tables variables network_tables.attach_fn(self.netTable, "Catapult Values", self.on_update_CatapultValues, self.window) network_tables.attach_fn(self.netTable, "EnableTuning", self.on_update_EnableTuning, self.window) def on_update_EnableTuning(self, key, value): if not self.dead and not value: self.netTable.PutBoolean('EnableTuning', True) def on_update_CatapultValues(self, key, value): arraybutitsastring = self.netTable.GetString('Catapult Values', key) print(arraybutitsastring, 'String version') array = eval(arraybutitsastring) print(array, 'array version') self.count += 1 step = 0.025 x = arange(0, len(array) * step, step) plot = self.axes.plot(x, array, label=str(self.count)) # clear old things if len(self.axes.lines) > self.HISTORY: self.axes.lines.pop(0) self.axes.legend() self.canvas.draw() def on_destroy(self, window): self.dead = True self.netTable.PutBoolean('EnableTuning', False)
class G_Plot(): def __init__(self, title, function): self.title = title # MAT-PLOT-LIB_____________________________________________________ self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(400, 300) # set min size self.markers = [ '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd' ] self.colors = [ 'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple', 'white' ] self.pstyle = [ 'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '', '25', '', '', '20', '15', '', '', '20', '15' ] self.styledict = {} self.styledict["style"] = 'bmh' self.styledict["point_style"] = 's' self.styledict["point_size"] = '6' self.styledict["point_color"] = 'red' self.styledict["point_alpha"] = '0.8' self.styledict["line_color"] = 'black' self.styledict["line_width"] = '2' self.styledict["band_color"] = 'black' self.styledict["band_alpha"] = '0.3' self.styledict["title_size"] = '25' self.styledict["xtitle_size"] = '20' self.styledict["xlabel_size"] = '15' self.styledict["ytitle_size"] = '20' self.styledict["ylabel_size"] = '15' self.function = function self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1] self.plot_labels = ["Time Exposure", "t", "G(x)", " [h]", " []"] #print plt.style.available self.fit_toggle = 'inactive' self.points_toggle = 1 self.function_toggle = 1 self.err_toggle = 1 self.ci_func_toggle = 1 self.ci_points_toggle = 1 #self.plotting(function) def plotting(self, t, t0): """Generating matplotlib canvas""" plt.style.use(self.pstyle[0]) self.ax1 = self.fig.add_subplot(111) self.ax1.clear() self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3], fontsize=int(self.pstyle[13])) self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(0.000001, 1.5 * max(t, t0), 0.01) y = self.function(x, t0) self.ax1.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) self.ax1.axvline(x=t, linewidth=1, linestyle='-', color='red') self.ax1.axhline(y=self.function(t, t0), linewidth=1, linestyle='--', color='red') self.fig.tight_layout() self.canvas.draw()
class PlotPane: # A display class which contains a MPL canvas, plot container and # various other capabilities to enable rapid GUI-driven plots based # on the list of series in the plot container. m_sType = 0 # Type indicating whether it takes trajectories or series def __init__(self, window, name, consts, xlabel): # Must pass pointer to the main window reference, to allow MPL toolbar # to be properly initialised. # Initialise the list of series to be plotted self.m_series_dict = {} self.m_xlDefaul = xlabel self.m_styles = PlotStyles() self.m_consts = consts # Series currently being plotted self.m_plotted = {} # Is the plot editor open? self.m_editOpen = False # Initialise a h/vbox for storage of all the plot elements. self.m_vbox = gtk.VBox(homogeneous=False) self.m_hbox = gtk.HBox(homogeneous=False) self.m_vbox.pack_start(self.m_hbox, padding=self.m_consts.m_pad) # Create a frame to hold everything self.m_main_vbox = gtk.VBox(homogeneous=False) self.m_main_hbox = gtk.HBox() # Hbox for padding self.m_main_hbox.pack_start(self.m_main_vbox, padding=self.m_consts.m_pad) #self.m_main_vbox.set_size_request(400,300) frame = gtk.Frame() frame.set_label(name) frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT) self.m_hbox.add(frame) frame.add(self.m_main_hbox) # Initialise the buttons hbox = self.createCommandButtons() # Create the MPL canvas self.createMPLCanvas() # Create the MPL toolbar self.m_mpl_toolbar = self.createMPLToolbar(self.m_canvas, window) self.m_main_vbox.pack_start(self.m_mpl_toolbar, expand=False) self.m_main_vbox.pack_start(self.m_canvas, padding=self.m_consts.m_pad) # Add the buttons after the plot self.m_main_vbox.pack_start(hbox, expand=False) # Create a scroller and plot list pane scroller = self.createPlotList() box = gtk.HBox(homogeneous=False) box.set_size_request(self.m_consts.x_lv,self.m_consts.y_lv) box.pack_start(scroller) self.m_main_vbox.pack_start(box, expand=False, \ padding=self.m_consts.m_pad) # Add the series controller sidepane = SidePane(self) box.pack_start(sidepane.vbox, expand=False) def addColumn(self, title, colID): col = gtk.TreeViewColumn(title, gtk.CellRendererText(), \ text=colID) col.set_resizable(True) col.set_sort_column_id(colID) self.m_listview.append_column(col) def createMPLCanvas(self): # Create the figure #self.m_figure = Figure(figsize=(5,4), dpi=100) self.m_figure = Figure() self.m_canvas = FigureCanvas(self.m_figure) self.initialisePlot() def initialisePlot(self): self.m_plotted = {} self.m_axes = self.m_figure.add_subplot(111) self.m_axes.set_xlabel(self.m_xlDefaul) self.m_figure.subplots_adjust(bottom=0.15) self.m_figure.subplots_adjust(left=0.15) self.toggleLogAxis(self.m_b_logx_toggle, "x") self.toggleLogAxis(self.m_b_logy_toggle, "y") self.m_canvas.draw() def createMPLToolbar(self, canvas, window): # Create the toolbar toolbar = NavToolbar(canvas, window) return toolbar def createCommandButtons(self): # Create handy buttons for plotting thins with MPL] self.m_b_plot_selection = gtk.Button("Plot selected") self.m_b_logx_toggle = gtk.CheckButton("LogX?") self.m_b_logy_toggle = gtk.CheckButton("LogY?") self.m_b_editor = gtk.Button("Edit plot") self.m_b_reset = gtk.Button("Reset") # Add some tooltips self.m_b_plot_selection.set_tooltip_text("Plot the selected series") self.m_b_logx_toggle.set_tooltip_text("Toggle Log10 x scale") self.m_b_logy_toggle.set_tooltip_text("Toggle log10 y scale") self.m_b_editor.set_tooltip_text("Open the plot editor") self.m_b_reset.set_tooltip_text("Reset the plot") # Connect some signals self.m_b_plot_selection.connect("clicked", self.plotSelected, None) self.m_b_logx_toggle.connect("toggled", self.toggleLogAxis, "x") self.m_b_logy_toggle.connect("toggled", self.toggleLogAxis, "y") self.m_b_editor.connect("clicked", self.editAxes, None) self.m_b_reset.connect("clicked", self.resetPlot, None) hbox = gtk.HBox(homogeneous=False) hbox.pack_start(self.m_b_plot_selection, expand=False) hbox.pack_start(self.m_b_logx_toggle, expand=False) hbox.pack_start(self.m_b_logy_toggle, expand=False) hbox.pack_end(self.m_b_reset, expand=False) hbox.pack_end(self.m_b_editor, expand=False) return hbox def toggleLogAxis(self, widget, data): # Toggles between logx/logy axes if widget.get_active(): if data == "x": self.m_axes.set_xscale("log") self.m_canvas.draw() elif data == "y": self.m_axes.set_yscale("log") self.m_canvas.draw() else: if data == "x": self.m_axes.set_xscale("linear") self.m_canvas.draw() if data == "y": self.m_axes.set_yscale("linear") self.m_canvas.draw() def plotSelected(self, widget, data=None): # Plots the selected series on the itemlist selection = self.m_listview.get_selection() if selection.count_selected_rows() > 0: (model, pathlist) = selection.get_selected_rows() id_list = [] name_list = [] unit_list = [] for path in pathlist: id_list.append(model[path[0]][0]) name_list.append(model[path[0]][1]) unit_list.append(model[path[0]][2]) if not checkListOfStrings(unit_list): if type(unit_list[0]) == type(1.0): self.m_axes.set_ylabel("kernel density, 1/nm") lines = [] for id in id_list: lines.append(self.plotSeries(self.m_series_dict[id])) self.m_plotted[id] = self.m_series_dict[id] else: print("Wrong units being plotted on same axis!") print("Nothing plotted.") else: self.m_axes.set_ylabel("parameter, {0}".format(unit_list[0])) lines = [] for id in id_list: lines.append(self.plotSeries(self.m_series_dict[id])) self.m_plotted[id] = self.m_series_dict[id] def plotSeries(self, series): # Displays the selected series in the MPL figure line = self.m_axes.plot(series.m_xvalues, series.m_yvalues, \ self.m_styles.getNextStyle(), label=series.m_name) #line[0].set_picker(True) self.m_axes.set_autoscale_on(True) self.m_axes.legend(loc=0, prop={'size':10}) self.m_canvas.draw() return line def addSeries(self, serieslist): # Add a series to the plotlist from series list. for item in serieslist: # Get the ID of the run entry = [getNextIndex(self.m_series_dict)] entry += item.getPlotPaneList() # Add the series to the dictionary appendDict(self.m_series_dict, item) # Add it to the listview self.m_liststore.append(entry) def removeSelected(self): # Removes the selected series from the list selection = self.m_listview.get_selection() if selection.count_selected_rows() > 0: (model, pathlist) = selection.get_selected_rows() # Reverse doesn't seem to work? for path in reversed(pathlist): del self.m_liststore[path[0]] else: print("Nothing selected.") def clearSeries(self): # Clears all the series and resets the plot self.m_liststore.clear() for k in self.m_series_dict.keys(): del self.m_series_dict[k] self.m_series_dict = {} self.resetPlot(None, None) def editAxes(self, widget, data=None): if not self.m_editOpen: editor = PlotEditor(self) def resetPlot(self, widget, data=None): # Removes all the lines from the figure for i in range(0, len(self.m_axes.lines)): self.m_axes.lines.pop(0) self.m_figure.clear() self.initialisePlot() def chooseSaveFile(self): # Check PyGTK version if gtk.pygtk_version < (2,3,90): print("PyGtk 2.3.90 or later required!") raise SystemExit dialog = gtk.FileChooserDialog("Select file or path..", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) # Allow multiple files to be selected dialog.set_select_multiple(False) # Add file filters to dialog filter = gtk.FileFilter() filter.set_name("DSV files") filter.add_pattern("*.csv") filter.add_pattern("*.dat") filter.add_pattern("*.dsv") dialog.add_filter(filter) filter = gtk.FileFilter() filter.set_name("All files") filter.add_pattern("*") dialog.add_filter(filter) # Now run the chooser! fname = dialog.run() # Check the response if fname == gtk.RESPONSE_OK: filename = dialog.get_filename() elif fname == gtk.RESPONSE_CANCEL: print 'Saving file cancelled!' filename = None dialog.destroy() return filename def setDelimiter(self, widget, data=None): # Sets the delimiter when saving files. print 1 def saveSeries(self): # Saves the selected series selection = self.m_listview.get_selection() if selection.count_selected_rows() > 0: (model, pathlist) = selection.get_selected_rows() id_list = [] name_list = [] for path in pathlist: id_list.append(model[path[0]][0]) name_list.append(model[path[0]][1]) # Loop over all series to save them as a separate file for id in id_list: # Call file saver dialog oname = self.chooseSaveFile() if oname != None: print("Saving file " + oname) parser = Out.DSVOut(oname) data = self.m_series_dict[id].getOutputData() parser.parseData(data, ",") parser.close() else: print("File saving cancelled.") else: print "Nothing selected."
class ROIImage: def __init__(self): # Minimal gtk initialization self.builder = gtk.Builder() self.builder.add_from_file("roi_image.glade") self.builder.connect_signals(self) # Create a matplotlib figure for the image self.imageFigure = Figure(figsize=(5,4), dpi=100) self.imagePlot = self.imageFigure.add_subplot(111) # Place the matplotlib figures into a container self.imageCanvas = FigureCanvas(self.imageFigure) # a gtk.DrawingArea self.builder.get_object('imageViewPort').add(self.imageCanvas) # Create a matplotlib figure for the plot self.plotFigure = Figure(figsize=(5,4), dpi=100) self.plotPlot = self.plotFigure.add_subplot(111) # Place the matplotlib figures into a container self.plotCanvas = FigureCanvas(self.plotFigure) # a gtk.DrawingArea self.builder.get_object('plotViewPort').add(self.plotCanvas) self.builder.get_object('lowIndexSlider').set_range(0,2047) self.builder.get_object('lowIndexSlider').set_value(0) self.builder.get_object('highIndexSlider').set_range(0,2047) self.builder.get_object('highIndexSlider').set_value(2047) self.mCurrentLowLimit = 0 self.mCurrentHighLimit = 2047 # This one is called when the main window is destroyed (i.e. when # delete_event returns null) def on_main_window_destroy(self, widget, data=None): print "destroy signal occurred" gtk.main_quit() # This one is called when the main window close-button is clicked def on_main_window_delete_event(self, widget, event, data=None): # If you return FALSE in the "delete_event" signal handler, # GTK will emit the "destroy" signal. Returning TRUE means # you don't want the window to be destroyed. # This is useful for popping up 'are you sure you want to quit?' # type dialogs. print "delete event occurred" # Change FALSE to TRUE and the main window will not be destroyed # with a "delete_event". return False def openDataButtonClicked(self,widget,data = None): # Open file chooser to choose a single file chooser = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) resp = chooser.run() if resp == gtk.RESPONSE_OK: filename = chooser.get_filename() print "selected file: " + filename self.mDataSet = FluoDataset() self.mDataSet.populate_dataset(filename) print "Dataset populated" # Test display self.showImage() self.showPlot() elif resp == gtk.RESPONSE_CANCEL: print 'Closed, no files selected' chooser.destroy() def showImage(self): data_set = self.mDataSet.get_fluo_data('xia00',0,0) if not data_set == None: self.imagePlot.clear() self.imagePlot.imshow(data_set[:,self.mCurrentLowLimit:self.mCurrentHighLimit,:].sum(1)) self.imageCanvas.draw() def showPlot(self): data_set = self.mDataSet.get_fluo_data('xia00',0,0) if not data_set == None: self.plotPlot.clear() self.plotPlot.plot(data_set.sum((0,2))) self.plotPlot.axvline(self.mCurrentLowLimit) self.plotPlot.axvline(self.mCurrentHighLimit) self.plotCanvas.draw() def lowerLimitChanged(self,widget,data = None): self.mCurrentLowLimit = widget.get_value() self.mCurrentHighLimit = max(self.mCurrentHighLimit,self.mCurrentLowLimit) self.showImage() self.showPlot() def upperLimitChanged(self,widget,data = None): self.mCurrentHighLimit = widget.get_value() self.mCurrentLowLimit = min(self.mCurrentHighLimit,self.mCurrentLowLimit) self.showImage() self.showPlot() # def singleDistanceClicked(self, widget, data = None): # print 'single distance clicked' # f,y = self.gen_1dist() # self.a.clear() # self.a.plot(f,y) # self.canvas.draw() # def twoDistanceClicked(self, widget, data = None): # print 'two distance clicked' # f,y = self.gen_2dist() # self.a.clear() # self.a.plot(f,y) # self.canvas.draw() def run(self): self.builder.get_object("window1").show_all() gtk.main()
class template: def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file(os.path.splitext(__file__)[0]+".glade") self.window = self.builder.get_object("window") dic = { "on_toolbutton_refresh_clicked" : self.generate_testdata, "on_button1_clicked" : self.generate_testdata, "on_vboxMain_button_press_event" : self.button_press_event, "on_vboxMain_button_release_event" : self.button_release_event, "on_vboxMain_drag" : self.drag_begin, "on_vboxMain_motion_notify_event" : self.drag_begin, "on_toolbar_clear_clicked" : self.clear_selections, "on_toolbar_zoomin_clicked" : self.zoomin_time, "on_toolbar_zoomout_clicked" : self.zoomout_time, "on_go_back_clicked" : self.go_back, "on_go_forward_clicked" : self.go_forward, "on_toolbutton_preferences_clicked" : self.preferences_open, "on_button_pref_apply_activate" : self.pref_apply, "set_channel_groups" : self.set_channel_groups, } self.builder.connect_signals(dic) self.create_draw_frame('none') self.space = 0 self.generate_testdata(None) def create_draw_frame(self,widget): self.fig = Figure(figsize=[100,100], dpi=72) self.canvas = FigureCanvas(self.fig) self.canvas.connect("scroll_event", self.scroll_event) #self.canvas.connect('button_press_event', self.button_press_event) self.canvas.show() self.figure = self.canvas.figure self.axes = self.fig.add_axes([0.045, 0.05, 0.93, 0.925], axisbg='#FFFFCC') self.vb = self.builder.get_object("vboxMain") self.vb.pack_start(self.canvas, gtk.TRUE, gtk.TRUE) self.vb.show() def preferences_open(self,widget): self.win_prefs = self.builder.get_object("window_prefs") self.win_prefs.show() self.channel_tree(None) def scroll_event(self, widget, event): if event.direction == gdk.SCROLL_UP: direction = 1 self.space = self.space + .1*self.scalefact else: direction = -1 self.space = self.space - .1*self.scalefact if self.space < 0: self.space = 0 print 'space', self.space print (arange(0,size(self.data2plot,1))*(self.space)) self.space_data() self.redraw(None) curpos = self.axes.get_position() l1 = curpos.x0 b1 = curpos.y0 w1 = curpos.x1 h1 = curpos.y1 def space_data(self): self.data2plot = self.data[self.tstart:self.tstop,self.chanind] + \ (arange(0,size(self.data[self.tstart:self.tstop,self.chanind],1)) * \ (self.space)) def get_cursor_position(self,event): ap = self.axes.get_position() x,y = self.canvas.get_width_height() posx = ((event.x/x)-ap.x0)*(1/(ap.x1-ap.x0)) posy = ((event.y/y)-(1-ap.y0))*(1/(ap.y0-ap.y1)) self.sx = (posx*(self.time[-1]-self.time[0]))+self.time[0] self.sy = (posy*(self.data2plot.max()-self.data2plot.min()))+self.data2plot.min() print self.sx, self.sy def button_press_event(self,widget,event): self.get_cursor_position(event) print 'button pushed',event.button,event.type if event.type == gtk.gdk.BUTTON_PRESS: print "single click" if event.button == 1: #clicked line #self.axes.axvline(x=self.sx) self.xstart = self.sx elif event.type == gtk.gdk._2BUTTON_PRESS: print "double click" #highlight channel #self.axes.axhspan(self.sy-1, self.sy+1, xmin=0, xmax=1, color='yellow') elif event.type == gtk.gdk._3BUTTON_PRESS: print "triple click. ouch, you hurt your user." if event.type == gtk.gdk.BUTTON_PRESS and event.button == 2: print 'highlighting channel' self.axes.axhspan(self.sy-self.scalefact, \ self.sy+self.scalefact, xmin=0, xmax=1, color='g') #refresh canvas self.canvas.draw() def button_release_event(self,widget,event): pass self.get_cursor_position(event) #print event#.button if event.type == gtk.gdk.BUTTON_RELEASE and event.button == 1: self.axes.axvspan(ymin=0, ymax=1, xmin=self.xstart, xmax=self.sx, color='b') try: self.selections = vstack((self.selections,[self.xstart,self.sx])) except AttributeError: self.selections = array([[self.xstart,self.sx]]) print 'sels',self.selections self.canvas.draw() def clear_selections(self,widget): del self.selections self.redraw(None) def drag_begin(self,widget,event): pass #self.get_cursor_position(event) def redraw(self,widget): #print 'button press' print len(self.time),self.data2plot.shape self.color = 'black' self.axes.cla() self.axes = self.figure.axes[0] self.axes.plot(self.time, self.data2plot,color=self.color) self.axes.axis('tight') #self.axes.axis('off') try: print 'd',self.selections for i in self.selections: self.axes.axvspan(ymin=0, ymax=1, xmin=i[0], xmax=i[1], color='b') except: pass self.canvas.draw() def zoomin_time(self,widget): startind = self.tstart; stopind = self.tstop-((self.tstop-self.tstart)/2) self.check_scale(startind,stopind) def zoomout_time(self,widget): startind = self.tstart; stopind = self.tstop+((self.tstop-self.tstart)*2) self.check_scale(startind,stopind) def go_forward(self,widget): startind = ((self.tstop-self.tstart)/2)+self.tstart; stopind = ((self.tstop-self.tstart)/2)+self.tstop; self.check_scale(startind,stopind) def go_back(self,widget): startind = self.tstart-((self.tstop-self.tstart)/2); stopind = self.tstop-((self.tstop-self.tstart)/2); self.check_scale(startind,stopind) def check_scale(self,startind,stopind): print 'req',startind,stopind, self.tstart,self.tstop if startind < 0: startind = 0 stopind = self.tstop if stopind > len(self.t): startind = self.tstart stopind = len(self.t) if stopind < 0: stopind = self.tstop print 'set',startind,stopind,self.tstart,self.tstop self.tstart = startind self.tstop = stopind self.time = self.t[self.tstart:self.tstop] self.data2plot = self.data[self.tstart:self.tstop,self.chanind] self.space_data() self.redraw(None) def page_down(self,widget): pass def channel_tree(self,widget): print('updating list') self.View = self.builder.get_object("treeview1") self.dataList = gtk.ListStore(str,str) self.AddListColumn('Number', 0) self.AddListColumn('Label', 1) for k in range(0,self.numchannels): iter = self.dataList.append([k,'label'+str(k)]) self.View.set_model(self.dataList) print 'adding channels' def AddListColumn(self, title, columnId): column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=columnId) column.set_resizable(True) column.set_sort_column_id(columnId) self.View.append_column(column) self.View.get_selection().set_mode(gtk.SELECTION_MULTIPLE) def pref_apply(self, widget): liststore,iter = self.View.get_selection().get_selected_rows() self.chanind = [] for i in iter: print i, liststore[i][1] self.chanind.append(int(liststore[i][0])) #print self.dataList.get_value(iter,0) print self.chanind self.space_data() self.redraw(None) def set_channel_groups(self,widget): print widget.get_label(), widget #for i in self.builder.get_object('vbox2').get_children(): #if i.get_active() == True: #print(i) #print i.get_label() if widget.get_label() == 'meg' and widget.get_active() == True: #self.View.get_selection().select_all() #self.View.get_selection().select_all() self.View.get_selection().select_range(0,2) if widget.get_label() == 'Clear': self.View.get_selection().unselect_all() if widget.get_label() == 'all' and widget.get_active() == True: self.View.get_selection().select_all() def generate_testdata(self,widget): numpts = 10 self.numchannels = 10 self.t = arange(0,numpts, .01) self.data = zeros((len(self.t),self.numchannels)) self.scalefact = 1e-9 for i in arange(0,self.numchannels): r = random.randn() self.data[:,i] = float32((sin(2*0.32*pi*self.t*r) * sin(2*2.44*pi*self.t*r)))#+ self.space self.data = self.data * self.scalefact self.tstart = 0; self.tstop = len(self.t) self.time = copy(self.t[self.tstart:self.tstop]) print self.tstart,self.tstop self.chanind = arange(0,self.numchannels) self.data2plot = self.data self.space_data() #self.time_view() self.redraw(None) def datahandler(data=None): pass
class MPLTest: def __init__(self): # Minimal gtk initialization self.builder = gtk.Builder() self.builder.add_from_file("mpltest.glade") self.builder.connect_signals(self) # Create a matplotlib figure with a plot self.figure = Figure(figsize=(5, 4), dpi=100) self.a = self.figure.add_subplot(111) f, y = self.gen_1dist() self.a.plot(f, y) # Place the matplotlib figure into a container self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.builder.get_object('viewport1').add(self.canvas) # This one is called when the main window is destroyed (i.e. when # delete_event returns null) def on_main_window_destroy(self, widget, data=None): print "destroy signal occurred" gtk.main_quit() # This one is called when the main window close-button is clicked def on_main_window_delete_event(self, widget, event, data=None): # If you return FALSE in the "delete_event" signal handler, # GTK will emit the "destroy" signal. Returning TRUE means # you don't want the window to be destroyed. # This is useful for popping up 'are you sure you want to quit?' # type dialogs. print "delete event occurred" # Change FALSE to TRUE and the main window will not be destroyed # with a "delete_event". return False def gen_1dist(self): f = arange(0.0, 3.0, 0.01) y = sin(2 * pi * f * f) return f, y def gen_2dist(self): f = arange(0.0, 3.0, 0.01) y = sin(2 * pi * f * f) + sin(1.1 * 2 * pi * f * f) return f, y def singleDistanceClicked(self, widget, data=None): print 'single distance clicked' f, y = self.gen_1dist() self.a.clear() self.a.plot(f, y) self.canvas.draw() def twoDistanceClicked(self, widget, data=None): print 'two distance clicked' f, y = self.gen_2dist() self.a.clear() self.a.plot(f, y) self.canvas.draw() def run(self): self.builder.get_object("window1").show_all() gtk.main()
class _Matplotlib: def __init__(self, pp, progressbar): self.pp = pp self.pb = progressbar self.figure = pylab.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, pp["MainWindow"]) self.pp["BoxPlotArea"].pack_start(self.toolbar, expand=False, fill=False) self.pp["BoxPlotArea"].pack_start(self.canvas, expand=True, fill=True) self.canvas.connect("button_press_event", self.on_button_press_event) self.l = 0 self.dataAreOld = True self.pathLength = None self.pathId = None self.dl = None def get_x_cursor_position(self, event): gca = self.figure.gca() ap = gca.get_position() xmin, xmax = gca.get_xbound() x, y = self.canvas.get_width_height() posx = ((event.x / x) - ap.x0) * (1 / (ap.x1 - ap.x0)) sx = (posx * (xmax - xmin)) + xmin return sx def on_button_press_event(self, w, event): if not event.type == gtk.gdk._2BUTTON_PRESS \ or not event.button == 1: return False l = self.get_x_cursor_position(event) self.pp["PathScale"].set_value(l) return True def selectData(self, x, ys): self.x = x self.ys = ys if not self.pathLength == self.pp.pathLength \ or not self.pathId == self.pp.pathId \ or not self.dl == self.pp.dl: self.dataAreOld = True self.pathId = self.pp.pathId self.pathLength = self.pp.pathLength self.dl = self.pp.dl self.l = 0 self.datas = list() else: self.dataAreOld = False def init_pulse(self): if self.dataAreOld: self.pb.set_text("Generating datas...") self.pb.set_fraction(0) glib.idle_add(self.getData_pulse) else: glib.idle_add(self.genPlot_pulse) return False def getData_pulse(self): d = [ self.l, ] d.extend(self.pp.client.problem.configAtParam(self.pathId, self.l)) self.datas.append(d) self.l += self.dl if self.l < self.pathLength: self.pb.set_fraction(self.l / self.pathLength) return True else: self.pb.set_fraction(1) glib.idle_add(self.genPlot_pulse) return False def genPlot_pulse(self): self.pb.set_text("Generating plots...") self.npdatas = np.matrix(self.datas) self.figure.clf() gca = pylab.gca() for elt in self.ys: pylab.plot(self.npdatas[:, self.x[1]], self.npdatas[:, elt[1]], label=elt[0]) gca.set_xlabel(self.x[0]) pylab.legend(loc='best') self.canvas.draw() self.pb.set_text("Idle") return False
class TesiDogs: """This is the application main class - there is only one class because socialists don't believe in the class system.""" def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("tesidog.glade") dic = {"mainwindowdestroy" : gtk.main_quit, "fwdbtnclicked" : self.LoadNextFrame, "backbtnclicked" : self.LoadPreviousFrame, "file1fileset":self.FileLoad, "zoomoutbtnclicked": self.ZoomOut, "zoominbtnclicked":self.ZoomIn, "panleftbtnclicked":self.PanLeft, "panrightbtnclicked":self.PanRight, "pandownbtnclicked":self.PanDown, "panupbtnclicked":self.PanUp, "mainwindowkeypress":self.GetKeyPress, "basebtnclicked":self.BaseButtonClicked, "tailbtnclicked":self.TailButtonClicked, "nolinebtnclicked":self.NoLineButtonClicked, "drawtailendbtnclicked":self.DrawTailEndButtonClicked, "autorunbtnclicked":self.AutorunButtonClicked, "pklchoosefileset":self.PickleFileSet, "imagesavebtnclicked":self.ShowImageSaveDialog, "imagesaveokbtnclicked":self.SaveImageOkButtonClicked, "imagesavecancelbtnclicked":self.SaveImageCancelButtonClicked, "copytailbasepointbtnclicked":self.ShowCopyDialog, "copybaselinebtnclicked":self.ShowCopyDialog, "copyokbtnclicked":self.CopyOkButtonClicked, "copycancelbtnclicked":self.CopyCancelButtonClicked} self.builder.connect_signals(dic) self.conid=self.builder.get_object("statusbar").get_context_id("maps") self.curid=None self.copybtn=None filterplot2 = gtk.FileFilter() filterplot2.set_name("PKL") filterplot2.add_pattern("*.pkl") filterplot2.add_pattern("*.PKL") self.builder.get_object("pklchoose").add_filter(filterplot2) self.images=[] self.clickstate="none" self.linewidth=3. self.circleradius=2 self.circlealpha=0.4 self.taillinealpha=0.7 self.points=[] self.currentbase1=None self.currentbase2=None self.currenttail1=None self.baseline=None self.hoverline=None self.tailline=None self.paraline=None self.autorun=True self.datafile=None self.datastr=None self.builder.get_object("autorunbtn").set_sensitive(0) self.builder.get_object("toolbar1").set_sensitive(0) self.builder.get_object("pklchoose").set_sensitive(0) self.origin="lower" now = datetime.datetime.now() self.timestr=now.strftime("%d_%m_%H%M") self.textbuffer=gtk.TextBuffer() self.builder.get_object("dataview").set_buffer(self.textbuffer) def ClearLines(self): self.axis.clear() self.hoverline=None self.tailline=None def FileLoad(self, widget): self.points=[] self.folder=widget.get_filenames()[0] #get full path self.filenames = os.listdir(self.folder) i=0 while i<len(self.filenames): if self.filenames[i][-3:]!="BMP" and self.filenames[i][-3:]!="bmp": self.filenames.pop(i) else: self.filenames[i]=self.folder+"/"+self.filenames[i] i+=1 if len(self.filenames)==0: if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: No BMPs in given folder!") return 0 self.filenames.sort() try: self.datafilename=self.filenames[0].split("/")[-1].split("_")[0]+self.timestr+".dat" except: self.datafilename=self.filenames[0].split("/")[-1].split(".")[0]+self.timestr+".dat" self.builder.get_object("toolbar1").set_sensitive(1) if (self.filenames[0].split(".")[-1]=="bmp") or (self.filenames[0].split(".")[-1]=="BMP"): self.origin="lower" else: self.origin="upper" #Reset other data here - TODO for filen in self.filenames: #no faster self.images.append(mpimg.imread(filen)) self.figure=Figure() self.axis=self.figure.add_subplot(111) img=mpimg.imread(self.filenames[0]) self.frame=0 self.points.append({"base1":None, "base2":None, "tail1":None, "tail2":None, "angle":None, "side":None, "topbottom":None, "length":None}) self.axis.imshow(img, origin=self.origin) self.canvas=FigureCanvasGTKAgg(self.figure) self.canvas.show() self.canvas.mpl_connect('motion_notify_event', self.HoverOnImage) self.canvas.mpl_connect('button_release_event', self.CaptureClick) self.builder.get_object("npbox").pack_start(self.canvas, True, True) self.builder.get_object("pklchoose").set_sensitive(1) self.SetClickState("base1") self.UpdateInstructions("Zoom in and click two points along the dog's feet to draw the base line") def LoadNextFrame(self, widget): xlims=self.axis.get_xlim() ylims=self.axis.get_ylim() #Load next frame self.ClearLines() self.frame+=1 if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, 'Click mode: "'+self.clickstate+'". Autorun: ' + str(self.autorun) + '. Frame: '+ str(self.frame+1) + "/" + str(len(self.filenames)) +".") if (self.frame >= len(self.points)): #if image unseen, prepare dictionary - this code disallows skipping, assumption is the mother of all fuckups self.points.append({"base1":self.currentbase1, "base2":self.currentbase2, "tail1":self.currenttail1, "tail2":None, "angle":None, "side":None, "topbottom":None, "length":None}) img=self.images[self.frame] self.axis.imshow(img, origin=self.origin) self.axis.set_xlim(left=xlims[0], right=xlims[1]) self.axis.set_ylim(top=ylims[1], bottom=ylims[0]) if self.points[self.frame]["base2"] != None: #if already line, draw that one self.baseline = lines.Line2D(np.array([self.points[self.frame]["base1"][0],self.points[self.frame]["base2"][0]]), np.array([self.points[self.frame]["base1"][1],self.points[self.frame]["base2"][1]]), lw=self.linewidth, color='r', alpha=0.9) self.currentbase1=(self.points[self.frame]["base1"][0], self.points[self.frame]["base1"][1]) self.currentbase2=(self.points[self.frame]["base2"][0], self.points[self.frame]["base2"][1]) self.axis.add_line(self.baseline) self.DrawParallelLine() elif (self.points[self.frame]["base2"] == None) and (self.currentbase2!=None): #if not line, use previous one, don't think this is ever run self.baseline = lines.Line2D(np.array([self.currentbase1[0],self.currentbase2[0]]), np.array([self.currentbase1[1],self.currentbase2[1]]), lw=self.linewidth, color='r', alpha=0.9) self.axis.add_line(self.baseline) self.DrawParallelLine() if self.clickstate=="none": self.UpdateInstructions("Browsing mode. Use toolbar buttons to edit points. Autorun disabled. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) if self.points[self.frame]["tail2"] != None: #if already line, draw that one self.tailline = lines.Line2D(np.array([self.points[self.frame]["tail1"][0],self.points[self.frame]["tail2"][0]]), np.array([self.points[self.frame]["tail1"][1],self.points[self.frame]["tail2"][1]]), lw=self.linewidth, color='b', alpha=self.taillinealpha) self.axis.add_line(self.tailline) self.currenttail1=(self.points[self.frame]["tail1"][0], self.points[self.frame]["tail1"][1]) #bad hack to fix parallel line if (self.frame-1>=0): self.builder.get_object("backbtn").set_sensitive(1) else: self.builder.get_object("backbtn").set_sensitive(0) if (len(self.filenames)<=self.frame+1): self.builder.get_object("fwdbtn").set_sensitive(0) else: self.builder.get_object("fwdbtn").set_sensitive(1) self.canvas.draw() def LoadPreviousFrame(self, widget): xlims=self.axis.get_xlim() ylims=self.axis.get_ylim() #Load next frame self.ClearLines() self.frame-=1 img=self.images[self.frame] self.axis.imshow(img, origin=self.origin) self.axis.set_xlim(left=xlims[0], right=xlims[1]) self.axis.set_ylim(top=ylims[1], bottom=ylims[0]) if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, 'Click mode: "'+self.clickstate+'". Autorun: ' + str(self.autorun) + '. Frame: '+ str(self.frame+1) + "/" + str(len(self.filenames)) +".") if self.points[self.frame]["base2"] != None: #if already line, draw that one self.baseline = lines.Line2D(np.array([self.points[self.frame]["base1"][0],self.points[self.frame]["base2"][0]]), np.array([self.points[self.frame]["base1"][1],self.points[self.frame]["base2"][1]]), lw=self.linewidth, color='r', alpha=0.9) self.axis.add_line(self.baseline) self.currentbase1=(self.points[self.frame]["base1"][0], self.points[self.frame]["base1"][1]) self.currentbase2=(self.points[self.frame]["base2"][0], self.points[self.frame]["base2"][1]) self.DrawParallelLine() if self.clickstate=="none": self.UpdateInstructions("Browsing mode. Use toolbar buttons to edit points. Autorun disabled. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) if self.points[self.frame]["tail2"] != None: #if already line, draw that one self.tailline = lines.Line2D(np.array([self.points[self.frame]["tail1"][0],self.points[self.frame]["tail2"][0]]), np.array([self.points[self.frame]["tail1"][1],self.points[self.frame]["tail2"][1]]), lw=self.linewidth, color='b', alpha=self.taillinealpha) self.axis.add_line(self.tailline) self.currenttail1=(self.points[self.frame]["tail1"][0], self.points[self.frame]["tail1"][1]) #bad hack to fix parallel line if (len(self.filenames)<=self.frame+1): self.builder.get_object("fwdbtn").set_sensitive(0) else: self.builder.get_object("fwdbtn").set_sensitive(1) if (self.frame-1<0): self.builder.get_object("backbtn").set_sensitive(0) else: self.builder.get_object("backbtn").set_sensitive(1) self.canvas.draw() def HoverOnImage(self, event): if event.x!=None and event.y!=None and event.xdata!=None and event.ydata!=None: if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, 'Click mode: "'+self.clickstate+'", Autorun: ' + str(self.autorun) + '. Frame: '+ str(self.frame+1) + "/" + str(len(self.filenames)) + '. x=%d, y=%d'%(int(round(event.xdata)), int(round(event.ydata)))) if self.clickstate=="base2": if self.hoverline==None: self.hoverline = lines.Line2D(np.array([self.points[self.frame]["base1"][0],int(round(event.xdata))]), np.array([self.points[self.frame]["base1"][1],int(round(event.ydata))]), lw=self.linewidth, color='y', alpha=0.5) self.axis.add_line(self.hoverline) else: self.hoverline.set_data(np.array([self.points[self.frame]["base1"][0],int(round(event.xdata))]), np.array([self.points[self.frame]["base1"][1],int(round(event.ydata))])) self.canvas.draw() if self.clickstate=="tail2": if self.hoverline==None: self.hoverline = lines.Line2D(np.array([self.points[self.frame]["tail1"][0],int(round(event.xdata))]), np.array([self.points[self.frame]["tail1"][1],int(round(event.ydata))]), lw=self.linewidth, color='y', alpha=0.5) self.axis.add_line(self.hoverline) else: self.hoverline.set_data(np.array([self.points[self.frame]["tail1"][0],int(round(event.xdata))]), np.array([self.points[self.frame]["tail1"][1],int(round(event.ydata))])) self.canvas.draw() def ZoomIn(self, widget): xlims=self.axis.get_xlim() ylims=self.axis.get_ylim() xchange=abs(xlims[1]-xlims[0])*0.1 ychange=abs(ylims[1]-ylims[0])*0.1 self.axis.set_xlim(left=xlims[0]+xchange, right=xlims[1]-xchange) self.axis.set_ylim(top=ylims[1]-ychange, bottom=ylims[0]+ychange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def ZoomOut(self, widget): xlims=self.axis.get_xlim() ylims=self.axis.get_ylim() xchange=abs(xlims[1]-xlims[0])*0.111 ychange=abs(ylims[1]-ylims[0])*0.111 self.axis.set_xlim(left=xlims[0]-xchange, right=xlims[1]+xchange) self.axis.set_ylim(top=ylims[1]+ychange, bottom=ylims[0]-ychange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def PanLeft(self, widget): xlims=self.axis.get_xlim() xchange=abs(xlims[1]-xlims[0])*0.1 self.axis.set_xlim(left=xlims[0]-xchange, right=xlims[1]-xchange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def PanRight(self, widget): xlims=self.axis.get_xlim() xchange=abs(xlims[1]-xlims[0])*0.1 self.axis.set_xlim(left=xlims[0]+xchange, right=xlims[1]+xchange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def PanUp(self, widget): ylims=self.axis.get_ylim() ychange=abs(ylims[1]-ylims[0])*0.1 self.axis.set_ylim(top=ylims[1]+ychange, bottom=ylims[0]+ychange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def PanDown(self, widget): ylims=self.axis.get_ylim() ychange=abs(ylims[1]-ylims[0])*0.1 self.axis.set_ylim(top=ylims[1]-ychange, bottom=ylims[0]-ychange) self.builder.get_object("npbox").remove(self.canvas) self.builder.get_object("npbox").pack_start(self.canvas, True, True) def UpdateInstructions(self, message): self.builder.get_object("instructions").set_label(message) def CaptureClick(self, event): #self.clickstate can be "none", "base1", "base2", "tail1", "tail2" #Datastructure is list of dicts - one list for each frame #dict contains base1 point, base2 point, tail1 point, tail2 point #base can be changed per frame but is assumed from previous frame by default if self.clickstate=="none": return 0 elif event.x==None or event.y==None or event.xdata==None or event.ydata==None: return 0 elif self.clickstate=="base1": self.currentbase1=(int(round(event.xdata)), int(round(event.ydata))) self.points[self.frame]["base1"]=(int(round(event.xdata)), int(round(event.ydata))) self.SetClickState("base2") elif self.clickstate=="base2": self.currentbase2=(int(round(event.xdata)), int(round(event.ydata))) self.points[self.frame]["base2"]=(int(round(event.xdata)), int(round(event.ydata))) self.baseline = lines.Line2D(np.array([self.points[self.frame]["base1"][0],self.points[self.frame]["base2"][0]]), np.array([self.points[self.frame]["base1"][1],self.points[self.frame]["base2"][1]]), lw=self.linewidth, color='r', alpha=0.9) self.axis.add_line(self.baseline) if self.points[self.frame]["tail1"]!=None: self.DrawParallelLine() self.canvas.draw() if self.points[self.frame]["tail2"]!=None: self.CalculateAngle() if self.autorun==True: self.SetClickState("tail1") elif self.autorun==False: self.SetClickState("none") elif self.clickstate=="tail1": if self.points[self.frame]["tail1"]!=None: #point already there, must clear already=True else: already=False self.currenttail1=(int(round(event.xdata)), int(round(event.ydata))) self.points[self.frame]["tail1"]=(int(round(event.xdata)), int(round(event.ydata))) self.DrawParallelLine() if self.points[self.frame]["tail2"]!=None: self.CalculateAngle() if already==True: self.SetClickState("none") self.frame=self.frame-1 self.LoadNextFrame(None) if self.autorun==True: self.SetClickState("tail2") else: self.SetClickState("none") #Draw parallel line and circle elif self.clickstate=="tail2": self.points[self.frame]["tail2"]=(int(round(event.xdata)), int(round(event.ydata))) self.tailline = lines.Line2D(np.array([self.points[self.frame]["tail1"][0],self.points[self.frame]["tail2"][0]]), np.array([self.points[self.frame]["tail1"][1],self.points[self.frame]["tail2"][1]]), lw=self.linewidth, color='b', alpha=0.9) self.axis.add_line(self.tailline) self.canvas.draw() self.CalculateAngle() if (len(self.filenames)<=self.frame+1): self.SetClickState("none") self.UpdateInstructions("Finished") else: if self.autorun==True: self.UpdateInstructions("Click the end of the tail. Frame " + str(self.frame+2) + "/" + str(len(self.filenames))) self.LoadNextFrame(None) elif self.autorun==False: self.SetClickState("none") def DrawParallelLine(self): if self.currenttail1==None and self.points[self.frame]["tail1"]==None: return 0 if self.currenttail1==None: if self.points[self.frame]["tail1"]==None: return 0; else: self.currenttail1=self.points[self.frame]["tail1"] if self.points[self.frame]["base2"]!=None: #draw actual line if self.points[self.frame]["tail1"]!=None: circle=Circle(self.points[self.frame]["tail1"], radius=self.circleradius, alpha=self.circlealpha, color="yellow") #put here because here has check for tail1 basem=(float(self.points[self.frame]["base2"][1]-self.points[self.frame]["base1"][1]))/(float(self.points[self.frame]["base2"][0]-self.points[self.frame]["base1"][0])) c=self.points[self.frame]["base2"][1]-(basem*self.points[self.frame]["base2"][0]) ydiff=self.points[self.frame]["tail1"][1]-((basem*self.points[self.frame]["tail1"][0])+c) #fails if points[self.frame]["tail1"]==None - should never be called in this case self.paraline = lines.Line2D(np.array([self.points[self.frame]["base1"][0], self.points[self.frame]["base2"][0]]), np.array([self.points[self.frame]["base1"][1]+ydiff, self.points[self.frame]["base2"][1]+ydiff]), lw=self.linewidth, color='r', alpha=0.3) else: circle=Circle(self.currenttail1, radius=self.circleradius, alpha=self.circlealpha, color="yellow") #put here because here has check for tail1 basem=(float(self.points[self.frame]["base2"][1]-self.points[self.frame]["base1"][1]))/(float(self.points[self.frame]["base2"][0]-self.points[self.frame]["base1"][0])) c=self.points[self.frame]["base2"][1]-(basem*self.points[self.frame]["base2"][0]) ydiff=self.currenttail1[1]-((basem*self.currenttail1[0])+c) #fails if currenttail1==None - should never be called in this case self.paraline = lines.Line2D(np.array([self.points[self.frame]["base1"][0], self.points[self.frame]["base2"][0]]), np.array([self.points[self.frame]["base1"][1]+ydiff, self.points[self.frame]["base2"][1]+ydiff]), lw=self.linewidth, color='r', alpha=0.3) elif self.points[self.frame]["base2"] == None: if self.points[self.frame]["tail1"]!=None: circle=Circle(self.points[self.frame]["tail1"], radius=self.circleradius, alpha=self.circlealpha, color="yellow") #put here because here has check for tail1 basem=(float(self.currentbase2[1]-self.currentbase1[1]))/(float(self.currentbase2[0]-self.currentbase1[0])) c=self.currentbase2[1]-(basem*self.currentbase2[0]) ydiff=self.points[self.frame]["tail1"][1]-((basem*self.points[self.frame]["tail1"][0])+c) #fails if points[self.frame]["tail1"]==None - should never be called in this case self.paraline = lines.Line2D(np.array([self.currentbase1[0], self.currentbase2[0]]), np.array([self.currentbase1[1]+ydiff, self.currentbase2[1]+ydiff]), lw=self.linewidth, color='r', alpha=0.3) else: circle=Circle(self.currenttail1, radius=self.circleradius, alpha=self.circlealpha, color="yellow") #put here because here has check for tail1 basem=(float(self.currentbase2[1]-self.currentbase1[1]))/(float(self.currentbase2[0]-self.currentbase1[0])) c=self.currentbase2[1]-(basem*self.currentbase2[0]) ydiff=self.currenttail1[1]-((basem*self.currenttail1[0])+c) #fails if currenttail1==None - should never be called in this case self.paraline = lines.Line2D(np.array([self.currentbase1[0], self.currentbase2[0]]), np.array([self.currentbase1[1]+ydiff, self.currentbase2[1]+ydiff]), lw=self.linewidth, color='r', alpha=0.3) self.axis.add_line(self.paraline) self.axis.add_patch(circle) self.canvas.draw() def GetKeyPress(self, widget, event): if event.keyval==65307: #ESC key pressed self.SetClickState("none") def SetClickState(self, clickstate): if clickstate=="none": self.UpdateInstructions("Browsing mode. Use toolbar buttons to edit points. Autorun disabled. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) if self.hoverline!=None: #Remove hover line self.hoverline.set_data(np.array([0,0]),np.array([0,0])) self.canvas.draw() self.hoverline=None self.builder.get_object("nolinebtn").set_sensitive(0) #Make noline button insensitive self.builder.get_object("basebtn").set_sensitive(1) self.builder.get_object("tailbtn").set_sensitive(1) self.builder.get_object("tailendbtn").set_sensitive(1) self.builder.get_object("copytailbasepointbtn").set_sensitive(1) self.builder.get_object("copybaselinebtn").set_sensitive(1) self.builder.get_object("tailendbtn").set_sensitive(1) #Attempt to make next/prev buttons sensitive if (self.frame-1>=0): self.builder.get_object("backbtn").set_sensitive(1) if (len(self.filenames)>self.frame+1): self.builder.get_object("fwdbtn").set_sensitive(1) self.autorun=False self.builder.get_object("autorunbtn").set_sensitive(1) elif clickstate=="base1": self.UpdateInstructions("Click the first base point. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) if self.baseline!=None: self.baseline.set_data(np.array([0,0]),np.array([0,0])) self.canvas.draw() if self.paraline!=None: self.paraline.set_data(np.array([0,0]),np.array([0,0])) self.canvas.draw() self.builder.get_object("nolinebtn").set_sensitive(1) self.builder.get_object("basebtn").set_sensitive(0) self.builder.get_object("tailbtn").set_sensitive(0) self.builder.get_object("tailendbtn").set_sensitive(0) self.builder.get_object("backbtn").set_sensitive(0) self.builder.get_object("fwdbtn").set_sensitive(0) self.builder.get_object("copytailbasepointbtn").set_sensitive(0) self.builder.get_object("copybaselinebtn").set_sensitive(0) elif clickstate=="base2": self.UpdateInstructions("Click the second base point. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) elif clickstate=="tail1": self.UpdateInstructions("Click the base of the tail on the dog. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) self.builder.get_object("nolinebtn").set_sensitive(1) self.builder.get_object("basebtn").set_sensitive(0) self.builder.get_object("tailbtn").set_sensitive(0) self.builder.get_object("tailendbtn").set_sensitive(0) self.builder.get_object("backbtn").set_sensitive(0) self.builder.get_object("fwdbtn").set_sensitive(0) self.builder.get_object("copytailbasepointbtn").set_sensitive(0) self.builder.get_object("copybaselinebtn").set_sensitive(0) elif clickstate=="tail2": if self.points[self.frame]["tail1"]==None: self.SetClickState("none") if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: First tail point not set!") return None else: self.UpdateInstructions("Click the end of the tail. Frame " + str(self.frame+1) + "/" + str(len(self.filenames))) if self.tailline!=None: self.tailline.set_data(np.array([0,0]),np.array([0,0])) self.canvas.draw() self.builder.get_object("nolinebtn").set_sensitive(1) self.builder.get_object("basebtn").set_sensitive(0) self.builder.get_object("tailbtn").set_sensitive(0) self.builder.get_object("tailendbtn").set_sensitive(0) self.builder.get_object("backbtn").set_sensitive(0) self.builder.get_object("fwdbtn").set_sensitive(0) self.builder.get_object("copytailbasepointbtn").set_sensitive(0) self.builder.get_object("copybaselinebtn").set_sensitive(0) #Push changed message to statusbar self.clickstate=clickstate if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, 'Changed click mode to "'+clickstate+'". Autorun: ' + str(self.autorun) + '. Frame: '+ str(self.frame+1) + "/" + str(len(self.filenames)) +".") def BaseButtonClicked(self, widget): self.SetClickState("base1") def TailButtonClicked(self, widget): self.SetClickState("tail1") def DrawTailEndButtonClicked(self, widget): self.SetClickState("tail2") def NoLineButtonClicked(self, widget): self.SetClickState("none") def AutorunButtonClicked(self, widget): self.autorun=True self.builder.get_object("autorunbtn").set_sensitive(0) def CalculateAngle(self): #Angle always measured from normal, above and below #Find line between tail2 and tail1 graderror=False try: tailm=(float(self.points[self.frame]["tail2"][1]-self.points[self.frame]["tail1"][1]))/(float(self.points[self.frame]["tail2"][0]-self.points[self.frame]["tail1"][0])) tailc=self.points[self.frame]["tail2"][1]-(tailm*self.points[self.frame]["tail2"][0]) except: #Assume divide by zero error poix=self.points[self.frame]["tail2"][0] graderror=True try: basem=(float(self.points[self.frame]["base2"][1]-self.points[self.frame]["base1"][1]))/(float(self.points[self.frame]["base2"][0]-self.points[self.frame]["base1"][0])) basec=self.points[self.frame]["base2"][1]-(basem*self.points[self.frame]["base2"][0]) except: poix=self.points[self.frame]["base2"][0] graderror=True if graderror==False: poix=((tailc-basec)/(basem-tailm)) try: poiy=(basem*poix)+basec except: poiy=(tailm*poix)+tailc #if both fail then divergent self.points[self.frame]["angle"]=abs(90-math.degrees(math.acos((((self.points[self.frame]["tail2"][0] - poix)*(self.points[self.frame]["base1"][0] - poix)) + ((self.points[self.frame]["tail2"][1] - poiy)*(self.points[self.frame]["base1"][1] - poiy)))/(math.sqrt( ((math.pow(self.points[self.frame]["tail2"][0] - poix,2)) + (math.pow(self.points[self.frame]["tail2"][1] - poiy,2))) * ( ((math.pow(self.points[self.frame]["base1"][0] - poix,2)) + (math.pow(self.points[self.frame]["base1"][1] - poiy,2))))) )))) if ((self.points[self.frame]["tail2"][0]-self.points[self.frame]["tail1"][0])>=0): self.points[self.frame]["side"]="R" else: self.points[self.frame]["side"]="L" if ((self.points[self.frame]["tail2"][1]-self.points[self.frame]["tail1"][1])>=0): self.points[self.frame]["topbottom"]="T" else: self.points[self.frame]["topbottom"]="B" self.points[self.frame]["length"]=math.sqrt(pow(self.points[self.frame]["tail2"][1]-self.points[self.frame]["tail1"][1],2) + pow(self.points[self.frame]["tail2"][0]-self.points[self.frame]["tail1"][0],2) ) self.SaveData() def SaveData(self): #get datastr from dictionary #save that, pickle dictionary base1xlist=[] base1ylist=[] base2xlist=[] base2ylist=[] tail1xlist=[] tail1ylist=[] tail2xlist=[] tail2ylist=[] anglelist=[] sidelist=[] topbottomlist=[] lengthlist=[] for item in self.points: try: base1xlist.append(item["base1"][0]) except: base1xlist.append("NA") try: base1ylist.append(item["base1"][1]) except: base1ylist.append("NA") try: base2xlist.append(item["base2"][0]) except: base2xlist.append("NA") try: base2ylist.append(item["base2"][1]) except: base2ylist.append("NA") try: tail1xlist.append(item["tail1"][0]) except: tail1xlist.append("NA") try: tail1ylist.append(item["tail1"][1]) except: tail1ylist.append("NA") try: tail2xlist.append(item["tail2"][0]) except: tail2xlist.append("NA") try: tail2ylist.append(item["tail2"][1]) except: tail2ylist.append("NA") try: if item["angle"]!=None: anglelist.append(item["angle"]) else: anglelist.append("NA") except: anglelist.append("NA") try: if item["side"]!=None: sidelist.append(item["side"]) else: sidelist.append("NA") except: sidelist.append("NA") try: if item["topbottom"]!=None: topbottomlist.append(item["topbottom"]) else: topbottomlist.append("NA") except: topbottomlist.append("NA") try: if item["length"]!=None: lengthlist.append(item["length"]) else: lengthlist.append("NA") except: lengthlist.append("NA") for i in range(len(self.filenames)-len(self.points)): base1xlist.append("NA") base1ylist.append("NA") base2xlist.append("NA") base2ylist.append("NA") tail1xlist.append("NA") tail1ylist.append("NA") tail2xlist.append("NA") tail2ylist.append("NA") anglelist.append("NA") sidelist.append("NA") topbottomlist.append("NA") lengthlist.append("NA") self.datastr="id,base1x,base1y,base2x,base2y,tail1x,tail1y,tail2x,tail2y,angle,length,side,topbottom\n" for i in range(len(base1xlist)): self.datastr+=str(i+1) +","+str(base1xlist[i])+ ","+str(base1ylist[i]) + "," +str(base2xlist[i]) +"," +str(base2ylist[i]) + "," + str(tail1xlist[i]) + "," + str(tail1ylist[i]) + "," + str(tail2xlist[i]) + "," + str(tail2ylist[i]) + "," + str(anglelist[i]) + "," + str(lengthlist[i]) + "," + str(sidelist[i]) + "," + str(topbottomlist[i]) +"\n" self.textbuffer.set_text(self.datastr) self.datafile=open(self.datafilename, "w") self.datafile.write(self.datastr) self.datafile.close() picklefile=open(self.datafilename[:-3]+"pkl", "w") pickle.dump(self.points,picklefile) picklefile.close() def PickleFileSet(self, widget): self.SetClickState("none") pklfilename=widget.get_filenames()[0] try: picklefile=open(pklfilename, "r") temppoints=pickle.load(picklefile) picklefile.close() except: return 0 if len(temppoints)>len(self.filenames): if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: PKL file had more frames than frames loaded!") return 0 self.points=temppoints self.datafilename=pklfilename[:-3]+"dat" self.SaveData() i=0 while i < len(self.points): #hopefully this works, might need to initialise full list if self.points[i]["tail2"]==None: self.frame=i break i+=1 if i == len(self.points): if len(self.filenames)>len(self.points): self.frame = len(self.points) else: self.frame=0 #redraw canvas, load data self.frame=self.frame-1 self.LoadNextFrame(None) if self.frame==0: self.SetClickState("none") else: #assumes these are defined self.currentbase1=(self.points[self.frame-1]["base1"][0], self.points[self.frame-1]["base1"][1]) self.currentbase2=(self.points[self.frame-1]["base2"][0], self.points[self.frame-1]["base2"][1]) self.currenttail1=(self.points[self.frame-1]["tail1"][0], self.points[self.frame-1]["tail1"][1]) if self.points[self.frame]["base1"]==None: self.points[self.frame]["base1"]=self.currentbase1 if self.points[self.frame]["base2"]==None: self.points[self.frame]["base2"]=self.currentbase2 if self.points[self.frame]["tail1"]==None: self.points[self.frame]["tail1"]=self.currenttail1 self.frame=self.frame-1 self.LoadNextFrame(None) self.AutorunButtonClicked(None) self.SetClickState("tail2") def ShowImageSaveDialog(self, widget): self.builder.get_object("imagesavedialog").set_visible(1) def SaveImageCancelButtonClicked(self, widget): self.builder.get_object("imagesavedialog").set_visible(0) def SaveImageOkButtonClicked(self, widget): filename=self.builder.get_object("imagesavedialog").get_filenames()[0] if filename[-4:]!=".png" and filename[-4:]!=".PNG": filename=filename+".png" self.figure.savefig(filename, format="png") self.builder.get_object("imagesavedialog").set_visible(0) def ShowCopyDialog(self, widget): self.SetClickState("none") if gtk.Buildable.get_name(widget) == "copybaselinebtn": self.builder.get_object("copylabel").set_label("From which frame number (1-" + str(len(self.points))+") do you wish to copy the base line?") self.copybtn="base" else: self.builder.get_object("copylabel").set_label("From which frame number (1-" + str(len(self.points))+") do you wish to copy the tail basepoint?") self.copybtn="tail" self.builder.get_object("copydialog").set_visible(1) def CopyCancelButtonClicked(self, widget): self.builder.get_object("copydialog").set_visible(0) def CopyOkButtonClicked(self, widget): try: number=int(self.builder.get_object("entry1").get_text()) except: self.builder.get_object("copydialog").set_visible(0) if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: Frame number given was not an integer!") return 0 if number>len(self.points) or number<1: self.builder.get_object("copydialog").set_visible(0) if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: Frame number was not within valid range!") return 0 if self.copybtn=="base": if self.points[number-1]["base2"]==None: self.builder.get_object("copydialog").set_visible(0) if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: Frame does not have valid base line!") return 0 else: self.builder.get_object("copydialog").set_visible(0) self.points[self.frame]["base1"]=self.points[number-1]["base1"] self.currentbase1=self.points[number-1]["base1"] self.points[self.frame]["base2"]=self.points[number-1]["base2"] self.currentbase2=self.points[number-1]["base2"] self.frame=self.frame-1 self.LoadNextFrame(None) if self.points[self.frame]["tail2"]!=None: self.CalculateAngle() if self.copybtn=="tail": if self.points[number-1]["tail1"]==None: self.builder.get_object("copydialog").set_visible(0) if self.curid!=None: self.builder.get_object("statusbar").remove_message(self.conid, self.curid) self.curid=self.builder.get_object("statusbar").push(self.conid, "Error: Frame does not have valid tail basepoint!") return 0 else: self.builder.get_object("copydialog").set_visible(0) self.points[self.frame]["tail1"]=self.points[number-1]["tail1"] self.currenttail1=self.points[number-1]["tail1"] self.frame=self.frame-1 self.LoadNextFrame(None) if self.points[self.frame]["tail2"]!=None: self.CalculateAngle() return 0
class ScannerView(SlaveView): def __init__(self, scanner, width=400, height=300): self.scanner = scanner self.callback_ids = {} self.width = width self.height = height super(ScannerView, self).__init__() def on_button_debug__clicked(self, button): import IPython import inspect # Get parent from stack parent_stack = inspect.stack()[1] IPython.embed() def create_ui(self): self.fig = Figure(figsize=(4, 3), frameon=False) # Remove padding around axes. self.fig.subplots_adjust(bottom=0, top=1, right=1, left=0) self.canvas = FigureCanvas(self.fig) self.canvas.set_size_request(self.width, self.height) self.reset_axis() self.button_scan = gtk.Button('Scan') self.button_debug = gtk.Button('Debug') self.widget.pack_start(self.canvas, True, True, 0) for widget_i in (self.button_scan, self.button_debug): self.widget.pack_start(widget_i, False, False, 0) self.widget.show_all() self.button_scan.connect('clicked', lambda *args: self.enable_scan()) def reset_axis(self): self.fig.clf() self.axis = self.fig.add_subplot(111) self.axis.set_aspect(True) self.axis.set_axis_off() def cleanup(self): for callback_id in ['frame', 'symbol']: if callback_id in self.callback_ids: self.scanner.disconnect(self.callback_ids[callback_id]) del self.callback_ids[callback_id] def disable_scan(self): self.cleanup() self.scanner.disable_scan() self.button_scan.set_sensitive(True) def enable_scan(self): self.reset_axis() self.scanner.reset() self.scanner.enable_scan() self.button_scan.set_sensitive(False) self.callback_ids['frame'] = self.scanner.connect('frame-update', self.on_frame_update) self.callback_ids['symbol'] = self.scanner.connect('symbols-found', self.on_symbols_found) def __dealloc__(self): self.cleanup() def on_frame_update(self, scanner, np_img): self.axis.clear() self.axis.set_axis_off() self.axis.imshow(np_img) self.canvas.draw() def on_symbols_found(self, scanner, np_img, symbols): patches = [] if symbols: for symbol_record_i in symbols: symbol_i = symbol_record_i['symbol'] location_i = Polygon(symbol_i.location) patches.append(location_i) patch_collection = PatchCollection(patches, cmap=mpl.cm.jet, alpha=0.4) self.on_frame_update(scanner, np_img) self.axis.add_collection(patch_collection) self.canvas.draw() self.disable_scan()
class Plotter(): def __init__(self, context, data, fitfunction): self.context = context self.data = data self.fitfunction = fitfunction self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(600, 400) # set min size self.markers = [ '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd' ] self.colors = [ 'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple', 'white' ] self.pstyle = [ 'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '', '25', '', '', '20', '15', '', '', '20', '15' ] self.styledict = {} self.styledict["style"] = 'bmh' self.styledict["point_style"] = 's' self.styledict["point_size"] = '6' self.styledict["point_color"] = 'red' self.styledict["point_alpha"] = '0.8' self.styledict["line_color"] = 'black' self.styledict["line_width"] = '2' self.styledict["band_color"] = 'black' self.styledict["band_alpha"] = '0.3' self.styledict["title_size"] = '25' self.styledict["xtitle_size"] = '20' self.styledict["xlabel_size"] = '15' self.styledict["ytitle_size"] = '20' self.styledict["ylabel_size"] = '15' self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1] self.plot_labels = [] self.plot_labels.append(data.labels[3] + " vs " + data.labels[0]) # plot title self.plot_labels.append(data.labels[0]) # x-axis title self.plot_labels.append(data.labels[3]) # y-axis title self.plot_labels.append("[Gy]") # x-axis unit self.plot_labels.append(" ") # y-axis unit #print plt.style.available self.fit_toggle = 'active' self.points_toggle = 1 self.function_toggle = 1 self.err_toggle = 1 self.ci_func_toggle = 1 self.ci_points_toggle = 1 toolbar = NavigationToolbar(self.canvas, self) toolbarbox = gtk.HBox() image = gtk.Image() image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR) options_button = gtk.Button() options_button.add(image) image2 = gtk.Image() image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR) refresh_button = gtk.Button() refresh_button.add(image2) toolbarbox.pack_start(toolbar, True, True) toolbarbox.pack_end(options_button, False, True) toolbarbox.pack_end(refresh_button, False, True) self.vbox = gtk.VBox() self.vbox.pack_start(toolbarbox, False, False) self.vbox.pack_start(self.canvas, True, True) # signals self.canvas.mpl_connect('pick_event', self.on_pick) options_button.connect('clicked', self.mpl_options) refresh_button.connect('clicked', self.on_refresh_clicked) def on_pick(self, event): artist = event.artist xmouse, ymouse = event.mouseevent.xdata, event.mouseevent.ydata x, y = artist.get_xdata(), artist.get_ydata() ind = event.ind print 'Artist picked:', event.artist print '{} vertices picked'.format(len(ind)) print 'Pick between vertices {} and {}'.format(min(ind), max(ind)) print 'x, y of mouse: {:.2f},{:.2f}'.format(xmouse, ymouse) print 'Data point:', x[ind[0]], y[ind[0]] print self.context.log('Data point:\t ' + str(x[ind[0]]) + '\t' + str(y[ind[0]])) self.context.treeview.treeview.set_cursor(min(ind)) self.context.treeview.treeview.grab_focus() def mpl_options(self, button): """Create GTKDialog containing options for plotting and connect signals.""" mpl_options_dialog = MPLOptions(self.context, self) def on_refresh_clicked(self, button): """Refresh canvas - plot everything again""" self.plotting() def plotvline(self, **kwargs): self.ax1.axvline(**kwargs) def plothline(self, **kwargs): self.ax1.axhline(**kwargs) def replot(self): self.canvas.draw() def plotting(self): """Generating matplotlib canvas""" plt.style.use(self.pstyle[0]) self.ax1 = self.fig.add_subplot(111) self.ax1.clear() if self.points_toggle == 1: self.ax1.errorbar(self.data.get_xdata(), self.data.get_ydata(), self.data.get_yerr(), fmt='none', ecolor='black', elinewidth=0.5, capsize=0.5, capthick=0.5) self.ax1.plot(self.data.get_xdata(), self.data.get_ydata(), color=self.pstyle[3], label=self.data.labels[3], marker=self.pstyle[1], alpha=float(self.pstyle[4]), linestyle='None', markersize=float(self.pstyle[2]), picker=float(self.pstyle[2])) self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3], fontsize=int(self.pstyle[13])) self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(-0.1, max(20, max(self.data.get_xdata())) * 1.1, 0.05) if (self.fit_toggle == 'active'): if len(self.data.get_xdata()) >= 3: print "before fit", self.fitfunction.params print "before fit", self.fitfunction.params print "xdata", self.data.get_xdata() print "ydata", self.data.get_ydata() self.fitfunction.fit_function(self.data.get_xdata(), self.data.get_ydata(), self.data.get_yerr()) print "after fit", self.fitfunction.params print "after fit", self.fitfunction.params self.context.functiontab.function_changed() else: self.context.log("Too few data to fit the function!") if self.function_toggle == 1: y = self.fitfunction.func(x, self.fitfunction.params) self.ax1.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) if self.ci_func_toggle == 1 and self.fit_toggle == 'active': conf = confidence(x, self.data.get_xdata(), len(x), np.mean(self.data.get_xdata()), self.fitfunction.dof, self.fitfunction.rmse) upper = self.fitfunction.func(x, self.fitfunction.params) + conf lower = self.fitfunction.func(x, self.fitfunction.params) - conf self.ax1.fill_between(x, lower, upper, facecolor=self.pstyle[7], alpha=float(self.pstyle[8])) if self.ci_points_toggle == 1: upper = self.fitfunction.func( x, self.fitfunction.params) + confidence_points( x, self.fitfunction.std_err) lower = self.fitfunction.func( x, self.fitfunction.params) - confidence_points( x, self.fitfunction.std_err) self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8])) if self.err_toggle == 1: upper = self.fitfunction.func( x, self.fitfunction.params) + uncertainty( x, self.fitfunction.std_err) lower = self.fitfunction.func( x, self.fitfunction.params) - uncertainty( x, self.fitfunction.std_err) self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8])) self.fig.subplots_adjust(left=0.13, right=0.96, top=0.91, bottom=0.13, hspace=0.04) self.canvas.draw() print self.fitfunction.params print self.fitfunction.std_err
class asaplotgui(asaplotbase): """ ASAP plotting class based on matplotlib. """ def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): """ Create a new instance of the ASAPlot plotting class. If rows < 1 then a separate call to set_panels() is required to define the panel layout; refer to the doctext for set_panels(). """ v = vars() del v['self'] asaplotbase.__init__(self, **v) matplotlib.rcParams['interactive'] = True matplotlib.interactive = True _pylab_helpers.Gcf.destroy(0) self.canvas = FigureCanvas(self.figure) # Simply instantiating this is enough to get a working toolbar. self.figmgr = FigureManagerGTKAgg(self.canvas, 1) def dest_callback(val): self.is_dead = True self.figmgr.window.destroy() self.window = self.figmgr.window self.window.connect("destroy", dest_callback ) self.window.set_title('ASAP Plotter - GTK') #self.canvas.set_size_request(800,600) _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr #self.canvas.show() def map(self): """ Reveal the ASAPlot graphics window and bring it to the top of the window stack. """ if self.is_dead: raise RuntimeError( "No plotter to show. Not yet plotted or plotter is closed." ) self.window.deiconify() #self.window.lift() def quit(self): """ Destroy the ASAPlot graphics window. """ self.is_dead = True if not self.figmgr: return #self.window.destroy() _pylab_helpers.Gcf.destroy(self.figmgr.num) del self.window, self.canvas, self.figmgr self.window = None self.canvas = None self.figmgr = None def show(self, hardrefresh=True): """ Show graphics dependent on the current buffering state. """ if self.is_dead: raise RuntimeError( "No plotter to show (not yet plotted or closed)." ) if not self.buffering: if hardrefresh: asaplotbase.show(self, hardrefresh) self.window.deiconify() self.canvas.draw() self.window.show_all() def terminate(self): """ Clear the figure. """ if not self.window: asaplog.push( "No plotter window to terminate." ) asaplog.post( "WARN" ) return self.window.destroy() def unmap(self): """ Hide the ASAPlot graphics window. """ if not self.window: asaplog.push( "No plotter window to unmap." ) asaplog.post( "WARN" ) return self.window.wm_withdraw()
class makewin(): def __init__(self): self.win = gtk.Window() #win.connect("destroy", lambda x: gtk.main_quit()) self.win.connect("delete-event", self.hideinsteadofdelete) self.win.set_default_size(400,300) self.win.set_title("Embedding in GTK") vbox = gtk.VBox() self.win.add(vbox) self.f = Figure(figsize=(5,4), dpi=100) sw = gtk.ScrolledWindow() vbox.pack_start(sw) #self.win.add (sw) # A scrolled window border goes outside the scrollbars and viewport sw.set_border_width (10) # policy: ALWAYS, AUTOMATIC, NEVER sw.set_policy (hscrollbar_policy=gtk.POLICY_AUTOMATIC, vscrollbar_policy=gtk.POLICY_ALWAYS) self.canvas = FigureCanvas(self.f) # a gtk.DrawingArea #vbox.pack_start(canvas) self.canvas.set_size_request(300,200) sw.add_with_viewport (self.canvas) manager = get_current_fig_manager() # you can also access the window or vbox attributes this way toolbar = manager.toolbar #vbox.pack_start(canvas) toolbar = NavigationToolbar(self.canvas, self.win) vbox.pack_start(toolbar, False, False) self.win.show_all() #gtk.main() def hideinsteadofdelete(self,widget,ev=None): print widget widget.hide() return True def plot_data(self,xi,yi,zi,intx,inty): """provide... xi=grid x data yi=grided y data zi=interpolated MEG data for contour intx and inty= sensor coords for channel plotting""" tstart = time.time() zim = ma.masked_where(isnan(zi),zi) self.p.pcolor(xi,yi,zim,shading='interp',cmap=cm.jet) self.p.contourf(xi,yi,zim,cmap=cm.jet) self.p.scatter(intx,inty, alpha=.75,s=3) def plot_data_loop(self,xi,yi,zi,intx,inty): pass def printlabels(self,chanlocs, labels): #if labels != None: count = 0 for l in labels: p.text(chanlocs[1,count], chanlocs[0,count], l, alpha=1, fontsize=9) count = count + 1 def titles(titletxt): print def display(self, data, chanlocs, data2=None, subplot='off', animate='off', quiver='off', title=None, labels=None, colorbar='off'): #self.p = f.add_subplot(111) if len(shape(chanlocs)) != 2: print 'Chanlocs shape error. Should be 2D array "(2,N)"' print 'transposing' chanlocs = chanlocs.T print chanlocs.shape #xi, yi = mgrid[-.5:.5:67j,-.5:.5:67j] xi, yi = mgrid[chanlocs[1,:].min():chanlocs[1,:].max():57j,chanlocs[0,:].min():chanlocs[0,:].max():57j] intx=chanlocs[1,:] inty=chanlocs[0,:] if shape(shape(data))[0]==2: #more than a single vector, need to animate or subplot print '2d array of data' z = data[0,:] if delaunay == 'yes': print 'delaunay is set' tri = Triangulation(intx,inty) interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: #try griddata method print 'delaunay is off' zi = griddata(intx,inty,z,xi,yi) if animate == 'on': #single plot with a loop to animate p.scatter(intx,inty, alpha=.5,s=.5) print 'animating' for i in range(0, shape(data)[0]): dataslice=data[i,:]; z = dataslice if delaunay == 'yes': interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) p.contourf(xi,yi,zim,cmap=p.cm.jet, alpha=.8) if labels != None: printlabels(chanlocs, labels) p.draw() if subplot == 'on': print 'suplotting' for i in range(0, shape(data)[0]): spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots #self.p = f.add_subplot(spnum,spnum,i+1) self.p = self.f.add_subplot(spnum,spnum,i+1);#axis('off') dataslice=data[i,:]; self.p.scatter(intx,inty, alpha=.75,s=3) z = dataslice if delaunay == 'yes': interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) self.p.contourf(xi,yi,zim,cmap=cm.jet, alpha=.8) self.p.axis('off') if labels != None: printlabels(chanlocs, labels) if title != None: self.p.title(str(title[i])) else: pass #self.p.title(str(i)) if quiver == 'on': print 'suplotting quiver' for i in range(0, shape(data)[0]): spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots fig.add_subplot(spnum,spnum,i+1);#axis('off') dataslice=data[i,:]; p.scatter(intx,inty, alpha=.75,s=3) z = dataslice print 'size or z', size(z) for xx in range(0,size(z)): quiver(intx[xx],inty[xx], z[xx], data2[xx]) p.axis('off') if labels != None: printlabels(chanlocs, labels) if colorbar == 'on': p.colorbar() else: z = data if delaunay == 'yes': print 'delaunay is set' tri = Triangulation(intx,inty) interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: print 'delaunay is off' zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) self.plot_data(xi,yi,zi,intx,inty) if labels != None: printlabels(chanlocs, labels) if colorbar == 'on': p.colorbar(cm) self.canvas.draw()
class ViewerGTK: hicolor = gtk.gdk.Color(20000,65000,20000) locolor = gtk.gdk.Color(65000,65000,65000) def __init__(self): self.wTree = gtk.Builder() self.wTree.add_from_file('viewer/gui.xml') dic = { 'on_window_destroy' : self.quit } self.wTree.connect_signals(dic) f = Figure(figsize=(5,4), dpi=100) self.subplot = f.add_subplot(111) self.subplot.grid(True) self.subplot.plot() #self.msgls = gtk.ListStore(gobject.TYPE_PYOBJECT,str,str,str,str) self.msgls = gtk.ListStore(str,str,str,str) self.wTree.get_object('tv_messages').set_model(self.msgls) for colit,colname in enumerate(['device','message','value']): cell = gtk.CellRendererText() col = gtk.TreeViewColumn(colname,cell) col.add_attribute(cell,'text',colit+1) self.wTree.get_object('tv_messages').append_column(col) self.canvas = FigureCanvas(f) self.wTree.get_object('hbox').add(self.canvas) self.wTree.get_object('window').set_default_size(640,480) self.wTree.get_object('window').show_all() gobject.timeout_add(500, self.timer_callback) self.rows = {} self.values = {} self.dbg = 0 def data_callback(self, data): dev = data['device'] msg = data['message'] date = data['date'] for vname, value in data['values']: xs = '%s_%s'%(msg.name,vname) if xs in self.values: self.values[xs].append( (date,value) ) if len(self.values[xs]) > 100: self.values[xs].pop(0) else: self.values[xs] = [(date,value)] self.rows[xs] = self.msgls.append((dev.name,msg.name,vname,xs)) def twilite_callback(self, xs): self.msgls[ self.rows[xs] ][0] = self.locolor def timer_callback(self): self.subplot.cla() for vs in self.values.values(): pt = [ d for (d,v) in vs] pv = [ v for (d,v) in vs] self.subplot.plot(pt, pv, 'r') self.canvas.draw() return True def quit(self, widget): gtk.main_quit()
class ArrayMapper(gtk.Window, ScalarMapper, Observer): """ CLASS: ArrayMapper DESCR: """ def __init__(self, gridManager, X, channels, amp, addview3, view3, start_time=None, end_time=None): ScalarMapper.__init__(self, gridManager) gtk.Window.__init__(self) Observer.__init__(self) self.resize(512,570) self.set_title('Array data') self.view3 = view3 self.addview3 = addview3 self.channels = channels self.amp = amp self.trodes = [(gname, gnum) for cnum, gname, gnum in amp] self.X = X self.ax = None self.numChannels, self.numSamples = X.shape self.addview3destroy = False self.time_in_secs = False self.start_time = None self.end_time = None if ((start_time != None) & (end_time != None)) : self.time_in_secs = True self.start_time = start_time self.end_time = end_time vbox = gtk.VBox() vbox.show() self.add(vbox) self.fig = self.make_fig(start_time, end_time) if self.addview3: button = gtk.Button('Remove from View3') button.show() #button.set_active(False) vbox.pack_start(button, False, False) button.connect('clicked', self.view3_remove) if self.addview3destroy == False: self.broadcast(Observer.ARRAY_CREATED, self.fig, True, False) self.addview3Button = button self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.show() vbox.pack_start(self.canvas, True, True) hbox = gtk.HBox() hbox.show() vbox.pack_start(hbox, False, False) label = gtk.Label('Sample num') label.show() hbox.pack_start(label, False, False) scrollbar = gtk.HScrollbar() scrollbar.show() hbox.pack_start(scrollbar, True, True) if (self.time_in_secs == True): scrollbar.set_range(start_time, end_time) #scrollbar.set_increments(1,1) print "set_increments(%f, %f)" % ((end_time-start_time)/float(self.numSamples), (end_time-start_time)/float(self.numSamples)) scrollbar.set_increments((end_time-start_time)/float(self.numSamples), (end_time-start_time)/float(self.numSamples)) scrollbar.set_value(start_time + (end_time-start_time)/2.0) else: scrollbar.set_range(0, self.numSamples-1) scrollbar.set_increments(1,1) scrollbar.set_value(self.numSamples/2.0) scrollbar.connect('value_changed', self.set_sample_num) self.scrollbarIndex = scrollbar self.numlabel = gtk.Label(str(scrollbar.get_value())) self.numlabel.show() hbox.pack_start(self.numlabel,False, False) hbox2 = gtk.HBox() hbox2.show() toolbar = NavigationToolbar(self.canvas, self) toolbar.show() hbox2.pack_start(toolbar, True, True) button = gtk.Button('Coh. Here') button.show() hbox2.pack_start(button, False, False) button.connect('clicked', self.coh_here) vbox.pack_start(hbox2, False, False) self.set_sample_num(scrollbar) self.connect("destroy", self.on_destroy) def coh_here(self, button): val = self.scrollbarIndex.get_value() if (self.time_in_secs == True): val = (val*self.view3.eeg.freq)/1000 #convert val to points self.view3.offset = int(val - self.view3.newLength/2) #set the new view3 offset to the beginning of the window self.view3.compute_coherence() self.view3.plot_band() #I know I should be using the receiver. I really dislike that interface tho, so for now I'll be raw about it, until we get a better one. def view3_remove(self, button): #a switch in the array mapper to toggle view3 display if self.addview3destroy == False: self.addview3destroy = True self.broadcast(Observer.ARRAY_CREATED, self.fig, False, self.addview3destroy) self.addview3Button.set_label("Add to view3") else: self.addview3destroy = False self.broadcast(Observer.ARRAY_CREATED, self.fig, True, self.addview3destroy) self.addview3Button.set_label("Remove from view3") def on_destroy(self, widget): #take the view3 display out if we close the window self.view3_remove(self.addview3destroy) print "garbage collecting - unfortunately this doesn't prevent a segfault that will happen if you make a new arraymapper window and then try to drive the autoplay function with it. to be fixed in an upcoming patch, hopefully." gc.collect() def set_sample_num(self, bar): LO = self.view3.newLength/2 if (self.time_in_secs == True): LO = (LO*1000)/self.view3.eeg.freq #convert LO to ms val = float(bar.get_value()) ind = ((val - self.start_time) / (self.end_time - self.start_time) * self.numSamples) #print "ArrayMapper.set_sample_num() : ind=", ind datad = self.get_datad(ind) self.gridManager.set_scalar_data(datad) xdata = array([val, val], 'd') #print "shape of xdata is " , xdata.shape #for line in self.lines: # print "ArrayMapper.set_sample_num(): doing line " , line # line.set_xdata(xdata) self.lines[0].set_xdata(array([val-LO, val-LO], 'd')) self.lines[1].set_xdata(array([val, val], 'd')) #middle line self.lines[2].set_xdata(array([val+LO, val+LO], 'd')) else: ind = int(bar.get_value()) #print "ArrayMapper.set_sample_num(", ind, ")" datad = self.get_datad(ind) self.gridManager.set_scalar_data(datad) #xdata = array([ind, ind], 'd') #for line in self.lines: # line.set_xdata(xdata) self.lines[0].set_xdata(array([ind-LO, ind-LO], 'd')) self.lines[1].set_xdata(array([ind, ind], 'd')) #middle line self.lines[2].set_xdata(array([ind+LO, ind+LO], 'd')) if (self.time_in_secs == True): self.numlabel.set_text(str(float(bar.get_value()))) else: self.numlabel.set_text(str(int(bar.get_value()))) #print "self.fig.get_axes() = ", self.fig.get_axes() self.canvas.draw() if self.addview3: if self.addview3destroy == False: #don't signal unless we have to self.broadcast(Observer.ARRAY_CREATED, self.fig, False, False) #redraw the view3 version of the array #the second false is to say that we shouldn't destroy the display in view3 def get_datad(self, ind): slice = self.X[:,ind] datad = dict(zip(self.trodes, slice)) return datad def make_fig(self, start_time, end_time): fig = Figure(figsize=(8,8), dpi=72) self.lines = [] N = len(self.channels) self.ax = fig.add_subplot(1,1,1) #new singleplot configuration colordict = ['#A6D1FF','green','red','cyan','magenta','yellow','white'] minx = 0 maxx = 0 graph = [] for i, channel in enumerate(self.channels): #subplot syntax is numrows, numcolumns, subplot ID print "ArrayMapper.make_fig(): self.X is is " , self.X, type(self.X), len(self.X) print "ArrayMapper.make_fig(): channel is ", channel print "ArrayMapper.make_fig(): self.numSamples=", self.numSamples time_range = arange(self.numSamples) #print "start_time= ", start_time, "end_time =", end_time if ((start_time != None) & (end_time != None)): time_range = arange(start_time, end_time, (end_time - start_time)/self.numSamples) #print "time_range is ", time_range x = self.X[channel-1,:] if minx > min(x): minx = copy.deepcopy(min(x)) if maxx < max(x): maxx = copy.deepcopy(max(x)) color = colordict[((i-1)%7)] newp = self.ax.plot(time_range, x, color, label=("channel " + str(i+1))) newp[0].set_linewidth(4) graph.append(newp) self.ax.set_xlabel('index') self.ax.set_title('Evoked response') #self.ax.legend() fig.legend(graph,self.channels,'upper right') if ((start_time != None) & (end_time != None)): mid = start_time + (end_time - start_time)/2.0 else: mid = self.numSamples/2.0 #print "setting up line at (([%d, %d], [%d, %d])[0]" % (mid, mid, min(x), max(x)) LO = self.view3.newLength/2 #line = self.ax.plot([mid, mid], [minx, maxx],'w')[0] #left edge of window: line = self.ax.plot([mid-LO, mid-LO], [minx, maxx],'y')[0] self.ax.add_line(line) self.lines.append(line) #middle of window, where the scalar data comes from: line = self.ax.plot([mid, mid], [minx, maxx],'r')[0] self.ax.add_line(line) self.lines.append(line) #right edge of window line = self.ax.plot([mid+LO, mid+LO], [minx, maxx],'y')[0] self.ax.add_line(line) self.lines.append(line) self.ax.patch.set_facecolor('black') #transparency self.finishedFigure = fig return fig def recieve(self, event, *args): if event in (Observer.SET_SCALAR,): #move the scrollbar forward by the twidth, #except that this is always coming in in points, and we need to #convert to ms if self.time_in_secs is true newVal = args[0] if self.time_in_secs == True: newVal = ((newVal*1000)/self.view3.eeg.freq) self.scrollbarIndex.set_value(newVal) print "ARRAY MAPPER: RECIEVED SCALAR MESSAGE: ", newVal return
class MPLTest: def __init__(self): # Minimal gtk initialization self.builder = gtk.Builder() self.builder.add_from_file("mpltest.glade") self.builder.connect_signals(self) # Create a matplotlib figure with a plot self.figure = Figure(figsize=(5, 4), dpi=100) self.a = self.figure.add_subplot(111) f, y = self.gen_1dist() self.a.plot(f, y) # Place the matplotlib figure into a container self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.builder.get_object("viewport1").add(self.canvas) # This one is called when the main window is destroyed (i.e. when # delete_event returns null) def on_main_window_destroy(self, widget, data=None): print "destroy signal occurred" gtk.main_quit() # This one is called when the main window close-button is clicked def on_main_window_delete_event(self, widget, event, data=None): # If you return FALSE in the "delete_event" signal handler, # GTK will emit the "destroy" signal. Returning TRUE means # you don't want the window to be destroyed. # This is useful for popping up 'are you sure you want to quit?' # type dialogs. print "delete event occurred" # Change FALSE to TRUE and the main window will not be destroyed # with a "delete_event". return False def gen_1dist(self): f = arange(0.0, 3.0, 0.01) y = sin(2 * pi * f * f) return f, y def gen_2dist(self): f = arange(0.0, 3.0, 0.01) y = sin(2 * pi * f * f) + sin(1.1 * 2 * pi * f * f) return f, y def singleDistanceClicked(self, widget, data=None): print "single distance clicked" f, y = self.gen_1dist() self.a.clear() self.a.plot(f, y) self.canvas.draw() def twoDistanceClicked(self, widget, data=None): print "two distance clicked" f, y = self.gen_2dist() self.a.clear() self.a.plot(f, y) self.canvas.draw() def run(self): self.builder.get_object("window1").show_all() gtk.main()
class nice_gui(): def __init__(self, host, PORT): try: self.AWG = awg(host, PORT) except: print 'failed to connect to AWG' self.builder = gtk.Builder() gladefile = 'SCPI_GUI_V2.glade' self.builder.add_from_file(gladefile) #extract the useful objects from the gui self.win = self.builder.get_object('Charter') self.vbox1 = self.builder.get_object('vbox2') self.end_time_inp= self.builder.get_object('end_time_input') self.end_time_inp.set_text('0.15') self.amplitude_inp = self.builder.get_object('amplitude_input') self.amplitude_inp.set_text('4.5') self.sample_rate_inp = self.builder.get_object('sample_rate_input') self.sample_rate_inp.set_text('20000') #self.offset_inp = self.builder.get_object('offset_input') #self.offset_inp.set_text('0.0') self.waveform_inp = self.builder.get_object('waveform_input') self.waveform_inp.set_text('np.sin(100*t*np.pi*2.)*step(0.01,0.1)') self.execute_button = self.builder.get_object('execute_button') self.execute_button.set_sensitive(False) self.check_button_50ohm = self.builder.get_object('check_button_50ohm') #Create a matplotlib figure to show everything self.fig = Figure(figsize=(5,4), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.grid() self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.vbox1.pack_start(self.canvas) self.toolbar = NavigationToolbar(self.canvas, self.win) self.vbox1.pack_start(self.toolbar, False, False) #Connect handles to functions here self.handlers = { "gtk_main_quit": gtk.main_quit, "on_validate_button_clicked": self.validate, "on_execute_button_clicked": self.execute, "on_retrieve_button_clicked": self.retreive, "on_store_button_clicked": self.store, "on_end_time_input_changed": self.text_changed, "on_amplitude_input_changed": self.text_changed, "on_sample_rate_input_changed": self.text_changed, "on_waveform_input_changed": self.text_changed, "on_check_button_50ohm_toggled": self.text_changed, "on_check_button_50ohm_clicked": self.text_changed, } self.builder.connect_signals(self.handlers) #show the gui and give control to gtk self.win.show_all() gtk.main() def text_changed(self, widget): ''' Some of the settings have changed - disable the execute button SH : 11Mar2013 ''' self.execute_button.set_sensitive(False) def validate(self, button): ''' Validate the settings, and create the arb file to send to the AWG Checks to implement : minimum voltage, maximum voltage, maximum samples maximum sample rate, output impedance ''' self.end_time = float(self.end_time_inp.get_text()) self.amplitude = float(self.amplitude_inp.get_text()) self.sample_rate = int(self.sample_rate_inp.get_text()) #self.offset = float(self.offset_inp.get_text()) self.waveform = self.waveform_inp.get_text() print 'waveform :', self.waveform def step(start, stop): sig_time = self.t start_point = np.argmin(np.abs(sig_time - start)) end_point = np.argmin(np.abs(sig_time - stop)) output = np.zeros(len(sig_time)) output[start_point:end_point] = 1 return output t = np.arange(0,self.end_time,1./self.sample_rate) self.t = t if self.waveform[0]=='[': self.data = self.t*0 tmp = self.waveform.lstrip('[').rstrip(']') tmp_list = tmp.split(';') for i in range(len(tmp_list)-1): tmp1 = tmp_list[i].lstrip('(').rstrip(')') tmp1 = tmp1.split(',') tmp2 = tmp_list[i+1].lstrip('(').rstrip(')') tmp2 = tmp2.split(',') start_pt = np.argmin(np.abs(self.t-float(tmp1[0]))) end_pt = np.argmin(np.abs(self.t-float(tmp2[0]))) tmp_poly = np.polyfit([float(tmp1[0]),float(tmp2[0])],[float(tmp1[1]),float(tmp2[1])], 1) self.data[start_pt:end_pt] = tmp_poly[0]*self.t[start_pt:end_pt] +tmp_poly[1] pass else: self.data = eval(self.waveform) error = 0 if np.min(self.data) <0: print '!!! Error : data below minimim' error = 1 if self.data[0] != 0: print '!!! Error : first value isnt zero' error = 1 if self.data[-1] != 0: print '!!! Error : last value isnt zero' error = 1 if np.max(self.data) >4.5 : print '!!! Error : asking for a drive greater than 4.5' error = 1 self.amplitude = np.max(self.data) self.offset = np.min(self.data) print 'Validate!! end time : %.2f, amp : %.2f, sample : %d, offset : %.2f'%(self.end_time, self.amplitude, self.sample_rate, self.offset) if not self.check_button_50ohm.get_active(): self.amplitude = np.max(self.data)*0.5 self.offset = np.min(self.data)*0.5 self.output_string = self.create_arb_file(1, self.sample_rate, self.amplitude, self.offset, 60 , 'off', self.data) if error==0: self.execute_button.set_sensitive(True) else: print '!!! Unable to allow execution due to validation problems' #Update the figure with the new waveform self.ax.cla() self.ax.plot(t, self.data, '.-') self.ax.grid() self.ax.set_xlabel('Time (s)') self.ax.set_ylabel('Output (V)') self.canvas.draw() def create_arb_file(self, chan_count, samp_rate, amp, offset, mark_point, filt, data): ''' Create the arb file based on the settings given SH : 11Mar2013 ''' output = 'File Format:1.10\n' output += 'Checksum:0\n' output += 'Channel Count:%d\n'%(chan_count) output += 'Sample Rate:%.4f\n'%(samp_rate) output += 'High Level:%.5f\n'%(amp) output += 'Low Level:%.5f\n'%(offset) output += 'Marker Point:%d\n'%(mark_point) output += 'Data Type:"short"\n' output += 'Filter:"%s"\n'%(filt) output += 'Data Points:%d\n'%(len(data)) output += 'Data:\n' max_value = np.max(data) min_value = np.min(data) offset = (min_value+max_value)/2 multiplier = 32767/(max_value-offset) print multiplier, offset raw_data = [] cropped_data = [] for i in data: tmp = int(np.round((i-offset)*multiplier)) raw_data.append(tmp) #tmp = int(np.round(32767*i)) if tmp>32767: tmp=32767 print 'too large' if tmp<-32767: tmp = -32767 print 'too low' cropped_data.append(tmp) output+=str(tmp)+'\n' show_dac_values = 0 if show_dac_values: fig, ax = pt.subplots() ax.plot(raw_data,'.') ax.plot(cropped_data,'x') fig.canvas.draw(); fig.show() tmp = file('tmp_output.txt','w') tmp.write(output) tmp.close() return output def execute(self,button): ''' Download the data to the AWG, and set everything up so its ready to trigger SH : 11Mar2013 ''' self.AWG.reset_awg() self.AWG.download_data_to_awg(self.output_string) self.AWG.setup_arb_mode() self.AWG.setup_trigger() self.AWG.set_status_on() def retreive(self,button): ''' Going to implement something with MDSplus here SH : 11Mar2013 ''' print 'Retreive!!' def store(self,button): ''' Going to implement something with MDSplus here for the future SH : 11Mar2013 ''' print 'Store!!' self.error('BLAHHHHHH') def error(self, error_msg): self.dia = gtk.Dialog('TEST DIALOG', self.win, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) self.dia.vbox.pack_start(gtk.Label(error_msg)) self.dia.show_all() result = self.dia.run() self.dia.hide()
class DataManager(gtk.Window): # global variables needed to share among classes global labels ########################################################################################### def __init__(self): # init gtk::Window gtk.Window.__init__(self) self.set_default_size(600, 800) self.connect('destroy', lambda win: gtk.main_quit()) self.set_title('DOSEMATIC v0.1') # variable name -- TODO self.xvariable="Dose" self.xvar="D" self.xunits="Gy" self.yvariable="Yield" self.yvar="Y" self.yunits="" # main layout container main_eb = gtk.EventBox() # horizontal box hbox = gtk.HBox(False, 8) # vertical box VBOX = gtk.VBox(False, 0) main_eb.add(VBOX) #main_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(red=60000,green=60000,blue=60000)) self.add(main_eb) vbox1 = gtk.VBox(False,8) hbox.pack_start(vbox1, True, True) top_band = gtk.HBox() bottom_band = gtk.HBox() top_eb = gtk.EventBox() bottom_eb = gtk.EventBox() top_eb.add(top_band) bottom_eb.add(bottom_band) top_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0)) bottom_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0)) l1 = gtk.Label('DOSEMATIC v1.0 --- beta testing --- module 1, basic view') l2 = gtk.Label('author: Maciej Lewicki [email protected], [email protected]') top_band.add(l1) bottom_band.add(l2) hruler = gtk.HSeparator() hruler2 = gtk.HSeparator() VBOX.pack_start(top_eb,False,False) VBOX.pack_start(hruler,False,True,5) VBOX.pack_start(hbox,True,True) VBOX.pack_start(hruler2,False,True,5) VBOX.pack_end(bottom_eb,False,False) # TEXT SCREEN______________________________________________________ self.text = gtk.TextView() # TEXT VIEW self.text.set_wrap_mode(gtk.WRAP_WORD) # wrap words self.scroll_text = gtk.ScrolledWindow() # into scrollable env self.scroll_text.set_shadow_type(gtk.SHADOW_ETCHED_IN) self.scroll_text.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC) self.scroll_text.add(self.text) text_view_box = gtk.VBox(False,5) text_view_box.pack_start(self.scroll_text,True,True) #__________________________________________________________________ # ESTIMATOR________________________________________________________ estimator_box = gtk.HBox(False,5) self.estxt = gtk.TextView() self.estxt.set_wrap_mode(gtk.WRAP_WORD) self.scroll_estxt = gtk.ScrolledWindow() self.scroll_estxt.set_shadow_type(gtk.SHADOW_ETCHED_IN) self.scroll_estxt.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC) self.scroll_estxt.add(self.estxt) label = gtk.Label(self.yvariable+' = ') entry = gtk.Entry() entry.set_text("0.00") button = gtk.Button('Estimate '+self.xvariable) button.connect('clicked',self.y_estimate,entry) combo = gtk.combo_box_new_text() combo.append_text("Method A") combo.append_text("Method B") combo.append_text("Method C-original") combo.append_text("Method C-simplified") self.method="Method C-simplified" combo.set_active(3) combo.connect('changed', self.on_method_changed) ruler = gtk.HSeparator() grid = gtk.Table(2,4) grid.attach(label, 0,1,0,1) grid.attach(entry, 1,2,0,1) grid.attach(button, 0,2,1,2) grid.attach(ruler,0,2,2,3) grid.attach(combo,0,2,3,4) estimator_box.pack_start(grid,False,False) estimator_box.pack_start(self.scroll_estxt,True,True) #__________________________________________________________________ # FUNCTION TAB_____________________________________________________ function_box = gtk.HBox(False,5) self.ftxt = gtk.TextView() self.ftxt.set_wrap_mode(gtk.WRAP_WORD) self.scroll_ftxt = gtk.ScrolledWindow() self.scroll_ftxt.set_shadow_type(gtk.SHADOW_ETCHED_IN) self.scroll_ftxt.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC) self.scroll_ftxt.add(self.ftxt) label_Y = gtk.Label() label_Y.set_use_markup(True) label_Y.set_markup('Y = c + αD + βD<sup>2</sup>') self.entry_c = gtk.Entry() self.entry_c.set_width_chars(5) label_c = gtk.Label('c: ') self.entry_alpha = gtk.Entry() self.entry_alpha.set_width_chars(5) label_alpha = gtk.Label() label_alpha.set_use_markup(True) label_alpha.set_markup('α: ') self.entry_beta = gtk.Entry() self.entry_beta.set_width_chars(5) label_beta = gtk.Label() label_beta.set_use_markup(True) label_beta.set_markup('β: ') self.entry_sc = gtk.Entry() self.entry_sc.set_width_chars(5) label_sc = gtk.Label() label_sc.set_use_markup(True) label_sc.set_markup('σ(c): ') self.entry_salpha = gtk.Entry() self.entry_salpha.set_width_chars(5) label_salpha = gtk.Label() label_salpha.set_use_markup(True) label_salpha.set_markup('σ(α): ') self.entry_sbeta = gtk.Entry() self.entry_sbeta.set_width_chars(5) label_sbeta = gtk.Label() label_sbeta.set_use_markup(True) label_sbeta.set_markup('σ(β): ') table_f = gtk.Table(6,3) #table_f.attach(label_Y, False, False) table_f.attach(label_c,0,1,0,1) table_f.attach(self.entry_c,1,2,0,1) table_f.attach(label_alpha,0,1,1,2) table_f.attach(self.entry_alpha,1,2,1,2) table_f.attach(label_beta,0,1,2,3) table_f.attach(self.entry_beta,1,2,2,3) table_f.attach(label_sc,4,5,0,1) table_f.attach(self.entry_sc,5,6,0,1) table_f.attach(label_salpha,4,5,1,2) table_f.attach(self.entry_salpha,5,6,1,2) table_f.attach(label_sbeta,4,5,2,3) table_f.attach(self.entry_sbeta,5,6,2,3) vruler = gtk.VSeparator() table_f.attach(vruler,3,4,0,3,xpadding=10) check_function = gtk.CheckButton("Plot function") check_points = gtk.CheckButton("Plot data points") check_err = gtk.CheckButton("Plot uncertainty band") check_ci_curve = gtk.CheckButton("Plot CI95% band (curve)") check_ci_points = gtk.CheckButton("Plot CI95% band (points)") check_function.set_active(True) check_points.set_active(True) check_err.set_active(True) check_ci_curve.set_active(True) check_ci_points.set_active(True) vbox_checks = gtk.VBox(False, 5) vbox_checks.pack_start(check_function, False, False) vbox_checks.pack_start(check_points, False, False) vbox_checks.pack_start(check_err, False, False) vbox_checks.pack_start(check_ci_curve, False, False) vbox_checks.pack_start(check_ci_points, False, False) check_function.connect('toggled',self.on_toggled, 'function') check_points.connect('toggled',self.on_toggled, 'points') check_err.connect('toggled',self.on_toggled, 'err') check_ci_curve.connect('toggled',self.on_toggled, 'ci_curve') check_ci_points.connect('toggled',self.on_toggled, 'ci_points') hbox_buttons = gtk.HBox(True,5) button_save_f = gtk.Button("Save Funtion") button_load_f = gtk.Button("Load Funtion") hbox_buttons.pack_start(button_save_f,True,True) hbox_buttons.pack_start(button_load_f,True,True) button_save_f.connect('clicked',self.save_function) button_load_f.connect('clicked',self.load_function) left_box = gtk.VBox(False,5) ruler_f1 = gtk.HSeparator() ruler_f2 = gtk.HSeparator() left_box.pack_start(label_Y, False, False) left_box.pack_start(table_f, False, False) left_box.pack_start(ruler_f1, False, True, 5) left_box.pack_start(vbox_checks, False, False) left_box.pack_start(ruler_f2, False, True, 5) left_box.pack_start(hbox_buttons, False, True) function_box.pack_start(left_box, False, False) function_box.pack_start(self.scroll_ftxt, True, True) #__________________________________________________________________ # NOTEBOOK WRAP____________________________________________________ self.notebook = gtk.Notebook() self.notebook.append_page(text_view_box, gtk.Label('Log console')) self.notebook.append_page(estimator_box, gtk.Label('Estimator')) self.notebook.append_page(function_box, gtk.Label('Calibration function')) vbox1.pack_end(self.notebook,True,True) #__________________________________________________________________ # MAT-PLOT-LIB_____________________________________________________ self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(600,400) # set min size self.markers = ['.',',','+','x','|','_','o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd'] self.colors = ['black','blue','green','red','cyan','magenta','yellow','purple','white'] self.pstyle = ['bmh','s','6','red','0.8','black','2','black','0.3','','25','','','20','15','','','20','15'] self.styledict = {} self.styledict["style"]='bmh' self.styledict["point_style"]='s' self.styledict["point_size"]='6' self.styledict["point_color"]='red' self.styledict["point_alpha"]='0.8' self.styledict["line_color"]='black' self.styledict["line_width"]='2' self.styledict["band_color"]='black' self.styledict["band_alpha"]='0.3' self.styledict["title_size"]='25' self.styledict["xtitle_size"]='20' self.styledict["xlabel_size"]='15' self.styledict["ytitle_size"]='20' self.styledict["ylabel_size"]='15' self.nselec = [1,12,5,3,-1,0,-1,0,-1,-1,-1,-1,-1,-1] self.plot_labels = ["Foci per cell vs Dose", "Dose", "Foci per cell", " [Gy]", " []"] #print plt.style.available self.mode='quadratic' self.function = None if self.mode=='linear' : self.function = self.linear elif self.mode=='quadratic' : self.function = self.quadratic self.fit_toggle='active' self.points_toggle=1 self.function_toggle=1 self.err_toggle=1 self.ci_func_toggle=1 self.ci_points_toggle=1 self.plotting() # --- CORE plotting function --- toolbar = NavigationToolbar(self.canvas, self) toolbarbox = gtk.HBox() image = gtk.Image() image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR) options_button = gtk.Button() options_button.add(image) options_button.connect('clicked',self.mpl_options) image2 = gtk.Image() image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR) refresh_button = gtk.Button() refresh_button.add(image2) refresh_button.connect('clicked',self.on_refresh_clicked) toolbarbox.pack_start(toolbar, True, True) toolbarbox.pack_end(options_button, False, True) toolbarbox.pack_end(refresh_button, False, True) vbox1.pack_start(toolbarbox, False, False) vbox1.pack_start(self.canvas, True, True) # into box layout #__________________________________________________________________ def plotting(self): plt.style.use(self.pstyle[0]) self.ax1 = self.fig.add_subplot(111) self.ax1.clear() self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax1.set_xlabel(self.plot_labels[1]+self.plot_labels[3], fontsize=int(self.pstyle[13])) self.ax1.set_ylabel(self.plot_labels[2]+self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(-0.1, max(20,200)*1.1, 0.05) xdata=array([100,110,120,130,140,150,160,170,180,190,1000]); ydata=array([100,110,120,130,140,130,160,170,180,190,1000]); if (self.fit_toggle=='active'): self.params, self.rmse, self.p_value, self.std_err, self.dof, self.rss, self.cov_mtx = self.fit_function(xdata,ydata) self.function_changed() if self.function_toggle==1: y = self.function(x,self.params) self.ax1.plot(x,y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) if self.ci_func_toggle==1 and self.fit_toggle=='active': conf = self.confidence(x,xdata,len(x),np.mean(xdata),self.dof,self.rmse) upper = self.function(x,self.params) + conf lower = self.function(x,self.params) - conf self.ax1.fill_between(x, lower, upper, facecolor=self.pstyle[7], alpha=float(self.pstyle[8])) if self.ci_points_toggle==1: upper = self.function(x,self.params) + self.confidence_points(x,self.std_err) lower = self.function(x,self.params) - self.confidence_points(x,self.std_err) self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8])) if self.err_toggle==1: upper = self.function(x,self.params) + self.uncertainty(x,self.std_err) lower = self.function(x,self.params) - self.uncertainty(x,self.std_err) self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8])) self.canvas.draw() def on_refresh_clicked(self,button) : self.plotting() def log(self,txt): end_iter = self.text.get_buffer().get_end_iter() self.text.get_buffer().insert(end_iter, txt+'\n') adj = self.scroll_text.get_vadjustment() adj.set_value( adj.upper - adj.page_size ) self.notebook.set_current_page(0) def loges(self,txt): end_iter = self.estxt.get_buffer().get_end_iter() self.estxt.get_buffer().insert(end_iter, txt+'\n') adj = self.scroll_estxt.get_vadjustment() adj.set_value( adj.upper - adj.page_size ) self.notebook.set_current_page(1) def logf(self,txt): end_iter = self.ftxt.get_buffer().get_end_iter() self.ftxt.get_buffer().insert(end_iter, txt+'\n') adj = self.scroll_ftxt.get_vadjustment() adj.set_value( adj.upper - adj.page_size ) self.notebook.set_current_page(2) def linear(self, x, params): return params[0]*x + params[1] def quadratic(self, x, params): return params[0]*x*x + params[1]*x + params[2] def fit_linear(self, x, a, b): return a*x + b def fit_quadratic(self, x, a, b, c): return a*x*x + b*x + c def confidence(self, x, xdata, n, mean_x, dof, RMSE): alpha=0.05 t = stats.t.isf(alpha/2., df=dof) #conf = t * np.sqrt((RSS/(n-2))*(1.0/n + ( (x-mean_x)**2 / ((np.sum(x**2)) - n*(mean_x**2))))) Sxx = np.sum(xdata**2) - np.sum(xdata)**2/n se_a = RMSE / np.sqrt(Sxx) se_b = RMSE * np.sqrt(np.sum(xdata**2)/(n*Sxx)) conf = t * RMSE * np.sqrt( 1./n + (x-mean_x)**2/Sxx) #pred = t * RMSE * np.sqrt(1+1./n + (x-mean_x)**2/Sxx) return conf def uncertainty(self, x, std_err) : return std_err[2] + x*std_err[1] + x*x*std_err[0] def confidence_points(self, x, std_err) : return 1.96*self.uncertainty(x, std_err) def fit_function(self,x,y): # fit the model if self.mode=='linear' : popt, pcov = curve_fit(self.fit_linear, x, y) elif self.mode=='quadratic' : popt, pcov = curve_fit(self.fit_quadratic, x, y) # parameters standard error std_err = np.sqrt(np.diag(pcov)) # degrees of freedom ndata = len(y) npar = len(popt) dof = max(0, ndata - npar) # root mean squared error residuals = y - self.function(x,popt) RSS = sum(residuals**2) MSE = RSS/dof RMSE = np.sqrt(MSE) # t-value t_value = popt/std_err # p-value P(>|t|) p_value=(1 - stats.t.cdf( abs(t_value), dof))*2 return popt, RMSE, p_value, std_err, dof, RSS, pcov def function_changed(self): if self.mode=='quadratic' : self.entry_c.set_text('%.3f' % self.params[2]) self.entry_alpha.set_text('%.3f' % self.params[1]) self.entry_beta.set_text('%.3f' % self.params[0]) self.entry_sc.set_text('%.3f' % self.std_err[2]) self.entry_salpha.set_text('%.3f' % self.std_err[1]) self.entry_sbeta.set_text('%.3f' % self.std_err[0]) self.logf("params:\t[beta\talpha\tc ]") self.logf("values\t\t" + str(self.params)) self.logf("std_err\t" + str(self.std_err)) self.logf("p-value\t" + str(self.p_value)) self.logf("RSS\t" + str(self.rss)) self.logf("RMSE\t" + str(self.rmse)) self.logf("---------------------------------------------------------------------------") def y_estimate(self, button, entry): if not isfloat(entry.get_text()): self.loges("___Not a number!___") return Y = float(entry.get_text()) plist = self.get_fit_params() u = uncer.UCER(Y=Y,par_list=plist) D = u.D if self.method=="Method A": DL, DU = u.method_a() elif self.method=="Method B": DL, DU = u.method_b() elif self.method=="Method C-original": DL, DU = u.method_c1() elif self.method=="Method C-simplified": DL, DU = u.method_c2() xlab=self.xvar ylab=self.yvar self.loges( xlab + " estimation for " + ylab + " = " + str(Y) + " using " + self.method + ":") self.loges( "D = " + str(D) + "; DL = " + str(DL) + "; DU = " + str(DU)) self.loges("-----------------------------------------------------------------") self.ax1.axhline(y=Y,linewidth=1,linestyle='-',color='red') self.ax1.axvline(x=D,linewidth=1,linestyle='-',color='blue') self.ax1.axvline(x=DL,linewidth=1,linestyle='--',color='green') self.ax1.axvline(x=DU,linewidth=1,linestyle='--',color='green') self.canvas.draw() def mpl_options(self,button) : dialog = gtk.Dialog("My Dialog",self,0,(gtk.STOCK_OK, gtk.RESPONSE_OK)) box = dialog.get_content_area() table = gtk.Table(2,18) table.set_row_spacings(5) table.set_col_spacings(5) l=[] l.append(gtk.Label("Canvas Style")) l.append(gtk.Label("Marker Style")) l.append(gtk.Label("Marker Size")) l.append(gtk.Label("Marker Color")) l.append(gtk.Label("Marker Alpha")) l.append(gtk.Label("Line Color")) l.append(gtk.Label("Line Width")) l.append(gtk.Label("CI Band Color")) l.append(gtk.Label("CI Band Alpha")) l.append(gtk.Label("Title")) l.append(gtk.Label("Title size")) l.append(gtk.Label("X-axis title")) l.append(gtk.Label("X-axis unit")) l.append(gtk.Label("X-axis title size")) l.append(gtk.Label("X-axis labels size")) l.append(gtk.Label("Y-axis title")) l.append(gtk.Label("Y-axis unit")) l.append(gtk.Label("Y-axis title size")) l.append(gtk.Label("Y-axis labels size")) hbox=[] hlines=[] for i in range(0,len(l)) : l[i].set_alignment(xalign=0,yalign=0.5) hbox.append(gtk.HBox(False,5)) hlines.append(gtk.HSeparator()) table.attach(l[i],0,1,2*i,2*i+1) table.attach(hbox[i],1,2,2*i,2*i+1) table.attach(hlines[i],0,2,2*i+1,2*i+2) combo_cs = self.create_combobox(plt.style.available,hbox,0) combo_mst = self.create_combobox(self.markers,hbox,1) spin_msz = self.create_spinbutton(hbox,float(self.pstyle[2]), 1.0,20.0,1.0,2, 2) combo_mc = self.create_combobox(self.colors,hbox,3) spin_ma = self.create_spinbutton(hbox,float(self.pstyle[4]), 0.0,1.0,0.05,2, 4) combo_lc = self.create_combobox(self.colors,hbox,5) spin_lw = self.create_spinbutton(hbox,float(self.pstyle[6]), 0.0,10.0,0.5,2, 6) combo_bc = self.create_combobox(self.colors,hbox,7) spin_ba = self.create_spinbutton(hbox,float(self.pstyle[8]), 0.0,1.0,0.05,2, 8) entry_title = self.create_entry(hbox,0, 9) entry_xaxis = self.create_entry(hbox,1, 11) entry_xunit = self.create_entry(hbox,3, 12) entry_yaxis = self.create_entry(hbox,2, 15) entry_yunit = self.create_entry(hbox,4, 16) spin_title_size = self.create_spinbutton(hbox,float(self.pstyle[10]), 10.0,40.0,1.0,1 , 10) spin_xtile_size = self.create_spinbutton(hbox,float(self.pstyle[13]), 10.0,40.0,1.0,1 , 13) spin_xlabels_size = self.create_spinbutton(hbox,float(self.pstyle[14]), 10.0,40.0,1.0,1 , 14) spin_ytile_size = self.create_spinbutton(hbox,float(self.pstyle[17]), 10.0,40.0,1.0,1 , 17) spin_ylabels_size = self.create_spinbutton(hbox,float(self.pstyle[18]), 10.0,40.0,1.0,1 , 18) box.add(table) dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_OK : dialog.destroy() else : dialog.destroy() def create_combobox(self,slist,whereto,n) : combo = gtk.combo_box_new_text() whereto[n].pack_start(combo) for style in slist : combo.append_text(str(style)) combo.set_active(self.nselec[n]) combo.connect('changed', self.on_combo_changed, n) def create_spinbutton(self,whereto,val,mini,maxi,step,digits,n) : adj = gtk.Adjustment(val,mini,maxi,step,0.5,0.0) spin = gtk.SpinButton(adj,step,digits) whereto[n].pack_start(spin) spin.connect('changed',self.on_spin_changed,n) def create_entry(self,whereto,m,n) : entry_title = gtk.Entry() entry_title.set_text(self.plot_labels[m]) whereto[n].pack_start(entry_title) entry_title.connect("activate",self.on_entry_changed,m) def on_combo_changed(self,cb,n): model = cb.get_model() index = cb.get_active() cb.set_active(index) self.pstyle[n] = model[index][0] self.nselec[n]=index self.plotting() def on_spin_changed(self,spin,n) : self.pstyle[n] = spin.get_value() self.plotting() def on_entry_changed(self,entry,n) : self.plot_labels[n] = entry.get_text() self.plotting() def on_toggled(self,button,s) : if(s=='ci_points'): self.ci_points_toggle*=-1 elif(s=='ci_curve'): self.ci_func_toggle*=-1 elif(s=='function'): self.function_toggle*=-1 elif(s=='points'): self.points_toggle*=-1 elif(s=='err'): self.err_toggle*=-1 self.plotting() def save_function(self,button) : file_chooser = gtk.FileChooserDialog("Open...", self, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) response = file_chooser.run() path='' if response == gtk.RESPONSE_OK : path = file_chooser.get_filename() self.logf('Curve saved in file: ' + path) self.logf("---------------------------------------------------------------------------") if ".csv" not in path: path = path + '.csv' file_chooser.destroy() ofile = open(path,"wb") writer = csv.writer(ofile, delimiter=',') writer.writerow(self.params) writer.writerow(self.std_err) writer.writerow(self.p_value) writer.writerow(self.cov_mtx[0]) writer.writerow(self.cov_mtx[1]) writer.writerow(self.cov_mtx[2]) writer.writerow((self.rss, self.rmse, 0.0)) ofile.close() else : file_chooser.destroy() def get_fit_params(self): l=[self.params,self.std_err,self.p_value,self.cov_mtx[0],self.cov_mtx[1],self.cov_mtx[2],[self.rss,self.rmse,0.0]] return l def load_function(self,button) : file_chooser = gtk.FileChooserDialog("Open...", self, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) response = file_chooser.run() path='' if response == gtk.RESPONSE_OK : path = file_chooser.get_filename() self.logf('Loaded curve from file: ' + path) self.logf("---------------------------------------------------------------------------") f = open(path, 'rt') try: reader = csv.reader(f) l=list(reader) print l self.params=[float(i) for i in l[0]] self.std_err=[float(i) for i in l[1]] self.p_value=[float(i) for i in l[2]] self.cov_mtx=[[float(i) for i in l[3]],[float(i) for i in l[4]],[float(i) for i in l[5]]] self.rss=float(l[6][0]) self.rmse=float(l[6][1]) self.function_changed() self.fit_toggle='inactive' self.points_toggle=False self.plotting() finally: f.close() #self.plotting() file_chooser.destroy() else : file_chooser.destroy() def on_method_changed(self,cb): model = cb.get_model() index = cb.get_active() cb.set_active(index) self.method = model[index][0]
class setup_gui: def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file(os.path.splitext(__file__)[0]+".glade") self.window = self.builder.get_object("window1") dic = { "on_subplot_clicked" : self.subplot_redraw, "on_animate_clicked" : self.animate_redraw, "on_quiver_clicked" : self.quiver_redraw, "gtk_widget_hide" : self.hideinsteadofdelete, "on_menu_load_data_activate" : self.load_data, "on_menu_load_channels_activate" : self.load_channel_positions, "on_channellabels_toggled" : self.channel_labels_toggle, } self.builder.connect_signals(dic) self.create_draw_frame('none') def load_data(self,widget): pass def load_channel_positions(self,widget): pass def subplot_redraw(self,widget): self.fig.clf() self.display(self.data,self.chanlocs,subplot='on',labels=self.labels) def animate_redraw(self,widget): self.fig.clf() self.display(self.data,self.chanlocs,animate='on',labels=self.labels) def quiver_redraw(self,widget): self.fig.clf() self.display(self.data,self.chanlocs,data2=self.data[0],quiver='on',labels=self.labels) def channel_labels_toggle(self,widget): pass def hideinsteadofdelete(self,widget,ev=None): print 'hiding',widget widget.hide() return True def create_draw_frame(self,widget): self.fig = Figure(figsize=[500,500], dpi=40) self.canvas = FigureCanvas(self.fig) self.canvas.show() self.figure = self.canvas.figure self.axes = self.fig.add_axes([0.045, 0.05, 0.93, 0.925], axisbg='#FFFFCC') self.axes.axis('off') self.vb = self.builder.get_object("vbox1") self.vb.pack_start(self.canvas, gtk.TRUE, gtk.TRUE) self.vb.show() #self.canvas.connect("scroll_event", self.scroll_event) #self.canvas.connect('button_press_event', self.button_press_event) def plot_data(self,xi,yi,zi,intx,inty): """provide... xi=grid x data yi=grided y data zi=interpolated MEG data for contour intx and inty= sensor coords for channel plotting""" tstart = time.time() zim = ma.masked_where(isnan(zi),zi) self.sp.pcolor(xi,yi,zim,shading='interp',cmap=cm.jet) self.sp.contourf(xi,yi,zim,cmap=cm.jet) self.sp.scatter(intx,inty, alpha=.75,s=3) def plot_data_loop(self,xi,yi,zi,intx,inty): pass def clear_axes(self): pass def printlabels(self,chanlocs, labels): #if labels != None: count = 0 for l in labels: self.sp.text(chanlocs[1,count], chanlocs[0,count], l, alpha=.6, fontsize=15) count = count + 1 def titles(titletxt): print def display(self, data, chanlocs, labels, data2=None, subplot='off', animate='off', quiver='off', title=None, colorbar='off'): self.data = data self.chanlocs = chanlocs self.labels = labels if len(shape(chanlocs)) != 2: print 'Chanlocs shape error. Should be 2D array "(2,N)"' print 'transposing' chanlocs = chanlocs.T #print chanlocs.shape xi, yi = mgrid[chanlocs[1,:].min():chanlocs[1,:].max():57j,chanlocs[0,:].min():chanlocs[0,:].max():57j] intx=chanlocs[1,:] inty=chanlocs[0,:] labelstatus = self.builder.get_object('channellabels').get_active(); #print 'ls', labelstatus if shape(shape(data))[0]==2: #more than a single vector, need to animate or subplot print '2d array of data' z = data[0,:] if delaunay == 'yes': print 'delaunay is set' tri = Triangulation(intx,inty) interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: #try griddata method print 'delaunay is off' try: zi = griddata(intx,inty,z,xi,yi) except TypeError: print('something wrong with data your trying to plot') return -1 if animate == 'on': #single plot with a loop to animate self.sp = self.fig.add_subplot(111); self.sp.scatter(intx,inty, alpha=.5,s=.5) print 'animating' for i in range(0, shape(data)[0]): dataslice=data[i,:]; z = dataslice if delaunay == 'yes': interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) self.sp.contourf(xi,yi,zim,cmap=cm.jet)#, alpha=.8) if labels != None and labelstatus == True: self.printlabels(chanlocs, labels) self.sp.axes.axis('off') self.canvas.draw() if subplot == 'on': print 'suplotting' for i in range(0, shape(data)[0]): spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots #self.p = f.add_subplot(spnum,spnum,i+1) self.sp = self.fig.add_subplot(spnum,spnum,i+1);#axis('off') dataslice=data[i,:]; self.sp.scatter(intx,inty, alpha=.75,s=3) z = dataslice if delaunay == 'yes': interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) self.sp.contourf(xi,yi,zim,cmap=cm.jet, alpha=.8) self.sp.axes.axis('off') print 'plotting figure',i+1#len(labels), labelstatus if labels != None and labelstatus == True: self.printlabels(chanlocs, labels) if title != None: self.sp.title(str(title[i])) else: pass if quiver == 'on': print 'suplotting quiver' for i in range(0, shape(data)[0]): spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots self.sp = self.fig.add_subplot(spnum,spnum,i+1);#axis('off') dataslice=data[i,:]; self.sp.scatter(intx,inty, alpha=.75,s=3) z = dataslice print 'size or z', size(z) for xx in range(0,size(z)): self.sp.quiver(intx[xx],inty[xx], z[xx], data2[xx]) self.sp.axis('off') if labels != None and labelstatus == True: printlabels(chanlocs, labels) self.canvas.draw() if colorbar == 'on': self.sp.colorbar() else: self.sp = self.fig.add_subplot(111); z = data if delaunay == 'yes': print 'delaunay is set' tri = Triangulation(intx,inty) interp = tri.nn_interpolator(z) zi = interp(xi,yi) else: print 'delaunay is off' zi = griddata(intx,inty,z,xi,yi) zim = ma.masked_where(isnan(zi),zi) self.plot_data(xi,yi,zi,intx,inty) if labels != None and labelstatus == True: printlabels(chanlocs, labels) if colorbar == 'on': p.colorbar(cm) self.sp.axes.axis('off') self.canvas.draw()
class ArrayMapper(gtk.Window, ScalarMapper, Observer): """ CLASS: ArrayMapper DESCR: """ def __init__(self, gridManager, X, channels, amp, addview3, view3, start_time=None, end_time=None): ScalarMapper.__init__(self, gridManager) gtk.Window.__init__(self) Observer.__init__(self) self.resize(512, 570) self.set_title('Array data') self.view3 = view3 self.addview3 = addview3 self.channels = channels self.amp = amp self.trodes = [(gname, gnum) for cnum, gname, gnum in amp] self.X = X self.ax = None self.numChannels, self.numSamples = X.shape self.addview3destroy = False self.time_in_secs = False self.start_time = None self.end_time = None if ((start_time != None) & (end_time != None)): self.time_in_secs = True self.start_time = start_time self.end_time = end_time vbox = gtk.VBox() vbox.show() self.add(vbox) self.fig = self.make_fig(start_time, end_time) if self.addview3: button = gtk.Button('Remove from View3') button.show() #button.set_active(False) vbox.pack_start(button, False, False) button.connect('clicked', self.view3_remove) if self.addview3destroy == False: self.broadcast(Observer.ARRAY_CREATED, self.fig, True, False) self.addview3Button = button self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.show() vbox.pack_start(self.canvas, True, True) hbox = gtk.HBox() hbox.show() vbox.pack_start(hbox, False, False) label = gtk.Label('Sample num') label.show() hbox.pack_start(label, False, False) scrollbar = gtk.HScrollbar() scrollbar.show() hbox.pack_start(scrollbar, True, True) if (self.time_in_secs == True): scrollbar.set_range(start_time, end_time) #scrollbar.set_increments(1,1) print "set_increments(%f, %f)" % ( (end_time - start_time) / float(self.numSamples), (end_time - start_time) / float(self.numSamples)) scrollbar.set_increments( (end_time - start_time) / float(self.numSamples), (end_time - start_time) / float(self.numSamples)) scrollbar.set_value(start_time + (end_time - start_time) / 2.0) else: scrollbar.set_range(0, self.numSamples - 1) scrollbar.set_increments(1, 1) scrollbar.set_value(self.numSamples / 2.0) scrollbar.connect('value_changed', self.set_sample_num) self.scrollbarIndex = scrollbar self.numlabel = gtk.Label(str(scrollbar.get_value())) self.numlabel.show() hbox.pack_start(self.numlabel, False, False) hbox2 = gtk.HBox() hbox2.show() toolbar = NavigationToolbar(self.canvas, self) toolbar.show() hbox2.pack_start(toolbar, True, True) button = gtk.Button('Coh. Here') button.show() hbox2.pack_start(button, False, False) button.connect('clicked', self.coh_here) vbox.pack_start(hbox2, False, False) self.set_sample_num(scrollbar) self.connect("destroy", self.on_destroy) def coh_here(self, button): val = self.scrollbarIndex.get_value() if (self.time_in_secs == True): val = (val * self.view3.eeg.freq) / 1000 #convert val to points self.view3.offset = val - self.view3.newLength / 2 #set the new view3 offset to the beginning of the window self.view3.compute_coherence() self.view3.plot_band() #I know I should be using the receiver. I really dislike that interface tho, so for now I'll be raw about it, until we get a better one. def view3_remove(self, button): #a switch in the array mapper to toggle view3 display if self.addview3destroy == False: self.addview3destroy = True self.broadcast(Observer.ARRAY_CREATED, self.fig, False, self.addview3destroy) self.addview3Button.set_label("Add to view3") else: self.addview3destroy = False self.broadcast(Observer.ARRAY_CREATED, self.fig, True, self.addview3destroy) self.addview3Button.set_label("Remove from view3") def on_destroy(self, widget): #take the view3 display out if we close the window self.view3_remove(self.addview3destroy) print "garbage collecting - unfortunately this doesn't prevent a segfault that will happen if you make a new arraymapper window and then try to drive the autoplay function with it. to be fixed in an upcoming patch, hopefully." gc.collect() def set_sample_num(self, bar): LO = self.view3.newLength / 2 if (self.time_in_secs == True): LO = (LO * 1000) / self.view3.eeg.freq #convert LO to ms val = float(bar.get_value()) ind = ((val - self.start_time) / (self.end_time - self.start_time) * self.numSamples) #print "ArrayMapper.set_sample_num() : ind=", ind datad = self.get_datad(ind) self.gridManager.set_scalar_data(datad) xdata = array([val, val], 'd') #print "shape of xdata is " , xdata.shape #for line in self.lines: # print "ArrayMapper.set_sample_num(): doing line " , line # line.set_xdata(xdata) self.lines[0].set_xdata(array([val - LO, val - LO], 'd')) self.lines[1].set_xdata(array([val, val], 'd')) #middle line self.lines[2].set_xdata(array([val + LO, val + LO], 'd')) else: ind = int(bar.get_value()) #print "ArrayMapper.set_sample_num(", ind, ")" datad = self.get_datad(ind) self.gridManager.set_scalar_data(datad) #xdata = array([ind, ind], 'd') #for line in self.lines: # line.set_xdata(xdata) self.lines[0].set_xdata(array([ind - LO, ind - LO], 'd')) self.lines[1].set_xdata(array([ind, ind], 'd')) #middle line self.lines[2].set_xdata(array([ind + LO, ind + LO], 'd')) if (self.time_in_secs == True): self.numlabel.set_text(str(float(bar.get_value()))) else: self.numlabel.set_text(str(int(bar.get_value()))) #print "self.fig.get_axes() = ", self.fig.get_axes() self.canvas.draw() if self.addview3: if self.addview3destroy == False: #don't signal unless we have to self.broadcast(Observer.ARRAY_CREATED, self.fig, False, False) #redraw the view3 version of the array #the second false is to say that we shouldn't destroy the display in view3 def get_datad(self, ind): slice = self.X[:, ind] datad = dict(zip(self.trodes, slice)) return datad def make_fig(self, start_time, end_time): fig = Figure(figsize=(8, 8), dpi=72) self.lines = [] N = len(self.channels) self.ax = fig.add_subplot(1, 1, 1) #new singleplot configuration colordict = [ '#A6D1FF', 'green', 'red', 'cyan', 'magenta', 'yellow', 'white' ] minx = 0 maxx = 0 graph = [] for i, channel in enumerate(self.channels): #subplot syntax is numrows, numcolumns, subplot ID print "ArrayMapper.make_fig(): self.X is is ", self.X, type( self.X), len(self.X) print "ArrayMapper.make_fig(): channel is ", channel print "ArrayMapper.make_fig(): self.numSamples=", self.numSamples time_range = arange(self.numSamples) #print "start_time= ", start_time, "end_time =", end_time if ((start_time != None) & (end_time != None)): time_range = arange(start_time, end_time, (end_time - start_time) / self.numSamples) #print "time_range is ", time_range x = self.X[channel - 1, :] if minx > min(x): minx = copy.deepcopy(min(x)) if maxx < max(x): maxx = copy.deepcopy(max(x)) color = colordict[((i - 1) % 7)] newp = self.ax.plot(time_range, x, color, label=("channel " + str(i + 1))) newp[0].set_linewidth(4) graph.append(newp) self.ax.set_xlabel('index') self.ax.set_title('Evoked response') #self.ax.legend() fig.legend(graph, self.channels, 'upper right') if ((start_time != None) & (end_time != None)): mid = start_time + (end_time - start_time) / 2.0 else: mid = self.numSamples / 2.0 #print "setting up line at (([%d, %d], [%d, %d])[0]" % (mid, mid, min(x), max(x)) LO = self.view3.newLength / 2 #line = self.ax.plot([mid, mid], [minx, maxx],'w')[0] #left edge of window: line = self.ax.plot([mid - LO, mid - LO], [minx, maxx], 'y')[0] self.ax.add_line(line) self.lines.append(line) #middle of window, where the scalar data comes from: line = self.ax.plot([mid, mid], [minx, maxx], 'r')[0] self.ax.add_line(line) self.lines.append(line) #right edge of window line = self.ax.plot([mid + LO, mid + LO], [minx, maxx], 'y')[0] self.ax.add_line(line) self.lines.append(line) self.ax.patch.set_facecolor('black') #transparency self.finishedFigure = fig return fig def recieve(self, event, *args): if event in (Observer.SET_SCALAR, ): #move the scrollbar forward by the twidth, #except that this is always coming in in points, and we need to #convert to ms if self.time_in_secs is true newVal = args[0] if self.time_in_secs == True: newVal = ((newVal * 1000) / self.view3.eeg.freq) self.scrollbarIndex.set_value(newVal) print "ARRAY MAPPER: RECIEVED SCALAR MESSAGE: ", newVal return
class Plotter(): def __init__(self, context, f_function, g_function): self.context = context self.f_function = f_function self.g_function = g_function self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(600, 600) # set min size self.markers = [ '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd' ] self.colors = [ 'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple', 'white' ] self.pstyle = [ 'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '', '25', '', '', '20', '15', '', '', '20', '15' ] self.styledict = {} self.styledict["style"] = 'bmh' self.styledict["point_style"] = 's' self.styledict["point_size"] = '6' self.styledict["point_color"] = 'red' self.styledict["point_alpha"] = '0.8' self.styledict["line_color"] = 'black' self.styledict["line_width"] = '2' self.styledict["band_color"] = 'black' self.styledict["band_alpha"] = '0.3' self.styledict["title_size"] = '8' self.styledict["xtitle_size"] = '8' self.styledict["xlabel_size"] = '8' self.styledict["ytitle_size"] = '8' self.styledict["ylabel_size"] = '8' self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1] self.plot_labels = ["", "x", "f(x)", "", "g(x)"] self.points_toggle = 1 self.function_toggle = 1 self.err_toggle = 1 self.ci_func_toggle = 1 self.ci_points_toggle = 1 toolbar = NavigationToolbar(self.canvas, self) toolbarbox = gtk.HBox() image = gtk.Image() image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR) options_button = gtk.Button() options_button.add(image) image2 = gtk.Image() image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR) refresh_button = gtk.Button() refresh_button.add(image2) toolbarbox.pack_start(toolbar, True, True) toolbarbox.pack_end(options_button, False, True) toolbarbox.pack_end(refresh_button, False, True) self.vbox = gtk.VBox() self.vbox.pack_start(toolbarbox, False, False) self.vbox.pack_start(self.canvas, True, True) self.x1 = -0.1 self.x2 = 20.1 # signals options_button.connect('clicked', self.mpl_options) refresh_button.connect('clicked', self.on_refresh_clicked) def mpl_options(self, button): """Create GTKDialog containing options for plotting and connect signals.""" mpl_options_dialog = MPLOptions(self.context, self) def on_refresh_clicked(self, button): """Refresh canvas - plot everything again""" self.plotting() def plotvline(self, **kwargs): self.ax1.axvline(**kwargs) def plothline(self, **kwargs): self.ax1.axhline(**kwargs) def replot(self): self.canvas.draw() def plotting(self): """Generating matplotlib canvas""" plt.style.use(self.pstyle[0]) self.ax1 = self.fig.add_subplot(311) self.ax1.clear() self.ax1.set_title("f(x) and g(x)", fontsize=self.pstyle[10]) self.ax1.set_xlabel("", fontsize=int(self.pstyle[13])) self.ax1.set_ylabel("", fontsize=int(self.pstyle[17])) self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(self.x1, self.x2, 0.05) y = self.f_function.func(x) self.ax1.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) upper = self.f_function.func(x) + self.f_function.confidence_points(x) lower = self.f_function.func(x) - self.f_function.confidence_points(x) self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8])) upper = self.f_function.func(x) + self.f_function.uncertainty(x) lower = self.f_function.func(x) - self.f_function.uncertainty(x) self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8])) y = self.g_function.func(x) self.ax1.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) upper = self.g_function.func(x) + self.g_function.confidence_points(x) lower = self.g_function.func(x) - self.g_function.confidence_points(x) self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8])) upper = self.g_function.func(x) + self.g_function.uncertainty(x) lower = self.g_function.func(x) - self.g_function.uncertainty(x) self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8])) self.ax1.tick_params(axis='x', labelbottom='off') self.ax2 = self.fig.add_subplot(312) self.ax2.clear() self.ax2.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax2.set_xlabel("", fontsize=int(self.pstyle[13])) self.ax2.set_ylabel(self.plot_labels[2] + ' / ' + self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax2.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax2.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) self.ax2.tick_params(axis='x', labelbottom='off') x = np.arange(self.x1, self.x2, 0.05) ly = [] for i in x: if self.g_function.func(i): ly.append(self.f_function.func(i) / self.g_function.func(i)) else: ly.append(0.) y = array(ly) self.ax2.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) self.ax3 = self.fig.add_subplot(313) self.ax3.clear() self.ax3.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax3.set_xlabel(self.plot_labels[1], fontsize=int(self.pstyle[13])) self.ax3.set_ylabel(self.plot_labels[2] + ' - ' + self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax3.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax3.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(self.x1, self.x2, 0.05) ly = [] for i in x: ly.append(self.f_function.func(i) - self.g_function.func(i)) y = array(ly) self.ax3.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) self.fig.subplots_adjust(left=0.12, right=0.97, top=0.94, bottom=0.11, hspace=0.17) self.canvas.draw()
class _Matplotlib: def __init__ (self, pp, progressbar): self.pp = pp self.pb = progressbar self.figure = pylab.figure () self.canvas = FigureCanvas (self.figure) self.toolbar = NavigationToolbar (self.canvas, pp ["MainWindow"]) self.pp ["BoxPlotArea"].pack_start (self.toolbar, expand = False, fill = False) self.pp ["BoxPlotArea"].pack_start (self.canvas , expand = True, fill = True) self.canvas.connect ("button_press_event", self.on_button_press_event) self.l = 0 self.dataAreOld = True self.pathLength = None self.pathId = None self.dl = None def get_x_cursor_position(self,event): gca = self.figure.gca () ap = gca.get_position () xmin, xmax = gca.get_xbound () x,y = self.canvas.get_width_height() posx = ((event.x/x)-ap.x0)*(1/(ap.x1-ap.x0)) sx = (posx*(xmax - xmin)) + xmin return sx def on_button_press_event (self, w, event): if not event.type == gtk.gdk._2BUTTON_PRESS \ or not event.button == 1: return False l = self.get_x_cursor_position(event) self.pp ["PathScale"].set_value (l) return True def selectData (self, x, ys): self.x = x self.ys = ys if not self.pathLength == self.pp.pathLength \ or not self.pathId == self.pp.pathId \ or not self.dl == self.pp.dl: self.dataAreOld = True self.pathId = self.pp.pathId self.pathLength = self.pp.pathLength self.dl = self.pp.dl self.l = 0 self.datas = list () else: self.dataAreOld = False def init_pulse (self): if self.dataAreOld: self.pb.set_text ("Generating datas...") self.pb.set_fraction (0) glib.idle_add (self.getData_pulse) else: glib.idle_add (self.genPlot_pulse) return False def getData_pulse (self): d = [ self.l, ] d.extend (self.pp.client.problem.configAtParam (self.pathId, self.l)) self.datas.append (d) self.l += self.dl if self.l < self.pathLength: self.pb.set_fraction (self.l / self.pathLength) return True else: self.pb.set_fraction (1) glib.idle_add (self.genPlot_pulse) return False def genPlot_pulse (self): self.pb.set_text ("Generating plots...") self.npdatas = np.matrix (self.datas) self.figure.clf () gca = pylab.gca () for elt in self.ys: pylab.plot (self.npdatas [:,self.x[1]], self.npdatas [:,elt[1]], label=elt[0]) gca.set_xlabel (self.x[0]) pylab.legend (loc='best') self.canvas.draw () self.pb.set_text ("Idle") return False
class Plotpar(): def __init__(self, context, f_function, g_function): self.context = context self.f_function = f_function self.g_function = g_function self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(600, 600) # set min size self.markers = [ '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd' ] self.colors = [ 'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple', 'white' ] self.pstyle = [ 'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '', '25', '', '', '20', '15', '', '', '20', '15' ] self.styledict = {} self.styledict["style"] = 'bmh' self.styledict["point_style"] = 's' self.styledict["point_size"] = '6' self.styledict["point_color"] = 'red' self.styledict["point_alpha"] = '0.8' self.styledict["line_color"] = 'black' self.styledict["line_width"] = '2' self.styledict["band_color"] = 'black' self.styledict["band_alpha"] = '0.3' self.styledict["title_size"] = '8' self.styledict["xtitle_size"] = '8' self.styledict["xlabel_size"] = '8' self.styledict["ytitle_size"] = '8' self.styledict["ylabel_size"] = '8' self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1] self.plot_labels = ["", "x", "f(x)", "", "g(x)"] toolbar = NavigationToolbar(self.canvas, self) toolbarbox = gtk.HBox() image = gtk.Image() image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR) options_button = gtk.Button() options_button.add(image) image2 = gtk.Image() image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR) refresh_button = gtk.Button() refresh_button.add(image2) toolbarbox.pack_start(toolbar, True, True) toolbarbox.pack_end(options_button, False, True) toolbarbox.pack_end(refresh_button, False, True) self.vbox = gtk.VBox() self.vbox.pack_start(toolbarbox, False, False) self.vbox.pack_start(self.canvas, True, True) self.x1 = -0.1 self.x2 = 20.1 # signals options_button.connect('clicked', self.mpl_options) refresh_button.connect('clicked', self.on_refresh_clicked) def mpl_options(self, button): """Create GTKDialog containing options for plotting and connect signals.""" mpl_options_dialog = MPLOptions(self.context, self) def on_refresh_clicked(self, button): """Refresh canvas - plot everything again""" self.plotting() def plotvline(self, **kwargs): self.ax1.axvline(**kwargs) def plothline(self, **kwargs): self.ax1.axhline(**kwargs) def replot(self): self.canvas.draw() def plotting(self): """Generating matplotlib canvas""" plt.style.use(self.pstyle[0]) f_kwargs = { 'color': 'black', 'fmt': 's', 'ecolor': 'black', 'elinewidth': 1.5, 'capsize': 4.5, 'capthick': 1.0, 'markersize': 10 } g_kwargs = { 'color': 'red', 'fmt': 's', 'ecolor': 'red', 'elinewidth': 1.5, 'capsize': 4.5, 'capthick': 1.0, 'markersize': 10 } if self.f_function.mode == "quadratic" or self.g_function.mode == "quadratic": self.ax1 = self.fig.add_subplot(131) self.ax1.clear() self.ax2 = self.fig.add_subplot(132) self.ax2.clear() self.ax3 = self.fig.add_subplot(133) self.ax3.clear() if self.f_function.mode == "quadratic": fc = self.f_function.params[2] fa = self.f_function.params[1] fb = self.f_function.params[0] sfc = self.f_function.std_err[2] sfa = self.f_function.std_err[1] sfb = self.f_function.std_err[0] else: fc = self.f_function.params[1] fa = self.f_function.params[0] fb = 0.0 sfc = self.f_function.std_err[1] sfa = self.f_function.std_err[0] sfb = 0.0 if self.g_function.mode == "quadratic": gc = self.g_function.params[2] ga = self.g_function.params[1] gb = self.g_function.params[0] sgc = self.g_function.std_err[2] sga = self.g_function.std_err[1] sgb = self.g_function.std_err[0] else: gc = self.g_function.params[1] ga = self.g_function.params[0] gb = 0.0 sgc = self.g_function.std_err[1] sga = self.g_function.std_err[0] sgb = 0.0 fx = [0] fy = [fc] fe = [sfc] self.ax1.errorbar(fx, fy, fe, **f_kwargs) gx = [1] gy = [gc] ge = [sgc] self.ax1.errorbar(gx, gy, ge, **g_kwargs) fx = [0] fy = [fa] fe = [sfa] self.ax2.errorbar(fx, fy, fe, **f_kwargs) gx = [1] gy = [ga] ge = [sga] self.ax2.errorbar(gx, gy, ge, **g_kwargs) fx = [0] fy = [fb] fe = [sfb] self.ax3.errorbar(fx, fy, fe, **f_kwargs) gx = [1] gy = [gb] ge = [sgb] self.ax3.errorbar(gx, gy, ge, **g_kwargs) plt.setp([self.ax1, self.ax2, self.ax3], xticks=[it for it in range(2)], xticklabels=['f', 'g']) self.ax1.set_xlim([-0.5, 1.5]) self.ax2.set_xlim([-0.5, 1.5]) self.ax3.set_xlim([-0.5, 1.5]) elif self.f_function.mode == "linear" and self.g_function.mode == "linear": self.ax1 = self.fig.add_subplot(121) self.ax1.clear() self.ax2 = self.fig.add_subplot(122) self.ax2.clear() fc = self.f_function.params[1] fa = self.f_function.params[0] sfc = self.f_function.std_err[1] sfa = self.f_function.std_err[0] gc = self.g_function.params[1] ga = self.g_function.params[0] sgc = self.g_function.std_err[1] sga = self.g_function.std_err[0] fx = [0] fy = [fc] fe = [sfc] self.ax1.errorbar(fx, fy, fe, **f_kwargs) gx = [1] gy = [gc] ge = [sgc] self.ax1.errorbar(gx, gy, ge, **g_kwargs) fx = [0] fy = [fa] fe = [sfa] self.ax2.errorbar(fx, fy, fe, **f_kwargs) gx = [1] gy = [ga] ge = [sga] self.ax2.errorbar(fx, fy, fe, **g_kwargs) plt.setp([self.ax1, self.ax2, self.ax3], xticks=[it for it in range(2)], xticklabels=['f', 'g']) self.ax1.set_xlim([-0.5, 1.5]) self.ax2.set_xlim([-0.5, 1.5]) self.fig.subplots_adjust(left=0.07, right=0.97, top=0.94, bottom=0.1, wspace=0.30) self.canvas.draw()
class Plot(): def __init__(self, title, function, labels): self.title = title # MAT-PLOT-LIB_____________________________________________________ self.fig = Figure(figsize=(6, 4)) # create fig self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(500, 300) # set min size self.markers = [ '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd' ] self.colors = [ 'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'purple', 'white' ] self.pstyle = [ 'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '', '25', '', '', '20', '15', '', '', '20', '15' ] self.styledict = {} self.styledict["style"] = 'bmh' self.styledict["point_style"] = 's' self.styledict["point_size"] = '6' self.styledict["point_color"] = 'red' self.styledict["point_alpha"] = '0.8' self.styledict["line_color"] = 'black' self.styledict["line_width"] = '2' self.styledict["band_color"] = 'black' self.styledict["band_alpha"] = '0.3' self.styledict["title_size"] = '25' self.styledict["xtitle_size"] = '20' self.styledict["xlabel_size"] = '15' self.styledict["ytitle_size"] = '20' self.styledict["ylabel_size"] = '15' self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1] self.plot_labels = [] self.plot_labels.append(labels[3] + " vs " + labels[0]) # plot title self.plot_labels.append(labels[0]) # x-axis title self.plot_labels.append(labels[3]) # y-axis title self.plot_labels.append("[Gy]") # x-axis unit self.plot_labels.append(" ") # y-axis unit #print plt.style.available self.fit_toggle = 'inactive' self.points_toggle = 1 self.function_toggle = 1 self.err_toggle = 1 self.ci_func_toggle = 1 self.ci_points_toggle = 1 #self.plotting(function) # --- CORE plotting function --- def plotting(self, function): """Generating matplotlib canvas""" plt.style.use(self.pstyle[0]) self.ax1 = self.fig.add_subplot(111) self.ax1.clear() self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10]) self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3], fontsize=int(self.pstyle[13])) self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4], fontsize=int(self.pstyle[17])) self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14])) self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18])) x = np.arange(-0.1, max(20, 200) * 1.1, 0.05) if self.function_toggle == 1: y = function.func(x, function.t, function.t0, function.params) self.ax1.plot(x, y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6])) if self.ci_points_toggle == 1: upper = function.func(x, function.t, function.t0, function.params) + confidence_points( x, function.std_err) lower = function.func(x, function.t, function.t0, function.params) - confidence_points( x, function.std_err) self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8])) if self.err_toggle == 1: upper = function.func(x, function.t, function.t0, function.params) + uncertainty( x, function.std_err) lower = function.func(x, function.t, function.t0, function.params) - uncertainty( x, function.std_err) self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8])) self.fig.tight_layout() self.canvas.draw() def plotvline(self, **kwargs): self.ax1.axvline(**kwargs) def plothline(self, **kwargs): self.ax1.axhline(**kwargs) def replot(self): self.canvas.draw()
class gui: """Main application class.""" def __init__(self): self.builder=gtk.Builder() self.dsizes=[] self.builder.add_from_file("gladeb.glade") myscreen=gtk.gdk.Screen() self.screensize=(myscreen.get_width(),myscreen.get_height()) print self.screensize dic={"mainwindowdestroy" : gtk.main_quit,"openwindow":self.openWindow, "closewindow":self.closeWindow, "devicenumchanged":self.changeDeviceNumber, "btnclicked":self.btnclicked, "fileset":self.fileSet, "mctoolbarbtn":self.mctoolbarClicked, "trkeypress":self.getKeyPress} self.builder.connect_signals(dic) #Initialise defaults #Camera config window self.devicenumcb = gtk.combo_box_new_text() self.builder.get_object("combospace").add(self.devicenumcb) self.builder.get_object("combospace").show_all() self.devicenumcb.append_text('0') self.devicenumcb.append_text('1') self.devicenumcb.set_active(0) self.devicenumcb.connect("changed", self.changeDeviceNumber) self.figurecc=Figure() self.axiscc=self.figurecc.add_subplot(111) try: self.cap = cv2.VideoCapture(self.devicenumcb.get_active()) except: pass self.pixelthreshold=0 #Monitor config window self.tolerance=25 self.blocksize=7 self.d1size=(80,50) self.d2size=None self.builder.get_object("tolerance").set_text("25") self.builder.get_object("blocksize").set_text("7") self.builder.get_object("d1x").set_text("50") self.builder.get_object("d1y").set_text("80") self.figuremc=Figure() self.axismc=self.figuremc.add_subplot(111) self.figuretmc=Figure() self.axistmc=self.figuretmc.add_subplot(111) self.mcflipx=False self.mcflipy=False self.clickstate="none" self.crop1=None self.crop2=None self.builder.get_object("tolerance").set_editable(True) self.builder.get_object("blocksize").set_editable(True) self.builder.get_object("d1x").set_editable(True) self.builder.get_object("d1y").set_editable(True) self.builder.get_object("d2x").set_editable(True) self.builder.get_object("d2y").set_editable(True) self.contours=[] self.dlist=[] self.trdlist=[] self.figuretr=Figure() self.axistr=self.figuretr.add_subplot(111) self.trframe=0 self.trtotal=0 self.traindict={} self.solsdict={} #General functions def fileSet(self, widget): call=gtk.Buildable.get_name(widget) if call=="monitorconfigloadfile": self.loadMonitorImage(widget.get_filename()) elif call=="trainingfilechooser": self.loadTrainingImage(widget.get_filename()) elif call=="testmcfile": self.loadMonitorImage(widget.get_filename(), testmc=True) def btnclicked(self, widget): call=gtk.Buildable.get_name(widget) if call=="resbtn": self.setResolution() elif call=="imagesavebtn": fname=self.builder.get_object("imagesavetext").get_text() if fname!="" and fname!=None: self.saveImage(fname) elif call=="videosavebtn": fname=self.builder.get_object("videosavefile").get_text() if fname!="" and fname!=None: self.saveVideo(fname) elif call=="setparameters": self.setParameters() elif call=="setdigits": self.setDigitSizes() elif call=="mcflipx": if self.mcflipx==False: self.mcflipx=True else: self.mcflipx=False self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) elif call=="mcflipy": if self.mcflipy==False: self.mcflipy=True else: self.mcflipy=False self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) elif call=="addtag": self.setClickMode("tag") elif call=="cleartags": #TODO Clear tags pass elif call=="addcontour": self.setClickMode("addcontour1") elif call=="rmcontour": self.setClickMode("rmcontour") elif call=="splitcontour": self.setClickMode("splitcontour") elif call=="cropimage": self.setClickMode("crop1") elif call=="getdigitsize": self.setClickMode("getdigit1") elif call=="tagokbtn": self.curtag=self.builder.get_object("tagname").get_text() self.builder.get_object("tagwindow").set_visible(0) self.contours.append(Contour(self.tempditem,self.tempitem,self.curtag)) if not (self.d1size in self.dsizes): self.dsizes.append(self.d1size) elif call=="tagcancelbtn": self.setClickMode("none") self.builder.get_object("tagwindow").set_visible(0) elif call=="trnext": self.trNext() elif call=="trprev": if self.trframe>0: self.trframe-=1 self.updateTrainingDataWindow() elif call=="savetrdata": fn=self.builder.get_object("trfile").get_text() f=open(fn, "w") pickle.dump(self.traindict, f) f.close() elif call=="allconts": #show all contours in monitor config window self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename(), allconts=True) elif call=="clearunsaved": #redraw only those ritems in self.contours self.drawMonitor(clearunsaved=True) elif call=="liverecord": #TODO test? Fix all parameters here #start loop to get data fn=self.builder.get_object("livefile").get_text() f=open(fn,"r") #log to f while True: self.livelist=[] #get image using current camera config ret,im=self.cap.read() #run contour detection (self.monimage,self.dlist,self.rlist)=self.getContours(a,self.d1size) #take only labelled ones for i in range(len(self.rlist)): for j in range(len(self.contours)): #if self.rlist[i]==cont.ritem: #TODO remove hidden parameters here cont=self.contours[j] if np.abs(self.rlist[i][0][0]-cont.ritem[0][0])<=4 and np.abs(self.rlist[i][0][1]-cont.ritem[0][1])<=4: #Need to append x position, label self.livelist.append((self.dlist[i],j)) #could add width, height check as well #run digit analysis #TODO - modify this for known number of digits? for item2 in self.livelist: item=item2[0][0] q=False #data = np.zeros((esize), dtype=np.uint8) esize1=self.d1size[0]*self.d1size[1] #results=[] #err=[] data=item.flatten() boolarray=(data>self.pixelthreshold) resultd=[] #print self.traindict.keys() for j in range(len(self.traindict.keys())): result=np.sum(self.traindict[j][boolarray]) #penalisation factor result-=4*np.sum(self.traindict[j][data<=self.pixelthreshold]) resultd.append(result/float(esize1)) #print resultd # sr=reversed(sorted(resultd)) # srlist=[] # for j in sr: # srlist.append(j) # err.append(srlist[0]-srlist[1]) resultf=(resultd.index(max(resultd))) #print resultf if max(resultd)<-0.1: #print "IGNORE!" q=True #print "---" #cv2.imshow("newtest",item) #cv2.waitKey(0) #Append digit to correct place #rl = {mlabel:{x:(1,q)}} #use label instead of y co-ordinate as constant if self.contours[item2[1]].label in rl.keys(): rl[self.contours[item2[1]].label][item2[0][1]]=(resultf, q) else: rl[self.contours[item2[1]].label]={item2[0][1]:(resultf,q)} #Want data structure instead of string for key in sorted(rl.iterkeys()): #print "%s: %s" % (key, mydict[key]) for key2 in sorted(rl[key].iterkeys()): string+=str(rl[key][key2][0]) #if rl[key][key2][1]==False: #create solutions dictionary #string+=str(rl[key][key2][0]) #if rl[key][key2][1]==True: #string+="?" solsdict[self.contours[item2[1]].label]=string #reconstruct labelled data for item in solsdict.keys(): f.write(item +":" + solsdict[item]) f.write("\n") #log to f def trNext(self): if self.trframe<(self.trtotal-1): self.trframe+=1 self.updateTrainingDataWindow() def openWindow(self, widget): #Make dict of widgets to functions call=gtk.Buildable.get_name(widget) if call=="opencameraconfig": self.openCameraConfig() elif call=="openimagesave": self.builder.get_object("imagesavewindow").set_visible(1) elif call=="openrecordvideo": self.builder.get_object("videosavewindow").set_visible(1) elif call=="openmonitorconfig": self.builder.get_object("monitorconfig").set_visible(1) elif call=="opentrainingdatawindow": self.builder.get_object("trainingdatawindow").set_visible(1) elif call=="openlive": self.builder.get_object("livewindow").set_visible(1) elif call=="opentmc": self.builder.get_object("testmcwindow").set_visible(1) def closeWindow(self,widget): call=gtk.Buildable.get_name(widget) if call=="closecameraconfig": self.applyCameraConfig() elif call=="imagesaveclosebtn": self.builder.get_object("imagesavewindow").set_visible(0) elif call=="closevideowindow": self.builder.get_object("videosavewindow").set_visible(0) elif call=="closemonitorconfig": self.builder.get_object("monitorconfig").set_visible(0) elif call=="closetrainingwindow": self.builder.get_object("trainingdatawindow").set_visible(0) elif call=="closelive": self.builder.get_object("livewindow").set_visible(0) elif call=="closetc": self.builder.get_object("testmcwindow").set_visible(0) #Camera config functions def openCameraConfig(self): try: self.builder.get_object("ccimgbox").remove(self.canvascc) except: pass ret,img = self.cap.read() try: img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #cv2.imshow("newtest",img) except: img=np.zeros((100,100)) self.builder.get_object("resx").set_text(str(img.shape[1])) self.builder.get_object("resy").set_text(str(img.shape[0])) self.resolution=(img.shape[1], img.shape[0]) if img.shape[1]<self.screensize[0] and img.shape[0]<self.screensize[1]: pass else: img=imresize(img, (img.shape[0]/2, img.shape[1]/2)) self.axiscc.imshow(img, cmap=cm.gray) #set scale to 0,255 somehow self.canvascc=FigureCanvasGTKAgg(self.figurecc) self.canvascc.draw() self.canvascc.show() self.builder.get_object("ccimgbox").pack_start(self.canvascc, True, True) self.builder.get_object("cameraconfig").set_visible(1) def applyCameraConfig(self): self.builder.get_object("cameraconfig").set_visible(0) def changeDeviceNumber(self, widget): self.cap = cv2.VideoCapture(self.devicenumcb.get_active()) self.openCameraConfig() def setResolution(self): x=self.builder.get_object("resx").get_text() y=self.builder.get_object("resy").get_text() self.cap.set(3,int(x)) self.cap.set(4,int(y)) self.resolution=(int(x),int(y)) self.openCameraConfig() #Image saving def saveImage(self,fname): if fname!="" or None: ret,im=self.cap.read() cv2.imwrite(fname,im) #Video saving def saveVideo(self,fname): try: if fname.lower()[-4:]!=".avi": fname=fname+".avi" except: fname=fname+".avi" video = cv2.VideoWriter(fname,CV_FOURCC(ord("D"),ord("I"),ord("V"),ord("X")), 25, self.resolution) ret,im = self.cap.read() for i in range(1000): ret,im = self.cap.read() video.write(im) video.release() #TODO: May want to chuck away last frame - perhaps do this in analysis #Monitor configuration def loadMonitorImage(self,fname, allconts=False, testmc=False): if fname[-4:].lower()==".avi": #TODO get first frame - look this up pass elif fname[-4:].lower()==".png" or fname[-4:].lower()==".jpg": a=cv2.imread(fname, 0) #note 0 implies grayscale #getcontours else: #Error pass if self.mcflipx==True and self.mcflipy==True: a=cv2.flip(a,-1) elif self.mcflipx==True and self.mcflipy==False: a=cv2.flip(a,0) if self.mcflipy==True and self.mcflipx==False: a=cv2.flip(a,1) if self.crop1!=None and self.crop2!=None: #print str(self.crop1) #print str(self.crop2) a=a[np.min([self.crop1[1],self.crop2[1]]):np.max([self.crop1[1],self.crop2[1]]),np.min([self.crop1[0],self.crop2[0]]):np.max([self.crop1[0],self.crop2[0]])] #TODO add other digit sizes if testmc==True: self.trlist=[] for dsize in self.dsizes: (self.tmonimage,self.dlist,rlist)=self.getContours(a,dsize) self.trlist+=rlist self.drawMonitorTest() else: if allconts==False: (self.monimage,self.dlist,self.rlist)=self.getContours(a,self.d1size) self.drawMonitor() else: (self.monimage,self.rlist1,self.rlist2)=self.getAllContours(a) self.drawMonitor(allconts=True) def setParameters(self): self.tolerance=int(self.builder.get_object("tolerance").get_text()) self.blocksize=int(self.builder.get_object("blocksize").get_text()) self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) def setDigitSizes(self): if (self.builder.get_object("d1y").get_text()!=None and self.builder.get_object("d1y").get_text()!="") and (self.builder.get_object("d1x").get_text()!="" and self.builder.get_object("d1x").get_text()!=None): self.d1size=(int(self.builder.get_object("d1y").get_text()),int(self.builder.get_object("d1x").get_text())) else: self.d1size=None if (self.builder.get_object("d2y").get_text()!=None and self.builder.get_object("d2y").get_text()!="") and (self.builder.get_object("d2x").get_text()!="" and self.builder.get_object("d2x").get_text()!=None): self.d2size=(int(self.builder.get_object("d2y").get_text()),int(self.builder.get_object("d2x").get_text())) else: self.d2size=None #Redo contours, etc. self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) def getContours(self,a,dsize): a=cv2.GaussianBlur(a,(3,3), 0) orig=a.copy() a=cv2.adaptiveThreshold(a, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, self.tolerance, self.blocksize) b=a.copy() contours, hierarchy = cv2.findContours(a, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS) mask = np.zeros(a.shape, dtype=np.uint8) dlist=[] output=np.zeros(b.shape,dtype=np.uint8) rlist=[] for cont in contours: br=cv2.boundingRect(cont) charray=np.zeros(dsize, dtype=np.uint8) temp=b[br[1]:br[1]+br[3], br[0]:br[0]+br[2]] if temp.shape[0]>10 and temp.shape[1]>10: temp=cv2.bitwise_not(temp) temp2=temp.copy() contours2, hierarchy = cv2.findContours(temp2, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for cont2 in contours2: br2=cv2.boundingRect(cont2) #important hidden parameters if br2[3]<dsize[0]+20 and br2[3]>dsize[0]-20 and br2[2]<dsize[1]+20 and br2[2]>dsize[1]-60: #After cropping, edge constrains not necessary # and br2[0]>0+(temp.shape[1]/40.0) and br2[0]<temp.shape[1]-(temp.shape[1]/40.0) mask = np.zeros(temp2.shape, dtype=np.uint8) cv2.drawContours(mask,[cont2],0,255,-1) temp2=temp.copy() temp2[mask==0]=0 temp3=temp2[br2[1]:br2[1]+br2[3], br2[0]:br2[0]+br2[2]] charray=temp3.copy() charray=imresize(charray, dsize) #dlist.append((charray, br[0]+br2[0], br[1])) if br2[2]>5 and br2[3]>5: #cv2.rectangle(b, (br[0]+br2[0],br[1]+br2[1]), (br[0]+br2[0]+br2[2],br[1]+br2[1]+br2[3]), 100) dlist.append((charray, br[0]+br2[0], br[1])) rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3])) return (b,dlist,rlist) def getAllContours(self,a): a=cv2.GaussianBlur(a,(3,3), 0) orig=a.copy() a=cv2.adaptiveThreshold(a, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, self.tolerance, self.blocksize) b=a.copy() contours, hierarchy = cv2.findContours(a, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS) mask = np.zeros(a.shape, dtype=np.uint8) output=np.zeros(b.shape,dtype=np.uint8) rlist1=[] rlist2=[] for cont in contours: br=cv2.boundingRect(cont) rlist1.append(((br[0], br[1]), br[2], br[3])) temp=b[br[1]:br[1]+br[3], br[0]:br[0]+br[2]] if temp.shape[0]>5 and temp.shape[1]>5: temp=cv2.bitwise_not(temp) temp2=temp.copy() contours2, hierarchy = cv2.findContours(temp2, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for cont2 in contours2: br2=cv2.boundingRect(cont2) #if br2[3]<dsize[0]+10 and br2[3]>dsize[0]-10 and br2[2]<dsize[1]+10 and br2[2]>dsize[1]-50 and br2[0]>0+(temp.shape[1]/30) and br2[0]<temp.shape[1]-(temp.shape[1]/5): mask = np.zeros(temp2.shape, dtype=np.uint8) cv2.drawContours(mask,[cont2],0,255,-1) temp2=temp.copy() temp2[mask==0]=0 temp3=temp2[br2[1]:br2[1]+br2[3], br2[0]:br2[0]+br2[2]] #dlist.append((charray, br[0]+br2[0], br[1])) if br2[2]>3 and br2[3]>3: #cv2.rectangle(b, (br[0]+br2[0],br[1]+br2[1]), (br[0]+br2[0]+br2[2],br[1]+br2[1]+br2[3]), 100) #dlist.append((charray, br[0]+br2[0], br[1])) rlist2.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3])) return (b,rlist1, rlist2) def drawMonitor(self, allconts=False, clearunsaved=False): try: self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.axismc.clear() #self.builder.get_object("mctoolbar").remove(self.mctoolbar) except: pass #Add cropping self.axismc.imshow(self.monimage, cmap=cm.gray) #set scale to 0,255 somehow #Maybe this needn't be redefined for every draw - only need draw() but not drawn often anyway self.canvasmc=FigureCanvasGTKAgg(self.figuremc) self.canvasmc.draw() self.canvasmc.show() self.canvasmc.mpl_connect('motion_notify_event', self.mcHoverOnImage) self.canvasmc.mpl_connect('button_release_event', self.mcCaptureClick) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) #TODO stop this getting so complicated if clearunsaved==False: if allconts==False: for item in self.rlist: #Structure of rlist: #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3])) r=Rectangle(item[0], item[1], item[2], fill=False, color="red") #Rectangle has (lowerleft, width, height) self.axismc.add_patch(r) elif allconts==True: #allcontours for item in self.rlist1: #Structure of rlist: #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3])) r=Rectangle(item[0], item[1], item[2], fill=False, color="blue") #Rectangle has (lowerleft, width, height) self.axismc.add_patch(r) for item in self.rlist2: #Structure of rlist: #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3])) r=Rectangle(item[0], item[1], item[2], fill=False, color="green") #Rectangle has (lowerleft, width, height) self.axismc.add_patch(r) #Always draw saved contours in blue for ditem in self.contours: item=ditem.ritem r=Rectangle(item[0], item[1], item[2], fill=False, color="blue") self.axismc.add_patch(r) def drawMonitorTest(self): try: self.builder.get_object("tmcspace").remove(self.canvastmc) self.axistmc.clear() except: pass #Add cropping self.axistmc.imshow(self.tmonimage, cmap=cm.gray) #set scale to 0,255 somehow #Maybe this needn't be redefined for every draw - only need draw() but not drawn often anyway self.canvastmc=FigureCanvasGTKAgg(self.figuretmc) self.canvastmc.draw() self.canvastmc.show() self.builder.get_object("tmcspace").pack_start(self.canvastmc, True, True) for i in range(len(self.trlist)): for cont in self.contours: #if self.rlist[i]==cont.ritem: #TODO remove hidden parameters here if np.abs(self.trlist[i][0][0]-cont.ritem[0][0])<=4 and np.abs(self.trlist[i][0][1]-cont.ritem[0][1])<=4: item=self.trlist[i] r=Rectangle(item[0], item[1], item[2], fill=False, color="blue") self.axistmc.add_patch(r) #could add width, height check as well #Always draw saved contours in blue for ditem in self.contours: item=ditem.ritem def mcHoverOnImage(self, event): #add contour stuff here if not too expensive #find innermost contour #Cannot afford to redraw, must work out how to remove rectangle afterwards since only one at a time #TODO if event.x!=None and event.y!=None and event.xdata!=None and event.ydata!=None: pass def mcCaptureClick(self, event): #print "click" if self.clickstate=="none": pass #elif not(event.x==None or event.y==None or event.xdata==None or event.ydata==None): else: if self.clickstate=="crop1": self.crop1=(int(round(event.xdata)), int(round(event.ydata))) self.setClickMode("crop2") elif self.clickstate=="getdigit1": self.getdigit1=(int(round(event.xdata)), int(round(event.ydata))) self.setClickMode("getdigit2") elif self.clickstate=="crop2": self.crop2=(int(round(event.xdata)), int(round(event.ydata))) self.setClickMode("none") self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) elif self.clickstate=="getdigit2": self.getdigit2=(int(round(event.xdata)), int(round(event.ydata))) #apply stuff self.d1size=(np.abs(self.getdigit2[1]-self.getdigit1[1]),np.abs(self.getdigit2[0]-self.getdigit1[0])) self.builder.get_object("d1x").set_text(str(np.abs(self.getdigit2[0]-self.getdigit1[0]))) self.builder.get_object("d1y").set_text(str(np.abs(self.getdigit2[1]-self.getdigit1[1]))) self.setClickMode("none") self.loadMonitorImage(self.builder.get_object("monitorconfigloadfile").get_filename()) elif self.clickstate=="tag": #Check if we are inside contour, if so present label window, if not, ignore #Contours checked by rlist? coords=(int(round(event.xdata)), int(round(event.ydata))) #found=False #Find innermost not just first contour fitem=None fi=None for i in range(len(self.rlist)): item=self.rlist[i] if (coords[0] >= item[0][0]) and (coords[0] <= (item[0][0]+item[1])) and (coords[1] >= item[0][1]) and (coords[1] <= item[0][1]+item[2]): #Found contour, create contour object for final contour list if fitem==None: fitem=item fi=i else: if (item[0][0] >= fitem[0][0]) and (item[0][0]+item[1] <= (fitem[0][0]+fitem[1])) and (item[0][1] >= fitem[0][1]) and (item[0][1]+item[2] <= fitem[0][1]+fitem[2]): fitem=item fi=i if fitem!=None: self.tempitem=fitem self.tempditem=self.rlist[fi] self.builder.get_object("tagwindow").set_visible(1) #self.contours.append(Contour(item,self.curtag)) def mctoolbarClicked(self,widget): call=gtk.Buildable.get_name(widget) if call=="mczoomin": self.mcZoomIn() elif call=="mczoomout": self.mcZoomOut() elif call=="mcpanleft": self.mcPanLeft() elif call=="mcpanright": self.mcPanRight() elif call=="mcpanup": self.mcPanUp() elif call=="mcpandown": self.mcPanDown() elif call=="mcresetzoom": self.mcResetZoom() def mcZoomIn(self): xlims=self.axismc.get_xlim() ylims=self.axismc.get_ylim() xchange=abs(xlims[1]-xlims[0])*0.1 ychange=abs(ylims[1]-ylims[0])*0.1 self.axismc.set_xlim(left=xlims[0]+xchange, right=xlims[1]-xchange) self.axismc.set_ylim(top=ylims[1]+ychange, bottom=ylims[0]-ychange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcZoomOut(self): xlims=self.axismc.get_xlim() ylims=self.axismc.get_ylim() xchange=abs(xlims[1]-xlims[0])*0.111 ychange=abs(ylims[1]-ylims[0])*0.111 self.axismc.set_xlim(left=xlims[0]-xchange, right=xlims[1]+xchange) self.axismc.set_ylim(top=ylims[1]-ychange, bottom=ylims[0]+ychange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcPanLeft(self): xlims=self.axismc.get_xlim() xchange=abs(xlims[1]-xlims[0])*0.1 self.axismc.set_xlim(left=xlims[0]-xchange, right=xlims[1]-xchange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcPanRight(self): xlims=self.axismc.get_xlim() xchange=abs(xlims[1]-xlims[0])*0.1 self.axismc.set_xlim(left=xlims[0]+xchange, right=xlims[1]+xchange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcPanDown(self): ylims=self.axismc.get_ylim() ychange=abs(ylims[1]-ylims[0])*0.1 self.axismc.set_ylim(top=ylims[1]+ychange, bottom=ylims[0]+ychange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcPanUp(self): ylims=self.axismc.get_ylim() ychange=abs(ylims[1]-ylims[0])*0.1 self.axismc.set_ylim(top=ylims[1]-ychange, bottom=ylims[0]-ychange) self.builder.get_object("monitorconfigspace").remove(self.canvasmc) self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True) def mcResetZoom(self): #Reset view to original somehow - fit entire image pass def setClickMode(self,mode): #none, crop1, crop2, tag, addcontour1, addcontour2, rmcontour, splitcontour, getdigit1, getdigit2 self.builder.get_object("mcclickmode").set_label("Mode:" + str(mode)) self.clickstate=mode def loadTrainingImage(self,fname): if fname[-4:].lower()==".avi": #get first frame - look this up pass elif fname[-4:].lower()==".png" or fname[-4:].lower()==".jpg": a=cv2.imread(fname, 0) #note 0 implies grayscale #getcontours else: #Error pass if self.mcflipx==True and self.mcflipy==True: a=cv2.flip(a,-1) elif self.mcflipx==True and self.mcflipy==False: a=cv2.flip(a,0) if self.mcflipy==True and self.mcflipx==False: a=cv2.flip(a,1) if self.crop1!=None and self.crop2!=None: #print str(self.crop1) #print str(self.crop2) a=a[np.min([self.crop1[1],self.crop2[1]]):np.max([self.crop1[1],self.crop2[1]]),np.min([self.crop1[0],self.crop2[0]]):np.max([self.crop1[0],self.crop2[0]])] (self.monimage,self.dlist,self.rlist)=self.getContours(a,self.d1size) #for cont in self.contours: #add individual digits to list, then tag list #self.dlist.append(self.monimage[cont.ritem[0][1]:cont.ritem[0][1]+cont.ritem[2],cont.ritem[0][0]:cont.ritem[0][0]+cont.ritem[1]]) #TODO FIX THIS - need to take ditem of new image, not config one, where the coords are the same #for cont in self.contours: #self.dlist.append(cont.ditem[0]) for i in range(len(self.rlist)): for cont in self.contours: #if self.rlist[i]==cont.ritem: #TODO remove hidden parameters here if np.abs(self.rlist[i][0][0]-cont.ritem[0][0])<=4 and np.abs(self.rlist[i][0][1]-cont.ritem[0][1])<=4: self.trdlist.append(self.dlist[i]) self.trtotal+=1 #could add width, height check as well #update display self.updateTrainingDataWindow() def updateTrainingDataWindow(self): #Use curframe number, like TesiDogs program try: self.builder.get_object("bvbox3").remove(self.canvastr) self.axistr.clear() except: pass self.axistr.imshow(self.trdlist[self.trframe][0], cmap=cm.gray) #set scale to 0,255 somehow self.canvastr=FigureCanvasGTKAgg(self.figuretr) self.canvastr.draw() self.canvastr.show() self.builder.get_object("bvbox3").pack_start(self.canvastr, True, True) self.builder.get_object("trframecount").set_label(str(self.trframe+1) + "/" + str(self.trtotal)) #self.builder.get_object("trcursol").set_label(str(self.trframe+1) + "/" + str(self.trtotal)) #TODO update labels #bvbox3 #trframecount #trcursol def getKeyPress(self, widget, event): #TODO training #GTKwidget keyreleaseevent ci=event.keyval ci=ci-48 if event.keyval==45: #set to not a number self.trNext() elif ci in [0,1,2,3,4,5,6,7,8,9]: data=self.trdlist[self.trframe][0].flatten() if ci in self.traindict.keys(): self.traindict[ci]+=data self.traindict[ci]/=2.0 self.trNext() else: self.traindict[ci]=data self.trNext() def sumpmtestlive(self): rl={} for item2 in dlist: item=item2[0] q=False data = np.zeros((esize1), dtype=np.uint8) #results=[] #err=[] data=item.flatten() boolarray=(data>self.pixelthreshold) resultd=[] #print tdict.keys() for j in range(len(tdict.keys())): result=np.sum(tdict[j][boolarray]) #penalisation factor result-=4*np.sum(tdict[j][data<=self.pixelthreshold]) resultd.append(result/float(esize1)) #print resultd # sr=reversed(sorted(resultd)) # srlist=[] # for j in sr: # srlist.append(j) # err.append(srlist[0]-srlist[1]) resultf=(resultd.index(max(resultd))) #print resultf if max(resultd)<-0.1: #print "IGNORE!" q=True #print "---" #cv2.imshow("newtest",item) #cv2.waitKey(0) #Append digit to correct place #rl = {y:{x:(1,q)}} if item2[2] in rl.keys(): rl[item2[2]][item2[1]]=(resultf, q) else: rl[item2[2]]={item2[1]:(resultf,q)} string="" for key in sorted(rl.iterkeys()): #print "%s: %s" % (key, mydict[key]) for key2 in sorted(rl[key].iterkeys()): if rl[key][key2][1]==False: string+=str(rl[key][key2][0]) #if rl[key][key2][1]==True: #string+="?" string+=" " print string
class rydec(object): def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file('rydec.glade') signals = {'on_ionizerWindow_destroy' : gtk.main_quit,\ 'on_btn_StartAcquisition_clicked' : self.on_btn_StartAcquisition_clicked} self.builder.connect_signals(signals) self.window = self.builder.get_object('rydecWindow') box = self.builder.get_object('box') fig = Figure(figsize=(5,4), dpi=100) self.axScope = fig.add_subplot(111) self.scopeCanvas = FigureCanvas(fig) box.pack_start(self.scopeCanvas) self.window.show_all() self.plotData = numpy.zeros(100) self.tagTimers = {} self.lastImage = None self.dataLabel = self.builder.get_object('txtDataLabel') self.dataLabel.set_text('unknown') self.active = False self.tagTimers = {} self.pipe, pipe = Pipe() self.acqLoop = Process(target=acquisitionLoop, args=(pipe, )) self.acqLoop.daemon = True self.acqLoop.start() # set the proper default directory for data: try: os.chdir("D:\Data") except OSError: try: os.chdir("/tmp/") except OSError: logger.error("Could not set data directory") try: today = datetime.now().strftime('%Y-%m-%d %a') if not os.path.exists(today): os.mkdir(today) os.chdir(today) except OSError: logger.error("Could not create data directory") self.datadir = os.getcwd() def on_btn_StartAcquisition_clicked(self, widget): if self.active: self.pipe.send(['ACTIVATE', False]) gobject.source_remove(self.tagTimers['ACQ']) del self.tagTimers['ACQ'] widget.set_label('Start') self.active = False else: self.pipe.send(['ACTIVATE', True]) self.tagTimers['ACQ'] = gobject.timeout_add(100, self.acquisitionTimer) widget.set_label('Stop') self.active = True def acquisitionTimer(self): if self.pipe.poll(): self.axScope.clear() data = self.pipe.recv() self.axScope.plot(data) self.axScope.set_title('Scope trace signal', fontsize=12) self.axScope.set_xlabel(r'Time ($\mu$s)', fontsize=12) self.axScope.set_ylabel('Amplitude (V)', fontsize=12) self.axScope.axis([-0.02*len(data), len(data)*1.02, min(data)*1.2, max(data)*1.2]) self.axScope.grid(True) #cursor = Cursor(self.scopeCanvas.ax, useblit=True, color='red', linewidth=2 ) self.scopeCanvas.draw() return True def teardown(self): print 'tearing down everything' self.pipe.send(["QUIT"]) if self.active: self.pipe.recv() self.pipe.close() self.acqLoop.join()
class Iverplot_window (object): """ Iverplot_window---main Iverplot GUI object Parameters ----------- Notes ------ """ def __init__ (self): self.builder = gtk.Builder () self.builder.add_from_file ('iverplot.glade') self.builder.connect_signals (self) self.window = self.builder.get_object ('main_window') # add matplotlib figure canvas w,h = self.window.get_size () self.fig = Figure (figsize=(6,4)) self.canvas = FigureCanvas (self.fig) # a gtk.DrawingArea self.canvas.set_size_request (w-150,-1) vbox = gtk.VBox() toolbar = NavigationToolbar (self.canvas, self.window) vbox.pack_start (self.canvas, True, True) vbox.pack_start (toolbar, False, False) # a little hacky for packing hpane with figure canvas first then tool # bar---not sure if glade is to blame---first, remove tool_vbox then # repack plot_hpaned = self.builder.get_object ('plot_hpaned') self.tool_vbox = self.builder.get_object ('tool_vbox') plot_hpaned.remove (self.tool_vbox) #plot_hpaned.pack1 (self.canvas, resize=True, shrink=False) plot_hpaned.pack1 (vbox, resize=True, shrink=False) plot_hpaned.pack2 (self.tool_vbox) # data self.uvclog = None self.lcmlog = None # plot limits self.xlimits = [None,None] self.xlimits_abs = [None,None] # add single plot item self.plotdex = {} self.plot_items = [] self.plot_items.append (Plot_item (self.tool_vbox, self.on_plot_item_selected, self.uvclog, self.lcmlog)) self.update_subplots () # setwin self.setwin = None # set some defaults self.cd_saveas = os.getcwd () self.cd_open = os.getcwd () self.window.show_all () def on_setwin_clicked (self, widget): if self.setwin is None: self.setwin = Setwin (self.canvas, self.fig, self.on_setwin_complete) def on_setwin_complete (self, xmin, xmax): self.xlimits = [xmin,xmax] for p in self.plot_items: ax = self.fig.axes[self.plotdex[p]] p.plot_type.set_limits (ax, *self.xlimits) self.canvas.draw () self.setwin = None def on_setwin_reset (self, widget): if not self.setwin is None: return self.xlimits = [x for x in self.xlimits_abs] for p in self.plot_items: ax = self.fig.axes[self.plotdex[p]] p.plot_type.set_limits (ax, *self.xlimits) self.canvas.draw () def update_subplots (self): self.fig.clear () n = len (self.plot_items) for i,p in enumerate (self.plot_items): p.plot_type.uvclog = self.uvclog p.plot_type.lcmlog = self.lcmlog ax = self.fig.add_subplot (n,1,i+1) p.plot_type.plot (ax, *self.xlimits) self.plotdex[p] = i self.canvas.draw () def on_plot_item_selected (self, combo, item): ax = self.fig.axes[self.plotdex[item]] item.plot_type.plot (ax, *self.xlimits) self.canvas.draw () def update_window (self): while gtk.events_pending (): gtk.main_iteration_do (True) def on_add_subplot_clicked (self, widget): if len (self.plot_items) >= 3: return self.plot_items.append (Plot_item (self.tool_vbox, self.on_plot_item_selected, self.uvclog, self.lcmlog)) self.update_subplots () self.update_window () def on_remove_subplot_clicked (self, widget): if len (self.plot_items) <= 1: return item = self.plot_items.pop (-1) item.remove () self.update_subplots () self.update_window () def run_open_dialog (self): open_dlg = self.builder.get_object ('open_dialog') #open_dlg.set_current_folder (self.cd_open) open_dlg.set_current_folder ('/home/jeff/data/UMBS_0513/iver28/2013-06-01-dive.046') if len (open_dlg.list_filters ()) == 0: all_filter = gtk.FileFilter () all_filter.set_name ('All files') all_filter.add_pattern ('*') open_dlg.add_filter (all_filter) lcm_filter = gtk.FileFilter () lcm_filter.set_name ('LCM logs') lcm_filter.add_pattern ('lcmlog*') open_dlg.add_filter (lcm_filter) uvc_filter = gtk.FileFilter () uvc_filter.set_name ('UVC logs') uvc_filter.add_pattern ('*.log') open_dlg.add_filter (uvc_filter) response = open_dlg.run () fname = None if response == gtk.RESPONSE_OK: fname = open_dlg.get_filename () self.cd_open = os.path.dirname (fname) open_dlg.hide () return fname def on_open_lcm_clicked (self, widget): fname = self.run_open_dialog () if fname: print 'selected', fname def on_open_uvc_clicked (self, widget): fname = self.run_open_dialog () if fname: print 'selected', fname try: self.uvclog = UVCLog (fname) self.xlimits_abs = [self.uvclog.utime[0], self.uvclog.utime[-1]] self.xlimits = [x for x in self.xlimits_abs] self.update_subplots () except: print 'could not load correctly' def on_save_as_clicked (self, widget): save_as_dlg = self.builder.get_object ('save_as_dialog') save_as_dlg.set_current_folder (self.cd_saveas) save_as_dlg.set_current_name ('iverplot.png') if len (save_as_dlg.list_filters ()) == 0: all_filter = gtk.FileFilter () all_filter.set_name ('All files') all_filter.add_pattern ('*') save_as_dlg.add_filter (all_filter) img_filter = gtk.FileFilter () img_filter.set_name ('All images') img_filter.add_pattern ('*.png') img_filter.add_pattern ('*.jpg') img_filter.add_pattern ('*.pdf') save_as_dlg.add_filter (img_filter) response = save_as_dlg.run () if response == gtk.RESPONSE_OK: fname = save_as_dlg.get_filename () self.fig.savefig (fname, dpi=self.fig.dpi) self.cd_saveas = os.path.dirname (fname) save_as_dlg.hide () def on_about_clicked (self, widget): about = self.builder.get_object ('about_dialog') about.run () about.hide () def on_main_window_destroy (self, widget): gtk.main_quit ()
class AppFluViewer: def __init__(self): gladefile = 'fluviewer.glade' # This must match the window name in glade windowname = 'fluviewer' self.wTree = gtk.glade.XML(gladefile, windowname) dic = { # Also need to set fluviewer's signal tab 'on_fluviewer_destroy': gtk.main_quit, 'on_tv_country_button_release_event': self.on_tv_country_changed, 'on_tv_country_key_release_event': self.on_tv_country_changed, 'on_btn_update_clicked': self.on_btn_update_clicked, } self.wTree.signal_autoconnect (dic) self.fluviewer = self.wTree.get_widget('fluviewer') # Load CSV if it is in current directory self.update(False) self.reload() # Setting up figure self.figure = Figure() self.axis = self.figure.add_subplot(111) self.canvas = FigureCanvas(self.figure) vbox = self.wTree.get_widget('vbox2') vbox.pack_start(self.canvas, True, True) # Setting figure navigation toolbar vbox.pack_start(NavigationToolbar(self.canvas, self.fluviewer), False, False) vbox.show_all() def on_tv_country_changed(self, tv, *args): # Clear figure self.axis.clear() self.axis.hold(True) ls_idx = [sel[0] + 1 for sel in tv.get_selection().get_selected_rows()[1]] for idx in xrange(1, len(self.rec.dtype)): if idx in ls_idx: self.axis.plot(self.rec.date, self.rec.field(idx), label=self.tv_data.get_column(idx).get_title()) self.tv_data.get_column(idx).set_visible(idx in ls_idx) self.axis.legend() self.canvas.draw() def on_btn_update_clicked(self, *args): self.update() self.reload() def update(self, force=True): if force or not os.path.exists(CSV_FILENAME): csv_started = False f = open(CSV_FILENAME, 'w') for line in urllib2.urlopen(DATA_URI): # Skip the notes before the csv data if line.startswith('Date,'): csv_started = True if csv_started: f.write(line) f.close() def reload(self): # Some data is missing, default converter will raise ValueError because of # int(''), use missingd or converterd to resolve the problem but we have to # load csv first to get field names. f = open(CSV_FILENAME, 'r') line = f.readline() f.close() fields = line.replace(' ', '_').lower().split(',')[1:] d = dict(zip(fields, [lambda value: int(value) if value != '' else nan]*len(fields))) self.rec = mlab.csv2rec(CSV_FILENAME, converterd=d) country_names = [] for name in self.rec.dtype.names: if name == 'date': continue # Prettify the field name, ex. united_states -> United States name = ' '.join([_x.capitalize() for _x in name.replace('_', ' ').split(' ')]) country_names.append(name) # Setting up country names tv_country = self.wTree.get_widget('tv_country') # Define the types to ListStore types = [str] store = gtk.ListStore(*types) # Add country names to ListStore for name in country_names: store.append([name]) tv_country.set_model(store) # Clean up columns for column in tv_country.get_columns(): tv_country.remove_column(column) # Add column to TreeView (Specify what to show) column = gtk.TreeViewColumn('Country', gtk.CellRendererText(), text=0) tv_country.append_column(column) # Set up multiselect tv_country.get_selection().set_mode(gtk.SELECTION_MULTIPLE) # Setting up data tv_data = self.wTree.get_widget('tv_data') # Let date and number all be str type types = [str] * len(self.rec.dtype) store = gtk.ListStore(*types) for rec in self.rec: store.append(rec) # Clean up columns for column in tv_data.get_columns(): tv_data.remove_column(column) column = gtk.TreeViewColumn('Date', gtk.CellRendererText(), text=0) tv_data.append_column(column) for i in xrange(len(country_names)): name = country_names[i] column = gtk.TreeViewColumn(name, gtk.CellRendererText(), text=i+1) column.set_visible(False) tv_data.append_column(column) tv_data.set_model(store) self.tv_data = tv_data # Update last data date self.wTree.get_widget('lbl_last_date').set_text(str(self.rec[-1][0]))
window.show_all() window.connect('destroy', gtk.main_quit) def save_gtk(window, event): if gtk.gdk.keyval_name(event.keyval) == 's': save_fig() window.connect('key-press-event', save_gtk) gtk.main() except: import matplotlib as mpl from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk mpl.use('TkAgg') ax.tick_params(axis='x', labelsize=15) ax.tick_params(axis='y', labelsize=15) root = tk.Tk() root.title(args.filename) root.geometry('800x600+100+100') canvas = FigureCanvasTkAgg(fig, master=root) canvas.get_tk_widget().grid() canvas.get_tk_widget().pack(fill='both') canvas.draw() def save_tk(event): if event.keysym == 's': save_fig() root.bind('<KeyPress>', save_tk) root.mainloop()
class app: data_location='' def __init__(self): app.data_location='/home/'+getpass.getuser()+'/.expensemanager/data/' dest_dir = os.path.join(app.data_location[0:-5],'data/') try: f=open(app.data_location+'years','r') f.readlines() f.close() except : #script_dir = os.path.dirname(os.path.abspath(__file__)) #dest_dir = os.path.join(app.data_location) #print type(dest_dir), dest_dir #print 1 try: #print 2 os.makedirs(dest_dir) except OSError: pass self.window=gtk.Window() self.window.set_default_size(1220,658) self.window.set_position(gtk.WIN_POS_CENTER) self.window.connect("delete_event",self.terminate) self.window.set_title("Expense Manager") vbox = gtk.VBox(False) hbox = gtk.HBox() settings=(gtk.Button()).get_settings() settings.set_property("gtk-button-images",True) button1 = gtk.Button(stock=gtk.STOCK_EDIT) button1.connect('clicked',self.edit) button2 = gtk.Button(stock=gtk.STOCK_ADD) button2.connect('clicked',self.gocl) #liststore for months liststore = gtk.ListStore(str) self.months=["JAN",'FEB','MAR','APR','MAY','JUNE','JULY','AUG','SEPT','OCT','NOV','DEC'] for i in self.months: liststore.append([i]) cell = gtk.CellRendererText() self.combobox = gtk.ComboBox(liststore) self.combobox.pack_start(cell, True) self.combobox.add_attribute(cell, "text", 0) self.combobox.connect('changed',self.changed_item) now=datetime.datetime.now() self.mm=now.month-1 self.dd=now.day self.yy=now.year #self.yy='2012' self.combobox.set_active(self.mm) a= self.combobox.get_active_text() #dest_dir = os.path.join(/home/+get,getpass.getuser() 'data') self.fname=app.data_location+str(self.yy)+'_'+a try: f=open(app.data_location+'years','r') f.close() except : f=open(app.data_location+'years','w') f.write(str(self.yy)+'\n') f.close() #hbox.add(button1) hbox.pack_start(button2,False) hbox.pack_start(button1,False) #hbox.add(button4) self.select_years() hbox.pack_end(self.combobox2,False) hbox.pack_end(self.combobox,False) button5=gtk.Button(stock=gtk.STOCK_ABOUT) button5.connect('clicked',self.about) #hbox.pack_end(buttmon5,False) vbox.pack_start(hbox, False) #hbox contains the add/stats/edit etc buttons/comboboxes hbox2=gtk.HBox() hbox2.pack_end(button5,False) #button5 is the about button label_user=gtk.Label(' Welcome, '+getpass.getuser().title()+'.') hbox2.pack_start(label_user,False) vbox.pack_end(hbox2,False) #hbox2 holds only the about button sw = gtk.ScrolledWindow() sw.set_shadow_type(gtk.SHADOW_ETCHED_IN) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) store = self.create_model() self.treeView = gtk.TreeView(store) #tvc=gtk.TreeViewColumn() self.treeView.set_rules_hint(True) self.treeView.connect('cursor-changed',self.on_activated) sw.add(self.treeView) pane=gtk.HPaned() pane.pack1(sw)#,resize=True, shrink=True) #self.sw_graphs=gtk.ScrolledWindow() #self.sw_graphs.set_shadow_type(gtk.SHADOW_ETCHED_IN) #self.sw_graphs.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.f = plt.figure(dpi=75,facecolor='w') #self.f.patch.set_alpha(0.95) self.f.subplots_adjust(left = 0.08,bottom=0.1,top = 0.9,right=0.95,wspace=0.25,hspace=0.25) self.canvas = FigureCanvas(self.f) self.line1=[] self.line1b=[] self.line2=[] self.graphs(1) self.graphs(2) #self.sw_graphs.add_with_viewport(self.canvas) frame=gtk.Frame() frame.add(self.canvas) pane_rightPane=gtk.VPaned() pane_stats_viewer=gtk.HPaned() viewer_sw = gtk.ScrolledWindow() viewer_sw.set_shadow_type(gtk.SHADOW_ETCHED_IN) viewer_sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) viewer_sw.add(viewer.treeView) x=app.data_location+str(self.yy)+'_'+ str(self.months[self.mm])+' '+str(self.dd) #print x viewer.update(self,x) viewer.main(self) stats_sw = gtk.ScrolledWindow() stats_sw.set_shadow_type(gtk.SHADOW_ETCHED_IN) stats_sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) stats.main(self,self.fname) stats_sw.add(stats.treeView) pane_stats_viewer.add1(stats_sw) pane_stats_viewer.set_position(182) pane_stats_viewer.add2(viewer_sw) pane_rightPane.add1(frame) pane_rightPane.set_position(390) pane_rightPane.add2(pane_stats_viewer) pane.pack2(pane_rightPane,resize=True, shrink=False) pane.set_position(590) #pane.compute_position(1120, True, False) #pane.queue_resize() vbox.pack_start(pane) self.create_columns(self.treeView) self.window.add(vbox) self.window.show_all() def graphs(self,option): # when option==1, the first graph, self.a is redrawn # when option==2, the second graph, self.c is redrawn #self.f.text(0.5,0.92,'',fontsize=14) #self.f.text(0.5,0.92,self.combobox.get_active_text()+' '+self.combobox2.get_active_text(),fontsize=14,horizontalalignment='center') #print self.get_suptitle() matplotlib.rc('xtick', labelsize=11) matplotlib.rc('ytick', labelsize=11) try: if option==1: self.a = self.f.add_subplot(221) self.a.patch.set_color('black') self.a.patch.set_alpha(0.05) #print self.a.get_yticks() self.a.yaxis.grid('True') #print self.combobox.get_active_text() self.a.set_xlabel(self.combobox.get_active_text()+' '+self.combobox2.get_active_text(),fontsize=12) #print self.a.get_xlabel() self.a.set_ylabel('Daily Expense',fontsize=12) model=self.treeView.get_model() total_list=[0] counter=0 for i in model: for j in i: counter+=1 if counter%7==0: total_list.append(j) #print j, type(j), #print '\n' #print range(len(total_list)) #print total_list if max(total_list)==0: M=1 else: M=max(total_list)+0.1*max(total_list) self.a.set_ylim(0,M) self.a.set_xlim(1,len(total_list)-1) days=[] for i in range(len(total_list)): if i%2!=0: days.append(i) self.a.set_xticks(days) self.a.set_xticklabels(days,fontsize=9) #print total_list, len(total_list) #total_list.append(100) while len(self.line1)!=0: l=self.line1.pop(0) l.remove() total_list.append(0) #self.a.set_antialiased(False) #print total_list self.line1=self.a.fill(total_list,'blue',alpha=0.6) self.canvas.draw() #print line self.b=self.f.add_subplot(222) self.b.patch.set_color('black') self.b.patch.set_alpha(0.05) self.b.yaxis.grid('True') self.b.set_xlabel('Categories',fontsize=12) self.b.set_ylabel('Category Expense',fontsize=12) total_list=[0] counter=0 #print 1 stats.update(self.fname) counter=0 cat=[] for i in stats.create_model(self): for j in i: counter+=1 if counter%2==0: total_list.append(j) else: cat.append(j) del total_list[-1] del cat[-1] #print cat #print total_list #print 'sfdf' if max(total_list)==0: M=1 else: M=max(total_list)+0.1*max(total_list) self.b.set_ylim(0,M) self.b.set_xlim(0.5,5.5) self.b.set_xticks([1,2,3,4,5]) self.b.set_xticklabels(cat,fontsize=9) #print total_list, len(total_list) #total_list.append(100) while len(self.line1b)!=0: l2=self.line1b.pop(0) l2.remove() #self.line1b=[] #print 3 total_list.append(0) #self.a.set_antialiased(False) #print total_list self.line1b=self.b.fill(total_list,'yellow',alpha=0.6) self.canvas.draw() else: self.c = self.f.add_subplot(212) self.c.patch.set_color('black') self.c.patch.set_alpha(0.05) self.c.yaxis.grid('True') self.c.set_xlabel(self.combobox2.get_active_text(),fontsize=12) self.c.set_ylabel('Monthly Expense',fontsize=12) self.c.set_xlim(0,13) self.c.set_xticks(range(1,13)) #self.c.set_xticks(range(5)) #for i in max(monthly_totals_list): #print self.c.get_yticks() self.c.set_xticklabels(self.months,fontsize=11) year=self.combobox2.get_active_text() monthly_totals_list=[0] for i in range(12): cost=0 s=year+'_'+str(self.months[i]) #print s try: f=open(app.data_location+s,'r') s=f.readlines() f.close() #print 0 for i in s: #print i[19:22] #print i cost+=float(i[19:27].strip()) #print cost, except IOError: #print 2 pass #print cost monthly_totals_list.append(cost) #print if max(monthly_totals_list)==0: M=1 else: M=max(monthly_totals_list)+0.1*max(monthly_totals_list) self.c.set_ylim(0,M) while len(self.line2)!=0: l=self.line2.pop(0) l.remove() monthly_totals_list.append(0) self.line2=self.c.fill(monthly_totals_list,'green',alpha=0.6) self.canvas.draw() ##print line except AttributeError: pass def about(self,widget): dialog = gtk.AboutDialog() license='''Expense-Manager is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Expense-Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Expense-Manager; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA''' dialog.set_license(license) dialog.set_wrap_license(False) dialog.set_name('Expense-Manager') dialog.set_copyright('(c) 2013 Souradeep De') dialog.set_website('http://github.com/desouradeep/Expense-Manager') #dialog.set_website_label('http://desouradeep.wordpress.com') dialog.set_authors(['Souradeep De \n email: <*****@*****.**> \n blog: http://desouradeep.wordpress.com']) dialog.set_program_name('Expense-Manager') dialog.set_version('1.0') dialog.run() dialog.destroy() def edit(self,widget): self.treeView.set_model(self.create_model()) model=self.treeView.get_model() edit.edit(self.fname) #print 1 update_list.main(self.fname) self.treeView.set_model(self.create_model()) model=self.treeView.get_model() '''print 1 for i in model: for j in i: print j, print print 2 ''' self.graphs(1) self.graphs(2) stats.update(self.fname) stats.treeView.set_model(stats.create_model(self)) try: viewer.update(self,'') viewer.treeView.set_model(viewer.create_model(self)) except AttributeError: pass def select_years(self): #this method selects the years to be stored in the years combobox liststore2 = gtk.ListStore(str) f=open(app.data_location+'years','a') f.close() f=open(app.data_location+'years','r') yrs=f.readlines() f.close() #print 1 x=0 y=0 for i in yrs: #print 'i = '+i[0:-1] i=i[0:-1] x=x+1 if int(i)==self.yy: y=x #print y liststore2.append([i]) #print yrs cell = gtk.CellRendererText() self.combobox2 = gtk.ComboBox(liststore2) self.combobox2.set_active(y-1) #activating the current year if records exist self.combobox2.pack_start(cell, True) self.combobox2.add_attribute(cell, "text", 0) #print type(self.yy) self.combobox2.connect('changed',self.changed_item_years) #self.combobox2.set_active(2012) a= self.combobox2.get_active_text() #print type(a) def changed_item_years(self,widget): #activated when combobox value holding years is changed #creates a file(if not present) and opens it and reads its contents self.fname=app.data_location+str(widget.get_active_text())+'_'+self.combobox.get_active_text() f=open(self.fname,'a') f.close() f=open(self.fname,'r') x=f.readlines() f.close() #print 1 update_list.main(self.fname) try: self.treeView.set_model(self.create_model()) #model=self.treeView.get_model() except AttributeError: pass self.graphs(1) self.graphs(2) stats.update(self.fname) stats.treeView.set_model(stats.create_model(self)) try: viewer.update(self,'') viewer.treeView.set_model(viewer.create_model(self)) except AttributeError: pass def changed_item(self,widget): #activated when combobox value holding months is changed #self.yy='2012' a= widget.get_active_text() try: #print type(self.combobox2.get_active_text()) self.fname=app.data_location+self.combobox2.get_active_text()+'_'+a #print self.fname f=open(self.fname,'a') f.close() f=open(self.fname,'r') x=f.readlines() f.close() #print 1 update_list.main(self.fname) except AttributeError: f=open(app.data_location+str(self.yy)+'_'+str(self.months[self.mm]),'a') f.close() update_list.main(app.data_location+str(self.yy)+'_'+self.combobox.get_active_text()) pass try: self.treeView.set_model(self.create_model()) #model=self.treeView.get_model() except AttributeError: pass #del self.line self.graphs(1) self.graphs(2) try: stats.update(self.fname) stats.treeView.set_model(stats.create_model(self)) viewer.update(self,self.fname) viewer.treeView.set_model(viewer.create_model(self)) except AttributeError: pass viewer.treeView.set_model(viewer.create_model(self)) except AttributeError: pass def create_model(self): #updates the liststore in treeView store = gtk.ListStore( str, int, int, int, int, int, int) for a in update_list.z: store.append([a[0], a[1], a[2], a[3], a[4], a[5], a[6]]) return store def create_columns(self,treeView): rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("DATE ", rendererText, text=0) column.set_sort_column_id(0) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn('ENTR', rendererText, text=1) column.set_sort_column_id(1) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("FOOD", rendererText, text=2) column.set_sort_column_id(2) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("OTHERS", rendererText, text=3) column.set_sort_column_id(3) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("MOBILE", rendererText, text=4) column.set_sort_column_id(4) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("TRANSPORT", rendererText, text=5) column.set_sort_column_id(5) treeView.append_column(column) rendererText = gtk.CellRendererText() column = gtk.TreeViewColumn("TOTAL", rendererText, text=6) column.set_sort_column_id(6) treeView.append_column(column) def gocl(self,btn): newEntry.newEntry(self.combobox2) self.changed_item(self.combobox) self.changed_item_years(self.combobox2) def on_activated(self,widget): #single click on the treeView model=widget.get_model() #b= self.treeView.get_selection() b=self.treeView.get_cursor() row=0 for i in b[0]: row= int(i) x=app.data_location+str(self.combobox2.get_active_text())+'_'+ model[row][0] #print x viewer.update(self,x) viewer.treeView.set_model(viewer.create_model(self)) #print 1 def terminate(self,a,r): clean_database.clean() sys.exit(0)
class SMCPlotGui: """ PYGtk GUI class wrapper for displaying SMC gridded data """ def __init__(self, filename=None): # initialise some variables: self.ncfn = filename self.pc = None self.cfacs = None self.proj = None self.src_proj = None self.lon1 = None self.lon2 = None self.lat1 = None self.lat2 = None ############### ## GTK setup ## ############### # create new window self.win = gtk.Window(gtk.WINDOW_TOPLEVEL) ###################### # setup window ###################### self.win.set_border_width(10) self.win.set_default_size(600, 400) self.win.set_title('SMC Gridded Data Plotter') ###################### # add the GTK canvas: ###################### self.fig = plt.Figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.fig) ################ # Add menu bar # ################ menu_bar = gtk.MenuBar() file_menu = gtk.Menu() open_item = gtk.MenuItem("Open") exit_item = gtk.MenuItem("Exit") file_menu.append(open_item) file_menu.append(exit_item) open_item.connect("activate", self.load_event) root_menu = gtk.MenuItem("File") root_menu.set_submenu(file_menu) menu_bar.append(root_menu) ########### # Controls ########## # buttons: btnPlot = gtk.Button('Update Plot') btnPrev = gtk.Button('Prev Time') btnNext = gtk.Button('Next Time') # Field combo box: store = gtk.ListStore(str, str) self.cbox_field = gtk.ComboBox(store) cell = gtk.CellRendererText() self.cbox_field.pack_start(cell, True) self.cbox_field.add_attribute(cell, 'text', 1) store.append(['hs', 'sig wave heihgt']) # Times combo box: store = gtk.ListStore(int, str) self.cbox_times = gtk.ComboBox(store) cell = gtk.CellRendererText() self.cbox_times.pack_start(cell, True) self.cbox_times.add_attribute(cell, 'text', 1) #for i in range(1,61): # store.append([i-1, 'T+%03d' % i]) # Domain combo box: store = gtk.ListStore(str, float, float, float, float) self.cbox_domains = gtk.ComboBox(store) cell = gtk.CellRendererText() self.cbox_domains.pack_start(cell, True) self.cbox_domains.add_attribute(cell, 'text', 0) store.append( ['Full Domain (could be slow)', -999.9, -999.9, -999.9, -999.9]) store.append(['UK', 35.0, 70.0, -15.0, 10.0]) store.append(['South West UK', 49.4, 51.5, -6.7, -1.6]) store.append(['Mediterranean', 29.5, 46.5, -6.0, 36.5]) store.append(['North Atlantic', 20.0, 70.0, -90, 30]) store.append(['West Pacific', -70.0, 70.0, 120, 200]) store.append(['East Pacific', -70.0, 70.0, -160, -68]) store.append(['Arabian Gulf', 23.0, 30.5, 47.5, 59.5]) store.append(['Caspian Sea', 36.0, 47.5, 46.0, 55.5]) store.append(['Black Sea', 40.5, 47.1, 27.0, 42.0]) store.append(['Caribbean', 10.0, 27.5, -86.5, -58.5]) store.append(['South China Sea', -9.5, 24.0, 98.0, 128.0]) store.append(['Australasia', -48, 0.0, 105.0, 179.0]) self.cbox_domains.set_active(1) # Projections: store = gtk.ListStore(object, str) self.cbox_proj = gtk.ComboBox(store) cell = gtk.CellRendererText() self.cbox_proj.pack_start(cell, True) self.cbox_proj.add_attribute(cell, 'text', 1) store.append([ccrs.PlateCarree(), 'Plate Carree']) store.append([ ccrs.RotatedPole(pole_latitude=37.5, pole_longitude=177.5), 'Euro Rotated Pole' ]) store.append([ccrs.Robinson(), 'Robinson']) store.append([ccrs.Mercator(), 'Mercator']) store.append([ccrs.Geostationary(), 'Geostationary']) self.cbox_proj.set_active(0) # coastlines: store = gtk.ListStore(object, str) self.cbox_coast = gtk.ComboBox(store) cell = gtk.CellRendererText() self.cbox_coast.pack_start(cell, True) self.cbox_coast.add_attribute(cell, 'text', 1) store.append([None, 'None']) store.append(['10m', 'High res (10m)']) store.append(['50m', 'Medium res (50m)']) store.append(['110m', 'Low res (110m)']) self.cbox_coast.set_active(3) self.coast = '110m' # lat/lon ranges: self.inLat1 = gtk.Entry() self.inLat2 = gtk.Entry() self.inLon1 = gtk.Entry() self.inLon2 = gtk.Entry() self.domain_changed_event( self.cbox_domains) # update with default domain # Cell size selection cellsbox = gtk.HBox(homogeneous=False, spacing=5) self.chkf1 = gtk.CheckButton("3km") self.chkf2 = gtk.CheckButton("6km") self.chkf3 = gtk.CheckButton("12km") self.chkf4 = gtk.CheckButton("25km") cellsbox.pack_end(self.chkf1) cellsbox.pack_end(self.chkf2) cellsbox.pack_end(self.chkf3) cellsbox.pack_end(self.chkf4) # Colour range box: crangebox = gtk.HBox(homogeneous=False, spacing=5) self.cmin = gtk.Entry() self.cmax = gtk.Entry() self.cauto = gtk.CheckButton('Auto') crangebox.pack_start(self.cmin) crangebox.pack_start(self.cmax) crangebox.pack_start(self.cauto) self.cauto.set_active(True) self.cmin.set_sensitive(False) self.cmax.set_sensitive(False) self.cauto.connect('toggled', self.cauto_changed_event) ## controls layout grid = gtk.Table(rows=8, columns=3) grid.attach(gtk.Label('Field'), 0, 1, 0, 1, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Time'), 0, 1, 1, 2, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Projection'), 0, 1, 2, 3, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Coastline'), 0, 1, 3, 4, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Domain '), 0, 1, 4, 5, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Lat Range'), 0, 1, 5, 6, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Lon Range'), 0, 1, 6, 7, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Cells'), 0, 1, 7, 8, yoptions=gtk.SHRINK) grid.attach(gtk.Label('Colour range'), 0, 1, 8, 9, yoptions=gtk.SHRINK) grid.attach(self.cbox_field, 1, 3, 0, 1, yoptions=gtk.SHRINK) grid.attach(self.cbox_times, 1, 3, 1, 2, yoptions=gtk.SHRINK) grid.attach(self.cbox_proj, 1, 3, 2, 3, yoptions=gtk.SHRINK) grid.attach(self.cbox_coast, 1, 3, 3, 4, yoptions=gtk.SHRINK) grid.attach(self.cbox_domains, 1, 3, 4, 5, yoptions=gtk.SHRINK) grid.attach(self.inLat1, 1, 2, 5, 6, yoptions=gtk.SHRINK) grid.attach(self.inLat2, 2, 3, 5, 6, yoptions=gtk.SHRINK) grid.attach(self.inLon1, 1, 2, 6, 7, yoptions=gtk.SHRINK) grid.attach(self.inLon2, 2, 3, 6, 7, yoptions=gtk.SHRINK) grid.attach(cellsbox, 1, 3, 7, 8, yoptions=gtk.SHRINK) grid.attach(crangebox, 1, 3, 8, 9, yoptions=gtk.SHRINK) #grid.attach(btnPlot, 0, 1, 8, 9, yoptions=gtk.SHRINK, xoptions=gtk.SHRINK) # Hbox for plot buttons btn_hbox = gtk.HBox(homogeneous=False, spacing=5) btn_hbox.pack_start(btnPrev, True, False, 0) btn_hbox.pack_start(btnPlot, True, False, 0) btn_hbox.pack_start(btnNext, True, False, 0) ## File details text view txt = gtk.TextBuffer() txt.set_text('Please load a file') self.tv_file_details = gtk.TextView(txt) vbox = gtk.VBox(spacing=15) vbox.pack_start(grid, False) vbox.pack_start(btn_hbox, False) vbox.pack_end(self.tv_file_details, True) # plot controls from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar toolbar = NavigationToolbar(self.canvas, self.win) #vbox.pack_end(toolbar, False, False) # Top level layout box: topbox = gtk.VBox() topbox.pack_start(menu_bar, expand=False, fill=True) box = gtk.HBox(homogeneous=False, spacing=5) topbox.pack_end(box) # canvas/toolbar layout plotbox = gtk.VBox(homogeneous=False, spacing=0) plotbox.pack_start(self.canvas, expand=True, fill=True) plotbox.pack_end(toolbar, False, False) box.pack_start(plotbox, expand=True, fill=True) box.pack_end(vbox, expand=False, fill=False) self.win.add(topbox) ################### # connect signals: ################### # destroy/delete: self.win.connect("delete_event", self.delete_event) self.win.connect("destroy", self.destroy) btnPlot.connect("clicked", self.plot_event) btnNext.connect("clicked", self.next_time_event) btnPrev.connect("clicked", self.prev_time_event) self.cbox_domains.connect('changed', self.domain_changed_event) # show window self.win.show_all() #### Load file, if passed in: if self.ncfn is not None: self.loadfile(self.ncfn) def get_cbox_selection(self, combobox, col=0): model = combobox.get_model() active = combobox.get_active() if active < 0: return None return model[active][col] def delete_event(self, widget, event, data=None): # returning false after a delete event destroys the widget, # returning true means you don't want to destroy the widget. return False def cauto_changed_event(self, widget, data=None): # update the lat/lon boxes: active = widget.get_active() self.cmin.set_sensitive(not active) self.cmax.set_sensitive(not active) def domain_changed_event(self, widget, data=None): # update the lat/lon boxes: model = widget.get_model() active = widget.get_active() if active < 0: return for i, o in enumerate( [self.inLat1, self.inLat2, self.inLon1, self.inLon2]): val = model[active][i + 1] if val < -900.0: val = '' else: val = str(val) o.set_text(val) def destroy(self, widget, data=None): gtk.main_quit() def load_event(self, widget, data=None): # pop up a file selectro dialog and load the file if self.selectfile(): self.loadfile(self.ncfn) def selectfile(self): dlg = gtk.FileChooserDialog(title='Select a SMC netCDF file', action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dlg.set_default_response(gtk.RESPONSE_OK) ret = dlg.run() if ret == gtk.RESPONSE_OK: self.ncfn = dlg.get_filename() dlg.destroy() return (ret == gtk.RESPONSE_OK) def loadfile(self, fn): self.d = nc.Dataset(fn, mode='r') if self.d.dimensions.has_key('seapoint'): seapoint_dim = 'seapoint' else: seapoint_dim = 'seapoints' # populate text bxo with file details txt = self.tv_file_details.get_buffer() txt.set_text('File details:\n' + '\tNo. sea points: %d\n' % len(self.d.dimensions[seapoint_dim]) + '\tNo. times: %d\n' % len(self.d.dimensions['time'])) # update the fields combobox store = self.cbox_field.get_model() store.clear() store.append(['grid', 'Grid mesh only']) for varname, var in self.d.variables.items(): if var.ndim == 2 and hasattr(var, 'long_name'): store.append([varname, var.long_name]) if var.ndim == 3 and hasattr(var, 'long_name'): store.append(["ens_" + varname, var.long_name + " (ens)"]) self.cbox_field.set_active(0) # find location of uwnd or vwnd and insert a wspd option (this will calculate # a wind speed field from uwnd and vwnd): i = store.get_iter_first() while i is not None: varname = store.get_value(i, 0) if varname in ['uwnd', 'vwnd']: # insert new field here: store.insert_before(i, ['wspd_derived', 'wind speed (derived)']) break i = store.iter_next(i) # update times text box: store = self.cbox_times.get_model() store.clear() t = self.d.variables['time'] t = nc.num2date(t[:], t.units) for itime, fctime in enumerate(t): store.append([ itime, "%s (T+%03d)" % (fctime.strftime("%d/%m/%Y %H:%M"), itime + 1) ]) self.cbox_times.set_active(0) # get model extents: try: self.minlat = float(self.d.southernmost_latitude) self.maxlat = float(self.d.northernmost_latitude) self.minlon = float(self.d.westernmost_longitude) self.maxlon = float(self.d.easternmost_longitude) except: self.minlat = -90 self.maxlat = 90 self.minlon = 0 self.maxlon = 360 return def plot_event(self, widget, data=None): self.plotfield() def next_time_event(self, widget, data=None): # move to next timestep and replot itime = self.get_cbox_selection(self.cbox_times) if itime is None: return itime = itime + 1 ntimes = len(self.cbox_times.get_model()) if itime >= ntimes: itime = 0 self.cbox_times.set_active(itime) self.plot_event(None) def prev_time_event(self, widget, data=None): # move to next timestep and replot itime = self.get_cbox_selection(self.cbox_times) if itime is None: return itime = itime - 1 ntimes = len(self.cbox_times.get_model()) if itime < 0: itime = ntimes - 1 self.cbox_times.set_active(itime) self.plot_event(None) def getfloat(self, string): try: return float(string) except ValueError: return None def plotfield(self): # get reference to details text view and clear it txt = self.tv_file_details.get_buffer() start_iter = txt.get_start_iter() end_iter = txt.get_end_iter() txt.delete(start_iter, end_iter) end_iter = txt.get_end_iter() # get required field, time, etc: var = self.get_cbox_selection(self.cbox_field) if var.startswith('ens_'): var = var[4:] ens = True else: ens = False itime = self.get_cbox_selection(self.cbox_times) # get lat/lon ranges lat1 = self.getfloat(self.inLat1.get_text()) lat2 = self.getfloat(self.inLat2.get_text()) lon1 = self.getfloat(self.inLon1.get_text()) lon2 = self.getfloat(self.inLon2.get_text()) # get celfacs: cfacs = [] if self.chkf1.get_active(): cfacs.append(1) if self.chkf2.get_active(): cfacs.append(2) if self.chkf3.get_active(): cfacs.append(4) if self.chkf4.get_active(): cfacs.append(8) if len(cfacs) == 0: cfacs = None if cfacs != self.cfacs: self.pc = None self.cfacs = cfacs if (lat1 != self.lat1 or lat2 != self.lat2 or lon1 != self.lon1 or lon2 != self.lon2): self.pc = None self.lat1 = lat1 self.lat2 = lat2 self.lon1 = lon1 self.lon2 = lon2 proj = self.get_cbox_selection(self.cbox_proj) if self.proj != proj: self.proj = proj self.pc = None self.fig.clf() self.ax = self.fig.add_subplot(111, projection=self.proj) sm = plt.cm.ScalarMappable(norm=plt.Normalize()) sm._A = [] self.cbar = plt.colorbar(sm, ax=self.ax, orientation='horizontal', fraction=0.05, shrink=0.8, pad=0.04) coast = self.get_cbox_selection(self.cbox_coast) if self.coast != coast: newcoast = True self.coast = coast else: newcoast = False ax = self.ax # determin extents: if isinstance(proj, ccrs.Geostationary) or (lon1 is None and lon2 is None and lat1 is None and lat2 is None): ax.set_global() global_extent = True else: if lon1 is None: lon1 = self.minlon if lon2 is None: lon2 = self.maxlon if lat1 is None: lat1 = self.minlat if lat2 is None: lat2 = self.maxlat global_extent = False ## check source projection of requested variable: chkvar = var if var == 'wspd_derived': chkvar = 'uwnd' if var == 'grid': chkvar = 'hs' if hasattr(self.d.variables[chkvar], "grid_mapping"): # get rotated pole projection: mapname = self.d.variables[chkvar].grid_mapping gmap = self.d.variables[mapname] plat = gmap.grid_north_pole_latitude plon = gmap.grid_north_pole_longitude src_proj = ccrs.RotatedPole(pole_latitude=plat, pole_longitude=plon) else: src_proj = None if self.src_proj != src_proj: # source projection changed need to update patches: self.pc = None self.src_proj = src_proj # If patch collection not yet calculated, then build it now and add it to # the axis along with the coastlines: if self.pc is None: txt.insert(end_iter, "Domain has changed - recalculating patches...") while gtk.events_pending(): gtk.main_iteration_do(True) self.pc = smc.generate_patch_collection(self.d, lon1=self.lon1, lon2=self.lon2, lat1=self.lat1, lat2=self.lat2, target_crs=self.proj, cfacs=cfacs, source_crs=self.src_proj) end_iter = txt.get_end_iter() txt.insert(end_iter, "Done\n") while gtk.events_pending(): gtk.main_iteration_do(True) end_iter = txt.get_end_iter() txt.insert(end_iter, "Adding patches to axes\n") print("Adding patches to axes\n") while gtk.events_pending(): gtk.main_iteration_do(True) ax.cla() self.cm = ax.add_collection(self.pc.pcol) if not global_extent: ax.set_extent((lon1, lon2, lat1, lat2), crs=ccrs.PlateCarree()) if self.coast is not None: end_iter = txt.get_end_iter() txt.insert(end_iter, "Adding coastline\n") while gtk.events_pending(): gtk.main_iteration_do(True) ax.coastlines(resolution=self.coast) elif newcoast: # coastline changed; clear axis and redraw: ax.cla() end_iter = txt.get_end_iter() txt.insert(end_iter, "Adding patches to axes\n") while gtk.events_pending(): gtk.main_iteration_do(True) self.cm = ax.add_collection(self.pc.pcol) if not global_extent: ax.set_extent((lon1, lon2, lat1, lat2), crs=ccrs.PlateCarree()) if self.coast is not None: end_iter = txt.get_end_iter() txt.insert(end_iter, "Adding coastline\n") while gtk.events_pending(): gtk.main_iteration_do(True) ax.coastlines(resolution=self.coast) # update the patch face colours with the new data: end_iter = txt.get_end_iter() txt.insert(end_iter, "Updating patches...\n") while gtk.events_pending(): gtk.main_iteration_do(True) if var == 'grid': # special case - just plot grid mesh: self.pc.pcol.set_facecolor('#EAEAEA') self.pc.pcol.set_edgecolor('#5E5E5E') self.pc.pcol.set_linewidth(0.5) cmin = 0 cmax = 1 else: # load field and set face colours if var == 'wspd_derived': end_iter = txt.get_end_iter() txt.insert(end_iter, "Deriving wind speed from uwnd and vwnd fields\n") fld = self.d.variables['uwnd'] fld2 = self.d.variables['vwnd'] dat = np.sqrt( np.power(fld[itime, :][self.pc.mask], 2) + np.power(fld2[itime, :][self.pc.mask], 2)) else: fld = self.d.variables[var] if ens: dat = fld[0, itime, :][self.pc.mask] # just get member 0 else: dat = fld[itime, :][self.pc.mask] if self.cauto.get_active(): cmin = dat.min() cmax = dat.max() self.cmin.set_text("%.2f" % cmin) self.cmax.set_text("%.2f" % cmax) else: cmin = self.getfloat(self.cmin.get_text()) cmax = self.getfloat(self.cmax.get_text()) clrs = smc.generate_color_array(dat, cmin=cmin, cmax=cmax) self.pc.pcol.set_facecolor(clrs) self.pc.pcol.set_edgecolor(clrs) self.pc.pcol.set_linewidth(0.5) # update colorbar mappable with new range: self.cbar.mappable.set_clim(cmin, cmax) ## update title fldname = self.get_cbox_selection(self.cbox_field, 1) time = self.get_cbox_selection(self.cbox_times, 1) ax.set_title("%s @ %s" % (fldname, time), fontsize=12) # update canvas self.canvas.draw() end_iter = txt.get_end_iter() txt.insert(end_iter, "Done.\n") while gtk.events_pending(): gtk.main_iteration_do(True) def main(self): gtk.main()
class DataMatrixGuiXYProbe(gtk.Window): """ 2009-3-13 migrated from QCVisualize.py. now become a standalone program and able to read data from a file and plot ... QCVisualize.py inherits from here 2008-02-05 embed it into a bigger gnome app, add more buttons, and change the __init__() 2008-01-01 class to visualize the results from QualityControl.py """ def __init__(self, plot_title='', id_is_strain=1, header=None, strain_acc_list=None, category_list=None, data_matrix=None): """ 2008-01-10 use a paned window to wrap the scrolledwindow and the canvas so that the relative size of canvas to the scrolledwindow could be adjusted by the user. """ prog = gnome.program_init('DataMatrixGuiXYProbe', '0.1') #this must be called before any initialization for gnome app program_path = os.path.dirname(__init__.__file__) #sys.argv[0]) xml = gtk.glade.XML(os.path.join(program_path, 'DataMatrixGuiXYProbe.glade')) xml.signal_autoconnect(self) self.app1 = xml.get_widget("app1") self.app1.connect("delete_event", gtk.main_quit) self.app1.set_default_size(800, 1000) self.app1.set_title(plot_title) self.plot_title = plot_title self.id_is_strain = id_is_strain self.header = header self.strain_acc_list = strain_acc_list self.category_list = category_list self.data_matrix = data_matrix self.column_types = None self.column_header = None self.column_editable_flag_ls = None self.list_2d = None self.column_types = None self.list_2d = None self.column_header = None self.editable_flag_ls = None self.vbox1 = xml.get_widget("vbox1") self.treeview_matrix = xml.get_widget("treeview_matrix") # matplotlib stuff fig = Figure(figsize=(8,8)) self.canvas = FigureCanvas(fig) # a gtk.DrawingArea self._idClick = self.canvas.mpl_connect('button_press_event', self.onUserClickCanvas) self.vpaned1 = xml.get_widget("vpaned1") self.vpaned1.add2(self.canvas) #vbox.pack_start(self.canvas, True, True) self.ax = fig.add_subplot(111) self.treeview_matrix.connect('row-activated', self.plot_row) toolbar = NavigationToolbar(self.canvas, self.app1) self.vbox1.pack_start(toolbar, False, False) self.checkbutton_label_dot = xml.get_widget('checkbutton_label_dot') self.entry_dot_label_column = xml.get_widget('entry_dot_label_column') self.entry_x_na = xml.get_widget('entry_x_na') self.entry_y_na = xml.get_widget('entry_y_na') self.entry_multiply_x = xml.get_widget('entry_multiply_x') self.entry_multiply_y = xml.get_widget('entry_multiply_y') self.entry_add_x = xml.get_widget('entry_add_x') self.entry_add_y = xml.get_widget('entry_add_y') self.entry_x_error = xml.get_widget("entry_x_error") self.entry_y_error = xml.get_widget("entry_y_error") self.checkbutton_logX = xml.get_widget('checkbutton_logX') #2014.06.09 self.checkbutton_logY = xml.get_widget('checkbutton_logY') self.entry_x_column = xml.get_widget('entry_x_column') self.entry_y_column = xml.get_widget('entry_y_column') #self.checkbutton_histLogX = xml.get_widget('checkbutton_histLogX') #2014.06.09 #self.checkbutton_histLogY = xml.get_widget('checkbutton_histLogY') self.entry_hist_column = xml.get_widget('entry_hist_column') self.entry_no_of_bins = xml.get_widget('entry_no_of_bins') #2009-5-20 self.entry_plot_title = xml.get_widget('entry_plot_title') self.entry_plot_title.set_text(self.plot_title) self.filechooserdialog_save = xml.get_widget("filechooserdialog_save") self.filechooserdialog_save.connect("delete_event", yh_gnome.subwindow_hide) self.entry_sampling_probability = xml.get_widget("entry_sampling_probability") self.filechooserdialog_open = xml.get_widget("filechooserdialog_open") self.filechooserdialog_open.connect("delete_event", yh_gnome.subwindow_hide) self.app1_appbar1 = xml.get_widget('app1_appbar1') self.app1_appbar1.push('Status Message.') #import gnome.ui has to be executed. self.treeview_matrix.connect('cursor-changed', self.update_no_of_selected, self.app1_appbar1) self.app1.show_all() self.xValuePreProcessor = None self.yValuePreProcessor = None self.x_error_column_index = None self.y_error_column_index = None #self.add_events(gdk.BUTTON_PRESS_MASK|gdk.KEY_PRESS_MASK|gdk.KEY_RELEASE_MASK) def onUserClickCanvas(self, event): """ 2009-3-13 use (x_lim[1]-x_lim[0])/200. as the resolution for a dot to be called identical to a data point. similar for the y_data 2009-3-13 deal with checkbutton_label_dot, entry_dot_label_column, entry_x_column, entry_y_column 2008-01-01 derived from on_click_row() of QualityControl.py reaction when user clicked in the plot """ # get the x and y coords, flip y from top to bottom x, y = event.x, event.y to_label_dot = self.checkbutton_label_dot.get_active() dot_label_column = int(self.entry_dot_label_column.get_text()) x_column = int(self.entry_x_column.get_text()) y_column = int(self.entry_y_column.get_text()) x_lim = self.ax.get_xlim() x_grain_size = (x_lim[1]-x_lim[0])/200. y_lim = self.ax.get_ylim() y_grain_size = (y_lim[1]-y_lim[0])/200. if event.button==1: if event.inaxes is not None: print 'data coords', event.xdata, event.ydata if self.list_2d is None: return for row in self.list_2d: if row[x_column] and row[y_column]: #not empty try: x_data = float(row[x_column]) y_data = float(row[y_column]) x = self.processDataValue(x_data, self.xValuePreProcessor) if x is None: continue y = self.processDataValue(y_data, self.yValuePreProcessor) if y is None: continue if abs(x-event.xdata)<x_grain_size and abs(y-event.ydata)<y_grain_size: info = row[dot_label_column] if to_label_dot: self.ax.text(event.xdata, event.ydata, info, size=8) self.canvas.draw() sys.stderr.write("%s: %s, %s: %s, raw xy=(%s, %s), scaled xy=(%s,%s), info: %s.\n"%\ (self.column_header[0], row[0], self.column_header[1], row[1], row[x_column], row[y_column], x,y, info)) except: sys.stderr.write("Column %s, %s of row (%s), could not be converted to float. skip.\n"%\ (x_column, y_column, repr(row))) def setUserDataPreprocessingFlags(self): """ 2014.07.25 """ self.xValuePreProcessor = ValuePreProcessor(na = self.entry_x_na.get_text()) self.yValuePreProcessor = ValuePreProcessor(na = self.entry_y_na.get_text()) if self.entry_multiply_x.get_text(): self.xValuePreProcessor.scalar = float(self.entry_multiply_x.get_text()) if self.entry_multiply_y.get_text(): self.yValuePreProcessor.scalar = float(self.entry_multiply_y.get_text()) if self.entry_add_x.get_text(): self.xValuePreProcessor.addition = float(self.entry_add_x.get_text()) if self.entry_add_y.get_text(): self.yValuePreProcessor.addition = float(self.entry_add_y.get_text()) if self.entry_x_error.get_text(): self.xValuePreProcessor.errorColumnIndex = int(self.entry_x_error.get_text()) if self.entry_y_error.get_text(): self.yValuePreProcessor.errorColumnIndex = int(self.entry_y_error.get_text()) if self.checkbutton_logX.get_active(): self.xValuePreProcessor.logScale = True if self.checkbutton_logY.get_active(): self.yValuePreProcessor.logScale = True def processDataValue(self, value=None, valuePreProcessor=None): """ 2014.07.31 """ if valuePreProcessor.na is not None and (value==valuePreProcessor.na or float(value)==float(valuePreProcessor.na)): return None value = float(value) if valuePreProcessor.scalar is not None: value = value*valuePreProcessor.scalar if valuePreProcessor.addition is not None: value = value + valuePreProcessor.addition return value def decorateAxisLabel(self, label=None, valuePreProcessor=None): """ 2014.07.31 """ if valuePreProcessor.scalar is not None: label = "%s*%s"%(valuePreProcessor.scalar, label) if valuePreProcessor.addition: label = "%s+%s"%(label, valuePreProcessor.addition) return label def plotXY(self, ax, canvas, liststore, plot_title='', chosen_index_ls=[]): """ 2015.01.28 add summary stats to title 2014.04.29 add error bars 2009-3-13 rename plot_NA_mismatch_rate to plotXY() 2008-02-05 chosen_index => chosen_index_ls 2007-12-14 """ x_column = int(self.entry_x_column.get_text()) y_column = int(self.entry_y_column.get_text()) self.setUserDataPreprocessingFlags() plot_title = self.entry_plot_title.get_text() min_x = 1 min_y = 1 max_x = 0 max_y = 0 x_ls = [] x_error_ls = [] y_ls = [] y_error_ls = [] x_chosen_ls = [] x_chosen_error_ls = [] y_chosen_ls = [] y_chosen_error_ls = [] chosen_index_set = set(chosen_index_ls) for i in range(len(liststore)): row = liststore[i] x = row[x_column] y = row[y_column] if not x or not y: #2013.07.12 skip if empty cells continue x = self.processDataValue(x, self.xValuePreProcessor) if x is None: continue y = self.processDataValue(y, self.yValuePreProcessor) if y is None: continue if self.xValuePreProcessor.errorColumnIndex is not None: x_error = row[self.xValuePreProcessor.errorColumnIndex] else: x_error = 0 if self.yValuePreProcessor.errorColumnIndex is not None: y_error = row[self.yValuePreProcessor.errorColumnIndex] else: y_error = 0 if x<min_x: min_x = x if x>max_x: max_x = x if y<min_y: min_y = y if y>max_y: max_y = y if i in chosen_index_set: x_chosen_ls.append(x) y_chosen_ls.append(y) x_chosen_error_ls.append(x_error) y_chosen_error_ls.append(y_error) else: x_ls.append(x) y_ls.append(y) x_error_ls.append(x_error) y_error_ls.append(y_error) ax.clear() if self.xValuePreProcessor.logScale: ax.set_xscale('log') if self.yValuePreProcessor.logScale: ax.set_yscale('log') if self.x_error_column_index is not None and self.y_error_column_index is not None: ax.errorbar(x_ls, y_ls, xerr=x_error_ls, yerr=y_error_ls, ecolor='g', fmt='o') else: ax.plot(x_ls, y_ls, '.') """ #diagonal line give a rough feeling about the notion, more NA, worse calling diagonal_start = min(min_x, min_y)-0.1 diagonal_end = max(max_x, max_x)+0.1 ax.plot([diagonal_start, diagonal_end],[diagonal_start, diagonal_end]) """ if x_chosen_ls and y_chosen_ls: #highlight titleWithStats = "Highlighted data\n" + yh_matplotlib.constructTitleFromTwoDataSummaryStat(x_chosen_ls, y_chosen_ls) ax.plot(x_chosen_ls, y_chosen_ls, '.', c='r') if self.x_error_column_index is not None and self.y_error_column_index is not None: ax.errorbar(x_chosen_ls, y_chosen_ls, xerr=x_chosen_error_ls, yerr=y_chosen_error_ls, ecolor='r', color='r', fmt='o') else: #take all data titleWithStats = yh_matplotlib.constructTitleFromTwoDataSummaryStat(x_ls+x_chosen_ls, y_ls+y_chosen_ls) if plot_title: ax.set_title("%s %s"%(plot_title, titleWithStats)) else: ax.set_title(titleWithStats) xlabel = "(%s)"%self.column_header[x_column] xlabel = self.decorateAxisLabel(xlabel, self.xValuePreProcessor) ax.set_xlabel(xlabel) ylabel = "(%s)"%self.column_header[y_column] ylabel = self.decorateAxisLabel(ylabel, self.yValuePreProcessor) ax.set_ylabel(ylabel) canvas.draw() def plot_row(self, treeview, path, view_column): if self._idClick==None: self._idClick = self.canvas.mpl_connect('button_press_event', self.onUserClickCanvas) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title, path) def setupColumns(self, treeview): """ 2009-3-13 """ if not getattr(self, 'column_header', None): sys.stderr.write("Nothing in columns yet.\n") return self.liststore = gtk.ListStore(*self.column_types) #self.add_columns(self.treeview_matrix) yh_gnome.create_columns(self.treeview_matrix, self.column_header, self.editable_flag_ls, self.liststore) yh_gnome.fill_treeview(self.treeview_matrix, self.liststore, self.list_2d, reorderable=True) self.treeselection = self.treeview_matrix.get_selection() def on_button_PlotXY_clicked(self, widget, data=None): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) 2008-02-05 """ if self._idClick==None: self._idClick = self.canvas.mpl_connect('button_press_event', self.onUserClickCanvas) pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) index_ls = [] for path in pathlist_strains1: index_ls.append(path[0]) self.app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title, index_ls) def on_button_save_clicked(self, widget, data=None): """ 2008-02-05 """ self.filechooserdialog_save.show_all() def on_button_filechooserdialog_cancel_ok_clicked(self, widget, data=None): """ 2008-02-05 """ self.filechooserdialog_save.hide() def on_button_filechooserdialog_save_ok_clicked(self, widget, data=None): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) 2008-02-05 """ output_fname = self.filechooserdialog_save.get_filename() self.filechooserdialog_save.hide() pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) self.app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) if self.header and self.strain_acc_list and self.category_list and self.data_matrix: selected_index_set = set() for path in pathlist_strains1: row = self.liststore[path[0]] id = row[0] index_in_data_matrix = row[-1] selected_index_set.add(index_in_data_matrix) if self.id_is_strain: id = id[1:-1].split(',') #id is a tuple of (ecotypeid,duplicate) self.strain_acc_list[index_in_data_matrix] = id[0].strip() #remove extra space self.category_list[index_in_data_matrix] = id[1].strip() #else: # self.header[index_in_data_matrix+2] = id FilterStrainSNPMatrix_instance = FilterStrainSNPMatrix() if self.id_is_strain: rows_to_be_tossed_out = set(range(len(self.strain_acc_list))) - selected_index_set FilterStrainSNPMatrix_instance.write_data_matrix(self.data_matrix, output_fname, self.header, self.strain_acc_list, self.category_list,\ rows_to_be_tossed_out, cols_to_be_tossed_out=set(), nt_alphabet=0) else: cols_to_be_tossed_out = set(range(len(self.header)-2)) - selected_index_set FilterStrainSNPMatrix_instance.write_data_matrix(self.data_matrix, output_fname, self.header, self.strain_acc_list, self.category_list,\ rows_to_be_tossed_out=set(), cols_to_be_tossed_out=cols_to_be_tossed_out, nt_alphabet=0) def show_all(self): """ 2008-02-05 preserve the old interface. in order not to change anything in plot_col_NA_mismatch_rate() and plot_row_NA_mismatch_rate() of QualityControl.py """ self.app1.show_all() def on_button_PlotHistogram_clicked(self, widget, data=None): """ 2015.01.28 add summary stats to title 2009-5-20 get the number of bins from entry_no_of_bins 2009-3-13 draw histogram of specific hist_column 2008-02-06 """ if not getattr(self, 'column_header', None): sys.stderr.write("Nothing in columns yet.\n") return self.setUserDataPreprocessingFlags() self.ax.clear() self.canvas.mpl_disconnect(self._idClick) #drop the signal handler self._idClick = None #reset the _idClick hist_ls = [] hist_column = int(self.entry_hist_column.get_text()) for i in range(len(self.liststore)): x = self.liststore[i][hist_column] if not x: continue x = self.processDataValue(x, self.xValuePreProcessor) if x is None: continue if self.xValuePreProcessor.logScale: if x>0: x = math.log10(x) else: sys.stderr.write("x value %s, not good for log10.\n"%(x)) continue hist_ls.append(x) title = "%s %s %s"%(self.plot_title, self.column_header[hist_column], yh_matplotlib.constructTitleFromDataSummaryStat(hist_ls)) self.ax.set_title(title); #"Histogram of %s %s"%(self.plot_title, self.column_header[hist_column])) no_of_bins = int(self.entry_no_of_bins.get_text()) #if self.x_logScale: # self.ax.set_xscale('log') if self.yValuePreProcessor.logScale: self.ax.set_yscale('log') xlabel = "(%s)"%self.column_header[hist_column] xlabel = self.decorateAxisLabel(xlabel, self.xValuePreProcessor) if self.xValuePreProcessor.logScale: xlabel = "log10(%s)"%(xlabel) self.ax.set_xlabel(xlabel) self.ax.hist(hist_ls, no_of_bins) self.canvas.draw() def update_no_of_selected(self, treeview, app1_appbar1): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) """ pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) return True def readInDataToPlot(self, input_fname, sampling_probability=1.0): """ 2015.01.23 added argument sampling_probability to sub-sample data 2013.07.11 use MatrixFile to read in the file 2009-5-20 add the column index into the column header for easy picking 2009-3-13 wrap the float conversion part into try...except to report what goes wrong 2009-3-13 """ if sampling_probability>1 or sampling_probability<0: sampling_probability=1.0 reader = MatrixFile(inputFname=input_fname) self.column_header=reader.next() for i in range(len(self.column_header)): self.column_header[i] = '%s %s'%(i, self.column_header[i]) no_of_cols = len(self.column_header) self.column_types = [str]*2 + [float]*(no_of_cols-2) self.column_editable_flag_ls = [True, True] + [False]*(no_of_cols-2) self.list_2d = [] for row in reader: if sampling_probability>0 and sampling_probability<1: if random.random()>sampling_probability: #skip continue float_part = row[2:] try: float_part = map(float, float_part) except: sys.stderr.write('Except type: %s\n'%repr(sys.exc_info())) traceback.print_exc() new_row = row[:2]+float_part self.list_2d.append(new_row) reader.close() self.setupColumns(self.treeview_matrix) #update status to reflect the input filename self.app1.set_title(os.path.basename(input_fname)) self.app1_appbar1.push(input_fname) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title) def readInRawMatrixData(self, input_fname): """ 2009-3-13 """ delimiter = figureOutDelimiter(input_fname) self.header, self.strain_acc_list, self.category_list, self.data_matrix = read_data(input_fname, delimiter=delimiter) def on_imagemenuitem_open_activate(self, widget, data=None): """ 2009-3-13 """ self.filechooserdialog_open.show_all() def on_button_fileopen_cancel_clicked(self, widget, data=None): """ 2015.01.23 """ self.filechooserdialog_open.hide() def on_button_fileopen_ok_clicked(self, widget, data=None): """ 2009-3-13 """ input_fname = self.filechooserdialog_open.get_filename() sampling_probability = float(self.entry_sampling_probability.get_text()) self.filechooserdialog_open.hide() self.readInDataToPlot(input_fname, sampling_probability) def on_entry_plot_title_change(self, widget, data=None): """ 2009-3-13 upon any change in the entry_plot_title """ self.plot_title = self.entry_plot_title.get_text()
def __init__(self, data=None, orient="LPS", overlay=None, colormap=cm.gray, pixdim=None): ## import sys print sys.argv if data == None: try: fn = sys.argv[1] from mri import img data = img.read(fn) except AttributeError: print "not passing data arg" pass try: data.qform print "think its a nifti volume" nim = data mrdata = nim.data print shape(mrdata) pixdim = nim.voxdim[::-1] except AttributeError: if pixdim != None: print "using user supplied pixeldimensions", pixdim else: print "probably not a nifti volume. using voxel units instead of actual distance units" pixdim = [1.0, 1.0, 1.0] # unitless mrdata = data ## self.win = gtk.Window() # win.connect("destroy", lambda x: gtk.main_quit()) self.win.connect("delete-event", self.hideinsteadofdelete) self.win.set_default_size(600, 600) self.win.set_title("Embedding in GTK") vbox = gtk.VBox() self.win.add(vbox) fig = figure() # figsize=(5,4), dpi=100) # subplots_adjust(left=.15, bottom=.15,right=1, top=.95,wspace=.25, hspace=.35) # a = fig.add_subplot(111) # t = arange(0.0,3.0,0.01) # s = sin(2*pi*t) # a.plot(t,s) # a.plot(data) ax1 = fig.add_subplot(221) # axis('off') # colorbar(fig,ax=ax1) xlabel("Anterior (A->P 1st Dim)") ylabel("Right (R->L 2nd Dim)") ax2 = fig.add_subplot(222) # axis('off') xlabel("Inferior (I->S Dim)") ylabel("Anterior (A->P 1st Dim)") ax3 = fig.add_subplot(223) # axis('off') xlabel("Infererior (I->S 3rd dim)") ylabel("Right (R->L 2nd Dim)") coord = fig.add_subplot(224) axis("off") tracker = IndexTracker(mrdata, ax1, ax2, ax3, colormap, pixdim, overlay, coord) # fig.canvas.mpl_connect('scroll_event', tracker.onscroll) cid = connect("button_press_event", tracker.click) print ("something") sw = gtk.ScrolledWindow() vbox.pack_start(sw) # self.win.add (sw) ## A scrolled window border goes outside the scrollbars and viewport sw.set_border_width(10) # policy: ALWAYS, AUTOMATIC, NEVER sw.set_policy(hscrollbar_policy=gtk.POLICY_AUTOMATIC, vscrollbar_policy=gtk.POLICY_ALWAYS) canvas = FigureCanvas(fig) # a gtk.DrawingArea ##vbox.pack_start(canvas) canvas.set_size_request(300, 200) sw.add_with_viewport(canvas) canvas.draw() # manager = get_current_fig_manager() ## you can also access the window or vbox attributes this way # toolbar = manager.toolbar ##vbox.pack_start(canvas) # toolbar = NavigationToolbar(canvas, self.win) ##vbox.pack_start(toolbar, False, False) # show() # print tracker # # fig.show() self.win.show_all()
class Gtk_NetworkCanvas: """Gtk_NetworkCanvas class. This class contains the canvas to draw the topology. It implements event listener and zoom. Parameters ---------- canvas : the gtk canvas to draw adjustement : used for zoom scroll bar zoom_scale : a scroll bar to zoom redraw : a button to redraw the graph popup : a popup for interaction on right click bRefresh : bool. if True enable refresh with do_refresh function corners : the limit of the canvas drawing area press : bool. True if mouse click on canvas (used for zoom) x_old, y_old : position for zoom """ def __init__(self): fig = plt.figure(num=None, facecolor='w', edgecolor='k') plt.axis('off') plt.subplots_adjust(left=0., right=1., bottom=0., top=1., wspace=0.2, hspace=0.2) self.canvas = FigureCanvas(fig) self.canvas.add_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.canvas.connect("motion_notify_event", self.on_motion) self.canvas.connect("button-press-event", self.on_click) self.canvas.connect("button-release-event", self.on_release) self.canvas.connect("scroll-event", self.on_scroll) self.canvas.connect("leave-notify-event", self.on_lose_focus) self.adjustement = gtk.Adjustment(0.0, 0.0, 100.0, 1.0, 1.0, 1.0) self.adjustement_signal = self.adjustement.connect( "value-changed", self.on_zoom_changed) self.zoom_scale = gtk.HScale(self.adjustement) self.zoom_scale.set_draw_value(False) self.zoom_value = 0.0 self.redraw = gtk.Button("Redraw") self.redraw.connect("clicked", self.on_redraw) self.hbox = gtk.HBox() self.hbox.pack_start(self.zoom_scale, True, True, 0) self.hbox.pack_end(self.redraw, False, False, 0) self.vbox = gtk.VBox() self.vbox.pack_start(self.canvas, True, True, 0) self.vbox.pack_end(self.hbox, False, False, 0) self.popup = Gtk_NewtworkPopupMenu() self.bRefresh = True self.corners = None self.press = False self.x_old = 0 self.y_old = 0 self.bg_img = None self.i = 1 def on_click(self, widget, event): """Event listener : click If double left click : - on edge, show edges rules - on firewall, show firewall conf - on interface, add note If left click : - on edge, show message - on firewall, show message interaction firewall - on interface, show message interaction interface - else move x/y limit drawing area If right click : - on edge, show edge menu - on firewall, show firewall menu - on interface, show interface menu - else show canvas menu """ if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: dbl_click = False dbl_click |= self.on_dblclick_edge() dbl_click |= self.on_dblclick_node() if not dbl_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message( Gtk_Message.TOPOLOGY_MESSAGE) if event.button == 3 and event.type == gtk.gdk.BUTTON_PRESS: right_click = False right_click |= self.on_right_click_edge(event) right_click |= self.on_right_click_node(event) if not right_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message( Gtk_Message.ON_BACKGROUND_CLICK) self.popup.popup_clear(event) if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS: left_click = False left_click |= self.on_left_click_edge() left_click |= self.on_left_click_node() if not left_click: self.press = True self.x_old = event.x self.y_old = event.y Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message( Gtk_Message.TOPOLOGY_MESSAGE) return True def on_dblclick_edge(self): """Show interface rules""" def get_firewall(x, y): if isinstance(x, Firewall): return x elif isinstance(y, Firewall): return y return None def get_ip(x, y): if isinstance(x, Ip): return x elif isinstance(y, Ip): return y return None g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: fw = get_firewall(elem[0], elem[1]) ip = get_ip(elem[0], elem[1]) result = [] [ result.append(acl) for acl in g.get_acl_list(src=ip, dst=None, firewall=fw) ] [ result.append(acl) for acl in g.get_acl_list(src=None, dst=ip, firewall=fw) ] if not result: Gtk_DialogBox("No rules found for this interface !") [ Gtk_Main.Gtk_Main().notebook.add_interface_tab(acl) for acl in result ] return True return False def on_dblclick_node(self): """Event listener, on double click node, if firewall show conf file else add note""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press and isinstance(v['object'].object, Firewall): Gtk_Main.Gtk_Main().notebook.add_conf_tab( v['object'].object.name, v['object'].object.hostname) return True if v['object'].gtk_press and isinstance(v['object'].object, Ip): self.popup.node = v['object'] self.popup.on_add_note(None) return True return False def on_right_click_edge(self, event): """Event listener, on right click edge, popup menu showing acl list of related to this interface""" g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: self.popup.popup(elem, event, edge) edge.gtk_press = False return True return False def on_right_click_node(self, event): """Event listener, on right click node, show popup menu for node""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: self.popup.popup(None, event, v['object']) v['object'].gtk_press = False return True return False def on_left_click_node(self): """Show node details""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message( Gtk_Message.ON_CLICK_NODE) Gtk_Main.Gtk_Main().lateral_pane.details.clear() tmp_intf = [ e[2]['object'].object for e in g.graph.edges(k, data=True) ] if isinstance(tmp_intf, Interface): for e in sorted(tmp_intf, key=lambda tmp_intf: tmp_intf.nameif): message = "%s:\n- %s\n- %s" % (e.nameif, e.name, e.network.to_string()) for key, value in e.attributes.items(): message += "\n- %s : %s" % (key, value) Gtk_Main.Gtk_Main().lateral_pane.details.add_row( message) Gtk_Main.Gtk_Main().lateral_pane.focus_details() return True if isinstance(v['object'].object, Route_info): lateral_pane = Gtk_Main.Gtk_Main().lateral_pane notebook_routes = Gtk_Main.Gtk_Main( ).lateral_pane.notebook_routes treeview_routes = Gtk_Main.Gtk_Main( ).lateral_pane.routes_tab_treeview scrolled_window = lateral_pane.routes_tab_treeview.scrolled_window data = v['object'].object.data notebook_routes.notebook.set_tab_label( scrolled_window, gtk.Label('Networks reached by ' + v['object'].object.iface.nameif)) treeview_routes.clear() for gateway, networks in data.iteritems(): parent = treeview_routes.add_row(None, gateway, foreground='black', background='grey') for network in networks: treeview_routes.add_row(parent, network) if lateral_pane.vpane.get_child1( ) == lateral_pane.notebook_path.notebook: lateral_pane.vpane.remove( lateral_pane.notebook_path.notebook) elif lateral_pane.vpane.get_child1( ) == lateral_pane.notebook_details.notebook: lateral_pane.vpane.remove( lateral_pane.notebook_details.notebook) lateral_pane.vpane.pack1( lateral_pane.notebook_routes.notebook, True, False) lateral_pane.vpane.pack2(lateral_pane.help_message.eb, True, False) Gtk_Main.Gtk_Main().hpaned.set_position( 4 * Gtk_Main.Gtk_Main().window.get_size()[0] / 5) lateral_pane.vpane.show_all() return False def on_left_click_edge(self): """If left click edge, show help message""" g = NetworkGraph.NetworkGraph() for edge in g.graph.edges(): if g.graph[edge[0]][edge[1]]['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message( Gtk_HelpMessage.Gtk_Message.ON_CLICK_EDGE) return True return False def on_motion(self, widget, event): """If not click node, then move axis""" if self.press and self.corners: xlim = list(plt.gca().get_xlim()) ylim = list(plt.gca().get_ylim()) x = (self.x_old - event.x) / (1. * self.canvas.window.get_size()[0] / (xlim[1] - xlim[0])) y = (event.y - self.y_old) / (1. * self.canvas.window.get_size()[1] / (ylim[1] - ylim[0])) self.x_old = event.x self.y_old = event.y self.axes_move(x, y, x, y) self.do_refresh() def refresh(self): """refresh function. This function is call periodically by do_refresh""" self.bRefresh = True def do_refresh(self): """Update the graph if bRefresh is True""" if self.bRefresh: self.bRefresh = False self.canvas.draw() gtk.timeout_add(30, self.refresh) def on_release(self, widget, event): """Event listener : release""" self.press = False def on_scroll(self, widget, event): """Event listener : scroll. Update zoom""" if event.direction == 0 and self.adjustement.get_value() < 99: self.adjustement.set_value(self.adjustement.get_value() + 1) elif event.direction == 1 and self.adjustement.get_value() > 0: self.adjustement.set_value(self.adjustement.get_value() - 1) def on_zoom_changed(self, widget): """Event listerner : HScale change. Update zoom""" if self.corners: im = None if self.bg_img: im = self.bg_img.get_children()[0] if widget.value != 0: zoom = (self.zoom_value - widget.value) * ( self.corners[1][0] - self.corners[0][0]) / 200 self.axes_zoom(-zoom, -zoom, zoom, zoom) if im: dim = min( 1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data'])) corners = min(self.corners[1][0] - self.corners[0][0], self.corners[1][1] - self.corners[0][1]) im.set_zoom(im.get_zoom() - zoom * 2 * dim / corners) else: plt.gca().set_xlim((self.corners[0][0], self.corners[1][0])) plt.gca().set_ylim((self.corners[0][1], self.corners[1][1])) if im: im.set_zoom( min( 1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.zoom_value = widget.value self.do_refresh() def on_lose_focus(self, widget, event): """Event listener : focus""" self.press = False NetworkGraph.NetworkGraph().node_click = False for node in NetworkGraph.NetworkGraph().graph.nodes(data=True): node[1]['object'].press = False for edge in NetworkGraph.NetworkGraph().graph.edges(data=True): edge[2]['object'].press = False self.do_refresh() def on_redraw(self, widget): """Event listener : button redraw""" self.draw() def axes_move(self, x0, y0, x1, y1): """Change axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if ((x0 < 0 and x[0] + x0 >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1])) and \ ((x1 > 0 and x[1] + x1 <= self.corners[1][0]) or (x1 < 0 and x[1] + x1 > x[0])): x[0] += x0 x[1] += x1 if ((y0 < 0 and y[0] + y0 >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1])) and \ ((y1 > 0 and y[1] + y1 <= self.corners[1][1]) or (y1 < 0 and y[1] + y1 > y[0])): y[0] += y0 y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def axes_zoom(self, x0, y0, x1, y1): """Zoom axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if (x0 < 0 and x[0] >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1]): x[0] += x0 if (x1 > 0 and x[1] <= self.corners[1][0]) or (x1 < 0 and x[1] - x1 > x[0]): x[1] += x1 if (y0 < 0 and y[0] >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1]): y[0] += y0 if (y1 > 0 and y[1] <= self.corners[1][1]) or (y1 < 0 and y[1] - y1 > y[0]): y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def background_image(self, file): """Set the file image as background image""" if self.bg_img: self.bg_img.remove() datafile = get_sample_data(file) img = plt.imread(datafile) im = OffsetImage(img) im.set_zoom( min( 1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False) self.bg_img.set_zorder(-1) plt.gca().add_artist(self.bg_img) self.do_refresh() def draw(self): """Draw the netowrk graph and set limit corners""" g = NetworkGraph.NetworkGraph() g.layout_graph() g.draw(self.canvas) self.corners = (-0.05, -0.05), (1.05, 1.05) plt.gca().set_xlim((-0.05, 1.05)) plt.gca().set_ylim((-0.05, 1.05)) self.do_refresh()
class DataMatrixGuiXYProbe(gtk.Window): """ 2009-3-13 migrated from QCVisualize.py. now become a standalone program and able to read data from a file and plot ... QCVisualize.py inherits from here 2008-02-05 embed it into a bigger gnome app, add more buttons, and change the __init__() 2008-01-01 class to visualize the results from QualityControl.py """ def __init__(self, plot_title='', id_is_strain=1, header=None, strain_acc_list=None, category_list=None, data_matrix=None): """ 2008-01-10 use a paned window to wrap the scrolledwindow and the canvas so that the relative size of canvas to the scrolledwindow could be adjusted by the user. """ prog = gnome.program_init('DataMatrixGuiXYProbe', '0.1') #this must be called before any initialization for gnome app program_path = os.path.dirname(__init__.__file__) #sys.argv[0]) xml = gtk.glade.XML(os.path.join(program_path, 'DataMatrixGuiXYProbe.glade')) xml.signal_autoconnect(self) self.app1 = xml.get_widget("app1") self.app1.connect("delete_event", gtk.main_quit) self.app1.set_default_size(800, 1000) self.app1.set_title(plot_title) self.plot_title = plot_title self.id_is_strain = id_is_strain self.header = header self.strain_acc_list = strain_acc_list self.category_list = category_list self.data_matrix = data_matrix self.column_types = None self.column_header = None self.column_editable_flag_ls = None self.list_2d = None self.column_types = None self.list_2d = None self.column_header = None self.editable_flag_ls = None self.vbox1 = xml.get_widget("vbox1") self.treeview_matrix = xml.get_widget("treeview_matrix") # matplotlib stuff fig = Figure(figsize=(8,8)) self.canvas = FigureCanvas(fig) # a gtk.DrawingArea self._idClick = self.canvas.mpl_connect('button_press_event', self.on_click) self.vpaned1 = xml.get_widget("vpaned1") self.vpaned1.add2(self.canvas) #vbox.pack_start(self.canvas, True, True) self.ax = fig.add_subplot(111) self.treeview_matrix.connect('row-activated', self.plot_row) toolbar = NavigationToolbar(self.canvas, self.app1) self.vbox1.pack_start(toolbar, False, False) self.checkbutton_label_dot = xml.get_widget('checkbutton_label_dot') self.entry_dot_label_column = xml.get_widget('entry_dot_label_column') self.entry_x_column = xml.get_widget('entry_x_column') self.entry_y_column = xml.get_widget('entry_y_column') self.entry_hist_column = xml.get_widget('entry_hist_column') self.entry_no_of_bins = xml.get_widget('entry_no_of_bins') #2009-5-20 self.entry_plot_title = xml.get_widget('entry_plot_title') self.entry_plot_title.set_text(self.plot_title) self.filechooserdialog_save = xml.get_widget("filechooserdialog_save") self.filechooserdialog_save.connect("delete_event", yh_gnome.subwindow_hide) self.filechooserdialog_open = xml.get_widget("filechooserdialog_open") self.filechooserdialog_open.connect("delete_event", yh_gnome.subwindow_hide) self.app1_appbar1 = xml.get_widget('app1_appbar1') self.app1_appbar1.push('Status Message.') #import gnome.ui has to be executed. self.treeview_matrix.connect('cursor-changed', self.update_no_of_selected, self.app1_appbar1) self.app1.show_all() #self.add_events(gdk.BUTTON_PRESS_MASK|gdk.KEY_PRESS_MASK|gdk.KEY_RELEASE_MASK) def on_click(self, event): """ 2009-3-13 use (x_lim[1]-x_lim[0])/200. as the resolution for a dot to be called identical to a data point. similar for the y_data 2009-3-13 deal with checkbutton_label_dot, entry_dot_label_column, entry_x_column, entry_y_column 2008-01-01 derived from on_click_row() of QualityControl.py reaction when user clicked in the plot """ # get the x and y coords, flip y from top to bottom x, y = event.x, event.y to_label_dot = self.checkbutton_label_dot.get_active() dot_label_column = int(self.entry_dot_label_column.get_text()) x_column = int(self.entry_x_column.get_text()) y_column = int(self.entry_y_column.get_text()) x_lim = self.ax.get_xlim() x_grain_size = (x_lim[1]-x_lim[0])/200. y_lim = self.ax.get_ylim() y_grain_size = (y_lim[1]-y_lim[0])/200. if event.button==1: if event.inaxes is not None: print 'data coords', event.xdata, event.ydata for row in self.list_2d: x_data = row[x_column] y_data = row[y_column] if abs(x_data-event.xdata)<x_grain_size and abs(y_data-event.ydata)<y_grain_size: info = row[dot_label_column] if to_label_dot: self.ax.text(event.xdata, event.ydata, info, size=8) self.canvas.draw() sys.stderr.write("%s: %s, %s: %s, xy=(%s, %s), info: %s.\n"%(self.column_header[0], row[0], self.column_header[1], row[1], x_data, y_data, info)) def plotXY(self, ax, canvas, liststore, plot_title='', chosen_index_ls=[]): """ 2009-3-13 rename plot_NA_mismatch_rate to plotXY() 2008-02-05 chosen_index => chosen_index_ls 2007-12-14 """ x_column = int(self.entry_x_column.get_text()) y_column = int(self.entry_y_column.get_text()) plot_title = self.entry_plot_title.get_text() min_x = 1 min_y = 1 max_x = 0 max_y = 0 x_ls = [] y_ls = [] x_chosen_ls = [] y_chosen_ls = [] from sets import Set chosen_index_set = Set(chosen_index_ls) for i in range(len(liststore)): row = liststore[i] x = row[x_column] y = row[y_column] if x<min_x: min_x = x if x>max_x: max_x = x if y<min_y: min_y = y if y>max_y: max_y = y if i in chosen_index_set: x_chosen_ls.append(x) y_chosen_ls.append(y) else: x_ls.append(x) y_ls.append(y) ax.clear() ax.plot(x_ls, y_ls, '.') """ #diagonal line give a rough feeling about the notion, more NA, worse calling diagonal_start = min(min_x, min_y)-0.1 diagonal_end = max(max_x, max_x)+0.1 ax.plot([diagonal_start, diagonal_end],[diagonal_start, diagonal_end]) """ if x_chosen_ls and y_chosen_ls: #highlight ax.plot(x_chosen_ls, y_chosen_ls, '.', c='r') if plot_title: ax.set_title(plot_title) ax.set_xlabel(self.column_header[x_column]) ax.set_ylabel(self.column_header[y_column]) canvas.draw() def plot_row(self, treeview, path, view_column): if self._idClick==None: self._idClick = self.canvas.mpl_connect('button_press_event', self.on_click) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title, path) def setupColumns(self, treeview): """ 2009-3-13 """ if not getattr(self, 'column_header', None): sys.stderr.write("Nothing in columns yet.\n") return self.liststore = gtk.ListStore(*self.column_types) #self.add_columns(self.treeview_matrix) yh_gnome.create_columns(self.treeview_matrix, self.column_header, self.editable_flag_ls, self.liststore) yh_gnome.fill_treeview(self.treeview_matrix, self.liststore, self.list_2d, reorderable=True) self.treeselection = self.treeview_matrix.get_selection() def on_button_highlight_clicked(self, widget, data=None): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) 2008-02-05 """ if self._idClick==None: self._idClick = self.canvas.mpl_connect('button_press_event', self.on_click) pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) index_ls = [] for path in pathlist_strains1: index_ls.append(path[0]) self.app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title, index_ls) def on_button_save_clicked(self, widget, data=None): """ 2008-02-05 """ self.filechooserdialog_save.show_all() def on_button_filechooserdialog_cancel_ok_clicked(self, widget, data=None): """ 2008-02-05 """ self.filechooserdialog_save.hide() def on_button_filechooserdialog_save_ok_clicked(self, widget, data=None): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) 2008-02-05 """ output_fname = self.filechooserdialog_save.get_filename() self.filechooserdialog_save.hide() pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) self.app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) if self.header and self.strain_acc_list and self.category_list and self.data_matrix: selected_index_set = Set() for path in pathlist_strains1: row = self.liststore[path[0]] id = row[0] index_in_data_matrix = row[-1] selected_index_set.add(index_in_data_matrix) if self.id_is_strain: id = id[1:-1].split(',') #id is a tuple of (ecotypeid,duplicate) self.strain_acc_list[index_in_data_matrix] = id[0].strip() #remove extra space self.category_list[index_in_data_matrix] = id[1].strip() #else: # self.header[index_in_data_matrix+2] = id from variation.src.FilterStrainSNPMatrix import FilterStrainSNPMatrix FilterStrainSNPMatrix_instance = FilterStrainSNPMatrix() if self.id_is_strain: rows_to_be_tossed_out = Set(range(len(self.strain_acc_list))) - selected_index_set FilterStrainSNPMatrix_instance.write_data_matrix(self.data_matrix, output_fname, self.header, self.strain_acc_list, self.category_list,\ rows_to_be_tossed_out, cols_to_be_tossed_out=Set(), nt_alphabet=0) else: cols_to_be_tossed_out = Set(range(len(self.header)-2)) - selected_index_set FilterStrainSNPMatrix_instance.write_data_matrix(self.data_matrix, output_fname, self.header, self.strain_acc_list, self.category_list,\ rows_to_be_tossed_out=Set(), cols_to_be_tossed_out=cols_to_be_tossed_out, nt_alphabet=0) def show_all(self): """ 2008-02-05 preserve the old interface. in order not to change anything in plot_col_NA_mismatch_rate() and plot_row_NA_mismatch_rate() of QualityControl.py """ self.app1.show_all() def on_button_histogram_clicked(self, widget, data=None): """ 2009-5-20 get the number of bins from entry_no_of_bins 2009-3-13 draw histogram of specific hist_column 2008-02-06 """ if not getattr(self, 'column_header', None): sys.stderr.write("Nothing in columns yet.\n") return self.ax.clear() self.canvas.mpl_disconnect(self._idClick) #drop the signal handler self._idClick = None #reset the _idClick hist_ls = [] hist_column = int(self.entry_hist_column.get_text()) for i in range(len(self.liststore)): hist_ls.append(self.liststore[i][hist_column]) self.ax.set_title("Histogram of %s %s"%(self.plot_title, self.column_header[hist_column])) no_of_bins = int(self.entry_no_of_bins.get_text()) self.ax.hist(hist_ls, no_of_bins) self.canvas.draw() def update_no_of_selected(self, treeview, app1_appbar1): """ 2008-02-12 to update the no_of_selected rows (have to double click a row to change a cursor if it's multiple selection) """ pathlist_strains1 = [] self.treeselection.selected_foreach(yh_gnome.foreach_cb, pathlist_strains1) app1_appbar1.push("%s rows selected."%len(pathlist_strains1)) return True def readInDataToPlot(self, input_fname): """ 2009-5-20 add the column index into the column header for easy picking 2009-3-13 wrap the float conversion part into try...except to report what goes wrong 2009-3-13 """ reader = csv.reader(open(input_fname), delimiter=figureOutDelimiter(input_fname)) self.column_header=reader.next() for i in range(len(self.column_header)): self.column_header[i] = '%s %s'%(i, self.column_header[i]) no_of_cols = len(self.column_header) self.column_types = [str]*2 + [float]*(no_of_cols-2) self.column_editable_flag_ls = [True, True] + [False]*(no_of_cols-2) self.list_2d = [] for row in reader: float_part = row[2:] try: float_part = map(float, float_part) except: sys.stderr.write('Except type: %s\n'%repr(sys.exc_info())) traceback.print_exc() new_row = row[:2]+float_part self.list_2d.append(new_row) self.setupColumns(self.treeview_matrix) self.plotXY(self.ax, self.canvas, self.liststore, self.plot_title) def readInRawMatrixData(self, input_fname): """ 2009-3-13 """ delimiter = figureOutDelimiter(input_fname) self.header, self.strain_acc_list, self.category_list, self.data_matrix = read_data(input_fname, delimiter=delimiter) def on_imagemenuitem_open_activate(self, widget, data=None): """ 2009-3-13 """ self.filechooserdialog_open.show_all() def on_button_fileopen_ok_clicked(self, widget, data=None): """ 2009-3-13 """ input_fname = self.filechooserdialog_open.get_filename() self.filechooserdialog_open.hide() self.readInDataToPlot(input_fname) def on_entry_plot_title_change(self, widget, data=None): """ 2009-3-13 upon any change in the entry_plot_title """ self.plot_title = self.entry_plot_title.get_text()
class PopUpImage(object): def __init__(self, xdata, ydata, xlabel, ylabel, title): self.popupwin=gtk.Window() self.popupwin.set_size_request(600,550) self.popupwin.set_position(gtk.WIN_POS_CENTER) self.popupwin.set_border_width(10) self.xdata = xdata self.ydata = ydata vbox = gtk.VBox() self.fig=Figure(dpi=100) self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.main_figure_navBar = NavigationToolbar(self.canvas, self) self.cursor = Cursor(self.ax, color='k', linewidth=1, useblit=True) self.canvas.mpl_connect("button_press_event",self.on_press) self.ax.set_xlabel(xlabel, fontsize = 18) self.ax.set_ylabel(ylabel, fontsize = 18) self.ax.set_title(title, fontsize = 18) self.ax.plot(self.xdata, self.ydata, 'b-', lw=2) self.textes = [] self.plots = [] vbox.pack_start(self.main_figure_navBar, False, False, 0) vbox.pack_start(self.canvas, True, True, 2) self.popupwin.add(vbox) self.popupwin.connect("destroy", self.dest) self.popupwin.show_all() def dest(self,widget): self.popupwin.destroy() def on_press(self, event): if event.inaxes == self.ax and event.button==3: self.clear_notes() xc = event.xdata #***** Find the closest x value ***** residuel = self.xdata - xc residuel = N.abs(residuel) j = N.argmin(residuel) #y = self.ydata[i-1:i+1] #yc= y.max() #j = N.where(self.ydata == yc) #j = j[0][0] xc= self.xdata[j] x_fit = self.xdata[j-3:j+3] y_fit = self.ydata[j-3:j+3] fitted_param, fitted_data = fit(x_fit, y_fit, xc, True) x_fit = N.linspace(x_fit.min(), x_fit.max(), 200) y_fit = psdVoigt(fitted_param, x_fit) period = fitted_param['xc'].value std_err= fitted_param['xc'].stderr p = self.ax.plot(x_fit, y_fit,'r-') p2 = self.ax.axvline(period,color='green',lw=2) txt=self.ax.text(0.05, 0.9, 'Period = %.4f +- %.4f (nm)'%(period, std_err), transform = self.ax.transAxes, color='red') self.textes.append(txt) self.plots.append(p[0]) self.plots.append(p2) elif event.inaxes == self.ax and event.button==2: dif = N.diff(self.ydata) dif = dif/dif.max() p3 = self.ax.plot(dif,'r-') self.plots.append(p3[0]) self.canvas.draw() def clear_notes(self): if len(self.textes)>0: for t in self.textes: t.remove() if len(self.plots)>0: for p in self.plots: p.remove() self.textes = [] self.plots = []
class appGui: def __init__(self): gladefile = "paViewerGUI.glade" self.windowname = "MainWindow" self.wTree = gtk.glade.XML(gladefile, self.windowname) dic = { "on_MainWindow_destroy": gtk.main_quit, "on_ButtonQuit_clicked": gtk.main_quit, "on_ButtonOpen_clicked": self.Open, "on_ButtonPlane_clicked": self.ChangePlane, "on_change_Current": self.ChangeCurrent, "on_ButtonSave_clicked": self.SaveFigure } self.wTree.signal_autoconnect(dic) self.window = self.wTree.get_widget(self.windowname) self.XmaxIndicator = self.wTree.get_widget("LabelXMax") self.YmaxIndicator = self.wTree.get_widget("LabelYMax") self.ZmaxIndicator = self.wTree.get_widget("LabelZMax") self.XScaler = self.wTree.get_widget("ScaleX") self.YScaler = self.wTree.get_widget("ScaleY") self.ZScaler = self.wTree.get_widget("ScaleZ") self.XText = self.wTree.get_widget("EntryX") self.YText = self.wTree.get_widget("EntryY") self.ZText = self.wTree.get_widget("EntryZ") self.PlaneSwitcher = self.wTree.get_widget("ButtonPlane") self.PlaneIndicator = self.wTree.get_widget("LabelPlane") self.window.show() self.OpenFileName = os.getcwd() self.plane = "xy" self.lock = 0 self.draw_lock = 0 self.pa = None self.TitleOfPlots = [] self.ax = [] self.figure = Figure(figsize=(6, 6), dpi=72) self.figure.subplots_adjust(left=0.05, right=1.0, bottom=0.07, top=0.95, wspace=0.2, hspace=0.1) self.canvas = FigureCanvasGTKAgg(self.figure) # a gtk.DrawingArea self.canvas.show() self.view = self.wTree.get_widget("ViewFrame") self.view.add(self.canvas) def DirectOpen(self, filename): self.OpenFileName = filename self.pa = PA.PA(file=self.OpenFileName) self.currentX = self.pa.nx() / 2 self.currentY = self.pa.ny() / 2 self.currentZ = self.pa.nz() / 2 self.XmaxIndicator.set_text(str(self.pa.nx())) self.YmaxIndicator.set_text(str(self.pa.ny())) self.ZmaxIndicator.set_text(str(self.pa.nz())) self.XScaler.set_range(0.0, self.pa.nx()) self.XScaler.set_value(self.currentX) self.YScaler.set_range(0.0, self.pa.ny()) self.YScaler.set_value(self.currentY) self.ZScaler.set_range(0.0, self.pa.nz()) self.ZScaler.set_value(self.currentZ) self.XText.set_text(str(self.currentX)) self.YText.set_text(str(self.currentY)) self.ZText.set_text(str(self.currentZ)) self.DrawPicture(self.window) def Open(self, widget): # A SIMPLE FILE CHOOSE DIALOG dialog = gtk.FileChooserDialog("Please select your PA File...", self.window, gtk.FILE_CHOOSER_ACTION_OPEN, None, None) dialog.add_button("Cancel", gtk.RESPONSE_CANCEL) dialog.add_button("Select", gtk.RESPONSE_OK) if self.OpenFileName != os.getcwd(): dialog.set_current_folder(os.path.split(self.OpenFileName)[0]) else: dialog.set_current_folder(os.getcwd()) result = dialog.run() if result == gtk.RESPONSE_OK: self.OpenFileName = dialog.get_filename() dialog.destroy() else: dialog.destroy() return 0 # SO EVERYTHING GOOD, LETS OPEN THE FILE self.pa = PA.PA(file=self.OpenFileName) self.currentX = self.pa.nx() / 2 self.currentY = self.pa.ny() / 2 self.currentZ = self.pa.nz() / 2 self.XmaxIndicator.set_text(str(self.pa.nx())) self.YmaxIndicator.set_text(str(self.pa.ny())) self.ZmaxIndicator.set_text(str(self.pa.nz())) self.XScaler.set_range(0.0, self.pa.nx()) self.XScaler.set_value(self.currentX) self.YScaler.set_range(0.0, self.pa.ny()) self.YScaler.set_value(self.currentY) self.ZScaler.set_range(0.0, self.pa.nz()) self.ZScaler.set_value(self.currentZ) self.XText.set_text(str(self.currentX)) self.YText.set_text(str(self.currentY)) self.ZText.set_text(str(self.currentZ)) self.DrawPicture(self.window) def DrawPicture_thread(self, widget): drawFigureThreat().start() def DrawPicture(self, widget): # Nothing open if self.pa == None: return 0 self.wTree.get_widget("View").set_text(self.OpenFileName) # CHECK WHO WANTS TO BE PLOTTED? self.TitleOfPlots = [] if self.wTree.get_widget("CheckRaw").get_active() == True: self.TitleOfPlots.append("Raw") if self.wTree.get_widget("CheckGeo").get_active() == True: self.TitleOfPlots.append("Geometry") if self.wTree.get_widget("CheckPot").get_active() == True: self.TitleOfPlots.append("Potential") # CLEAR FIGURE IS IMPORTANT! self.figure.clear() self.ax = [] i = 0 while i < len(self.TitleOfPlots): num = 100 + 10 * len(self.TitleOfPlots) + 1 + i self.ax.append(self.figure.add_subplot(num)) if self.plane == "xy": self.ax[i].set_xlabel('Y') self.ax[i].set_ylabel('X') elif self.plane == "xz": self.ax[i].set_xlabel('Z') self.ax[i].set_ylabel('X') elif self.plane == "yz": self.ax[i].set_xlabel('Z') self.ax[i].set_ylabel('Y') self.ax[i].set_title(self.TitleOfPlots[i]) i = i + 1 data_raw = [] data_geo = [] data_pot = [] if self.plane == "xy": i = 0 while i < self.pa.nx(): j = 0 data_raw.append([]) data_geo.append([]) data_pot.append([]) while j < self.pa.ny(): data_pot[i].append(self.pa.potential(i, j, self.currentZ)) data_geo[i].append(self.pa.electrode(i, j, self.currentZ)) data_raw[i].append(self.pa.raw(i, j, self.currentZ)) j = j + 1 i = i + 1 elif self.plane == "xz": i = 0 while i < self.pa.nx(): j = 0 data_raw.append([]) data_geo.append([]) data_pot.append([]) while j < self.pa.nz(): data_pot[i].append(self.pa.potential(i, self.currentY, j)) data_geo[i].append(self.pa.electrode(i, self.currentY, j)) data_raw[i].append(self.pa.raw(i, self.currentY, j)) j = j + 1 i = i + 1 elif self.plane == "yz": i = 0 while i < self.pa.ny(): j = 0 data_raw.append([]) data_geo.append([]) data_pot.append([]) while j < self.pa.nz(): data_pot[i].append(self.pa.potential(self.currentX, i, j)) data_geo[i].append(self.pa.electrode(self.currentX, i, j)) data_raw[i].append(self.pa.raw(self.currentX, i, j)) j = j + 1 i = i + 1 i = 0 while i < len(self.TitleOfPlots): if self.TitleOfPlots[i] == "Raw": self.ax[i].imshow(data_raw) self.figure.colorbar(self.ax[i].imshow(data_raw), ax=self.ax[i], shrink=(1.1 - len(self.TitleOfPlots) / 10.0), pad=0.01) elif self.TitleOfPlots[i] == "Geometry": self.ax[i].imshow(data_geo) self.figure.colorbar(self.ax[i].imshow(data_geo), ax=self.ax[i], shrink=(1.1 - len(self.TitleOfPlots) / 10.0), pad=0.01) elif self.TitleOfPlots[i] == "Potential": self.ax[i].imshow(data_pot) self.figure.colorbar(self.ax[i].imshow(data_pot), ax=self.ax[i], shrink=(1.1 - len(self.TitleOfPlots) / 10.0), pad=0.01) i = i + 1 self.canvas.draw() def ChangePlane(self, widget): if self.plane == "xy": self.plane = "xz" self.PlaneIndicator.set_text("XZ") elif self.plane == "xz": self.plane = "yz" self.PlaneIndicator.set_text("YZ") elif self.plane == "yz": self.plane = "xy" self.PlaneIndicator.set_text("XY") self.DrawPicture(self.window) def ChangeCurrent(self, widget): if self.lock == 1: return 0 self.lock = 1 if widget.get_name() == "ScaleX": self.currentX = int(self.XScaler.get_value()) elif widget.get_name() == "ScaleY": self.currentY = int(self.YScaler.get_value()) elif widget.get_name() == "ScaleZ": self.currentZ = int(self.ZScaler.get_value()) # elif widget.get_name() == "CheckRaw" or widget.get_name() == "CheckGeo" or widget.get_name() == "CheckPot": else: self.currentX = int(float(self.XText.get_text())) self.currentY = int(float(self.YText.get_text())) self.currentZ = int(float(self.ZText.get_text())) self.XText.set_text(str(self.currentX)) self.YText.set_text(str(self.currentY)) self.ZText.set_text(str(self.currentZ)) self.XScaler.set_value(self.currentX) self.YScaler.set_value(self.currentY) self.ZScaler.set_value(self.currentZ) self.DrawPicture(self.window) self.lock = 0 def SaveFigure(self, widget): # A SIMPLE FILE CHOOSE DIALOG dialog = gtk.FileChooserDialog("Please select your PA File...", self.window, gtk.FILE_CHOOSER_ACTION_SAVE, None, None) dialog.add_button("Cancel", gtk.RESPONSE_CANCEL) dialog.add_button("Select", gtk.RESPONSE_OK) result = dialog.run() if result == gtk.RESPONSE_OK: FileName = dialog.get_filename() dialog.destroy() else: dialog.destroy() return 0 self.figure.savefig((FileName + ".pdf"))
class Gtk_NetworkCanvas: """Gtk_NetworkCanvas class. This class contains the canvas to draw the topology. It implements event listener and zoom. Parameters ---------- canvas : the gtk canvas to draw adjustement : used for zoom scroll bar zoom_scale : a scroll bar to zoom redraw : a button to redraw the graph popup : a popup for interaction on right click bRefresh : bool. if True enable refresh with do_refresh function corners : the limit of the canvas drawing area press : bool. True if mouse click on canvas (used for zoom) x_old, y_old : position for zoom """ def __init__(self): fig = plt.figure(num=None, facecolor='w', edgecolor='k') plt.axis('off') plt.subplots_adjust(left=0., right=1., bottom=0., top=1., wspace=0.2, hspace=0.2) self.canvas = FigureCanvas(fig) self.canvas.add_events( gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_RELEASE_MASK) self.canvas.connect("motion_notify_event", self.on_motion) self.canvas.connect("button-press-event", self.on_click) self.canvas.connect("button-release-event", self.on_release) self.canvas.connect("scroll-event", self.on_scroll) self.canvas.connect("leave-notify-event", self.on_lose_focus) self.adjustement = gtk.Adjustment(0.0, 0.0, 100.0, 1.0, 1.0, 1.0) self.adjustement_signal = self.adjustement.connect("value-changed", self.on_zoom_changed) self.zoom_scale = gtk.HScale(self.adjustement) self.zoom_scale.set_draw_value(False) self.zoom_value = 0.0 self.redraw = gtk.Button("Redraw") self.redraw.connect("clicked", self.on_redraw) self.hbox = gtk.HBox() self.hbox.pack_start(self.zoom_scale, True, True, 0) self.hbox.pack_end(self.redraw, False, False, 0) self.vbox = gtk.VBox() self.vbox.pack_start(self.canvas, True, True, 0) self.vbox.pack_end(self.hbox, False, False, 0) self.popup = Gtk_NewtworkPopupMenu() self.bRefresh = True self.corners = None self.press = False self.x_old = 0 self.y_old = 0 self.bg_img = None def on_click(self, widget, event): """Event listener : click If double left click : - on edge, show edges rules - on firewall, show firewall conf - on interface, add note If left click : - on edge, show message - on firewall, show message interaction firewall - on interface, show message interaction interface - else move x/y limit drawing area If right click : - on edge, show edge menu - on firewall, show firewall menu - on interface, show interface menu - else show canvas menu """ if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: dbl_click = False dbl_click |= self.on_dblclick_edge() dbl_click |= self.on_dblclick_node() if not dbl_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.TOPOLOGY_MESSAGE) if event.button == 3 and event.type == gtk.gdk.BUTTON_PRESS: right_click = False right_click |= self.on_right_click_edge(event) right_click |= self.on_right_click_node(event) if not right_click: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.ON_BACKGROUND_CLICK) self.popup.popup_clear(event) if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS: left_click = False left_click |= self.on_left_click_edge() left_click |= self.on_left_click_node() if not left_click: self.press = True self.x_old = event.x self.y_old = event.y Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.TOPOLOGY_MESSAGE) return True def on_dblclick_edge(self): """Show interface rules""" def get_firewall(x, y): if isinstance(x, Firewall): return x elif isinstance(y, Firewall): return y return None def get_ip(x, y): if isinstance(x, Ip): return x elif isinstance(y, Ip): return y return None g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: fw = get_firewall(elem[0], elem[1]) ip = get_ip(elem[0], elem[1]) result = [] [result.append(acl) for acl in g.get_acl_list(src=ip, dst=None, firewall=fw)] [result.append(acl) for acl in g.get_acl_list(src=None, dst=ip, firewall=fw)] if not result: Gtk_DialogBox("No rules found for this interface !") [Gtk_Main.Gtk_Main().notebook.add_interface_tab(acl) for acl in result] return True return False def on_dblclick_node(self): """Event listener, on double click node, if firewall show conf file else add note""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press and isinstance(v['object'].object, Firewall): Gtk_Main.Gtk_Main().notebook.add_conf_tab(v['object'].object.name, v['object'].object.hostname) return True if v['object'].gtk_press and isinstance(v['object'].object, Ip): self.popup.node = v['object'] self.popup.on_add_note(None) return True return False def on_right_click_edge(self, event): """Event listener, on right click edge, popup menu showing acl list of related to this interface""" g = NetworkGraph.NetworkGraph() for elem in g.graph.edges(data=True): edge = elem[2]['object'] if edge.gtk_press: self.popup.popup(elem, event, edge) edge.gtk_press = False return True return False def on_right_click_node(self, event): """Event listener, on right click node, show popup menu for node""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: self.popup.popup(None, event, v['object']) v['object'].gtk_press = False return True return False def on_left_click_node(self): """Show node details""" g = NetworkGraph.NetworkGraph() for k, v in g.graph.node.items(): if v['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_Message.ON_CLICK_NODE) Gtk_Main.Gtk_Main().lateral_pane.details.clear() tmp_intf = [e[2]['object'].object for e in g.graph.edges(k, data=True)] for e in sorted(tmp_intf, key=lambda tmp_intf: tmp_intf.nameif): message = "%s:\n- %s\n- %s" % (e.nameif, e.name, e.network.to_string()) for key, value in e.attributes.items(): message += "\n- %s : %s" % (key, value) Gtk_Main.Gtk_Main().lateral_pane.details.add_row(message) Gtk_Main.Gtk_Main().lateral_pane.focus_details() return True return False def on_left_click_edge(self): """If left click edge, show help message""" g = NetworkGraph.NetworkGraph() for edge in g.graph.edges(): if g.graph[edge[0]][edge[1]]['object'].gtk_press: Gtk_Main.Gtk_Main().lateral_pane.help_message.change_message(Gtk_HelpMessage.Gtk_Message.ON_CLICK_EDGE) return True return False def on_motion(self, widget, event): """If not click node, then move axis""" if self.press and self.corners: xlim = list(plt.gca().get_xlim()) ylim = list(plt.gca().get_ylim()) x = (self.x_old - event.x) / (1. * self.canvas.window.get_size()[0] / (xlim[1] - xlim[0])) y = (event.y - self.y_old) / (1. * self.canvas.window.get_size()[1] / (ylim[1] - ylim[0])) self.x_old = event.x self.y_old = event.y self.axes_move(x, y, x, y) self.do_refresh() def refresh(self): """refresh function. This function is call periodically by do_refresh""" self.bRefresh = True def do_refresh(self): """Update the graph if bRefresh is True""" if self.bRefresh: self.bRefresh = False self.canvas.draw() gtk.timeout_add(30, self.refresh) def on_release(self, widget, event): """Event listener : release""" self.press = False def on_scroll(self, widget, event): """Event listener : scroll. Update zoom""" if event.direction == 0 and self.adjustement.get_value() < 99: self.adjustement.set_value(self.adjustement.get_value() + 1) elif event.direction == 1 and self.adjustement.get_value() > 0: self.adjustement.set_value(self.adjustement.get_value() - 1) def on_zoom_changed(self, widget): """Event listerner : HScale change. Update zoom""" if self.corners: im = None if self.bg_img: im = self.bg_img.get_children()[0] if widget.value != 0: zoom = (self.zoom_value - widget.value) * (self.corners[1][0] - self.corners[0][0]) / 200 self.axes_zoom(-zoom, -zoom, zoom, zoom) if im: dim = min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data'])) corners = min(self.corners[1][0] - self.corners[0][0], self.corners[1][1] - self.corners[0][1]) im.set_zoom(im.get_zoom() - zoom * 2 * dim / corners) else: plt.gca().set_xlim((self.corners[0][0], self.corners[1][0])) plt.gca().set_ylim((self.corners[0][1], self.corners[1][1])) if im: im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.zoom_value = widget.value self.do_refresh() def on_lose_focus(self, widget, event): """Event listener : focus""" self.press = False NetworkGraph.NetworkGraph().node_click = False for node in NetworkGraph.NetworkGraph().graph.nodes(data=True): node[1]['object'].press = False for edge in NetworkGraph.NetworkGraph().graph.edges(data=True): edge[2]['object'].press = False self.do_refresh() def on_redraw(self, widget): """Event listener : button redraw""" self.draw() def axes_move(self, x0, y0, x1, y1): """Change axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if ((x0 < 0 and x[0] + x0 >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1])) and \ ((x1 > 0 and x[1] + x1 <= self.corners[1][0]) or (x1 < 0 and x[1] + x1 > x[0])): x[0] += x0 x[1] += x1 if ((y0 < 0 and y[0] + y0 >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1])) and \ ((y1 > 0 and y[1] + y1 <= self.corners[1][1]) or (y1 < 0 and y[1] + y1 > y[0])): y[0] += y0 y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def axes_zoom(self, x0, y0, x1, y1): """Zoom axis position according to the drawing area limit. Parameters ---------- x0 : float. x minimal value x1 : float. x maximal value y0 : float. y minimal value y1 : float. y maximal value """ if self.corners: x = list(plt.gca().get_xlim()) y = list(plt.gca().get_ylim()) if (x0 < 0 and x[0] >= self.corners[0][0]) or (x0 > 0 and x[0] + x0 < x[1]): x[0] += x0 if (x1 > 0 and x[1] <= self.corners[1][0]) or (x1 < 0 and x[1] - x1 > x[0]): x[1] += x1 if (y0 < 0 and y[0] >= self.corners[0][1]) or (y0 > 0 and y[0] + y0 < y[1]): y[0] += y0 if (y1 > 0 and y[1] <= self.corners[1][1]) or (y1 < 0 and y[1] - y1 > y[0]): y[1] += y1 plt.gca().set_xlim((x[0], x[1])) plt.gca().set_ylim((y[0], y[1])) def background_image(self, file): """Set the file image as background image""" if self.bg_img: self.bg_img.remove() datafile = get_sample_data(file) img = plt.imread(datafile) im = OffsetImage(img) im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False) self.bg_img.set_zorder(-1) plt.gca().add_artist(self.bg_img) self.do_refresh() def draw(self): """Draw the netowrk graph and set limit corners""" g = NetworkGraph.NetworkGraph() g.layout_graph() g.draw(self.canvas) self.corners = (-0.05, -0.05), (1.05, 1.05) plt.gca().set_xlim((-0.05, 1.05)) plt.gca().set_ylim((-0.05, 1.05)) self.do_refresh()
class Graph_viewer: def __init__(self, graph, actions=['nothing'], callback=None): """ weights : dictionary mapping name to weight kmers will be colored in rank order of weight """ self.graph = graph self.callback = callback self.window = gtk.Window() self.window.connect('destroy', lambda x: gtk.main_quit()) self.window.set_default_size(800, 600) self.window.set_title('Graph viewer') vbox = gtk.VBox() self.window.add(vbox) self.figure = Figure(figsize=(8, 6), dpi=50) self.axes = self.figure.add_subplot(111) colors = numpy.empty((len(graph.names), 3)) sizes = numpy.empty(len(graph.names)) sizes[:] = 2.0 #if weights is None: # #self.axes.plot(graph.positions[:,0], graph.positions[:,1], ',') # # colors[:,:] = [[0.0,0.0,0.0]] # #else: #names = weights.keys() #values = weights.values() ##names.sort(key=lambda x: weights[x]) #idents = numpy.array([ graph.name_to_ident[name] for name in names ]) #x = numpy.array(values, dtype='float64') x = numpy.array(graph.weights, dtype='float64') x = numpy.log(x) x -= numpy.minimum.reduce(x) x /= numpy.average(x) * 2.0 #x /= numpy.sum(x*x)*2.0/numpy.sum(x) xx = numpy.minimum(x, 1.0) #x = numpy.arange(len(graph.names)) / float(len(graph.names)) colors[:, 0] = 0.5 - xx * 0.5 colors[:, 1] = 0.75 - xx * 0.5 colors[:, 2] = 1.0 - xx * 0.5 sizes[:] = numpy.maximum(x, 1.0)**2 #*2.0 #n = 20 #for i in xrange(n): # start = i*len(names)//n # end = (i+1)*len(names)//n # if start == end: continue # # x = (1.0-float(i)/(n-1)) # position_block = graph.positions[idents[start:end]] # self.axes.scatter(position_block[:,0], # position_block[:,1], # linewidths=0, # marker='s', # s=10.0, # c=(0.0,x,x*0.5+0.5), # zorder=i) dots = Dots(graph.positions[:, 1], graph.positions[:, 0], colors, sizes) self.axes.add_artist(dots) #if len(graph.links) < 1000: # for i, (other, other_sign, other_travel) in enumerate(graph.links): # for j in other: # if j > i: # self.axes.plot([graph.positions[i,0],graph.positions[j,0]], # [graph.positions[i,1],graph.positions[j,1]], # 'k-') self.axes.axis('scaled') self.axes.set_xlim(0.0, numpy.maximum.reduce(graph.positions[:, 0]) * 1.1) self.axes.set_ylim(0.0, numpy.maximum.reduce(graph.positions[:, 1]) * 1.1) self.figure.subplots_adjust(top=0.99, bottom=0.05, right=0.99, left=0.05) #pylab.connect('button_press_event', self._on_click) self.annotation_pylab = [] self.clear_annotation() self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.mpl_connect('button_press_event', self._on_down) self.canvas.mpl_connect('button_release_event', self._on_up) vbox.pack_start(self.canvas) hbox = gtk.HBox() vbox.pack_start(hbox, False, False, 10) label = gtk.Label('Middle click:') hbox.pack_start(label, False, False, 5) self.radios = {} last = None for action in actions: radio = gtk.RadioButton(group=last, label=action) last = radio self.radios[action] = radio hbox.pack_start(radio, False, False, 5) label = gtk.Label('Right click: clear') hbox.pack_end(label, False, False, 5) self.radios[actions[0]].set_active(True) toolbar = NavigationToolbar(self.canvas, self.window) vbox.pack_start(toolbar, False, False) def run(self): self.window.show_all() gtk.main() def clear_annotation(self): self.annotation = {} def label(self, name, label): ident = self.graph.name_to_ident[name] self.axes.text(self.graph.positions[ident, 0], self.graph.positions[ident, 1], label, horizontalalignment='center', verticalalignment='bottom', zorder=100000) def arrow(self, names, label): positions = [ self.graph.positions[self.graph.name_to_ident[name]] for name in names if self.graph.has(name) ] if not positions: return #Error? max_positions = max(4, (len(positions) + 29) // 30) #20 if len(positions) > max_positions: positions = [ positions[i * (len(positions) - 1) // (max_positions - 1)] for i in xrange(max_positions) ] arrow = Arrow(positions, label, True) #names = [ name for name in names if self.graph.has(name) ] # #if len(names) < 2: return #Error? # #ident1 = self.graph.name_to_ident[names[0]] #ident2 = self.graph.name_to_ident[names[-1]] # #arrow = Arrow(self.graph.positions[ident1], # self.graph.positions[ident2], # label, # True) self.axes.add_artist(arrow) def annotate(self, name, mass, r, g, b): r *= mass g *= mass b *= mass old_mass, old_r, old_g, old_b = self.annotation.get( name, (0.0, 0.0, 0.0, 0.0)) self.annotation[name] = (old_mass + mass, old_r + r, old_g + g, old_b + b) def refresh_annotation(self): while self.annotation_pylab: item = self.annotation_pylab.pop(-1) item.remove() xs = [] ys = [] colors = [] sizes = [] for name in self.annotation: mass, r, g, b = self.annotation[name] if not mass: continue ident = self.graph.name_to_ident[name] xs.append(self.graph.positions[ident, 0]) ys.append(self.graph.positions[ident, 1]) colors.append((r / mass, g / mass, b / mass)) sizes.append(mass) if xs: #thing = self.axes.scatter( # xs, # ys, # s=sizes, # c=colors, # linewidths=0, # marker='s', # zorder=10000) thing = Dots(numpy.array(ys), numpy.array(xs), numpy.array(colors), numpy.array(sizes), zorder=2) self.axes.add_artist(thing) self.annotation_pylab.append(thing) self.canvas.draw() def name_from_position(self, x, y): xoff = self.graph.positions[:, 0] - x yoff = self.graph.positions[:, 1] - y dist2 = xoff * xoff + yoff * yoff best = numpy.argmin(dist2) return self.graph.names[best] def _on_down(self, event): self.down_name = self.name_from_position(event.xdata, event.ydata) def _on_up(self, event): if event.inaxes and event.button == 3: self.clear_annotation() self.refresh_annotation() elif event.inaxes and event.button == 2: name = self.name_from_position(event.xdata, event.ydata) if self.callback: action = None for item in self.radios: if self.radios[item].get_active(): action = item self.callback(self, action, self.down_name, name) self.refresh_annotation() del self.down_name
class band_graph(gtk.VBox): def init(self): toolbar = gtk.Toolbar() toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_size_request(-1, 50) self.pack_start(toolbar, False, False, 0) tool_bar_pos=0 save = gtk.ToolButton(gtk.STOCK_SAVE) save.connect("clicked", self.callback_save_image) toolbar.insert(save, tool_bar_pos) toolbar.show_all() tool_bar_pos=tool_bar_pos+1 self.my_figure=Figure(figsize=(5,4), dpi=100) self.canvas = FigureCanvas(self.my_figure) # a gtk.DrawingArea self.canvas.figure.patch.set_facecolor('white') self.canvas.set_size_request(600, 400) self.canvas.show() self.pack_start(self.canvas, False, False, 0) self.canvas.connect('key_press_event', self.on_key_press_event) self.show_all() def on_key_press_event(self,widget, event): keyname = gtk.gdk.keyval_name(event.keyval) if keyname == "c": if event.state == gtk.gdk.CONTROL_MASK: self.do_clip() self.canvas.draw() def do_clip(self): print "doing clip" snap = self.my_figure.canvas.get_snapshot() pixbuf = gtk.gdk.pixbuf_get_from_drawable(None, snap, snap.get_colormap(),0,0,0,0,snap.get_size()[0], snap.get_size()[1]) clip = gtk.Clipboard() clip.set_image(pixbuf) def callback_save_image(self, widget): dialog = gtk.FileChooserDialog("Save plot", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_action(gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER) filter = gtk.FileFilter() filter.set_name("png") filter.add_pattern("*.png") dialog.add_filter(filter) response = dialog.run() if response == gtk.RESPONSE_OK: self.my_figure.savefig(dialog.get_filename()) elif response == gtk.RESPONSE_CANCEL: print 'Closed' dialog.destroy() def set_data_file(self,file): self.optical_mode_file=os.path.join(os.getcwd(),"light_dump",file) def draw_graph(self): self.layer_end=[] self.layer_name=[] n=0 self.my_figure.clf() ax1 = self.my_figure.add_subplot(111) ax2 = ax1.twinx() x_pos=0.0 layer=0 color =['r','g','b','y','o','r','g','b','y','o'] start=0.0 for i in range(0,epitaxy_get_layers()): if epitaxy_get_electrical_layer(i)=="none": start=start-epitaxy_get_width(i) else: break print "START=",start start=start*1e9 x_pos=start for i in range(0,epitaxy_get_layers()): label=epitaxy_get_mat_file(i) layer_ticknes=epitaxy_get_width(i) layer_material=epitaxy_get_mat_file(i) delta=float(layer_ticknes)*1e9 if epitaxy_get_electrical_layer(i)=="none": mat_file=os.path.join(os.getcwd(),'materials',layer_material,'mat.inp') myfile = open(mat_file) self.mat_file_lines = myfile.readlines() myfile.close() for ii in range(0, len(self.mat_file_lines)): self.mat_file_lines[ii]=self.mat_file_lines[ii].rstrip() lumo=-float(self.mat_file_lines[1]) Eg=float(self.mat_file_lines[3]) else: lines=[] if inp_load_file(lines,epitaxy_get_electrical_layer(i)+".inp")==True: lumo=-float(inp_search_token_value(lines, "#Xi")) Eg=float(inp_search_token_value(lines, "#Eg")) x = [x_pos,x_pos+delta,x_pos+delta,x_pos] lumo_delta=lumo-0.1 h**o=lumo-Eg homo_delta=h**o-0.1 if Eg==0.0: lumo_delta=-7.0 h**o=0.0 lumo_shape = [lumo,lumo,lumo_delta,lumo_delta] x_pos=x_pos+delta self.layer_end.append(x_pos) self.layer_name.append(layer_material) ax2.fill(x,lumo_shape, color[layer],alpha=0.4) ax2.text(x_pos-delta/1.5, lumo-0.4, epitaxy_get_name(i)) if h**o!=0.0: homo_shape = [h**o,h**o,homo_delta,homo_delta] ax2.fill(x,homo_shape, color[layer],alpha=0.4) layer=layer+1 n=n+1 state=plot_state() get_plot_file_info(state,self.optical_mode_file) #summary="<big><b>"+self.store[path[0]][0]+"</b></big>\n"+"\ntitle: "+state.title+"\nx axis: "+state.x_label+" ("+latex_to_pygtk_subscript(state.x_units)+")\ny axis: "++" ("+latex_to_pygtk_subscript(state.y_units)+")\n\n<big><b>Double click to open</b></big>" print "ROD!!!!",state.y_label,self.optical_mode_file ax1.set_ylabel(state.y_label) ax1.set_xlabel('Position (nm)') ax2.set_ylabel('Energy (eV)') ax2.set_xlim([start, x_pos]) #ax2.axis(max=)#autoscale(enable=True, axis='x', tight=None) loaded=False if os.path.isfile("light_dump.zip"): zf = zipfile.ZipFile("light_dump.zip", 'r') lines = zf.read(self.optical_mode_file).split("\n") zf.close() loaded=True elif os.path.isfile(self.optical_mode_file): print "I want to load",self.optical_mode_file f = open(self.optical_mode_file) lines = f.readlines() f.close() loaded=True if loaded==True: xx=[] yy=[] zz=[] lines_to_xyz(xx,yy,zz,lines) t = asarray(xx) s = asarray(yy) t=t*1e9 ax1.plot(t,s, 'black', linewidth=3 ,alpha=0.5) self.my_figure.tight_layout()
class ionizer(object): def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file('ionizer.glade') signals = {'on_ionizerWindow_destroy' : gtk.main_quit,\ 'on_btn_StartAcquisition_clicked' : self.on_btn_StartAcquisition_clicked,\ 'on_btnSave_clicked' : self.on_save,\ 'on_adjExposure_value_changed' : lambda w: self.pipe.send(['EXPOSURE', w.get_value()])} self.builder.connect_signals(signals) self.window = self.builder.get_object('ionizerWindow') box = self.builder.get_object('box') self.fig = Figure(figsize=(5,4), dpi=100) self.axCam = self.fig.add_subplot(111) self.Camcanvas = FigureCanvas(self.fig) box.pack_start(self.Camcanvas) self.window.show_all() self.tagTimers = {} self.lastImage = None self.dataLabel = self.builder.get_object('txtDataLabel') self.dataLabel.set_text('unknown') self.active = False self.isControlling = False self.pipe, pipe = Pipe() self.acqLoop = Process(target=acquisitionLoop, args=(pipe, )) self.acqLoop.daemon = True self.acqLoop.start() self.cmap = plt.cm.bone#bone#afmhot#coolwarm # set the proper default directory for data: try: today = datetime.now().strftime('%Y-%m-%d %a') if not os.path.exists(today): os.mkdir(today) os.chdir(today) except OSError: logger.error("Could not create data directory") self.datadir = os.getcwd() def on_btn_StartAcquisition_clicked(self, widget): if self.active: self.pipe.send(['ACTIVATE', False]) gobject.source_remove(self.tagTimers['ACQ']) del self.tagTimers['ACQ'] widget.set_label('Start') self.active = False else:# self.pipe.send(['ACTIVATE', True]) self.tagTimers['ACQ'] = gobject.timeout_add(50, self.acquisitionTimer) widget.set_label('Stop') self.active = True def acquisitionTimer(self): if self.pipe.poll(): self.axCam.clear() self.lastImage = self.pipe.recv() self.axCam.imshow(self.lastImage, cmap = self.cmap)#, vmin=450, vmax=650) print self.lastImage.min() print self.lastImage.max() self.Camcanvas.draw() return True def on_save(self, btn): prefix = datetime.now().strftime('%H%M%S-') + self.dataLabel.get_text() print 'saving to', prefix self.fig.savefig(prefix + '.png') numpy.save(prefix, self.lastImage) # if self.lastImage is not None: # savePGM(prefix + '.pgm', self.lastImage) # Image.fromarray(cmap[(1.*self.lastImage/self.lastImage.max()*255).astype(int)]).convert('RGB').save(prefix + '.jpg') def teardown(self): print 'tearing down everything' for t in self.tagTimers: gobject.source_remove(self.tagTimers[t]) self.pipe.send(["QUIT"]) if self.active: self.pipe.recv() self.pipe.close() self.acqLoop.join()
class FeedbackApp: def __init__(self): # initialize the feedbackloop gtk.threads_init() gtk.threads_enter() self.feedbackloop = feedbackLoop() self.feedbackloop.active = False self.feedbackloop.start() gtk.threads_leave() # create a window self.win = gtk.Window(gtk.WINDOW_TOPLEVEL) self.win.set_size_request(600,500) self.win.connect('destroy', gtk.main_quit) #vbox to put everything in self.vbox = gtk.VBox() self.win.add(self.vbox) # add a graph self.figure = Figure(figsize=(10,4)) self.figureCanvas = FigureCanvas(self.figure) self.vbox.pack_start(self.figureCanvas, expand=True, fill=True) # graph self.axes = self.figure.add_subplot(111) self.axes.grid() self.line, = self.axes.plot([1,2,3,4,5],[5,3,5,2,5],'-^', label='output signal PID') # topline self.topline, = self.axes.plot([-1e99, 1e99], 2*[self.feedbackloop.max_signal], label='upper lim') self.botline, = self.axes.plot([-1e99, 1e99], 2*[self.feedbackloop.min_signal], label='lower lim') self.figureCanvas.draw() self.axes.legend(loc=2) # button start/stop self.buttonBox = gtk.HButtonBox() self.vbox.pack_end(self.buttonBox, expand=False, fill=True) self.startStopButton = gtk.ToggleButton('Start/Stop') self.startStopButton.connect('toggled', self.activateFeedbackLoop) self.buttonBox.pack_start(self.startStopButton) self.win.show_all() gobject.idle_add(self.update_graph) def activateFeedbackLoop(self, *args): """ Activate the feedbackloop """ if self.startStopButton.get_active(): print "ctivating feedback" self.feedbackloop.active = self.startStopButton.get_active() # add a start/stop box def update_graph(self): """ Update the graphical representation of the feedback loop""" xdata = self.feedbackloop.time_history.toArray() order = np.argsort(xdata) xdata = xdata[order] ydata = self.feedbackloop.signal_history.toArray() ydata = ydata[order] self.line.set_xdata(xdata) self.line.set_ydata(ydata) self.figureCanvas.draw() try: if not (None in xdata.tolist()): self.axes.set_xlim(min(xdata),max(xdata)) else: self.axes.set_xlim(max(xdata)-20, max(xdata)) self.axes.set_ylim(0,5) except: pass return True
class Iverplot_window(object): """ Iverplot_window---main Iverplot GUI object Parameters ----------- Notes ------ """ def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file('iverplot.glade') self.builder.connect_signals(self) self.window = self.builder.get_object('main_window') # add matplotlib figure canvas w, h = self.window.get_size() self.fig = Figure(figsize=(6, 4)) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.set_size_request(w - 150, -1) vbox = gtk.VBox() toolbar = NavigationToolbar(self.canvas, self.window) vbox.pack_start(self.canvas, True, True) vbox.pack_start(toolbar, False, False) # a little hacky for packing hpane with figure canvas first then tool # bar---not sure if glade is to blame---first, remove tool_vbox then # repack plot_hpaned = self.builder.get_object('plot_hpaned') self.tool_vbox = self.builder.get_object('tool_vbox') plot_hpaned.remove(self.tool_vbox) #plot_hpaned.pack1 (self.canvas, resize=True, shrink=False) plot_hpaned.pack1(vbox, resize=True, shrink=False) plot_hpaned.pack2(self.tool_vbox) # data self.uvclog = None self.lcmlog = None # plot limits self.xlimits = [None, None] self.xlimits_abs = [None, None] # add single plot item self.plotdex = {} self.plot_items = [] self.plot_items.append( Plot_item(self.tool_vbox, self.on_plot_item_selected, self.uvclog, self.lcmlog)) self.update_subplots() # setwin self.setwin = None # set some defaults self.cd_saveas = os.getcwd() self.cd_open = os.getcwd() self.window.show_all() def on_setwin_clicked(self, widget): if self.setwin is None: self.setwin = Setwin(self.canvas, self.fig, self.on_setwin_complete) def on_setwin_complete(self, xmin, xmax): self.xlimits = [xmin, xmax] for p in self.plot_items: ax = self.fig.axes[self.plotdex[p]] p.plot_type.set_limits(ax, *self.xlimits) self.canvas.draw() self.setwin = None def on_setwin_reset(self, widget): if not self.setwin is None: return self.xlimits = [x for x in self.xlimits_abs] for p in self.plot_items: ax = self.fig.axes[self.plotdex[p]] p.plot_type.set_limits(ax, *self.xlimits) self.canvas.draw() def update_subplots(self): self.fig.clear() n = len(self.plot_items) for i, p in enumerate(self.plot_items): p.plot_type.uvclog = self.uvclog p.plot_type.lcmlog = self.lcmlog ax = self.fig.add_subplot(n, 1, i + 1) p.plot_type.plot(ax, *self.xlimits) self.plotdex[p] = i self.canvas.draw() def on_plot_item_selected(self, combo, item): ax = self.fig.axes[self.plotdex[item]] item.plot_type.plot(ax, *self.xlimits) self.canvas.draw() def update_window(self): while gtk.events_pending(): gtk.main_iteration_do(True) def on_add_subplot_clicked(self, widget): if len(self.plot_items) >= 3: return self.plot_items.append( Plot_item(self.tool_vbox, self.on_plot_item_selected, self.uvclog, self.lcmlog)) self.update_subplots() self.update_window() def on_remove_subplot_clicked(self, widget): if len(self.plot_items) <= 1: return item = self.plot_items.pop(-1) item.remove() self.update_subplots() self.update_window() def run_open_dialog(self): open_dlg = self.builder.get_object('open_dialog') #open_dlg.set_current_folder (self.cd_open) open_dlg.set_current_folder( '/home/jeff/data/UMBS_0513/iver28/2013-06-01-dive.046') if len(open_dlg.list_filters()) == 0: all_filter = gtk.FileFilter() all_filter.set_name('All files') all_filter.add_pattern('*') open_dlg.add_filter(all_filter) lcm_filter = gtk.FileFilter() lcm_filter.set_name('LCM logs') lcm_filter.add_pattern('lcmlog*') open_dlg.add_filter(lcm_filter) uvc_filter = gtk.FileFilter() uvc_filter.set_name('UVC logs') uvc_filter.add_pattern('*.log') open_dlg.add_filter(uvc_filter) response = open_dlg.run() fname = None if response == gtk.RESPONSE_OK: fname = open_dlg.get_filename() self.cd_open = os.path.dirname(fname) open_dlg.hide() return fname def on_open_lcm_clicked(self, widget): fname = self.run_open_dialog() if fname: print 'selected', fname def on_open_uvc_clicked(self, widget): fname = self.run_open_dialog() if fname: print 'selected', fname try: self.uvclog = UVCLog(fname) self.xlimits_abs = [ self.uvclog.utime[0], self.uvclog.utime[-1] ] self.xlimits = [x for x in self.xlimits_abs] self.update_subplots() except: print 'could not load correctly' def on_save_as_clicked(self, widget): save_as_dlg = self.builder.get_object('save_as_dialog') save_as_dlg.set_current_folder(self.cd_saveas) save_as_dlg.set_current_name('iverplot.png') if len(save_as_dlg.list_filters()) == 0: all_filter = gtk.FileFilter() all_filter.set_name('All files') all_filter.add_pattern('*') save_as_dlg.add_filter(all_filter) img_filter = gtk.FileFilter() img_filter.set_name('All images') img_filter.add_pattern('*.png') img_filter.add_pattern('*.jpg') img_filter.add_pattern('*.pdf') save_as_dlg.add_filter(img_filter) response = save_as_dlg.run() if response == gtk.RESPONSE_OK: fname = save_as_dlg.get_filename() self.fig.savefig(fname, dpi=self.fig.dpi) self.cd_saveas = os.path.dirname(fname) save_as_dlg.hide() def on_about_clicked(self, widget): about = self.builder.get_object('about_dialog') about.run() about.hide() def on_main_window_destroy(self, widget): gtk.main_quit()
class Correl: def __init__(self,w=None): self.prefix="SH" if w==None: self.win=gtk.Window() self.win.set_title("LGS correlation tool for AO-LAB on %s"%socket.gethostname()) self.win.set_icon_from_file(os.path.join(os.path.split(__file__)[0],"logouc.png")) self.win.connect("delete-event",self.quit) else: self.win=w self.img=None self.pad=0 self.hbox=gtk.HBox() vbox=gtk.VBox() self.win.add(self.hbox) self.hbox.pack_start(vbox,False) h=gtk.HBox() vbox.pack_start(h,False) i=gtk.Image() i.set_from_file(os.path.join(os.path.split(__file__)[0],"logouc.png")) h.pack_start(i,False) b=gtk.Button("Grab") b.set_tooltip_text("Grab calibrated images") h.pack_start(b,False) e=gtk.Entry() e.set_width_chars(4) e.set_text("100") e.set_tooltip_text("Number of frames to average") h.pack_start(e,False) b.connect("clicked",self.grab,e) b=gtk.Button("Update") b.set_tooltip_text("Gets current darc state") b.connect("clicked",self.update) h.pack_start(b,False) b=gtk.Button("Reset") b.set_tooltip_text("Resets to CoG, refslopes to 0") b.connect("clicked",self.reset) h.pack_start(b,False) h=gtk.HBox() vbox.pack_start(h,False) b=gtk.Button("Save ref") b.set_tooltip_text("Gets ref slopes from darc and saves") b.connect("clicked",self.saveRef) h.pack_start(b,False) e=gtk.Entry() e.set_width_chars(10) if os.path.exists("/Canary"): e.set_text("/Canary/data/") else: e.set_text("data/") e.set_tooltip_text("Directory for ref slopes") self.dataDirEntry=e h.pack_start(e,True) h=gtk.HBox() vbox.pack_start(h,False) b=gtk.Button("Load") b.set_tooltip_text("Loads ref slopes and sets in darc") b.connect("clicked",self.loadRef) h.pack_start(b,False) e=gtk.Entry() e.set_width_chars(10) e.set_tooltip_text("Filename for loading ref slopes") self.entrySlopesFilename=e h.pack_start(e,True) h=gtk.HBox() vbox.pack_start(h,False) b=gtk.Button("Compute slopes") b.set_tooltip_text("Computes slopes related to this image") h.pack_start(gtk.Label("Padding:"),False) e=gtk.Entry() e.set_width_chars(4) e.set_text("8") e.set_tooltip_text("FFT padding") self.entryPad=e h.pack_start(e,False) b.connect("clicked",self.computeSlopes,e) h.pack_start(b,False) b=gtk.Button("RTD") b.set_tooltip_text("Start a RTD looking at correlation (this will need restarting if padding changes)") b.connect("clicked",self.rtd) h.pack_start(b,False) h=gtk.HBox() vbox.pack_start(h,False) b=gtk.Button("Upload img") b.set_tooltip_text("upload the correlation image (but don't change centroiding mode") b.connect("clicked",self.upload,e) h.pack_start(b,False) b=gtk.RadioButton(None,"Set to CoG") self.setCoGButton=b b.set_tooltip_text("Set to CoG mode, will restore ref slopes to CoG slopes.") self.setCoGHandle=b.connect("toggled",self.setCoG,e) h.pack_start(b,False) b=gtk.RadioButton(b,"Set to Corr") self.setCorrButton=b b.set_tooltip_text("Set to Correlation mode (LGS only). Updates ref slopes. Doesn't upload new correlation image.") h.pack_start(b,False) fig1=Figure() self.fig1=FigureCanvas(fig1) self.fig1.set_size_request(300,300) self.im=fig1.add_subplot(2,1,1) self.im2=fig1.add_subplot(2,1,2) self.hbox.pack_start(self.fig1,True) vbox.pack_start(gtk.Label("""Instructions: Click "update". Grab some data by clicking grab. This is calibrated pixels. Choose your padding and compute slopes. Then upload img. Then set to correlation. This should automagically update the refslopes so that the AO correction should be unaffected. When you want to update the correlation image, grab some more data, click compute slopes and then upload img. This can be done when already in correlation mode. It will update the ref slopes as necessary. When finished, go back to CoG mode, and you should find the ref slopes are returned to what they were at the start (with maybe slight differences due to floating point rounding error). Clicking reset sets to CoG, and zeros the ref slopes. Clicking load will load the ref slopes from disk and set in darc. Save will save the ref slopes (so do this at the start). Padding should be such that fft wrapping doesn't occur in the RTD image"""),False) self.win.show_all() def quit(self,w,e=None): gtk.main_quit() def grab(self,w,e): nfr=int(e.get_text()) self.img=getImg(nfr) img=self.img[256**2:] img.shape=128,128 self.im.cla() self.im.set_title("rtcCalPxlBuf") self.im.imshow(img) self.fig1.draw() def update(self,w): d=darc.Control(self.prefix) cm=d.Get("centroidMode") if type(cm)==numpy.ndarray and numpy.any(cm[-49:]):#in correlation mode. cur=getCurrentImg() cog=0 print "In correlation mode" else: cur=makeIdent() cog=1 print "In CoG mode" self.setCoGButton.handler_block(self.setCoGHandle) if cog: self.setCoGButton.set_active(True) else: self.setCorrButton.set_active(True) self.setCoGButton.handler_unblock(self.setCoGHandle) self.img=getCurrentImg() print self.img.shape img=self.img[256**2:] img.shape=128,128 self.im.cla() self.im.set_title("Currently used image") self.im.imshow(img) self.fig1.draw() #self.computeSlopes(None,self.entryPad) def reset(self,w): d=darc.Control(self.prefix) d.Set(["centroidMode","refCentroids","corrFFTPattern","corrSubapLoc","corrNpxlx","corrNpxlCum"],["CoG",None,None,None,d.Get("npxlx"),numpy.insert(numpy.cumsum(d.Get("npxlx")*d.Get("npxly")),0,0).astype(numpy.int32)]) def makefilename(self,dironly=0): fdir=self.dataDirEntry.get_text() if not os.path.exists(fdir): rel="" if fdir[0]=='/': rel="/" dirs=fdir.split("/") for d in dirs: rel+=d+"/" if not os.path.exists(rel): print "Making directory %s"%rel os.mkdir(rel) if dironly: return fdir else: return os.path.join(fdir,"corr"+time.strftime("%y%m%d_%H%M%S_")) def saveRef(self,w): d=darc.Control(self.prefix) rf=d.Get("refCentroids") if rf!=None: fn=self.makefilename() fn2=fn+self.prefix+"refCentroids.fits" FITS.Write(rf,fn2) self.entrySlopesFilename.set_text(os.path.split(fn2)[1]) else: print "No ref slopes to save" def loadRef(self,w): dd=self.makefilename(dironly=1) e=self.entrySlopesFilename fname=e.get_text() if len(fname)==0: fname=None else: fname=os.path.join(dd,fname) flist=glob.glob(fname) flist.sort() if len(flist)==0: #file selection fname=None else: fname=flist[-1]#chose latest. e.set_text(os.path.split(fname)[1]) if fname==None: #pop up file selection. f=gtk.FileChooserDialog("Load ref slopes",self.win,action=gtk.FILE_CHOOSER_ACTION_OPEN,buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_REJECT,gtk.STOCK_OK,gtk.RESPONSE_ACCEPT)) f.set_current_folder(dd) f.set_modal(True) fil=gtk.FileFilter() fil.set_name("Ref slopes files") fil.add_pattern("corr*_*_*refCentroids.fits") f.add_filter(fil) f.set_filter(fil) fil=gtk.FileFilter() fil.set_name("All files") fil.add_pattern("*") f.add_filter(fil) resp=f.run() if resp==gtk.RESPONSE_ACCEPT: fname=f.get_filename() f.destroy() if fname!=None: print "Reading %s"%fname data=FITS.Read(fname)[1] d=darc.Control(self.prefix) d.Set("refCentroids",data) self.entrySlopesFilename.set_text(os.path.split(fname)[1]) def computeSlopes(self,w,e): pad=int(e.get_text()) self.newslopes,usernow,self.corr=getSlopes(self.img,pad,1) img=self.corr["correlation"] img=img[self.corr["corrNpxlCum"][2]:] img.shape=self.corr["corrNpxly"][2],self.corr["corrNpxlx"][2] self.pad=pad self.im.cla() self.im.set_title("Correlated img") self.im.imshow(img) self.im2.cla() self.im2.set_title("Update to slopes") self.im2.plot(self.newslopes[288:]) self.fig1.draw() def upload(self,w,e): pad=int(e.get_text()) if pad!=self.pad: self.computeSlopes(None,e) d=gtk.Dialog("Padding changed",self.win,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_CANCEL,gtk.RESPONSE_REJECT,gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) d.vbox.pack_start(gtk.Label("Padding has changed since you last computed slopes.\nThese have been recomputed for you to check.\nClick OK to continue.")) d.show_all() resp=d.run() d.destroy() if resp==gtk.RESPONSE_ACCEPT: self.pad=pad if self.pad==pad: newslopes,usenow=getSlopes(self.img,pad) newcorr=makefft(self.img,pad) d=darc.Control(self.prefix) if usenow:#currently in corr mode, so update the slopes... refSlopes=d.Get("refCentroids") if refSlopes==None: refSlopes=-newslopes else: refSlopes-=newslopes newcorr["refCentroids"]=refSlopes d.Set(newcorr.keys(),newcorr.values()) def setCoG(self,w,e): d=darc.Control(self.prefix) if w.get_active(): #has set to cog mode. So change back to cog mode. cm=numpy.zeros((49*5,),numpy.int32) #so get current correlation image, and compute the ref slopes offset. img=makeIdent() #compute padding currently used. sl=d.Get("subapLocation") try: sl2=d.Get("corrSubapLoc") except: sl2=sl.copy() sl.shape=sl.size//6,6 sl2.shape=sl2.size//6,6 padarr=(sl2[:,1::3]-sl2[:,::3])/numpy.where(sl2[:,2::3]==0,1000,sl2[:,2::3])-(sl[:,1::3]-sl[:,::3])/numpy.where(sl[:,2::3]==0,1000,sl[:,2::3]) padused=numpy.max(padarr)//2 print "Calculated currently used padding as %d"%padused slopes,usenow=getSlopes(img,padused) refSlopes=d.Get("refCentroids") if refSlopes==None: refSlopes=-slopes else: refSlopes-=slopes d.Set(["centroidMode","refCentroids"],[cm,refSlopes]) else: #has set to corr mode (but currently in cog mode). img=getCurrentImg() slopes,usenow=getSlopes(img,self.pad) refSlopes=d.Get("refCentroids") if refSlopes==None: refSlopes=-slopes else: refSlopes-=slopes cm=numpy.zeros((49*5,),numpy.int32) cm[-49:]=1 d.Set(["centroidMode","refCentroids"],[cm,refSlopes]) def rtd(self,w): d=darc.Control(self.prefix) try: npxlx=d.Get("corrNpxlx") except: npxlx=d.Get("npxlx") try: npxly=d.Get("corrNpxly") except: npxly=d.Get("npxly") off=(npxlx*npxly)[:-1].sum() os.system("""darcplot --prefix=SH rtcCorrBuf 25 "-mdata=data[%d:];data.shape=%d,%d" &"""%(off,npxly[-1],npxlx[-1]))
class BenchitGUI(object): #biRootDir = os.getcwd() biRootDir = None guiRootDir = None # ich weiss noch nicht wie ich wieder an die canvas und das ax (Axes) der canvas rankomme -> also erst mal globaler pointer :( ax = None canvas = None # leeres dictionary um sich die geoeffneten files / modificationsdaten der files zu speichern openedFiles = {} def __init__(self): # selber ################# self.guiRootDir = os.path.dirname( sys.argv[0] ) self.biRootDir = self.guiRootDir ########################## builder = gtk.Builder() builder.add_from_file( os.path.join(self.guiRootDir, 'gui.xml') ) builder.connect_signals({ "on_BenchitGUI_destroy" : gtk.main_quit }) self.window = builder.get_object("BenchitGUI") # selber ################# # args durchsuchen try: i = sys.argv.index("-p") except: i = -1 # benchit root dir setzen if i != -1: self.biRootDir = os.path.normpath(sys.argv[i + 1]) # ein paar einstellung an den gui elementen machen self.setHostsTreeview(builder) self.setKernelTreeview(builder) self.setFilesTreeview(builder) self.setKernelNotebook(builder) self.setPlotNotebook(builder) self.setMenubar(builder) self.setSourceTextview(builder) self.setEnvTextview(builder) self.setBatchTextview(builder) self.setHWInfoTextview(builder) self.setPlainTextview(builder) self.setCompileAndRunButtons(builder) self.setHostsCheckButtons(builder) self.setCompileAndRunNotebook(builder) ########################## self.window.show() def setCompileAndRunNotebook(self, builder): #print "setCompileAndRunNotebook: ", self, builder notebook = builder.get_object("carNotebook") notebook.set_scrollable(True) notebook.connect("key-press-event", self.on_control_w) def on_control_w(self, notebook, event): #print "on_control_w: ", self, notebook, event, dictkey # die gedrueckte key / keycombi auslesen, fuehrt auf verschiedenen rechnern zu unterschiedlichen keys, zb Ctrl+W <-> Ctrl+Mod2+W, ABER event.keyval ist gleich #key = gtk.accelerator_get_label(event.keyval, event.state) # wenn die keycombi ctrl+w -> event.keyval=119 ist, dann schliesse das aktuelle tab des carNotebooks if event.keyval == 119: pagenum = notebook.get_current_page() notebook.remove_page(pagenum) def setHostsCheckButtons(self, builder): #print "setHostsCheckButtons: ", self, builder hosts = [] treeview = builder.get_object("hostsTreeview") liststore = treeview.get_model() try: iterator = liststore.get_iter_root() except: iterator = None while iterator != None: hosts.append(liststore.get_value(iterator, 0)) iterator = liststore.iter_next(iterator) # mal sehen wie das dann unter win gehen soll localhost = '' if sys.platform == 'linux2': localhost = commands.getoutput('hostname') vbox = builder.get_object("vbox7") if len(hosts) > 0: for host in hosts: checkbutton = gtk.CheckButton(host) if localhost == host: checkbutton.set_active(True) #button.connect("toggled", self.callback, "check button 1") vbox.pack_start(checkbutton, True, True, 2) checkbutton.show() else: checkbutton = gtk.CheckButton('no hosts found') vbox.pack_start(checkbutton, True, True, 2) checkbutton.show() def setCompileAndRunButtons(self, builder): button = builder.get_object("compileButton") button.connect("clicked", self.on_compileKernel, builder) button = builder.get_object("runButton") button.connect("clicked", self.on_runKernel, builder) button = builder.get_object("carButton") button.connect("clicked", self.on_compileAndRunKernel, builder) def on_compileKernel(self, button, builder): #print "on_compileKernel: ", self, button, builder self.compileKernel(builder) def on_runKernel(self, button, builder): #print "on_runKernel: ", self, button, builder self.runKernel(builder) def on_compileAndRunKernel(self, button, builder): #print "on_compileAndRunKernel: ", self, button, builder self.compileAndRunKernel(builder) def compileAndRunKernel(self, builder): #print "compileAndRunKernel: ", self, builder # hole den kerneTreeview aus dem builder treeview = builder.get_object("kernelTreeview") # ermittle welches kernel grad angewaehlt ist path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) tooltip = '' for subdir in subdirs: tooltip = os.path.join(tooltip, subdir) directory = os.path.join('kernel', tooltip) binary = '' for subdir in subdirs: binary = '%s%s%s' % (binary, '.', subdir) # fuehrenden punkt loeschen und am ende ein .0 anfuegen, warum auch immer die kerne mit .0 enden binary = '%s%s' % (binary[1:], '.0') binary = os.path.join('bin', binary) label = '%s%s%s%s' % ('C&R: ', subdirs[0], '/../', subdirs[-1]) toggledHosts = self.getToggledHosts(builder) if toggledHosts == []: print 'you have no hosts selected to run this command' # mal sehen wie das dann unter win gehen soll localhost = '' if sys.platform == 'linux2': localhost = commands.getoutput('hostname') for host in toggledHosts: if host == localhost: # rufe die benchit compile.sh und run.sh mit dem selectierten kern compileCommand = '%s%s%s' % (os.path.join(self.biRootDir, 'COMPILE.SH'), ' ', directory) runCommand = '%s%s%s' % (os.path.join(self.biRootDir, 'RUN.SH'), ' ', binary) command = '%s%s%s' % (compileCommand, ' && ', runCommand) self.update_carNotebook(command, label, tooltip, builder) else: print 'remote measurement is actually not implemented' def compileKernel(self, builder): #print "compileKernel: ", self, builder # hole den kerneTreeview aus dem builder treeview = builder.get_object("kernelTreeview") # ermittle welches kernel grad angewaehlt ist path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) tooltip = '' for subdir in subdirs: tooltip = os.path.join(tooltip, subdir) directory = os.path.join('kernel', tooltip) label = '%s%s%s%s' % ('C: ', subdirs[0], '/../', subdirs[-1]) toggledHosts = self.getToggledHosts(builder) if toggledHosts == []: print 'you have no hosts selected to run this command' # mal sehen wie das dann unter win gehen soll localhost = '' if sys.platform == 'linux2': localhost = commands.getoutput('hostname') for host in toggledHosts: if host == localhost: # rufe die benchit compile.sh mit dem selectierten kern command = '%s%s%s' % (os.path.join(self.biRootDir, 'COMPILE.SH'), ' ', directory) self.update_carNotebook(command, label, tooltip, builder) else: print 'remote measurement is actually not implemented' def runKernel(self, builder): #print "compileKernel: ", self, builder # hole den kerneTreeview aus dem builder treeview = builder.get_object("kernelTreeview") # ermittle welches kernel grad angewaehlt ist path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) tooltip = '' for subdir in subdirs: tooltip = '%s%s%s' % (tooltip, '.', subdir) # fuehrenden punkt loeschen und am ende ein .0 anfuegen, warum auch immer die kerne mit .0 enden tooltip = '%s%s' % (tooltip[1:], '.0') binary = os.path.join('bin', tooltip) label = '%s%s%s%s%s' % ('R: ', subdirs[0], '..', subdirs[-1], '.0') toggledHosts = self.getToggledHosts(builder) if toggledHosts == []: print 'you have no hosts selected to run this command' # mal sehen wie das dann unter win gehen soll localhost = '' if sys.platform == 'linux2': localhost = commands.getoutput('hostname') for host in toggledHosts: if host == localhost: # rufe die benchit run.sh mit dem selectierten kern command = '%s%s%s' % (os.path.join(self.biRootDir, 'RUN.SH'), ' ', binary) self.update_carNotebook(command, label, tooltip, builder) else: print 'remote measurement is actually not implemented' def getToggledHosts(self, builder): #print "getToggledHosts: ", self, builder vbox = builder.get_object("vbox7") hosts = [] for checkbutton in vbox.get_children(): if checkbutton.get_active(): hosts.append( checkbutton.get_label() ) # liefer die liste mit den host checkbuttons die momentan aktiviert sind return hosts def update_carNotebook(self, command, label, tooltip, builder): #print "update_carNotebook: ", self, command, builder notebook = builder.get_object("carNotebook") sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() textview.set_editable(False) textbuffer = textview.get_buffer() sw.add(textview) sw.show() textview.show() pagelabel = gtk.Label(label) pagelabel.set_tooltip_text(tooltip) notebook.append_page(sw, pagelabel) # starte das commando und uebergib einem io_watch den buffer in den er schreiben soll, wenn von dem compile/run command was auf stdout geschrieben wird proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) glib.io_add_watch(proc.stdout, glib.IO_IN | glib.IO_HUP, self.write_to_buffer_in_tab, textbuffer) # frag mich nciht, ich habs nur von http://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/ def write_to_buffer_in_tab(self, filedescriptor, condition, textbuffer): if condition == glib.IO_IN or condition == glib.IO_IN | glib.IO_HUP: char = filedescriptor.read(1) textbuffer.insert_at_cursor(char) return True elif condition == glib.IO_HUP: return False else: return False def setMenubar(self, builder): imageMenuItem = builder.get_object("imagemenuitem11") imageMenuItem.connect("activate", self.showPrimNumbersWindow, builder) imageMenuItem = builder.get_object("imagemenuitem5") imageMenuItem.connect("activate", gtk.main_quit) def showPrimNumbersWindow(self, menuitem, builder): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_size_request(500, 500) window.set_title("Prim Numbers - Range 1 to 100000") # das hier auskommentieren verursacht viellei datenlecks # window.connect("", lambda w: window.destroy()) # window.connect("destroy", lambda w: window.destroy()) vbox = gtk.VBox(False, 0) sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() textview.set_editable(False) textbuffer = textview.get_buffer() sw.add(textview) sw.show() textview.show() vbox.pack_start(sw) filepath = os.path.join(self.guiRootDir, 'primNumbers.txt') primNumberFile = open( filepath , 'r') if primNumberFile: string = primNumberFile.read() primNumberFile.close() textbuffer.set_text(string) window.add(vbox) vbox.show() window.show() def setKernelNotebook(self, builder): self.notebook = builder.get_object("kernelNotebook") self.notebook.connect('switch-page', self.on_pageOfKernelNotebook_selected, builder) def getSubDirsFromTreeview(self, treeview, path): #print "getSubDirsFromTreeview: ", self, treeview subdirs = [] treestore = treeview.get_model() try: iterator = treestore.get_iter(path) except: iterator = None while iterator != None: subdirs.append(treestore.get_value(iterator, 0)) iterator = treestore.iter_parent(iterator) # reihenfolge war falsch rum subdirs.reverse() # gebe die subdirectories im feld zurueck return subdirs def on_pageOfKernelNotebook_selected(self, notebook, notneeded, pageNumber, builder): # print "on_pageOfKernelNotebook_selected: ", self, notebook, notneeded, pageNumber, builder # hole den kerneTreeview aus dem builder treeview = builder.get_object("kernelTreeview") # ermittle welches kernel grad angewaehlt ist path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) # ermittle das label der selectierten tabs page = notebook.get_nth_page(pageNumber) label = notebook.get_tab_label_text(page) # update den filesTreeview, jenachdem welches tab/page aktiviert ist self.updateKernelFilesTreeview( subdirs, label, builder ) def setKernelTreeview(self, builder): self.treestore = gtk.TreeStore(str) kernelDir = os.path.join(self.biRootDir, 'kernel') c = kernelDir.count(os.sep) parentIter = [None] # parents fuer die einzelnen TreeStores # erstelle den kernel baum for path, subdirs, files in os.walk(kernelDir): if c != path.count(os.sep): # sonst wird kernel dir mit angezeigt tmpc = path.count(os.sep) if path.find('.svn') == -1: tmpIter = self.treestore.append(parentIter[tmpc - c - 1], [os.path.basename(path)]) if tmpc - c == len(parentIter): parentIter.append(tmpIter) else: parentIter[tmpc - c] = tmpIter # create the TreeView using treestore self.treeview = builder.get_object("kernelTreeview") self.treeview.set_model(self.treestore) # create the TreeViewColumn to display the data self.tvcolumn = gtk.TreeViewColumn('Kernels') # add tvcolumn to treeview self.treeview.append_column(self.tvcolumn) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() # add the cell to the tvcolumn and allow it to expand self.tvcolumn.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text # from that column in treestore self.tvcolumn.add_attribute(self.cell, 'text', 0) # make it NOT searchable self.treeview.set_enable_search(False) # self.treeview.set_show_expanders(False) # self.treeview.set_level_indentation(20) self.treeview.connect('row_activated', self.on_row_activated, builder) self.treeview.connect('row-expanded', self.on_row_expanded, builder) self.treeview.connect('row-collapsed', self.on_row_expanded, builder) def setFilesTreeview(self, builder): self.liststore = gtk.ListStore(str) # create the TreeView using treestore self.treeview = builder.get_object('kernelFilesTreeview') self.treeview.set_model(self.liststore) # create the TreeViewColumn to display the data self.tvcolumn = gtk.TreeViewColumn('Files') # add tvcolumn to treeview self.treeview.append_column(self.tvcolumn) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() # add the cell to the tvcolumn and allow it to expand self.tvcolumn.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text # from that column in treestore self.tvcolumn.add_attribute(self.cell, 'text', 0) # make it NOT searchable self.treeview.set_enable_search(False) self.treeview.connect('row_activated', self.on_file_selected, builder) def on_file_selected(self, treeview, path, view_column, builder): #print "on_file_selected: ", self, treeview, path, view_column, builder # auslesen ob editTab, compileTab oder plotTab aktiviert ist self.notebook = builder.get_object('kernelNotebook') pagenum = self.notebook.get_current_page() page = self.notebook.get_nth_page(pagenum) label = self.notebook.get_tab_label_text(page) # je nachdem was angewaehlt ist, wird irgendwas gemacht ;) if label == 'Edit Source Code': self.on_sourcefile_selected(treeview, path, view_column, builder) elif label == 'Compile / Run': print 'mal sehen' elif label == 'Plot Result': self.on_plotfile_selected(treeview, path, view_column, builder) else: print 'Unknown label: ', label, ' in function: on_file_selected!' def on_sourcefile_selected(self, treeview, path, view_column, builder): #print "on_sourcefile_selected: ", self, treeview, path, view_column, builder # wie heisst das selectierte source file sourcefile = treeview.get_model().get_value( treeview.get_model().get_iter(path), 0 ) # wie ist der pfad zu dem sourcefile treeview = builder.get_object("kernelTreeview") path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) # try: # iterator = treeview.get_model().get_iter(path) # except: # iterator = None # # subdirs = [] # while iterator != None: # subdirs.append(treeview.get_model().get_value(iterator, 0)) # iterator = treeview.get_model().iter_parent(iterator) # # reihenfolge war falsch rum # subdirs.reverse() directory = os.path.join(self.biRootDir, 'kernel') for subdir in subdirs: directory = os.path.join(directory, subdir) # hole entsprechende textview sourceTextview = builder.get_object("sourceTextview") sourceFileBuffer = sourceTextview.get_buffer() # sourcefile einlesen und dem buffer uebergeben filepath = os.path.join(directory, sourcefile) sourceFile = open(filepath, 'r') if sourceFile: self.updateOpenedFiles('sourceTextview', filepath) sourceString = sourceFile.read() sourceFile.close() else: self.updateOpenedFiles('sourceTextview', '') sourceString = '%s%s%s' % ('File: ', filepath, ' not found') sourceFileBuffer.set_text(sourceString) def setSourceTextview(self, builder): #print "setSourceTextview: ", self, builder textview = builder.get_object('sourceTextview') textview.connect("key-press-event", self.on_control_s, 'sourceTextview') def setEnvTextview(self, builder): #print "setEnvTextview: ", self, builder textview = builder.get_object('envTextview') textview.connect("key-press-event", self.on_control_s, 'envTextview') def setBatchTextview(self, builder): #print "setBatchTextview: ", self, builder textview = builder.get_object('batchTextview') textview.connect("key-press-event", self.on_control_s, 'batchTextview') def setHWInfoTextview(self, builder): #print "setHWInfoTextview: ", self, builder textview = builder.get_object('hwInfoTextview') textview.connect("key-press-event", self.on_control_s, 'hwInfoTextview') def setPlainTextview(self, builder): #print "setPlainTextview: ", self, builder textview = builder.get_object('env_plainTextview') textview.connect("key-press-event", self.on_control_s_in_PlainTextview, 'plainTextview', builder) textview = builder.get_object('value_plainTextview') textview.connect("key-press-event", self.on_control_s_in_PlainTextview, 'plainTextview', builder) def updateOpenedFiles(self, string, filepath): #print "updateOpenedFiles: ", self, string, filepath if os.path.exists(filepath): self.openedFiles[string] = (filepath, os.path.getmtime(filepath)) else: self.openedFiles[string] = ('', 0.0) def getOpenedFiles(self, dictkey): #print "getOpenedFiles: ", self, dictkey if dictkey in self.openedFiles: return self.openedFiles[dictkey] else: return ('', 0.0) def on_control_s(self, textview, event, dictkey): #print "on_control_s: ", self, textview, event, dictkey # die gedrueckte key / keycombi auslesen, fuehrt auf verschiedenen rechnern zu unterschiedlichen keys, zb Ctrl+S <-> Ctrl+Mod2+S, ABER event.keyval ist gleich #key = gtk.accelerator_get_label(event.keyval, event.state) # wenn die keycombi ctrl+s -> event.keyval=115 ist, dann speicher den textbuffer in die datei if event.keyval == 115: # hole den filenamen dessen inhalt im buffer steckt und hole den timestamp der letzten modifikation als die datei eingelesen wurde filepath, lastmod = self.getOpenedFiles(dictkey) if os.path.exists(filepath): if os.path.getmtime(filepath) == lastmod: # hole den text aus dem textbuffer des textview textbuffer = textview.get_buffer() text = textbuffer.get_text( textbuffer.get_start_iter(), textbuffer.get_end_iter(), True ) # file hinter filepath oeffnen und inhalt des textbuffers reinschreiben outfile = open(filepath, 'w') if outfile: outfile.write(text) outfile.close() self.updateOpenedFiles(dictkey, filepath) else: print '%s%s%s' % ('File: ', filepath, ' not found') else: print '%s%s%s' % ('File: ', filepath, ' has modified by another program') else: print '%s%s%s' % ('File: ', filepath, ' not found') def on_control_s_in_PlainTextview(self, textview, event, dictkey, builder): #print "on_control_s: ", self, textview, event, dictkey # die gedrueckte key / keycombi auslesen key = gtk.accelerator_get_label(event.keyval, event.state) # wenn die keycombi ctrl+s ist, dann speicher den textbuffer in die datei if key == 'Ctrl+S': # hole den filenamen dessen inhalt im buffer steckt und hole den timestamp der letzten modifikation als die datei eingelesen wurde filepath, lastmod = self.getOpenedFiles(dictkey) if os.path.exists(filepath): if os.path.getmtime(filepath) == lastmod: # hole den text aus dem textbuffer der 2 textviews textview = builder.get_object('env_plainTextview') textbuffer = textview.get_buffer() text1 = textbuffer.get_text( textbuffer.get_start_iter(), textbuffer.get_end_iter(), True ) textview = builder.get_object('value_plainTextview') textbuffer = textview.get_buffer() text2 = textbuffer.get_text( textbuffer.get_start_iter(), textbuffer.get_end_iter(), True ) # file hinter filepath oeffnen und inhalt des textbuffers reinschreiben outfile = open(filepath, 'w') if outfile: outfile.write(text1) outfile.write(text2) outfile.close() self.updateOpenedFiles(dictkey, filepath) # wenn die zahlen geaendert werden muss naturlich auch der plot geaendert werden self.updateViewPlot(filepath, builder) else: print '%s%s%s' % ('File: ', filepath, ' not found') else: print '%s%s%s' % ('File: ', filepath, ' has modified by another program') else: print '%s%s%s' % ('File: ', filepath, ' not found') def on_plotfile_selected(self, treeview, path, view_column, builder): #print "on_plotfile_selected: ", self, treeview, path, view_column, builder # wie heisst das selectierte result file resultfile = treeview.get_model().get_value( treeview.get_model().get_iter(path), 0 ) # wie ist der pfad zu dem resultfile treeview = builder.get_object("kernelTreeview") path, tvcolumn = treeview.get_cursor() # hole die zweige des ermittelten kernels subdirs = self.getSubDirsFromTreeview(treeview, path) # iterator = treeview.get_model().get_iter(path) # subdirs = [] # while iterator != None: # subdirs.append(treeview.get_model().get_value(iterator, 0)) # iterator = treeview.get_model().iter_parent(iterator) # # reihenfolge war falsch rum # subdirs.reverse() directory = os.path.join(self.biRootDir, 'output') for subdir in subdirs: directory = os.path.join(directory, subdir) filepath = os.path.join(directory, resultfile) # auslesen welches aktiviert ist self.notebook = builder.get_object('plotNotebook') pagenum = self.notebook.get_current_page() page = self.notebook.get_nth_page(pagenum) label = self.notebook.get_tab_label_text(page) # update die einzelnen tabs # je nachdem was angewaehlt ist, wird zuerst diess tab als prioritaet erachtet if label == 'View Plot': self.updateViewPlot(filepath, builder) #self.updateConfigPlot(filepath, builder) #self.updateExportPlot(filepath, builder) self.updatePlainTextview(filepath, builder) elif label == 'Config Plot': #self.updateConfigPlot(filepath, builder) #self.updateExportPlot(filepath, builder) self.updatePlainTextview(filepath, builder) self.updateViewPlot(filepath, builder) elif label == 'Export Plot': #self.updateExportPlot(filepath, builder) #self.updateConfigPlot(filepath, builder) self.updatePlainTextview(filepath, builder) self.updateViewPlot(filepath, builder) elif label == 'Plain Source': self.updatePlainTextview(filepath, builder) #self.updateConfigPlot(filepath, builder) #self.updateExportPlot(filepath, builder) self.updateViewPlot(filepath, builder) else: print 'Unknown label: ', label, ' in function: on_plotfile_selected!' def setPlotNotebook(self, builder): #print "setPlotNotebook: ", self, builder fig = Figure(figsize=(10,10), dpi=100) self.ax = fig.add_subplot(111) self.canvas = FigureCanvas(fig) notebook = builder.get_object("plotNotebook") notebook.remove_page(0) notebook.insert_page(self.canvas, gtk.Label('View Plot'), 0) self.canvas.show() # setze wieder auf 1. tab, das remove und insert hat den focus verschoben notebook.set_current_page(0) def updateViewPlot(self, filepath, builder): #print "updatePlainTextview: ", self, filepath, builder # oeffne das resultfile, lese inhalt ein, schliesse file wieder resultFile = open(filepath, 'r') if resultFile: # alle zeilen der datei lesen res = resultFile.readlines() pos1 = res.index('beginofdata\n') + 1 pos2 = res.index('endofdata\n') # ergebnisse (messdaten) in eine liste konvertieren data = map(lambda x: string.split(x, '\t')[0:-1], res[pos1:pos2]) # dummys erstellt um spaeter zu fuellen numfunc = len(data[0]) - 1 x = zeros(pos2-pos1) y = zeros((pos2-pos1, numfunc)) # dummys fuellen i = -1 for row in data: i = i + 1 x[i] = float(row[0]) j = -1 for elem in row[1:]: j = j + 1 try: y[i, j] = float(elem) except: y[i, j] = nan # alte grafik loeschen self.ax.clear() # neue funktionen der grafik hinzufuegen for i in range(0, numfunc): self.ax.plot(x, y[:,i], 'o') # grafik neu zeichen self.canvas.draw() resultFile.close() else: print '%s%s%s' % ('File: ', filepath, ' not found') def updatePlainTextview(self, filepath, builder): #print "updatePlainTextview: ", self, filepath, builder # hole textview fuer die sachen die nix mit die wirklichen funktionsergebnissen zu tun haben env_plainTextview = builder.get_object("env_plainTextview") env_plainTextviewBuffer = env_plainTextview.get_buffer() # hole textview fuer die wirklichen funktionsergebnisse value_plainTextview = builder.get_object("value_plainTextview") value_plainTextviewBuffer = value_plainTextview.get_buffer() # oeffne das resultfile, lese inhalt ein, schliesse file wieder resultFile = open(filepath, 'r') if resultFile: self.updateOpenedFiles('plainTextview', filepath) string = resultFile.read() # schreibe in envString bis 'beginofdata' im resultFile gefunden wird # dort weiter lesen und die messergebnisse auslesen pos = string.find('%s%s' % ('beginofdata', os.linesep)) envString = string[:pos] valueString = string[pos:] resultFile.close() else: self.updateOpenedFiles('plainTextview', '') envString = '%s%s%s' % ('File: ', filepath, ' not found') valueString = '%s%s%s' % ('File: ', filepath, ' not found') # setze die buffer auf die richtigen strings env_plainTextviewBuffer.set_text(envString) value_plainTextviewBuffer.set_text(valueString) def on_row_activated(self, treeview, path, view_column, builder): # print "on_row_activated: ", self, treeview, path, view_column, builder path, tvcolumn = treeview.get_cursor() if treeview.row_expanded(path): treeview.collapse_row(path) else: if treeview.get_model().iter_has_child(treeview.get_model().get_iter(path)): treeview.expand_row(path, False) else: # wenn ich ein blatt bin, dann zeige nur die files self.on_row_expanded(treeview, treeview.get_model().get_iter(path), path, builder) def on_row_expanded(self, treeview, iterator, path, builder): # print "on_row_expanded: ", self, treeview, iterator, path, builder subdirs = [] while iterator != None: subdirs.append(treeview.get_model().get_value(iterator, 0)) iterator = treeview.get_model().iter_parent(iterator) # reihenfolge war falsch rum subdirs.reverse() self.notebook = builder.get_object('kernelNotebook') pagenum = self.notebook.get_current_page() page = self.notebook.get_nth_page(pagenum) label = self.notebook.get_tab_label_text(page) self.updateKernelFilesTreeview( subdirs, label, builder ) def updateKernelFilesTreeview( self, selectedPathInKernelTreeview, selectedKernelNotebookPageLabel, builder ): treeview = builder.get_object('kernelFilesTreeview') liststore = treeview.get_model() liststore.clear() subdirs = selectedPathInKernelTreeview label = selectedKernelNotebookPageLabel # fuer die dateien etweder im kernel oder im output ordner if label == 'Edit Source Code': directory = os.path.join(self.biRootDir, 'kernel') for subdir in subdirs: directory = os.path.join(directory, subdir) # durchsuche das LOCALDEF dir nach hosts for files in os.listdir(directory): if os.path.isfile(os.path.join(directory, files)): liststore.append(['%s' % files]) # fuer die binaries im bin ordner elif label == 'Compile / Run': directory = os.path.join(self.biRootDir, 'bin') for files in os.listdir(directory): if os.path.isfile(os.path.join(directory, files)): rightFile = True for substr in subdirs: if files.find(substr) == -1: rightFile = False break if rightFile: liststore.append(['%s' % files]) elif label == 'Plot Result': directory = os.path.join(self.biRootDir, 'output') for subdir in subdirs: directory = os.path.join(directory, subdir) # nur die durchsuchen wenn es den ordner wirklich gibt, muss bei output nicht der fall sein if os.path.exists(directory): # durchsuche das output dir nach bit files for files in os.listdir(directory): if os.path.isfile(os.path.join(directory, files)) and (not files.endswith('.bit.gp') and (not files.endswith('.bit.gui'))): liststore.append(['%s' % files]) else: print 'Unknown label: ', label, ' in function: updateKernelFilesTreeview!' def setHostsTreeview(self, builder): self.liststore = gtk.ListStore(str) # durchsuche das LOCALDEF dir nach hosts for hostfile in os.listdir(os.path.join(self.biRootDir, 'LOCALDEFS')): if (not hostfile.endswith('_input_architecture')) and (not hostfile.endswith('_input_display')) and (not hostfile.startswith('PROTOTYPE')) and (not hostfile.startswith('.svn')): self.liststore.append(['%s' % hostfile]) # create the TreeView using treestore self.treeview = builder.get_object("hostsTreeview") self.treeview.set_model(self.liststore) # create the TreeViewColumn to display the data self.tvcolumn = gtk.TreeViewColumn('Hosts') # add tvcolumn to treeview self.treeview.append_column(self.tvcolumn) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() # add the cell to the tvcolumn and allow it to expand self.tvcolumn.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text # from that column in treestore self.tvcolumn.add_attribute(self.cell, 'text', 0) # make it NOT searchable self.treeview.set_enable_search(False) # make it searchable #self.treeview.set_search_column(0) # Allow sorting on the column #self.tvcolumn.set_sort_column_id(0) # Allow drag and drop reordering of rows #self.treeview.set_reorderable(True) self.treeview.connect('row_activated', self.on_host_selected, builder) # reagiere wenn Host angewaehlt wird def on_host_selected(self, treeview, path, view_column, builder): # print "on_host_selected: ", self, treeview, path, view_column, builder host = treeview.get_model().get_value( treeview.get_model().get_iter(path), 0 ) # setze die buffer um die files einzulesen envTextview = builder.get_object("envTextview") envFileBuffer = envTextview.get_buffer() batchTextview = builder.get_object("batchTextview") batchFileBuffer = batchTextview.get_buffer() hwInfoTextview = builder.get_object("hwInfoTextview") hwInfoFileBuffer = hwInfoTextview.get_buffer() # oeffne das hostFile, lese inhalt ein, schliesse file wieder filepath = os.path.join(self.biRootDir, 'LOCALDEFS') filepath = os.path.join(filepath, host) envFile = open(filepath, 'r') if envFile: self.updateOpenedFiles('envTextview', filepath) envString = envFile.read() # suche das zum host gehoerende batchsystemFile in dem hostFile envFile.seek(0, 0) for line in envFile: if line.find('BENCHIT_ENVIRONMENT=') != -1: batch = line.split('\"') break envFile.close() else: self.updateOpenedFiles('envTextview', '') envString = '%s%s%s' % ('File: ', filepath, ' not found') batch = ['', 'unknown (cause: envFile not found)'] # oeffne das zum hostFile gehoerende hardwareInfoFile, lese inhalt ein, schliesse file wieder filepath = os.path.join(self.biRootDir, 'LOCALDEFS') filepath = os.path.join(filepath, '%s%s' % (host, '_input_architecture')) hwInfoFile = open(filepath, 'r') if hwInfoFile: self.updateOpenedFiles('hwInfoTextview', filepath) hwInfoString = hwInfoFile.read() hwInfoFile.close() else: self.updateOpenedFiles('hwInfoTextview', '') hwInfoString = '%s%s%s' % ('File: ', filepath, ' not found') # oeffne das zum hostFile gehoerende batchsystemFile, lese inhalt ein, schliesse file wieder filepath = os.path.join(self.biRootDir, 'tools') filepath = os.path.join(filepath, 'environments') filepath = os.path.join(filepath, batch[1]) batchFile = open(filepath, 'r') if batchFile: self.updateOpenedFiles('batchTextview', filepath) batchString = batchFile.read() batchFile.close() else: self.updateOpenedFiles('batchTextview', '') batchString = '%s%s%s' % ('File: ', filepath, ' not found') # setze die buffer auf die richtigen strings envFileBuffer.set_text(envString) hwInfoFileBuffer.set_text(hwInfoString) batchFileBuffer.set_text(batchString)