def recreate_canvas(self, fig): canvas = FigureCanvas(fig) canvas.set_size_request(450, 200) if self.canvas_frame.get_child(): self.canvas_frame.remove(self.canvas_frame.get_child()) self.canvas_frame.add(canvas) canvas.show()
class WidgetsWrapper(object): def __init__(self): self.widgets = gtk.glade.XML('mpl_with_glade.glade') self.widgets.signal_autoconnect(GladeHandlers.__dict__) self['windowMain'].connect('destroy', lambda x: gtk.main_quit()) self['windowMain'].move(10, 10) self.figure = Figure(figsize=(8, 6), dpi=72) self.axis = self.figure.add_subplot(111) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axis.plot(t, s) self.axis.set_xlabel('time (s)') self.axis.set_ylabel('voltage') self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.show() self.canvas.set_size_request(600, 400) self.canvas.set_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK) self.canvas.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS) self.canvas.grab_focus() def keypress(widget, event): print('key press') def buttonpress(widget, event): print('button press') self.canvas.connect('key_press_event', keypress) self.canvas.connect('button_press_event', buttonpress) def onselect(xmin, xmax): print(xmin, xmax) span = SpanSelector(self.axis, onselect, 'horizontal', useblit=False, rectprops=dict(alpha=0.5, facecolor='red')) self['vboxMain'].pack_start(self.canvas, True, True) self['vboxMain'].show() # below is optional if you want the navigation toolbar self.navToolbar = NavigationToolbar(self.canvas, self['windowMain']) self.navToolbar.lastDir = '/var/tmp/' self['vboxMain'].pack_start(self.navToolbar) self.navToolbar.show() sep = gtk.HSeparator() sep.show() self['vboxMain'].pack_start(sep, True, True) self['vboxMain'].reorder_child(self['buttonClickMe'], -1) def __getitem__(self, key): return self.widgets.get_widget(key)
class HelloMatplotlib: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("delete_event", self.delete_event) self.window.connect("destroy", self.destroy) self.window.set_size_request(400, 400) self.window.set_border_width(10) f = Figure(figsize=(5,4), dpi=100) a = f.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) a.plot(t,s) self.canvas = FigureCanvas(f) self.canvas.show() self.window.add(self.canvas) self.window.show() def delete_event(self, widget, event, data=None): gtk.main_quit() def destroy(self, widget, data=None): gtk.main_quit() def main(self): gtk.main()
def __init__(self): self._gladefile = "neuronview.glade" self._builder = gtk.Builder() self._builder.add_from_file(self._gladefile) self._builder.connect_signals(self) self._win = self._builder.get_object("mainwindow") self._win.resize(900, 700) box = self._builder.get_object("box5") self._stimulatordictview = DictView() self._builder.get_object("scrolledwindow2").add(self._stimulatordictview) box = self._builder.get_object("box4") self._neurondictview = DictView() self._builder.get_object("scrolledwindow3").add(self._neurondictview) self.populate_comboboxes() self._figure = Figure(figsize=(5,4), dpi=100) canvas = FigureCanvas(self._figure) canvas.set_size_request(200, 250) canvas.show() box = self._builder.get_object("box3") bg_style = box.get_style().bg[gtk.STATE_NORMAL] gtk_color = (bg_style.red_float, bg_style.green_float, bg_style.blue_float) self._figure.set_facecolor(gtk_color) box.pack_start(canvas) self._win.show() gtk.main()
class WidgetsWrapper(object): def __init__(self): self.widgets = gtk.glade.XML('mpl_with_glade.glade') self.widgets.signal_autoconnect(GladeHandlers.__dict__) self['windowMain'].connect('destroy', lambda x: gtk.main_quit()) self['windowMain'].move(10, 10) self.figure = Figure(figsize=(8, 6), dpi=72) self.axis = self.figure.add_subplot(111) t = arange(0.0, 3.0, 0.01) s = sin(2*pi*t) self.axis.plot(t, s) self.axis.set_xlabel('time (s)') self.axis.set_ylabel('voltage') self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.show() self.canvas.set_size_request(600, 400) self.canvas.set_events( gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK ) self.canvas.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS) self.canvas.grab_focus() def keypress(widget, event): print('key press') def buttonpress(widget, event): print('button press') self.canvas.connect('key_press_event', keypress) self.canvas.connect('button_press_event', buttonpress) def onselect(xmin, xmax): print(xmin, xmax) span = SpanSelector(self.axis, onselect, 'horizontal', useblit=False, rectprops=dict(alpha=0.5, facecolor='red')) self['vboxMain'].pack_start(self.canvas, True, True) self['vboxMain'].show() # below is optional if you want the navigation toolbar self.navToolbar = NavigationToolbar(self.canvas, self['windowMain']) self.navToolbar.lastDir = '/var/tmp/' self['vboxMain'].pack_start(self.navToolbar) self.navToolbar.show() sep = gtk.HSeparator() sep.show() self['vboxMain'].pack_start(sep, True, True) self['vboxMain'].reorder_child(self['buttonClickMe'], -1) def __getitem__(self, key): return self.widgets.get_widget(key)
def graficar(self, datos, datos1, titulo): datos = datos # valores del tiempo de espera. datos1 = datos1 # valores de tiempo de cpu, tiempo de llegada y numeró de procesos. titulo = titulo x1 = [] y1 = [] y2 = [] n = len(datos) for i in xrange(n): x1.append(datos1[i][0]) #Numero de proceso y1.append(datos[i][1]) #Tiempo de espera y2.append(datos1[i][1]) #tiempo de uso del cpu self.win = gtk.Window() self.win.set_default_size(600,480) self.win.set_position(gtk.WIN_POS_CENTER) self.win.set_title(titulo) f = Figure(figsize=(5,4), dpi=100) a = f.add_subplot(111) a.plot(x1, y1, color='blue', label='(Procesos, Tiempo de espera)') a.legend(loc = 2) a.set_title(titulo, color='red', size=14) a.set_xlabel(u'Número de procesos', color='red', size=14) a.set_ylabel('Tiempo de espera ', color='red', size=14) """ # gráfica procesos vs tiempo de cpu #g = Figure(figsize=(5,4), dpi=100) b = f.add_subplot(111) b.plot(x1, y2, color='red', label='(Procesos, Tiempo de CPU)') b.set_xlabel(u'Número de procesos', color='red', size=14) b.set_ylabel('Tiempo de CPU ', color='red', size=14) """ vbox = gtk.VBox(False, 5) canvas = FigureCanvas(f) canvas.show() #canvas1 = FigureCanvas(g) #canvas1.show() vbox.pack_start(canvas, True, True, 0) #vbox.pack_start(canvas1, True, True, 0) cerrar = gtk.Button(stock=gtk.STOCK_CLOSE) cerrar.connect("activate", self.close) vbox.pack_start(cerrar, False, False, 0) self.win.add(vbox) self.win.show_all()
class WidgetsWrapper: def __init__(self): self.widgets = gtk.glade.XML('test.glade') self.widgets.signal_autoconnect(GladeHandlers.__dict__) self['windowMain'].connect('destroy', lambda x: gtk.main_quit()) self['windowMain'].move(10,10) self.figure = Figure(figsize=(8,6), dpi=72) self.axis = self.figure.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) self.axis.plot(t,s) self.axis.set_xlabel('time (s)') self.axis.set_ylabel('voltage') self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.show() self.canvas.set_size_request(600, 400) def onselect(xmin, xmax): print xmin, xmax span = HorizontalSpanSelector(self.axis, onselect, useblit=False, rectprops=dict(alpha=0.5, facecolor='red') ) self['vboxMain'].pack_start(self.canvas, True, True) self['vboxMain'].show() # below is optional if you want the navigation toolbar self.navToolbar = NavigationToolbar(self.canvas, self['windowMain']) self.navToolbar.lastDir = '/var/tmp/' self['vboxMain'].pack_start(self.navToolbar) self.navToolbar.show() sep = gtk.HSeparator() sep.show() self['vboxMain'].pack_start(sep, True, True) self['vboxMain'].reorder_child(self['buttonClickMe'],-1) def __getitem__(self, key): return self.widgets.get_widget(key)
class WidgetsWrapper: def __init__(self): self.widgets = gtk.glade.XML('test.glade') self.widgets.signal_autoconnect(GladeHandlers.__dict__) self['windowMain'].connect('destroy', lambda x: gtk.main_quit()) self['windowMain'].move(10, 10) self.figure = Figure(figsize=(8, 6), dpi=72) self.axis = self.figure.add_subplot(111) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axis.plot(t, s) self.axis.set_xlabel('time (s)') self.axis.set_ylabel('voltage') self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.show() self.canvas.set_size_request(600, 400) def onselect(xmin, xmax): print xmin, xmax span = HorizontalSpanSelector(self.axis, onselect, useblit=False, rectprops=dict(alpha=0.5, facecolor='red')) self['vboxMain'].pack_start(self.canvas, True, True) self['vboxMain'].show() # below is optional if you want the navigation toolbar self.navToolbar = NavigationToolbar(self.canvas, self['windowMain']) self.navToolbar.lastDir = '/var/tmp/' self['vboxMain'].pack_start(self.navToolbar) self.navToolbar.show() sep = gtk.HSeparator() sep.show() self['vboxMain'].pack_start(sep, True, True) self['vboxMain'].reorder_child(self['buttonClickMe'], -1) def __getitem__(self, key): return self.widgets.get_widget(key)
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, wTree, widget): figure = Figure(figsize=(6,4), dpi=72) axes = figure.add_subplot(1,1,1) canvas = FigureCanvasGTKAgg(figure) canvas.show() canvas.mpl_connect('pick_event', self.pick_handler) canvas.mpl_connect('motion_notify_event', self.motion_handler) canvas.mpl_connect('button_release_event', self.release_handler) canvas.mpl_connect('button_press_event', self.press_handler) graphview = wTree.get_widget(widget) graphview.add_with_viewport(canvas) self.figure = figure self.canvas = canvas self.axes = axes self.plot_line = self.axes.plot([], [], 'b-', animated=True)[0] self.cursors = [] self.picked = None self.data = []
def get_ax(self, custom_location=None): from matplotlib.figure import Figure from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas if custom_location: widget = self.get_widget(custom_location) else: widget = self.get_widget_in_current_location(self) if not widget or not widget.get_data('ax'): #logging.debug('creating ax') widget = gtk.Frame() fig = Figure(dpi=100) ax = fig.add_subplot(111) ax.set_aspect('auto') canvas = FigureCanvas(fig) self.on_canvas_draw(canvas) #canvas.mpl_connect('draw_event', self.on_canvas_draw) canvas.show() widget.add(canvas) if custom_location: services.add_widget(widget, custom_location) else: services.add_widget(widget, self.current_widget_locations[0]) widget.set_data('ax', ax) return widget.get_data('ax')
def __init__(self): self._gladefile = "neuronview.glade" self._builder = gtk.Builder() self._builder.add_from_file(self._gladefile) self._builder.connect_signals(self) self._win = self._builder.get_object("mainwindow") self._win.resize(900, 700) box = self._builder.get_object("box5") self._stimulatordictview = DictView() self._builder.get_object("scrolledwindow2").add( self._stimulatordictview) box = self._builder.get_object("box4") self._neurondictview = DictView() self._builder.get_object("scrolledwindow3").add(self._neurondictview) self.populate_comboboxes() self._figure = Figure(figsize=(5, 4), dpi=100) canvas = FigureCanvas(self._figure) canvas.set_size_request(200, 250) canvas.show() box = self._builder.get_object("box3") bg_style = box.get_style().bg[gtk.STATE_NORMAL] gtk_color = (bg_style.red_float, bg_style.green_float, bg_style.blue_float) self._figure.set_facecolor(gtk_color) box.pack_start(canvas) self._win.show() gtk.main()
def init(self): print "INIT!!" self.emesh_editor=electrical_mesh_editor() self.emesh_editor.init() self.fig = Figure(figsize=(5,4), dpi=100) self.ax1=None self.show_key=True self.hbox=gtk.HBox() self.edit_list=[] self.line_number=[] gui_pos=0 gui_pos=gui_pos+1 self.draw_graph() canvas = FigureCanvas(self.fig) # a gtk.DrawingArea #canvas.set_background('white') #canvas.set_facecolor('white') canvas.figure.patch.set_facecolor('white') canvas.set_size_request(500, 150) canvas.show() tooltips = gtk.Tooltips() toolbar = gtk.Toolbar() #toolbar.set_orientation(gtk.ORIENTATION_VERTICAL) toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_size_request(-1, 50) tool_bar_pos=0 save = gtk.ToolButton(gtk.STOCK_SAVE) tooltips.set_tip(save, "Save image") save.connect("clicked", self.callback_save) toolbar.insert(save, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 hide_key = gtk.ToolButton(gtk.STOCK_INFO) tooltips.set_tip(hide_key, "Hide key") hide_key.connect("clicked", self.callback_hide_key) toolbar.insert(hide_key, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 image = gtk.Image() image.set_from_file(os.path.join(get_image_file_path(),"play.png")) save = gtk.ToolButton(image) tooltips.set_tip(save, "Run simulation") save.connect("clicked", self.run_simulation) toolbar.insert(save, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 plot_toolbar = NavigationToolbar(canvas, self) plot_toolbar.show() box=gtk.HBox(True, 1) box.set_size_request(500,-1) box.show() box.pack_start(plot_toolbar, True, True, 0) tb_comboitem = gtk.ToolItem(); tb_comboitem.add(box); tb_comboitem.show() toolbar.insert(tb_comboitem, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 sep = gtk.SeparatorToolItem() sep.set_draw(False) sep.set_expand(True) toolbar.insert(sep, tool_bar_pos) sep.show() tool_bar_pos=tool_bar_pos+1 help = gtk.ToolButton(gtk.STOCK_HELP) toolbar.insert(help, tool_bar_pos) help.connect("clicked", self.callback_help) help.show() tool_bar_pos=tool_bar_pos+1 toolbar.show_all() window_main_vbox=gtk.VBox() window_main_vbox.pack_start(toolbar, False, True, 0) #self.attach(toolbar, 0, 1, 0, 1) tool_bar_pos=tool_bar_pos+1 self.hbox.pack_start(canvas, True, True, 0) self.emesh_editor.show() self.hbox.pack_start(self.emesh_editor, True, True, 0) self.emesh_editor.mesh_dump_ctl.connect("update", self.callback_update) window_main_vbox.add(self.hbox) self.add(window_main_vbox) self.set_title("Electrical Mesh Editor - (www.opvdm.com)") self.set_icon_from_file(os.path.join(get_image_file_path(),"mesh.png")) self.connect("delete-event", self.callback_close) self.set_position(gtk.WIN_POS_CENTER)
class MainWindow: OPTICAL_FLOW_BLOCK_WIDTH = 8 OPTICAL_FLOW_BLOCK_HEIGHT = 8 OPTICAL_FLOW_RANGE_WIDTH = 8 # Range to look outside of a block for motion OPTICAL_FLOW_RANGE_HEIGHT = 8 PROCESSED_FRAME_DIFF = 1 # Classes of pixel in GrabCut algorithm GC_BGD = 0 # background GC_FGD = 1 # foreground GC_PR_BGD = 2 # most probably background GC_PR_FGD = 3 # most probably foreground # GrabCut algorithm flags GC_INIT_WITH_RECT = 0 GC_INIT_WITH_MASK = 1 GC_EVAL = 2 #--------------------------------------------------------------------------- def __init__( self, options, bagFilename = None ): self.options = options self.scriptPath = os.path.dirname( __file__ ) self.image = None self.frameIdx = 0 self.workerThread = None self.numFramesProcessed = 0 self.graphCanvas = None self.graphNavToolbar = None self.PROCESSED_FRAME_DIFF = int( self.options.frameSkip ) # Setup the GUI builder = gtk.Builder() builder.add_from_file( self.scriptPath + "/GUI/ObjectDetectorExplorer.glade" ) self.window = builder.get_object( "winMain" ) self.comboOutput_1_Mode = builder.get_object( "comboOutput_1_Mode" ) self.comboOutput_2_Mode = builder.get_object( "comboOutput_2_Mode" ) self.vboxGraphs = builder.get_object( "vboxGraphs" ) dwgInput = builder.get_object( "dwgInput" ) dwgOutput_1 = builder.get_object( "dwgOutput_1" ) dwgOutput_2 = builder.get_object( "dwgOutput_2" ) self.dwgInputDisplay = Display( dwgInput ) self.dwgOutput_1_Display = Display( dwgOutput_1 ) self.dwgOutput_2_Display = Display( dwgOutput_2 ) self.sequenceControls = builder.get_object( "sequenceControls" ) self.sequenceControls.setNumFrames( 1 ) self.sequenceControls.setOnFrameIdxChangedCallback( self.onSequenceControlsFrameIdxChanged ) builder.connect_signals( self ) #updateLoop = self.update() #gobject.idle_add( updateLoop.next ) self.window.show() if bagFilename != None: self.tryToLoadBagFile( bagFilename ) #--------------------------------------------------------------------------- def onWinMainDestroy( self, widget, data = None ): gtk.main_quit() #--------------------------------------------------------------------------- def main( self ): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.gdk.threads_init() gtk.main() #--------------------------------------------------------------------------- def isCurFrameReady( self ): return self.frameIdx < self.numFramesProcessed #--------------------------------------------------------------------------- def setFrameIdx( self, frameIdx ): frameReady = frameIdx < self.numFramesProcessed if frameReady or frameIdx == 0: self.frameIdx = frameIdx self.updateDisplay() else: # Try to reset to current frame index if self.isCurFrameReady(): self.sequenceControls.setFrameIdx( self.frameIdx ) else: self.sequenceControls.setFrameIdx( 0 ) #--------------------------------------------------------------------------- def updateDisplay( self ): if self.isCurFrameReady(): self.dwgInputDisplay.setImageFromOpenCVMatrix( self.inputImageList[ self.frameIdx ] ) output_1_Mode = self.comboOutput_1_Mode.get_active_text() if output_1_Mode == OutputMode.OPTICAL_FLOW: self.dwgOutput_1_Display.setImageFromOpenCVMatrix( self.inputImageList[ self.frameIdx ] ) elif output_1_Mode == OutputMode.DETECTED_MOTION: self.dwgOutput_1_Display.setImageFromNumpyArray( self.motionImageList[ self.frameIdx ] ) elif output_1_Mode == OutputMode.SEGMENTATION: self.dwgOutput_1_Display.setImageFromNumpyArray( self.segmentationList[ self.frameIdx ] ) elif output_1_Mode == OutputMode.SALIENCY: self.dwgOutput_1_Display.setImageFromNumpyArray( self.saliencyMapList[ self.frameIdx ] ) elif output_1_Mode == OutputMode.SEGMENTATION_MASK: self.dwgOutput_1_Display.setImageFromNumpyArray( self.segmentationMaskList[ self.frameIdx ] ) output_2_Mode = self.comboOutput_2_Mode.get_active_text() if output_2_Mode == OutputMode.OPTICAL_FLOW: self.dwgOutput_2_Display.setImageFromOpenCVMatrix( self.inputImageList[ self.frameIdx ] ) elif output_2_Mode == OutputMode.DETECTED_MOTION: self.dwgOutput_2_Display.setImageFromNumpyArray( self.motionImageList[ self.frameIdx ] ) elif output_2_Mode == OutputMode.SEGMENTATION: diffImage = np.array( self.motionImageList[ self.frameIdx ], dtype=np.int32 ) \ - np.array( self.imageFlowList[ self.frameIdx ][ 3 ], dtype=np.int32 ) diffImage = np.array( np.maximum( diffImage, 0 ), dtype=np.uint8 ) #self.dwgOutput_2_Display.setImageFromNumpyArray( diffImage ) self.dwgOutput_2_Display.setImageFromNumpyArray( self.segmentationList[ self.frameIdx ] ) elif output_2_Mode == OutputMode.SALIENCY: self.dwgOutput_2_Display.setImageFromNumpyArray( self.saliencyMapList[ self.frameIdx ] ) elif output_2_Mode == OutputMode.SEGMENTATION_MASK: self.dwgOutput_2_Display.setImageFromNumpyArray( self.segmentationMaskList[ self.frameIdx ] ) #--------------------------------------------------------------------------- def chooseBagFile( self ): result = None dialog = gtk.FileChooserDialog( title="Choose Bag File", action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) ) dialog.set_current_folder( self.scriptPath + "/../../test_data/bags" ) filter = gtk.FileFilter() filter.add_pattern( "*.bag" ) filter.set_name( "Bag Files" ) dialog.add_filter( filter ) dialog.set_filter( filter ) result = dialog.run() if result == gtk.RESPONSE_ACCEPT: result = dialog.get_filename() dialog.destroy() return result #--------------------------------------------------------------------------- def onMenuItemOpenBagActivate( self, widget ): bagFilename = self.chooseBagFile() if bagFilename != None: self.tryToLoadBagFile( bagFilename ) #--------------------------------------------------------------------------- def onMenuItemQuitActivate( self, widget ): self.onWinMainDestroy( widget ) #--------------------------------------------------------------------------- def onSequenceControlsFrameIdxChanged( self, widget ): self.setFrameIdx( widget.frameIdx ) #--------------------------------------------------------------------------- def onComboOutput_1_ModeChanged( self, widget ): self.updateDisplay() #--------------------------------------------------------------------------- def onComboOutput_2_ModeChanged( self, widget ): self.updateDisplay() #--------------------------------------------------------------------------- def onDwgInputExposeEvent( self, widget, data ): self.dwgInputDisplay.drawPixBufToDrawingArea( data.area ) #--------------------------------------------------------------------------- def onDwgOutput_1_ExposeEvent( self, widget, data = None ): imgRect = self.dwgOutput_1_Display.drawPixBufToDrawingArea( data.area ) if imgRect != None: imgRect = imgRect.intersect( data.area ) outputMode = self.comboOutput_1_Mode.get_active_text() self.drawOutputOverlay( widget, imgRect, outputMode ) #--------------------------------------------------------------------------- def onDwgOutput_2_ExposeEvent( self, widget, data = None ): imgRect = self.dwgOutput_2_Display.drawPixBufToDrawingArea( data.area ) if imgRect != None: imgRect = imgRect.intersect( data.area ) outputMode = self.comboOutput_2_Mode.get_active_text() self.drawOutputOverlay( widget, imgRect, outputMode ) #--------------------------------------------------------------------------- def drawOutputOverlay( self, widget, imgRect, outputMode ): if outputMode == OutputMode.OPTICAL_FLOW: # Draw the optical flow if it's available opticalFlowX = self.opticalFlowListX[ self.frameIdx ] opticalFlowY = self.opticalFlowListY[ self.frameIdx ] if opticalFlowX != None and opticalFlowY != None: graphicsContext = widget.window.new_gc() graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 65535, 0 ) ) blockCentreY = imgRect.y + self.OPTICAL_FLOW_BLOCK_HEIGHT / 2 for y in range( opticalFlowX.shape[ 0 ] ): blockCentreX = imgRect.x + self.OPTICAL_FLOW_BLOCK_WIDTH / 2 for x in range( opticalFlowX.shape[ 1 ] ): endX = blockCentreX + opticalFlowX[ y, x ] endY = blockCentreY + opticalFlowY[ y, x ] if endY < blockCentreY: # Up is red graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 65535, 0, 0 ) ) elif endY > blockCentreY: # Down is blue graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 0, 65535 ) ) else: # Static is green graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 65535, 0 ) ) widget.window.draw_line( graphicsContext, int( blockCentreX ), int( blockCentreY ), int( endX ), int( endY ) ) blockCentreX += self.OPTICAL_FLOW_BLOCK_WIDTH blockCentreY += self.OPTICAL_FLOW_BLOCK_HEIGHT elif outputMode == OutputMode.SALIENCY: graphicsContext = widget.window.new_gc() graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 65535, 0 ) ) for cluster in self.saliencyClusterList[ self.frameIdx ]: mean = cluster[ 0 ] stdDev = cluster[ 1 ] arcX = int( imgRect.x + mean[ 0 ] ) arcY = int( imgRect.y + mean[ 1 ] ) # Draw a circle to represent the cluster arcWidth = arcHeight = int( stdDev * 2 ) drawFilledArc = False widget.window.draw_arc( graphicsContext, drawFilledArc, arcX, arcY, arcWidth, arcHeight, 0, 360 * 64 ) #--------------------------------------------------------------------------- def tryToLoadBagFile( self, bagFilename ): # Locate and open file try: bag = rosbag.Bag( bagFilename ) except: print "Error: Unable to load", bagFilename return # Count the number of frames in the bag file numFrames = 0 for topic, msg, t in bag.read_messages(): if msg._type == "sensor_msgs/Image": numFrames += 1 if numFrames == 0: print "Error: No frames in bag file" return numFrames = int( math.ceil( float( numFrames )/int( self.PROCESSED_FRAME_DIFF ) ) ) # Throw away existing data and prepare to process the bag file if self.workerThread != None and self.workerThread.is_alive(): self.workCancelled = True self.workerThread.join() self.inputImageList = [ None for i in range( numFrames ) ] self.grayScaleImageList = [ None for i in range( numFrames ) ] self.motionImageList = [ None for i in range( numFrames ) ] self.opticalFlowListX = [ None for i in range( numFrames ) ] self.opticalFlowListY = [ None for i in range( numFrames ) ] self.segmentationList = [ None for i in range( numFrames ) ] self.segmentationMaskList = [ None for i in range( numFrames ) ] self.imageFlowList = [ ( 0, 0, 0, None ) for i in range( numFrames ) ] self.maxMotionCounts = [ 0 for i in range( numFrames ) ] self.leftMostMotionList = [ 0 for i in range( numFrames ) ] self.saliencyMapList = [ None for i in range( numFrames ) ] self.saliencyClusterList = [ [] for i in range( numFrames ) ] self.numFramesProcessed = 0 # Kick off worker thread to process the bag file self.workCancelled = False self.workerThread = threading.Thread( target=self.processBag, args=( bag, ) ) self.workerThread.daemon = True self.workerThread.start() self.sequenceControls.setNumFrames( numFrames ) #--------------------------------------------------------------------------- def produceSegmentation( self, startFrame, impactMotionImage, preMotionImages, postMotionImages ): ROI_X = 0 ROI_Y = 76 ROI_WIDTH = 230 ROI_HEIGHT = 100 blankFrame = np.zeros( ( startFrame.height, startFrame.width ), dtype=np.uint8 ) imageFlowFilter = ImageFlowFilter() # Create the accumulator image accumulatorArray = np.copy( impactMotionImage ).astype( np.int32 ) # Take maximum values from motion images after the impact but # don't add them in to de-emphasise the manipulator imageNum = 1 for postMotionImage in postMotionImages: print "Aligning post impact image {0}...".format( imageNum ) imageNum += 1 ( transX, transY, rotationAngle, alignedImage ) = \ imageFlowFilter.calcImageFlow( impactMotionImage, postMotionImage ) accumulatorArray = np.maximum( accumulatorArray, alignedImage ) # Dilate and subtract motion images from before the impact imageNum = 1 for preMotionImage in preMotionImages: print "Aligning pre impact image {0}...".format( imageNum ) imageNum += 1 ( transX, transY, rotationAngle, alignedImage ) = \ imageFlowFilter.calcImageFlow( impactMotionImage, preMotionImage ) cv.Dilate( alignedImage, alignedImage ) cv.Dilate( alignedImage, alignedImage ) cv.Dilate( alignedImage, alignedImage ) accumulatorArray = accumulatorArray - alignedImage accumulatorImage = np.clip( accumulatorArray, 0, 255 ).astype( np.uint8 ) # Create the segmentation mask from the accumulator image startMask = np.copy( accumulatorImage ) cv.Dilate( startMask, startMask ) cv.Erode( startMask, startMask ) cv.Dilate( startMask, startMask ) cv.Erode( startMask, startMask ) startMask = scipy.ndimage.filters.gaussian_filter( startMask, 5.0, mode='constant' ) startMask[ startMask > 0 ] = 255 # Find the larget blob in the ROI # Label blobs startMask, numBlobs = PyBlobLib.labelBlobs( startMask ) # Find blobs in the region of interest testMap = np.copy( startMask ) testMap[ :ROI_Y, : ] = 0 # Mask out area above the ROI testMap[ :, :ROI_X ] = 0 # Mask out area to the left of the ROI testMap[ ROI_Y+ROI_HEIGHT: ] = 0 # Mask out area below the ROI testMap[ :, ROI_X+ROI_WIDTH: ] = 0 # Mask out area to the right of the ROI biggestBlobIdx = None biggestBlobSize = 0 for blobIdx in range( 1, numBlobs + 1 ): if testMap[ testMap == blobIdx ].size > 0: blobSize = startMask[ startMask == blobIdx ].size if blobSize > biggestBlobSize: biggestBlobSize = blobSize biggestBlobIdx = blobIdx # Isolate the largest blob if biggestBlobIdx != None: biggestBlobPixels = (startMask == biggestBlobIdx) startMask[ biggestBlobPixels ] = 255 startMask[ biggestBlobPixels == False ] = 0 else: print "No central blob" return blankFrame # Now expand it to get exclusion mask exclusionMask = np.copy( startMask ) for i in range( 10 ): cv.Dilate( exclusionMask, exclusionMask ) cv.Erode( exclusionMask, exclusionMask ) cv.Erode( exclusionMask, exclusionMask ) #---------------------------------------------------- maskArray = np.copy( startMask ) possiblyForeground = ( maskArray > 0 ) & ( accumulatorImage > 0 ) maskArray[ possiblyForeground ] = self.GC_PR_FGD maskArray[ possiblyForeground == False ] = self.GC_PR_BGD maskArray[ exclusionMask == 0 ] = self.GC_BGD definiteMask = np.copy( accumulatorImage ) definiteMask[ possiblyForeground ] = 255 definiteMask[ possiblyForeground == False ] = 0 cv.Erode( definiteMask, definiteMask ) cv.Erode( definiteMask, definiteMask ) maskArray[ definiteMask == 255 ] = self.GC_FGD # Now create the working mask and segment the image workingMask = np.copy( maskArray ) fgModel = cv.CreateMat( 1, 5*13, cv.CV_64FC1 ) cv.Set( fgModel, 0 ) bgModel = cv.CreateMat( 1, 5*13, cv.CV_64FC1 ) cv.Set( bgModel, 0 ) workingImage = np.copy( startFrame ) cv.GrabCut( workingImage, workingMask, (0,0,0,0), fgModel, bgModel, 6, self.GC_INIT_WITH_MASK ) cv.Set( fgModel, 0 ) cv.Set( bgModel, 0 ) bgdPixels = (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) workingMask[ bgdPixels ] = 0 workingMask[ bgdPixels == False ] = 255 cv.Erode( workingMask, workingMask ) bgdPixels = workingMask == 0 workingMask[ bgdPixels ] = self.GC_PR_BGD workingMask[ bgdPixels == False ] = self.GC_PR_FGD workingMask[ exclusionMask == 0 ] = self.GC_BGD cv.GrabCut( workingImage, workingMask, (0,0,0,0), fgModel, bgModel, 6, self.GC_INIT_WITH_MASK ) segmentation = np.copy( startFrame ) segmentation[ (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) ] = 0 # Remove everything apart from the biggest blob in the ROI graySeg = np.zeros( ( startFrame.height, startFrame.width ), dtype=np.uint8 ) cv.CvtColor( segmentation, graySeg, cv.CV_RGB2GRAY ) startMask = np.copy( graySeg ) startMask[ startMask > 0 ] = 255 # Find the larget blob in the ROI # Label blobs startMask, numBlobs = PyBlobLib.labelBlobs( startMask ) # Find blobs in the region of interest testMap = np.copy( startMask ) testMap[ :ROI_Y, : ] = 0 # Mask out area above the ROI testMap[ :, :ROI_X ] = 0 # Mask out area to the left of the ROI testMap[ ROI_Y+ROI_HEIGHT: ] = 0 # Mask out area below the ROI testMap[ :, ROI_X+ROI_WIDTH: ] = 0 # Mask out area to the right of the ROI biggestBlobIdx = None biggestBlobSize = 0 for blobIdx in range( 1, numBlobs + 1 ): if testMap[ testMap == blobIdx ].size > 0: blobSize = startMask[ startMask == blobIdx ].size if blobSize > biggestBlobSize: biggestBlobSize = blobSize biggestBlobIdx = blobIdx # Isolate the largest blob if biggestBlobIdx != None: biggestBlobPixels = (startMask == biggestBlobIdx) segmentation[ biggestBlobPixels == False, 0 ] = 255 segmentation[ biggestBlobPixels == False, 1 ] = 0 segmentation[ biggestBlobPixels == False, 2 ] = 255 else: print "No central blob after main segmentation" return blankFrame return segmentation #--------------------------------------------------------------------------- def processBag( self, bag ): FLIP_IMAGE = bool( self.options.frameFlip == "True" ) USING_OPTICAL_FLOW_FOR_MOTION = False print "frameFlip = ", FLIP_IMAGE bagFrameIdx = 0 frameIdx = 0 impactFrameIdx = None # Setup filters opticalFlowFilter = OpticalFlowFilter( self.OPTICAL_FLOW_BLOCK_WIDTH, self.OPTICAL_FLOW_BLOCK_HEIGHT, self.OPTICAL_FLOW_RANGE_WIDTH, self.OPTICAL_FLOW_RANGE_HEIGHT ) motionDetectionFilter = MotionDetectionFilter() imageFlowFilter = ImageFlowFilter() residualSaliencyFilter = ResidualSaliencyFilter() # Process bag file for topic, msg, t in bag.read_messages(): if self.workCancelled: # We've been given the signal to quit break if msg._type == "sensor_msgs/Image": bagFrameIdx += 1 if (bagFrameIdx-1)%self.PROCESSED_FRAME_DIFF != 0: continue print "Processing image", frameIdx # Get input image image = cv.CreateMatHeader( msg.height, msg.width, cv.CV_8UC3 ) cv.SetData( image, msg.data, msg.step ) if FLIP_IMAGE: cv.Flip( image, None, 1 ) # Convert to grayscale grayImage = cv.CreateMat( msg.height, msg.width, cv.CV_8UC1 ) cv.CvtColor( image, grayImage, cv.CV_BGR2GRAY ) grayImageNumpPy = np.array( grayImage ) # Calculate optical flow opticalFlowArrayX, opticalFlowArrayY = \ opticalFlowFilter.calcOpticalFlow( grayImage ) # Detect motion if USING_OPTICAL_FLOW_FOR_MOTION: if frameIdx == 0: motionImage = PyVarFlowLib.createMotionMask( grayImageNumpPy, grayImageNumpPy ) else: motionImage = PyVarFlowLib.createMotionMask( np.array( self.grayScaleImageList[ frameIdx - 1 ] ), grayImageNumpPy ) else: motionImage = motionDetectionFilter.calcMotion( grayImage ) # Work out the left most point in the image where motion appears motionTest = np.copy( motionImage ) cv.Erode( motionTest, motionTest ) if frameIdx == 0: leftMostMotion = motionImage.shape[ 1 ] else: leftMostMotion = self.leftMostMotionList[ frameIdx - 1 ] leftMostMotionDiff = 0 for i in range( leftMostMotion ): if motionTest[ :, i ].max() > 0: leftMostMotionDiff = abs( leftMostMotion - i ) leftMostMotion = i break segmentationMask = np.zeros( ( msg.height, msg.width ), dtype=np.uint8 ) FRAMES_BACK = 3 if impactFrameIdx == None: if leftMostMotionDiff > 18 and leftMostMotion < 0.75*msg.width: # Found impact frame impactFrameIdx = frameIdx else: PROCESS_IMPACT = False if PROCESS_IMPACT and frameIdx - impactFrameIdx == FRAMES_BACK: # Should now have enough info to segment object impactMotionImage = self.motionImageList[ impactFrameIdx ] print "Aligning" postImpactRealFarFlow = imageFlowFilter.calcImageFlow( impactMotionImage, motionImage ) print "Aligning" postImpactFarFlow = imageFlowFilter.calcImageFlow( impactMotionImage, self.motionImageList[ impactFrameIdx + 2 ] ) print "Aligning" postImpactNearFlow = imageFlowFilter.calcImageFlow( impactMotionImage, self.motionImageList[ impactFrameIdx + 1 ] ) segmentationMask = np.maximum( np.maximum( np.maximum( impactMotionImage, postImpactNearFlow[ 3 ] ), postImpactFarFlow[ 3 ] ), postImpactRealFarFlow[ 3 ] ) cv.Dilate( segmentationMask, segmentationMask ) print "Aligning" preImpactRealFarFlow = imageFlowFilter.calcImageFlow( impactMotionImage, self.motionImageList[ impactFrameIdx - 8 ] ) print "Aligning" preImpactFarFlow = imageFlowFilter.calcImageFlow( impactMotionImage, self.motionImageList[ impactFrameIdx - 6 ] ) print "Aligning" preImpactNearFlow = imageFlowFilter.calcImageFlow( impactMotionImage, self.motionImageList[ impactFrameIdx - 4 ] ) subMask = np.maximum( np.maximum( preImpactRealFarFlow[ 3 ], preImpactFarFlow[ 3 ] ), preImpactNearFlow[ 3 ] ) cv.Erode( subMask, subMask ) cv.Dilate( subMask, subMask ) cv.Dilate( subMask, subMask ) cv.Dilate( subMask, subMask ) subMask[ subMask > 0 ] = 255 diffImage = segmentationMask.astype( np.int32 ) - subMask.astype( np.int32 ) diffImage[ diffImage < 0 ] = 0 diffImage = diffImage.astype( np.uint8 ) cv.Erode( diffImage, diffImage ) #diffImage[ diffImage > 0 ] = 255 #segmentationMask = subMask segmentationMask = diffImage #segmentationMask = np.where( diffImage > 128, 255, 0 ).astype( np.uint8 ) # Calculate image flow #imageFlow = imageFlowFilter.calcImageFlow( motionImage ) ## Calculate saliency map #saliencyMap, largeSaliencyMap = residualSaliencyFilter.calcSaliencyMap( grayImageNumpPy ) #blobMap = np.where( largeSaliencyMap > 128, 255, 0 ).astype( np.uint8 ) #blobMap, numBlobs = PyBlobLib.labelBlobs( blobMap ) #print "found", numBlobs, "blobs" #largeSaliencyMap = np.where( largeSaliencyMap > 128, 255, 0 ).astype( np.uint8 ) # Threshold the saliency map #largeSaliencyMap = (largeSaliencyMap > 128).astype(np.uint8) * 255 #cv.AdaptiveThreshold( largeSaliencyMap, largeSaliencyMap, 255 ) # Detect clusters within the saliency map #NUM_CLUSTERS = 5 #numSamples = np.sum( saliencyMap ) #sampleList = np.ndarray( ( numSamples, 2 ), dtype=np.float32 ) #sampleListIdx = 0 #for y in range( saliencyMap.shape[ 0 ] ): #for x in range( saliencyMap.shape[ 1 ] ): #numNewSamples = saliencyMap[ y, x ] #if numNewSamples > 0: #sampleList[ sampleListIdx:sampleListIdx+numNewSamples, 0 ] = x #sampleList[ sampleListIdx:sampleListIdx+numNewSamples, 1 ] = y #sampleListIdx += numNewSamples #sampleList[ 0:numSamples/2 ] = ( 20, 20 ) #sampleList[ numSamples/2: ] = ( 200, 200 ) #labelList = np.ndarray( ( numSamples, 1 ), dtype=np.int32 ) #cv.KMeans2( sampleList, NUM_CLUSTERS, labelList, #(cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 10, 0.01) ) #saliencyScaleX = float( largeSaliencyMap.shape[ 1 ] ) / saliencyMap.shape[ 1 ] #saliencyScaleY = float( largeSaliencyMap.shape[ 0 ] ) / saliencyMap.shape[ 0 ] clusterList = [] #for clusterIdx in range( NUM_CLUSTERS ): #clusterSamples = sampleList[ #np.where( labelList == clusterIdx )[ 0 ], : ] #if clusterSamples.size <= 0: #mean = ( 0.0, 0.0 ) #stdDev = 0.0 #else: #mean = clusterSamples.mean( axis=0 ) #mean = ( mean[ 0 ]*saliencyScaleX, mean[ 1 ]*saliencyScaleY ) #stdDev = clusterSamples.std()*saliencyScaleX #clusterList.append( ( mean, stdDev ) ) # Work out the maximum amount of motion we've seen in a single frame so far #motionCount = motionImage[ motionImage > 0 ].size #if frameIdx == 0: #lastMotionCount = 0 #else: #lastMotionCount = self.maxMotionCounts[ frameIdx - 1 ] #if motionCount < lastMotionCount: #motionCount = lastMotionCount ## Work out diffImage #diffImage = np.array( motionImage, dtype=np.int32 ) \ #- np.array( imageFlow[ 3 ], dtype=np.int32 ) #diffImage = np.array( np.maximum( diffImage, 0 ), dtype=np.uint8 ) # Segment the image #workingMask = np.copy( motionImage ) #workingMask = np.copy( diffImage ) workingMask = np.copy( segmentationMask ) kernel = cv.CreateStructuringElementEx( cols=3, rows=3, anchorX=1, anchorY=1, shape=cv.CV_SHAPE_CROSS ) cv.Erode( workingMask, workingMask, kernel ) cv.Dilate( workingMask, workingMask ) extraExtraMask = np.copy( workingMask ) cv.Dilate( extraExtraMask, extraExtraMask ) cv.Dilate( extraExtraMask, extraExtraMask ) cv.Dilate( extraExtraMask, extraExtraMask ) cv.Dilate( extraExtraMask, extraExtraMask ) cv.Dilate( extraExtraMask, extraExtraMask ) cv.Dilate( extraExtraMask, extraExtraMask ) allMask = np.copy( extraExtraMask ) cv.Dilate( allMask, allMask ) cv.Dilate( allMask, allMask ) cv.Dilate( allMask, allMask ) cv.Dilate( allMask, allMask ) cv.Dilate( allMask, allMask ) cv.Dilate( allMask, allMask ) possibleForeground = workingMask > 0 if workingMask[ possibleForeground ].size >= 100 \ and frameIdx >= 16: print "Msk size", workingMask[ possibleForeground ].size print workingMask[ 0, 0:10 ] fgModel = cv.CreateMat( 1, 5*13, cv.CV_64FC1 ) bgModel = cv.CreateMat( 1, 5*13, cv.CV_64FC1 ) #workingMask[ possibleForeground ] = self.GC_FGD #workingMask[ possibleForeground == False ] = self.GC_PR_BGD #workingMask[ : ] = self.GC_PR_BGD #workingMask[ possibleForeground ] = self.GC_FGD workingMask[ : ] = self.GC_BGD workingMask[ allMask > 0 ] = self.GC_PR_BGD workingMask[ extraExtraMask > 0 ] = self.GC_PR_FGD workingMask[ possibleForeground ] = self.GC_FGD if frameIdx == 16: # Save mask maskCopy = np.copy( workingMask ) maskCopy[ maskCopy == self.GC_BGD ] = 0 maskCopy[ maskCopy == self.GC_PR_BGD ] = 64 maskCopy[ maskCopy == self.GC_PR_FGD ] = 128 maskCopy[ maskCopy == self.GC_FGD ] = 255 print "Unused pixels", \ maskCopy[ (maskCopy != 255) & (maskCopy != 0) ].size outputImage = cv.CreateMat( msg.height, msg.width, cv.CV_8UC3 ) cv.CvtColor( maskCopy, outputImage, cv.CV_GRAY2BGR ) cv.SaveImage( "output.png", image ); cv.SaveImage( "outputMask.png", outputImage ); print "Saved images" #return #print "Set Msk size", workingMask[ workingMask == self.GC_PR_FGD ].size imageToSegment = image #self.inputImageList[ frameIdx - FRAMES_BACK ] imageCopy = np.copy( imageToSegment ) cv.CvtColor( imageCopy, imageCopy, cv.CV_BGR2RGB ) print "Start seg" cv.GrabCut( imageCopy, workingMask, (0,0,0,0), fgModel, bgModel, 12, self.GC_INIT_WITH_MASK ) print "Finish seg" segmentation = np.copy( imageToSegment ) segmentation[ (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) ] = 0 black = (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) #motionImage = np.where( black, 0, 255 ).astype( np.uint8 ) # Refine the segmentation REFINE_SEG = False if REFINE_SEG: motionImageCopy = np.copy( motionImage ) cv.Erode( motionImageCopy, motionImageCopy ) #cv.Erode( motionImageCopy, motionImageCopy ) #cv.Erode( motionImageCopy, motionImageCopy ) workingMask[ motionImageCopy > 0 ] = self.GC_PR_FGD workingMask[ motionImageCopy == 0 ] = self.GC_PR_BGD cv.Dilate( motionImageCopy, motionImageCopy ) cv.Dilate( motionImageCopy, motionImageCopy ) cv.Dilate( motionImageCopy, motionImageCopy ) cv.Dilate( motionImageCopy, motionImageCopy ) workingMask[ motionImageCopy == 0 ] = self.GC_BGD print "Other seg" cv.GrabCut( imageCopy, workingMask, (0,0,0,0), fgModel, bgModel, 12, self.GC_INIT_WITH_MASK ) print "Other seg done" segmentation = np.copy( imageToSegment ) segmentation[ (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) ] = 0 black = (workingMask != self.GC_PR_FGD) & (workingMask != self.GC_FGD) motionImage = np.where( black, 0, 255 ).astype( np.uint8 ) else: segmentation = np.zeros( ( image.height, image.width ), dtype=np.uint8 ) # Save output data self.inputImageList[ frameIdx ] = image self.grayScaleImageList[ frameIdx ] = grayImage self.opticalFlowListX[ frameIdx ] = opticalFlowArrayX self.opticalFlowListY[ frameIdx ] = opticalFlowArrayY self.motionImageList[ frameIdx ] = motionImage self.segmentationList[ frameIdx ] = segmentation self.segmentationMaskList[ frameIdx ] = segmentationMask #self.maxMotionCounts[ frameIdx ] = motionCount #self.imageFlowList[ frameIdx ] = imageFlow #self.saliencyMapList[ frameIdx ] = largeSaliencyMap #self.saliencyClusterList[ frameIdx ] = clusterList self.leftMostMotionList[ frameIdx ] = leftMostMotion frameIdx += 1 self.numFramesProcessed += 1 if not self.workCancelled: SAVE_MOTION_IMAGES = True BASE_MOTION_IMAGE_NAME = self.scriptPath + "/../../test_data/motion_images/motion_{0:03}.png" if SAVE_MOTION_IMAGES and len( self.motionImageList ) > 0: width = self.motionImageList[ 0 ].shape[ 1 ] height = self.motionImageList[ 0 ].shape[ 0 ] colourImage = np.zeros( ( height, width, 3 ), dtype=np.uint8 ) for frameIdx, motionImage in enumerate( self.motionImageList ): colourImage[ :, :, 0 ] = motionImage colourImage[ :, :, 1 ] = motionImage colourImage[ :, :, 2 ] = motionImage outputName = BASE_MOTION_IMAGE_NAME.format( frameIdx + 1 ) cv.SaveImage( outputName, colourImage ) # Recalculate impactFrameIdx width = self.motionImageList[ 0 ].shape[ 1 ] totalMotionDiff = 0 maxMotionDiff = 0 impactFrameIdx = None for motionIdx in range( 1, len( self.leftMostMotionList ) ): motionDiff = abs( self.leftMostMotionList[ motionIdx ] \ - self.leftMostMotionList[ motionIdx - 1 ] ) totalMotionDiff += motionDiff if motionDiff > maxMotionDiff and totalMotionDiff > 0.5*width: maxMotionDiff = motionDiff impactFrameIdx = motionIdx if maxMotionDiff <= 18: impactFrameIdx = None if impactFrameIdx != None: preMotionImages = [] postMotionImages = [] impactMotionImage = None NUM_FRAMES_BEFORE = 3 prefix = self.options.outputPrefix if prefix != "": prefix += "_" BASE_MOTION_IMAGE_NAME = self.scriptPath + "/../../test_data/impact_images/" + prefix + "motion_{0:03}.png" START_MOTION_IMAGE_NAME = self.scriptPath + "/../../test_data/impact_images/" + prefix + "start_motion.png" START_IMAGE_NAME = self.scriptPath + "/../../test_data/impact_images/" + prefix + "start.png" IMPACT_IMAGE_NAME = self.scriptPath + "/../../test_data/impact_images/" + prefix + "impact.png" SEGMENTATION_IMAGE_NAME = self.scriptPath + "/../../test_data/impact_images/" + prefix + "segmentation.png" NUM_FRAMES_AFTER = 3 width = self.motionImageList[ 0 ].shape[ 1 ] height = self.motionImageList[ 0 ].shape[ 0 ] colourImage = np.zeros( ( height, width, 3 ), dtype=np.uint8 ) for frameIdx in range( impactFrameIdx - NUM_FRAMES_BEFORE, impactFrameIdx + NUM_FRAMES_AFTER + 1 ): motionImage = self.motionImageList[ frameIdx ] if frameIdx < impactFrameIdx: preMotionImages.append( motionImage ) elif frameIdx == impactFrameIdx: impactMotionImage = motionImage else: # frameIdx > impactFrameIdx postMotionImages.append( motionImage ) colourImage[ :, :, 0 ] = motionImage colourImage[ :, :, 1 ] = motionImage colourImage[ :, :, 2 ] = motionImage outputName = BASE_MOTION_IMAGE_NAME.format( frameIdx - impactFrameIdx ) cv.SaveImage( outputName, colourImage ) motionDetectionFilter.calcMotion( self.grayScaleImageList[ 0 ] ) startMotionImage = motionDetectionFilter.calcMotion( self.grayScaleImageList[ impactFrameIdx ] ) colourImage[ :, :, 0 ] = startMotionImage colourImage[ :, :, 1 ] = startMotionImage colourImage[ :, :, 2 ] = startMotionImage cv.SaveImage( START_MOTION_IMAGE_NAME, colourImage ) cv.CvtColor( self.inputImageList[ 0 ], colourImage, cv.CV_RGB2BGR ) cv.SaveImage( START_IMAGE_NAME, colourImage ) cv.CvtColor( self.inputImageList[ impactFrameIdx ], colourImage, cv.CV_RGB2BGR ) cv.SaveImage( IMPACT_IMAGE_NAME, colourImage ) print "Segmenting..." segmentation = self.produceSegmentation( self.inputImageList[ 0 ], impactMotionImage, preMotionImages, postMotionImages ) cv.CvtColor( segmentation, colourImage, cv.CV_RGB2BGR ) cv.SaveImage( SEGMENTATION_IMAGE_NAME, colourImage ) self.refreshGraphDisplay() print "Finished processing bag file" if bool( self.options.quitAfterFirstSegmentation == "True" ): print "Trying to quit" self.onWinMainDestroy( None ) else: print "Not trying to quit so neeah" #--------------------------------------------------------------------------- def refreshGraphDisplay( self ): # Remove existing graph items if self.graphCanvas != None: self.vboxGraphs.remove( self.graphCanvas ) self.graphCanvas.destroy() self.graphCanvas = None if self.graphNavToolbar != None: self.vboxGraphs.remove( self.graphNavToolbar ) self.graphNavToolbar.destroy() self.graphNavToolbar = None # Draw the graphs self.graphFigure = Figure( figsize=(8,6), dpi=72 ) self.graphAxis = self.graphFigure.add_subplot( 111 ) #self.graphAxis.plot( range( 1, len( self.maxMotionCounts )+1 ), self.maxMotionCounts ) diffs = [ 0 ] + [ self.leftMostMotionList[ i+1 ] - self.leftMostMotionList[ i ] for i in range( len( self.leftMostMotionList ) - 1 ) ] #self.graphAxis.plot( range( 1, len( self.leftMostMotionList )+1 ), self.leftMostMotionList ) self.graphAxis.plot( range( 1, len( self.leftMostMotionList )+1 ), diffs ) # Build the new graph display self.graphCanvas = FigureCanvas( self.graphFigure ) # a gtk.DrawingArea self.graphCanvas.show() self.graphNavToolbar = NavigationToolbar( self.graphCanvas, self.window ) self.graphNavToolbar.lastDir = '/var/tmp/' self.graphNavToolbar.show() # Show the graph self.vboxGraphs.pack_start( self.graphNavToolbar, expand=False, fill=False ) self.vboxGraphs.pack_start( self.graphCanvas, True, True ) self.vboxGraphs.show() self.vboxGraphs.show() #--------------------------------------------------------------------------- def update( self ): lastTime = time.clock() while 1: curTime = time.clock() #print "Processing image", framIdx yield True yield False
class DDTF(): def __init__(self): ttle1 = 'Spectrum el1' ttle2 = ' el2 - . el1' ttle3 = ' el3 - . el1' ttle4 = ' el1 - . el2' ttle5 = ' Spectrum el2' ttle6 = ' el3 - . el2' ttle7 = ' el1 - . el3' ttle8 = 'el2 - . el3' ttle9 = 'Spectrum el3' self.win = gtk.Window() self.win.set_border_width(5) self.win.resize(800, 400) vbox = gtk.VBox(spacing=3) self.win.add(vbox) vbox.show() self.fig = Figure(figsize=(7, 5), dpi=72) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.show() vbox.pack_start(self.canvas, True, True) (self.e1, self.e2, self.e3) = signal_gen.signal_gen(3, .1, .001) c = 0 for i in self.e1: print i, self.e2[c] c += 1 self.ax1 = self.fig.add_subplot(431, title=ttle1) # self.ax1.set_xlim(0,60) # self.ax1.set_ylim(0,1) self.ax2 = self.fig.add_subplot(432, title=ttle2) self.ax2.set_xlim(0, 60) self.ax2.set_ylim(0, 1) self.ax3 = self.fig.add_subplot(433, title=ttle3) self.ax3.set_xlim(0, 60) self.ax3.set_ylim(0, 1) self.ax4 = self.fig.add_subplot(434, title=ttle4) self.ax4.set_xlim(0, 60) self.ax4.set_ylim(0, 1) self.ax5 = self.fig.add_subplot(435, title=ttle5) self.ax5.set_xlim(0, 60) self.ax5.set_ylim(0, 1) self.ax6 = self.fig.add_subplot(436, title=ttle6) self.ax6.set_xlim(0, 60) self.ax6.set_ylim(0, 1) self.ax7 = self.fig.add_subplot(437, title=ttle7) self.ax7.set_xlim(0, 60) self.ax7.set_ylim(0, 1) self.ax8 = self.fig.add_subplot(438, title=ttle8) self.ax8.set_xlim(0, 60) self.ax8.set_ylim(0, 1) self.ax9 = self.fig.add_subplot(439, title=ttle9) self.ax9.set_xlim(0, 60) self.ax9.set_ylim(0, 1) self.ax10 = self.fig.add_subplot(4, 3, 10, title="el1") self.ax11 = self.fig.add_subplot(4, 3, 11, title="el2") self.ax12 = self.fig.add_subplot(4, 3, 12, title="el3") def make_wave(self, newLength, eegfreq): srate = eegfreq * 10 newLength_t = newLength * 1.0 / eegfreq # want the freq of the wave to be 4 per length in points t = np.arange(0, newLength_t, 1.0 / srate) # time axis in seconds modifier = 7.0 / newLength_t freq_array = np.arange(modifier / 2, modifier, ((modifier) / (newLength * 2)) / 10) # if len(freq_array) > len(t): # freq_array=freq_array[0,len(t)] print t, np.pi, freq_array wave = np.cos(2.0 * np.pi * freq_array * t) print wave self.ax1.plot(t, wave) self.ax10.plot(self.e1) self.ax11.plot(self.e2) self.ax12.plot(self.e3) return wave def ddtf(self, el1, el2, el3, sample_rate=400, duration=20, step=128, increment=5): self.ax10.plot(el1) self.ax11.plot(el2) self.ax12.plot(el3) # notes: duration is the length of a window in seconds # increment is the length of a step in seconds # step is the num points in an fft-analysis epoch N = len(el1) dt = 1 / float(sample_rate) fNyq = sample_rate / 2 df = 1 / (step * dt) f = np.arange(0, fNyq, df) #Frequency axis for the FFT count = 0 end_step = N - duration * sample_rate print "end_step ", end_step print "stepping by ", increment * sample_rate for w in np.arange(0, end_step, increment * sample_rate): x = el1[w:w + duration * sample_rate] # should this be - 1 or 2? y = el2[w:w + duration * sample_rate] z = el3[w:w + duration * sample_rate] # Initialize the Cross-Spectral arrays for averaging print "step first is : ", step Sxx = np.zeros((1, step - 1)) # - 1 here? print "Sxx: ", Sxx.shape Syy = Sxx Szz = Sxx Sxy = Sxx Sxz = Sxx Syz = Sxx Szy = Sxx print "xshape : ", x.shape print "Sxx shape : ", Sxx.shape xtemp = np.arange(0, step - 1) xtemp_ones = np.ones(len(xtemp)) print "xtempshape: ", xtemp.shape A = np.vstack([xtemp, xtemp_ones]).T print "A shape: ", A.shape inner_end_step = sample_rate * duration - step print "inner_end_step ", inner_end_step print "step ", step for i in np.arange(0, inner_end_step - 1, step): m, b = np.linalg.lstsq(A, x[i:i + step - 1])[0] # the minus 1? print "m, b: ", m, b trend = m * xtemp + b # print "istep : ", (i+step-1) x[i:i + step - 1] = x[i:i + step - 1] - trend # detrend x[i:i + step - 1] = x[i:i + step - 1] - np.mean(x[i:i + step - 1]) # demean fx = np.fft.fft(x[i:i + step - 1] * np.hanning(step - 1).T) # windowed fft m, b = np.linalg.lstsq(A, y[i:i + step - 1])[0] # the minus 1? trend = m * xtemp + b y[i:i + step - 1] = y[i:i + step - 1] - trend # detrend y[i:i + step - 1] = y[i:i + step - 1] - np.mean(y[i:i + step - 1]) # demean fy = np.fft.fft(y[i:i + step - 1] * np.hanning(step - 1).T) # windowed fft m, b = np.linalg.lstsq(A, z[i:i + step - 1])[0] # the minus 1? trend = m * xtemp + b z[i:i + step - 1] = z[i:i + step - 1] - trend # detrend z[i:i + step - 1] = z[i:i + step - 1] - np.mean(z[i:i + step - 1]) # demean fz = np.fft.fft(z[i:i + step - 1] * np.hanning(step - 1).T) # windowed fft # print "fs are ", fx, fy, fz # print "fxconf ", fx.conj() # print "Sxx ", Sxx.shape, Sxx.shape # print "fxstuff ", ((fx * fx.conj())).shape Sxx = Sxx + (fx * fx.conj()) # print "Sxx2 ", Sxx.shape Syy = Syy + (fy * fy.conj()) Szz = Szz + (fz * fz.conj()) Sxy = Sxy + (fx * fy.conj()) Sxz = Sxz + (fx * fz.conj()) Syz = Syz + (fy * fz.conj()) # print "Sxx shape: ", Sxx.shape # print "Sxy shape: ", Sxy.shape # print "Szy shape: ", Sxx.shape # print "Syz shape: ", Syz.shape Syx = Sxy.conj() Szx = Sxz.conj() Szy = Syz.conj() S11 = abs(Sxx)**2 S12 = abs(Sxy)**2 S13 = abs(Sxz)**2 S21 = abs(Syx)**2 S22 = abs(Syy)**2 S23 = abs(Syz)**2 S31 = abs(Szx)**2 S32 = abs(Szy)**2 S33 = abs(Szz)**2 sumS = S11 + S12 + S13 sumS2 = S21 + S22 + S23 sumS3 = S31 + S32 + S33 NS11 = S11 / S11.max() NS12 = S12 / sumS NS13 = S13 / sumS NS21 = S21 / sumS2 NS22 = S22 / S22.max() NS23 = S23 / sumS2 NS31 = S31 / sumS3 NS32 = S32 / sumS3 NS33 = S33 / S33.max() count += 1 self.ax1.plot(f[0:step / 4], NS11[0][0:step / 4]) self.ax2.plot(f[0:step / 4], NS12[0][0:step / 4]) self.ax3.plot(f[0:step / 4], NS13[0][0:step / 4]) self.ax4.plot(f[0:step / 4], NS21[0][0:step / 4]) self.ax5.plot(f[0:step / 4], NS22[0][0:step / 4]) self.ax6.plot(f[0:step / 4], NS23[0][0:step / 4]) self.ax7.plot(f[0:step / 4], NS31[0][0:step / 4]) self.ax8.plot(f[0:step / 4], NS32[0][0:step / 4]) self.ax9.plot(f[0:step / 4], NS33[0][0:step / 4]) return (f, step, NS11, NS12, NS13, NS21, NS22, NS23, NS31, NS32, NS33)
class MetaAnalysis(InfoFrameComponent): """ Run a meta analysis and graph the results """ anaInstance = None __plotVBox = None __plotFigure = None __plotAxis = None __plotCanvas = None __plotToolbar = None __hasPlotNow = False __targetLineBox = None __targetLineEntry = None __varSelectorTable = None __varSelectorXEntry = None __varSelectorYEntry = None __filterBox = None __filterEntry = None __filterValEntry = None __runAnaButton = None __exportButton = None __clearLockdownButton = None def __init__(self, frameManager, metaAnalysis): InfoFrameComponent.__init__(self, frameManager) self.anaInstance = metaAnalysis self.baseWidget = gtk.VBox() self.__plotVBox = gtk.VBox() self.baseWidget.pack_start(self.__plotVBox, expand=True, padding=5) self.baseWidget.pack_start(gtk.HSeparator(), expand=False, padding=10) self.__targetLineBox = gtk.HBox() self.baseWidget.pack_start(self.__targetLineBox,expand=False) self.__targetLineBox.pack_start(gtk.Label("Target horizontal line = "),expand=False, padding=5) self.__targetLineEntry = gtk.Entry() self.__targetLineBox.pack_start(self.__targetLineEntry, expand=True, padding=5) self.baseWidget.pack_start(gtk.HSeparator(), expand=False, padding=10) self.__varSelectorTable = gtk.Table(1,4,True) self.__varSelectorTable.attach(gtk.Label("X variable:"), 0,1, 0,1) self.__varSelectorXEntry = gtk.Entry() self.__varSelectorTable.attach(self.__varSelectorXEntry, 1,2, 0,1) self.__varSelectorTable.attach(gtk.Label("Y variable:"), 2,3, 0,1) self.__varSelectorYEntry = gtk.Entry() self.__varSelectorTable.attach(self.__varSelectorYEntry, 3,4, 0,1) self.baseWidget.pack_start(self.__varSelectorTable, expand=False, padding=5) #self.baseWidget.pack_start(gtk.Label("Meta-language syntax: {GEOM|MESH|ANA}.key([idx]).key([idx]) ..."), expand=False, padding=5) self.baseWidget.pack_start(gtk.Label("Meta-language syntax: {GEOM|MESH|ANA}.key.key([idx]) .... For ANA, field[1] is analysis name, field[2] is a name in exportResults"), expand=False, padding=5) self.baseWidget.pack_start(gtk.HSeparator(), expand=False, padding=10) self.__filterBox = gtk.HBox() self.__filterBox.pack_start(gtk.Label("Filter: "), expand=False) self.__filterEntry = gtk.Entry() self.__filterBox.pack_start(self.__filterEntry) self.__filterBox.pack_start(gtk.Label(" = "),expand=False) self.__filterValEntry = gtk.Entry() self.__filterBox.pack_start(self.__filterValEntry) self.baseWidget.pack_start(self.__filterBox, expand=False,padding=5) self.baseWidget.pack_start(gtk.HSeparator(), expand=False, padding=10) self.__runAnaButton = gtk.Button("Run analysis") self.__runAnaButton.connect("clicked", self.event_button_runAna, None) self.baseWidget.pack_start(self.__runAnaButton, expand=False) self.__exportButton = gtk.Button("Export data") self.__exportButton.connect("clicked", self.event_button_export, None) self.baseWidget.pack_start(self.__exportButton, expand=False) self.__clearLockdownButton = gtk.Button("Clear lockdown") self.__clearLockdownButton.connect("clicked", self.event_button_clearLockdown, None) self.baseWidget.pack_start(self.__clearLockdownButton, expand=False) self.updateDisplay() self.baseWidget.show_all() def __createNewFigure(self): #Setup for plotting if self.__hasPlotNow: self.__plotVBox.remove(self.__plotToolbar) self.__plotVBox.remove(self.__plotCanvas) del self.__plotToolbar self.__plotCanvas.destroy() del self.__plotFigure self.__plotFigure = matplotlib.pyplot.figure() self.__plotAxis = self.__plotFigure.add_subplot(1,1,1) self.__plotCanvas = FigureCanvasGTKAgg(self.__plotFigure) self.__plotCanvas.show() self.__plotVBox.pack_start(self.__plotCanvas, expand=True) self.__plotToolbar = NavigationToolbar2GTKAgg(self.__plotCanvas, window=self.getBaseWindow().get_parent_window()) self.__plotVBox.pack_start(self.__plotToolbar, expand=False) self.__hasPlotNow = True #Plot the data self.__plotAxis.set_xlabel(self.anaInstance.xVariable) self.__plotAxis.set_ylabel(self.anaInstance.yVariable) self.__plotAxis.set_title("Filter: " + self.anaInstance.fVariable + " = " + str(self.anaInstance.fEquals)) matplotlib.pyplot.plot(self.anaInstance.xArray, self.anaInstance.yArray, "*") if self.anaInstance.targetValue != None: matplotlib.pyplot.axhline(self.anaInstance.targetValue, color="r", linestyle="--") (xmin,xmax,ymin,ymax) = self.__plotAxis.axis() dx = xmax-xmin; dy = ymax-ymin; self.__plotAxis.axis([xmin-dx*0.05, xmax+dx*0.05, ymin-dy*0.05, ymax+dy*0.05]) # matplotlib.pyplot.plot(np.linspace(0,2*np.pi, 100), np.sin(np.linspace(0,2*np.pi, 100))/self.counter) #TEST def updateDisplay(self): print "MetaAnalysis::updateDisplay()" self.__createNewFigure() if self.anaInstance.targetValue != None: self.__targetLineEntry.set_text(str(self.anaInstance.targetValue)) else: self.__targetLineEntry.set_text("") self.__varSelectorXEntry.set_text(self.anaInstance.xVariable) self.__varSelectorYEntry.set_text(self.anaInstance.yVariable) self.__filterEntry.set_text(self.anaInstance.fVariable) if self.anaInstance.fEquals != None: self.__filterValEntry.set_text(str(self.anaInstance.fEquals)) else: self.__filterValEntry.set_text("") if self.anaInstance.lockdown: self.__targetLineEntry.set_sensitive(False) self.__varSelectorXEntry.set_sensitive(False) self.__varSelectorYEntry.set_sensitive(False) self.__filterEntry.set_sensitive(False) self.__filterValEntry.set_sensitive(False) self.__runAnaButton.set_sensitive(False) self.__exportButton.set_sensitive(True) self.__clearLockdownButton.set_sensitive(True) else: self.__targetLineEntry.set_sensitive(True) self.__varSelectorXEntry.set_sensitive(True) self.__varSelectorYEntry.set_sensitive(True) self.__filterEntry.set_sensitive(True) self.__filterValEntry.set_sensitive(True) self.__runAnaButton.set_sensitive(True) self.__exportButton.set_sensitive(False) self.__clearLockdownButton.set_sensitive(False) def saveToAna(self): print "MetaAnalysis::saveToAna()" try: self.anaInstance.targetValue = float(self.__targetLineEntry.get_text()) except: self.anaInstance.targetValue = None self.anaInstance.xVariable = self.__varSelectorXEntry.get_text() self.anaInstance.yVariable = self.__varSelectorYEntry.get_text() self.anaInstance.fVariable = self.__filterEntry.get_text() try: self.anaInstance.fEquals = float(self.__filterValEntry.get_text()) except: self.anaInstance.fEquals = None self.anaInstance.write() def event_button_runAna(self, widget, data=None): print "MetaAnalysis::event_button_runAna()" self.saveToAna() try: self.anaInstance.runAnalysis() except AcdOptiException_metaAnalysis_anaFail as e: mDia = gtk.MessageDialog(self.getBaseWindow(), gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Analysis failed with error message:\n" + e.args[0]) mDia.run() mDia.destroy() self.updateDisplay() def event_button_export(self, widget, data=None): print "MetaAnalysis::event_button_export()" #Find the filename #call export in self.anaInstance def event_button_clearLockdown(self, widget, data=None): print "MetaAnalysis::event_button_clearLockdown()" self.anaInstance.clearLockdown() self.anaInstance.write() self.updateDisplay() def event_delete(self): print "MetaAnalysis::event_delete()" self.saveToAna() return False
class tab_bands(gtk.HBox,tab_base): lines=[] edit_list=[] line_number=[] save_file_name="" def update(self): self.enabled=inp_isfile("./lumo0.inp") def __create_model(self): # create list store model = gtk.ListStore( gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN ) # add items for item in articles: iter = model.append() model.set (iter, LUMO_FUNCTION, item[LUMO_FUNCTION], LUMO_ENABLE, item[LUMO_ENABLE], LUMO_A, item[LUMO_A], LUMO_B, item[LUMO_B], LUMO_C, item[LUMO_C], LUMO_EDITABLE, item[LUMO_EDITABLE] ) return model def __create_model_mesh(self): model_mesh = gtk.ListStore( gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN ) for item in HOMO_articles: iter = model_mesh.append() model_mesh.set (iter, HOMO_FUNCTION, item[HOMO_FUNCTION], HOMO_ENABLE, item[HOMO_ENABLE], HOMO_A, item[HOMO_A], HOMO_B, item[HOMO_B], HOMO_C, item[HOMO_C], HOMO_EDITABLE, item[HOMO_EDITABLE] ) return model_mesh def __add_columns(self, treeview): model = treeview.get_model() # Function renderer = gtk.CellRendererText() renderer.connect("edited", self.on_cell_edited, model) renderer.set_data("column", LUMO_FUNCTION) column = gtk.TreeViewColumn("Function", renderer, text=LUMO_FUNCTION, editable=LUMO_EDITABLE) treeview.append_column(column) # Enable renderer = gtk.CellRendererText() renderer.connect("edited", self.on_cell_edited, model) renderer.set_data("column", LUMO_ENABLE) column = gtk.TreeViewColumn("enabled", renderer, text=LUMO_ENABLE, editable=LUMO_EDITABLE) treeview.append_column(column) # A renderer = gtk.CellRendererText() renderer.connect("edited", self.on_cell_edited, model) renderer.set_data("column", LUMO_A) column = gtk.TreeViewColumn("a", renderer, text=LUMO_A, editable=LUMO_EDITABLE) treeview.append_column(column) # B renderer = gtk.CellRendererText() renderer.connect("edited", self.on_cell_edited, model) renderer.set_data("column", LUMO_B) column = gtk.TreeViewColumn("b", renderer, text=LUMO_B, editable=LUMO_EDITABLE) treeview.append_column(column) # C renderer = gtk.CellRendererText() renderer.connect("edited", self.on_cell_edited, model) renderer.set_data("column", LUMO_C) column = gtk.TreeViewColumn("c", renderer, text=LUMO_C, editable=LUMO_EDITABLE) treeview.append_column(column) def __add_columns_mesh(self, treeview): model = treeview.get_model() # Function renderer = gtk.CellRendererText() renderer.connect("edited", self.on_HOMO_edited, model) renderer.set_data("column", HOMO_FUNCTION) column = gtk.TreeViewColumn("Function", renderer, text=HOMO_FUNCTION, editable=HOMO_EDITABLE) treeview.append_column(column) # Enable renderer = gtk.CellRendererText() renderer.connect("edited", self.on_HOMO_edited, model) renderer.set_data("column", HOMO_ENABLE) column = gtk.TreeViewColumn("Enable", renderer, text=HOMO_ENABLE, editable=HOMO_EDITABLE) treeview.append_column(column) # A renderer = gtk.CellRendererText() renderer.connect("edited", self.on_HOMO_edited, model) renderer.set_data("column", HOMO_A) column = gtk.TreeViewColumn("a", renderer, text=HOMO_A, editable=HOMO_EDITABLE) treeview.append_column(column) # B renderer = gtk.CellRendererText() renderer.connect("edited", self.on_HOMO_edited, model) renderer.set_data("column", HOMO_B) column = gtk.TreeViewColumn("b", renderer, text=HOMO_B, editable=HOMO_EDITABLE) treeview.append_column(column) # C renderer = gtk.CellRendererText() renderer.connect("edited", self.on_HOMO_edited, model) renderer.set_data("column", HOMO_C) column = gtk.TreeViewColumn("c", renderer, text=HOMO_C, editable=HOMO_EDITABLE) treeview.append_column(column) def on_add_item_clicked(self, button, model): new_item = ["exp","0" ,"A","B","C",True] articles.append(new_item) iter = model.append() model.set (iter, LUMO_FUNCTION, new_item[LUMO_FUNCTION], LUMO_ENABLE, new_item[LUMO_ENABLE], LUMO_A, new_item[LUMO_A], LUMO_B, new_item[LUMO_B], LUMO_C, new_item[LUMO_C], LUMO_EDITABLE, new_item[LUMO_EDITABLE] ) def on_add_HOMO_clicked(self, button, model): new_item = ["exp","0" ,"A","B","C",True] HOMO_articles.append(new_item) iter = model.append() model.set (iter, HOMO_FUNCTION, new_item[HOMO_FUNCTION], HOMO_ENABLE, new_item[HOMO_ENABLE], HOMO_A, new_item[HOMO_A], HOMO_B, new_item[HOMO_B], HOMO_C, new_item[HOMO_C], HOMO_EDITABLE, new_item[HOMO_EDITABLE] ) def save_model(self, ): lines=[] function=0 for item in self.LUMO_model: lines.append("#function_"+item[HOMO_FUNCTION]+str(function)) lines.append(item[LUMO_FUNCTION]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_enable") lines.append(item[LUMO_ENABLE]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_a") lines.append(item[LUMO_A]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_b") lines.append(item[LUMO_B]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_c") lines.append(item[LUMO_C]) function=function+1 lines.append("#ver") lines.append("#1.0") lines.append("#end") inp_write_lines_to_file("./lumo0.inp",lines) lines=[] function=0 for item in self.HOMO_model: lines.append("#function_"+item[HOMO_FUNCTION]+str(function)) lines.append(item[HOMO_FUNCTION]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_enable") lines.append(item[HOMO_ENABLE]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_a") lines.append(item[HOMO_A]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_b") lines.append(item[HOMO_B]) lines.append("#function_"+item[HOMO_FUNCTION]+str(function)+"_c") lines.append(item[HOMO_C]) function=function+1 lines.append("#ver") lines.append("#1.0") lines.append("#end") inp_write_lines_to_file("./homo0.inp",lines) def on_remove_item_from_lumo_clicked(self, button, treeview): selection = treeview.get_selection() model, iter = selection.get_selected() if iter: path = model.get_path(iter)[0] model.remove(iter) del articles[ path ] self.save_model() self.update_graph() def on_remove_item_from_homo_clicked(self, button, treeview): selection = treeview.get_selection() model, iter = selection.get_selected() if iter: path = model.get_path(iter)[0] model.remove(iter) del HOMO_articles[ path ] self.save_model() self.update_graph() def on_cell_edited(self, cell, path_string, new_text, model): iter = model.get_iter_from_string(path_string) path = model.get_path(iter)[0] column = cell.get_data("column") if column == LUMO_FUNCTION: articles[path][LUMO_FUNCTION] = new_text model.set(iter, column, articles[path][LUMO_FUNCTION]) if column == LUMO_ENABLE: #old_text = model.get_value(iter, column) articles[path][LUMO_ENABLE] = new_text model.set(iter, column, articles[path][LUMO_ENABLE]) if column == LUMO_A: #old_text = model.get_value(iter, column) articles[path][LUMO_A] = new_text model.set(iter, column, articles[path][LUMO_A]) if column == LUMO_B: #old_text = model.get_value(iter, column) articles[path][LUMO_B] = new_text model.set(iter, column, articles[path][LUMO_B]) if column == LUMO_C: #old_text = model.get_value(iter, column) articles[path][LUMO_C] = new_text model.set(iter, column, articles[path][LUMO_C]) self.save_model() self.update_graph() def on_HOMO_edited(self, cell, path_string, new_text, model): iter = model.get_iter_from_string(path_string) path = model.get_path(iter)[0] column = cell.get_data("column") if column == HOMO_FUNCTION: HOMO_articles[path][HOMO_FUNCTION] = new_text model.set(iter, column, HOMO_articles[path][HOMO_FUNCTION]) if column == HOMO_ENABLE: #old_text = model.get_value(iter, column) HOMO_articles[path][HOMO_ENABLE] = new_text model.set(iter, column, HOMO_articles[path][HOMO_ENABLE]) if column == HOMO_A: #old_text = model.get_value(iter, column) HOMO_articles[path][HOMO_A] = new_text model.set(iter, column, HOMO_articles[path][HOMO_A]) if column == HOMO_B: #old_text = model.get_value(iter, column) HOMO_articles[path][HOMO_B] = new_text model.set(iter, column, HOMO_articles[path][HOMO_B]) if column == HOMO_C: #old_text = model.get_value(iter, column) HOMO_articles[path][HOMO_C] = new_text model.set(iter, column, HOMO_articles[path][HOMO_C]) self.save_model() self.update_graph() def update_graph(self): #cmd = './go.o --onlypos' #ret= os.system(cmd) self.LUMO_fig.clf() self.draw_graph_lumo() self.LUMO_fig.canvas.draw() def draw_graph_lumo(self): n=0 ax1 = self.LUMO_fig.add_subplot(111) ax1.set_ylabel('$DoS (m^{-3} eV^{-1})$') ax1.set_xlabel('Energy (eV)') #ax2 = ax1.twinx() x_pos=0.0 layer=0 color =['r','g','b','y','o','r','g','b','y','o'] ax1.set_yscale('log') ax1.set_ylim(ymin=1e17,ymax=1e28) pos=0 Eg=2.0 ax1.set_xlim([0,-Eg]) x = linspace(0, -Eg, num=40) for item in self.LUMO_model: if item[LUMO_FUNCTION]=="exp": y = float(item[LUMO_A])*exp(x/float(item[LUMO_B])) line, = ax1.plot(x,y , '-', linewidth=3) if item[LUMO_FUNCTION]=="gaus": y = float(item[LUMO_A])*exp(-pow(((float(item[LUMO_B])+x)/(sqrt(2.0)*float(item[LUMO_C])*1.0)),2.0)) line, = ax1.plot(x,y , color[pos], linewidth=3) pos=pos+1 pos=0 x_homo = linspace(-Eg, 0, num=40) for item in self.HOMO_model: if item[HOMO_FUNCTION]=="exp": y = float(item[HOMO_A])*exp(x/float(item[HOMO_B])) line, = ax1.plot(x_homo,y , '-', linewidth=3) if item[LUMO_FUNCTION]=="gaus": y = float(item[HOMO_A])*exp(-pow(((float(item[HOMO_B])+x)/(sqrt(2.0)*float(item[HOMO_C])*1.0)),2.0)) line, = ax1.plot(x_homo,y , color[pos], linewidth=3) pos=pos+1 def save_image(self,file_name): data=os.path.splitext(file_name)[0] lumo=data+'_bands.jpg' self.canvas_lumo.figure.savefig(lumo) def callback_save(self, widget, data=None): dialog = gtk.FileChooserDialog("Save as..", 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) filter = gtk.FileFilter() filter.set_name(".jpg") filter.add_pattern("*.jpg") dialog.add_filter(filter) response = dialog.run() if response == gtk.RESPONSE_OK: file_name=dialog.get_filename() if os.path.splitext(file_name)[1]: self.save_image(file_name) else: filter=dialog.get_filter() self.save_image(file_name+filter.get_name()) elif response == gtk.RESPONSE_CANCEL: print 'Closed, no files selected' dialog.destroy() def wow(self): self.edit_list=[] self.line_number=[] self.lines=[] self.save_file_name="lumo0.inp" inp_load_file(self.lines,"./lumo0.inp") n=0 pos=0 while True: if self.lines[pos]=="#end": break if self.lines[pos]=="#ver": break tag=self.lines[pos] scan_item_add("lumo0.inp",tag,tag,1) pos=pos+1 #skip hash tag function=self.lines[pos] #read label pos=pos+1 tag=self.lines[pos] scan_item_add("lumo0.inp",tag,tag,1) pos=pos+1 #skip hash tag enabled=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("lumo0.inp",tag,tag,1) pos=pos+1 #skip hash tag a=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("lumo0.inp",tag,tag,1) pos=pos+1 #skip hash tag b=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("lumo0.inp",tag,tag,1) pos=pos+1 #skip hash tag c=self.lines[pos] #read value pos=pos+1 articles.append([ str(function), str(enabled), str(a), str(b), str(c), True ]) self.save_file_name="homo0.inp" inp_load_file(self.lines,"./homo0.inp") n=0 pos=0 while True: if self.lines[pos]=="#end": break if self.lines[pos]=="#ver": break tag=self.lines[pos] scan_item_add("homo0.inp",tag,tag,1) pos=pos+1 #skip hash tag function=self.lines[pos] #read label pos=pos+1 tag=self.lines[pos] scan_item_add("homo0.inp",tag,tag,1) pos=pos+1 #skip hash tag enabled=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("homo0.inp",tag,tag,1) pos=pos+1 #skip hash tag a=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("homo0.inp",tag,tag,1) pos=pos+1 #skip hash tag b=self.lines[pos] #read value pos=pos+1 tag=self.lines[pos] scan_item_add("homo0.inp",tag,tag,1) pos=pos+1 #skip hash tag c=self.lines[pos] #read value pos=pos+1 HOMO_articles.append([ str(function), str(enabled), str(a), str(b), str(c), True ]) tooltips = gtk.Tooltips() toolbar = gtk.Toolbar() toolbar.set_orientation(gtk.ORIENTATION_VERTICAL) toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_size_request(50, -1) save = gtk.ToolButton(gtk.STOCK_SAVE) tooltips.set_tip(save, "Save image") pos=0 toolbar.insert(save, pos) save.connect("clicked", self.callback_save) toolbar.show_all() self.pack_start(toolbar, False, True, 0) vbox = gtk.VBox(False, 2) self.LUMO_model = self.__create_model() self.HOMO_model = self.__create_model_mesh() self.LUMO_fig = Figure(figsize=(5,4), dpi=100) self.draw_graph_lumo() self.canvas_lumo = FigureCanvas(self.LUMO_fig) # a gtk.DrawingArea self.canvas_lumo.figure.patch.set_facecolor('white') self.canvas_lumo.show() vbox.pack_start(self.canvas_lumo, True, True, 1) self.pack_start(vbox, True, True, 0) #self.attach(vbox, 0, 3, 0, 2) vbox.show() #Layer editor self.LUMO_fig.tight_layout(pad=0.5) vbox = gtk.VBox(False, 2) frame = gtk.Frame() frame.set_label("LUMO") vbox_layers = gtk.VBox(False, 2) treeview = gtk.TreeView(self.LUMO_model) treeview.set_size_request(400, 100) treeview.set_rules_hint(True) treeview.get_selection().set_mode(gtk.SELECTION_SINGLE) self.__add_columns(treeview) vbox_layers.pack_start(treeview, False, False, 0) treeview.show() add_button = gtk.Button("Add",gtk.STOCK_ADD) add_button.connect("clicked", self.on_add_item_clicked, self.LUMO_model) add_button.show() delete_button = gtk.Button("Delete",gtk.STOCK_DELETE) delete_button.connect("clicked", self.on_remove_item_from_lumo_clicked, treeview) delete_button.show() hbox = gtk.HBox(False, 2) hbox.pack_start(add_button, False, False, 0) hbox.pack_start(delete_button, False, False, 0) hbox.show() vbox_layers.pack_start(hbox, False, False, 0) vbox_layers.show() frame.add(vbox_layers) frame.show() vbox.pack_start(frame, False, False, 0) #spacer label=gtk.Label(" \n\n ") #self.attach(label, 4, 5, 1, 2,gtk.SHRINK ,gtk.SHRINK) vbox.pack_start(label, False, False, 0) label.show() #mesh editor frame = gtk.Frame() frame.set_label("H**O") vbox_mesh = gtk.VBox(False, 2) treeview = gtk.TreeView(self.HOMO_model) treeview.set_size_request(400, 100) treeview.set_rules_hint(True) treeview.get_selection().set_mode(gtk.SELECTION_SINGLE) self.__add_columns_mesh(treeview) vbox_mesh.pack_start(treeview, False, False, 0) treeview.show() add_button = gtk.Button("Add",gtk.STOCK_ADD) add_button.connect("clicked", self.on_add_HOMO_clicked, self.HOMO_model) add_button.show() delete_button = gtk.Button("Delete",gtk.STOCK_DELETE) delete_button.connect("clicked", self.on_remove_item_from_homo_clicked, treeview) delete_button.show() hbox = gtk.HBox(False, 2) hbox.pack_start(add_button, False, False, 0) hbox.pack_start(delete_button, False, False, 0) vbox_mesh.pack_start(hbox, False, False, 0) frame.add(vbox_mesh) vbox.pack_start(frame, False, False, 0) frame.show() vbox_mesh.show() hbox.show() self.pack_start(vbox, False, False, 0) #self.attach(vbox, 3, 4, 0, 1,gtk.SHRINK ,gtk.SHRINK) vbox.show()
class WaveletRunner(gtk.Window, Observer): def __init__(self, eoi, freq, t, data, trial_length, offset, window_length): gtk.Window.__init__(self) Observer.__init__(self) self.choose_file() self.channels = eoi self.selected_channels = [] # wavelets is a dict from name to np array self.wavelets = {} self.selected_wavelets = [] self.eegfreq = freq self.t = t # an array of ms exactly indexed into self.data[0] self.trial_length = trial_length self.offset = offset print t print data.shape print self.channels self.data = data self.fig = Figure(figsize=(15, 15), dpi=72) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.show() self.resize(700, 512) self.set_title('Wavelet Runner') vbox = gtk.VBox() vbox.show() self.add(vbox) buttonChans = gtk.Button("Chans") buttonChans.show() buttonChans.connect('clicked', self.load_chans) buttonWB = gtk.Button("Wavelet Toolbox") buttonWB.show() buttonWB.connect('clicked', self.load_wavelets) buttonPlot = gtk.Button(stock=gtk.STOCK_EXECUTE) buttonPlot.show() buttonPlot.connect('clicked', self.execute) lwindow = gtk.Label() lwindow.set_text("window in ms") lwindow.show() self.window_length_entry = gtk.Entry() self.window_length_entry.set_text( str((window_length / float(self.eegfreq)) * 1000)) self.window_length_entry.show() lmod = gtk.Label() lmod.set_text("modval") lmod.show() self.modval_entry = gtk.Entry() self.modval_entry.set_text('7.0') self.modval_entry.show() hbox = gtk.HBox() hbox.show() hbox.set_spacing(3) vbox.pack_start(hbox, False, False) hbox.pack_start(buttonChans, False, False) hbox.pack_start(buttonWB, False, False) hbox.pack_start(buttonPlot, False, False) hbox.pack_start(lwindow, False, False) hbox.pack_start(self.window_length_entry, False, False) hbox.pack_start(lmod, False, False) hbox.pack_start(self.modval_entry, False, False) self.statBar = gtk.Label() self.statBar.set_alignment(0, 0) self.statBar.show() self.progBar = gtk.ProgressBar() self.progBar.set_orientation(0) # bottom-to-top self.progBar.set_fraction(0) self.progBar.show() vbox.pack_start(self.canvas, True, True) vbox.pack_start(self.statBar, False, False) vbox.pack_start(self.progBar, False, False) def choose_file(self): chooser = gtk.FileChooserDialog( title="please create dump file", action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) response = chooser.run() if response == gtk.RESPONSE_OK: filename = chooser.get_filename() else: chooser.destroy() return # try and write a dummy file to fname to make sure the dir # is writable tmpfile = filename + 'tmp' try: file(tmpfile, 'wb').write('123') except IOError: error_msg('Basepath %s does not appear to be writable' % filename, parent=self) return else: os.remove(tmpfile) chooser.destroy() self.save_file = filename return def write_line(self, f, channel_name, wavelet_name, time_start, window_length, result): channel_name = '-'.join(str(channel_name)[1:-1].split(',')).replace( "\'", "") print >> f, "%s,%s,%f,%d,%f" % (channel_name, wavelet_name, time_start * 1000, window_length, result) def ms2points(self, val): return (float(val) * self.eegfreq) / 1000.0 def execute(self, button): file(self.save_file, 'wb').write('') f = open(self.save_file, 'ab') self.window_length = self.ms2points( float(self.window_length_entry.get_text())) self.modval = float(self.modval_entry.get_text()) self.window_length_ms = float(self.window_length_entry.get_text()) if self.selected_channels == []: channels = range(len(self.channels)) else: channels = self.selected_channels print "CHANNELS: ", channels numRows, numCols = self.data.shape ind = range(int(self.offset), int(numRows - self.window_length + 1), int(self.window_length)) num_slices = len(ind) for entry in ind: for channel in channels: thisSlice = self.data[entry:(entry + self.window_length), channel] # print "CHANNEL: ", channel, "THISSLICE: \n", thisSlice, for wavelet in self.selected_wavelets: assert (len(self.wavelets[wavelet]) == len(thisSlice)) result, p = pearsonr(thisSlice, self.wavelets[wavelet]) self.write_line(f, self.channels[channel], wavelet, self.t[entry], self.window_length_ms, result) # print result f.close def load_wavelets(self, button): self.window_length = float( self.ms2points(self.window_length_entry.get_text())) self.modval = float(self.modval_entry.get_text()) self.wavelets = wavelet_creator.create_all(self.window_length, self.eegfreq, self.modval) dlg = gtk.Dialog("Wavelet Manipulation") dlg.connect("destroy", dlg.destroy) dlg.set_size_request(400, 400) scrolled_window = gtk.ScrolledWindow(None, None) scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) dlg.vbox.pack_start(scrolled_window, True, True, 0) scrolled_window.show() table = gtk.Table(2, (1 + len(self.wavelets))) table.set_row_spacings(8) table.set_col_spacings(8) scrolled_window.add_with_viewport(table) table.show() #attach format: obj, beg end x, beg end y l1 = gtk.Label("show wavelet") l1.show() table.attach(l1, 0, 1, 0, 1) #an array to control the check boxes buttons = {} counter = 0 for i in self.wavelets.keys(): s1 = " %s" % (i, ) buttons[i] = gtk.CheckButton(s1) buttons[i].show() if i in self.selected_wavelets: buttons[i].set_active( True) #reactivate previously active wavelets buttons[i].connect("toggled", self.waveswitch, i) table.attach(buttons[i], 0, 1, counter + 1, counter + 2) counter += 1 butOK = gtk.Button("OK") butOK.connect('clicked', (lambda b, x: x.destroy()), dlg) butOK.show() dlg.vbox.pack_start(butOK, False, False) dlg.show() def load_chans(self, button): dlg = gtk.Dialog("Channel Manipulation") dlg.connect("destroy", dlg.destroy) dlg.set_size_request(400, 400) scrolled_window = gtk.ScrolledWindow(None, None) scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) dlg.vbox.pack_start(scrolled_window, True, True, 0) scrolled_window.show() table = gtk.Table(2, (1 + len(self.channels))) table.set_row_spacings(8) table.set_col_spacings(8) scrolled_window.add_with_viewport(table) table.show() #attach format: obj, beg end x, beg end y l1 = gtk.Label("show channel") l1.show() table.attach(l1, 0, 1, 0, 1) #an array to control the check boxes chanbuts = [] for i in range(0, len(self.channels)): s1 = " %s" % (self.channels[i], ) chanbuts.append(gtk.CheckButton(s1)) chanbuts[i].show() if i in self.selected_channels: chanbuts[i].set_active( True) #reactivate previously active channels chanbuts[i].connect("toggled", self.chanswitch, self.channels[i]) table.attach(chanbuts[i], 0, 1, i + 1, i + 2) butOK = gtk.Button("OK") butOK.connect('clicked', (lambda b, x: x.destroy()), dlg) butOK.show() dlg.vbox.pack_start(butOK, False, False) dlg.show() def chanswitch(self, widget, channelnum): print channelnum if widget.get_active(): self.selected_channels.append(self.channels.index(channelnum)) else: self.selected_channels.remove(self.channels.index(channelnum)) def waveswitch(self, widget, label): print label if widget.get_active(): self.selected_wavelets.append(label) else: self.selected_wavelets.remove(label)
class SOM: def If_running(self): #print som.running self.play.set_sensitive(not self.som.running) return self.som.running def If_paused(self): #print som.running #self.pause.set_sensitive(self.som.running) return False def Status_update(self): if self.som.running: context_id = self.status_bar.get_context_id("Running") #print context_id text = "Iteration: " + str(self.som.tick).zfill( len(str(self.som.ticks))) + "/" + str(self.som.ticks).zfill( len(str(self.som.ticks))) if self.som.paused: text += ", Paused" self.status_bar.push(context_id, text) return True # we need it to keep updating if the model is running elif not self.som.running: if not self.som.paused: self.status_bar.remove_all( self.status_bar.get_context_id("Running")) self.status_bar.remove_all( self.status_bar.get_context_id("Ready")) context_id = self.status_bar.get_context_id("Ready") #print context_id text = "Ready" self.status_bar.push(context_id, text) return False #def Quit(self, widget, data=None): ##print 'Byez!' #gtk.main_quit() #def Pause(self, widget=None, data=None): #self.som.Pause() #if self.som.paused: #self.pause.set_label("Unpause") #else: #self.pause.set_label("Pause") #glib.idle_add(self.som.Run) #glib.idle_add(self.If_running) #glib.idle_add(self.Status_update) def open_file(self, file_name): try: #cols = self.columns[self.combobox.get_active()] #print cols self.data = np.genfromtxt(file_name, delimiter=',', usecols=(self.visual_and_acoustic), skip_header=1) self.pattern_labels = np.genfromtxt( file_name, delimiter=',', usecols=(self.visual_and_acoustic), skip_footer=14, dtype=str) self.file_name = file_name self.update_treeview(self.data, self.patterns_liststore) #print self.data except: print "File is probably not in the right format:", file_name raise def select_file(self, widget=None, data=None): #response = self.dialog.run() #if response == gtk.RESPONSE_OK: #self.open_file(self.dialog.get_filename()) #elif response == gtk.RESPONSE_CANCEL: #print 'Closed, no files selected' #self.dialog.destroy() dialog = gtk.FileChooserDialog("Open..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) tmp = os.getcwd() tmp = 'file://' + tmp #print tmp #print dialog.set_current_folder_uri(tmp) #print dialog.get_current_folder_uri() filter = gtk.FileFilter() filter.set_name("All files") filter.add_pattern("*") dialog.add_filter(filter) filter = gtk.FileFilter() filter.set_name("Comma-separated values") filter.add_pattern("*.csv") dialog.add_filter(filter) dialog.set_filter(filter) #dialog = gtk.FileChooserDialog("Please choose a file", self, #gtk.FileChooserAction.OPEN, #(gtk.STOCK_CANCEL, gtk.ResponseType.CANCEL, #gtk.STOCK_OPEN, gtk.ResponseType.OK)) response = dialog.run() if response == gtk.RESPONSE_OK: #print("Open clicked") #print("File selected: " + dialog.get_filename()) self.open_file(dialog.get_filename()) #elif response == gtk.RESPONSE_CANCEL: #print("Cancel clicked") dialog.destroy() def Run(self, widget=None, data=None): #self.som.ticks += self.iterations_spin_button.get_value_as_int() if not self.som.running: ### Initialization and training ### #self.som = MiniSom(5, 15, 8,sigma=1.2,learning_rate=0.5) #self.init_som() for i in range(1): self.train_som() #self.figure.clf() self.Draw_figure() self.canvas.draw() self.canvas.draw_idle() #We need to draw *and* flush self.figure.canvas.draw() self.figure.canvas.flush_events() #print "draw" self.update_treeview(self.test_data, self.test_liststore) self.update_treeview(self.data, self.patterns_liststore) glib.idle_add(self.Status_update) glib.idle_add(self.If_running) glib.idle_add(self.If_paused) def Test(self, widget=None, data=None): #self.som.ticks += self.iterations_spin_button.get_value_as_int() if not self.som.running: ### Initialization and training ### #self.som = MiniSom(5, 15, 8,sigma=1.2,learning_rate=0.5) self.test_som() #self.figure.clf() self.Draw_figure() self.canvas.draw() self.canvas.draw_idle() #We need to draw *and* flush self.figure.canvas.draw() self.figure.canvas.flush_events() #print "draw" glib.idle_add(self.Status_update) glib.idle_add(self.If_running) glib.idle_add(self.If_paused) def Reset(self, widget=None, data=None): self.init_som() self.Draw_figure() self.canvas.draw() self.canvas.draw_idle() #We need to draw *and* flush self.figure.canvas.draw() self.figure.canvas.flush_events() #print "draw" self.update_treeview(self.test_data, self.test_liststore) self.update_treeview(self.data, self.patterns_liststore) glib.idle_add(self.Status_update) glib.idle_add(self.If_running) glib.idle_add(self.If_paused) def delete_event(self, widget=None, event=None, 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 on_key_event(self, event): #print('you pressed %s'%event.key) #key_press_handler(event, self.canvas, self.toolbar) def destroy(self, widget=None, data=None): #print "destroy signal occurred" gtk.main_quit() # T def Draw_figure(self): # this function draws the exemplars on the best matching units self.axes.cla() # Clear axis cols = self.columns[self.combobox.get_active()] data = self.data[:, 0:len(cols)] test_data = self.test_data[:, 0:len(cols)] #ion() # Turn on interactive mode. #hold(True) # Clear the plot before adding new data. #print som.distance_map().T #exit() bone() background = self.axes.pcolor(self.som.distance_map( ).T) # plotting the distance map as background #f.colorbar(a) t = np.zeros(len(self.target), dtype=int) t[self.target == 'A'] = 0 t[self.target == 'B'] = 1 #t[self.target == 'C'] = 2 #t[self.target == 'D'] = 3 tTest = np.zeros(len(self.test_target), dtype=int) tTest[self.test_target == 'A'] = 2 #0 tTest[self.test_target == 'B'] = 3 #1 # use different colors and markers for each label markers = ['o', 's', '*', '+'] colors = ['r', 'g', 'b', 'y'] for cnt, xx in enumerate(data): # training data ( noisy simulation) w = self.som.winner(xx) # getting the winner # place a marker on the winning position for the sample xx tmp = self.axes.plot(w[0] + .5, w[1] + .5, markers[t[cnt]], markerfacecolor='None', markeredgecolor=colors[t[cnt]], markersize=12, markeredgewidth=2) # plot the test data (ideal input) for cnt, xx in enumerate(test_data): # test data ( ideal ) w = self.som.winner(xx) # getting the winner # place a marker on the winning position for the sample xx tmp = self.axes.plot(w[0] + .5, w[1] + .5, markers[tTest[cnt]], markerfacecolor='None', markeredgecolor=colors[tTest[cnt]], markersize=12, markeredgewidth=2) self.axes.axis( [0, self.som.weights.shape[0], 0, self.som.weights.shape[1]]) #show() # show the figure #print "drawing" #self.figure.canvas.draw() def init_som(self, widget=None, data=None): ##print self.data ### Initialization and training ### cols = self.columns[self.combobox.get_active()] data = self.data[:, 0:len(cols)] #print len(cols) self.som = MiniSom(self.width_spin_button.get_value_as_int(), self.height_spin_button.get_value_as_int(), len(cols), sigma=1.2, learning_rate=0.5) # self.som.weights_init_gliozzi(data) self.som.random_weights_init(data) def train_som(self): cols = self.columns[self.combobox.get_active()] data = self.data[:, 0:len(cols)] print("Training...") #self.som.train_gliozzi(data) # Gliozzi et al training self.som.train_random(data, 100) print("\n...ready!") def make_treeview(self, data, liststore): #i = 0 cols = self.columns[self.combobox.get_active()] #print type(cols) #print len(cols) for d in data: #i += 1 tmp = d.tolist() #print 'tmp', tmp #while len(tmp) < cols: #tmp.append(False) #print 'tmp', tmp #cols = cols - 1 Qe = MiniSom.quantization_error_subset(self.som, d, len(cols)) #print tmp tmp.append(Qe) tmp.append(4 * Qe**0.5) liststore.append(tmp) treeview = gtk.TreeView(model=liststore) #i = 0 for d in range(len(self.test_data[0])): # not sure what this is doing #print i #i += 1 renderer_text = gtk.CellRendererText() column_text = gtk.TreeViewColumn(self.pattern_labels[d], renderer_text, text=d) treeview.append_column(column_text) column_text = gtk.TreeViewColumn('Qe', renderer_text, text=d + 1) treeview.append_column(column_text) column_text = gtk.TreeViewColumn('NLT', renderer_text, text=d + 2) treeview.append_column(column_text) return treeview def update_treeview(self, data, liststore): cols = len(self.columns[self.combobox.get_active()]) for i, d in enumerate(data): for j in range(len(d)): #print j liststore[i][j] = d[j] if j >= cols: liststore[i][j] = -999 Qe = MiniSom.quantization_error_subset(self.som, d, cols) #print d, liststore[i] liststore[i][-2] = Qe liststore[i][-1] = 4 * Qe**0.5 def select_columns(self, widget=None): #self.open_file(self.file_name) #self.init_som() self.update_treeview(self.test_data, self.test_liststore) self.update_treeview(self.data, self.patterns_liststore) #---------------------------------------- # SAM added these functions here def pertSomWeights(self, widget=None, data=None): #if scale == None: scale = .5 print('Adding noise to SOM weights') # print( self.som.weights ) # print( self.som.weights.shape ) pertAmount = scale * (np.random.random_sample(self.som.weights.shape) - .5) self.som.weights = self.som.weights + pertAmount # print self.som.weights self.Draw_figure() self.canvas.draw() self.canvas.draw_idle() #We need to draw *and* flush self.figure.canvas.draw() self.figure.canvas.flush_events() def pertInputs(self, widget=None, data=None): #if scale == None: p = .2 print('Making %f prop of inputs 0.5' % p) #print( self.data.shape ) # randomly get indices to switch, then replace noiseIndex = np.random.binomial( 1, p, self.data.shape) #ones at p proportion of samples self.data[noiseIndex == 1] = .5 print(self.data) # update the treeview for the "Patterns" tab to see the result graphically self.update_treeview(self.data, self.patterns_liststore) #---------------------------------------- def __init__(self): # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # When the window is given the "delete_event" signal (this is given # by the window manager, usually by the "close" option, or on the # titlebar), we ask it to call the delete_event () function # as defined above. The data passed to the callback # function is NULL and is ignored in the callback function. self.window.connect("delete_event", self.delete_event) # Here we connect the "destroy" event to a signal handler. # This event occurs when we call gtk_widget_destroy() on the window, # or if we return FALSE in the "delete_event" callback. self.window.connect("destroy", self.destroy) #window.set_icon_from_file(get_resource_path("icon.png")) #window.connect("delete-event", Quit) #window.connect("destroy", Quit) self.window.set_title("SOM model") self.window.set_default_size( 500, 500 ) #this si to ensure the window is always the smallest it can be #self.window.set_resizable(False) #window.set_border_width(10) # Args are: homogeneous, spacing, expand, fill, padding homogeneous = False spacing = 0 expand = False fill = False padding = 10 self.hbox = gtk.HBox(homogeneous, spacing) self.vbox = gtk.VBox(homogeneous, spacing) self.window.add(self.vbox) #self.adjustment = gtk.Adjustment(value=10000, lower=1, upper=100000000, step_incr=1000, page_incr=10000) #self.iterations_spin_button = gtk.SpinButton(self.adjustment, climb_rate=0, digits=0) self.label = gtk.Label("Dimensions:") self.adjustment = gtk.Adjustment(value=5, lower=1, upper=100, step_incr=2, page_incr=5) self.width_spin_button = gtk.SpinButton(self.adjustment, climb_rate=0, digits=0) self.adjustment = gtk.Adjustment(value=10, lower=1, upper=100, step_incr=2, page_incr=5) self.height_spin_button = gtk.SpinButton(self.adjustment, climb_rate=0, digits=0) # Create a series of buttons with the appropriate settings image = gtk.Image() # (from http://www.pygtk.org/docs/pygtk/gtk-stock-items.html) image.set_from_stock(gtk.STOCK_EXECUTE, 1) self.play = gtk.Button() self.play.set_image(image) self.play.set_label("Train") #image = gtk.Image() ## (from http://www.pygtk.org/docs/pygtk/gtk-stock-items.html) #image.set_from_stock(gtk.STOCK_APPLY, 1) #self.test = gtk.Button() #self.test.set_image(image) #self.test.set_label("Test") image = gtk.Image() # (from http://www.pygtk.org/docs/pygtk/gtk-stock-items.html) image.set_from_stock(gtk.STOCK_OPEN, 1) self.open = gtk.Button() self.open.set_image(image) self.open.set_label("Open patterns") #self.pause = gtk.Button(stock = gtk.STOCK_MEDIA_PAUSE) image = gtk.Image() image.set_from_stock(gtk.STOCK_REFRESH, 1) self.reset = gtk.Button() self.reset.set_image(image) self.reset.set_label("Reset") self.play.connect("clicked", self.Run, None) #self.test.connect("clicked", self.Test, None) self.open.connect("clicked", self.select_file, None) #self.pause.connect("clicked", self.Pause, None) self.reset.connect("clicked", self.Reset, None) self.height_spin_button.connect("value-changed", self.Reset, "Height changed") self.width_spin_button.connect("value-changed", self.Reset, "Width changed") # add perturb button to disturb trained som weights self.perturb = gtk.Button( "Perturb SOM") # create gtk button to perturb som weights self.perturb.connect("clicked", self.pertSomWeights, None) # run self.pertSomWeights self.perturb.show() # tell GTK to show button, but not where # add button to add noisy encoding to training inputs self.perturbInputButton = gtk.Button( "Perturb Inputs") # create gtk button to perturb som weights self.perturbInputButton.connect("clicked", self.pertInputs, None) # run self.pertSomWeights self.perturbInputButton.show( ) # tell GTK to show button, but not where #self.width_spin_button.connect("value_changed", self.init_som) #self.height_spin_button.connect("value_changed", self.init_som) #self.som = Environment(width = self.width_spin_button.get_value_as_int(), height = self.height_spin_button.get_value_as_int()) #self.som.show() #self.pause.set_sensitive(self.som.paused) #self.vbox.pack_start(self.som, True, True, 0) file_names = ['4749.csv'] #['stimuli.csv'] self.visual_only = [0, 1, 2, 3, 4, 5, 6, 7] self.visual_and_acoustic = [0, 1, 2, 3, 4, 5, 6, 7, 8] self.columns = [self.visual_only, self.visual_and_acoustic] self.file_name = file_names[0] # the cusom noisy data to load self.test_file_name = 'stimuli.csv' # idealized exemplar data #f = Figure(figsize=(5,4), dpi=100) #a = f.add_subplot(111) self.combobox = gtk.combo_box_new_text() self.combobox.append_text('Visual only') self.combobox.append_text('Visual and acoustic') self.test_data = np.genfromtxt(self.test_file_name, delimiter=',', usecols=(self.visual_and_acoustic), skip_header=1) self.test_data += -.5 #0.00001 self.test_data = np.apply_along_axis( lambda x: x / np.linalg.norm(x), 1, self.test_data) # data normalization # here specify the labels (for coloring them nicely on the figure) self.target = np.genfromtxt( self.file_name, delimiter=',', usecols=(9), dtype=str, skip_header=1 ) # loading the labels for use in the figure (corresponding to data) self.test_target = np.genfromtxt( self.test_file_name, delimiter=',', usecols=(9), dtype=str, skip_header=1) # corresponding to test_data self.combobox.set_active(1) self.combobox.connect('changed', self.Reset) #cols = self.columns[self.combobox.get_active()] #print cols self.data = np.genfromtxt(self.file_name, delimiter=',', usecols=(self.visual_and_acoustic), skip_header=1) self.data += -.5 #0.00001 self.data = np.apply_along_axis(lambda x: x / np.linalg.norm(x), 1, self.data) # data normalization self.pattern_labels = np.genfromtxt(self.file_name, delimiter=',', usecols=(self.visual_and_acoustic), skip_footer=14, dtype=str) #print self.pattern_labels self.init_som() #self.toolbar = NavigationToolbar(self.canvas, self.window) #self.vbox.pack_start(self.toolbar, False, False) #self.vbox.pack_start(self.canvas) self.test_liststore = gtk.ListStore(float, float, float, float, float, float, float, float, float, float, float) self.patterns_liststore = gtk.ListStore(float, float, float, float, float, float, float, float, float, float, float) self.test_treeview = self.make_treeview(self.test_data, self.test_liststore) self.patterns_treeview = self.make_treeview(self.data, self.patterns_liststore) #self.data = np.genfromtxt(self.file_name, delimiter=',',usecols=(0,1,2,3,4,5,6,7),skip_header=1) #self.pattern_labels = np.genfromtxt(self.file_name, delimiter=',',usecols=(0,1,2,3,4,5,6,7), skip_footer=8, dtype=str) ##self.data = np.apply_along_axis(lambda x: x/np.linalg.norm(x),1,self.data) # data normalization self.figure, self.axes = plt.subplots() # Create canvas. self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea self.canvas.set_size_request(300, 400) self.Draw_figure() self.notebook = gtk.Notebook() self.notebook.set_tab_pos(gtk.POS_TOP) self.vbox.pack_start(self.notebook) label = gtk.Label("Distance map") self.notebook.append_page(self.canvas, label) label = gtk.Label("Patterns") self.notebook.append_page(self.patterns_treeview, label) label = gtk.Label("Testing") #hbox = gtk.HBox(homogeneous, spacing) self.notebook.append_page(self.test_treeview, label) #hbox.pack_start(test_treeview, expand, fill, 0) #hbox.pack_start(test_treeview, expand, fill, 0) self.patterns_treeview.show() self.test_treeview.show() self.canvas.draw_idle() self.canvas.show() self.figure.canvas.draw() self.vbox.pack_start(self.hbox, expand, fill, 10) self.status_bar = gtk.Statusbar() self.vbox.pack_start(self.status_bar, expand, fill, 0) self.status_bar.show() glib.idle_add(self.Status_update) self.hbox.show() self.vbox.show() self.play.show() #self.test.show() self.open.show() #self.pause.show() self.reset.show() #self.iterations_spin_button.show() self.width_spin_button.show() self.height_spin_button.show() self.hbox.pack_start(self.play, expand, fill, padding) #self.hbox.pack_start(self.test, expand, fill, padding) self.hbox.pack_start(self.open, expand, fill, padding) self.hbox.pack_start(self.combobox, expand, fill, padding) #self.hbox.pack_start(self.pause, expand, fill, 0) self.hbox.pack_start(self.reset, expand, fill, padding) #self.hbox.pack_start(self.iterations_spin_button, expand, fill, 0) self.hbox.pack_start(self.label, expand, fill, padding) self.hbox.pack_start(self.width_spin_button, expand, fill, padding) self.hbox.pack_start(self.height_spin_button, expand, fill, 0) self.hbox.pack_start(self.perturb, expand, fill, padding) self.hbox.pack_start(self.perturbInputButton, expand, fill, padding) #self.quit = gtk.Button("Quit") self.quit = gtk.Button(stock=gtk.STOCK_QUIT) self.combobox.connect('changed', self.select_columns) self.quit.connect("clicked", self.destroy, None) self.hbox.pack_end(self.quit, expand, fill, padding) self.quit.show() #print window.get_size() self.window.show_all() self.window.present() #gtk.main() # And of course, our main loop. #gtk.main() # Control returns here when main_quit() is called return None def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main()
def display_graph(self, widget): dialog = gtk.Dialog("My dialog", self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) dialog.set_size_request(1300, 500) # Crime name filter if " " not in self.combobox_crime.get_active_text(): crime = self.combobox_crime.get_active_text() else: crime = ".".join(self.combobox_crime.get_active_text().split(" ")) fig = Figure(figsize=(12, 10), dpi=100) sales = [{ 'Groups': '0-9', 'Counts': 38 }, { 'Groups': '10-19', 'Counts': 41 }, { 'Groups': '20-29', 'Counts': 77 }, { 'Groups': '30-39', 'Counts': 73 }, { 'Groups': '40-49', 'Counts': 77 }] df = pd.DataFrame(sales) ax = fig.add_subplot(111) if (self.combobox_year.get_active_text() == "All" and self.combobox_district.get_active_text() != "All"): self.filtered_data = self.filtered_data.reset_index(drop=True) ypos = np.arange(len(self.filtered_data['YEAR'].tolist())) p1 = ax.bar(ypos, self.filtered_data[crime], width=0.6, color='r') ax.set_title(crime.lower() + 's in ' + self.combobox_district.get_active_text() + ' - Yearwise') ax.set_xticks(ypos + 0.3) ax.set_xticklabels(self.filtered_data.YEAR) elif (self.combobox_district.get_active_text() == "All" and self.combobox_year.get_active_text() != "All"): fd_total_removed = self.filtered_data[ self.filtered_data.DISTRICT != 'TOTAL'] ypos = np.arange(len(fd_total_removed['DISTRICT'].tolist())) p1 = ax.bar(ypos, fd_total_removed[crime], width=0.3, color='r') fontx = { 'fontsize': 7, 'fontweight': 2, 'verticalalignment': 'center', 'horizontalalignment': 'center' } ax.set_title(crime + 's in ' + self.combobox_state.get_active_text() + '(' + self.combobox_state.get_active_text() + ' )' + ' - Districtwise') ax.set_xticks(ypos + 0.15) ax.set_xticklabels(fd_total_removed.DISTRICT, fontdict=fontx) else: print(df.index) p1 = ax.bar(df.index, df.Counts, width=0.8, color='r') ax.set_title('Scores by group and gender') ax.set_xticks(df.index + 0.4) ax.set_xticklabels(df.Groups) canvas = FigureCanvas(fig) # a gtk.DrawingArea canvas.set_size_request(800, 600) dialog.vbox.pack_start(canvas) toolbar = NavigationToolbar(canvas, dialog) dialog.vbox.pack_start(toolbar, False, False) canvas.show() dialog.run() dialog.destroy() return
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 DrawArea: def __init__(self, vbox=None, window=None): logging.debug('>>') #self.figure = Figure(figsize=(6,4), dpi=72) #self.axis = self.figure.add_subplot(111) self.vbox = vbox self.window = window #self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea #self.drawDefault() self.NEARLY_ZERO = 0.0000000000000000000001 logging.debug('<<') def stadistics(self, type, xvalues, yvalues, xlabel, ylabel, title, color=None, zones=None): logging.debug('>>') if len(xvalues[0]) < 1: #self.drawDefault() return False #logging.debug('xvalues: '+str(xvalues)) #logging.debug('yvalues: '+str(yvalues)) #logging.debug("Type: "+type+" | title: "+str(title)+" | col: "+str(color)+" | xlabel: "+str(xlabel)+" | ylabel: "+str(ylabel)) if type == "bars": self.drawBars(xvalues, yvalues, xlabel, ylabel, title, color) elif type == "plot": self.drawPlot(xvalues, yvalues, xlabel, ylabel, title, color, zones) elif type == "pie": self.drawPie(xvalues, yvalues, xlabel, ylabel, title, color, zones) logging.debug('<<') def drawBars(self, xvalues, yvalues, xlabel, ylabel, title, color): logging.debug('>>') logging.debug("Type: bars | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) numCols = len(xvalues[0]) xmod = 0.4 self.showGraph = False axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 logging.debug("One axis, barWidth %f, barOffset %f" % (barWidth, barOffset)) elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 logging.debug("Twin axes, barWidth %f, barOffset %f" % (barWidth, barOffset)) else: #Error logging.debug("Error: invalid number of axes") return axis.set_xlabel(xlabel[0]) axis.set_ylabel(ylabel[0]) logging.debug("Labels set x: %s, y: %s" % (xlabel[0], ylabel[0])) xvals = [x + barOffset for x in range(0, numCols)] yvals = [0] * numCols for i in range(0, numCols): yval = yvalues[0][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Drawing bars") axis.bar(xvals, yvals, barWidth, color=color[0], align='edge') else: #Only zero results logging.debug("No results to draw") pass axis.grid(True) axis.set_title("%s" % (title[0])) logging.debug("Setting title to: %s" % title[0]) for tl in axis.get_yticklabels(): logging.debug("Setting ticklabel color %s" % color[0]) tl.set_color('%s' % color[0]) if len(xvalues) == 2: #Display twin axis ax2 = axis.twinx() logging.debug("Axis 2: Twin axis: %s " % str(ax2)) xvals = [x + barOffset + barWidth for x in range(0, numCols)] for i in range(0, numCols): yval = yvalues[1][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Axis 2: Drawing bars") ax2.bar(xvals, yvals, barWidth, color=color[1], align='edge') logging.debug("Axis 2: Label set y: %s" % (ylabel[1])) ax2.set_ylabel(ylabel[1]) else: #Only zero results logging.debug("Axis 2: No results to draw") pass for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[1]) logging.debug("Axis 2: Setting ticklabel color %s" % color[1]) _title = "%s vs %s" % (title[0], title[1]) logging.debug("Axis 2: Setting title to: %s" % _title) axis.set_title(_title) logging.debug("Setting x ticks") tickLocations = [x + 0.5 for x in xrange(0, numCols)] axis.set_xticks(tickLocations) axis.set_xticklabels(xvalues[0]) logging.debug("Setting x limits") axis.set_xlim(0, numCols) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Got canvas: %s" % (str(canvas))) canvas.show() logging.debug("Adding canvas to vbox") self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<') def getColor(self, x): colors = ["b", "g", "r", "c", "m", "y", "k", "w"] if x >= len(colors): x = x % len(colors) return colors[x] def fmtTableText(self, x, valuesAreTime): if x <= 0.0001: return ' ' elif valuesAreTime: hour = int(x) minutes = int((x - hour) * 60) hourLabel = _("h") minLabel = _("min") if hour > 0: return "%d%s %02d%s" % (hour, hourLabel, minutes, minLabel) else: return "%02d%s" % (minutes, minLabel) else: return '%1.1f' % x def drawStackedBars(self, xvalues, yvalues, ylabel, title, valuesAreTime=False, colors={}): '''function to draw stacked bars xvalues needs to be a list of lists of strings, e.g. [0]["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] yvalues needs to be a list of dicts e.g. [0]{'Kayak': {'Tue': 10.08, 'Fri': 17.579999999999998, 'Thu': 15.66, 'Sat': 30.619999999999997}, {'Run': {'Mon': 9.65, 'Sun': 15.59}} ''' #TODO tidy logging.debug('>>') logging.debug("Title: %s", (title, )) logging.debug("X values received: %s", str(xvalues)) logging.debug("Y values received: %s", str(yvalues)) self.removeVboxChildren() #Check how many axes to draw if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 else: #Error return keys = yvalues[0].keys() # days of the week numRows = len(keys) numCols = len(xvalues[0]) if numRows == 0: return width = .8 #figure = plt.figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) axis = plt.subplot(111) ybottoms = [0] * numCols yheights = [0] * numCols inds = xrange(0, numCols) xvals = [x + barOffset for x in range(0, numCols)] cellText = [] self.showGraph = False for k in colors: if colors[k] == None: colors[k] = '' #Display first axis xticks = [] for key in keys: logging.debug("Day of the week: %s", str(key)) for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[0][key]: height = yvalues[0][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height cellText.append( [self.fmtTableText(x, valuesAreTime[0]) for x in yheights]) if self.showGraph: axis.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results pass axis.set_xticklabels('' * len(xvalues[0])) axis.set_ylabel(ylabel[0]) if len(xvalues) == 1: plt.title(title[0]) axis.legend(loc=0) axis.set_xlim(0, numCols) logging.debug("X values first axis: %s", str(xvals)) logging.debug("Y values first axis: %s", str(yheights)) #Display twin axis if len(xvalues) == 2: self.showGraph = False ax2 = axis.twinx() keys = yvalues[1].keys() ybottoms = [0] * numCols yheights = [self.NEARLY_ZERO] * numCols for key in keys: for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0.0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[1][key]: height = yvalues[1][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height textToAdd = self.fmtTableText(height, valuesAreTime[1]) if textToAdd is not ' ': row = keys.index(key) col = index cellText[row][col] += " | %s" % (self.fmtTableText( height, valuesAreTime[1])) #print "Would add %s to %s %s" % (self.fmtTableText(height, valuesAreTime[1]), index, keys.index(key)) if self.showGraph: xvals = [ x + barOffset + barWidth for x in range(0, numCols) ] #print "ax2", xvals, yheights, ybottoms ax2.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results ax2.bar(xvals, [0] * numCols, bottom=[0] * numCols, width=barWidth, color=color, align='edge', label=key) pass ax2.set_xticklabels('' * len(xvalues[1])) ax2.set_xlim(0, numCols) ax2.set_ylabel(ylabel[1]) ax2.legend(loc=0) plt.title("%s vs %s" % (title[0], title[1])) ## try to do some table stuff colLabels = xvalues[0] rowLabels = keys axis.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, colLabels=colLabels, loc='bottom') plt.subplots_adjust(left=0.15, bottom=0.08 + (0.03 * numRows)) axis.grid(True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<') def drawPlot(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None, xzones=None, ylimits=None, y1_linewidth=None): logging.debug('>>') logging.debug("Type: plot | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) logging.debug('xlabel: ' + str(xlabel) + ' | ylabel: ' + str(ylabel) + ' | title: ' + str(title)) self.removeVboxChildren() figure = plt.Figure() logging.debug("Figure: %s" % str(figure)) #figure.clf() i = 0 for value in xvalues: if i < 1: logging.debug("i: %d, value: (%s) %s %s" % (i, str(value), str(xvalues), str(yvalues))) axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) line = axis.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis plotted, Line: %s" % str(line)) if y1_linewidth is not None: line[0].set_linewidth(y1_linewidth) linewidth = line[0].get_linewidth() axis.grid(True) logging.debug("Axis grid on") for tl in axis.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Ticklabels color set") #Draw zones on graph, eg for each lap if xzones is not None: logging.debug("Setting xzones") for xzone in xzones: if xzones.index(xzone) % 2: zonecolor = 'b' else: zonecolor = 'g' axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor) maxX = max(xvalues[i]) if i >= 1: ax2 = axis.twinx() logging.debug("Axis2: Axis: %s" % str(ax2)) ax2.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis2: plotted") for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Axis2: Ticklabels color set") maxXt = max(xvalues[i]) if maxXt > maxX: maxX = maxXt axis.set_xlabel(xlabel[i]) logging.debug("X label set") i += 1 axis.set_xlim(0, maxX) if (len(xvalues) > 1): axis.set_title("%s vs %s" % (ylabel[0], ylabel[1])) else: axis.set_title("%s" % (ylabel[0])) ylim_min, ylim_max = axis.get_ylim() if ylimits is not None: logging.debug("Using ylimits: %s" % str(ylimits)) if ylimits[0] is not None: ylim_min = ylimits[0] if ylimits[1] is not None: ylim_max = ylimits[1] axis.set_ylim(ylim_min, ylim_max) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Canvas: %s" % str(canvas)) canvas.show() self.vbox.pack_start(canvas, True, True) toolbar = NavigationToolbar(canvas, self.window) self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<') return { 'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth } def drawPie(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None): logging.debug('>>') logging.debug("Type: pie | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = Figure() logging.debug("Figure: %s" % str(figure)) axis = figure.add_subplot(111) labels = [] colors = [] frac0 = 0 frac1 = 0 frac2 = 0 frac3 = 0 frac4 = 0 frac5 = 0 for zone in zones: labels.insert(0, zone[3]) colors.insert(0, zone[2]) labels.insert(0, _("rest")) colors.insert(0, "#ffffff") for value in yvalues[0]: if value <= zones[4][0]: frac0 += 1 elif value > zones[4][0] and value <= zones[4][1]: frac1 += 1 elif value > zones[3][0] and value <= zones[3][1]: frac2 += 1 elif value > zones[2][0] and value <= zones[2][1]: frac3 += 1 elif value > zones[1][0] and value <= zones[1][1]: frac4 += 1 elif value > zones[0][0] and value <= zones[0][1]: frac5 += 1 fracs = [] explode = [] if frac5 == 0: labels.pop(5) colors.pop(5) else: fracs.insert(0, frac5) explode.insert(0, 0) if frac4 == 0: labels.pop(4) colors.pop(4) else: fracs.insert(0, frac4) explode.insert(0, 0) if frac3 == 0: labels.pop(3) colors.pop(3) else: fracs.insert(0, frac3) explode.insert(0, 0) if frac2 == 0: labels.pop(2) colors.pop(2) else: fracs.insert(0, frac2) explode.insert(0, 0) if frac1 == 0: labels.pop(1) colors.pop(1) else: fracs.insert(0, frac1) explode.insert(0, 0) if frac0 == 0: labels.pop(0) colors.pop(0) else: fracs.insert(0, frac0) explode.insert(0, 0) axis.pie(fracs, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) self.vbox.pack_start(canvas, True, True) logging.debug('<<') def drawDefault(self): logging.debug('>>') self.axis = self.figure.add_subplot(111) self.axis.set_xlabel('Yepper') self.axis.set_ylabel('Flabber') self.axis.set_title('An Empty Graph') self.axis.grid(True) self.canvas.destroy() self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea self.canvas.show() self.vbox.pack_start(self.canvas, True, True) logging.debug('<<') def fill_over(self, ax, x, y, val, color, over=True): """ Plot filled x,y for all y over val if over = False, fill all areas < val """ logging.debug('>>') ybase = asarray(y) - val crossings = nonzero(less(ybase[:-1] * ybase[1:], 0)) if ybase[0] >= 0: fillon = over else: fillon = not over indLast = 0 for ind in crossings: if fillon: thisX = x[indLast:ind + 1] thisY = y[indLast:ind + 1] thisY[0] = val thisY[-1] = val ax.fill(thisX, thisY, color) fillon = not fillon indLast = ind logging.debug('<<') def removeVboxChildren(self): ''' function to delete vbox children so that multiple graphs do not appear there must a better way to do this - pyplot? ''' logging.debug('>>') #Tidy up draw areas vboxChildren = self.vbox.get_children() logging.debug('Vbox has %d children %s' % (len(vboxChildren), str(vboxChildren))) # ToDo: check why vertical container is shared for child in vboxChildren: #Remove all FigureCanvasGTK and NavigationToolbar2GTKAgg to stop double ups of graphs if isinstance(child, matplotlib.backends.backend_gtkagg. FigureCanvasGTK) or isinstance( child, matplotlib.backends.backend_gtkagg. NavigationToolbar2GTKAgg): logging.debug('Removing child: ' + str(child)) self.vbox.remove(child) logging.debug('<<')
def drawPlot(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None, xzones=None, ylimits=None, y1_linewidth=None): logging.debug('>>') logging.debug("Type: plot | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) logging.debug('xlabel: ' + str(xlabel) + ' | ylabel: ' + str(ylabel) + ' | title: ' + str(title)) self.removeVboxChildren() figure = plt.Figure() logging.debug("Figure: %s" % str(figure)) #figure.clf() i = 0 for value in xvalues: if i < 1: logging.debug("i: %d, value: (%s) %s %s" % (i, str(value), str(xvalues), str(yvalues))) axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) line = axis.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis plotted, Line: %s" % str(line)) if y1_linewidth is not None: line[0].set_linewidth(y1_linewidth) linewidth = line[0].get_linewidth() axis.grid(True) logging.debug("Axis grid on") for tl in axis.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Ticklabels color set") #Draw zones on graph, eg for each lap if xzones is not None: logging.debug("Setting xzones") for xzone in xzones: if xzones.index(xzone) % 2: zonecolor = 'b' else: zonecolor = 'g' axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor) maxX = max(xvalues[i]) if i >= 1: ax2 = axis.twinx() logging.debug("Axis2: Axis: %s" % str(ax2)) ax2.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis2: plotted") for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Axis2: Ticklabels color set") maxXt = max(xvalues[i]) if maxXt > maxX: maxX = maxXt axis.set_xlabel(xlabel[i]) logging.debug("X label set") i += 1 axis.set_xlim(0, maxX) if (len(xvalues) > 1): axis.set_title("%s vs %s" % (ylabel[0], ylabel[1])) else: axis.set_title("%s" % (ylabel[0])) ylim_min, ylim_max = axis.get_ylim() if ylimits is not None: logging.debug("Using ylimits: %s" % str(ylimits)) if ylimits[0] is not None: ylim_min = ylimits[0] if ylimits[1] is not None: ylim_max = ylimits[1] axis.set_ylim(ylim_min, ylim_max) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Canvas: %s" % str(canvas)) canvas.show() self.vbox.pack_start(canvas, True, True) toolbar = NavigationToolbar(canvas, self.window) self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<') return { 'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth }
def drawPie(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None): logging.debug('>>') logging.debug("Type: pie | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = Figure() logging.debug("Figure: %s" % str(figure)) axis = figure.add_subplot(111) labels = [] colors = [] frac0 = 0 frac1 = 0 frac2 = 0 frac3 = 0 frac4 = 0 frac5 = 0 for zone in zones: labels.insert(0, zone[3]) colors.insert(0, zone[2]) labels.insert(0, _("rest")) colors.insert(0, "#ffffff") for value in yvalues[0]: if value <= zones[4][0]: frac0 += 1 elif value > zones[4][0] and value <= zones[4][1]: frac1 += 1 elif value > zones[3][0] and value <= zones[3][1]: frac2 += 1 elif value > zones[2][0] and value <= zones[2][1]: frac3 += 1 elif value > zones[1][0] and value <= zones[1][1]: frac4 += 1 elif value > zones[0][0] and value <= zones[0][1]: frac5 += 1 fracs = [] explode = [] if frac5 == 0: labels.pop(5) colors.pop(5) else: fracs.insert(0, frac5) explode.insert(0, 0) if frac4 == 0: labels.pop(4) colors.pop(4) else: fracs.insert(0, frac4) explode.insert(0, 0) if frac3 == 0: labels.pop(3) colors.pop(3) else: fracs.insert(0, frac3) explode.insert(0, 0) if frac2 == 0: labels.pop(2) colors.pop(2) else: fracs.insert(0, frac2) explode.insert(0, 0) if frac1 == 0: labels.pop(1) colors.pop(1) else: fracs.insert(0, frac1) explode.insert(0, 0) if frac0 == 0: labels.pop(0) colors.pop(0) else: fracs.insert(0, frac0) explode.insert(0, 0) axis.pie(fracs, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) self.vbox.pack_start(canvas, True, True) logging.debug('<<')
def __init__(self, data_file, data_type=2, color_map='jet', plot_label="", time_zone=0, plot_max_freq=30.0, run_quietly=False, save_file='', parent=None, interactive=True): self.data_type = data_type self.data_file = VOAOutFile(data_file, \ time_zone=time_zone, \ data_type=self.data_type) self.image_defs = self.IMG_TYPE_DICT[self.data_type] color_map = eval('P.cm.' + color_map) num_grp = self.data_file.get_number_of_groups() if num_grp < 2: md = gtk.MessageDialog(parent, \ gtk.DIALOG_MODAL,\ gtk.MESSAGE_ERROR, \ gtk.BUTTONS_CANCEL, \ "There must be 2 groups or more") md.run() md.destroy() return plot_groups = range(0, num_grp) self.subplots = [] number_of_subplots = len(plot_groups) matplotlib.rcParams['axes.edgecolor'] = 'gray' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['axes.grid'] = True matplotlib.rcParams['figure.facecolor'] = 'white' matplotlib.rcParams['legend.fancybox'] = True matplotlib.rcParams['legend.shadow'] = True matplotlib.rcParams['figure.subplot.hspace'] = 0.45 matplotlib.rcParams['figure.subplot.wspace'] = 0.35 matplotlib.rcParams['figure.subplot.right'] = 0.85 colorbar_fontsize = 12 self.main_title_fontsize = 24 matplotlib.rcParams['legend.fontsize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 10 matplotlib.rcParams['ytick.labelsize'] = 10 self.x_axes_ticks = P.arange(0, 25, 2) self.fig = plt.figure() ax = Axes3D(self.fig) X = P.arange(0, 25) Y = P.arange(0, len(plot_groups)) X, Y = np.meshgrid(X, Y) data_buffer = [] # hold the Z data sets for chan_grp in plot_groups: (group_name, group_info, fot, muf, hpf, image_buffer) = \ self.data_file.get_group_data(chan_grp) # Copy the element at [0] to the tail of the array #to 'wrap-around' the values at 24hrs. np.resize(muf, len(muf) + 1) muf[-1] = muf[0] data_buffer.append(muf) Z = np.vstack((tuple(data_buffer))) # set up the titles and labels ax.set_xticks(P.arange(0, 25, 2)) if (plot_max_freq == self.AUTOSCALE): z_max = math.ceil(max(muf) / 5.0) * 5.0 z_max = min(plot_max_freq, 30.0) z_max = max(plot_max_freq, 5.0) else: z_max = math.ceil(plot_max_freq / 5.0) * 5.0 z_ticks = [2, 5] for z_tick_value in P.arange(10, z_max + 1, 5): z_ticks.append(z_tick_value) #ax.set_yticks(z_ticks) #label axes tz_sign = '+' if (time_zone >= 0) else '' self.x_label = ax.set_xlabel('Time (UTC%s%s)' % (tz_sign, time_zone)) self.y_label = ax.set_ylabel('Group') self.z_label = ax.set_zlabel('Frequency (MHz)') #do the plot ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('jet')) if interactive: plt.show() else: canvas = FigureCanvasGTKAgg(self.fig) canvas.show() VOAPlotWindow('pythonProp - ' + self.image_defs['title'], \ canvas, \ parent) return
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 setup: def __init__(self,chanlocs=None,chanlabels=None,result_handler=None): self.builder = gtk.Builder() self.builder.add_from_file(os.path.splitext(__file__)[0]+".glade") self.window = self.builder.get_object("window") self.statusbar = self.builder.get_object("statusbar") self.statusbar_cid = self.statusbar.get_context_id("") try: self.data = chanlocs; self.chanlabels = chanlabels; self.result_handler = result_handler except: pass dic = { #"on_auto_select_toggled" : self.test, "on_selection": self.selection_made, "showpopupmenu" : self.showpopupmenu, "on_select_toggled" : self.select_toggled, #"on_checked_toggled" : self.select_checked, "on_view_label_toggle" : self.view_label_toggled, "on_apply_clicked" : self.apply_selection, } self.builder.connect_signals(dic) self.create_draw_frame(None) self.channel_tree(None) def select_toggled(self,widget): print 'wid stat',widget.get_active() liststore,iter = self.View.get_selection().get_selected_rows() if widget.get_active() == True: for i in iter: print i liststore[i][2] = True x = liststore[i][0] self.axes.scatter(self.data[1,x],self.data[0,x],marker='o',color='r') else: for i in iter: print i liststore[i][2] = False x = liststore[i][0] self.axes.scatter(self.data[1,x],self.data[0,x],marker='o') self.canvas.draw() self.get_checked_channels() def get_checked_channels(self): liststore = self.View.get_model() self.chanchecked = [] #index to checked channels for i in liststore: if i[2] == True: self.chanchecked = append(self.chanchecked,i[0]) self.statusbar.push(self.statusbar_cid, 'Number of channels checked: '+str(len(self.chanchecked))) def channel_tree(self,widget): print('updating list') self.View = self.builder.get_object("treeview1") self.dataList = gtk.ListStore(int,str,gobject.TYPE_BOOLEAN) self.AddListColumn('Number', 0, self.View) self.AddListColumn('Label', 1, self.View) self.AddBoolColumn('Select', 2, self.View) self.numchannels=np.size(self.data,1)#300 for k in range(0,self.numchannels): iter = self.dataList.append([k,self.chanlabels[k],k]) self.dataList[k][2] = False self.View.set_model(self.dataList) print 'adding channels' def AddBoolColumn(self, title, columnId, viewtype): self.render = gtk.CellRendererToggle() self.render.set_property('activatable', True) self.render.connect( 'toggled', self.checkit, self.dataList ) column = gtk.TreeViewColumn(title,self.render)#,text=columnId) column.set_resizable(True) column.add_attribute( self.render, "active", 2) column.set_sort_column_id(columnId) viewtype.append_column(column) viewtype.get_selection().set_mode(gtk.SELECTION_MULTIPLE) def checkit(self,cell,path,model): model[path][2] = not model[path][2] print "Toggle '%s' to: %s" % (model[path][1], model[path][2],) if model[path][2] == True: x = model[path][0] self.axes.scatter(self.data[1,x],self.data[0,x],marker='o',color='r') self.canvas.draw() self.get_checked_channels() def AddListColumn(self, title, columnId, viewtype): column = gtk.TreeViewColumn(title,gtk.CellRendererText(),text=columnId) column.set_resizable(True) column.set_sort_column_id(columnId) viewtype.append_column(column) viewtype.get_selection().set_mode(gtk.SELECTION_MULTIPLE) def selection_made(self,widget): liststore,iter = self.View.get_selection().get_selected_rows() self.channels_selected = []; for i in iter: x = liststore[i][0] self.channels_selected.append(int(liststore[i][0])) #index to channels selected. if liststore[i][2] == False: scat = self.axes.scatter(self.data[1,x],self.data[0,x],marker='o',color='magenta') try: for j in self.previter: if liststore[(j,)][2] == False: x = liststore[(j,)][0] scat = self.axes.scatter(self.data[1,x],self.data[0,x],marker='o') except AttributeError: print 'first click skip' pass self.previter = copy(iter) #print 'prev',type(self.previter),self.previter self.canvas.draw() self.statusbar.push(self.statusbar_cid, 'Number of channels selected: '+str(len(self.channels_selected))) def view_label_toggled(self,widget): liststore = self.View.get_model() if widget.get_active() == True: for i in liststore: xy = i[0] label = i[1] self.axes.text(self.data[1,xy],self.data[0,xy],label,fontsize=7) else: pass self.canvas.draw() def create_draw_frame(self,widget): self.fig = Figure(figsize=[200,200], dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.show() self.figure = self.canvas.figure self.axes = self.fig.add_axes([0, 0, 1, 1], axisbg='#FFFFCC') self.axes.axis('off') self.vb = self.builder.get_object("viewport1") self.vb.add(self.canvas) self.vb.show() self.axes.scatter(self.data[1],self.data[0],marker='o');#,facecolors='none'); def showpopupmenu(self,widget,event): print('button ',event.button) if event.button == 3: m = self.builder.get_object("menufunctions") print(widget, event) m.show_all() m.popup(None,None,None,3,0) if event.button == 1: ap = self.axes.get_position() x,y = self.canvas.get_width_height() posx = (event.x/x-.5)*(1/(ap.x1-ap.x0))*-1 posy = ((event.y/y-.5)*(1/(ap.y0-ap.y1))) #posx = ((event.x/x)-ap.x0)*(1/(ap.x1-ap.x0)) #posy = ((event.y/y)-(1-ap.y0))*(1/(ap.y0-ap.y1)) print posx,posy from meg import nearest nx=nearest.nearest(self.data[0],posy)[0] ny=nearest.nearest(self.data[1],posx)[0] print nx,ny def apply_selection(self, widget): print 'Number of channels applied:',size(self.chanchecked,0) self.result_handler(self.chanchecked) return self.chanchecked
def compare_states(self, widget): crimes = [ "MURDER", "RAPE", "KIDNAPPING.ABDUCTION", "RIOTS", "ROBBERY", "BURGLARY", "DOWRY.DEATHS" ] intyear = int(self.combobox_yearc.get_active_text()) state1_data = self.data.query( 'STATEorUT == @self.combobox_state1.get_active_text() and YEAR == @intyear' ).filter(items=[ 'STATEorUT', 'DISTRICT', 'YEAR', crimes[0], crimes[1], crimes[2], crimes[3], crimes[4], crimes[5], crimes[6] ])[self.data.DISTRICT == 'TOTAL'] state2_data = self.data.query( 'STATEorUT == @self.combobox_state2.get_active_text() and YEAR == @intyear' ).filter(items=[ 'STATEorUT', 'DISTRICT', 'YEAR', crimes[0], crimes[1], crimes[2], crimes[3], crimes[4], crimes[5], crimes[6] ])[self.data.DISTRICT == 'TOTAL'] print(state1_data.iloc[0]['MURDER']) state1_total = [ state1_data.iloc[0][crimes[0]], state1_data.iloc[0][crimes[1]], state1_data.iloc[0][crimes[2]], state1_data.iloc[0][crimes[3]], state1_data.iloc[0][crimes[4]], state1_data.iloc[0][crimes[5]], state1_data.iloc[0][crimes[6]] ] state2_total = [ state2_data.iloc[0][crimes[0]], state2_data.iloc[0][crimes[1]], state2_data.iloc[0][crimes[2]], state2_data.iloc[0][crimes[3]], state2_data.iloc[0][crimes[4]], state2_data.iloc[0][crimes[5]], state2_data.iloc[0][crimes[6]] ] print(state1_total) dialog = gtk.Dialog("My dialog", self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) fig = Figure(figsize=(5, 4), dpi=100) dialog.set_size_request(1300, 500) ax = fig.add_subplot(111) ypos = np.arange(len(crimes)) print(ypos) p1 = ax.bar(ypos - 0.4, state1_total, width=0.4, color='r', align='center') p2 = ax.bar(ypos, state2_total, width=0.4, color='b', align='center') ax.set_title("Comparison of " + self.combobox_state1.get_active_text() + " and " + self.combobox_state2.get_active_text()) ax.set_xticks(ypos - 0.2) ax.set_xticklabels(crimes) ax.set_ylabel('Total Crimes') ax.legend((p1[0], p2[0]), (self.combobox_state1.get_active_text(), self.combobox_state2.get_active_text())) canvas = FigureCanvas(fig) # a gtk.DrawingArea canvas.set_size_request(800, 600) dialog.vbox.pack_start(canvas) toolbar = NavigationToolbar(canvas, dialog) dialog.vbox.pack_start(toolbar, False, False) canvas.show() dialog.run() dialog.destroy() return
def draw(self, datalist=None, box=None, figure=None, title=None, y2=False, xgrid=False, ygrid=False): ''' Draw a graph using supplied information into supplied gtk.box datalist = populated graphdata class (required) box = gtk.box object (required) figure = matplotlib figure (optional) if supplied will add graph to this figure title = y2 = return = figure ''' logging.debug('>>') if box is None: logging.error("Must supply a vbox or hbox to display the graph") return #Check if have a graph object if figure is None: #No figure, so create figure figure = plt.figure() self.ax1 = plt.axes() #Reset second axis self.ax2 = None #Remove any existing plots for child in box.get_children(): logging.debug('Removing box child: ' + str(child)) box.remove(child) if datalist is None: logging.debug("drawPlot called with no data") return figure if y2 and self.ax2 is None: self.ax2 = plt.twinx() #Create canvas canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() #Display title etc if datalist.xlabel is not None: plt.xlabel(datalist.xlabel) if title is not None: plt.title(title) #Display grid if y2 and ygrid: self.ax2.grid(True) elif self.ax1 and ygrid: self.ax1.grid(True) plt.gca().xaxis.grid(xgrid) #Removed as now in legend #plt.ylabel(datalist.ylabel) #Determine graph type.... #print "Got graphtype: %s" % datalist.graphType #print datalist.x_values #print datalist.y_values #print datalist.linewidth #print datalist.linecolor #print datalist.ylabel if datalist.graphType == "plot": #Plot data if not y2: #plt.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.linecolor, label=datalist.ylabel ) self.ax1.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.linecolor, label=datalist.ylabel) else: self.ax2.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.y2linecolor, label=datalist.ylabel) elif datalist.graphType == "bar": if not y2: self.ax1.bar(datalist.x_values, datalist.y_values, datalist.bar_widths, datalist.bar_bottoms, color=datalist.linecolor, label=datalist.ylabel, alpha=0.5) else: self.ax2.bar(datalist.x_values, datalist.y_values, datalist.bar_widths, datalist.bar_bottoms, color=datalist.y2linecolor, label=datalist.ylabel, alpha=0.5) elif datalist.graphType == "vspan": i = 0 while i < len(datalist.x_values): #print datalist.x_values[i] , datalist.bar_widths[i] if not y2: self.ax1.axvspan(datalist.x_values[i], datalist.x_values[i] + datalist.bar_widths[i], alpha=0.15, facecolor=datalist.linecolor) else: self.ax2.axvspan(datalist.x_values[i], datalist.x_values[i] + datalist.bar_widths[i], alpha=0.15, facecolor=datalist.y2linecolor) i += 1 elif datalist.graphType == "hspan": i = 0 while i < len(datalist.x_values): #print datalist.x_values[i] , datalist.y_values[i], datalist.labels[i], datalist.colors[i] if not y2: self.ax1.axhspan(datalist.x_values[i], datalist.y_values[i], alpha=0.25, facecolor=datalist.colors[i], label=datalist.labels[i]) else: self.ax2.axhspan(datalist.x_values[i], datalist.y_values[i], alpha=0.25, facecolor=datalist.colors[i], label=datalist.labels[i]) i += 1 elif datalist.graphType == "date": if not y2: self.ax1.plot_date(datalist.x_values, datalist.y_values, color=datalist.linecolor, label=datalist.ylabel, alpha=0.5) else: self.ax2.plot_date(datalist.x_values, datalist.y_values, color=datalist.y2linecolor, label=datalist.ylabel, alpha=0.5) else: print "Unknown/unimplemented graph type: %s" % datalist.graphType return figure #Set axis limits #plt.axis([datalist.min_x_value, datalist.max_x_value, datalist.min_y_value, datalist.max_y_value]) if self.ax1 is not None: self.ax1.legend(loc='upper left', bbox_to_anchor=(0, 1)) if self.ax2 is not None: self.ax2.legend(loc='upper right', bbox_to_anchor=(1, 1)) #axis.set_xlim(0, data.max_x_value) #axis.set_ylim(0, data.max_y_value) #Display plot box.pack_start(canvas, True, True) logging.debug("<<") return figure
class Figure(gtk.VBox): def __init__(self): print "Starting up SamFigure!" gtk.VBox.__init__(self) self.figure = MPLFigure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect("button_press_event", self.on_click) self.ax = self.figure.add_subplot(111) self.ax2 = None self.mode = TWODPLOT self.new_data() self.xlabel = '' self.y1label = '' self.y2label = '' self.xsize = 0 self.ysize = 0 self.packed = False self.count_since_replot = 0 self.set_colors() def on_click(self, event): # If left button, if event.button == 1: # screen coordinates of click xclick, yclick = event.x, event.y top_ax = event.inaxes if top_ax is None: return # display coordinates of nearest point in ax data1=self.ax.transData.transform(\ zip(self.listing.getX(),self.listing.getY(1))) distances1=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data1] ind_sel1 = numpy.argmin(distances1) dist1 = distances1[ind_sel1] xsel, ysel = data1[ind_sel1] label_ax = self.ax label_color = 'b' # if DUAL, then also check ax2 for nearer points if self.mode == DUALTWODPLOT: data2=self.ax2.transData.transform(\ zip(self.listing.getX(),self.listing.getY(2))) distances2=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data2] ind_sel2 = numpy.argmin(distances2) dist2 = distances2[ind_sel2] if dist2 < dist1: xsel, ysel = data2[ind_sel2] label_color = 'g' label_ax = self.ax2 # Clear off old labels if hasattr(self, "label_text"): self.label_text.remove() self.label_point.remove() del (self.label_text) # Coordinates to show ( data coordinates of the selected axes) xlabel, ylabel = label_ax.transData.inverted().transform( (xsel, ysel)) # Coordinates to place label (on top set of axes) xloc, yloc = top_ax.transData.inverted().transform((xsel, ysel)) # Label the point if (xloc > sum(self.ax.get_xlim()) / 2): h_align = 'right' else: h_align = 'left' self.label_text=\ top_ax.text(xloc,yloc,'({0:.3g},{1:.3g})'\ .format(xlabel,ylabel),\ backgroundcolor='white', color=label_color,\ verticalalignment='bottom', horizontalalignment=h_align,\ bbox={'facecolor': 'white', 'boxstyle': 'round'},zorder=100 ) self.label_point,=\ top_ax.plot(xloc,yloc,'ro',\ zorder=self.label_text.get_zorder()+1) self.repaint() # Otherwise, just clear off old labels else: self.label_text.remove() self.label_point.remove() del (self.label_text) self.repaint() def replot(self): if self.mode == TWODPLOT: self.ax.clear() self.ax.plot(self.listing.getX(), self.listing.getY(1), self.color1 + '.-') self.count_since_replot = 0 elif self.mode == DUALTWODPLOT: self.ax.clear() self.ax2.clear() self.ax.plot(self.listing.getX(), self.listing.getY(1), self.color1 + '.-') self.ax2.plot(self.listing.getX(), self.listing.getY(2), self.color2 + '.-') self.count_since_replot = 0 def show(self): try: if not self.packed: self.pack_start(self.canvas, expand=True) toolbar = NavigationToolbar(self.canvas, self.get_parent_window()) next = 8 button = gtk.Button('Lin y') button.show() button2 = gtk.Button('Lin x') button2.show() # linear/log def clicked(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_yscale() == 'log': button.set_label('Lin y') self.ax.set_yscale('linear') else: button.set_label('Log y') self.ax.set_yscale('log') self.show() def clicked2(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_xscale() == 'log': button.set_label('Lin x') self.ax.set_xscale('linear') else: button.set_label('Log x') self.ax.set_xscale('log') self.show() button.connect('clicked', clicked) button2.connect('clicked', clicked2) toolitem = gtk.ToolItem() toolitem.show() toolitem.add(button) toolbar.insert(toolitem, next) next += 1 toolitem2 = gtk.ToolItem() toolitem2.show() toolitem2.add(button2) toolbar.insert(toolitem2, next) self.pack_start(toolbar, expand=False) self.packed = True super(Figure, self).show() except Exception, e: print 'Exception: ', e raise
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 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 GUI(object): """ main class which opens the actual GUI """ def __init__(self): ########################################################################################### # read in settings file from XChemExplorer to set the relevant paths self.settings = pickle.load(open(".xce_settings.pkl", "rb")) remote_qsub_submission = self.settings['remote_qsub'] self.database_directory = self.settings['database_directory'] self.xce_logfile = self.settings['xce_logfile'] self.Logfile = XChemLog.updateLog(self.xce_logfile) self.Logfile.insert('starting COOT gui for reference model refinement') self.data_source = self.settings['data_source'] # checking for external software packages self.external_software = XChemUtils.external_software( self.xce_logfile).check() self.external_software['qsub_remote'] = remote_qsub_submission # the Folder is kind of a legacy thing because my inital idea was to have separate folders # for Data Processing and Refinement self.reference_directory = self.settings['reference_directory'] self.refinementDir = '' self.Serial = 0 self.Refine = None self.xtalID = '' self.compoundID = '' self.spider_plot = '' self.refinement_folder = '' self.pdbFile = '' self.mtzFree = '' self.pdb_style = 'refine.pdb' self.mtz_style = 'refine.mtz' # stores imol of currently loaded molecules and maps self.mol_dict = { 'protein': -1, 'ligand': -1, '2fofc': -1, 'fofc': -1, 'event': -1 } self.ground_state_map_List = [] self.job_running = False ########################################################################################### # some COOT settings coot.set_map_radius(17) coot.set_colour_map_rotation_for_map(0) # coot.set_colour_map_rotation_on_read_pdb_flag(21) self.QualityIndicators = { 'Rcryst': '-', 'Rfree': '-', 'RfreeTL': 'gray', 'ResolutionHigh': '-', 'ResolutionColor': 'gray', 'MolprobityScore': '-', 'MolprobityScoreColor': 'gray', 'RamachandranOutliers': '-', 'RamachandranOutliersColor': 'gray', 'RamachandranFavored': '-', 'RamachandranFavoredColor': 'gray', 'rmsdBonds': '-', 'rmsdBondsTL': 'gray', 'rmsdAngles': '-', 'rmsdAnglesTL': 'gray', 'MatrixWeight': '-' } # default refmac parameters self.RefmacParams = { 'HKLIN': '', 'HKLOUT': '', 'XYZIN': '', 'XYZOUT': '', 'LIBIN': '', 'LIBOUT': '', 'TLSIN': '', 'TLSOUT': '', 'TLSADD': '', 'NCYCLES': '10', 'MATRIX_WEIGHT': 'AUTO', 'BREF': ' bref ISOT\n', 'TLS': '', 'NCS': '', 'TWIN': '' } def StartGUI(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("delete_event", gtk.main_quit) self.window.set_border_width(10) self.window.set_default_size(400, 800) self.window.set_title("Reference Model Builder") self.vbox = gtk.VBox() # this is the main container ################################################################################# # --- PDB file selection --- # checking for pdb files in reference directory referenceFiles = [] for files in glob.glob( os.path.join(self.reference_directory, '*-ground-state.pdb')): pdbFile = files[files.rfind('/') + 1:] referenceFiles.append(pdbFile) frame = gtk.Frame(label='Select PDB file') hbox = gtk.HBox() self.cb_select_pdb = gtk.combo_box_new_text() # self.cb_select_pdb.connect("changed", self.set_selection_mode) for pdbFile in referenceFiles: self.cb_select_pdb.append_text(pdbFile) hbox.add(self.cb_select_pdb) frame.add(hbox) self.vbox.pack_start(frame) self.load_pdb_file_button = gtk.Button(label="Load") # self.load_pdb_file_button.connect("clicked",self.get_samples_to_look_at) self.load_pdb_file_button.connect("clicked", self.load_pdb_file) hbox.add(self.load_pdb_file_button) frame.add(hbox) self.vbox.pack_start(frame) # SPACER self.vbox.add(gtk.Label(' ')) frame = gtk.Frame(label='MTZ file to refine against') hbox = gtk.HBox() self.mtzFree = '' self.mtzFree_label = gtk.Label() hbox.add(self.mtzFree_label) frame.add(hbox) self.vbox.pack_start(frame) # SPACER self.vbox.add(gtk.Label(' ')) frame = gtk.Frame(label='MTZ file after refinement') hbox = gtk.HBox() self.mtzRefine_label = gtk.Label() hbox.add(self.mtzRefine_label) frame.add(hbox) self.vbox.pack_start(frame) # SPACER self.vbox.add(gtk.Label(' \n ')) ################################################################################# # --- ground state mean map --- # checking for ground state mean map in reference folder # self.meanMaps = {} # for dirs in glob.glob(os.path.join(self.reference_directory,'pandda_*')): # panddaDir=dirs.split('/')[len(dirs.split('/'))-1] # for files in glob.glob(os.path.join(dirs,'processed_datasets','*','*ground-state-mean-map.native.ccp4')): # if os.path.isfile(files): # self.meanMaps[panddaDir]=files # break # frame = gtk.Frame(label='Load ground-state-mean-map files') # hbox=gtk.HBox() # self.cb_select_mean_map = gtk.combo_box_new_text() # for item in self.meanMaps: # self.cb_select_mean_map.append_text(item) # hbox.add(self.cb_select_mean_map) # self.load_ground_state_map_button = gtk.Button(label="Load") # self.load_ground_state_map_button.connect("clicked",self.load_ground_state_map) # hbox.add(self.load_ground_state_map_button) # frame.add(hbox) # self.vbox.pack_start(frame) # frame = gtk.Frame() # hbox=gtk.HBox() # self.cb_select_mean_map_by_resolution = gtk.combo_box_new_text() # self.cb_select_mean_map_by_resolution.connect("changed", self.show_selected_mean_map) # hbox.add(self.cb_select_mean_map_by_resolution) ## self.show_highres_ground_state_map_button = gtk.Button(label="Show Highest\nResolution Map") ## self.show_highres_ground_state_map_button.connect("clicked",self.show_highres_ground_state_map) ## hbox.add(self.show_highres_ground_state_map_button) ## self.show_all_ground_state_map_button = gtk.Button(label="Show All Maps") ## self.show_all_ground_state_map_button.connect("clicked",self.show_all_ground_state_map) ## hbox.add(self.show_all_ground_state_map_button) # frame.add(hbox) # self.vbox.pack_start(frame) # SPACER # self.vbox.add(gtk.Label(' \n ')) ################################################################################# # --- Refinement History --- frame = gtk.Frame(label='Refinement History') self.hbox_for_info_graphics = gtk.HBox() self.canvas = FigureCanvas(self.update_plot([0], [0], [0])) self.canvas.set_size_request(190, 190) self.hbox_for_info_graphics.add(self.canvas) frame.add(self.hbox_for_info_graphics) self.vbox.pack_start(frame) ################################################################################# # --- status window --- frame = gtk.Frame(label='Status') vbox = gtk.VBox() self.spinnerBox = gtk.VBox() self.refinementRunning = gtk.Spinner() vbox.add(self.spinnerBox) # hbox.add(self.refinementRunning) self.status_label = gtk.Label() vbox.add(self.status_label) frame.add(vbox) self.status_label.set_text('idle') # frame.add(self.status_label) self.vbox.pack_start(frame) ################################################################################# # --- Refinement Statistics --- # next comes a section which displays some global quality indicators # a combination of labels and textview widgets, arranged in a table RRfreeLabel_frame = gtk.Frame() self.RRfreeLabel = gtk.Label('R/Rfree') RRfreeLabel_frame.add(self.RRfreeLabel) self.RRfreeValue = gtk.Label(self.QualityIndicators['Rcryst'] + '/' + self.QualityIndicators['Rfree']) RRfreeBox_frame = gtk.Frame() self.RRfreeBox = gtk.EventBox() self.RRfreeBox.add(self.RRfreeValue) RRfreeBox_frame.add(self.RRfreeBox) ResolutionLabel_frame = gtk.Frame() self.ResolutionLabel = gtk.Label('Resolution') ResolutionLabel_frame.add(self.ResolutionLabel) self.ResolutionValue = gtk.Label( self.QualityIndicators['ResolutionHigh']) ResolutionBox_frame = gtk.Frame() self.ResolutionBox = gtk.EventBox() self.ResolutionBox.add(self.ResolutionValue) ResolutionBox_frame.add(self.ResolutionBox) MolprobityScoreLabel_frame = gtk.Frame() self.MolprobityScoreLabel = gtk.Label('MolprobityScore') MolprobityScoreLabel_frame.add(self.MolprobityScoreLabel) self.MolprobityScoreValue = gtk.Label( self.QualityIndicators['MolprobityScore']) MolprobityScoreBox_frame = gtk.Frame() self.MolprobityScoreBox = gtk.EventBox() self.MolprobityScoreBox.add(self.MolprobityScoreValue) MolprobityScoreBox_frame.add(self.MolprobityScoreBox) RamachandranOutliersLabel_frame = gtk.Frame() self.RamachandranOutliersLabel = gtk.Label('Rama Outliers') RamachandranOutliersLabel_frame.add(self.RamachandranOutliersLabel) self.RamachandranOutliersValue = gtk.Label( self.QualityIndicators['RamachandranOutliers']) RamachandranOutliersBox_frame = gtk.Frame() self.RamachandranOutliersBox = gtk.EventBox() self.RamachandranOutliersBox.add(self.RamachandranOutliersValue) RamachandranOutliersBox_frame.add(self.RamachandranOutliersBox) RamachandranFavoredLabel_frame = gtk.Frame() self.RamachandranFavoredLabel = gtk.Label('Rama Favored') RamachandranFavoredLabel_frame.add(self.RamachandranFavoredLabel) self.RamachandranFavoredValue = gtk.Label( self.QualityIndicators['RamachandranFavoredColor']) RamachandranFavoredBox_frame = gtk.Frame() self.RamachandranFavoredBox = gtk.EventBox() self.RamachandranFavoredBox.add(self.RamachandranFavoredValue) RamachandranFavoredBox_frame.add(self.RamachandranFavoredBox) rmsdBondsLabel_frame = gtk.Frame() self.rmsdBondsLabel = gtk.Label('rmsd(Bonds)') rmsdBondsLabel_frame.add(self.rmsdBondsLabel) self.rmsdBondsValue = gtk.Label(self.QualityIndicators['rmsdBonds']) rmsdBondsBox_frame = gtk.Frame() self.rmsdBondsBox = gtk.EventBox() self.rmsdBondsBox.add(self.rmsdBondsValue) rmsdBondsBox_frame.add(self.rmsdBondsBox) rmsdAnglesLabel_frame = gtk.Frame() self.rmsdAnglesLabel = gtk.Label('rmsd(Angles)') rmsdAnglesLabel_frame.add(self.rmsdAnglesLabel) self.rmsdAnglesValue = gtk.Label(self.QualityIndicators['rmsdAngles']) rmsdAnglesBox_frame = gtk.Frame() self.rmsdAnglesBox = gtk.EventBox() self.rmsdAnglesBox.add(self.rmsdAnglesValue) rmsdAnglesBox_frame.add(self.rmsdAnglesBox) MatrixWeightLabel_frame = gtk.Frame() self.MatrixWeightLabel = gtk.Label('Matrix Weight') MatrixWeightLabel_frame.add(self.MatrixWeightLabel) self.MatrixWeightValue = gtk.Label( self.QualityIndicators['MatrixWeight']) MatrixWeightBox_frame = gtk.Frame() self.MatrixWeightBox = gtk.EventBox() self.MatrixWeightBox.add(self.MatrixWeightValue) MatrixWeightBox_frame.add(self.MatrixWeightBox) outer_frame = gtk.Frame() hbox = gtk.HBox() frame = gtk.Frame() self.table_left = gtk.Table(8, 2, False) self.table_left.attach(RRfreeLabel_frame, 0, 1, 0, 1) self.table_left.attach(ResolutionLabel_frame, 0, 1, 1, 2) self.table_left.attach(MolprobityScoreLabel_frame, 0, 1, 2, 3) self.table_left.attach(RamachandranOutliersLabel_frame, 0, 1, 3, 4) self.table_left.attach(RamachandranFavoredLabel_frame, 0, 1, 4, 5) self.table_left.attach(rmsdBondsLabel_frame, 0, 1, 5, 6) self.table_left.attach(rmsdAnglesLabel_frame, 0, 1, 6, 7) self.table_left.attach(MatrixWeightLabel_frame, 0, 1, 7, 8) self.table_left.attach(RRfreeBox_frame, 1, 2, 0, 1) self.table_left.attach(ResolutionBox_frame, 1, 2, 1, 2) self.table_left.attach(MolprobityScoreBox_frame, 1, 2, 2, 3) self.table_left.attach(RamachandranOutliersBox_frame, 1, 2, 3, 4) self.table_left.attach(RamachandranFavoredBox_frame, 1, 2, 4, 5) self.table_left.attach(rmsdBondsBox_frame, 1, 2, 5, 6) self.table_left.attach(rmsdAnglesBox_frame, 1, 2, 6, 7) self.table_left.attach(MatrixWeightBox_frame, 1, 2, 7, 8) frame.add(self.table_left) hbox.add(frame) outer_frame.add(hbox) self.vbox.add(outer_frame) button = gtk.Button(label="Show MolProbity to-do list") button.connect("clicked", self.show_molprobity_to_do) self.vbox.add(button) self.vbox.pack_start(frame) # SPACER self.vbox.add(gtk.Label(' ')) # --- refinement & options --- self.hbox_for_refinement = gtk.HBox() self.REFINEbutton = gtk.Button(label="Refine") self.RefinementParamsButton = gtk.Button(label="refinement parameters") self.REFINEbutton.connect("clicked", self.REFINE) self.hbox_for_refinement.add(self.REFINEbutton) self.RefinementParamsButton.connect("clicked", self.RefinementParams) self.hbox_for_refinement.add(self.RefinementParamsButton) self.vbox.add(self.hbox_for_refinement) # --- CANCEL button --- self.CANCELbutton = gtk.Button(label="CANCEL") self.CANCELbutton.connect("clicked", self.CANCEL) self.vbox.add(self.CANCELbutton) self.window.add(self.vbox) self.window.show_all() def CANCEL(self, widget): self.window.destroy() def RefreshData(self): # initialize Refinement library self.Refine = XChemRefine.Refine(self.reference_directory, self.refinementDir, 'dummy_compound_ID', 'dummy_database') self.Serial = self.Refine.GetSerial() print '====> Serial', self.Serial ######################################################################################### # history # if the structure was previously refined, try to read the parameters self.hbox_for_info_graphics.remove(self.canvas) if self.Serial > 1: self.RefmacParams = self.Refine.ParamsFromPreviousCycle( self.Serial - 1) refinement_cycle, Rfree, Rcryst = self.Refine.GetRefinementHistory( ) self.canvas = FigureCanvas( self.update_plot(refinement_cycle, Rfree, Rcryst)) else: self.canvas = FigureCanvas(self.update_plot( [0], [0], [0])) # a gtk.DrawingArea self.canvas.set_size_request(190, 190) self.hbox_for_info_graphics.add(self.canvas) self.canvas.show() ######################################################################################### # update Quality Indicator table print self.QualityIndicators try: self.RRfreeValue.set_label( str(round(float(self.QualityIndicators['Rcryst']), 3)) + ' / ' + str(round(float(self.QualityIndicators['Rfree']), 3))) except ValueError: self.RRfreeValue.set_label('-') try: self.RRfreeBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse(self.QualityIndicators['RfreeTL'])) except ValueError: pass self.ResolutionValue.set_label( self.QualityIndicators['ResolutionHigh']) try: self.ResolutionBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse(self.QualityIndicators['ResolutionColor'])) except ValueError: pass self.MolprobityScoreValue.set_label( self.QualityIndicators['MolprobityScore']) try: self.MolprobityScoreBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse( self.QualityIndicators['MolprobityScoreColor'])) except ValueError: pass self.RamachandranOutliersValue.set_label( self.QualityIndicators['RamachandranOutliers']) try: self.RamachandranOutliersBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse( self.QualityIndicators['RamachandranOutliersColor'])) except ValueError: pass self.RamachandranFavoredValue.set_label( self.QualityIndicators['RamachandranFavored']) try: self.RamachandranFavoredBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse( self.QualityIndicators['RamachandranFavoredColor'])) except ValueError: pass self.rmsdBondsValue.set_label(self.QualityIndicators['rmsdBonds']) try: self.rmsdBondsBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse(self.QualityIndicators['rmsdBondsTL'])) except ValueError: pass self.rmsdAnglesValue.set_label(self.QualityIndicators['rmsdAngles']) try: self.rmsdAnglesBox.modify_bg( gtk.STATE_NORMAL, gtk.gdk.color_parse(self.QualityIndicators['rmsdAnglesTL'])) except ValueError: pass self.MatrixWeightValue.set_label( self.QualityIndicators['MatrixWeight']) def REFINE(self, widget): if self.job_running: coot.info_dialog('*** refinement in progress ***') return None ####################################################### # create folder for new refinement cycle and check if free.mtz exists if not os.path.isdir( os.path.join(self.reference_directory, self.refinementDir)): os.mkdir(os.path.join(self.reference_directory, self.refinementDir)) if not os.path.isdir( os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial))): os.mkdir( os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial))) if not os.path.isfile( os.path.join(self.reference_directory, self.refinementDir, self.refinementDir + '.free.mtz')): os.chdir(os.path.join(self.reference_directory, self.refinementDir)) os.symlink(self.mtzFree, self.refinementDir + '.free.mtz') ####################################################### # write PDB file # now take protein pdb file and write it to newly create Refine_<serial> folder # note: the user has to make sure that the ligand file was merged into main file for item in coot_utils_XChem.molecule_number_list(): if coot.molecule_name(item) in self.pdbFile: coot.write_pdb_file( item, os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial), 'in.pdb')) break self.Refine.RunRefmac(self.Serial, self.RefmacParams, self.external_software, self.xce_logfile) # self.spinnerBox.add(self.refinementRunning) # self.refinementRunning.start() self.status_label.set_text('Refinement running...') time.sleep( 1 ) # waiting 1s to make sure that REFINEMENT_IN_PROGRESS is written snooze = 0 while os.path.exists( os.path.join(self.reference_directory, self.refinementDir, 'REFINEMENT_IN_PROGRESS')): time.sleep(10) print '==> XCE: waiting for refinement to finish; elapsed time = ' + str( snooze) + 's' snooze += 10 self.update_pdb_mtz_files('') # launch refinement # time.sleep(1) # waiting 1s to make sure that REFINEMENT_IN_PROGRESS is written # self.source_id = gobject.timeout_add(100, self.wait_for_refined_pdb) # def wait_for_refined_pdb(self): # self.spinnerBox.add(self.refinementRunning) # self.refinementRunning.show() # self.refinementRunning.start() # if not os.path.isfile(os.path.join(self.reference_directory,self.refinementDir,'REFINEMENT_IN_PROGRESS')): # self.job_running=False # self.end_thread('update_pdb_mtz') # return True # def end_thread(self,action): # self.refinementRunning.stop() # self.spinnerBox.remove(self.refinementRunning) # self.status_label.set_text('idle') # gobject.source_remove(self.source_id) # if action=='update_pdb_mtz': # self.update_pdb_mtz_files('') def RefinementParams(self, widget): print '\n==> XCE: changing refinement parameters' self.RefmacParams = self.Refine.RefinementParams(self.RefmacParams) def set_selection_mode(self, widget): self.selection_mode = widget.get_active_text() def load_pdb_file(self, widget): pdbRoot = self.cb_select_pdb.get_active_text() if self.pdbFile != '': self.Logfile.error( 'sorry, you need to close the current instance of COOT and start again' ) return None self.refinementDir = pdbRoot.replace('.pdb', '') self.update_pdb_mtz_files(pdbRoot) def update_pdb_mtz_files(self, pdbRoot): # first remove all pdb and mtz files from memory self.Logfile.insert('removing all PDB and MTZ files from memory') if len(coot_utils_XChem.molecule_number_list()) > 0: for item in coot_utils_XChem.molecule_number_list(): if coot.molecule_name(item).endswith( '.pdb') or '.mtz' in coot.molecule_name(item): self.Logfile.insert('removing %s' % coot.molecule_name(item)) coot.close_molecule(item) coot.set_nomenclature_errors_on_read("ignore") # first we check if there is a refinement folder and the respective refine.pdb # from previous refinement cycles Root = self.cb_select_pdb.get_active_text() print 'ROOT', Root print 'REFI_DIR', os.path.join(self.reference_directory, self.refinementDir, 'refine.pdb') if os.path.isfile( os.path.join(self.reference_directory, self.refinementDir, 'refine.pdb')): os.chdir(self.reference_directory) print 'CURRENT DIR', os.getcwd() os.system('/bin/rm %s 2> /dev/null' % Root) os.symlink( os.path.realpath(os.path.join(self.refinementDir, 'refine.pdb')), '%s' % Root) self.pdbFile = os.path.join(self.reference_directory, self.refinementDir, 'refine.pdb') elif os.path.isfile(os.path.join(self.reference_directory, Root)): self.pdbFile = os.path.join(self.reference_directory, Root) else: self.Logfile.error('cannot find PDB file') if self.pdbFile != '': # os.chdir(os.path.join(self.reference_directory,self.refinementDir)) coot.set_colour_map_rotation_on_read_pdb(0) imol = coot.handle_read_draw_molecule_with_recentre( self.pdbFile, 0) self.QualityIndicators = XChemUtils.parse().PDBheader( os.path.join(self.pdbFile)) self.QualityIndicators.update( XChemUtils.logtools( os.path.join(self.reference_directory, self.refinementDir, 'refine_molprobity.log')).phenix_molprobity()) self.QualityIndicators.update( XChemUtils.logtools( os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial), 'refmac.log')).refmac_log()) self.mol_dict['protein'] = imol if self.mtzFree == '': print 'FREE', os.path.join( self.reference_directory, pdbRoot.replace('.pdb', '') + '.free.mtz') if os.path.isfile( os.path.join(self.reference_directory, pdbRoot.replace('.pdb', '') + '.free.mtz')): self.mtzFree = os.path.join( self.reference_directory, pdbRoot.replace('.pdb', '') + '.free.mtz') self.mtzFree_label.set_text( pdbRoot.replace('.pdb', '') + '.free.mtz') self.REFINEbutton.set_sensitive(True) else: self.mtzFree_label.set_text('missing file') self.Logfile.error( 'cannot find file with F,SIGF and FreeR_flag; cannot start refinement' ) self.REFINEbutton.set_sensitive(False) self.mtzRefine = '' if os.path.isfile( os.path.join(self.reference_directory, self.refinementDir, 'refine.mtz')): self.mtzRefine = os.path.join(self.reference_directory, self.refinementDir, 'refine.mtz') mtzRefineReal = os.path.realpath( os.path.join(self.reference_directory, self.refinementDir, 'refine.mtz')) mtzRefineCurrent = mtzRefineReal.replace( os.path.join(self.reference_directory, self.refinementDir + '/'), '') self.mtzRefine_label.set_text(mtzRefineCurrent) coot.set_default_initial_contour_level_for_map(1) if os.path.isfile( os.path.join(self.reference_directory, self.refinementDir, self.mtz_style)): coot.auto_read_make_and_draw_maps( os.path.join(self.reference_directory, self.refinementDir, self.mtz_style)) else: self.mtzRefine_label.set_text('missing file') self.Logfile.warning( 'cannot find file with F,SIGF and FreeR_flag; cannot start refinement' ) groundStateMap = os.path.join(self.reference_directory, Root + '-mean-map.native.ccp4').replace( '.pdb', '') print '===>', groundStateMap if os.path.isfile(groundStateMap): imol = coot.handle_read_ccp4_map(groundStateMap, 0) coot.set_contour_level_in_sigma(imol, 1) coot.set_last_map_colour(0.6, 0.6, 0) else: print '==> XCE: ERROR - cannot find ground state mean map!' self.RefreshData() # def load_ground_state_map(self,widget): # self.spinnerBox.add(self.refinementRunning) # self.refinementRunning.start() # self.status_label.set_text('loading ground state maps by reso...') # self.source_id = gobject.timeout_add(100, self.load_ground_state_map_thread) # def load_ground_state_map_thread(self): # self.spinnerBox.add(self.refinementRunning) # self.refinementRunning.show() # self.refinementRunning.start() # # # first remove all ground state maps files # if len(coot_utils_XChem.molecule_number_list()) > 0: # for item in coot_utils_XChem.molecule_number_list(): # if 'ground-state-mean-map' in coot.molecule_name(item): # coot.close_molecule(item) # # # first remove all entries for self.cb_select_mean_map_by_resolution # # clear CB first, 100 is sort of arbitrary since it's unlikely there will ever be 100 maps # for n in range(-1,100): # self.cb_select_mean_map_by_resolution.remove_text(0) # # self.status_label.set_text('loading ground state maps') # self.get_highest_reso_ground_state_map() # blueStart=0.02 # for map in self.ground_state_map_List: # self.cb_select_mean_map_by_resolution.append_text(map[0]) # imol=coot.handle_read_ccp4_map((map[1]),0) # coot.set_contour_level_in_sigma(imol,1) # coot.set_last_map_colour(0.74,0.44,blueStart) # blueStart+=0.05 # # show only highest resolution map to start with # self.show_highres_ground_state_map() # self.cb_select_mean_map_by_resolution.set_active(0) # self.end_thread('') # def show_highres_ground_state_map(self): # if len(self.ground_state_map_List) >= 1: # for imol in coot_utils_XChem.molecule_number_list(): # if coot.molecule_name(imol) in self.ground_state_map_List[0][1]: # coot.set_map_displayed(imol,1) # elif 'ground-state-mean-map' in coot.molecule_name(imol): # coot.set_map_displayed(imol,0) # def show_all_ground_state_map(self): # if len(self.ground_state_map_List) >= 1: # for imol in coot_utils_XChem.molecule_number_list(): # if 'ground-state-mean-map' in coot.molecule_name(imol): # coot.set_map_displayed(imol,1) # def show_selected_mean_map(self,widget): # reso=str(self.cb_select_mean_map_by_resolution.get_active_text()) # mapToshow='' # for maps in self.ground_state_map_List: # if maps[0]==reso: # mapToshow=maps[1] # for imol in coot_utils_XChem.molecule_number_list(): # if coot.molecule_name(imol) in mapToshow: # coot.set_map_displayed(imol,1) # elif 'ground-state-mean-map' in coot.molecule_name(imol): # coot.set_map_displayed(imol,0) def show_molprobity_to_do(self, widget): if os.path.isfile( os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial - 1), 'molprobity_coot.py')): coot.run_script( os.path.join(self.reference_directory, self.refinementDir, 'Refine_' + str(self.Serial - 1), 'molprobity_coot.py')) else: print '==> XCE: cannot find ' + os.path.join( self.reference_directory, self.xtalID, 'Refine_' + str(self.Serial - 1), 'molprobity_coot.py') def update_plot(self, refinement_cycle, Rfree, Rcryst): fig = Figure(figsize=(2, 2), dpi=50) Plot = fig.add_subplot(111) Plot.set_ylim([0, max(Rcryst + Rfree)]) Plot.set_xlabel('Refinement Cycle', fontsize=12) Plot.plot(refinement_cycle, Rfree, label='Rfree', linewidth=2) Plot.plot(refinement_cycle, Rcryst, label='Rcryst', linewidth=2) Plot.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0., fontsize=12) return fig def get_ground_state_maps_by_resolution(self): found = False mapList = [] for logFile in glob.glob( os.path.join(self.reference_directory, str(self.cb_select_mean_map.get_active_text()), 'logs', '*.log')): for n, line in enumerate(open(logFile)): if line.startswith( 'Statistical Electron Density Characterisation' ) and len(line.split()) == 6: # try: # resolution=float(line.split()[5]) resolution = line.split()[5] print resolution found = True foundLine = n # except ValueError: # print 'error' # break if found and n == foundLine + 3: xtal = line.split(',')[0].replace(' ', '').replace('\t', '') meanmap = os.path.join( self.reference_directory, self.cb_select_mean_map.get_active_text(), 'processed_datasets', xtal, xtal + '-ground-state-mean-map.native.ccp4') mapList.append([resolution, meanmap]) found = False return mapList def get_highest_reso_ground_state_map(self): mapList = self.get_ground_state_maps_by_resolution() print mapList self.ground_state_map_List = [] self.ground_state_map_List.append(min(mapList, key=lambda x: x[0])) return self.ground_state_map_List
class XratersWindow(gtk.Window): __gtype_name__ = "XratersWindow" def __init__(self): """__init__ - This function is typically not called directly. Creation a XratersWindow requires redeading the associated ui file and parsing the ui definition extrenally, and then calling XratersWindow.finish_initializing(). Use the convenience function NewXratersWindow to create XratersWindow object. """ self._acc_cal = ((128, 128, 128), (255, 255, 255)) self._acc = [0, 0, 0] self._connected = False self._wiiMote = None self._resetData() self._dataLock = threading.Lock() isConnected = property(lambda self: self._connected) def callback(funct): """A decorator used to require connection to the Wii Remote This decorator is used to implement the precondition that the Wii Remote must be connected. """ def _callback(cls, *args, **kwds): if cls.isConnected: funct(cls, *args, **kwds) return True else: return False return _callback def _connectCallback(self, connectionMaker): """Callback function called upon successful connection to the Wiimote """ if connectionMaker.connected: self._connected = True self._wiiMote = connectionMaker.wiiMote self._resetData() gobject.timeout_add(45, self._drawAcc) self.widget('actionDisconnect').set_sensitive(True) self.widget('actionSave').set_sensitive(True) self.widget('actionReset').set_sensitive(True) self.widget('actionPause').set_sensitive(True) self.widget('toolbutton1').set_related_action( self.widget('actionDisconnect')) self._acc_cal = connectionMaker.acc_cal self._wiiMote.mesg_callback = self._getAcc self._updBatteryLevel() gobject.timeout_add_seconds(60, self._updBatteryLevel) else: self.widget('actionWiiConnect').set_sensitive(True) @callback def _upd_background(self, event): """Keep a copy of the figure background """ self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox) def _getAcc(self, messages, theTime=0): """Process acceleration messages from the Wiimote This function is intended to be set as cwiid.mesg_callback """ if self._Paused: return for msg in messages: if msg[0] == cwiid.MESG_ACC: # Normalize data using calibration info for i, axisAcc in enumerate(msg[1]): self._acc[i] = float(axisAcc - self._acc_cal[0][i]) self._acc[i] /=(self._acc_cal[1][i]\ -self._acc_cal[0][i]) with self._dataLock: # Store time and acceleration in the respective arrays self._time.append(theTime - self._startTime) [self._accData[i].append(self._acc[i]) for i in threeAxes] # We only keep about 6 seconds worth of data if (self._time[-1] - self._time[0] > 6): with self._dataLock: self._time.pop(0) [self._accData[i].pop(0) for i in threeAxes] @callback def _drawAcc(self): """Update the acceleration graph """ # Do nothing while paused or there's no data available if self._Paused or len(self._time) == 0: return draw_flag = False # Update axes limits if the data fall out of range lims = self._accAxis.get_xlim() if self._time[-1] > lims[1]: self._accAxis.set_xlim(lims[0], lims[1] + 2) lims = self._accAxis.get_xlim() draw_flag = True if (self._time[-1] - lims[0] > 6): self._accAxis.set_xlim(lims[0] + 2, lims[1]) draw_flag = True if draw_flag: gobject.idle_add(self._accCanvas.draw) # Do the actual update of the background if self.__background != None: self._accCanvas.restore_region(self.__background) # Do the actual update of the lines with self._dataLock: [ self._lines[i].set_data(self._time, self._accData[i]) for i in threeAxes ] [self._accAxis.draw_artist(self._lines[i]) for i in threeAxes] self._accCanvas.blit(self._accAxis.bbox) @callback def _updBatteryLevel(self): """Callback to update the battery indicator in the status bar """ self._wiiMote.request_status() self._setBatteryIndicator( float(self._wiiMote.state['battery']) / cwiid.BATTERY_MAX) def _setBatteryIndicator(self, level): """Actually update the battery indicator in the status bar """ progressBar = self.widget("progressbarBattery") progressBar.set_fraction(level) progressBar.set_text("Battery: %.0f%%" % (level * 100)) def _resetData(self): """Reset stored data and status flags to their defaults """ self._accData = [list(), list(), list()] self._time = list() self._startTime = time.time() self._moveTime = self._startTime self._Paused = False def widget(self, name): """Helper function to retrieve widget handlers """ return self.builder.get_object(name) def finish_initializing(self, builder): """finish_initalizing should be called after parsing the ui definition and creating a XratersWindow object with it in order to finish initializing the start of the new XratersWindow instance. """ #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) #uncomment the following code to read in preferences at start up dlg = PreferencesXratersDialog.NewPreferencesXratersDialog() self.preferences = dlg.get_preferences() #code for other initialization actions should be added here self._accFigure = Figure(figsize=(8, 6), dpi=72) self._accAxis = self._accFigure.add_subplot(111) self._accAxis.set_xlabel("time (s)") self._accAxis.set_ylabel("acceleration (g)") self._lines = self._accAxis.plot(self._time, self._accData[X], self._time, self._accData[Y], self._time, self._accData[Z], animated=True) self._accFigure.legend(self._lines, ("X", "Y", "Z"), 'upper center', ncol=3) self._accAxis.set_xlim(0, 2) self._accAxis.set_ylim(-3, 3) self._accCanvas = FigureCanvas(self._accFigure) self._accCanvas.mpl_connect("draw_event", self._upd_background) self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox) self._accCanvas.show() self._accCanvas.set_size_request(600, 400) vbMain = self.widget("vboxMain") vbMain.pack_start(self._accCanvas, True, True) vbMain.show() vbMain.reorder_child(self._accCanvas, 2) self._setBatteryIndicator(0) def about(self, widget, data=None): """about - display the about box for xraters """ about = AboutXratersDialog.NewAboutXratersDialog() response = about.run() about.destroy() def preferences(self, widget, data=None): """preferences - display the preferences window for xraters """ prefs = PreferencesXratersDialog.NewPreferencesXratersDialog() response = prefs.run() if response == gtk.RESPONSE_OK: #make any updates based on changed preferences here self.preferences = prefs.get_preferences() prefs.destroy() def quit(self, widget, data=None): """quit - signal handler for closing the XratersWindow""" self.destroy() def on_destroy(self, widget, data=None): """on_destroy - called when the XratersWindow is close. """ #clean up code for saving application state should be added here if self.isConnected: self.on_wiiDisconnect(widget, data) gtk.main_quit() def on_wiiConnect(self, widget, data=None): """Signal handler for the WiiConnect action """ self.widget('actionWiiConnect').set_sensitive(False) connectionMaker = WiiConnectionMaker(self.preferences['wiiAddress'], self.widget("statusbar"), self._connectCallback) self._accAxis.set_xlim(0, 2) gobject.idle_add(self._accCanvas.draw) connectionMaker.start() def on_wiiDisconnect(self, widget, data=None): """Signal handler for the WiiDisconnect action """ self._wiiMote.close() self._connected = False self.widget('actionDisconnect').set_sensitive(False) self.widget('actionWiiConnect').set_sensitive(True) self.widget('actionReset').set_sensitive(False) self.widget('actionPause').set_sensitive(False) self.widget('toolbutton1').set_related_action( self.widget('actionWiiConnect')) self.widget('actionSave').set_sensitive(True) self.widget('statusbar').pop( self.widget("statusbar").get_context_id('')) self._setBatteryIndicator(0) def on_Reset(self, widget, data=None): """Signal handler for the reset action """ self._resetData() self._accAxis.set_xlim(0, 2) gobject.idle_add(self._accCanvas.draw) def on_Pause(self, widge, data=None): """Signal handler for the pause action """ if not self._Paused: self.widget('actionPause').set_short_label("Un_pause") else: self.widget('actionPause').set_short_label("_Pause") self._Paused = not (self._Paused) def save(self, widget, data=None): """Signal handler for the save action """ fileName = os.sep.join([ self.preferences['outputDir'], "acceleration_" + time.strftime("%Y-%m-%d_%H-%M-%S") + ".dat" ]) try: with open(fileName, 'wb') as outFile: writer = csv.writer(outFile, 'excel-tab') outFile.write( writer.dialect.delimiter.join(("#time", "Ax", "Ay", "Az"))) outFile.write(writer.dialect.lineterminator) outFile.write( writer.dialect.delimiter.join(("#s", "g", "g", "g"))) outFile.write(writer.dialect.lineterminator) with self._dataLock: writer.writerows(zip(self._time, *self._accData)) except IOError as error: dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_DESTROY_WITH_PARENT, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format=str(error)) dialog.set_title(error[1]) dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.show()
class DDTF(): def __init__(self): ttle1='Spectrum el1' ttle2=' el2 - . el1' ttle3=' el3 - . el1' ttle4=' el1 - . el2' ttle5=' Spectrum el2' ttle6=' el3 - . el2' ttle7=' el1 - . el3' ttle8='el2 - . el3' ttle9='Spectrum el3' self.win = gtk.Window() self.win.set_border_width(5) self.win.resize(800,400) vbox = gtk.VBox(spacing=3) self.win.add(vbox) vbox.show() self.fig = Figure(figsize=(7,5), dpi=72) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea self.canvas.show() vbox.pack_start(self.canvas, True, True) (self.e1,self.e2,self.e3) = signal_gen.signal_gen(3,.1,.001) self.ax1 = self.fig.add_subplot(431, title=ttle1) self.ax1.set_xlim(0,60) self.ax1.set_ylim(0,1) self.ax2 = self.fig.add_subplot(432, title=ttle2) self.ax2.set_xlim(0,60) self.ax2.set_ylim(0,1) self.ax3 = self.fig.add_subplot(433, title=ttle3) self.ax3.set_xlim(0,60) self.ax3.set_ylim(0,1) self.ax4 = self.fig.add_subplot(434, title=ttle4) self.ax4.set_xlim(0,60) self.ax4.set_ylim(0,1) self.ax5 = self.fig.add_subplot(435, title=ttle5) self.ax5.set_xlim(0,60) self.ax5.set_ylim(0,1) self.ax6 = self.fig.add_subplot(436, title=ttle6) self.ax6.set_xlim(0,60) self.ax6.set_ylim(0,1) self.ax7 = self.fig.add_subplot(437, title=ttle7) self.ax7.set_xlim(0,60) self.ax7.set_ylim(0,1) self.ax8 = self.fig.add_subplot(438, title=ttle8) self.ax8.set_xlim(0,60) self.ax8.set_ylim(0,1) self.ax9 = self.fig.add_subplot(439, title=ttle9) self.ax9.set_xlim(0,60) self.ax9.set_ylim(0,1) self.ax10 = self.fig.add_subplot(4,3,10, title="el1") self.ax11 = self.fig.add_subplot(4,3,11, title="el2") def ddtf(self,el1,el2,sample_rate=500,duration=20,step=128,increment=5): # self.ax10.plot(el1) # self.ax11.plot(el2) # self.ax12.plot(el3) # notes: duration is the length of a window in seconds # increment is the length of a step in seconds # step is the num points in an fft-analysis epoch N = len(el1) dt = 1/float(sample_rate) fNyq = sample_rate/2 df = 1/(step*dt) f = np.arange(0,fNyq,df) #Frequency axis for the FFT count = 0 end_step = N - duration*sample_rate print "end_step ", end_step print "stepping by ", increment * sample_rate for w in np.arange(0,end_step, increment * sample_rate): x=el1[w:w+duration*sample_rate] # should this be - 1 or 2? y=el2[w:w+duration*sample_rate] # z=el3[w:w+duration*sample_rate] # Initialize the Cross-Spectral arrays for averaging print "step first is : ", step Sxx=np.zeros((1,step - 1)); # - 1 here? print "Sxx: " , Sxx.shape Syy=Sxx # Szz=Sxx Sxy=Sxx # Sxz=Sxx # Syz=Sxx # Szy=Sxx # print "xshape : ", x.shape # print "Sxx shape : ", Sxx.shape xtemp=np.arange(0,step-1) xtemp_ones = np.ones(len(xtemp)) # print "xtempshape: ", xtemp.shape A = np.vstack([xtemp,xtemp_ones]).T # print "A shape: ", A.shape inner_end_step = sample_rate*duration - step # print "inner_end_step ", inner_end_step # print "step ", step for i in np.arange(0,inner_end_step - 1,step): m,b = np.linalg.lstsq(A,x[i:i+step-1])[0] # the minus 1? print "TESTING LINALG SHAPE: ", A.shape, x[i:i+step-1].shape # print "m, b: ", m, b trend = m*xtemp + b # print "istep : ", (i+step-1) x[i:i+step-1] = x[i:i+step-1] - trend # detrend x[i:i+step-1] = x[i:i+step-1] - np.mean(x[i:i+step-1]) # demean fx = np.fft.fft(x[i:i+step-1] * np.hanning(step-1).T) # windowed fft m,b = np.linalg.lstsq(A,y[i:i+step-1])[0] # the minus 1? trend = m*xtemp + b y[i:i+step-1] = y[i:i+step-1] - trend # detrend y[i:i+step-1] = y[i:i+step-1] - np.mean(y[i:i+step-1]) # demean fy = np.fft.fft(y[i:i+step-1] * np.hanning(step-1).T) # windowed fft # m,b = np.linalg.lstsq(A,z[i:i+step-1])[0] # the minus 1? # trend = m*xtemp + b # z[i:i+step-1] = z[i:i+step-1] - trend # detrend # z[i:i+step-1] = z[i:i+step-1] - np.mean(z[i:i+step-1]) # demean # fz = np.fft.fft(z[i:i+step-1] * np.hanning(step-1).T) # windowed fft # print "fs are ", fx, fy, fz # print "fxconf ", fx.conj() # print "Sxx ", Sxx.shape, Sxx.shape # print "fxstuff ", ((fx * fx.conj())).shape Sxx=Sxx+(fx * fx.conj()) # print "Sxx2 ", Sxx.shape Syy=Syy+(fy * fy.conj()) # Szz=Szz+(fz * fz.conj()) Sxy=Sxy+(fx * fy.conj()) # Sxz=Sxz+(fx * fz.conj()) # Syz=Syz+(fy * fz.conj()) # print "Sxx shape: ", Sxx.shape # print "Sxy shape: ", Sxy.shape # print "Szy shape: ", Sxx.shape # print "Syz shape: ", Syz.shape Syx = Sxy.conj() # Szx = Sxz.conj() # Szy = Syz.conj() S11=abs(Sxx)**2 S12=abs(Sxy)**2 # S13=abs(Sxz)**2 S21=abs(Syx)**2 S22=abs(Syy)**2 # S23=abs(Syz)**2 # S31=abs(Szx)**2 # S32=abs(Szy)**2 # S33=abs(Szz)**2 sumS = S11 + S12 # + S13 sumS2 = S21 + S22 # + S23 # sumS3 = S31 + S32 + S33 # NS11 = S11 / S11.max() NS12 = S12 / sumS # NS13 = S13 / sumS NS21 = S21 / sumS2 # NS22 = S22 / S22.max() # NS23 = S23 / sumS2 # NS31 = S31 / sumS3 # NS32 = S32 / sumS3 # NS33 = S33 / S33.max() count += 1 # print "NS13: ", NS13 # self.ax1.plot(f[0:step/4],NS11[0][0:step/4]) # self.ax2.plot(f[0:step/4],NS12[0][0:step/4]) # self.ax3.plot(f[0:step/4],NS13[0][0:step/4]) # self.ax4.plot(f[0:step/4],NS21[0][0:step/4]) # self.ax5.plot(f[0:step/4],NS22[0][0:step/4]) # self.ax6.plot(f[0:step/4],NS23[0][0:step/4]) # self.ax7.plot(f[0:step/4],NS31[0][0:step/4]) # self.ax8.plot(f[0:step/4],NS32[0][0:step/4]) # self.ax9.plot(f[0:step/4],NS33[0][0:step/4]) return (f,NS12[0], NS21[0])
class MainWindow: OPTICAL_FLOW_BLOCK_WIDTH = 16 OPTICAL_FLOW_BLOCK_HEIGHT = 16 OPTICAL_FLOW_RANGE_WIDTH = 16 # Range to look outside of a block for motion OPTICAL_FLOW_RANGE_HEIGHT = 16 OPTICAL_FLOW_METHOD = "BlockMatching" #OPTICAL_FLOW_METHOD = "LucasKanade" #OPTICAL_FLOW_METHOD = "HornSchunck" COMBINATION_METHOD = "NoChange" #GROUND_TRUTH_FILENAME = "/../../config/TopPosGripper.yaml" #GROUND_TRUTH_FILENAME = "/../../config/ExperimentPosGripper.yaml" #GROUND_TRUTH_FILENAME = "/../../config/OnTablePosGripper.yaml" GROUND_TRUTH_FILENAME = "/../../config/TightBasicWave_Gripper.yaml" CORRELATION_THRESHOLD = 0.52 MAX_TEST_POINT_X = (640 - OPTICAL_FLOW_BLOCK_WIDTH)/OPTICAL_FLOW_BLOCK_WIDTH - 1 MAX_TEST_POINT_Y = (480 - OPTICAL_FLOW_BLOCK_HEIGHT)/OPTICAL_FLOW_BLOCK_HEIGHT - 1 SAMPLES_PER_SECOND = 30.0 MAX_CORRELATION_LAG = 2.0 GRIPPER_WAVE_FREQUENCY = 1.0 # Waves per second GRIPPER_NUM_WAVES = 3.0 GRIPPER_WAVE_AMPLITUDE = math.radians( 20.0 ) #--------------------------------------------------------------------------- def __init__( self, bagFilename ): self.scriptPath = os.path.dirname( __file__ ) self.cameraImagePixBuf = None self.bagFilename = bagFilename self.lastImageGray = None # Read in sequence t1 = time.time() self.inputSequence = InputSequence( bagFilename ) distractors = [ Distractor( radius=24, startPos=( 25, 35 ), endPos=( 100, 100 ), frequency=2.0 ), Distractor( radius=24, startPos=( 200, 200 ), endPos=( 150, 50 ), frequency=0.25 ), Distractor( radius=24, startPos=( 188, 130 ), endPos=( 168, 258 ), frequency=0.6 ), Distractor( radius=24, startPos=( 63, 94 ), endPos=( 170, 81 ), frequency=1.5 ), Distractor( radius=24, startPos=( 40, 287 ), endPos=( 50, 197 ), frequency=3.0 ) ] #self.inputSequence.addDistractorObjects( distractors ) self.inputSequence.calculateOpticalFlow( self.OPTICAL_FLOW_BLOCK_WIDTH, self.OPTICAL_FLOW_BLOCK_HEIGHT, self.OPTICAL_FLOW_RANGE_WIDTH, self.OPTICAL_FLOW_RANGE_HEIGHT, self.OPTICAL_FLOW_METHOD ) t2 = time.time() print 'Processing sequence took %0.3f ms' % ((t2-t1)*1000.0) # Resample sequence t1 = time.time() self.regularisedInputSequence = RegularisedInputSequence( self.inputSequence, self.SAMPLES_PER_SECOND ) t2 = time.time() print 'Resampling took %0.3f ms' % ((t2-t1)*1000.0) t1 = time.time() self.crossCorrelatedSequence = CrossCorrelatedSequence( self.regularisedInputSequence, self.MAX_CORRELATION_LAG, self.COMBINATION_METHOD ) t2 = time.time() print 'Correlation took %0.3f ms' % ((t2-t1)*1000.0) # Detect the input signal based on the correlation in the x and y axis self.inputSignalDetectedArray = \ self.crossCorrelatedSequence.detectInputSequence( self.CORRELATION_THRESHOLD ) # Build a histogram for the gripper self.gripperHistogram = cv.CreateHist( [ 256/8, 256/8, 256/8 ], cv.CV_HIST_ARRAY, [ (0,255), (0,255), (0,255) ], 1 ) firstImage = self.inputSequence.cameraImages[ 0 ] imageRGB = cv.CreateImageHeader( ( firstImage.shape[ 1 ], firstImage.shape[ 0 ] ), cv.IPL_DEPTH_8U, 3 ) cv.SetData( imageRGB, firstImage.data, firstImage.shape[ 1 ]*3 ) r_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) g_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) b_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) cv.Split( imageRGB, r_plane, g_plane, b_plane, None ) planes = [ r_plane, g_plane, b_plane ] maskArray = np.zeros(shape=( imageRGB.height, imageRGB.width ), dtype=np.uint8 ) for rowIdx in range( self.inputSignalDetectedArray.shape[ 0 ] ): for colIdx in range( self.inputSignalDetectedArray.shape[ 1 ] ): if self.inputSignalDetectedArray[ rowIdx, colIdx ]: rowStartIdx = rowIdx*self.OPTICAL_FLOW_BLOCK_HEIGHT rowEndIdx = rowStartIdx + self.OPTICAL_FLOW_BLOCK_HEIGHT colStartIdx = colIdx*self.OPTICAL_FLOW_BLOCK_WIDTH colEndIdx = colStartIdx + self.OPTICAL_FLOW_BLOCK_WIDTH maskArray[ rowStartIdx:rowEndIdx, colStartIdx:colEndIdx ] = 255 cv.CalcHist( [ cv.GetImage( i ) for i in planes ], self.gripperHistogram, 0, mask=cv.fromarray( maskArray ) ) markerBuffer = MarkerBuffer.loadMarkerBuffer( self.scriptPath + self.GROUND_TRUTH_FILENAME ) if markerBuffer == None: raise Exception( "Unable to load marker buffer" ) self.rocCurve = GripperDetectorROCCurve( self.crossCorrelatedSequence, markerBuffer ) # Create the matplotlib graph self.figure = Figure( figsize=(8,6), dpi=72 ) self.axisX = self.figure.add_subplot( 311 ) self.axisY = self.figure.add_subplot( 312 ) self.axisROC = self.figure.add_subplot( 313 ) self.canvas = None # Wait for GUI to be created before creating canvas self.navToolbar = None # Setup the GUI builder = gtk.Builder() builder.add_from_file( self.scriptPath + "/GUI/OpticalFlowExplorer.glade" ) self.dwgCameraImage = builder.get_object( "dwgCameraImage" ) self.window = builder.get_object( "winMain" ) self.vboxMain = builder.get_object( "vboxMain" ) self.hboxWorkArea = builder.get_object( "hboxWorkArea" ) self.adjTestPointX = builder.get_object( "adjTestPointX" ) self.adjTestPointY = builder.get_object( "adjTestPointY" ) self.adjTestPointX.set_upper( self.MAX_TEST_POINT_X ) self.adjTestPointY.set_upper( self.MAX_TEST_POINT_Y ) self.sequenceControls = builder.get_object( "sequenceControls" ) self.sequenceControls.setNumFrames( len( self.inputSequence.cameraImages ) ) self.sequenceControls.setOnFrameIdxChangedCallback( self.onSequenceControlsFrameIdxChanged ) self.setFrameIdx( 0 ) self.processOpticalFlowData() builder.connect_signals( self ) updateLoop = self.update() gobject.idle_add( updateLoop.next ) self.window.show() self.window.maximize() #--------------------------------------------------------------------------- def onWinMainDestroy( self, widget, data = None ): gtk.main_quit() #--------------------------------------------------------------------------- def main( self ): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main() #--------------------------------------------------------------------------- def processOpticalFlowData( self ): testX = int( self.adjTestPointX.get_value() ) testY = int( self.adjTestPointY.get_value() ) regSeq = self.regularisedInputSequence corSeq = self.crossCorrelatedSequence # Normalise the data ready for display normalisedServoAngleData = Utils.normaliseSequence( regSeq.regularServoAngleData ) normalisedOpticalFlowDataX = Utils.normaliseSequence( regSeq.regularOpticalFlowArrayX[ testY ][ testX ] ) normalisedOpticalFlowDataY = Utils.normaliseSequence( regSeq.regularOpticalFlowArrayY[ testY ][ testX ] ) numCorrelationChannels = len( corSeq.correlationChannels ) # Plot graphs self.axisX.clear() self.axisX.plot( regSeq.regularSampleTimes, normalisedServoAngleData ) self.axisX.plot( regSeq.regularSampleTimes, normalisedOpticalFlowDataX ) if numCorrelationChannels >= 1: correlationChannel = corSeq.correlationChannels[ 0 ][ testY ][ testX ] self.axisX.plot( regSeq.regularSampleTimes[:len(correlationChannel)], correlationChannel ) self.axisY.clear() self.axisY.plot( regSeq.regularSampleTimes, normalisedServoAngleData ) self.axisY.plot( regSeq.regularSampleTimes, normalisedOpticalFlowDataY ) inpSeq = self.inputSequence self.axisY.plot( inpSeq.imageTimes, Utils.normaliseSequence( inpSeq.opticalFlowArraysY[ testY ][ testX ] ) ) if numCorrelationChannels >= 2: correlationChannel = corSeq.correlationChannels[ 1 ][ testY ][ testX ] self.axisY.plot( regSeq.regularSampleTimes[:len(correlationChannel)], correlationChannel ) self.axisROC.clear() self.axisROC.plot( self.rocCurve.falsePositiveRates, self.rocCurve.truePositiveRates ) #self.axisROC.plot( self.rocCurve.thresholds, self.rocCurve.sensitivity ) #self.axisROC.plot( self.rocCurve.thresholds, self.rocCurve.specificity ) self.refreshGraphDisplay() outputFile = open( self.scriptPath + "/../../test_results/CrossCorrelation.csv", "w" ) numSamples = len( regSeq.regularSampleTimes ) correlationChannel = corSeq.correlationChannels[ 0 ][ testY ][ testX ] numCorrelationSamples = len( correlationChannel ) print >>outputFile, "Time,Input,Output,CrossCorrelation" for i in range( numSamples ): if i < numCorrelationSamples: correlationData = correlationChannel[ i ] else: correlationData = 0.0 print >>outputFile, "{0},{1},{2},{3}".format( regSeq.regularSampleTimes[ i ], normalisedServoAngleData[ i ], normalisedOpticalFlowDataX[ i ], correlationData ) outputFile.close() #--------------------------------------------------------------------------- def refreshGraphDisplay( self ): if self.canvas != None: self.hboxWorkArea.remove( self.canvas ) self.canvas.destroy() self.canvas = None if self.navToolbar != None: self.vboxMain.remove( self.navToolbar ) self.navToolbar.destroy() self.navToolbar = None self.canvas = FigureCanvas( self.figure ) # a gtk.DrawingArea self.canvas.show() self.hboxWorkArea.pack_start( self.canvas, True, True ) self.hboxWorkArea.show() # Navigation toolbar self.navToolbar = NavigationToolbar( self.canvas, self.window ) self.navToolbar.lastDir = '/var/tmp/' self.vboxMain.pack_start( self.navToolbar, expand=False, fill=False ) self.navToolbar.show() self.vboxMain.show() #--------------------------------------------------------------------------- def setFrameIdx( self, frameIdx ): self.frameIdx = frameIdx # Display the frame image = self.inputSequence.cameraImages[ frameIdx ] imageWidth = image.shape[ 1 ] imageHeight = image.shape[ 0 ] imageStep = imageWidth*3 self.cameraImagePixBuf = gtk.gdk.pixbuf_new_from_data( image.tostring(), gtk.gdk.COLORSPACE_RGB, False, 8, imageWidth, imageHeight, imageStep ) # Track gripper imageRGB = cv.CreateImageHeader( ( imageWidth, imageHeight ), cv.IPL_DEPTH_8U, 3 ) cv.SetData( imageRGB, image.data, imageStep ) imageRGB = cv.CloneImage( imageRGB ) r_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) g_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) b_plane = cv.CreateMat( imageRGB.height, imageRGB.width, cv.CV_8UC1 ) cv.Split( imageRGB, r_plane, g_plane, b_plane, None ) planes = [ r_plane, g_plane, b_plane ] backproject = cv.CreateImage(cv.GetSize(imageRGB), 8, 1) # Run the cam-shift cv.CalcArrBackProject( planes, backproject, self.gripperHistogram ) #cv.Threshold( backproject, backproject, 1, 255, cv.CV_THRESH_BINARY ) cv.CvtColor( backproject, imageRGB, cv.CV_GRAY2RGB ) #self.cameraImagePixBuf = gtk.gdk.pixbuf_new_from_data( #imageRGB.tostring(), #gtk.gdk.COLORSPACE_RGB, #False, #8, #imageRGB.width, #imageRGB.height, #imageRGB.width*3 ) # Resize the drawing area if necessary if self.dwgCameraImage.get_size_request() != ( imageWidth, imageHeight ): self.dwgCameraImage.set_size_request( imageWidth, imageHeight ) self.dwgCameraImage.queue_draw() #--------------------------------------------------------------------------- def onTestPointAdjustmentValueChanged( self, widget ): self.processOpticalFlowData() self.dwgCameraImage.queue_draw() #--------------------------------------------------------------------------- def onSequenceControlsFrameIdxChanged( self, widget ): self.setFrameIdx( widget.frameIdx ) #--------------------------------------------------------------------------- def onDwgCameraImageButtonPressEvent( self, widget, data ): if self.cameraImagePixBuf != None: imgRect = self.getImageRectangleInWidget( widget, self.cameraImagePixBuf.get_width(), self.cameraImagePixBuf.get_height() ) self.adjTestPointX.set_value( int( ( data.x - imgRect.x )/self.OPTICAL_FLOW_BLOCK_WIDTH ) ) self.adjTestPointY.set_value( int( ( data.y - imgRect.y )/self.OPTICAL_FLOW_BLOCK_HEIGHT ) ) #--------------------------------------------------------------------------- def onDwgCameraImageExposeEvent( self, widget, data = None ): if self.cameraImagePixBuf != None: imgRect = self.getImageRectangleInWidget( widget, self.cameraImagePixBuf.get_width(), self.cameraImagePixBuf.get_height() ) imgOffsetX = imgRect.x imgOffsetY = imgRect.y # Get the total area that needs to be redrawn imgRect = imgRect.intersect( data.area ) srcX = imgRect.x - imgOffsetX srcY = imgRect.y - imgOffsetY widget.window.draw_pixbuf( widget.get_style().fg_gc[ gtk.STATE_NORMAL ], self.cameraImagePixBuf, srcX, srcY, imgRect.x, imgRect.y, imgRect.width, imgRect.height ) #return # Draw an overlay to show places where the input motion has been detected if self.inputSignalDetectedArray != None: imageData = np.frombuffer( self.cameraImagePixBuf.get_pixels(), dtype=np.uint8 ) imageData.shape = ( self.cameraImagePixBuf.get_height(), self.cameraImagePixBuf.get_width(), 3 ) graphicsContext = widget.window.new_gc() graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 65535, 65535, 0 ) ) blockY = imgRect.y for y in range( self.inputSignalDetectedArray.shape[ 0 ] ): blockX = imgRect.x for x in range( self.inputSignalDetectedArray.shape[ 1 ] ): if self.inputSignalDetectedArray[ y, x ]: # Get source block as NumPy array srcX = blockX - imgRect.x srcY = blockY - imgRect.y srcData = imageData[ srcY:srcY+self.OPTICAL_FLOW_BLOCK_HEIGHT, srcX:srcX+self.OPTICAL_FLOW_BLOCK_WIDTH, : ] # Create a modified version of the block with a yellow layer # alpha blended over the top yellowLayer = np.ones( ( self.OPTICAL_FLOW_BLOCK_WIDTH, self.OPTICAL_FLOW_BLOCK_HEIGHT, 3 ) )*[255.0,255.0,0.0]*0.5 modifiedData = ( srcData.astype( np.float32 )*0.5 + yellowLayer ).astype( np.uint8 ) # Blit the modified version into the widget modifiedPixBuf = gtk.gdk.pixbuf_new_from_array( modifiedData, gtk.gdk.COLORSPACE_RGB, 8 ) widget.window.draw_pixbuf( widget.get_style().fg_gc[ gtk.STATE_NORMAL ], modifiedPixBuf, 0, 0, blockX, blockY, self.OPTICAL_FLOW_BLOCK_WIDTH, self.OPTICAL_FLOW_BLOCK_HEIGHT ) blockX += self.OPTICAL_FLOW_BLOCK_WIDTH blockY += self.OPTICAL_FLOW_BLOCK_HEIGHT return # Draw the optical flow if it's available opticalFlowX = self.inputSequence.opticalFlowArraysX[ :, :, self.frameIdx ] opticalFlowY = self.inputSequence.opticalFlowArraysY[ :, :, self.frameIdx ] if opticalFlowX != None and opticalFlowY != None: testX = int( self.adjTestPointX.get_value() ) testY = int( self.adjTestPointY.get_value() ) graphicsContext = widget.window.new_gc() graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 65535, 0 ) ) blockCentreY = imgRect.y + self.OPTICAL_FLOW_BLOCK_HEIGHT / 2 for y in range( opticalFlowX.shape[ 0 ] ): blockCentreX = imgRect.x + self.OPTICAL_FLOW_BLOCK_WIDTH / 2 for x in range( opticalFlowX.shape[ 1 ] ): if testX == x and testY == y: # Highlight the current test point radius = 2 arcX = int( blockCentreX - radius ) arcY = int( blockCentreY - radius ) arcWidth = arcHeight = int( radius * 2 ) drawFilledArc = False graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 65535, 65535, 65535 ) ) widget.window.draw_arc( graphicsContext, drawFilledArc, arcX, arcY, arcWidth, arcHeight, 0, 360 * 64 ) endX = blockCentreX + opticalFlowX[ y, x ] endY = blockCentreY + opticalFlowY[ y, x ] if endY < blockCentreY: # Up is red graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 65535, 0, 0 ) ) elif endY > blockCentreY: # Down is blue graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 0, 65535 ) ) else: # Static is green graphicsContext.set_rgb_fg_color( gtk.gdk.Color( 0, 65535, 0 ) ) widget.window.draw_line( graphicsContext, int( blockCentreX ), int( blockCentreY ), int( endX ), int( endY ) ) blockCentreX += self.OPTICAL_FLOW_BLOCK_WIDTH blockCentreY += self.OPTICAL_FLOW_BLOCK_HEIGHT #--------------------------------------------------------------------------- def getImageRectangleInWidget( self, widget, imageWidth, imageHeight ): # Centre the image inside the widget widgetX, widgetY, widgetWidth, widgetHeight = widget.get_allocation() imgRect = gtk.gdk.Rectangle( 0, 0, widgetWidth, widgetHeight ) if widgetWidth > imageWidth: imgRect.x = (widgetWidth - imageWidth) / 2 imgRect.width = imageWidth if widgetHeight > imageHeight: imgRect.y = (widgetHeight - imageHeight) / 2 imgRect.height = imageHeight return imgRect #--------------------------------------------------------------------------- def update( self ): UPDATE_FREQUENCY = 30.0 # Updates in Hz lastTime = time.clock() while 1: curTime = time.clock() if curTime - lastTime >= 1.0 / UPDATE_FREQUENCY: # Save the time lastTime = curTime yield True yield False
def __init__(self, in_file, vg_files=[1], data_type=1, projection='cyl', color_map='jet', time_zone=0, plot_contours=False, plot_center='t', plot_meridians=True, plot_parallels=True, plot_terminator=True, resolution='c', points_of_interest=[], save_file='', run_quietly=False, dpi=150, parent=None): self.run_quietly = run_quietly self.dpi = float(dpi) plot_parameters = VOAFile((in_file + '.voa')) plot_parameters.parse_file() if (plot_parameters.get_projection() != 'cyl'): print _("Error: Only lat/lon (type 1) input files are supported") sys.exit(1) grid = plot_parameters.get_gridsize() self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)] # TODO This needs a little more work... what if the pcenter card is not specified if plot_center == 'p': plot_centre_location = plot_parameters.get_location( plot_parameters.P_CENTRE) else: plot_centre_location = plot_parameters.get_location( plot_parameters.TX_SITE) self.points_of_interest = [plot_centre_location] if len(points_of_interest) > 0: self.points_of_interest.extend(points_of_interest) imageBuf = P.zeros([grid, grid], float) area_rect = plot_parameters.get_area_rect() # The checks ought to be performed in the area_rect. # Do a few basic sanity checks # #if ( (area_rect.get_sw_lon() < -180) or (area_rect.get_ne_lon() > 180.0) or (area_rect.get_sw_lat() < -90) or (area_rect.get_ne_lat() > 90.0) ): # print "Input file latitudes/longitudes are out of range" # print "-180 < Latitude < 180.0, -90 < Longitude < 90" # sys.exit(1) #if ( (area_rect.get_sw_lon() == area_rect.get_ne_lon()) or (area_rect.get_sw_lat() == area_rect.get_ne_lat()) ): # print "Input file latitudes/longitudes are the same" # print "-180 < Latitude < 180.0, -90 < Longitude < 90" # sys.exit(1) points = P.zeros([grid, grid], float) lons = P.zeros(grid * grid, float) lats = P.zeros(grid * grid, float) lons = P.arange(area_rect.get_sw_lon(), area_rect.get_ne_lon() + 0.001, (area_rect.get_ne_lon() - area_rect.get_sw_lon()) / float(grid - 1)) lats = P.arange(area_rect.get_sw_lat(), area_rect.get_ne_lat() + 0.001, (area_rect.get_ne_lat() - area_rect.get_sw_lat()) / float(grid - 1)) colString = 'P.cm.' + color_map colMap = eval(colString) self.subplots = [] self.number_of_subplots = len(vg_files) matplotlib.rcParams['axes.edgecolor'] = 'gray' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['figure.facecolor'] = 'white' #matplotlib.rcParams['figure.figsize'] = (6, 10) matplotlib.rcParams['figure.subplot.hspace'] = 0.45 matplotlib.rcParams['figure.subplot.wspace'] = 0.35 matplotlib.rcParams['figure.subplot.right'] = 0.85 colorbar_fontsize = 12 if self.number_of_subplots <= 1: self.num_rows = 1 self.main_title_fontsize = 24 matplotlib.rcParams['legend.fontsize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 10 matplotlib.rcParams['ytick.labelsize'] = 10 matplotlib.rcParams[ 'figure.subplot.top'] = 0.8 # single figure plots have a larger title so require more space at the top. elif ((self.number_of_subplots >= 2) and (self.number_of_subplots <= 6)): self.num_rows = 2 self.main_title_fontsize = 18 matplotlib.rcParams['legend.fontsize'] = 10 matplotlib.rcParams['axes.labelsize'] = 10 matplotlib.rcParams['axes.titlesize'] = 11 matplotlib.rcParams['xtick.labelsize'] = 8 matplotlib.rcParams['ytick.labelsize'] = 8 #self.x_axes_ticks = P.arange(0,25,4) else: self.num_rows = 3 self.main_title_fontsize = 16 matplotlib.rcParams['legend.fontsize'] = 8 matplotlib.rcParams['axes.labelsize'] = 8 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 6 matplotlib.rcParams['ytick.labelsize'] = 6 #self.x_axes_ticks = P.arange(0,25,4) self.num_cols = int( math.ceil(float(self.number_of_subplots) / float(self.num_rows))) self.fig = Figure() self.main_title_label = self.fig.suptitle( unicode(self.image_defs['title'], 'utf-8'), fontsize=self.main_title_fontsize) if projection == 'ortho': self.show_subplot_frame = False for plot_ctr in range(self.number_of_subplots): #ax = self.fig.add_subplot(plot_ctr) ax = self.fig.add_subplot(self.num_rows, self.num_cols, plot_ctr + 1, frame_on=self.show_subplot_frame, axisbg='white') self.subplots.append(ax) ax.label_outer() #print "opening: ",(in_file+'.vg'+str(vg_files[plot_ctr])) vgFile = open(in_file + '.vg' + str(vg_files[plot_ctr])) pattern = re.compile(r"[a-z]+") for line in vgFile: match = pattern.search(line) if not match: value = float( line[int(self.image_defs['first_char'] ):int(self.image_defs['last_char'])]) # TODO Does this need to be normalised here if it's also being done in the plot? value = max(self.image_defs['min'], value) value = min(self.image_defs['max'], value) #if value < self.image_defs[2] : value = self.image_defs[2] #if value > self.image_defs[3] : value = self.image_defs[3] points[int(line[3:6]) - 1][int(line[0:3]) - 1] = value vgFile.close() map = Basemap(\ llcrnrlon=area_rect.get_sw_lon(), llcrnrlat=area_rect.get_sw_lat(),\ urcrnrlon=area_rect.get_ne_lon(), urcrnrlat=area_rect.get_ne_lat(),\ projection=projection,\ lat_0=plot_centre_location.get_latitude(),\ lon_0=plot_centre_location.get_longitude(),\ resolution=resolution, ax=ax) map.drawcoastlines(color='black') map.drawcountries(color='grey') map.drawmapboundary(color='black', linewidth=1.0) warped = ma.zeros((grid, grid), float) warped, warped_lon, warped_lat = map.transform_scalar( points, lons, lats, grid, grid, returnxy=True, checkbounds=False, masked=True) warped = warped.filled(self.image_defs['min'] - 1.0) colMap.set_under(color='k', alpha=0.0) im = map.imshow(warped, cmap=colMap, extent=(-180, 180, -90, 90), origin='lower', norm=P.Normalize(clip=False, vmin=self.image_defs['min'], vmax=self.image_defs['max'])) ####################### # Plot greyline ####################### if plot_terminator: the_sun = Sun() the_month = plot_parameters.get_month(vg_files[plot_ctr] - 1) the_day = plot_parameters.get_day(vg_files[plot_ctr] - 1) the_hour = plot_parameters.get_utc(vg_files[plot_ctr] - 1) if (the_day == 0): the_day = 15 the_year = datetime.date.today().year num_days_since_2k = the_sun.daysSince2000Jan0( the_year, the_month, the_day) res = the_sun.sunRADec(num_days_since_2k) declination = res[1] if (declination == 0.0): declination = -0.001 tau = the_sun.computeGHA(the_day, the_month, the_year, the_hour) if declination > 0: terminator_end_lat = area_rect.get_sw_lat() else: terminator_end_lat = area_rect.get_ne_lat() terminator_lat = [terminator_end_lat] terminator_lon = [area_rect.get_sw_lon()] for i in range(int(area_rect.get_sw_lon()), int(area_rect.get_ne_lon()), 1) + [int(area_rect.get_ne_lon())]: longitude = i + tau tan_lat = -the_sun.cosd(longitude) / the_sun.tand( declination) latitude = the_sun.atand(tan_lat) latitude = max(latitude, area_rect.get_sw_lat()) latitude = min(latitude, area_rect.get_ne_lat()) xpt, ypt = map(i, latitude) terminator_lon.append(xpt) terminator_lat.append(ypt) terminator_lon.append(area_rect.get_ne_lon()) terminator_lat.append(terminator_end_lat) #This is a little simplistic and doesn't work for ortho plots.... ax.plot(terminator_lon, terminator_lat, color='grey', alpha=0.75) ax.fill(terminator_lon, terminator_lat, facecolor='grey', alpha=0.5) tau = -tau if (tau > 180.0): tau = tau - 360.0 if (tau < -180.0): tau = tau + 360.0 #Plot the position of the sun (if it's in the coverage area) if area_rect.contains(declination, tau): xpt, ypt = map(tau, declination) #sbplt_ax.plot([xpt],[ypt],'yh') ax.plot([xpt], [ypt], 'yh') ########################## # Points of interest ########################## for location in self.points_of_interest: if area_rect.contains(location.get_latitude(), location.get_longitude()): xpt, ypt = map(location.get_longitude(), location.get_latitude()) ax.plot([xpt], [ypt], 'ro') ax.text(xpt + 100000, ypt + 100000, location.get_name()) if plot_meridians: if (area_rect.get_lon_delta() <= 90.0): meridians = P.arange(-180, 190.0, 10.0) elif (area_rect.get_lon_delta() <= 180.0): meridians = P.arange(-180.0, 210.0, 30.0) else: meridians = P.arange(-180, 240.0, 60.0) if ((projection == 'ortho') or (projection == 'vandg')): map.drawmeridians(meridians) else: map.drawmeridians(meridians, labels=[1, 1, 0, 1]) if plot_parallels: if (area_rect.get_lat_delta() <= 90.0): parallels = P.arange(-90.0, 120.0, 60.0) else: parallels = P.arange(-90.0, 120.0, 30.0) if ((projection == 'ortho') or (projection == 'vandg')): map.drawparallels(parallels) else: map.drawparallels(parallels, labels=[1, 1, 0, 1]) if plot_contours: map.contour(warped_lon, warped_lat, warped, self.image_defs['y_labels'], linewidths=1.0, colors='k', alpha=0.5) #add a title title_str = plot_parameters.get_plot_description_string( vg_files[plot_ctr] - 1, self.image_defs['plot_type'], time_zone) if self.number_of_subplots == 1: title_str = plot_parameters.get_plot_description_string( vg_files[plot_ctr] - 1, self.image_defs['plot_type'], time_zone) title_str = title_str + "\n" + plot_parameters.get_detailed_plot_description_string( vg_files[plot_ctr] - 1) else: title_str = plot_parameters.get_minimal_plot_description_string( vg_files[plot_ctr] - 1, self.image_defs['plot_type'], time_zone) self.subplot_title_label = ax.set_title(title_str) # Add a colorbar on the right hand side, aligned with the # top of the uppermost plot and the bottom of the lowest # plot. self.cb_ax = self.fig.add_axes(self.get_cb_axes()) self.fig.colorbar(im, cax=self.cb_ax, orientation='vertical', ticks=self.image_defs['y_labels'], format=P.FuncFormatter( eval('self.' + self.image_defs['formatter']))) #print self.image_defs['y_labels'] for t in self.cb_ax.get_yticklabels(): t.set_fontsize(colorbar_fontsize) canvas = FigureCanvasGTKAgg(self.fig) self.fig.canvas.mpl_connect('draw_event', self.on_draw) canvas.show() if save_file: self.save_plot(canvas, save_file) #todo this ought to a command line param if not self.run_quietly: dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent=parent) return
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_lpa_toggled" : self.set_lpa, "on_rpa_toggled" : self.set_rpa, "on_nas_toggled" : self.set_nas, "gtk_widget_hide" : self.hideinsteadofdelete, "on_menu_load_data_activate" : self.load_data, "on_menu_load_channels_activate" : self.load_channel_positions, "on_menuAbout_activate": self.show_aboutdialog, "on_menu_coregister_toggled" : self.coregister_toggle, "on_buttonsavecoreg_activate" : self.save_coregister_info, #"test" : self.changed_cb, } self.builder.connect_signals(dic) self.create_draw_frame('none') #self.load_data(None) def coregister_toggle(self,widget): if widget.get_active() == True: self.builder.get_object("hbuttonbox2").show() else: self.builder.get_object("hbuttonbox2").hide() def show_aboutdialog(self,widget): self.builder.get_object("aboutdialog1").show() def load_data(self,widget): chooser = gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) filter = gtk.FileFilter() filter.set_name('MRI files') filter.add_pattern('*.img') filter.add_pattern('*.nii*') chooser.add_filter(filter) chooser.run() print chooser.get_filename(), 'selected' fn = chooser.get_filename(); print type(fn); chooser.destroy() img = nibabel.load(fn) self.fig.clf() self.display(img) def load_channel_positions(self,widget): pass def set_lpa(self,widget): if widget.get_active() == True: print 'adding circle', self.ind1, self.ind2, self.ind3 circle = Circle((self.ind3,self.ind2),radius=5,color='b',alpha=.75)#self.ind2,self.ind3), 5) self.lpapatch = self.ax1.add_patch(circle) self.lpa = copy(self.coordinates) if widget.get_active() == False: self.lpapatch.remove() self.update() def set_rpa(self,widget): if widget.get_active() == True: print 'adding circle', self.ind1, self.ind2, self.ind3 circle = Circle((self.ind3,self.ind2),radius=5,color='r',alpha=.75)#self.ind2,self.ind3), 5) self.rpapatch = self.ax1.add_patch(circle) self.rpa = copy(self.coordinates) if widget.get_active() == False: self.rpapatch.remove() self.update() def set_nas(self,widget): if widget.get_active() == True: print 'adding circle', self.ind1, self.ind2, self.ind3 circle = Circle((self.ind3,self.ind2),radius=5,color='g',alpha=.75)#self.ind2,self.ind3), 5) self.naspatch = self.ax1.add_patch(circle) self.nas = copy(self.coordinates) if widget.get_active() == False: self.naspatch.remove() self.update() def save_coregister_info(self,widget): print 'current aux field in header',self.hdr['aux_file'] #filepath = os.path.splitext(self.img.file_map['header'].filename)[0] try: filepath = os.path.splitext(self.filename)[0] except: print 'Couldnt find filename for saving XFM, saving in current dir as MRI_XFM_DATA' filepath = 'MRI_XFM_DATA' coreg_dict = {'lpa': self.lpa,'rpa': self.rpa, 'nas':self.nas} readwrite.writedata(coreg_dict, filepath) def load_coregister_info(self, widget): if os.path.isfile(filepath+'.pym') == True: print('loading index points found in file',filepath+'.pym') self.fiddata = readwrite.readdata(filepath+'.pym') self.getfiducals(h) #def test2(self,widget): #self.fig.clf() #self.display(self.data,self.chanlocs,animate='on') #def test3(self,widget): #self.fig.clf() #self.display(self.data,self.chanlocs,data2=self.data[0],quiver='on') 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() #def plot_data(self,data): #"""provide... #xi=grid x data #yi=grided y data #zi=interpolated MEG data for contour #intx and inty= sensor coords for channel plotting""" #self.sp.imshow(data[100])#,shading='interp',cmap=cm.jet) def IndexTracker(self, data, ax1, ax2, ax3, colormap, pixdim, overlay, translation):#, coord): try: colormap = self.color_sel except: pass self.overlay = overlay self.ax1 = ax1 ax1.set_title('Axial') self.ax2 = ax2 ax2.set_title('Coronal') self.ax3 = ax3 ax3.set_title('Sagital') #coord.set_title('\n\n\n\ncoord') self.data = (data) self.slices1,self.slices2,self.slices3 = data.shape print self.slices3,self.slices2,self.slices1, translation, data.shape self.translation = translation #coord1 = (-1000,100,-100,1000) #coord1 = (translation[1]+self.slices2,translation[1],translation[0]+self.slices3,translation[0]) #coord2 = (translation[0]+self.slices3,translation[0],translation[2]-self.slices1,self.slices1-translation[2]) #coord3 = (translation[1]+self.slices2,translation[1],translation[2]-self.slices1,self.slices1-translation[2]) self.ind1 = self.slices3/2 self.ind2 = self.slices2/2 self.ind3 = self.slices1/2 self.im1 = ax1.imshow(self.data[:,:,self.ind1].T, aspect = 'auto',cmap=colormap); ax1.set_ylim(ax1.get_ylim()[::-1]); self.im2 = ax2.imshow(self.data[:,self.ind2,:].T, aspect = 'auto',cmap=colormap); ax2.set_ylim(ax2.get_ylim()[::-1]); self.im3 = ax3.imshow(self.data[self.ind3,:,:].T, aspect = 'auto',cmap=colormap); ax3.set_ylim(ax3.get_ylim()[::-1]); #self.coord = coord for im in gca().get_images(): im.set_clim(self.data.min(), self.data.max()) self.update1() self.pixdim = pixdim print pixdim def onscroll(self, event): if event.inaxes == self.ax1: if event.button=='up': self.ind1 = clip(self.ind1+1, 0, self.slices1-1) else: self.ind1 = clip(self.ind1-1, 0, self.slices1-1) self.update() if event.inaxes == self.ax2: if event.button=='up': self.ind2 = clip(self.ind2+1, 0, self.slices2-1) else: self.ind2 = clip(self.ind2-1, 0, self.slices2-1) self.update() if event.inaxes == self.ax3: if event.button=='up': self.ind3 = clip(self.ind3+1, 0, self.slices3-1) else: self.ind3 = clip(self.ind3-1, 0, self.slices3-1) self.update() def update(self): self.update1();self.update2();self.update3() def update1(self): self.im1.set_data(self.data[:,:,self.ind1].T) self.im1.axes.figure.canvas.draw() def update2(self): self.im2.set_data(self.data[:,self.ind2,:].T) self.im2.axes.figure.canvas.draw() def update3(self): self.im3.set_data(self.data[self.ind3,:,:].T) self.im3.axes.figure.canvas.draw() def click(self,event, pixdim=None): self.events=event if event.button == 3: self.showpopupmenu(None,event) return #print self.pixdim def printcoord(): #coordinates = round(self.ind3*self.pixdim[0]+(self.translation[0])), round(self.ind2*self.pixdim[1]+(self.translation[1])), round(self.ind1*self.pixdim[2]+(self.translation[2])) #coordinates = self.coordinates = array([round(self.ind2*self.pixdim[1]+(self.translation[1])), round(self.ind3*self.pixdim[0]+(self.translation[0])), round(self.ind1*self.pixdim[2]+(self.translation[2]))]) coordinates = self.coordinates = array([round(self.ind3*self.pixdim[0]), round(self.ind2*self.pixdim[1]), round(self.ind1*self.pixdim[2])]) print coordinates, 'mm'#, self.ind3, self.pixdim,(self.translation[0]) return coordinates if event.inaxes == self.ax1: self.ind2=int(event.ydata) self.ind3=int(event.xdata) #print round(self.ind3*self.pixdim[0]), round(self.ind2*self.pixdim[1]), round(self.ind1*self.pixdim[2]), 'mm' printcoord() self.update() if event.inaxes == self.ax2: self.ind1=int(event.ydata) self.ind3=int(event.xdata) #print round(self.ind3*self.pixdim[0]), round(self.ind2*self.pixdim[1]), round(self.ind1*self.pixdim[2]), 'mm' printcoord() self.update() if event.inaxes == self.ax3: self.ind1=int(event.ydata) self.ind2=int(event.xdata) #print round(self.ind3*self.pixdim[0]), round(self.ind2*self.pixdim[1]), round(self.ind1*self.pixdim[2]), 'mm' printcoord() self.update() #print self.ind1,self.ind2,self.ind3 #self.coord.title.set_text([round(self.ind3*self.pixdim[0]), round(self.ind2*self.pixdim[1]), round(self.ind1*self.pixdim[2])]) return self.ind3*self.pixdim[0], self.ind2*self.pixdim[1], self.ind1*self.pixdim[2]#event def showpopupmenu(self,widget,event): print('button ',event.button) if event.button == 3: m = self.builder.get_object("menufunctions") print(widget, event) m.show_all() m.popup(None,None,None,3,0) def get_color_maps(self): self.color_list = [] m = inspect.getmembers(cm) for i in m: try: if i[1].__module__ == 'matplotlib.colors': self.color_list.append(i[0]) except: pass self.populate_combo(colorlabels=self.color_list) def populate_combo(self, colorlabels=None): print 'populating channel list' #if colorlabels == None: #colorlabels = arange(50) combobox = self.builder.get_object("combobox1") combobox.clear() liststore = gtk.ListStore(str) cell = gtk.CellRendererText() combobox.pack_start(cell) combobox.add_attribute(cell, 'text', 0) combobox.set_wrap_width(int(ceil(sqrt(len(colorlabels))))) for n in colorlabels: #range(50): liststore.append([n]) combobox.set_model(liststore) combobox.connect('changed', self.changed_cb) try: prefs = readwrite.readdata(os.getenv('HOME')+'/.pymeg.pym') combobox.set_active(prefs['MRI_color']) print 'Setting color scheme to last' except: combobox.set_active(0) return def changed_cb(self, combobox): model = combobox.get_model() index = combobox.get_active() if index > -1: print model[index][0], 'selected','index',index #self.chan_ind = index self.color_sel = str(model[index][0]) #self.im1.axes.clear() print 'debug' self.im1.set_cmap(self.color_sel) self.im1.axes.figure.canvas.draw() self.im2.set_cmap(self.color_sel) self.im2.axes.figure.canvas.draw() self.im3.set_cmap(self.color_sel) self.im3.axes.figure.canvas.draw() try: prefs = readwrite.readdata(os.getenv('HOME')+'/.pymeg.pym') prefs['MRI_color'] = index readwrite.writedata(prefs, os.getenv('HOME')+'/.pymeg') except IOError: pass return def display(self,data=None, overlay=None, colormap=cm.gray, pixdim=None, translation=None): self.get_color_maps() try: if os.path.splitext(data.__module__)[0] == 'nibabel': print 'nibabel loaded data' self.filename = data.get_filename() self.hdr = data.get_header() pixdim = self.hdr['pixdim'][1:4] transform = data._affine[0:3,0:3];print 'orig trans',transform translation = data._affine[0:3,3]; print 'translation', translation data = squeeze(data.get_data()) self.img = data except: #Not a nifti or analyze file, raw data pass if translation == None: translation == [0,0,0] if pixdim == None: pixdim = [1.0,1.0,1.0]; #unitless ax1 = self.fig.add_subplot(221);#axis('off') #colorbar(fig,ax=ax1) xlabel('Anterior (A->P 1st Dim)');#ylabel('Right (R->L 2nd Dim)') ax2 = self.fig.add_subplot(222);#axis('off') xlabel('Inferior (I->S Dim)');#ylabel('Anterior (A->P 1st Dim)') ax3 = self.fig.add_subplot(223);#axis('off') xlabel('Infererior (I->S 3rd dim)');#ylabel('Right (R->L 2nd Dim)') #ax4 = self.fig.add_subplot(224);ax4.axis('off') #coord = self.fig.add_subplot(224);axis('off') tracker = self.IndexTracker(data, ax1, ax2, ax3, colormap, pixdim, overlay, translation)#, coord) self.fig.canvas.mpl_connect('scroll_event', self.onscroll) self.fig.canvas.mpl_connect('button_press_event', self.click) #ax1.imshow(data[100]) print 'plot setup done' return tracker
def init(self,index): self.index=index self.fig = Figure(figsize=(5,4), dpi=100) self.ax1=None self.show_key=True self.hbox=gtk.HBox() self.edit_list=[] self.line_number=[] gui_pos=0 self.list=[] self.load_data() self.update_scan_tokens() gui_pos=gui_pos+1 canvas = FigureCanvas(self.fig) # a gtk.DrawingArea #canvas.set_background('white') #canvas.set_facecolor('white') canvas.figure.patch.set_facecolor('white') canvas.set_size_request(500, 150) canvas.show() tooltips = gtk.Tooltips() toolbar = gtk.Toolbar() #toolbar.set_orientation(gtk.ORIENTATION_VERTICAL) toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_size_request(-1, 50) self.store = self.create_model() treeview = gtk.TreeView(self.store) treeview.show() tool_bar_pos=0 save = gtk.ToolButton(gtk.STOCK_SAVE) tooltips.set_tip(save, _("Save image")) save.connect("clicked", self.callback_save) toolbar.insert(save, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 add_section = gtk.ToolButton(gtk.STOCK_ADD) tooltips.set_tip(add_section, _("Add section")) add_section.connect("clicked", self.callback_add_section,treeview) toolbar.insert(add_section, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 add_section = gtk.ToolButton(gtk.STOCK_CLEAR) tooltips.set_tip(add_section, _("Delete section")) add_section.connect("clicked", self.callback_remove_item,treeview) toolbar.insert(add_section, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 move_down = gtk.ToolButton(gtk.STOCK_GO_DOWN) tooltips.set_tip(move_down, _("Move down")) move_down.connect("clicked", self.callback_move_down,treeview) toolbar.insert(move_down, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 image = gtk.Image() image.set_from_file(os.path.join(get_image_file_path(),"start.png")) start = gtk.ToolButton(image) tooltips.set_tip(start, _("Simulation start frequency")) start.connect("clicked", self.callback_start_fx,treeview) toolbar.insert(start, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 plot_toolbar = NavigationToolbar(self.fig.canvas, self) plot_toolbar.show() box=gtk.HBox(True, 1) box.set_size_request(300,-1) box.show() box.pack_start(plot_toolbar, True, True, 0) tb_comboitem = gtk.ToolItem(); tb_comboitem.add(box); tb_comboitem.show() toolbar.insert(tb_comboitem, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 sep = gtk.SeparatorToolItem() sep.set_draw(False) sep.set_expand(True) toolbar.insert(sep, tool_bar_pos) sep.show() tool_bar_pos=tool_bar_pos+1 help = gtk.ToolButton(gtk.STOCK_HELP) toolbar.insert(help, tool_bar_pos) help.connect("clicked", self.callback_help) help.show() tool_bar_pos=tool_bar_pos+1 toolbar.show_all() self.pack_start(toolbar, False, True, 0) self.pack_start(toolbar, True, True, 0) tool_bar_pos=tool_bar_pos+1 canvas.set_size_request(700,400) self.pack_start(canvas, True, True, 0) treeview.set_rules_hint(True) self.create_columns(treeview) self.pack_start(treeview, False, False, 0) self.statusbar = gtk.Statusbar() self.statusbar.show() self.pack_start(self.statusbar, False, False, 0) self.build_mesh() self.draw_graph() self.show()
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()
def init(self): self.fig = Figure(figsize=(5,4), dpi=100) self.ax1=None self.show_key=True self.hbox=gtk.HBox() self.exe_command = get_exe_command() self.edit_list=[] self.line_number=[] gui_pos=0 gui_pos=gui_pos+1 self.draw_graph() canvas = FigureCanvas(self.fig) # a gtk.DrawingArea #canvas.set_background('white') #canvas.set_facecolor('white') canvas.figure.patch.set_facecolor('white') canvas.set_size_request(500, 150) canvas.show() tooltips = gtk.Tooltips() toolbar = gtk.Toolbar() #toolbar.set_orientation(gtk.ORIENTATION_VERTICAL) toolbar.set_style(gtk.TOOLBAR_ICONS) toolbar.set_size_request(-1, 50) tool_bar_pos=0 save = gtk.ToolButton(gtk.STOCK_SAVE) tooltips.set_tip(save, "Save image") save.connect("clicked", self.callback_save) toolbar.insert(save, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 hide_key = gtk.ToolButton(gtk.STOCK_INFO) tooltips.set_tip(hide_key, "Hide key") hide_key.connect("clicked", self.callback_hide_key) toolbar.insert(hide_key, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 image = gtk.Image() image.set_from_file(os.path.join(get_image_file_path(),"play.png")) save = gtk.ToolButton(image) tooltips.set_tip(save, "Run simulation") save.connect("clicked", self.callback_refresh) toolbar.insert(save, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 plot_toolbar = NavigationToolbar(canvas, self) plot_toolbar.show() box=gtk.HBox(True, 1) box.set_size_request(500,-1) box.show() box.pack_start(plot_toolbar, True, True, 0) tb_comboitem = gtk.ToolItem(); tb_comboitem.add(box); tb_comboitem.show() toolbar.insert(tb_comboitem, tool_bar_pos) tool_bar_pos=tool_bar_pos+1 sep = gtk.SeparatorToolItem() sep.set_draw(False) sep.set_expand(True) toolbar.insert(sep, tool_bar_pos) sep.show() tool_bar_pos=tool_bar_pos+1 toolbar.show_all() window_main_vbox=gtk.VBox() window_main_vbox.pack_start(toolbar, False, True, 0) #self.attach(toolbar, 0, 1, 0, 1) tool_bar_pos=tool_bar_pos+1 self.hbox.pack_start(canvas, True, True, 0) #self.attach(canvas, 1, 3, 0, 1) vbox = gtk.VBox(False, 2) #spacer label=gtk.Label(" \n\n ") #self.attach(label, 4, 5, 1, 2,gtk.SHRINK ,gtk.SHRINK) vbox.pack_start(label, False, False, 0) label.show() hbox = gtk.HBox(False, 2) hbox.show() self.hbox.pack_start(vbox, False, False, 0) #self.attach(vbox, 3, 4, 0, 1,gtk.SHRINK ,gtk.SHRINK) vbox.show() window_main_vbox.add(self.hbox) self.add(window_main_vbox) self.set_title("Quantum Efficency calculator - (www.opvdm.com)") self.set_icon_from_file(os.path.join(get_image_file_path(),"qe.png")) self.connect("delete-event", self.callback_close) self.set_position(gtk.WIN_POS_CENTER)
class PlotViewer(gtk.VBox): def __init__ (self, plotters, fields): gtk.VBox.__init__ (self) self.figure = mpl.figure.Figure () self.canvas = FigureCanvas (self.figure) self.canvas.unset_flags (gtk.CAN_FOCUS) self.canvas.set_size_request (600, 400) self.pack_start (self.canvas, True, True) self.canvas.show () self.navToolbar = NavigationToolbar (self.canvas, self.window) #self.navToolbar.lastDir = '/tmp' self.pack_start (self.navToolbar, False, False) self.navToolbar.show () self.checkboxes = gtk.HBox (len (plotters)) self.pack_start (self.checkboxes, False, False) self.checkboxes.show () self.pol = (1+0j, 0j) self.pol2 = None self.handlers = [] i = 0 self.plots = [] for plotterClass, default in plotters: axes = self.figure.add_subplot (len (plotters), 1, i) def makeUpdateInfo (i): return lambda s: self.__updateInfo (i, s) def makeUpdatePos (i): return lambda s: self.__updatePos (i, s) plotter = plotterClass (axes, fields, makeUpdateInfo (i), makeUpdatePos (i)) d = PlottedData (axes, plotter, default, self.__updateChildren) self.checkboxes.pack_start (d.checkBox, False, False) self.plots.append (d) i += 1 self.__infos = [None] * len (self.plots) self.__posi = None self.legendBox = gtk.CheckButton ("Show legend") self.legendBox.set_active (True) self.legendBox.connect ("toggled", self.__on_legend_toggled) self.checkboxes.pack_start (self.legendBox, False, False) self.legendBox.show () self.__updateChildren () def __on_legend_toggled (self, button): for pd in self.plots: pd.plotter.setLegend (button.get_active ()) def __updateChildren (self): count = 0 for axes in self.figure.get_axes (): visible = axes.get_visible () if axes.get_visible (): count += 1 if count == 0: count = 1 nr = 1 for axes in self.figure.get_axes (): axes.change_geometry (count, 1, nr) if axes.get_visible (): if nr < count: nr += 1 else: axes.set_position ((0, 0, 1e-10, 1e-10)) # Hack to prevent the invisible axes from getting mouse events self.figure.canvas.draw () self.__updateGraph () def __updateGraph (self): for pd in self.plots: if pd.axes.get_visible (): #start = time () pd.plotter.plot (self.pol, self.pol2) #print "Plot ", pd.plotter.description, " needed ", time () - start def __updateInfo (self, i, arg): #print i, arg self.__infos[i] = arg s = '' for info in self.__infos: if info is not None: if s != '': s += ' ' s += info for handler in self.handlers: handler (s) def __updatePos (self, i, arg): if arg == None and self.__posi != i: return self.__posi = i j = 0 for pd in self.plots: if i != j: pd.plotter.updateCPos (arg) j += 1 def onUpdateInfo (self, handler): self.handlers.append (handler) def setPol (self, value): oldValue = self.pol self.pol = value if value != oldValue: self.__updateGraph () def setPol2 (self, value): oldValue = self.pol2 self.pol2 = value if value != oldValue: self.__updateGraph ()
class DDTF(gtk.Window): def ddtf(self,el1,el2,el3,sample_rate=400,duration=20,step=128,increment=5): # notes: duration is the length of a window in seconds # increment is the length of a step in seconds # step is the num points in an fft-analysis epoch N = len(el1) dt = 1/float(sample_rate) fNyq = sample_rate/2 df = 1/(step*dt) f = np.arange(0,fNyq,df) #Frequency axis for the FFT count = 0 end_step = N - duration*sample_rate print "end_step ", end_step print "stepping by ", increment * sample_rate for w in np.arange(0,end_step, increment * sample_rate): x=el1[w:w+duration*sample_rate] # should this be - 1 or 2? y=el2[w:w+duration*sample_rate] z=el3[w:w+duration*sample_rate] # Initialize the Cross-Spectral arrays for averaging print "step first is : ", step Sxx=np.zeros((1,step - 1)); # - 1 here? print "Sxx: " , Sxx.shape Syy=Sxx Szz=Sxx Sxy=Sxx Sxz=Sxx Syz=Sxx Szy=Sxx print "xshape : ", x.shape print "Sxx shape : ", Sxx.shape xtemp=np.arange(0,step-1) xtemp_ones = np.ones(len(xtemp)) print "xtempshape: ", xtemp.shape A = np.vstack([xtemp,xtemp_ones]).T print "A shape: ", A.shape inner_end_step = sample_rate*duration - step print "inner_end_step ", inner_end_step print "step ", step for i in np.arange(0,inner_end_step - 1,step): m,b = np.linalg.lstsq(A,x[i:i+step-1])[0] # the minus 1? print "m, b: ", m, b trend = m*xtemp + b # print "istep : ", (i+step-1) x[i:i+step-1] = x[i:i+step-1] - trend # detrend x[i:i+step-1] = x[i:i+step-1] - np.mean(x[i:i+step-1]) # demean fx = np.fft.fft(x[i:i+step-1] * np.hanning(step-1).T) # windowed fft m,b = np.linalg.lstsq(A,y[i:i+step-1])[0] # the minus 1? trend = m*xtemp + b y[i:i+step-1] = y[i:i+step-1] - trend # detrend y[i:i+step-1] = y[i:i+step-1] - np.mean(y[i:i+step-1]) # demean fy = np.fft.fft(y[i:i+step-1] * np.hanning(step-1).T) # windowed fft m,b = np.linalg.lstsq(A,z[i:i+step-1])[0] # the minus 1? trend = m*xtemp + b z[i:i+step-1] = z[i:i+step-1] - trend # detrend z[i:i+step-1] = z[i:i+step-1] - np.mean(z[i:i+step-1]) # demean fz = np.fft.fft(z[i:i+step-1] * np.hanning(step-1).T) # windowed fft # print "fs are ", fx, fy, fz # print "fxconf ", fx.conj() # print "Sxx ", Sxx.shape, Sxx.shape # print "fxstuff ", ((fx * fx.conj())).shape Sxx=Sxx+(fx * fx.conj()) # print "Sxx2 ", Sxx.shape Syy=Syy+(fy * fy.conj()) Szz=Szz+(fx * fz.conj()) Sxy=Sxy+(fx * fx.conj()) Sxz=Sxz+(fx * fy.conj()) Syz=Syz+(fy * fy.conj()) # print "Sxx shape: ", Sxx.shape # print "Sxy shape: ", Sxy.shape # print "Szy shape: ", Sxx.shape # print "Syz shape: ", Syz.shape Syx = Sxy.conj().T Szx = Sxz.conj().T Szy = Syz.conj().T S11=abs(Sxx)**2 S12=abs(Sxy)**2 S13=abs(Sxz)**2 S21=abs(Syx)**2 S22=abs(Syy)**2 S23=abs(Syz)**2 S31=abs(Szx)**2 S32=abs(Szy)**2 S33=abs(Szz)**2 sumS = S11 + S12 + S13 sumS2 = S21 + S22 + S23 sumS3 = S31 + S32 + S33 NS11 = S11 / S11.max() NS12 = S12 / sumS NS13 = S13 / sumS NS21 = S21 / sumS2 NS22 = S22 / S22.max() NS23 = S23 / sumS2 NS31 = S31 / sumS3 NS32 = S32 / sumS3 NS33 = S33 / S33.max() count += 1 ttle1='Spectrum el1' ttle2=' el2 - . el1' ttle3=' el3 - . el1' ttle4=' el1 - . el2' ttle5=' Spectrum el2' ttle6=' el3 - . el2' ttle7=' el1 - . el3' ttle8='el2 - . el3' ttle9='Spectrum el3' # print "ns11 shape ", NS11.shape # print "f shape ", f.shape # print "f is: " , f # print "step is: ", step # print "shape x, y ", f[1:step/4].shape, NS11[1:step/4].shape # plot.subplot(211) # plot.axis([0, 60, 0, 1]) # print (NS12, NS13, NS21, NS22, NS23, NS31, NS32, NS33) return (f ,step,NS11, NS12, NS13, NS21, NS22, NS23, NS31, NS32, NS33) def delete_event(self, widget, event, data=None): return False def destroy(self,widget, data=None): gtk.main_quit() def __init__(self): super(DDTF,self).__init__() self.connect("delete_event", self.delete_event) self.connect("destroy", self.destroy) e1,e2,e3 = signal_gen.signal_gen(.2,.01,.001) (f ,step,NS11, NS12, NS13, NS21, NS22, NS23, NS31, NS32, NS33) = self.ddtf(e1,e2,e3) # gtk.Window.__init__(self) self.fig = Figure(figsize = (20,15), dpi=72) self.canvas = FigureCanvas(self.fig) self.canvas.set_size_request(1800, 640) t = np.arange(0.0,50.0, 0.01) xlim = np.array([0,10]) self.axes = self.fig.add_axes([0.075, 0.25, 0.9, 0.725], axisbg='#FFFFCC') self.axes.plot(t, np.sin(2*0.32*np.pi*t) * np.sin(2*2.44*np.pi*t) ) self.axes.set_xlim([0.0,10.0]) self.axes.set_xticklabels([]) self.axesSpec = self.fig.add_axes([0.075, 0.05, 0.9, 0.2]) t = self.axesSpec.text( 0.5, 0.5, 'Click on EEG channel for spectrogram (scroll mouse to expand)', verticalalignment='center', horizontalalignment='center', ) t.set_transform(self.axes.transAxes) self.axesSpec.set_xlim([0.0,10.0]) self.axesSpec.set_xticklabels([]) self.axesSpec.set_yticklabels([]) self.canvas.show() self.show() # self.axes.plot(f[step/4],NS11[:,0:step/4],'k') # plot.plot([1,2,3,4]) # plot.show() def main(self): gtk.main()
def drawStackedBars(self, xvalues, yvalues, ylabel, title, valuesAreTime=False, colors={}): '''function to draw stacked bars xvalues needs to be a list of lists of strings, e.g. [0]["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] yvalues needs to be a list of dicts e.g. [0]{'Kayak': {'Tue': 10.08, 'Fri': 17.579999999999998, 'Thu': 15.66, 'Sat': 30.619999999999997}, {'Run': {'Mon': 9.65, 'Sun': 15.59}} ''' #TODO tidy logging.debug('>>') logging.debug("Title: %s", (title, )) logging.debug("X values received: %s", str(xvalues)) logging.debug("Y values received: %s", str(yvalues)) self.removeVboxChildren() #Check how many axes to draw if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 else: #Error return keys = yvalues[0].keys() # days of the week numRows = len(keys) numCols = len(xvalues[0]) if numRows == 0: return width = .8 #figure = plt.figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) axis = plt.subplot(111) ybottoms = [0] * numCols yheights = [0] * numCols inds = xrange(0, numCols) xvals = [x + barOffset for x in range(0, numCols)] cellText = [] self.showGraph = False for k in colors: if colors[k] == None: colors[k] = '' #Display first axis xticks = [] for key in keys: logging.debug("Day of the week: %s", str(key)) for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[0][key]: height = yvalues[0][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height cellText.append( [self.fmtTableText(x, valuesAreTime[0]) for x in yheights]) if self.showGraph: axis.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results pass axis.set_xticklabels('' * len(xvalues[0])) axis.set_ylabel(ylabel[0]) if len(xvalues) == 1: plt.title(title[0]) axis.legend(loc=0) axis.set_xlim(0, numCols) logging.debug("X values first axis: %s", str(xvals)) logging.debug("Y values first axis: %s", str(yheights)) #Display twin axis if len(xvalues) == 2: self.showGraph = False ax2 = axis.twinx() keys = yvalues[1].keys() ybottoms = [0] * numCols yheights = [self.NEARLY_ZERO] * numCols for key in keys: for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0.0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[1][key]: height = yvalues[1][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height textToAdd = self.fmtTableText(height, valuesAreTime[1]) if textToAdd is not ' ': row = keys.index(key) col = index cellText[row][col] += " | %s" % (self.fmtTableText( height, valuesAreTime[1])) #print "Would add %s to %s %s" % (self.fmtTableText(height, valuesAreTime[1]), index, keys.index(key)) if self.showGraph: xvals = [ x + barOffset + barWidth for x in range(0, numCols) ] #print "ax2", xvals, yheights, ybottoms ax2.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results ax2.bar(xvals, [0] * numCols, bottom=[0] * numCols, width=barWidth, color=color, align='edge', label=key) pass ax2.set_xticklabels('' * len(xvalues[1])) ax2.set_xlim(0, numCols) ax2.set_ylabel(ylabel[1]) ax2.legend(loc=0) plt.title("%s vs %s" % (title[0], title[1])) ## try to do some table stuff colLabels = xvalues[0] rowLabels = keys axis.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, colLabels=colLabels, loc='bottom') plt.subplots_adjust(left=0.15, bottom=0.08 + (0.03 * numRows)) axis.grid(True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<')
class PlotGui(object): def get_bg_bbox(self): return self.ax.bbox.padded(-3) def __init__(self, stats, interface=None, file=None, combine=False): if len(stats) == 1: combine = True self.interface = interface self.file = file self.combine = combine path = os.path.realpath(os.path.dirname(sys.argv[0])) self.builder = gtk.Builder() """ try: self.builder.add_from_file(os.path.join(path,'plot.glade')) except: path = os.path.dirname( os.path.realpath( __file__ ) ) self.builder.add_from_file(os.path.join(path, 'plot.glade')) """ self.builder.add_from_string(resource_string(__name__, 'plot.glade')) self.builder.connect_signals(self) self.ui = self.builder.get_object('ui') self.pbox = self.builder.get_object('pbox') self.nbox = self.builder.get_object('nbox') self.figure = Figure() self.canvas = FigureCanvasGTKAgg(self.figure) self.canvas.set_size_request(600, 400) if combine: self.ax = self.figure.add_subplot(111) self.ax.grid(b=True, which='both') self.stats = {} c = 0 size = 0.2 + 0.025 * (len(stats) - 1) step = (1 - size) / len(stats) for s, sc in stats: self.stats[s] = {} self.stats[s]['scale'] = sc self.stats[s]['x'] = [] self.stats[s]['y'] = [] self.stats[s]['count'] = 0 if not self.combine: if c == 0: ax = self.figure.add_axes([0.1, 0.1, 0.8, step]) self.ax = ax self.ax.grid(b=True, which='both') else: ax = self.figure.add_axes( [0.1, 0.1 + c * (0.025 + step), 0.8, step], sharex=ax) ax.grid(b=True, which='both') setp(ax.get_xticklabels(), visible=False) self.stats[s]['ax'] = ax ax.set_ylabel(s) self.stats[s]['line'], = ax.plot([], [], label=s) #ax.legend() else: self.stats[s]['line'], = self.ax.plot([], [], label=s) c += 1 if self.combine: self.ax.legend(loc=(0., 1.), mode="expand", borderaxespad=0., ncol=len(self.stats)) self.xwidth = 30 self.t0 = -1 self.ax.set_xlim(0, self.xwidth) self.pbox.pack_start(self.canvas, True, True) self.navToolbar = NavigationToolbar(self.canvas, self.ui) self.nbox.pack_start(self.navToolbar) self.nbox.hide() self.canvas.show() self.pbox.show() self.ui.show() if not self.file: self.loop = task.LoopingCall(self.getValues) self.loop.start(1) else: self.nbox.show() self.builder.get_object('pauseButton').set_sensitive(False) self.builder.get_object('saveButton').set_sensitive(False) self.readFiles() def on_pauseButton_clicked(self, widget): if widget.get_label() == 'Pause': widget.set_label('Resume') self.nbox.show() self.loop.stop() self.update(True) else: widget.set_label('Pause') self.nbox.hide() self.loop.start(1) def on_closeButton_clicked(self, widget): try: self.loop.stop() except: pass self.ui.destroy() def on_ui_destroy(self, widget=None, data=None): try: self.loop.stop() except: pass def update(self, static=False): try: tlast = max([s['x'][-1] for s in self.stats.values()]) except: return if not static: t0 = tlast - self.xwidth if t0 < 0: t0 = 0 else: t0 = 0 for s in self.stats: st = self.stats[s] i = bisect(st['x'], t0) if i > 0: i = i - 1 toleft = st['x'][i] st['newx'] = st['x'][i:] st['newy'] = st['y'][i:] try: st['maxy'] = max(st['newy'][1:]) except: st['maxy'] = max(st['newy']) if not self.combine: limnow = st['ax'].get_ylim()[1] if abs(st['maxy'] - limnow) > st['maxy'] / 2 or st['maxy'] > limnow: st['ax'].set_ylim(-0.1, st['maxy'] * 1.2) self.ax.set_xlim(t0, tlast) if self.combine: ylim = max([s['maxy'] for s in self.stats.values()]) limnow = self.ax.get_ylim()[1] if abs(ylim - limnow) > ylim / 2 or ylim > limnow: self.ax.set_ylim(-0.1, ylim * 1.2) for s in self.stats.values(): s['line'].set_data(s['newx'], s['newy']) self.ax.figure.canvas.draw_idle() def getValues(self): self.interface.getStatValues(self.getStatValues, [(k, v['count']) for k, v in self.stats.items()]) def getStatValues(self, stats): update = False if self.t0 < 0: m = [v[1][0][1] for v in stats if v[1]] if m: self.t0 = min(m) for s, v, c in stats: #for b,t in v: # print b,t if not len(v): break st = self.stats[s] update = True x = [x[1] - self.t0 for x in v] y = [y[0] * st['scale'] for y in v] st['x'] = st['x'] + x st['y'] = st['y'] + y st['count'] = c if update: self.update() def on_saveButton_clicked(self, widget): if self.loop.running: self.on_pauseButton_clicked(self.builder.get_object('pauseButton')) self.builder.get_object('buttonBox').set_visible(False) self.builder.get_object('saveBox').set_visible(True) def on_cButton_clicked(self, widget=None): self.builder.get_object('buttonBox').set_visible(True) self.builder.get_object('saveBox').set_visible(False) def on_sButton_clicked(self, widget): en = self.builder.get_object('fileEntry').get_text() if not en: return file = os.path.join(get_user_data_dir(), 'stats') if not os.path.isdir(file): os.mkdir(file) en1 = en + '.stat' f = open(os.path.join(file, en1), 'w') for s, v in self.stats.items(): f.write(s + '\n') en2 = en + s f2 = open(os.path.join(file, en2), 'w') for i in range(len(v['x'])): line = str(v['x'][i]) + ',' + str( v['y'][i] / v['scale']) + '\n' f2.write(line) f2.close() f.close() self.on_cButton_clicked() def readFiles(self): en = self.file[:-5] dir = os.path.dirname(self.file) for s, v in self.stats.items(): en1 = en + s en1 = os.path.join(dir, en1) en1 = en1.rsplit()[0] f = open(en1, 'r') for line in f.readlines(): x, y = line.split(',') v['y'].append(float(y) * v['scale']) v['x'].append(float(x)) f.close() self.update(True)
def __init__(self, contours, neutral, SHOW_LINGUAGRAM, SHOW_NEUTRAL, SHOW_WAVEFORM, SHOW_SPECTROGRAM): '''center points determined by transforming the point (426, 393) several times with peterotron, and taking the average. ''' self.static_dir = os.getcwd() + '/' #self.centerX = 710 #self.centerY = 638 # these come from hand tuning to find the smallest range of y values of polar mags self.centerX = 665 self.centerY = 525 self.gladefile = self.static_dir + "LinguaViewer.glade" self.wTree = gtk.glade.XML(self.gladefile, "window1") self.win = self.wTree.get_widget("window1") self.win.set_title(contours) self.title = contours self.mainVBox = self.wTree.get_widget("vbox1") dic = { "on_window1_destroy": self.onDestroy, "on_tbPlay_clicked": self.playSound, "on_tbSave_clicked": self.onSave, "on_tbLabel_clicked": self.onLabel } self.wTree.signal_autoconnect(dic) self.X, self.Y = self.loadContours(contours) self.wavname = contours[:-4] + ".wav" #Linguagram if (SHOW_LINGUAGRAM == True): x1 = array(self.X) y1 = array(self.Y) Z = [] for i in range(len(self.X)): zs = [] for j in range(32): zs.append(i + 1) Z.append(zs) z1 = array(Z) self.fig = Figure() canvas = FigureCanvas(self.fig) #ax = Axes3D(self.fig, rect=[-.23,-.2,1.447,1.4]) ax = self.fig.add_subplot(1, 1, 1, projection='3d') self.fig.subplots_adjust(left=-0.23, bottom=0, right=1.215, top=1) ax.mouse_init() surf = ax.plot_surface(z1, -x1, -y1, rstride=1, cstride=1, cmap=cm.jet) ax.view_init(90, -90) canvas.show() canvas.set_size_request(600, 200) self.mainVBox.pack_start(canvas, True, True) #Neutral if (SHOW_NEUTRAL == True): cx, cy = self.getNeutral(neutral) cmags = self.makePolar(cx, cy) M = self.batchConvert2Polar(self.X, self.Y) #D = self.batchGetMinD(M, cmags) fakeX = [] for i in range(len(M)): xs = [] for j in range(1, 33): xs.append(j) fakeX.append(xs) x1 = array(fakeX) y1 = array(M) Z = [] for i in range(len(M)): zs = [] for j in range(32): zs.append(i) Z.append(zs) z1 = array(Z) self.fig3 = Figure() canvas3 = FigureCanvas(self.fig3) ax = self.fig3.add_subplot(1, 1, 1, projection='3d') self.fig3.subplots_adjust(left=-0.23, bottom=0, right=1.215, top=1) ax.mouse_init() ax.plot_surface(z1, -x1, y1, rstride=1, cstride=1, cmap=cm.jet) ax.view_init(90, -90) canvas3.show() canvas3.set_size_request(600, 200) self.mainVBox.pack_start(canvas3, True, True) #Waveform windowsize = 0 self.fig2 = Figure() canvas2 = FigureCanvas(self.fig2) if (SHOW_WAVEFORM == True): fs, snd = wavread(self.wavname) chan = snd[:, 0] t = array(range(len(chan))) / float(fs) if SHOW_SPECTROGRAM == True: wavax = self.fig2.add_subplot(2, 1, 1) else: wavax = self.fig2.add_subplot(1, 1, 1) wavax.plot(t, chan, 'black') wavax.set_xlim(0, max(t)) windowsize += 200 #Spectrogram if (SHOW_SPECTROGRAM == True): '''This calls Praat to get the spectrogram and adds it to the viewer''' specname = contours[:-4] + '.Spectrogram' cleanname = contours[:-4] + '.clean' cmd = [ '/Applications/Praat.app/Contents/MacOS/Praat', self.static_dir + 'makeSpec.praat', self.wavname, specname ] proc = subprocess.Popen(cmd) status = proc.wait() cmd2 = [ 'bash', self.static_dir + 'cleanspec.sh', specname, cleanname ] proc2 = subprocess.Popen(cmd2) status2 = proc2.wait() f = open(cleanname, 'r').readlines() last = len(f) - 1 x = f[last].split('\t') rows = int(x[0]) cols = int(x[1]) img = zeros((rows, cols)) for i in range(len(f)): x = f[i][:-1].split('\t') img[int(x[0]) - 1, int(x[1]) - 1] = float(x[2]) img = log(img) if SHOW_WAVEFORM == True: specax = self.fig2.add_subplot(2, 1, 2) else: specax = self.fig2.add_subplot(1, 1, 1) specax.imshow(img, cmap=cm.gray_r, origin='lower', aspect='auto') windowsize += 200 # show it if (SHOW_WAVEFORM == True) or (SHOW_SPECTROGRAM == True): canvas2.show() canvas2.set_size_request(600, windowsize) self.mainVBox.pack_start(canvas2, True, True) self.SHOW_LINGUAGRAM = SHOW_LINGUAGRAM self.SHOW_NEUTRAL = SHOW_NEUTRAL self.SHOW_WAVEFORM = SHOW_WAVEFORM self.SHOW_SPECTROGRAM = SHOW_SPECTROGRAM self.windowsize = windowsize
def __init__(self, data_file, plot_groups=[1], data_type=2, color_map='jet', plot_contours=False, plot_label="", plot_bands=None, time_zone=0, plot_max_freq=30.0, run_quietly=False, save_file='', dpi=150, parent=None): self.data_type = data_type self.run_quietly = run_quietly self.dpi = dpi self.df = VOAOutFile(data_file, time_zone=time_zone, data_type=self.data_type, quiet=run_quietly) self.image_defs = self.IMG_TYPE_DICT[self.data_type] color_map = eval('P.cm.' + color_map) if plot_groups[0] == 'a': num_grp = self.df.get_number_of_groups() plot_groups = range(0, num_grp) self.subplots = [] number_of_subplots = len(plot_groups) matplotlib.rcParams['axes.edgecolor'] = 'gray' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['axes.grid'] = True matplotlib.rcParams['figure.facecolor'] = 'white' matplotlib.rcParams['legend.fancybox'] = True matplotlib.rcParams['legend.shadow'] = True matplotlib.rcParams['figure.subplot.hspace'] = 0.45 matplotlib.rcParams['figure.subplot.wspace'] = 0.35 matplotlib.rcParams['figure.subplot.right'] = 0.85 colorbar_fontsize = 12 if number_of_subplots <= 1: self.num_rows = 1 self.main_title_fontsize = 24 matplotlib.rcParams['legend.fontsize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['axes.titlesize'] = 8 matplotlib.rcParams['xtick.labelsize'] = 10 matplotlib.rcParams['ytick.labelsize'] = 10 matplotlib.rcParams[ 'figure.subplot.top'] = 0.79 # single figure plots have a larger title so require more space at the top. self.x_axes_ticks = P.arange(0, 25, 2) elif ((number_of_subplots >= 2) and (number_of_subplots <= 6)): self.num_rows = 2 self.main_title_fontsize = 18 matplotlib.rcParams['legend.fontsize'] = 10 matplotlib.rcParams['axes.labelsize'] = 10 matplotlib.rcParams['axes.titlesize'] = 11 matplotlib.rcParams['xtick.labelsize'] = 8 matplotlib.rcParams['ytick.labelsize'] = 8 self.x_axes_ticks = P.arange(0, 25, 4) else: self.num_rows = 3 self.main_title_fontsize = 16 matplotlib.rcParams['legend.fontsize'] = 8 matplotlib.rcParams['axes.labelsize'] = 8 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 6 matplotlib.rcParams['ytick.labelsize'] = 6 self.x_axes_ticks = P.arange(0, 25, 4) self.num_cols = int( math.ceil(float(number_of_subplots) / float(self.num_rows))) self.fig = Figure(figsize=(7, 6.5)) self.main_title_label = self.fig.suptitle( plot_label + unicode(self.image_defs['title'], 'utf-8'), fontsize=self.main_title_fontsize) for chan_grp in plot_groups: (group_name, group_info, fot, muf, hpf, image_buffer) = self.df.get_group_data(chan_grp) ax = self.fig.add_subplot(self.num_rows, self.num_cols, plot_groups.index(chan_grp) + 1) self.subplots.append(ax) if number_of_subplots > 4: #save a little space by only labelling the outer edges of the plot ax.label_outer() _sign = '+' if (time_zone >= 0) else '' self.x_label = ax.set_xlabel( _('Time (UTC%(sig)s%(tz)s)') % { 'sig': _sign, 'tz': time_zone }) self.y_label = ax.set_ylabel(_('Frequency (MHz)')) ## Autoscale y (frequency axis) if (plot_max_freq == self.AUTOSCALE): y_max = math.ceil(max(muf) / 5.0) * 5.0 y_max = min(plot_max_freq, 30.0) y_max = max(plot_max_freq, 5.0) else: y_max = math.ceil(plot_max_freq / 5.0) * 5.0 #resize the image image_buffer = image_buffer[0:y_max - 1, :] y_ticks = [2, 5] for y_tick_value in P.arange(10, y_max + 1, 5): y_ticks.append(y_tick_value) ax.plot(range(0, 25), muf, 'r-', range(0, 25), fot, 'g-') ax.set_ylim([2, y_max]) ax.set_xticks(self.x_axes_ticks) ax.set_yticks(y_ticks) self.add_legend(ax) title_str = group_info.strip() if number_of_subplots > 1: title_str = self.get_small_title(title_str) self.subplot_title_label = ax.set_title(title_str, multialignment='left', **self.mono_font) if (self.data_type > 0): im = ax.imshow(image_buffer, interpolation='bicubic', extent=(0, 24, 2, y_max), origin='lower', cmap=color_map, alpha=0.95, norm=P.Normalize(clip=False, vmin=self.image_defs['min'], vmax=self.image_defs['max'])) if plot_contours: ax.contour(image_buffer, self.image_defs['y_labels'], extent=(0, 24, 2, y_max), linewidths=1.0, colors='k', alpha=0.6) if plot_bands: for a, b in plot_bands: ax.axhspan(a, b, alpha=0.5, ec='k', fc='k') if (self.data_type > 0): self.cb_ax = self.fig.add_axes(self.get_cb_axes()) self.fig.colorbar(im, cax=self.cb_ax, orientation='vertical', format=P.FuncFormatter( eval('self.' + self.image_defs['formatter']))) for t in self.cb_ax.get_yticklabels(): t.set_fontsize(colorbar_fontsize) canvas = FigureCanvasGTKAgg(self.fig) self.fig.canvas.mpl_connect('draw_event', self.on_draw) canvas.show() if save_file: self.save_plot(canvas, save_file) if not self.run_quietly: # TODO consider using a scrolled pane here... dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent, dpi=self.dpi) return
def __init__(self, contours, neutral, SHOW_LINGUAGRAM, SHOW_NEUTRAL, SHOW_WAVEFORM, SHOW_SPECTROGRAM): '''center points determined by transforming the point (426, 393) several times with peterotron, and taking the average. ''' self.static_dir = os.getcwd() + '/' #self.centerX = 710 #self.centerY = 638 # these come from hand tuning to find the smallest range of y values of polar mags self.centerX = 665 self.centerY = 525 self.gladefile = self.static_dir + "LinguaViewer.glade" self.wTree = gtk.glade.XML(self.gladefile, "window1") self.win = self.wTree.get_widget("window1") self.win.set_title(contours) self.title = contours self.mainVBox = self.wTree.get_widget("vbox1") dic = { "on_window1_destroy": self.onDestroy, "on_tbPlay_clicked" : self.playSound, "on_tbSave_clicked" : self.onSave, "on_tbLabel_clicked": self.onLabel} self.wTree.signal_autoconnect(dic) self.X, self.Y = self.loadContours(contours) self.wavname = contours[:-4] + ".wav" #Linguagram if (SHOW_LINGUAGRAM == True): x1 = array(self.X) y1 = array(self.Y) Z = [] for i in range(len(self.X)): zs = [] for j in range(32): zs.append(i+1) Z.append(zs) z1 = array(Z) self.fig = Figure() canvas = FigureCanvas(self.fig) #ax = Axes3D(self.fig, rect=[-.23,-.2,1.447,1.4]) ax = self.fig.add_subplot(1, 1, 1, projection='3d') self.fig.subplots_adjust(left=-0.23, bottom=0, right=1.215, top=1) ax.mouse_init() surf = ax.plot_surface(z1, -x1, -y1, rstride=1, cstride=1, cmap=cm.jet) ax.view_init(90,-90) canvas.show() canvas.set_size_request(600, 200) self.mainVBox.pack_start(canvas, True, True) #Neutral if (SHOW_NEUTRAL == True): cx, cy = self.getNeutral(neutral) cmags = self.makePolar(cx, cy) M = self.batchConvert2Polar(self.X, self.Y) #D = self.batchGetMinD(M, cmags) fakeX = [] for i in range(len(M)): xs = [] for j in range(1,33): xs.append(j) fakeX.append(xs) x1 = array(fakeX) y1 = array(M) Z = [] for i in range(len(M)): zs = [] for j in range(32): zs.append(i) Z.append(zs) z1 = array(Z) self.fig3 = Figure() canvas3 = FigureCanvas(self.fig3) ax = self.fig3.add_subplot(1, 1, 1, projection='3d') self.fig3.subplots_adjust(left=-0.23, bottom=0, right=1.215, top=1) ax.mouse_init() ax.plot_surface(z1, -x1, y1, rstride=1, cstride=1, cmap=cm.jet) ax.view_init(90,-90) canvas3.show() canvas3.set_size_request(600, 200) self.mainVBox.pack_start(canvas3, True, True) #Waveform windowsize = 0 self.fig2 = Figure() canvas2 = FigureCanvas(self.fig2) if (SHOW_WAVEFORM == True): fs, snd = wavread(self.wavname) chan = snd[:,0] t=array(range(len(chan)))/float(fs); if SHOW_SPECTROGRAM == True: wavax = self.fig2.add_subplot(2, 1, 1) else: wavax = self.fig2.add_subplot(1, 1, 1) wavax.plot(t,chan,'black'); wavax.set_xlim(0,max(t)) windowsize += 200 #Spectrogram if (SHOW_SPECTROGRAM == True): '''This calls Praat to get the spectrogram and adds it to the viewer''' specname = contours[:-4] + '.Spectrogram' cleanname = contours[:-4] + '.clean' cmd = ['/Applications/Praat.app/Contents/MacOS/Praat', self.static_dir + 'makeSpec.praat', self.wavname, specname] proc = subprocess.Popen(cmd) status = proc.wait() cmd2 = ['bash', self.static_dir + 'cleanspec.sh', specname, cleanname] proc2 = subprocess.Popen(cmd2) status2 = proc2.wait() f = open(cleanname, 'r').readlines() last = len(f)-1 x = f[last].split('\t') rows = int(x[0]) cols = int(x[1]) img = zeros((rows, cols)) for i in range(len(f)): x = f[i][:-1].split('\t') img[int(x[0])-1,int(x[1])-1] = float(x[2]) img = log(img) if SHOW_WAVEFORM == True: specax = self.fig2.add_subplot(2, 1, 2) else: specax = self.fig2.add_subplot(1, 1, 1) specax.imshow(img, cmap=cm.gray_r, origin='lower', aspect='auto') windowsize += 200 # show it if (SHOW_WAVEFORM == True) or (SHOW_SPECTROGRAM == True): canvas2.show() canvas2.set_size_request(600, windowsize) self.mainVBox.pack_start(canvas2, True, True) self.SHOW_LINGUAGRAM = SHOW_LINGUAGRAM self.SHOW_NEUTRAL = SHOW_NEUTRAL self.SHOW_WAVEFORM = SHOW_WAVEFORM self.SHOW_SPECTROGRAM = SHOW_SPECTROGRAM self.windowsize = windowsize
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 RTP_motor_gui(object): # This is a callback function. The data arguments are ignored # in this example. More on callbacks below. def swept_sine_test(self, widget, data=None): print('in swept_sine_test') self.test.use_accel_fb = False stopn = 20000 amp = 30 maxf = 10 wp = 18.5*2*pi wz = 16.5*2*pi zz = 0.1 zp = 0.5 G_notch = controls.TransferFunction([1,2*wz*zz,wz**2],\ [1,2*wp*zp,wp**2])*(wp**2/wz**2) kwargs = {'amp':amp, 'minf':0.0, 'maxf':maxf, 'plot':False,\ 'stopn':stopn, 'plot':False} #self.test.Swept_Sine(**kwargs) #self.test.Notched_Swept_Sine(G_notch, **kwargs) self.test.Close_Serial() self.P_control_test = SLFR_RTP.P_control_Test(kp=1.0, neg_accel=neg_accel) self.P_control_test.Swept_Sine(**kwargs) self.plot_results(test=self.P_control_test, legloc=3) def plot_results(self, legloc=4, test=None): if test is None: test = self.test self.ax.cla() self.t = test.nvect*self.test.dt ## attrs = ['uvect','vvect','yvect','avect','thd_hatvect'] ## labels = ['u','v','$\\theta$','a','$\\hat{\\theta}_d$'] attrs = ['uvect','yvect'] labels = ['u','$\\theta$'] for attr, label in zip(attrs, labels): if hasattr(test, attr): data = getattr(test, attr) self.ax.plot(self.t, data, label=label) self.ax.legend(loc=legloc) self.ax.set_xlabel('Time (sec.)') self.ax.set_ylabel('Signal Amplitude (counts)') self.f.canvas.draw() def step_test(self, widget, data=None): if self.debug > 0: print('in step_test') #active = self.vib_check.get_active() #toggled = self.vib_check.toggled() self.test.Reset_Theta() time.sleep(0.05) self.test.Step_Response(amp=200, stopn=1000, plot=False)#, **kwargs)#, step_ind=10, \ ## off_ind=100, plot=True, fi=1, clear=True, \ ## legloc=5) self.test.Close_Serial() self.plot_results() def fixed_sine_test(self, widget, data=None): freq_text = self.fs_freq_entry.get_text() freq = float(freq_text) amp_text = self.fs_amp_entry.get_text() amp = int(amp_text) dur_text = self.fs_dur_entry.get_text() dur = int(dur_text) print('freq = %0.4f' % freq) print('amp = %i' % amp) print('dur = %i' % dur) self.test.Reset_Theta() time.sleep(0.05) self.test.Fixed_Sine(freq=freq, amp=amp, stopn=dur, plot=False) self.test.Close_Serial() self.plot_results() def run_ol_test(self, u): self.OL_test = RTP.Motor_OL_Test() self.OL_test.Reset_Theta() self.OL_test.Run_Test(u, plot=False) self.OL_test.Close_Serial() self.plot_results(test=self.OL_test) def system_check(self, widget, data=None): stopn = 1000 u = zeros((stopn), dtype=int64) startind = 50 width = 50 amp = 100 u[startind:startind+width] = amp ind3 = stopn/2+startind ind4 = ind3+width u[ind3:ind4] = -amp u[-5:] = 0 self.run_ol_test(u) def run_ol_step(self, widget, data=None): stopn = int(self.dur_entry.get_text()) u = zeros((stopn), dtype=int64) startind = 50 amp_text = self.ol_amp_entry.get_text() amp = int(amp_text) u[startind:] = amp self.run_ol_test(u) def return_to_zero(self, widget, data=None): self._set_vib_supress() self.test.Step_Response(0, plot=False) self.test.Close_Serial() def reset_theta(self, widget, data=None): self.test.Reset_Theta() self.test.Close_Serial() def 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 destroy(self, widget, data=None): print "destroy signal occurred" self.test.Close_Serial() gtk.main_quit() def __init__(self): self.debug = 0 self.test = RTP.Motor_PD_Control_Test(kp=2, kd=0.07) # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # When the window is given the "delete_event" signal (this is given # by the window manager, usually by the "close" option, or on the # titlebar), we ask it to call the delete_event () function # as defined above. The data passed to the callback # function is NULL and is ignored in the callback function. self.window.connect("delete_event", self.delete_event) # Here we connect the "destroy" event to a signal handler. # This event occurs when we call gtk_widget_destroy() on the window, # or if we return FALSE in the "delete_event" callback. self.window.connect("destroy", self.destroy) # Sets the border width of the window. self.window.set_border_width(10) # Creates a new button with the label "Hello World". self.swept_sine_button = gtk.Button("Swept Sine") self.step_button = gtk.Button("Step Response") self.reset_button = gtk.Button("Reset Theta") self.return_button = gtk.Button("Return to 0") self.sys_check_button = gtk.Button("System Check") self.ol_step_button = gtk.Button("OL Step") #self.vib_check = gtk.CheckButton(label="Use Vibration Suppression", \ # use_underline=False) self.vib_on_radio = gtk.RadioButton(None, "On") self.vib_off_radio = gtk.RadioButton(self.vib_on_radio, "Off") #button.connect("toggled", self.callback, "radio button 2") self.vib_off_radio.set_active(True) vib_label = gtk.Label("Vibration Suppression") ol_label = gtk.Label("OL Step Response") ol_hbox = gtk.HBox(homogeneous=False) amp_label = gtk.Label("amp:") dur_label = gtk.Label("duration:") self.ol_amp_entry = gtk.Entry() self.ol_amp_entry.set_max_length(7) self.ol_amp_entry.set_text("150") Entry_width = 50 self.ol_amp_entry.set_size_request(Entry_width,-1) self.dur_entry = gtk.Entry() self.dur_entry.set_max_length(7) self.dur_entry.set_text("300") self.dur_entry.set_size_request(Entry_width,-1) ol_hbox.pack_end(self.ol_amp_entry, False) ol_hbox.pack_end(amp_label, False) #ol_hbox.pack_start(amp_label, False) #ol_hbox.pack_start(self.ol_amp_entry, False) ol_dur_box = gtk.HBox(homogeneous=False) ol_dur_box.pack_end(self.dur_entry, False) ol_dur_box.pack_end(dur_label, False) #Fixed Sine Controls self.fs_amp_entry = gtk.Entry() self.fs_amp_entry.set_max_length(7) self.fs_amp_entry.set_size_request(Entry_width, -1) self.fs_amp_entry.set_text("5") self.fs_freq_entry = gtk.Entry() self.fs_freq_entry.set_max_length(7) self.fs_freq_entry.set_size_request(Entry_width, -1) self.fs_freq_entry.set_text("0.5") self.fs_dur_entry = gtk.Entry() self.fs_dur_entry.set_max_length(7) self.fs_dur_entry.set_size_request(Entry_width, -1) self.fs_dur_entry.set_text("300") fs_label = gtk.Label('Fixed Sine') fs_amp_label = gtk.Label("amp (counts):") fs_freq_label = gtk.Label("freq (Hz):") fs_dur_label = gtk.Label("duration:") fsvbox = gtk.VBox(homogeneous=False, spacing=5) fsvbox.show() fsvbox.pack_start(fs_label) fshbox1 = gtk.HBox(homogeneous=False) fshbox1.pack_end(self.fs_amp_entry, False) fshbox1.pack_end(fs_amp_label, False) fsvbox.pack_start(fshbox1, False) fshbox2 = gtk.HBox(homogeneous=False) fshbox2.pack_end(self.fs_freq_entry, False) fshbox2.pack_end(fs_freq_label, False) fsvbox.pack_start(fshbox2, False) fshbox3 = gtk.HBox(homogeneous=False) fshbox3.pack_end(self.fs_dur_entry, False) fshbox3.pack_end(fs_dur_label, False) fsvbox.pack_start(fshbox3, False) self.fixed_sine_button = gtk.Button("Fixed Sine") fsvbox.pack_start(self.fixed_sine_button, False) #ol_dur_box.pack_start(dur_label, False) #ol_dur_box.pack_start(self.dur_entry, False) sep0 = gtk.HSeparator() sep1 = gtk.HSeparator() sep2 = gtk.HSeparator() sep3 = gtk.HSeparator() sep4 = gtk.HSeparator() #self.button.set_size_request(30, 40) # When the button receives the "clicked" signal, it will call the # function hello() passing it None as its argument. The hello() # function is defined above. self.swept_sine_button.connect("clicked", self.swept_sine_test, None) self.step_button.connect("clicked", self.step_test, None) self.reset_button.connect("clicked", self.reset_theta, None) self.return_button.connect("clicked", self.return_to_zero, None) self.sys_check_button.connect("clicked", self.system_check, None) self.ol_step_button.connect("clicked", self.run_ol_step, None) self.fixed_sine_button.connect("clicked", self.fixed_sine_test, None) # This will cause the window to be destroyed by calling # gtk_widget_destroy(window) when "clicked". Again, the destroy # signal could come from here, or the window manager. #self.button.connect_object("clicked", gtk.Widget.destroy, self.window) big_hbox = gtk.HBox()#homogeneous=False, spacing=5) button_vbox = gtk.VBox(homogeneous=False, spacing=5) #self.vbox1 = gtk.VBox(homogeneous=False, spacing=0) # This packs the button into the window (a GTK container). #self.window.add(self.button) button_vbox.pack_start(self.sys_check_button, False) button_vbox.pack_start(sep0, False) button_vbox.pack_start(self.swept_sine_button, False, False, 0) button_vbox.pack_start(sep1, False) button_vbox.pack_start(vib_label, False) #button_vbox.pack_start(self.vib_check, False) button_vbox.pack_start(self.vib_on_radio, False) button_vbox.pack_start(self.vib_off_radio, False) button_vbox.pack_start(sep2, False) button_vbox.pack_start(self.step_button, False, False, 0) button_vbox.pack_start(sep3, False) #Fixed Sine Stuff button_vbox.pack_start(fsvbox, False) button_vbox.pack_start(sep4, False) button_vbox.pack_start(ol_label, False) button_vbox.pack_start(ol_hbox, False) button_vbox.pack_start(ol_dur_box, False) button_vbox.pack_start(self.ol_step_button, False) button_vbox.pack_start(self.reset_button, False) button_vbox.pack_start(self.return_button, False) self.f = Figure(figsize=(5,4), dpi=100) self.ax = self.f.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) self.ax.plot(t,s) self.figcanvas = FigureCanvas(self.f) # a gtk.DrawingArea self.figcanvas.show() canvas_vbox = gtk.VBox() toolbar = NavigationToolbar(self.figcanvas, self.window) #toolbar.set_size_request(-1,50) self.figcanvas.set_size_request(600,300) toolbar.set_size_request(600,50) toolbar.show() big_hbox.pack_start(button_vbox, False, False, 0) canvas_vbox.pack_start(self.figcanvas)#, expand=True, \ #fill=True, padding=5) canvas_vbox.pack_start(toolbar, False)#, False)#, padding=5) big_hbox.pack_start(canvas_vbox)#, expand=True, \ #fill=True, padding=5) self.window.add(big_hbox) # The final step is to display this newly created widget. #self.button.show() #self.window.set_size_request(1000,800) self.window.set_title('RTP Motor GUI v. 1.0') # and the window #self.window.show() self.window.set_position(gtk.WIN_POS_CENTER) self.window.show_all() def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main()
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"))
def drawBars(self, xvalues, yvalues, xlabel, ylabel, title, color): logging.debug('>>') logging.debug("Type: bars | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) numCols = len(xvalues[0]) xmod = 0.4 self.showGraph = False axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 logging.debug("One axis, barWidth %f, barOffset %f" % (barWidth, barOffset)) elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 logging.debug("Twin axes, barWidth %f, barOffset %f" % (barWidth, barOffset)) else: #Error logging.debug("Error: invalid number of axes") return axis.set_xlabel(xlabel[0]) axis.set_ylabel(ylabel[0]) logging.debug("Labels set x: %s, y: %s" % (xlabel[0], ylabel[0])) xvals = [x + barOffset for x in range(0, numCols)] yvals = [0] * numCols for i in range(0, numCols): yval = yvalues[0][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Drawing bars") axis.bar(xvals, yvals, barWidth, color=color[0], align='edge') else: #Only zero results logging.debug("No results to draw") pass axis.grid(True) axis.set_title("%s" % (title[0])) logging.debug("Setting title to: %s" % title[0]) for tl in axis.get_yticklabels(): logging.debug("Setting ticklabel color %s" % color[0]) tl.set_color('%s' % color[0]) if len(xvalues) == 2: #Display twin axis ax2 = axis.twinx() logging.debug("Axis 2: Twin axis: %s " % str(ax2)) xvals = [x + barOffset + barWidth for x in range(0, numCols)] for i in range(0, numCols): yval = yvalues[1][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Axis 2: Drawing bars") ax2.bar(xvals, yvals, barWidth, color=color[1], align='edge') logging.debug("Axis 2: Label set y: %s" % (ylabel[1])) ax2.set_ylabel(ylabel[1]) else: #Only zero results logging.debug("Axis 2: No results to draw") pass for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[1]) logging.debug("Axis 2: Setting ticklabel color %s" % color[1]) _title = "%s vs %s" % (title[0], title[1]) logging.debug("Axis 2: Setting title to: %s" % _title) axis.set_title(_title) logging.debug("Setting x ticks") tickLocations = [x + 0.5 for x in xrange(0, numCols)] axis.set_xticks(tickLocations) axis.set_xticklabels(xvalues[0]) logging.debug("Setting x limits") axis.set_xlim(0, numCols) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Got canvas: %s" % (str(canvas))) canvas.show() logging.debug("Adding canvas to vbox") self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<')
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 Plot(Widget): @Property def overlay(): def fget(self): return self.prefs['overlay'].enabled def fset(self, overlay): for plotable in self.__plotables: plotable.overlay = overlay widget = self.builder.get_object('overlay__enabled') widget.set_active(overlay) return locals() @Property def canvas(): def fget(self): return self.__canvas return locals() @Property def toolbar(): def fget(self): return self.__toolbar return locals() def __reset(self): nplotables = len(self.__plotables) for i, plotable in enumerate(self.__plotables): plotable.reset(nplotables, i) self.__figure.subplots_adjust(hspace = 0.5) def __plotable_new(self, plotable): plotable.axes_new(self.__figure, self.__canvas, len(self.__plotables)) self.__plotables.append(plotable) self.__reset() return plotable def __plotable_delete(self, plotable): plotable.axes_delete(self.__figure) self.__plotables.remove(plotable) self.__reset() def subplot_new(self): return self.__plotable_new(SubPlot()) def subplot_delete(self, plotable): self.__plotable_delete(plotable) def stripchart_new(self): return self.__plotable_new(StripChart()) def stripchart_delete(self, stripchart): self.__plotable_delete(stripchart) def plot3d_new(self): return self.__plotable_new(Plot3D()) def plot3d_delete(self, plot3d): self.__plotable_delete(plot3d) def __save(self, filename): if not filename: return self.__filename = filename with open(self.__filename, 'w') as fd: fd.write(self.__buffer.get_text(*self.__buffer.get_bounds())) def clear(self): for plotable in self.__plotables: plotable.clear() self.__reset() self.draw() def show(self): self.widget.show() self.__canvas.show() self.__toolbar.show() def hide(self): self.__toolbar.hide() self.__canvas.hide() self.widget.hide() def on_open(self, widget): pass def on_save(self, widget): if self.__filename: self.__save(self.__filename) else: self.__chooser.get_selection() def on_saveas(self, widget): self.__chooser.get_selection(filename=self.__filename) def on_clear(self, widget): self.clear() def get_toolbar(self): return self.__toolbar def __init__(self): Widget.__init__(self) path = os.environ['GRIMA_ETC'] name = 'grima-subplot-widget' self.loadui(path, name) self.loaddb(path, name) self.__figure = Figure() self.__canvas = FigureCanvas(self.__figure) self.__toolbar = NavigationToolbar(self.__canvas, None) self.__canvas.show() self.figure = self.__figure widget = gtk.VBox() widget.show() widget.pack_start(self.__canvas) widget.pack_start(self.__toolbar, False, False) container = self.builder.get_object('container') container.add(widget) self.__filename = None self.__plotables = [] self.__chooser = SaveAs() self.__chooser.deletable = False self.__chooser.embedded = True self.__chooser.callback = self.__save
class SensorWindow(object): def __init__(self, mainThread, gladefile='sensor_window.glade'): self.builder = gtk.Builder() self.builder.add_from_file(gladefile) self.builder.connect_signals(self) self._stopped = False self.mainThread = mainThread self.fig = plt.figure() self.numLines = 1 # lines plot self.ax = self.fig.add_subplot(111) self.ax.set_xlabel('Time') self.ax.set_ylabel('Power') self.ax.xaxis.set_animated(True) self.ax.yaxis.set_animated(True) self.ax.set_title('Light Intensity') self.ax.grid(True) self.start = time.time() self.background1 = None self.prev_time = self.start self.prev_pixel_offset = 0 self.x0 = 0 self.value = [0] * self.numLines self.ax.set_ylim(-1, 256) self.lines = [] for i in range(self.numLines): line, = self.ax.plot([], [], animated=True, lw=2) self.lines.append(line) self.canvas = FigureCanvas(self.fig) self.graphview = self.builder.get_object("box2") self.graphview.pack_start(self.canvas) self.graphview.reorder_child(self.canvas, 0) self.img = self.builder.get_object("image1") self.img.set_from_file("off.svg") self.lamp = False self.canvas.show() gobject.idle_add(self.update_line) self.canvas.mpl_connect('draw_event', self.on_draw) self.barpath = [] def close_window(self, obj): print "closing window" self.builder.get_object("window1").destroy() def destroy_callback(self, obj): print "destroying window" self.mainThread.stop() self._stopped = True def close_from_mainthread(self): print "close from mainthread" self.builder.get_object("window1").destroy() def toggle_lamp(self): print "toggle lamp!!" self.img = self.builder.get_object("image1") if (self.lamp): self.lamp = False self.img.set_from_file("off.svg") else: self.lamp = True self.img.set_from_file("on.svg") def update_line(self, *args): if self._stopped: self.destroy_callback(None) return False if self.background1 is None: return True cur_time = time.time() pixel_offset = int((cur_time - self.start) * 40.) dx_pixel = pixel_offset - self.prev_pixel_offset self.prev_pixel_offset = pixel_offset dx_data = self.get_dx_data(dx_pixel) #cur_time - self.prev_time) x0 = self.x0 self.x0 += dx_data self.prev_time = cur_time self.ax.set_xlim(self.x0 - 2, self.x0 + 0.1) # restore background which will plot lines from previous plots self.restore_background_shifted(dx_pixel) #x0, self.x0) # now plot line segment within [x0, x0+dx_data], # Note that we're only plotting a line between [x0, x0+dx_data]. xx = np.array([x0, self.x0]) for i in range(len(self.lines)): line = self.lines[i] line.set_xdata(xx) # the for loop below could be improved by using collection. line.set_ydata(np.array([self.value[i], self.value[i]])) self.ax.draw_artist(line) self.background2 = self.canvas.copy_from_bbox(self.get_bg_bbox()) self.ax.draw_artist(self.ax.xaxis) self.ax.draw_artist(self.ax.yaxis) self.canvas.blit(self.ax.get_figure().bbox) return True def get_dx_data(self, dx_pixel): tp = self.ax.transData.inverted().transform_point x0, y0 = tp((0, 0)) x1, y1 = tp((dx_pixel, 0)) return (x1 - x0) def get_bg_bbox(self): return self.ax.bbox.padded(-3) def save_bg(self): self.background1 = self.canvas.copy_from_bbox( self.ax.get_figure().bbox) self.background2 = self.canvas.copy_from_bbox(self.get_bg_bbox()) def on_draw(self, *args): self.save_bg() return False def restore_background_shifted(self, dx_pixel): """ restore bacground shifted by dx in data coordinate. This only works if the data coordinate system is linear. """ # restore the clean slate background self.canvas.restore_region(self.background1) # restore subregion (x1+dx, y1, x2, y2) of the second bg # in a offset position (x1-dx, y1) x1, y1, x2, y2 = self.background2.get_extents() self.canvas.restore_region(self.background2, bbox=(x1 + dx_pixel, y1, x2, y2), xy=(x1 - dx_pixel, y1)) return dx_pixel def update(self, data): if type(data) == ListType: assert (len(self.lines) == len(data)) self.value = data else: assert (len(self.lines) == 1) self.value = [data]
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("window") dic = { "on_auto_select_toggled" : self.test, "on_row-activated": self.test2, } self.builder.connect_signals(dic) self.create_draw_frame(None) self.channel_tree(None) def channel_tree(self,widget): print('updating list') self.View = self.builder.get_object("treeview1") self.dataList = gtk.ListStore(int,str,gobject.TYPE_BOOLEAN) self.AddListColumn('Number', 0, self.View) self.AddListColumn('Label', 1, self.View) self.AddBoolColumn('test', 2, self.View) self.numchannels=np.size(self.data,1)#300 self.chanlabels=np.arange(np.size(self.data,1))#300) for k in range(0,self.numchannels): iter = self.dataList.append([k,self.chanlabels[k],k]) self.dataList[k][2] = False self.View.set_model(self.dataList) print 'adding channels' def AddBoolColumn(self, title, columnId, viewtype): self.render = gtk.CellRendererToggle() self.render.set_property('activatable', True) self.render.connect( 'toggled', self.checkit, self.dataList ) column = gtk.TreeViewColumn(title,self.render)#,text=columnId) column.set_resizable(True) column.add_attribute( self.render, "active", 2) column.set_sort_column_id(columnId) viewtype.append_column(column) #viewtype.set_activatable(True) viewtype.get_selection().set_mode(gtk.SELECTION_MULTIPLE) #viewtype.get_selection().set_mode(gtk.set_activatable(True)) def checkit(self,cell,path,model): model[path][2] = not model[path][2] print "Toggle '%s' to: %s" % (model[path][1], model[path][2],) def AddListColumn(self, title, columnId, viewtype): column = gtk.TreeViewColumn(title,gtk.CellRendererText(),text=columnId) column.set_resizable(True) column.set_sort_column_id(columnId) viewtype.append_column(column) viewtype.get_selection().set_mode(gtk.SELECTION_MULTIPLE) def test(self,widget): print 'test',widget toggled = widget #self.builder.get_object("togglebutton1") print toggled.get_active()#toggled()#state box_children = self.builder.get_object("buttonbox1").get_children() if toggled.get_active() == True: for i in box_children: i.set_sensitive(True) if toggled.get_active() == False: for i in box_children: i.set_sensitive(False) toggled.set_sensitive(True) def test2(self,widget): try: self.axes.clear() except: pass self.axes.axis('off') self.axes.scatter(self.data[1],self.data[0],marker='o',facecolors='none'); liststore,iter = self.View.get_selection().get_selected_rows() self.chanind = [] for i in iter: print i,liststore[i][0] x = liststore[i][0] self.chanind.append(int(liststore[i][0])) self.axes.scatter(self.data[1,x],self.data[0,x],marker='o',color='r') #liststore[i][2] = True #liststore[i][2] = not liststore[i][2] #print liststore[i][2] self.canvas.draw() #self.canvas.show() def create_draw_frame(self,widget): #ion() self.fig = Figure(figsize=[200,200], dpi=100) 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.axes.axis('off') self.vb = self.builder.get_object("viewport1") self.vb.add(self.canvas) #self.vb.pack_start(self.canvas, gtk.TRUE, gtk.TRUE) self.vb.show() from pdf2py import readwrite self.data = readwrite.readdata('/home/danc/vault/decrypted/programming/python/chanlocs.pym') #self.data = np.arange(300)#np.random.randn(300) self.axes.scatter(self.data[1],self.data[0],marker='o',facecolors='none');