Esempio n. 1
0
def visualize(*args, **kwargs):
    """
    Method that does all magic to to with GTK.

    All arguments passed to grapher.matplot.Graph
    """

    logger.debug('Spawning a GTK window')
    win = gtk.Window()
    win.connect('destroy', lambda x: gtk.main_quit())
    win.set_default_size(800,500)
    win.set_title('BounceItBaby visualizer')

    sw = gtk.ScrolledWindow()
    win.add(sw)
    # TODO: allow arrow/hjkl buttons to scroll
    sw.set_policy(hscrollbar_policy=gtk.POLICY_ALWAYS,
                  vscrollbar_policy=gtk.POLICY_AUTOMATIC)

    logger.debug('Building the Figure from data')
    figure = Graph(*args, **kwargs)
    canvas = FigureCanvas(figure)
    # If time scale is 20 times longer than number of actors, make it 20 times
    # wider than it is tall.
    canvas.set_size_request(int(400 / figure.axes[0].get_data_ratio()), 400)
    sw.add_with_viewport(canvas)

    logger.debug('Displaying GTK window!')
    win.show_all()
    gtk.main()
Esempio n. 2
0
    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()
Esempio n. 3
0
 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()
Esempio n. 4
0
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)
Esempio n. 5
0
    def __init__(self):
        print 'test'
        self.win = gtk.Window()
        #win.connect("destroy", lambda x: gtk.main_quit())
        self.win.connect("delete-event", self.hideinsteadofdelete)
        self.win.set_default_size(400,300)
        self.win.set_title("Embedding in GTK")

        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)

        sw = gtk.ScrolledWindow()
        self.win.add (sw)
        # A scrolled window border goes outside the scrollbars and viewport
        sw.set_border_width (10)
        # policy: ALWAYS, AUTOMATIC, NEVER
        sw.set_policy (hscrollbar_policy=gtk.POLICY_AUTOMATIC,
                       vscrollbar_policy=gtk.POLICY_ALWAYS)

        canvas = FigureCanvas(f)  # a gtk.DrawingArea
        canvas.set_size_request(800,600)
        sw.add_with_viewport (canvas)

        self.win.show_all()
        gtk.main()
Esempio n. 6
0
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)
Esempio n. 7
0
File: ui.py Progetto: matze/af
class FigureWidget(gtk.ScrolledWindow):
    def __init__(self, figure):
        super(FigureWidget, self).__init__()
        self.set_border_width(10)
        self.set_policy(hscrollbar_policy=gtk.POLICY_AUTOMATIC,
            vscrollbar_policy=gtk.POLICY_ALWAYS)
        self.canvas = FigureCanvas(figure)
        self.canvas.set_size_request(500, 100)
        self.add_with_viewport(self.canvas)
Esempio n. 8
0
 def __init__(self, win, size, show_labels=True):
     fig = Figure(figsize=(size, size))
     canvas = FigureCanvas(fig)  # a gtk.DrawingArea
     canvas.set_size_request(500, 500)
     toolbar = NavigationToolbar(canvas, win)
     self.vbox = gtk.VBox()
     self.vbox.pack_start(canvas)
     self.vbox.pack_start(toolbar, False, False)
     self.fig = fig
     self.show_labels = show_labels
     self.eventfiles = {}
Esempio n. 9
0
def create_figure(quotes):

    f = Figure(figsize=(5, 4), dpi=100)

    a = f.add_subplot(111)
    canvas = FigureCanvas(f)  # a gtk.DrawingArea
    canvas.set_size_request(800, 300)

    a.xaxis_date()

    finance.candlestick(a, quotes, width=0.5)

    return f
Esempio n. 10
0
def create_figure(quotes):

  f = Figure(figsize=(5,4), dpi=100)

  a = f.add_subplot(111)
  canvas = FigureCanvas(f)  # a gtk.DrawingArea
  canvas.set_size_request(800,300)

  a.xaxis_date()
  
  finance.candlestick(a, quotes, width=0.5)

  return f
Esempio n. 11
0
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)
Esempio n. 12
0
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)
	def __init__(self):
		self.gladefile='./lvshort2.glade'
		self.wTree = gtk.glade.XML(self.gladefile)
		dic={"on_start_clicked":self.dynamics,"on_mainwin_destroy":gtk.main_quit}
		self.wTree.signal_autoconnect(dic)
		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)
#		a.plot(t,s)
		canvas = FigureCanvas(self.f)  # a gtk.DrawingArea
		canvas.set_size_request(600,400)
		self.wTree.get_widget("sw").add_with_viewport(canvas)
		toolbar = NavigationToolbar(canvas, self.wTree.get_widget("mainwin"))
		self.wTree.get_widget("vbox1").pack_start(toolbar,False,False)

		print 'added'
		self.wTree.get_widget("mainwin").show_all()
Esempio n. 14
0
class PlotWidget(Widgets.WidgetBase):
    def __init__(self, plot, width=500, height=500):
        super(PlotWidget, self).__init__()

        self.widget = FigureCanvas(plot.get_figure())
        self.plot = plot
        self.logger = plot.logger

        self.widget.set_size_request(width, height)
        self.widget.show_all()

    def set_plot(self, plot):
        self.plot = plot
        self.logger = plot.logger
        self.logger.debug("set_plot called")

    def configure_window(self, wd, ht):
        self.logger.debug("canvas resized to %dx%d" % (wd, ht))
        fig = self.plot.get_figure()
        fig.set_size_inches(float(wd) / fig.dpi, float(ht) / fig.dpi)
    def __init__(self, toolBoxWidgets=None, title="GTK Gui Plot", scaling=True, *args, **kwargs):
        if not toolBoxWidgets:
            toolBoxWidgets = []
        super(GuiWithCanvasAndToolbar, self).__init__(*args, **kwargs)
        self.connect("destroy", lambda x: gtk.main_quit())
        self.set_default_size(1100, 600)
        self.set_title(title)

        table = gtk.Table(1, 2, False)

        self.figures = []
        self.y_max = float("-inf")
        self.x_max = float("-inf")
        self.y_min = float("inf")
        self.x_min = float("inf")
        self.fig = Figure(figsize=(8, 6), dpi=100)
        self.ax = self.fig.add_subplot(111)
        canvas = FigureCanvas(self.fig)
        canvas.set_size_request(800, 600)
        canvas.mpl_connect('button_press_event', self.handle_click)

        table.attach(canvas, 0, 1, 0, 1)

        toolbox = gtk.Table(len(toolBoxWidgets) + 1, 1, False)
        i = 0
        for widget in toolBoxWidgets:
            toolbox.attach(widget, 0, 1, i, i + 1)
            i += 1

        label = gtk.Label("SimGUI")
        toolbox.attach(label, 0, 1, i, i + 1)

        table.attach(toolbox, 1, 2, 0, 1)

        self.canvas = canvas
        canvas.draw()
        self.update_figures()

        self.add(table)
        self.scaling = scaling
Esempio n. 16
0
 def make_fig(title = None):
     '''
     Create a figure window with a single set of axes and a single main subplot.
     Returns the axes of the main subplot
     '''
     global all_sub_figures
     if title == None:
         title = "Untitled Figure {0}".format(len(all_sub_figures)+1)
     dialog = gtk.Dialog(title, win, gtk.DIALOG_DESTROY_WITH_PARENT)
     dialog.set_default_size(500,400)
     fig = matplotlib.figure.Figure()
     axes = fig.add_subplot(111)
     #axes.invert_yaxis()
     #axes.autoscale()
     canvas = FigureCanvasGTKAgg(fig)  # a gtk.DrawingArea
     canvas.set_size_request(300,300)
     dialog.vbox.pack_start(canvas, expand=True)
     toolbar = NavigationToolbar2GTKAgg(canvas, dialog)
     dialog.vbox.pack_start(toolbar, False, False)
     dialog.show_all()
     canvas.draw()
     fig.prev_child_count = 0
     all_sub_figures.append(fig)
     return axes
Esempio n. 17
0
    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()
Esempio n. 18
0
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()
Esempio n. 19
0
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()
Esempio n. 20
0
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()
Esempio n. 21
0
	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)
Esempio n. 22
0
	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)
Esempio n. 23
0
class Plot():
    def __init__(self, title, function, labels):

        self.title = title

        # MAT-PLOT-LIB_____________________________________________________
        self.fig = Figure(figsize=(6, 4))  # create fig
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(500, 300)  # set min size
        self.markers = [
            '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's',
            'p', '*', 'h', 'H', 'D', 'd'
        ]
        self.colors = [
            'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow',
            'purple', 'white'
        ]
        self.pstyle = [
            'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '',
            '25', '', '', '20', '15', '', '', '20', '15'
        ]

        self.styledict = {}
        self.styledict["style"] = 'bmh'
        self.styledict["point_style"] = 's'
        self.styledict["point_size"] = '6'
        self.styledict["point_color"] = 'red'
        self.styledict["point_alpha"] = '0.8'
        self.styledict["line_color"] = 'black'
        self.styledict["line_width"] = '2'
        self.styledict["band_color"] = 'black'
        self.styledict["band_alpha"] = '0.3'
        self.styledict["title_size"] = '25'
        self.styledict["xtitle_size"] = '20'
        self.styledict["xlabel_size"] = '15'
        self.styledict["ytitle_size"] = '20'
        self.styledict["ylabel_size"] = '15'

        self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1]
        self.plot_labels = []
        self.plot_labels.append(labels[3] + " vs " + labels[0])  # plot title
        self.plot_labels.append(labels[0])  # x-axis title
        self.plot_labels.append(labels[3])  # y-axis title
        self.plot_labels.append("[Gy]")  # x-axis unit
        self.plot_labels.append(" ")  # y-axis unit
        #print plt.style.available
        self.fit_toggle = 'inactive'
        self.points_toggle = 1
        self.function_toggle = 1
        self.err_toggle = 1
        self.ci_func_toggle = 1
        self.ci_points_toggle = 1
        #self.plotting(function)					# --- CORE plotting function ---

    def plotting(self, function):
        """Generating matplotlib canvas"""
        plt.style.use(self.pstyle[0])

        self.ax1 = self.fig.add_subplot(111)
        self.ax1.clear()

        self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
        self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3],
                            fontsize=int(self.pstyle[13]))
        self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4],
                            fontsize=int(self.pstyle[17]))
        self.ax1.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax1.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))

        x = np.arange(-0.1, max(20, 200) * 1.1, 0.05)

        if self.function_toggle == 1:
            y = function.func(x, function.t, function.t0, function.params)
            self.ax1.plot(x,
                          y,
                          color=self.pstyle[5],
                          marker='.',
                          linestyle='None',
                          markersize=float(self.pstyle[6]))

        if self.ci_points_toggle == 1:
            upper = function.func(x, function.t, function.t0,
                                  function.params) + confidence_points(
                                      x, function.std_err)
            lower = function.func(x, function.t, function.t0,
                                  function.params) - confidence_points(
                                      x, function.std_err)
            self.ax1.fill_between(x,
                                  lower,
                                  upper,
                                  facecolor='blue',
                                  alpha=float(self.pstyle[8]))

        if self.err_toggle == 1:
            upper = function.func(x, function.t, function.t0,
                                  function.params) + uncertainty(
                                      x, function.std_err)
            lower = function.func(x, function.t, function.t0,
                                  function.params) - uncertainty(
                                      x, function.std_err)
            self.ax1.fill_between(x,
                                  lower,
                                  upper,
                                  facecolor='green',
                                  alpha=float(self.pstyle[8]))

        self.fig.tight_layout()
        self.canvas.draw()

    def plotvline(self, **kwargs):
        self.ax1.axvline(**kwargs)

    def plothline(self, **kwargs):
        self.ax1.axhline(**kwargs)

    def replot(self):
        self.canvas.draw()
Esempio n. 24
0
class ScannerView(SlaveView):
    def __init__(self, scanner, width=400, height=300):
        self.scanner = scanner
        self.callback_ids = {}
        self.width = width
        self.height = height
        super(ScannerView, self).__init__()

    def on_button_debug__clicked(self, button):
        import IPython
        import inspect

        # Get parent from stack
        parent_stack = inspect.stack()[1]
        IPython.embed()

    def create_ui(self):
        self.fig = Figure(figsize=(4, 3), frameon=False)
        # Remove padding around axes.
        self.fig.subplots_adjust(bottom=0, top=1, right=1, left=0)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.set_size_request(self.width, self.height)
        self.reset_axis()
        self.button_scan = gtk.Button('Scan')
        self.button_debug = gtk.Button('Debug')

        self.widget.pack_start(self.canvas, True, True, 0)
        for widget_i in (self.button_scan, self.button_debug):
            self.widget.pack_start(widget_i, False, False, 0)

        self.widget.show_all()
        self.button_scan.connect('clicked', lambda *args: self.enable_scan())

    def reset_axis(self):
        self.fig.clf()
        self.axis = self.fig.add_subplot(111)
        self.axis.set_aspect(True)
        self.axis.set_axis_off()

    def cleanup(self):
        for callback_id in ['frame', 'symbol']:
            if callback_id in self.callback_ids:
                self.scanner.disconnect(self.callback_ids[callback_id])
                del self.callback_ids[callback_id]

    def disable_scan(self):
        self.cleanup()
        self.scanner.disable_scan()
        self.button_scan.set_sensitive(True)

    def enable_scan(self):
        self.reset_axis()
        self.scanner.reset()
        self.scanner.enable_scan()
        self.button_scan.set_sensitive(False)
        self.callback_ids['frame'] = self.scanner.connect('frame-update',
                                                          self.on_frame_update)
        self.callback_ids['symbol'] = self.scanner.connect('symbols-found',
                                                           self.on_symbols_found)

    def __dealloc__(self):
        self.cleanup()

    def on_frame_update(self, scanner, np_img):
        self.axis.clear()
        self.axis.set_axis_off()
        self.axis.imshow(np_img)
        self.canvas.draw()

    def on_symbols_found(self, scanner, np_img, symbols):
        patches = []
        if symbols:
            for symbol_record_i in symbols:
                symbol_i = symbol_record_i['symbol']
                location_i = Polygon(symbol_i.location)
                patches.append(location_i)
            patch_collection = PatchCollection(patches, cmap=mpl.cm.jet,
                                               alpha=0.4)
            self.on_frame_update(scanner, np_img)
            self.axis.add_collection(patch_collection)
            self.canvas.draw()
            self.disable_scan()
Esempio n. 25
0
# uncomment to select /GTK/GTKAgg/GTKCairo
#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
#from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas

win = gtk.Window()
win.connect("destroy", lambda x: gtk.main_quit())
win.set_default_size(400,300)
win.set_title("Embedding in GTK")

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)

sw = gtk.ScrolledWindow()
win.add (sw)
# A scrolled window border goes outside the scrollbars and viewport
sw.set_border_width (10)
# policy: ALWAYS, AUTOMATIC, NEVER
sw.set_policy (hscrollbar_policy=gtk.POLICY_AUTOMATIC,
               vscrollbar_policy=gtk.POLICY_ALWAYS)

canvas = FigureCanvas(f)  # a gtk.DrawingArea
canvas.set_size_request(800,600)
sw.add_with_viewport (canvas)

win.show_all()
gtk.main()
Esempio n. 26
0
class makewin():
    def __init__(self):

        self.win = gtk.Window()
        #win.connect("destroy", lambda x: gtk.main_quit())
        self.win.connect("delete-event", self.hideinsteadofdelete)
        self.win.set_default_size(400,300)
        self.win.set_title("Embedding in GTK")

        vbox = gtk.VBox()
        self.win.add(vbox)

        self.f = Figure(figsize=(5,4), dpi=100)
        sw = gtk.ScrolledWindow()
        vbox.pack_start(sw)
        #self.win.add (sw)
        # A scrolled window border goes outside the scrollbars and viewport
        sw.set_border_width (10)
        # policy: ALWAYS, AUTOMATIC, NEVER
        sw.set_policy (hscrollbar_policy=gtk.POLICY_AUTOMATIC,
                       vscrollbar_policy=gtk.POLICY_ALWAYS)

        self.canvas = FigureCanvas(self.f)  # a gtk.DrawingArea
        #vbox.pack_start(canvas)
        self.canvas.set_size_request(300,200)
        sw.add_with_viewport (self.canvas)

        manager = get_current_fig_manager()
        # you can also access the window or vbox attributes this way
        toolbar = manager.toolbar

        #vbox.pack_start(canvas)
        toolbar = NavigationToolbar(self.canvas, self.win)
        vbox.pack_start(toolbar, False, False)

        self.win.show_all()
        #gtk.main()

    def hideinsteadofdelete(self,widget,ev=None):
        print widget
        widget.hide()
        return True
        
        
    def plot_data(self,xi,yi,zi,intx,inty):
        """provide...
            xi=grid x data
            yi=grided y data
            zi=interpolated MEG data for contour
            intx and inty= sensor coords for channel plotting"""

        tstart = time.time()

        zim = ma.masked_where(isnan(zi),zi)

        self.p.pcolor(xi,yi,zim,shading='interp',cmap=cm.jet)

        self.p.contourf(xi,yi,zim,cmap=cm.jet)
        self.p.scatter(intx,inty, alpha=.75,s=3)

    def plot_data_loop(self,xi,yi,zi,intx,inty):
        pass

    def printlabels(self,chanlocs, labels):
            #if labels != None:
        count = 0
        for l in labels:
            p.text(chanlocs[1,count], chanlocs[0,count], l, alpha=1, fontsize=9)
            count = count + 1

    def titles(titletxt):
        print

    def display(self, data, chanlocs, data2=None, subplot='off', animate='off', quiver='off', title=None, labels=None, colorbar='off'):
        #self.p = f.add_subplot(111)

        if len(shape(chanlocs)) != 2:
            print 'Chanlocs shape error. Should be 2D array "(2,N)"'
            print 'transposing'
            chanlocs = chanlocs.T
            print chanlocs.shape

        #xi, yi = mgrid[-.5:.5:67j,-.5:.5:67j]
        xi, yi = mgrid[chanlocs[1,:].min():chanlocs[1,:].max():57j,chanlocs[0,:].min():chanlocs[0,:].max():57j]
        intx=chanlocs[1,:]
        inty=chanlocs[0,:]

        if shape(shape(data))[0]==2: #more than a single vector, need to animate or subplot

            print '2d array of data'
            z = data[0,:]
            if delaunay == 'yes':
                print 'delaunay is set'
                tri = Triangulation(intx,inty)
                interp = tri.nn_interpolator(z)
                zi = interp(xi,yi)
            else: #try griddata method
                print 'delaunay is off'
                zi = griddata(intx,inty,z,xi,yi)


            if animate == 'on': #single plot with a loop to animate
                p.scatter(intx,inty, alpha=.5,s=.5)
                print 'animating'
                for i in range(0, shape(data)[0]):
                    dataslice=data[i,:];
                    z = dataslice
                    if delaunay == 'yes':
                        interp = tri.nn_interpolator(z)
                        zi = interp(xi,yi)
                    else:
                        zi = griddata(intx,inty,z,xi,yi)

                    zim = ma.masked_where(isnan(zi),zi)
                    p.contourf(xi,yi,zim,cmap=p.cm.jet, alpha=.8)
                    if labels != None:
                        printlabels(chanlocs, labels)
                    p.draw()
            if subplot == 'on':
                print 'suplotting'
                for i in range(0, shape(data)[0]):
                    spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots
                    #self.p = f.add_subplot(spnum,spnum,i+1)
                    self.p = self.f.add_subplot(spnum,spnum,i+1);#axis('off')
                    dataslice=data[i,:];
                    self.p.scatter(intx,inty, alpha=.75,s=3)
                    z = dataslice
                    if delaunay == 'yes':
                        interp = tri.nn_interpolator(z)
                        zi = interp(xi,yi)
                    else:
                        zi = griddata(intx,inty,z,xi,yi)

                    zim = ma.masked_where(isnan(zi),zi)
                    self.p.contourf(xi,yi,zim,cmap=cm.jet, alpha=.8)
                    self.p.axis('off')
                    if labels != None:
                        printlabels(chanlocs, labels)
                    if title != None:
                        self.p.title(str(title[i]))
                    else:
                        pass
                        #self.p.title(str(i))
            if quiver == 'on':
                print 'suplotting quiver'
                for i in range(0, shape(data)[0]):
                    spnum = ceil(sqrt(shape(data)[0])) #get x and y dimension of subplots
                    fig.add_subplot(spnum,spnum,i+1);#axis('off')
                    dataslice=data[i,:];
                    p.scatter(intx,inty, alpha=.75,s=3)
                    z = dataslice
                    print 'size or z', size(z)
                    for xx in range(0,size(z)):
                        quiver(intx[xx],inty[xx], z[xx], data2[xx])

                    p.axis('off')
                    if labels != None:
                        printlabels(chanlocs, labels)
            if colorbar == 'on':
                p.colorbar()

        else:
            z = data
            if delaunay == 'yes':
                print 'delaunay is set'
                tri = Triangulation(intx,inty)
                interp = tri.nn_interpolator(z)
                zi = interp(xi,yi)
            else:
                print 'delaunay is off'
                zi = griddata(intx,inty,z,xi,yi)

            zim = ma.masked_where(isnan(zi),zi)
            self.plot_data(xi,yi,zi,intx,inty)
            if labels != None:
                printlabels(chanlocs, labels)

            if colorbar == 'on':
                p.colorbar(cm)
        self.canvas.draw()
Esempio n. 27
0
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()
Esempio n. 28
0
class Plotter():
    def __init__(self, context, f_function, g_function):
        self.context = context
        self.f_function = f_function
        self.g_function = g_function

        self.fig = Figure(figsize=(6, 4))  # create fig
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(600, 600)  # set min size
        self.markers = [
            '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's',
            'p', '*', 'h', 'H', 'D', 'd'
        ]
        self.colors = [
            'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow',
            'purple', 'white'
        ]
        self.pstyle = [
            'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '',
            '25', '', '', '20', '15', '', '', '20', '15'
        ]

        self.styledict = {}
        self.styledict["style"] = 'bmh'
        self.styledict["point_style"] = 's'
        self.styledict["point_size"] = '6'
        self.styledict["point_color"] = 'red'
        self.styledict["point_alpha"] = '0.8'
        self.styledict["line_color"] = 'black'
        self.styledict["line_width"] = '2'
        self.styledict["band_color"] = 'black'
        self.styledict["band_alpha"] = '0.3'
        self.styledict["title_size"] = '8'
        self.styledict["xtitle_size"] = '8'
        self.styledict["xlabel_size"] = '8'
        self.styledict["ytitle_size"] = '8'
        self.styledict["ylabel_size"] = '8'

        self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1]
        self.plot_labels = ["", "x", "f(x)", "", "g(x)"]

        self.points_toggle = 1
        self.function_toggle = 1
        self.err_toggle = 1
        self.ci_func_toggle = 1
        self.ci_points_toggle = 1
        toolbar = NavigationToolbar(self.canvas, self)
        toolbarbox = gtk.HBox()
        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR)
        options_button = gtk.Button()
        options_button.add(image)
        image2 = gtk.Image()
        image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR)
        refresh_button = gtk.Button()
        refresh_button.add(image2)
        toolbarbox.pack_start(toolbar, True, True)
        toolbarbox.pack_end(options_button, False, True)
        toolbarbox.pack_end(refresh_button, False, True)
        self.vbox = gtk.VBox()
        self.vbox.pack_start(toolbarbox, False, False)
        self.vbox.pack_start(self.canvas, True, True)

        self.x1 = -0.1
        self.x2 = 20.1

        # signals
        options_button.connect('clicked', self.mpl_options)
        refresh_button.connect('clicked', self.on_refresh_clicked)

    def mpl_options(self, button):
        """Create GTKDialog containing options for plotting and connect signals."""
        mpl_options_dialog = MPLOptions(self.context, self)

    def on_refresh_clicked(self, button):
        """Refresh canvas - plot everything again"""
        self.plotting()

    def plotvline(self, **kwargs):
        self.ax1.axvline(**kwargs)

    def plothline(self, **kwargs):
        self.ax1.axhline(**kwargs)

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

    def plotting(self):
        """Generating matplotlib canvas"""

        plt.style.use(self.pstyle[0])

        self.ax1 = self.fig.add_subplot(311)
        self.ax1.clear()

        self.ax1.set_title("f(x) and g(x)", fontsize=self.pstyle[10])
        self.ax1.set_xlabel("", fontsize=int(self.pstyle[13]))
        self.ax1.set_ylabel("", fontsize=int(self.pstyle[17]))
        self.ax1.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax1.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))

        x = np.arange(self.x1, self.x2, 0.05)

        y = self.f_function.func(x)
        self.ax1.plot(x,
                      y,
                      color=self.pstyle[5],
                      marker='.',
                      linestyle='None',
                      markersize=float(self.pstyle[6]))

        upper = self.f_function.func(x) + self.f_function.confidence_points(x)
        lower = self.f_function.func(x) - self.f_function.confidence_points(x)
        self.ax1.fill_between(x,
                              lower,
                              upper,
                              facecolor='blue',
                              alpha=float(self.pstyle[8]))

        upper = self.f_function.func(x) + self.f_function.uncertainty(x)
        lower = self.f_function.func(x) - self.f_function.uncertainty(x)
        self.ax1.fill_between(x,
                              lower,
                              upper,
                              facecolor='green',
                              alpha=float(self.pstyle[8]))

        y = self.g_function.func(x)
        self.ax1.plot(x,
                      y,
                      color=self.pstyle[5],
                      marker='.',
                      linestyle='None',
                      markersize=float(self.pstyle[6]))

        upper = self.g_function.func(x) + self.g_function.confidence_points(x)
        lower = self.g_function.func(x) - self.g_function.confidence_points(x)
        self.ax1.fill_between(x,
                              lower,
                              upper,
                              facecolor='blue',
                              alpha=float(self.pstyle[8]))

        upper = self.g_function.func(x) + self.g_function.uncertainty(x)
        lower = self.g_function.func(x) - self.g_function.uncertainty(x)
        self.ax1.fill_between(x,
                              lower,
                              upper,
                              facecolor='green',
                              alpha=float(self.pstyle[8]))
        self.ax1.tick_params(axis='x', labelbottom='off')

        self.ax2 = self.fig.add_subplot(312)
        self.ax2.clear()

        self.ax2.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
        self.ax2.set_xlabel("", fontsize=int(self.pstyle[13]))
        self.ax2.set_ylabel(self.plot_labels[2] + ' / ' + self.plot_labels[4],
                            fontsize=int(self.pstyle[17]))
        self.ax2.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax2.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))
        self.ax2.tick_params(axis='x', labelbottom='off')

        x = np.arange(self.x1, self.x2, 0.05)

        ly = []
        for i in x:
            if self.g_function.func(i):
                ly.append(self.f_function.func(i) / self.g_function.func(i))
            else:
                ly.append(0.)
        y = array(ly)
        self.ax2.plot(x,
                      y,
                      color=self.pstyle[5],
                      marker='.',
                      linestyle='None',
                      markersize=float(self.pstyle[6]))

        self.ax3 = self.fig.add_subplot(313)
        self.ax3.clear()

        self.ax3.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
        self.ax3.set_xlabel(self.plot_labels[1], fontsize=int(self.pstyle[13]))
        self.ax3.set_ylabel(self.plot_labels[2] + ' - ' + self.plot_labels[4],
                            fontsize=int(self.pstyle[17]))
        self.ax3.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax3.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))

        x = np.arange(self.x1, self.x2, 0.05)

        ly = []
        for i in x:
            ly.append(self.f_function.func(i) - self.g_function.func(i))
        y = array(ly)
        self.ax3.plot(x,
                      y,
                      color=self.pstyle[5],
                      marker='.',
                      linestyle='None',
                      markersize=float(self.pstyle[6]))

        self.fig.subplots_adjust(left=0.12,
                                 right=0.97,
                                 top=0.94,
                                 bottom=0.11,
                                 hspace=0.17)

        self.canvas.draw()
Esempio n. 29
0
 def get_canvas_widget(self):
     """ returns a gtk widget including the plot to be directly used """
     self.load_plot()
     canvas = FigureCanvas(self.figure)
     canvas.set_size_request(365, 250)
     return canvas
Esempio n. 30
0
class PyApp(gtk.Window):
    def __init__(self):
        super(PyApp, self).__init__()

        self.reset = 1000 * 60 * 10
        self.interval = 30 * 1000
        self.n = 0
        self.selected = []
        self.buyprice = ''
        self.sellprice = ''
        self.balance = ''

        self.connect("destroy", gtk.main_quit)
        self.set_size_request(690, 600)
        self.set_position(gtk.WIN_POS_CENTER)
        self.set_title("Coinbase Trader")

        self.hfmt = dates.DateFormatter('%b %d')

        self.fixed = gtk.Fixed()

        self.btn_buy = gtk.Button("Buy BTC")
        self.btn_buy.set_size_request(110, 25)
        self.btn_buy.connect("clicked", self.buy_clicked)
        self.fixed.put(self.btn_buy, 570, 350)
        self.btn_buy.set_sensitive(False)

        self.btn_sell = gtk.Button("Sell BTC")
        self.btn_sell.set_size_request(110, 25)
        self.btn_sell.connect("clicked", self.sell_clicked)
        self.fixed.put(self.btn_sell, 570, 385)
        self.btn_sell.set_sensitive(False)

        self.btn_del = gtk.Button("Delete")
        self.btn_del.set_size_request(110, 25)
        self.btn_del.connect("clicked", self.del_clicked)
        self.fixed.put(self.btn_del, 570, 420)
        self.btn_del.set_sensitive(False)

        #self.btn_TRY = gtk.Button("TRY")
        #self.btn_TRY.set_size_request(110,25)
        #self.btn_TRY.connect("clicked",self.TRY)
        #self.fixed.put(self.btn_TRY, 570, 490)
        """self.btn_save.set_sensitive(False)"""

        self.btn_load = gtk.Button("Begin")
        self.btn_load.set_size_request(110, 25)
        self.btn_load.connect("clicked", self.load_clicked)
        self.fixed.put(self.btn_load, 570, 455)

        self.label_sell = gtk.Label("Sell: $" + self.sellprice)
        self.fixed.put(self.label_sell, 570, 490)
        self.label_buy = gtk.Label("Buy: $" + self.buyprice)
        self.fixed.put(self.label_buy, 570, 520)
        self.label_bal = gtk.Label("")  #Balance: "+self.balance)
        self.fixed.put(self.label_bal, 570, 550)

        self.statusbar = gtk.Label("")  #Balance: "+self.balance)
        self.fixed.put(self.statusbar, 10, 565)
        #------
        self.liststore = gtk.ListStore(bool, str)

        treeview = gtk.TreeView(model=self.liststore)

        renderer_radio = gtk.CellRendererToggle()
        renderer_radio.set_radio(False)
        renderer_radio.connect("toggled", self.order_selected)
        column_radio = gtk.TreeViewColumn("", renderer_radio, active=0)
        treeview.append_column(column_radio)

        renderer_text = gtk.CellRendererText()
        column_text = gtk.TreeViewColumn("Orders", renderer_text, text=1)
        treeview.append_column(column_text)

        treeview.set_size_request(550, 210)
        #------
        renderer_text.props.ellipsize = 3
        renderer_text.props.ellipsize_set = True  #wrap_width = 80
        self.fixed.put(treeview, 10, 350)

        self.S = ''
        self.n = 0
        self.API_KEY = ''
        self.API_SECRET = ''
        self.pwd = ''
        self.notAuth = True
        #self.load_file() #------------------------->COMMENT IT OUT LATER BUTTON WILL COME HERE

        self.add(self.fixed)
        self.show_all()
        self.update_graph()
        self.check_prices()

    def order_selected(self, widget, path):
        self.liststore[path][0] = not self.liststore[path][0]
        if (self.liststore[path][0]):
            self.selected.append(path)
        else:
            self.selected.remove(path)
        if (len(self.selected) > 0):
            self.btn_del.set_sensitive(True)
        #print(self.selected)

    def buy_clicked(self, button):
        z = ["Buy", 1, "BTC", "<", self.buyprice,
             -1]  # Buy/Sell QTY BTC/USD >/< Rate state
        createOrder.create_order(z)
        if (z[5] > 0):
            ordo = z[0] + '\t' + str(
                z[1]) + ' ' + z[2] + '\tif price ' + z[3] + ' ' + str(z[4])
            self.liststore.append([False, ordo])
            self.save_clicked()  #btn_save.set_sensitive(True)

    def sell_clicked(self, button):
        z = ["Sell", 1, "BTC", "<", self.sellprice,
             -1]  # Buy/Sell QTY BTC/USD >/< Rate state
        createOrder.create_order(z)
        if (z[5] > 0):
            ordo = z[0] + '\t' + str(
                z[1]) + ' ' + z[2] + '\tif price ' + z[3] + ' ' + str(z[4])
            self.liststore.append([False, ordo])
            self.save_clicked()  #btn_save.set_sensitive(True)

    def del_clicked(self, button):
        self.selected.sort()
        self.selected.reverse()
        for i in self.selected:
            self.liststore.remove(self.liststore[i].iter)
        self.selected = []  #.clear()
        self.btn_del.set_sensitive(False)
        self.save_clicked()  #btn_save.set_sensitive(True)

    def load_clicked(self, button):
        if (button.get_label() == "Begin"):
            try:
                self.S, self.p, self.API_KEY, self.API_SECRET, self.pwd = algos.begin_auth(
                )
                pp = self.p.split('\n')
                for tex in pp:
                    if (tex != ''):
                        self.liststore.append([False, tex])
                self.btn_buy.set_sensitive(True)
                self.btn_sell.set_sensitive(True)

                if (len(self.selected) > 0):
                    self.btn_del.set_sensitive(True)
                self.btn_load.set_label("New Password")
                self.notAuth = False
                self.check_prices()
            except:
                print("Couldn't open file")
                raise
                return

        else:
            pold = algos.getText("", "Current Password")
            count = 0
            while (algos.pad(str(pold)) != self.pwd):
                pold = algos.getText("Incorrect Password", "Current Password")
                count = count + 1
                if (count == 5):
                    return
            pwd = algos.getText('Enter new password',
                                'Password: '******'', 'Re-enter new password')  #raw_input("Re-enter passwd: ")
            count = 0
            while (pwd != pwd2):
                pwd = getText('Password mismatch, please try again',
                              'Password: '******'', 'Re-enter password')  #raw_input("Re-enter passwd: ")
                count = count + 1
                if (count == 5):
                    print("Password not changed")
                    return
            self.pwd = algos.pad(str(pwd))  #make it 32 chars long
        self.save_clicked()

    def save_clicked(self):  #,button):
        self.p = ''
        for k in self.liststore:
            self.p = self.p + k[1] + '\n'
        self.p = self.p[:-1]
        try:
            algos.end_auth(self.S, self.p, self.API_KEY, self.API_SECRET,
                           self.pwd)
            #self.btn_save.set_sensitive(False)
        except:
            print("Couldn't save changes")

    def update_graph(self):
        self.f = Figure(figsize=(4, 2.5), dpi=100)
        self.a = self.f.add_subplot(111)
        self.a.xaxis.set_major_formatter(self.hfmt)
        x, y = algos.update_mkt()
        self.a.plot(x, y)
        self.a.yaxis.grid()
        for item in ([self.a.title, self.a.xaxis.label, self.a.yaxis.label] +
                     self.a.get_xticklabels() + self.a.get_yticklabels()):
            item.set_fontsize(10)

        self.canvas = FigureCanvas(self.f)  # a gtk.DrawingArea
        self.canvas.set_size_request(670, 330)
        self.fixed.put(self.canvas, 10, 10)
        self.show_all()
        return True

    def check_prices(self):
        s = algos.get_http("http://coinbase.com/api/v1/prices/buy").read()
        s = s.translate(maketrans(':', ','), '[]{}\"').split(',')[-4:]
        if (s[3] == 'USD'):
            self.buyprice = s[1]
            self.label_buy.set_label("Buy: $" + self.buyprice)

        s = algos.get_http("http://coinbase.com/api/v1/prices/sell").read()
        s = s.translate(maketrans(':', ','), '[]{}\"').split(',')[-4:]
        if (s[3] == 'USD'):
            self.sellprice = s[1]
            self.label_sell.set_label("Sell: $" + self.sellprice)
        if (self.notAuth):
            return True

        #We Have an API KEY :)
        try:
            s = algos.get_https('https://coinbase.com/api/v1/account/balance',
                                self.API_KEY, self.API_SECRET).read()
            s = s.translate(maketrans(':', ','), '[]{}\"').split(',')
            if (s[0] == 'amount' and s[3] == 'BTC'):
                self.balance = s[1]
                self.label_bal.set_label("Bal: " + self.balance)
            else:
                print("Wrong KEYS")
                self.notAuth = True
        except:
            print("Lost Internet connection perhaps?")

        for k in self.liststore:
            s = k[1]
            #check if this order is satisfied
            fullfillable = False
            s = s.split()
            if (s[0] == "Sell"):
                price = float(self.sellprice)
            else:
                price = float(self.buyprice)
            if (s[5] == '>' and price > float(s[6])):
                fullfillable = True
            if (s[5] == '<' and price < float(s[6])):
                fullfillable = True
            qty = float(s[1])
            if (s[2] == 'USD'):
                qty = qty / price
            if (fullfillable):
                try:
                    bod = 'qty=' + str(qty)
                    if (s[0] == "Sell"):
                        res = algos.get_https(
                            'https://coinbase.com/api/v1/sells', self.API_KEY,
                            self.API_SECRET, bod).read()
                        res = res.translate(maketrans(':', ','),
                                            '[]{}\"').split(',')
                        s = res[4] + ": Sold " + s[1] + "BTC for " + res[
                            20] + " " + res[48]
                    if (s[0] == "Buy"):
                        res = algos.get_https(
                            'https://coinbase.com/api/v1/buys', self.API_KEY,
                            self.API_SECRET, bod).read()
                        res = res.translate(maketrans(':', ','),
                                            '[]{}\"').split(',')
                        s = res[4] + ": Bought " + s[1] + "BTC for " + res[
                            20] + " " + res[48]

                    if (res[:2] == ['success', 'true']):
                        self.statusbar.set_label(s)
                        self.liststore.remove(k.iter)
                        self.save_clicked()
                except:
                    print("failed for some reason")
                    fullfillable = False
                    raise

        self.selected = []
        i = 0
        for k in self.liststore:
            if (k[0]):
                self.selected.append(str(i))
            i = i + 1
        #self.clock.set_label('['+str(self.n)+']  '+str(time.strftime("%H:%M:%S")))
        self.n = self.n + 1
        return True
    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 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
Esempio n. 33
0
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 ()
Esempio n. 34
0
class G_Plot():
    def __init__(self, title, function):

        self.title = title

        # MAT-PLOT-LIB_____________________________________________________
        self.fig = Figure(figsize=(6, 4))  # create fig
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(400, 300)  # set min size
        self.markers = [
            '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's',
            'p', '*', 'h', 'H', 'D', 'd'
        ]
        self.colors = [
            'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow',
            'purple', 'white'
        ]
        self.pstyle = [
            'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '',
            '25', '', '', '20', '15', '', '', '20', '15'
        ]

        self.styledict = {}
        self.styledict["style"] = 'bmh'
        self.styledict["point_style"] = 's'
        self.styledict["point_size"] = '6'
        self.styledict["point_color"] = 'red'
        self.styledict["point_alpha"] = '0.8'
        self.styledict["line_color"] = 'black'
        self.styledict["line_width"] = '2'
        self.styledict["band_color"] = 'black'
        self.styledict["band_alpha"] = '0.3'
        self.styledict["title_size"] = '25'
        self.styledict["xtitle_size"] = '20'
        self.styledict["xlabel_size"] = '15'
        self.styledict["ytitle_size"] = '20'
        self.styledict["ylabel_size"] = '15'

        self.function = function

        self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1]
        self.plot_labels = ["Time Exposure", "t", "G(x)", " [h]", " []"]
        #print plt.style.available
        self.fit_toggle = 'inactive'
        self.points_toggle = 1
        self.function_toggle = 1
        self.err_toggle = 1
        self.ci_func_toggle = 1
        self.ci_points_toggle = 1
        #self.plotting(function)

    def plotting(self, t, t0):
        """Generating matplotlib canvas"""
        plt.style.use(self.pstyle[0])

        self.ax1 = self.fig.add_subplot(111)
        self.ax1.clear()

        self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
        self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3],
                            fontsize=int(self.pstyle[13]))
        self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4],
                            fontsize=int(self.pstyle[17]))
        self.ax1.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax1.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))

        x = np.arange(0.000001, 1.5 * max(t, t0), 0.01)

        y = self.function(x, t0)
        self.ax1.plot(x,
                      y,
                      color=self.pstyle[5],
                      marker='.',
                      linestyle='None',
                      markersize=float(self.pstyle[6]))

        self.ax1.axvline(x=t, linewidth=1, linestyle='-', color='red')
        self.ax1.axhline(y=self.function(t, t0),
                         linewidth=1,
                         linestyle='--',
                         color='red')

        self.fig.tight_layout()
        self.canvas.draw()
Esempio n. 35
0
# uncomment to select /GTK/GTKAgg/GTKCairo
#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
#from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas

win = gtk.Window()
win.connect("destroy", lambda x: gtk.main_quit())
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")

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)

sw = gtk.ScrolledWindow()
win.add(sw)
# A scrolled window border goes outside the scrollbars and viewport
sw.set_border_width(10)
# policy: ALWAYS, AUTOMATIC, NEVER
sw.set_policy(hscrollbar_policy=gtk.POLICY_AUTOMATIC,
              vscrollbar_policy=gtk.POLICY_ALWAYS)

canvas = FigureCanvas(f)  # a gtk.DrawingArea
canvas.set_size_request(800, 600)
sw.add_with_viewport(canvas)

win.show_all()
gtk.main()
Esempio n. 36
0
class GUI(gtk.Window):

    def __init__(self):
        gtk.Window.__init__(self)
        self.connect("destroy", self.onClose)

        # GUI layout initialization
        self.initLayout()

        # center it on the screen
        self.set_position(gtk.WIN_POS_CENTER)

        # show the form
        self.show_all()

    def initLayout(self):

        # initialization
        self.set_title("Data Acquisition")
        self.set_border_width(10)

        # add snapshot reading outputs, a tree on the left and a plot on the right
        self.liststore = gtk.ListStore(str, float, float, str)

        # create the TreeView using liststore
        self.treeview = gtk.TreeView(self.liststore)

        # setup a row in the liststore for each channel
        for ch in channels.Channels:
            self.liststore.append([ch.name, float('nan'), float('nan'), ch.units])

        # create a channel name column
        self.tvcolumn = gtk.TreeViewColumn('Channel Name')
        self.cell = gtk.CellRendererText()
        self.tvcolumn.pack_start(self.cell, True)
        self.tvcolumn.set_attributes(self.cell, text=0)

        # create a channel bits column
        self.tvcolumn1 = gtk.TreeViewColumn('Digital Bits')
        self.cell1 = gtk.CellRendererText()
        self.tvcolumn1.pack_start(self.cell1, True)
        self.tvcolumn1.set_attributes(self.cell1, text=1)

        # create a channel analog voltage column
        self.tvcolumn2 = gtk.TreeViewColumn('Analog Voltage')
        self.cell2 = gtk.CellRendererText()
        self.tvcolumn2.pack_start(self.cell2, True)
        self.tvcolumn2.set_attributes(self.cell2, text=2)

        # create a channel analog voltage column
        self.tvcolumn3 = gtk.TreeViewColumn('Value [units]')
        self.cell3 = gtk.CellRendererText()
        self.tvcolumn3.pack_start(self.cell3, True)
        self.tvcolumn3.set_attributes(self.cell3, text=3)

        # add columns to treeview
        self.treeview.append_column(self.tvcolumn)
        self.treeview.append_column(self.tvcolumn1)
        self.treeview.append_column(self.tvcolumn2)
        self.treeview.append_column(self.tvcolumn3)

        # create the plot and add it also
        self.plt = matplotlib.pyplot
        self.fig = self.plt.figure()
        self.ax = self.fig.add_subplot(1,1,1)
        self.canvas = Canvas(self.fig)
        self.ax.xaxis.grid(True)
        self.ax.yaxis.grid(True)
        self.ax.plot([0],[0])
        self.canvas.set_size_request(600,400)

        # create the hbox to hold this tree and the snapshot plot
        hbox_plot = gtk.HBox(spacing=6)
        hbox_plot.pack_start(self.treeview)
        hbox_plot.pack_start(self.canvas)

        # form buttons
        self.btnEditInfo = gtk.Button(label = "Edit Info")
        self.btnEditInfo.connect("clicked", self.onEdit)
        self.btnRunTest = gtk.Button(label = "Start (test)")
        self.btnRunTest.connect("clicked", self.onRunTest)
        self.btnRun = gtk.Button(label = "Start (write data)")
        self.btnRun.connect("clicked", self.onRun)
        self.btnStop = gtk.Button(label = "Stop")
        self.btnStop.connect("clicked", self.onStop)
        self.btnStop.set_sensitive(False)
        self.btnClose = gtk.Button(stock = gtk.STOCK_CLOSE)
        self.btnClose.connect("clicked", self.onClose)
        hbox_btns = gtk.HBox(spacing=6)
        hbox_btns.pack_start(self.btnEditInfo)
        hbox_btns.pack_start(self.btnRunTest)
        hbox_btns.pack_start(self.btnRun)
        hbox_btns.pack_start(self.btnStop)
        hbox_btns.pack_start(self.btnClose)

        # status bar
        self.sbar = gtk.Statusbar()
        self.context_id = self.sbar.get_context_id("Statusbar")
        self.sbar.push(self.context_id, "Program has been initialized!")
        self.sbar.show()
        hbox_status = gtk.HBox(spacing=6)
        hbox_status.pack_start(self.sbar)

        # vbox to hold everything
        vbox = gtk.VBox(spacing=6)
        vbox.pack_start(hbox_plot, False, False, 0)
        vbox.pack_start(hbox_btns, False, False, 0)
        vbox.pack_start(hbox_status)

        # store master container in the window
        self.add(vbox)

    def startThread(self, writeData = True):
        # instantiate the main data acquisition class
        self.DataAcquirer = MainDataLooper(gui.processIsComplete, gui.updateStatus, writeData)
        # start the data acquisition as a separate (background) thread
        Thread(target=self.DataAcquirer.run).start()

    def onRunTest(self, widget):
        for ch in channels.Channels:
            self.ax.plot(ch.timeHistory, ch.valueHistory, label=ch.name)
        self.startThread(writeData = False)
        self.btnRun.set_sensitive(False)
        self.btnRunTest.set_sensitive(False)
        self.btnEditInfo.set_sensitive(False)
        self.btnStop.set_sensitive(True)

    def onRun(self, widget):
        for ch in channels.Channels:
            self.ax.plot(ch.timeHistory, ch.valueHistory, label=ch.name)
        self.startThread()
        self.btnRun.set_sensitive(False)
        self.btnRunTest.set_sensitive(False)
        self.btnEditInfo.set_sensitive(False)
        self.btnStop.set_sensitive(True)

    def onStop(self, widget):
        self.DataAcquirer.forceStop = True
        self.btnRun.set_sensitive(True)
        self.btnRunTest.set_sensitive(True)
        self.btnEditInfo.set_sensitive(True)
        self.btnStop.set_sensitive(False)

    def onClose(self, widget):
        if hasattr(self, 'DataAcquirer'):
            self.DataAcquirer.forceStop = True
        gtk.main_quit()

    def onEdit(self, widget):

        # need to get project inputs first:
        InputWin = InputWindow()

        # this will block until the user clicks or destroys the form
        retVal = InputWin.run()

        # only continue if we surely got the OK response
        if retVal == gtk.RESPONSE_OK:
            # update the info class
            info.name.set_val(InputWin.entry_name.get_text())
            info.location.set_val(InputWin.entry_location.get_text())
            info.date.set_val(InputWin.entry_date.get_text())
            info.depth.set_val(InputWin.entry_depth.get_text())
            info.diameter.set_val(InputWin.entry_diameter.get_text())
            info.loop.set_val(InputWin.entry_loop.get_text())
            info.grout.set_val(InputWin.entry_grout.get_text())
            info.cement.set_val(InputWin.entry_cement.get_text())
            info.swl.set_val(InputWin.entry_swl.get_text())
            info.tester.set_val(InputWin.entry_tester.get_text())
            info.witness.set_val(InputWin.entry_witness.get_text())
            # update on the status bar
            self.sbar.push(self.context_id, "Project information was updated!")

        # of course we can destroy the window now
        InputWin.destroy()

    def updateTree(self):
        bits = []
        for ch in range(len(channels.Channels)):
            bits.append(channels.Channels[ch].bits)
            self.liststore[ch][1] = channels.Channels[ch].bits
            self.liststore[ch][2] = channels.Channels[ch].volts
            self.liststore[ch][3] = '%s %s' % (channels.Channels[ch].valueHistory[-1], channels.Channels[ch].units)

    def updatePlot(self):
        self.ax.clear()
        for ch in channels.Channels:
            if ch.plot:
                self.ax.plot(ch.timeHistory, ch.valueHistory, label=ch.name)
        self.ax.xaxis.grid(True)
        self.ax.yaxis.grid(True)
        self.plt.legend(loc='upper left')
        self.canvas.draw()

    def updateStatus(self, msg):
        self.sbar.push(self.context_id, msg)
        self.updateTree()
        self.updatePlot()

    def processIsComplete(self):
        self.btnRun.set_sensitive(True)
        self.btnRunTest.set_sensitive(True)
        self.btnEditInfo.set_sensitive(True)
        self.btnStop.set_sensitive(False)
        # update on the status bar
        self.sbar.push(self.context_id, "Data Acquisition Process Complete!")
Esempio n. 37
0
class Plotter():
    def __init__(self, context, data, fitfunction):
        self.context = context
        self.data = data
        self.fitfunction = fitfunction

        self.fig = Figure(figsize=(6, 4))  # create fig
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(600, 400)  # set min size
        self.markers = [
            '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's',
            'p', '*', 'h', 'H', 'D', 'd'
        ]
        self.colors = [
            'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow',
            'purple', 'white'
        ]
        self.pstyle = [
            'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '',
            '25', '', '', '20', '15', '', '', '20', '15'
        ]

        self.styledict = {}
        self.styledict["style"] = 'bmh'
        self.styledict["point_style"] = 's'
        self.styledict["point_size"] = '6'
        self.styledict["point_color"] = 'red'
        self.styledict["point_alpha"] = '0.8'
        self.styledict["line_color"] = 'black'
        self.styledict["line_width"] = '2'
        self.styledict["band_color"] = 'black'
        self.styledict["band_alpha"] = '0.3'
        self.styledict["title_size"] = '25'
        self.styledict["xtitle_size"] = '20'
        self.styledict["xlabel_size"] = '15'
        self.styledict["ytitle_size"] = '20'
        self.styledict["ylabel_size"] = '15'

        self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1]
        self.plot_labels = []
        self.plot_labels.append(data.labels[3] + " vs " +
                                data.labels[0])  # plot title
        self.plot_labels.append(data.labels[0])  # x-axis title
        self.plot_labels.append(data.labels[3])  # y-axis title
        self.plot_labels.append("[Gy]")  # x-axis unit
        self.plot_labels.append(" ")  # y-axis unit
        #print plt.style.available

        self.fit_toggle = 'active'
        self.points_toggle = 1
        self.function_toggle = 1
        self.err_toggle = 1
        self.ci_func_toggle = 1
        self.ci_points_toggle = 1
        toolbar = NavigationToolbar(self.canvas, self)
        toolbarbox = gtk.HBox()
        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR)
        options_button = gtk.Button()
        options_button.add(image)
        image2 = gtk.Image()
        image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR)
        refresh_button = gtk.Button()
        refresh_button.add(image2)
        toolbarbox.pack_start(toolbar, True, True)
        toolbarbox.pack_end(options_button, False, True)
        toolbarbox.pack_end(refresh_button, False, True)
        self.vbox = gtk.VBox()
        self.vbox.pack_start(toolbarbox, False, False)
        self.vbox.pack_start(self.canvas, True, True)

        # signals
        self.canvas.mpl_connect('pick_event', self.on_pick)
        options_button.connect('clicked', self.mpl_options)
        refresh_button.connect('clicked', self.on_refresh_clicked)

    def on_pick(self, event):
        artist = event.artist
        xmouse, ymouse = event.mouseevent.xdata, event.mouseevent.ydata
        x, y = artist.get_xdata(), artist.get_ydata()
        ind = event.ind
        print 'Artist picked:', event.artist
        print '{} vertices picked'.format(len(ind))
        print 'Pick between vertices {} and {}'.format(min(ind), max(ind))
        print 'x, y of mouse: {:.2f},{:.2f}'.format(xmouse, ymouse)
        print 'Data point:', x[ind[0]], y[ind[0]]
        print
        self.context.log('Data point:\t  ' + str(x[ind[0]]) + '\t' +
                         str(y[ind[0]]))
        self.context.treeview.treeview.set_cursor(min(ind))
        self.context.treeview.treeview.grab_focus()

    def mpl_options(self, button):
        """Create GTKDialog containing options for plotting and connect signals."""
        mpl_options_dialog = MPLOptions(self.context, self)

    def on_refresh_clicked(self, button):
        """Refresh canvas - plot everything again"""
        self.plotting()

    def plotvline(self, **kwargs):
        self.ax1.axvline(**kwargs)

    def plothline(self, **kwargs):
        self.ax1.axhline(**kwargs)

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

    def plotting(self):
        """Generating matplotlib canvas"""

        plt.style.use(self.pstyle[0])

        self.ax1 = self.fig.add_subplot(111)
        self.ax1.clear()

        if self.points_toggle == 1:
            self.ax1.errorbar(self.data.get_xdata(),
                              self.data.get_ydata(),
                              self.data.get_yerr(),
                              fmt='none',
                              ecolor='black',
                              elinewidth=0.5,
                              capsize=0.5,
                              capthick=0.5)
            self.ax1.plot(self.data.get_xdata(),
                          self.data.get_ydata(),
                          color=self.pstyle[3],
                          label=self.data.labels[3],
                          marker=self.pstyle[1],
                          alpha=float(self.pstyle[4]),
                          linestyle='None',
                          markersize=float(self.pstyle[2]),
                          picker=float(self.pstyle[2]))

        self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
        self.ax1.set_xlabel(self.plot_labels[1] + self.plot_labels[3],
                            fontsize=int(self.pstyle[13]))
        self.ax1.set_ylabel(self.plot_labels[2] + self.plot_labels[4],
                            fontsize=int(self.pstyle[17]))
        self.ax1.tick_params(axis='x',
                             which='both',
                             labelsize=int(self.pstyle[14]))
        self.ax1.tick_params(axis='y',
                             which='both',
                             labelsize=int(self.pstyle[18]))

        x = np.arange(-0.1, max(20, max(self.data.get_xdata())) * 1.1, 0.05)

        if (self.fit_toggle == 'active'):
            if len(self.data.get_xdata()) >= 3:
                print "before fit", self.fitfunction.params
                print "before fit", self.fitfunction.params
                print "xdata", self.data.get_xdata()
                print "ydata", self.data.get_ydata()
                self.fitfunction.fit_function(self.data.get_xdata(),
                                              self.data.get_ydata(),
                                              self.data.get_yerr())
                print "after fit", self.fitfunction.params
                print "after fit", self.fitfunction.params
                self.context.functiontab.function_changed()
            else:
                self.context.log("Too few data to fit the function!")

        if self.function_toggle == 1:
            y = self.fitfunction.func(x, self.fitfunction.params)
            self.ax1.plot(x,
                          y,
                          color=self.pstyle[5],
                          marker='.',
                          linestyle='None',
                          markersize=float(self.pstyle[6]))

        if self.ci_func_toggle == 1 and self.fit_toggle == 'active':
            conf = confidence(x, self.data.get_xdata(), len(x),
                              np.mean(self.data.get_xdata()),
                              self.fitfunction.dof, self.fitfunction.rmse)
            upper = self.fitfunction.func(x, self.fitfunction.params) + conf
            lower = self.fitfunction.func(x, self.fitfunction.params) - conf
            self.ax1.fill_between(x,
                                  lower,
                                  upper,
                                  facecolor=self.pstyle[7],
                                  alpha=float(self.pstyle[8]))

        if self.ci_points_toggle == 1:
            upper = self.fitfunction.func(
                x, self.fitfunction.params) + confidence_points(
                    x, self.fitfunction.std_err)
            lower = self.fitfunction.func(
                x, self.fitfunction.params) - confidence_points(
                    x, self.fitfunction.std_err)
            self.ax1.fill_between(x,
                                  lower,
                                  upper,
                                  facecolor='blue',
                                  alpha=float(self.pstyle[8]))

        if self.err_toggle == 1:
            upper = self.fitfunction.func(
                x, self.fitfunction.params) + uncertainty(
                    x, self.fitfunction.std_err)
            lower = self.fitfunction.func(
                x, self.fitfunction.params) - uncertainty(
                    x, self.fitfunction.std_err)
            self.ax1.fill_between(x,
                                  lower,
                                  upper,
                                  facecolor='green',
                                  alpha=float(self.pstyle[8]))

        self.fig.subplots_adjust(left=0.13,
                                 right=0.96,
                                 top=0.91,
                                 bottom=0.13,
                                 hspace=0.04)
        self.canvas.draw()

        print self.fitfunction.params
        print self.fitfunction.std_err
Esempio n. 38
0
	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()
Esempio n. 39
0
    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
Esempio n. 40
0
    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
Esempio n. 41
0
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()
Esempio n. 42
0
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)
Esempio n. 43
0
class MainView(BasePlotView, gtk.Frame):
    """
    A Gtk Frame based plotting widget for dreampy
    that contains additional tool bar items for printing
    and adding notes
    """
    def __init__(self, win, **kwargs):
        gtk.Frame.__init__(self)
        BasePlotView.__init__(self, **kwargs)
        self.win = win
        self.title = None

        #Put some stuff
        # self.suppress_header = kwargs.get('suppress_header', False)
        # self.suppress_title = kwargs.get('suppress_title', False)
        # self.suppress_legend = kwargs.get('suppress_legend', False)
        self.vbox = gtk.VBox(False, 0)
        self.add(self.vbox)
        self.sw = gtk.ScrolledWindow()
        self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.vbox.pack_start(self.sw, True, True, 0)
        self.sw.show()
        self.f = Figure(figsize=(5,4), dpi=100)
        self.canvas = FigureCanvas(self.f)  # a gtk.DrawingArea
        self.canvas.set_size_request(400,300)
        self.sw.add_with_viewport (self.canvas)
        self.canvas.show_all()
        self.toolbar = NavToolBar(self.canvas, self.win)
        self.vbox.pack_start(self.toolbar, False, False)
        self.toolbar.show()
        self.vbox.show()
        # self.autoscale = True
        # self.xmin = None
        # self.xmax = None
        # self.ymin = None
        # self.ymax = None
        # self.image = None
        # self.hold_plot = False
        # self.keyid = None
        # self.filter = None
        # self.labelsize = 8
        # self.titlesize = 10
        # self.ticklabelsize = 8
        # self.ticklabelweight = 'normal'
        # self.labelweight = 'bold'
        # self.titleweight = 'bold'
        # self.legendsize = 8
        # self.legendweight = 'normal'
        # self.hdrlabelsize = 9
        # self.hdrlabelweight = 'normal'
        # self.cur_axname = None
        self.refresh_canvas()
        self.show_all()
        #self.gtk_catchup()
        
    def gtk_catchup(self):
        gtk.gdk.threads_enter()
        while gtk.events_pending():
            gtk.main_iteration()
        gtk.gdk.threads_leave()        
        
    def create_arrow_button(self, arrow_type, shadow_type):
        button = gtk.Button()
        self.arrow = gtk.Arrow(arrow_type, shadow_type)
        button.add(self.arrow)
        button.show()
        self.arrow.show()
        return button

    def list_widgets_turnoff(self):
        self.left_button.set_sensitive(False)
        self.right_button.set_sensitive(False)
        self.ignore_button.set_sensitive(False)        
        #if self.keyid:
        #    self.canvas.disconnect(self.keyid)


    def disconnect_event(self, sig):
        if self.canvas:
            self.canvas.mpl_disconnect(sig)

    def connect_event(self, eventname, eventfunc):
        if self.canvas:
            self.canvas.set_flags(gtk.CAN_FOCUS)  #to grab focus for keystrokes
            self.canvas.grab_focus()    #to grab focus for keystrokes
            return self.canvas.mpl_connect(eventname, eventfunc)

    def redraw_plot(self):
        if self.hold_plot is False:
            if hasattr(self.canvas, 'show_all'):
                self.canvas.show_all()
            self.canvas.draw()
        self.gtk_catchup()
Esempio n. 44
0
class Iverplot_window (object):
    """
    Iverplot_window---main Iverplot GUI object

    Parameters
    -----------

    Notes
    ------

    """
    def __init__ (self):
        self.builder = gtk.Builder ()
        self.builder.add_from_file ('iverplot.glade')
        self.builder.connect_signals (self)
        self.window = self.builder.get_object ('main_window')

        # add matplotlib figure canvas
        w,h = self.window.get_size ()
        self.fig = Figure (figsize=(6,4))
        self.canvas = FigureCanvas (self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request (w-150,-1)

        vbox = gtk.VBox()
        toolbar = NavigationToolbar (self.canvas, self.window)
        vbox.pack_start (self.canvas, True, True)
        vbox.pack_start (toolbar, False, False)

        # a little hacky for packing hpane with figure canvas first then tool
        # bar---not sure if glade is to blame---first, remove tool_vbox then
        # repack
        plot_hpaned = self.builder.get_object ('plot_hpaned')
        self.tool_vbox = self.builder.get_object ('tool_vbox')
        plot_hpaned.remove (self.tool_vbox)

        #plot_hpaned.pack1 (self.canvas, resize=True, shrink=False)
        plot_hpaned.pack1 (vbox, resize=True, shrink=False)
        plot_hpaned.pack2 (self.tool_vbox)

        # data
        self.uvclog = None
        self.lcmlog = None

        # plot limits
        self.xlimits = [None,None]
        self.xlimits_abs = [None,None]

        # add single plot item
        self.plotdex = {}
        self.plot_items = []
        self.plot_items.append (Plot_item (self.tool_vbox,
            self.on_plot_item_selected, self.uvclog, self.lcmlog))
        self.update_subplots ()

        # setwin
        self.setwin = None

        # set some defaults
        self.cd_saveas = os.getcwd ()
        self.cd_open = os.getcwd ()

        self.window.show_all ()

    def on_setwin_clicked (self, widget):
        if self.setwin is None: 
            self.setwin = Setwin (self.canvas, self.fig, self.on_setwin_complete)

    def on_setwin_complete (self, xmin, xmax):
        self.xlimits = [xmin,xmax]
        for p in self.plot_items:
            ax = self.fig.axes[self.plotdex[p]]
            p.plot_type.set_limits (ax, *self.xlimits)
        self.canvas.draw ()
        self.setwin = None

    def on_setwin_reset (self, widget):
        if not self.setwin is None: return
        self.xlimits = [x for x in self.xlimits_abs]
        for p in self.plot_items:
            ax = self.fig.axes[self.plotdex[p]]
            p.plot_type.set_limits (ax, *self.xlimits)
        self.canvas.draw ()

    def update_subplots (self):
        self.fig.clear ()
        n = len (self.plot_items)
        for i,p in enumerate (self.plot_items):
            p.plot_type.uvclog = self.uvclog
            p.plot_type.lcmlog = self.lcmlog
            ax = self.fig.add_subplot (n,1,i+1)
            p.plot_type.plot (ax, *self.xlimits)
            self.plotdex[p] = i
        self.canvas.draw ()

    def on_plot_item_selected (self, combo, item):
        ax = self.fig.axes[self.plotdex[item]]
        item.plot_type.plot (ax, *self.xlimits)
        self.canvas.draw ()

    def update_window (self):
        while gtk.events_pending ():
            gtk.main_iteration_do (True)

    def on_add_subplot_clicked (self, widget):
        if len (self.plot_items) >= 3:
            return

        self.plot_items.append (Plot_item (self.tool_vbox,
            self.on_plot_item_selected, self.uvclog, self.lcmlog))
        self.update_subplots ()
        self.update_window ()

    def on_remove_subplot_clicked (self, widget):
        if len (self.plot_items) <= 1:
            return

        item = self.plot_items.pop (-1)
        item.remove ()
        self.update_subplots ()
        self.update_window ()

    def run_open_dialog (self):
        open_dlg = self.builder.get_object ('open_dialog')
        #open_dlg.set_current_folder (self.cd_open)
        open_dlg.set_current_folder ('/home/jeff/data/UMBS_0513/iver28/2013-06-01-dive.046')

        if len (open_dlg.list_filters ()) == 0:
            all_filter = gtk.FileFilter ()
            all_filter.set_name ('All files')
            all_filter.add_pattern ('*')
            open_dlg.add_filter (all_filter)

            lcm_filter = gtk.FileFilter ()
            lcm_filter.set_name ('LCM logs')
            lcm_filter.add_pattern ('lcmlog*')
            open_dlg.add_filter (lcm_filter)

            uvc_filter = gtk.FileFilter ()
            uvc_filter.set_name ('UVC logs')
            uvc_filter.add_pattern ('*.log')
            open_dlg.add_filter (uvc_filter)

        response = open_dlg.run ()
        fname = None
        if response == gtk.RESPONSE_OK:
            fname = open_dlg.get_filename ()
            self.cd_open = os.path.dirname (fname)

        open_dlg.hide ()
        return fname

    def on_open_lcm_clicked (self, widget):
        fname = self.run_open_dialog ()
        if fname: print 'selected', fname

    def on_open_uvc_clicked (self, widget):
        fname = self.run_open_dialog ()
        if fname: 
            print 'selected', fname
            try:
                self.uvclog = UVCLog (fname)
                self.xlimits_abs = [self.uvclog.utime[0], self.uvclog.utime[-1]]
                self.xlimits = [x for x in self.xlimits_abs]
                self.update_subplots ()
            except:
                print 'could not load correctly'

    def on_save_as_clicked (self, widget):
        save_as_dlg = self.builder.get_object ('save_as_dialog')
        save_as_dlg.set_current_folder (self.cd_saveas)
        save_as_dlg.set_current_name ('iverplot.png')

        if len (save_as_dlg.list_filters ()) == 0:
            all_filter = gtk.FileFilter ()
            all_filter.set_name ('All files')
            all_filter.add_pattern ('*')
            save_as_dlg.add_filter (all_filter)

            img_filter = gtk.FileFilter ()
            img_filter.set_name ('All images')
            img_filter.add_pattern ('*.png')
            img_filter.add_pattern ('*.jpg')
            img_filter.add_pattern ('*.pdf')
            save_as_dlg.add_filter (img_filter)

        response = save_as_dlg.run ()
        if response == gtk.RESPONSE_OK: 
            fname = save_as_dlg.get_filename ()
            self.fig.savefig (fname, dpi=self.fig.dpi)
            self.cd_saveas = os.path.dirname (fname)
        save_as_dlg.hide ()

    def on_about_clicked (self, widget):
        about = self.builder.get_object ('about_dialog')
        about.run ()
        about.hide () 

    def on_main_window_destroy (self, widget):
        gtk.main_quit ()
	def dynamics(self,*args,**kwargs):
#		self.wTree.get_widget("image").set_from_file("./wait.png")
		print 'dynamics started'
		mouse_size=20								#ind parameter
		cat_mature_size=60							#ind parameter
		
#		catch_rate=5*10**-4 	                                                #parameter
#		cat_efficiency=0.8                                                      #parameter
#		a=0.2                                                                   #will get from slider
#		c=0.2                                                                   #will get from slider
		
		cat_catch_rate=self.wTree.get_widget("catchrate").get_value()*10**-4    #parameter
		cat_efficiency=self.wTree.get_widget("efficiency").get_value()          #parameter
		a=self.wTree.get_widget("a").get_value()                                #parameter
		c=self.wTree.get_widget("c").get_value()                                #parameter      
		
		mouse_no=1000
		cat_no=1000
		t=0
		tmax=200
		dt=0.4
		
		timeli=[]
		miceli=[]
		catli=[]
			
		mice=[rodent() for i in range(mouse_no)]
		cats=[felix() for i in range(cat_no)]
		
		catn=len(cats)
		mousen=len(mice)
		
		self.dic={}
		num=40
		size=10
		catno=catn*num**2/(catn+mousen)
		disp_cats=random.sample(range(num**2),catno)
	
		if self.wTree.get_widget("anim").get_active()==1:
			print 'yay!'
			for i in range(num**2):
				coords=((i%num)*size*2-num*size,(i/num)*size*2-num*size)
				if i in disp_cats:
					self.dic[i]=visual.sphere(pos=coords,radius=size,color=visual.color.red)
				else :
					self.dic[i]=visual.sphere(pos=coords,radius=size,color=visual.color.green)
		print self.dic
		catn=len(cats)
		mousen=len(mice)
		data=open('tempdata.dat','w')
		timestart=time.time()
		while len(mice)>0 and len(cats)>0 and t<tmax and (time.time()-timestart)<60:
			print time.time()-timestart
			catn=len(cats)
			mousen=len(mice)
			if self.wTree.get_widget("anim").get_active()==1:
				print 'yay!'
#				self.visualize(catn,mousen)
				thread.start_new_thread(self.visualize,(catn,mousen))

			for mouse in mice:			
				if mouse.time_from_last_childbirth>=1/a:
					mouse.time_from_last_childbirth=0
					mice.append(rodent())
	
				mouse.time_from_last_childbirth+=dt
	
			ind=0
			while ind<len(cats):
				cat=cats[ind]
				cat.age+=dt
				num=cat_catch_rate*dt*len(mice)
				
				for i in range(int(num)):
					caught=random.randint(0,len(mice)-1)
					cat.size+=mouse_size*cat_efficiency			#size increases
					mice.pop(caught)
				
				if (num-int(num))>random.uniform(0,1):
					caught=random.randint(0,len(mice)-1)
					cat.size+=mouse_size*cat_efficiency			#size increases
					mice.pop(caught)
				
				if cat.size>cat_mature_size:
					if cat.is_virgin:
						cat.is_virgin=0
						cat.reproduction_gap=cat.age
						cats.append(felix())
					else :
						if cat.time_from_last_childbirth>cat.reproduction_gap:
							cats.append(felix())
							cat.time_from_last_childbirth=0
	
				if cat.is_virgin==0:
					cat.time_from_last_childbirth+=dt
	
	
				if len(cats)>0:
					if c*dt*2*atan(0.05*len(cats))/pi>random.uniform(0,1):
						cats.pop(ind)
					else :
						ind+=1
				else :
					ind+=1
	
	
			timeli.append(t)
			miceli.append(len(mice))
			catli.append(len(cats))
		#	print t,'\t',len(mice),'\t',len(cats)
			print >> data, t,'\t',len(mice),'\t',len(cats)
	
			t+=dt
		data.close()
		
		upper_limit=1.2*len(mice)
		pltfile=open('lv.plt','w')
		print >> pltfile,"""se te png
se o "/tmp/lv.png"
unse ke
#se yrange [0:%f]
se xl "Time"
se yl "Number of Prey/Predator"
p 'tempdata.dat' u 1:2 w l,'tempdata.dat' u 1:3 w l
"""%upper_limit
		pltfile.close()
		commands.getoutput('gnuplot lv.plt')
	
		self.ax.plot(timeli,miceli,timeli,catli)
		canvas = FigureCanvas(self.f)  # a gtk.DrawingArea
		canvas.set_size_request(600,400)
		self.wTree.get_widget("sw").add_with_viewport(canvas)


		print 'dynamics ended'
Esempio n. 46
0
class MPLWin(gtk.Window, Observer):
    """
    CLASS: MPLWin
    DESCR: Superclass for graphing a single channel
    """
    _title = 'Figure window'
    _size = 600,400
    _iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR


    _detrendd = {'None'  : detrend_none,
                 'Mean'  : detrend_mean,
                 'Linear': detrend_linear,
                 }

    _detrend = 'Mean'


    def __init__(self, eegplot, packstart=None, packend=None):    
        gtk.Window.__init__(self)
        Observer.__init__(self)
        self.set_size_request(*self._size)

        self.eegplot = eegplot
        self.eeg = eegplot.get_eeg()
        self.eoi = eegplot.get_eoi()

        self._filterButter = Filter(self)
        self._filter       = FilterBase()   # no filtering
        self._filterGM = self.eegplot.filterGM
        
        vbox = gtk.VBox()
        vbox.show()
        vbox.set_spacing(3)
        self.add(vbox)

        if packstart is not None:
            for w, expand, fill in packstart:
                vbox.pack_start(w, expand, fill)
        self.fig = Figure()
        self.axes = self.fig.add_subplot(111)        
        
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(0,0)
        self.canvas.show()
        vbox.pack_start(self.canvas, True, True)

        if packend is not None:
            for w, expand, fill in packend:
                vbox.pack_start(w, expand, fill)


        self.toolbar = self.make_toolbar()
        self.toolbar.show()
        vbox.pack_end(self.toolbar, False, False)


        self.set_title(self._title)
        self.set_border_width(10)

        def remove(*args):
            Observer.observers.remove(self)        
        self.connect('delete-event', remove)

        self._init()      # last call before make_plot
        self.make_plot()  #last line!
        


    def add_toolbutton(self, icon_name, tip_text, tip_private, clicked_function, clicked_param1=None):
        iconSize = gtk.ICON_SIZE_SMALL_TOOLBAR
        iconw = gtk.Image()
        iconw.set_from_stock(icon_name, iconSize)
        
        toolitem = gtk.ToolButton()
        toolitem.set_icon_widget(iconw)
        toolitem.show_all()
        toolitem.set_tooltip_text(tip_text)
        toolitem.connect("clicked", clicked_function, clicked_param1)
        toolitem.connect("scroll_event", clicked_function)
        self.toolbar.insert(toolitem, -1)

    def make_context_menu(self):
        contextMenu = gtk.Menu()
        contextMenu.set_title('Filters')

        # remove the mean, linear trend, etc
        itemDetrend = gtk.MenuItem('Detrend')
        contextMenu.append(itemDetrend)
        itemDetrend.show()
        menu = gtk.Menu()


        def set_detrend(item, l):
            if item.get_active():
                self._detrend = l
                self.make_plot() 

        group = None
        for l in ('None', 'Mean', 'Linear'):
            item = gtk.RadioMenuItem(label=l)
            if group is None: group = item
            else: item.set_group(group)
            if l==self._detrend:
                item.set_active(True)
            else:
                item.set_active(False)

            item.show()
            item.connect( "toggled", set_detrend, l)
            menu.append(item)
        itemDetrend.set_submenu(menu)


        # remove the mean, linear trend, etc
        itemFilter = gtk.MenuItem('Filter')
        contextMenu.append(itemFilter)
        itemFilter.show()
        menu = gtk.Menu()

        def set_filter(item, l):
            if l=='Butterworth':
                if item.get_active():
                    self._filterButter.make_butter_dialog()
                    self._filter = self._filterButter
                else:
                    self._filter       = FilterBase()  # no filtering

            if l=='Filter GM':
                self._filterGM = item.get_active()
            self.make_plot() 

        for l in ('Filter GM', 'Butterworth'):
            item = gtk.CheckMenuItem(label=l)
            item.show()
            if l=='Filter GM' and self._filterGM:
                item.set_active(True)
            if l=='Butterworth':
                item.set_active(False)
            item.connect( "toggled", set_filter, l)
            menu.append(item)
        itemFilter.set_submenu(menu)
        
        return contextMenu

    def on_move(self, widget, event):
        # get the x and y coords, flip y from top to bottom
        height = self.canvas.figure.bbox.height #no longer necessary for height method to have parens ()
        x, y = event.x, height-event.y
        print "on_move ", x, y

        if self.axes.in_axes(x, y):
            # transData transforms data coords to display coords.  Use the
            # inverse method to transform back
            x,y = self.axes.transData.inverted().transform( (x,y) ) #replaced inverse_xy_tup with inverted().transform

            msg = self.get_msg(x,y)
            #self.update_status_bar(msg)

        return True

    #def update_status_bar(self, msg):
    #    self.statbar.pop(self.statbarCID) 
    #    mid = self.statbar.push(self.statbarCID, msg)

    def recieve(self, event, *args):
        if not self.buttonFollowEvents.get_active(): return
        if event in (Observer.SELECT_CHANNEL, Observer.SET_TIME_LIM):
            self.make_plot()

    def make_toolbar(self):
        
        toolbar = NavigationToolbar(self.canvas, self)

        next = 8

        toolitem = gtk.SeparatorToolItem()
        toolitem.show()
        toolbar.insert(toolitem, next); next+=1
        toolitem.set_expand(False)

        self.buttonFollowEvents = gtk.CheckButton ()
        self.buttonFollowEvents.set_label('Auto')
        self.buttonFollowEvents.show()
        self.buttonFollowEvents.set_active(True)

        toolitem = gtk.ToolItem()
        toolitem.show()
 	
	#Rewriting this for the new gtk tooltips available in pygtk 2.12 and up	
	#toolitem.set_tooltip(
        #   toolbar.tooltips,
        #   'Automatically update in response to selections in EEG', 'Private')
	toolitem.set_tooltip_text('Automatically update in response to selections in EEG')

        toolitem.add(self.buttonFollowEvents)
        toolbar.insert(toolitem, next); next +=1

        # XXX: only available in gtk 2.6
        menu = gtk.MenuToolButton(gtk.STOCK_EDIT)
        menu.show()
        context = self.make_context_menu()
        menu.set_menu(context)

        #menu.set_tooltip(
        #   toolbar.tooltips,
        #   'Set filter/detrend etc', 'Private')
	menu.set_tooltip_text('Set filter/detrend etc')

        toolbar.insert(menu, next); next+=1

        toolitem = gtk.SeparatorToolItem()
        toolitem.show()
        toolbar.insert(toolitem, next)
        toolitem.set_expand(False)


        return toolbar

    def _init(self):
        'last call before make plot'
        pass
    
    def make_plot(self, *args):
        raise NotImplementedError

    def get_msg(self, *args):
        'get the status bar msg'
        return ''

    def get_data(self):
        'return t, data, dt, label, with t filtered according to selections'
        print "MPLWin.get_data(): self._filterGM =", self._filterGM
        selected = self.eegplot.get_selected(self._filterGM)
        if selected is None:
            error_msg('You must first select an EEG channel by clicking on it',
                      parent=self)
            return
        t, data, trode = selected

        print "MPLWin.get_data(): data[0:10] is " , data[0:10]

        print "MPLWin.get_data(): self._detrend=", self._detrend
        detrend = self._detrendd[self._detrend]    

        data = detrend(self._filter(t, data))
        gname, gnum = trode
        label = '%s %d' % (gname, gnum)

        dt = t[1]-t[0]
        return t, data, dt, label
Esempio n. 47
0
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
Esempio n. 48
0
class Plotpar():
    def __init__(self, context, f_function, g_function):
        self.context = context
        self.f_function = f_function
        self.g_function = g_function

        self.fig = Figure(figsize=(6, 4))  # create fig
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(600, 600)  # set min size
        self.markers = [
            '.', ',', '+', 'x', '|', '_', 'o', 'v', '^', '<', '>', '8', 's',
            'p', '*', 'h', 'H', 'D', 'd'
        ]
        self.colors = [
            'black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow',
            'purple', 'white'
        ]
        self.pstyle = [
            'bmh', 's', '6', 'red', '0.8', 'black', '2', 'black', '0.3', '',
            '25', '', '', '20', '15', '', '', '20', '15'
        ]

        self.styledict = {}
        self.styledict["style"] = 'bmh'
        self.styledict["point_style"] = 's'
        self.styledict["point_size"] = '6'
        self.styledict["point_color"] = 'red'
        self.styledict["point_alpha"] = '0.8'
        self.styledict["line_color"] = 'black'
        self.styledict["line_width"] = '2'
        self.styledict["band_color"] = 'black'
        self.styledict["band_alpha"] = '0.3'
        self.styledict["title_size"] = '8'
        self.styledict["xtitle_size"] = '8'
        self.styledict["xlabel_size"] = '8'
        self.styledict["ytitle_size"] = '8'
        self.styledict["ylabel_size"] = '8'

        self.nselec = [1, 12, 5, 3, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1]
        self.plot_labels = ["", "x", "f(x)", "", "g(x)"]

        toolbar = NavigationToolbar(self.canvas, self)
        toolbarbox = gtk.HBox()
        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR)
        options_button = gtk.Button()
        options_button.add(image)
        image2 = gtk.Image()
        image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR)
        refresh_button = gtk.Button()
        refresh_button.add(image2)
        toolbarbox.pack_start(toolbar, True, True)
        toolbarbox.pack_end(options_button, False, True)
        toolbarbox.pack_end(refresh_button, False, True)
        self.vbox = gtk.VBox()
        self.vbox.pack_start(toolbarbox, False, False)
        self.vbox.pack_start(self.canvas, True, True)

        self.x1 = -0.1
        self.x2 = 20.1

        # signals
        options_button.connect('clicked', self.mpl_options)
        refresh_button.connect('clicked', self.on_refresh_clicked)

    def mpl_options(self, button):
        """Create GTKDialog containing options for plotting and connect signals."""
        mpl_options_dialog = MPLOptions(self.context, self)

    def on_refresh_clicked(self, button):
        """Refresh canvas - plot everything again"""
        self.plotting()

    def plotvline(self, **kwargs):
        self.ax1.axvline(**kwargs)

    def plothline(self, **kwargs):
        self.ax1.axhline(**kwargs)

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

    def plotting(self):
        """Generating matplotlib canvas"""

        plt.style.use(self.pstyle[0])

        f_kwargs = {
            'color': 'black',
            'fmt': 's',
            'ecolor': 'black',
            'elinewidth': 1.5,
            'capsize': 4.5,
            'capthick': 1.0,
            'markersize': 10
        }

        g_kwargs = {
            'color': 'red',
            'fmt': 's',
            'ecolor': 'red',
            'elinewidth': 1.5,
            'capsize': 4.5,
            'capthick': 1.0,
            'markersize': 10
        }

        if self.f_function.mode == "quadratic" or self.g_function.mode == "quadratic":

            self.ax1 = self.fig.add_subplot(131)
            self.ax1.clear()
            self.ax2 = self.fig.add_subplot(132)
            self.ax2.clear()
            self.ax3 = self.fig.add_subplot(133)
            self.ax3.clear()

            if self.f_function.mode == "quadratic":
                fc = self.f_function.params[2]
                fa = self.f_function.params[1]
                fb = self.f_function.params[0]
                sfc = self.f_function.std_err[2]
                sfa = self.f_function.std_err[1]
                sfb = self.f_function.std_err[0]
            else:
                fc = self.f_function.params[1]
                fa = self.f_function.params[0]
                fb = 0.0
                sfc = self.f_function.std_err[1]
                sfa = self.f_function.std_err[0]
                sfb = 0.0

            if self.g_function.mode == "quadratic":
                gc = self.g_function.params[2]
                ga = self.g_function.params[1]
                gb = self.g_function.params[0]
                sgc = self.g_function.std_err[2]
                sga = self.g_function.std_err[1]
                sgb = self.g_function.std_err[0]
            else:
                gc = self.g_function.params[1]
                ga = self.g_function.params[0]
                gb = 0.0
                sgc = self.g_function.std_err[1]
                sga = self.g_function.std_err[0]
                sgb = 0.0

            fx = [0]
            fy = [fc]
            fe = [sfc]
            self.ax1.errorbar(fx, fy, fe, **f_kwargs)
            gx = [1]
            gy = [gc]
            ge = [sgc]
            self.ax1.errorbar(gx, gy, ge, **g_kwargs)

            fx = [0]
            fy = [fa]
            fe = [sfa]
            self.ax2.errorbar(fx, fy, fe, **f_kwargs)
            gx = [1]
            gy = [ga]
            ge = [sga]
            self.ax2.errorbar(gx, gy, ge, **g_kwargs)

            fx = [0]
            fy = [fb]
            fe = [sfb]
            self.ax3.errorbar(fx, fy, fe, **f_kwargs)
            gx = [1]
            gy = [gb]
            ge = [sgb]
            self.ax3.errorbar(gx, gy, ge, **g_kwargs)

            plt.setp([self.ax1, self.ax2, self.ax3],
                     xticks=[it for it in range(2)],
                     xticklabels=['f', 'g'])

            self.ax1.set_xlim([-0.5, 1.5])
            self.ax2.set_xlim([-0.5, 1.5])
            self.ax3.set_xlim([-0.5, 1.5])

        elif self.f_function.mode == "linear" and self.g_function.mode == "linear":

            self.ax1 = self.fig.add_subplot(121)
            self.ax1.clear()
            self.ax2 = self.fig.add_subplot(122)
            self.ax2.clear()

            fc = self.f_function.params[1]
            fa = self.f_function.params[0]
            sfc = self.f_function.std_err[1]
            sfa = self.f_function.std_err[0]

            gc = self.g_function.params[1]
            ga = self.g_function.params[0]
            sgc = self.g_function.std_err[1]
            sga = self.g_function.std_err[0]

            fx = [0]
            fy = [fc]
            fe = [sfc]
            self.ax1.errorbar(fx, fy, fe, **f_kwargs)
            gx = [1]
            gy = [gc]
            ge = [sgc]
            self.ax1.errorbar(gx, gy, ge, **g_kwargs)

            fx = [0]
            fy = [fa]
            fe = [sfa]
            self.ax2.errorbar(fx, fy, fe, **f_kwargs)
            gx = [1]
            gy = [ga]
            ge = [sga]
            self.ax2.errorbar(fx, fy, fe, **g_kwargs)

            plt.setp([self.ax1, self.ax2, self.ax3],
                     xticks=[it for it in range(2)],
                     xticklabels=['f', 'g'])

            self.ax1.set_xlim([-0.5, 1.5])
            self.ax2.set_xlim([-0.5, 1.5])

        self.fig.subplots_adjust(left=0.07,
                                 right=0.97,
                                 top=0.94,
                                 bottom=0.1,
                                 wspace=0.30)
        self.canvas.draw()
Esempio n. 49
0
File: gui.py Progetto: sriveravi/som
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()

    def Draw_figure(self):
  	self.axes.cla()   # Clear axis
	cols = self.columns[self.combobox.get_active()]
	data = self.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

	# use different colors and markers for each label
	markers = ['o','s','D', '+']
	colors = ['r','g','b', 'y']
	for cnt,xx in enumerate(data):
	  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)
	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,20)


      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])):
	  #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 =  #  ['stimuli.csv']

      allFileName = '4750.csv' #'stimuli.csv'	
      self.file_name =  allFileName  #'4749.csv' # 'stimuli.csv' # file_names[0]
      self.test_file_name = allFileName #'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]

      
      #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

      self.target = np.genfromtxt(self.file_name,delimiter=',',usecols=(9),dtype=str,skip_header=1) # loading the labels for use in the figure
      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)
      self.pattern_labels = np.genfromtxt(self.file_name, delimiter=',',usecols=(self.visual_and_acoustic), dtype=str)[0]


      #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()
Esempio n. 50
0
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()
Esempio n. 51
0
    def __init__(self, data=None, orient="LPS", overlay=None, colormap=cm.gray, pixdim=None):

        ##
        import sys

        print sys.argv
        if data == None:
            try:
                fn = sys.argv[1]
                from mri import img

                data = img.read(fn)
            except AttributeError:
                print "not passing data arg"
                pass

        try:
            data.qform
            print "think its a nifti volume"
            nim = data
            mrdata = nim.data
            print shape(mrdata)
            pixdim = nim.voxdim[::-1]

        except AttributeError:
            if pixdim != None:
                print "using user supplied pixeldimensions", pixdim
            else:
                print "probably not a nifti volume. using voxel units instead of actual distance units"
                pixdim = [1.0, 1.0, 1.0]
                # unitless
            mrdata = data
        ##

        self.win = gtk.Window()
        # win.connect("destroy", lambda x: gtk.main_quit())
        self.win.connect("delete-event", self.hideinsteadofdelete)
        self.win.set_default_size(600, 600)
        self.win.set_title("Embedding in GTK")

        vbox = gtk.VBox()
        self.win.add(vbox)

        fig = figure()  # figsize=(5,4), dpi=100)
        # subplots_adjust(left=.15, bottom=.15,right=1, top=.95,wspace=.25, hspace=.35)
        # a = fig.add_subplot(111)
        # t = arange(0.0,3.0,0.01)
        # s = sin(2*pi*t)
        # a.plot(t,s)
        # a.plot(data)

        ax1 = fig.add_subplot(221)
        # axis('off')
        # colorbar(fig,ax=ax1)
        xlabel("Anterior (A->P 1st Dim)")
        ylabel("Right (R->L 2nd Dim)")
        ax2 = fig.add_subplot(222)
        # axis('off')
        xlabel("Inferior (I->S Dim)")
        ylabel("Anterior (A->P 1st Dim)")
        ax3 = fig.add_subplot(223)
        # axis('off')
        xlabel("Infererior (I->S 3rd dim)")
        ylabel("Right (R->L 2nd Dim)")
        coord = fig.add_subplot(224)
        axis("off")
        tracker = IndexTracker(mrdata, ax1, ax2, ax3, colormap, pixdim, overlay, coord)
        # fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
        cid = connect("button_press_event", tracker.click)

        print ("something")

        sw = gtk.ScrolledWindow()
        vbox.pack_start(sw)
        # self.win.add (sw)
        ## A scrolled window border goes outside the scrollbars and viewport
        sw.set_border_width(10)
        # policy: ALWAYS, AUTOMATIC, NEVER
        sw.set_policy(hscrollbar_policy=gtk.POLICY_AUTOMATIC, vscrollbar_policy=gtk.POLICY_ALWAYS)

        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        ##vbox.pack_start(canvas)
        canvas.set_size_request(300, 200)
        sw.add_with_viewport(canvas)
        canvas.draw()

        # manager = get_current_fig_manager()
        ## you can also access the window or vbox attributes this way
        # toolbar = manager.toolbar

        ##vbox.pack_start(canvas)
        # toolbar = NavigationToolbar(canvas, self.win)
        ##vbox.pack_start(toolbar, False, False)
        # show()
        # print tracker
        #
        # fig.show()
        self.win.show_all()
Esempio n. 52
0
class DataManager(gtk.Window):

        # global variables needed to share among classes
	global labels

        ###########################################################################################
	def __init__(self):
                # init gtk::Window
		gtk.Window.__init__(self)
		self.set_default_size(600, 800)
		self.connect('destroy', lambda win: gtk.main_quit())

		self.set_title('DOSEMATIC v0.1')

                # variable name -- TODO
		self.xvariable="Dose"
		self.xvar="D"
		self.xunits="Gy"
		self.yvariable="Yield"
		self.yvar="Y"
		self.yunits=""

                # main layout container
		main_eb = gtk.EventBox()

                # horizontal box
		hbox = gtk.HBox(False, 8)
                # vertical box
		VBOX = gtk.VBox(False, 0)

		main_eb.add(VBOX)
		#main_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(red=60000,green=60000,blue=60000))
		self.add(main_eb)
		vbox1 = gtk.VBox(False,8)
		hbox.pack_start(vbox1, True, True)

		top_band = gtk.HBox()
		bottom_band = gtk.HBox()
		top_eb = gtk.EventBox()
		bottom_eb = gtk.EventBox()
		top_eb.add(top_band)
		bottom_eb.add(bottom_band)
		top_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
		bottom_eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
		l1 = gtk.Label('DOSEMATIC v1.0 --- beta testing --- module 1, basic view')
		l2 = gtk.Label('author: Maciej Lewicki                                       [email protected],   [email protected]')
		top_band.add(l1)
		bottom_band.add(l2)
		hruler = gtk.HSeparator()
		hruler2 = gtk.HSeparator()
		VBOX.pack_start(top_eb,False,False)
		VBOX.pack_start(hruler,False,True,5)
		VBOX.pack_start(hbox,True,True)
		VBOX.pack_start(hruler2,False,True,5)
		VBOX.pack_end(bottom_eb,False,False)

		# TEXT SCREEN______________________________________________________
		self.text = gtk.TextView()				# TEXT VIEW
		self.text.set_wrap_mode(gtk.WRAP_WORD)		# wrap words
		self.scroll_text = gtk.ScrolledWindow()		# into scrollable env
		self.scroll_text.set_shadow_type(gtk.SHADOW_ETCHED_IN)
		self.scroll_text.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
		self.scroll_text.add(self.text)
		text_view_box = gtk.VBox(False,5)
		text_view_box.pack_start(self.scroll_text,True,True)
		#__________________________________________________________________

		# ESTIMATOR________________________________________________________
		estimator_box = gtk.HBox(False,5)
		self.estxt = gtk.TextView()
		self.estxt.set_wrap_mode(gtk.WRAP_WORD)
		self.scroll_estxt = gtk.ScrolledWindow()
		self.scroll_estxt.set_shadow_type(gtk.SHADOW_ETCHED_IN)
		self.scroll_estxt.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
		self.scroll_estxt.add(self.estxt)
		label = gtk.Label(self.yvariable+' = ')
		entry = gtk.Entry()
		entry.set_text("0.00")
		button = gtk.Button('Estimate '+self.xvariable)
		button.connect('clicked',self.y_estimate,entry)
		combo = gtk.combo_box_new_text()
		combo.append_text("Method A")
		combo.append_text("Method B")
		combo.append_text("Method C-original")
		combo.append_text("Method C-simplified")
		self.method="Method C-simplified"
		combo.set_active(3)
		combo.connect('changed', self.on_method_changed)
		ruler = gtk.HSeparator()
		grid = gtk.Table(2,4)
		grid.attach(label, 0,1,0,1)
		grid.attach(entry, 1,2,0,1)
		grid.attach(button, 0,2,1,2)
		grid.attach(ruler,0,2,2,3)
		grid.attach(combo,0,2,3,4)
		estimator_box.pack_start(grid,False,False)
		estimator_box.pack_start(self.scroll_estxt,True,True)
		#__________________________________________________________________

		# FUNCTION TAB_____________________________________________________
		function_box = gtk.HBox(False,5)
		self.ftxt = gtk.TextView()
		self.ftxt.set_wrap_mode(gtk.WRAP_WORD)
		self.scroll_ftxt = gtk.ScrolledWindow()
		self.scroll_ftxt.set_shadow_type(gtk.SHADOW_ETCHED_IN)
		self.scroll_ftxt.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
		self.scroll_ftxt.add(self.ftxt)
		label_Y = gtk.Label()
		label_Y.set_use_markup(True)
		label_Y.set_markup('Y = c + &#945;D + &#946;D<sup>2</sup>') 
		self.entry_c = gtk.Entry()
		self.entry_c.set_width_chars(5)
		label_c = gtk.Label('c: ')
		self.entry_alpha = gtk.Entry()
		self.entry_alpha.set_width_chars(5)
		label_alpha = gtk.Label()
		label_alpha.set_use_markup(True)
		label_alpha.set_markup('&#945;: ') 
		self.entry_beta = gtk.Entry()
		self.entry_beta.set_width_chars(5)
		label_beta = gtk.Label()
		label_beta.set_use_markup(True)
		label_beta.set_markup('&#946;: ') 
		self.entry_sc = gtk.Entry()
		self.entry_sc.set_width_chars(5)
		label_sc = gtk.Label()
		label_sc.set_use_markup(True)
		label_sc.set_markup('&#963;(c): ') 
		self.entry_salpha = gtk.Entry()
		self.entry_salpha.set_width_chars(5)
		label_salpha = gtk.Label()
		label_salpha.set_use_markup(True)
		label_salpha.set_markup('&#963;(&#945;): ') 
		self.entry_sbeta = gtk.Entry()
		self.entry_sbeta.set_width_chars(5)
		label_sbeta = gtk.Label()
		label_sbeta.set_use_markup(True)
		label_sbeta.set_markup('&#963;(&#946;): ') 
		table_f = gtk.Table(6,3)
		#table_f.attach(label_Y, False, False)
		table_f.attach(label_c,0,1,0,1)
		table_f.attach(self.entry_c,1,2,0,1)
		table_f.attach(label_alpha,0,1,1,2)
		table_f.attach(self.entry_alpha,1,2,1,2)
		table_f.attach(label_beta,0,1,2,3)
		table_f.attach(self.entry_beta,1,2,2,3)
		table_f.attach(label_sc,4,5,0,1)
		table_f.attach(self.entry_sc,5,6,0,1)
		table_f.attach(label_salpha,4,5,1,2)
		table_f.attach(self.entry_salpha,5,6,1,2)
		table_f.attach(label_sbeta,4,5,2,3)
		table_f.attach(self.entry_sbeta,5,6,2,3)
		vruler = gtk.VSeparator()
		table_f.attach(vruler,3,4,0,3,xpadding=10)
		check_function = gtk.CheckButton("Plot function")
		check_points = gtk.CheckButton("Plot data points")
		check_err = gtk.CheckButton("Plot uncertainty band")
		check_ci_curve = gtk.CheckButton("Plot CI95% band (curve)")
		check_ci_points = gtk.CheckButton("Plot CI95% band (points)")
		check_function.set_active(True)
		check_points.set_active(True)
		check_err.set_active(True)
		check_ci_curve.set_active(True)
		check_ci_points.set_active(True)
		vbox_checks = gtk.VBox(False, 5)
		vbox_checks.pack_start(check_function, False, False)
		vbox_checks.pack_start(check_points, False, False)
		vbox_checks.pack_start(check_err, False, False)
		vbox_checks.pack_start(check_ci_curve, False, False)
		vbox_checks.pack_start(check_ci_points, False, False)
		check_function.connect('toggled',self.on_toggled, 'function')
		check_points.connect('toggled',self.on_toggled, 'points')
		check_err.connect('toggled',self.on_toggled, 'err')
		check_ci_curve.connect('toggled',self.on_toggled, 'ci_curve')
		check_ci_points.connect('toggled',self.on_toggled, 'ci_points')
		hbox_buttons = gtk.HBox(True,5)
		button_save_f = gtk.Button("Save Funtion")
		button_load_f = gtk.Button("Load Funtion")
		hbox_buttons.pack_start(button_save_f,True,True)
		hbox_buttons.pack_start(button_load_f,True,True)
		button_save_f.connect('clicked',self.save_function)
		button_load_f.connect('clicked',self.load_function)
		left_box = gtk.VBox(False,5)
		ruler_f1 = gtk.HSeparator()
		ruler_f2 = gtk.HSeparator()
		left_box.pack_start(label_Y, False, False)
		left_box.pack_start(table_f, False, False)
		left_box.pack_start(ruler_f1, False, True, 5)
		left_box.pack_start(vbox_checks, False, False)
		left_box.pack_start(ruler_f2, False, True, 5)
		left_box.pack_start(hbox_buttons, False, True)
		function_box.pack_start(left_box, False, False)
		function_box.pack_start(self.scroll_ftxt, True, True)
		#__________________________________________________________________

		# NOTEBOOK WRAP____________________________________________________
		self.notebook = gtk.Notebook()
		self.notebook.append_page(text_view_box, gtk.Label('Log console'))
		self.notebook.append_page(estimator_box, gtk.Label('Estimator'))
		self.notebook.append_page(function_box, gtk.Label('Calibration function'))
		vbox1.pack_end(self.notebook,True,True)
		#__________________________________________________________________

		# MAT-PLOT-LIB_____________________________________________________
		self.fig = Figure(figsize=(6, 4))		# create fig
		self.canvas = FigureCanvas(self.fig)		# a gtk.DrawingArea
		self.canvas.set_size_request(600,400)		# set min size
		self.markers = ['.',',','+','x','|','_','o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd']
		self.colors = ['black','blue','green','red','cyan','magenta','yellow','purple','white']
		self.pstyle = ['bmh','s','6','red','0.8','black','2','black','0.3','','25','','','20','15','','','20','15']

		self.styledict = {}
		self.styledict["style"]='bmh'
		self.styledict["point_style"]='s'
		self.styledict["point_size"]='6'
		self.styledict["point_color"]='red'
		self.styledict["point_alpha"]='0.8'
		self.styledict["line_color"]='black'
		self.styledict["line_width"]='2'
		self.styledict["band_color"]='black'
		self.styledict["band_alpha"]='0.3'
		self.styledict["title_size"]='25'
		self.styledict["xtitle_size"]='20'
		self.styledict["xlabel_size"]='15'
		self.styledict["ytitle_size"]='20'
		self.styledict["ylabel_size"]='15'

		self.nselec = [1,12,5,3,-1,0,-1,0,-1,-1,-1,-1,-1,-1]
		self.plot_labels = ["Foci per cell vs Dose", "Dose", "Foci per cell", " [Gy]", " []"]
		#print plt.style.available
		self.mode='quadratic'
		self.function = None
		if self.mode=='linear' :
			self.function = self.linear
		elif self.mode=='quadratic' :
			self.function = self.quadratic
		self.fit_toggle='active'
		self.points_toggle=1
		self.function_toggle=1
		self.err_toggle=1
		self.ci_func_toggle=1
		self.ci_points_toggle=1
		self.plotting()					# --- CORE plotting function ---
		toolbar = NavigationToolbar(self.canvas, self)
		toolbarbox = gtk.HBox()
		image = gtk.Image()
		image.set_from_stock(gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_LARGE_TOOLBAR)
		options_button = gtk.Button()
		options_button.add(image)
		options_button.connect('clicked',self.mpl_options)
		image2 = gtk.Image()
		image2.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_LARGE_TOOLBAR)
		refresh_button = gtk.Button()
		refresh_button.add(image2)
		refresh_button.connect('clicked',self.on_refresh_clicked)
		toolbarbox.pack_start(toolbar, True, True)
		toolbarbox.pack_end(options_button, False, True)
		toolbarbox.pack_end(refresh_button, False, True)
		vbox1.pack_start(toolbarbox, False, False)
		vbox1.pack_start(self.canvas, True, True)	# into box layout
		#__________________________________________________________________

		
	def plotting(self):
		plt.style.use(self.pstyle[0])

		self.ax1 = self.fig.add_subplot(111)
		self.ax1.clear()

		self.ax1.set_title(self.plot_labels[0], fontsize=self.pstyle[10])
		self.ax1.set_xlabel(self.plot_labels[1]+self.plot_labels[3], fontsize=int(self.pstyle[13]))
		self.ax1.set_ylabel(self.plot_labels[2]+self.plot_labels[4], fontsize=int(self.pstyle[17]))
		self.ax1.tick_params(axis='x', which='both', labelsize=int(self.pstyle[14]))
		self.ax1.tick_params(axis='y', which='both', labelsize=int(self.pstyle[18]))

		x = np.arange(-0.1, max(20,200)*1.1, 0.05)

                xdata=array([100,110,120,130,140,150,160,170,180,190,1000]);
                ydata=array([100,110,120,130,140,130,160,170,180,190,1000]);

		if (self.fit_toggle=='active'):
			self.params, self.rmse, self.p_value, self.std_err, self.dof, self.rss, self.cov_mtx = self.fit_function(xdata,ydata)
			self.function_changed()

		if self.function_toggle==1:
			y = self.function(x,self.params)
			self.ax1.plot(x,y, color=self.pstyle[5], marker='.', linestyle='None', markersize=float(self.pstyle[6]))

		if self.ci_func_toggle==1 and self.fit_toggle=='active':
			conf = self.confidence(x,xdata,len(x),np.mean(xdata),self.dof,self.rmse)
			upper =  self.function(x,self.params) + conf
			lower =  self.function(x,self.params) - conf
			self.ax1.fill_between(x, lower, upper, facecolor=self.pstyle[7], alpha=float(self.pstyle[8]))

		if self.ci_points_toggle==1:
			upper =  self.function(x,self.params) + self.confidence_points(x,self.std_err)
			lower =  self.function(x,self.params) - self.confidence_points(x,self.std_err)
			self.ax1.fill_between(x, lower, upper, facecolor='blue', alpha=float(self.pstyle[8]))

		if self.err_toggle==1:
			upper =  self.function(x,self.params) + self.uncertainty(x,self.std_err)
			lower =  self.function(x,self.params) - self.uncertainty(x,self.std_err)
			self.ax1.fill_between(x, lower, upper, facecolor='green', alpha=float(self.pstyle[8]))

		self.canvas.draw()

	def on_refresh_clicked(self,button) :
		self.plotting()

	def log(self,txt):
		end_iter = self.text.get_buffer().get_end_iter()
		self.text.get_buffer().insert(end_iter, txt+'\n')
		adj = self.scroll_text.get_vadjustment()
		adj.set_value( adj.upper - adj.page_size )
		self.notebook.set_current_page(0)

	def loges(self,txt):
		end_iter = self.estxt.get_buffer().get_end_iter()
		self.estxt.get_buffer().insert(end_iter, txt+'\n')
		adj = self.scroll_estxt.get_vadjustment()
		adj.set_value( adj.upper - adj.page_size )
		self.notebook.set_current_page(1)

	def logf(self,txt):
		end_iter = self.ftxt.get_buffer().get_end_iter()
		self.ftxt.get_buffer().insert(end_iter, txt+'\n')
		adj = self.scroll_ftxt.get_vadjustment()
		adj.set_value( adj.upper - adj.page_size )
		self.notebook.set_current_page(2)

	def linear(self, x, params):
		return params[0]*x + params[1]

	def quadratic(self, x, params):
		return params[0]*x*x + params[1]*x + params[2]

	def fit_linear(self, x, a, b):
		return a*x + b

	def fit_quadratic(self, x, a, b, c):
		return a*x*x + b*x + c

	def confidence(self, x, xdata, n, mean_x, dof, RMSE):
		alpha=0.05
		t = stats.t.isf(alpha/2., df=dof)
		#conf = t * np.sqrt((RSS/(n-2))*(1.0/n + ( (x-mean_x)**2 / ((np.sum(x**2)) - n*(mean_x**2)))))
		Sxx = np.sum(xdata**2) - np.sum(xdata)**2/n
		se_a = RMSE / np.sqrt(Sxx)
		se_b = RMSE * np.sqrt(np.sum(xdata**2)/(n*Sxx))
		
		conf = t * RMSE * np.sqrt(  1./n + (x-mean_x)**2/Sxx)
		#pred = t * RMSE * np.sqrt(1+1./n + (x-mean_x)**2/Sxx)
		return conf

	def uncertainty(self, x, std_err) :
		return std_err[2] + x*std_err[1] + x*x*std_err[0]

	def confidence_points(self, x, std_err) :
		return 1.96*self.uncertainty(x, std_err)

	def fit_function(self,x,y):
		# fit the model
		if self.mode=='linear' :
			popt, pcov = curve_fit(self.fit_linear, x, y)
		elif self.mode=='quadratic' :
			popt, pcov = curve_fit(self.fit_quadratic, x, y)
		# parameters standard error
		std_err = np.sqrt(np.diag(pcov))
		# degrees of freedom
		ndata = len(y)
		npar = len(popt)
		dof = max(0, ndata - npar)
		# root mean squared error
		residuals = y - self.function(x,popt)
		RSS = sum(residuals**2)
		MSE = RSS/dof
		RMSE = np.sqrt(MSE)
		# t-value
		t_value = popt/std_err
		# p-value P(>|t|)
		p_value=(1 - stats.t.cdf( abs(t_value), dof))*2

		return popt, RMSE, p_value, std_err, dof, RSS, pcov

	def function_changed(self):
		if self.mode=='quadratic' :
			self.entry_c.set_text('%.3f' % self.params[2])
			self.entry_alpha.set_text('%.3f' % self.params[1])
			self.entry_beta.set_text('%.3f' % self.params[0])
			self.entry_sc.set_text('%.3f' % self.std_err[2])
			self.entry_salpha.set_text('%.3f' % self.std_err[1])
			self.entry_sbeta.set_text('%.3f' % self.std_err[0])

			self.logf("params:\t[beta\talpha\tc ]")
			self.logf("values\t\t" + str(self.params))
			self.logf("std_err\t" + str(self.std_err))
			self.logf("p-value\t" + str(self.p_value))
			self.logf("RSS\t" + str(self.rss))
			self.logf("RMSE\t" + str(self.rmse))
			self.logf("---------------------------------------------------------------------------")

	def y_estimate(self, button, entry):
		if not isfloat(entry.get_text()):
			self.loges("___Not a number!___")
			return
		Y = float(entry.get_text())
		plist = self.get_fit_params()
		u = uncer.UCER(Y=Y,par_list=plist)
		D = u.D
		if self.method=="Method A":
			DL, DU = u.method_a()
		elif self.method=="Method B":
			DL, DU = u.method_b()
		elif self.method=="Method C-original":
			DL, DU = u.method_c1()
		elif self.method=="Method C-simplified":
			DL, DU = u.method_c2()

		xlab=self.xvar
		ylab=self.yvar
		self.loges( xlab + " estimation for   " + ylab + " = " + str(Y) + " using " + self.method + ":")
		self.loges( "D = " + str(D) + ";   DL = " + str(DL) + ";   DU = " + str(DU))
		self.loges("-----------------------------------------------------------------")

		self.ax1.axhline(y=Y,linewidth=1,linestyle='-',color='red')
		self.ax1.axvline(x=D,linewidth=1,linestyle='-',color='blue')
		self.ax1.axvline(x=DL,linewidth=1,linestyle='--',color='green')
		self.ax1.axvline(x=DU,linewidth=1,linestyle='--',color='green')
		self.canvas.draw()

	def mpl_options(self,button) :
		dialog = gtk.Dialog("My Dialog",self,0,(gtk.STOCK_OK, gtk.RESPONSE_OK))
		box = dialog.get_content_area()
		table = gtk.Table(2,18)
		table.set_row_spacings(5)
		table.set_col_spacings(5)
		l=[]
		l.append(gtk.Label("Canvas Style"))
		l.append(gtk.Label("Marker Style"))
		l.append(gtk.Label("Marker Size"))
		l.append(gtk.Label("Marker Color"))
		l.append(gtk.Label("Marker Alpha"))
		l.append(gtk.Label("Line Color"))
		l.append(gtk.Label("Line Width"))
		l.append(gtk.Label("CI Band Color"))
		l.append(gtk.Label("CI Band Alpha"))
		l.append(gtk.Label("Title"))
		l.append(gtk.Label("Title size"))
		l.append(gtk.Label("X-axis title"))
		l.append(gtk.Label("X-axis unit"))
		l.append(gtk.Label("X-axis title size"))
		l.append(gtk.Label("X-axis labels size"))
		l.append(gtk.Label("Y-axis title"))
		l.append(gtk.Label("Y-axis unit"))
		l.append(gtk.Label("Y-axis title size"))
		l.append(gtk.Label("Y-axis labels size"))
		hbox=[]
		hlines=[]
		for i in range(0,len(l)) :
			l[i].set_alignment(xalign=0,yalign=0.5) 
			hbox.append(gtk.HBox(False,5))
			hlines.append(gtk.HSeparator())
			table.attach(l[i],0,1,2*i,2*i+1)
			table.attach(hbox[i],1,2,2*i,2*i+1)
			table.attach(hlines[i],0,2,2*i+1,2*i+2)
		
		combo_cs = self.create_combobox(plt.style.available,hbox,0)
		combo_mst = self.create_combobox(self.markers,hbox,1)
		spin_msz = self.create_spinbutton(hbox,float(self.pstyle[2]), 1.0,20.0,1.0,2, 2)
		combo_mc = self.create_combobox(self.colors,hbox,3)
		spin_ma = self.create_spinbutton(hbox,float(self.pstyle[4]), 0.0,1.0,0.05,2, 4)
		combo_lc = self.create_combobox(self.colors,hbox,5)
		spin_lw = self.create_spinbutton(hbox,float(self.pstyle[6]), 0.0,10.0,0.5,2, 6)
		combo_bc = self.create_combobox(self.colors,hbox,7)
		spin_ba = self.create_spinbutton(hbox,float(self.pstyle[8]), 0.0,1.0,0.05,2, 8)

		entry_title = self.create_entry(hbox,0, 9)
		entry_xaxis = self.create_entry(hbox,1, 11)
		entry_xunit = self.create_entry(hbox,3, 12)
		entry_yaxis = self.create_entry(hbox,2, 15)
		entry_yunit = self.create_entry(hbox,4, 16)

		spin_title_size = self.create_spinbutton(hbox,float(self.pstyle[10]), 10.0,40.0,1.0,1 , 10)
		spin_xtile_size = self.create_spinbutton(hbox,float(self.pstyle[13]), 10.0,40.0,1.0,1 , 13)
		spin_xlabels_size = self.create_spinbutton(hbox,float(self.pstyle[14]), 10.0,40.0,1.0,1 , 14)
		spin_ytile_size = self.create_spinbutton(hbox,float(self.pstyle[17]), 10.0,40.0,1.0,1 , 17)
		spin_ylabels_size = self.create_spinbutton(hbox,float(self.pstyle[18]), 10.0,40.0,1.0,1 , 18)

		box.add(table)
		dialog.show_all()
		response = dialog.run()
		if response == gtk.RESPONSE_OK :
			dialog.destroy()
		else :
			dialog.destroy()

	def create_combobox(self,slist,whereto,n) :
		combo = gtk.combo_box_new_text()
		whereto[n].pack_start(combo)
		for style in slist :
			combo.append_text(str(style))
		combo.set_active(self.nselec[n])
		combo.connect('changed', self.on_combo_changed, n)

	def create_spinbutton(self,whereto,val,mini,maxi,step,digits,n) :
		adj = gtk.Adjustment(val,mini,maxi,step,0.5,0.0)
		spin = gtk.SpinButton(adj,step,digits)
		whereto[n].pack_start(spin)
		spin.connect('changed',self.on_spin_changed,n)

	def create_entry(self,whereto,m,n) :
		entry_title = gtk.Entry()
		entry_title.set_text(self.plot_labels[m])
		whereto[n].pack_start(entry_title)
		entry_title.connect("activate",self.on_entry_changed,m)

	def on_combo_changed(self,cb,n):
		model = cb.get_model()
		index = cb.get_active()
		cb.set_active(index)
		self.pstyle[n] = model[index][0]
		self.nselec[n]=index
		self.plotting()

	def on_spin_changed(self,spin,n) :
		self.pstyle[n] = spin.get_value()
		self.plotting()

	def on_entry_changed(self,entry,n) :
		self.plot_labels[n] = entry.get_text()
		self.plotting()

	def on_toggled(self,button,s) :
		if(s=='ci_points'): self.ci_points_toggle*=-1
		elif(s=='ci_curve'): self.ci_func_toggle*=-1
		elif(s=='function'): self.function_toggle*=-1
		elif(s=='points'): self.points_toggle*=-1
		elif(s=='err'): self.err_toggle*=-1
		self.plotting()

	def save_function(self,button) : 

		file_chooser = gtk.FileChooserDialog("Open...", self, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
		response = file_chooser.run()
		path=''
		if response == gtk.RESPONSE_OK :
			path = file_chooser.get_filename()
			self.logf('Curve saved in file:   ' + path)
			self.logf("---------------------------------------------------------------------------")
			if ".csv" not in path:
				path = path + '.csv'
			file_chooser.destroy()

			ofile = open(path,"wb")
			writer = csv.writer(ofile, delimiter=',')
			writer.writerow(self.params)
			writer.writerow(self.std_err)
			writer.writerow(self.p_value)
			writer.writerow(self.cov_mtx[0])
			writer.writerow(self.cov_mtx[1])
			writer.writerow(self.cov_mtx[2])
			writer.writerow((self.rss, self.rmse, 0.0))
			ofile.close()
		else :
			file_chooser.destroy()

	def get_fit_params(self):
		l=[self.params,self.std_err,self.p_value,self.cov_mtx[0],self.cov_mtx[1],self.cov_mtx[2],[self.rss,self.rmse,0.0]]
		return l

	def load_function(self,button) : 
		file_chooser = gtk.FileChooserDialog("Open...", self, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
		response = file_chooser.run()
		path=''
		if response == gtk.RESPONSE_OK :
			path = file_chooser.get_filename()
			self.logf('Loaded curve from file:   ' + path)
			self.logf("---------------------------------------------------------------------------")
			f = open(path, 'rt')
			try:
				reader = csv.reader(f)
				l=list(reader)
				print l
				self.params=[float(i) for i in l[0]]
				self.std_err=[float(i) for i in l[1]]
				self.p_value=[float(i) for i in l[2]]
				self.cov_mtx=[[float(i) for i in l[3]],[float(i) for i in l[4]],[float(i) for i in l[5]]]
				self.rss=float(l[6][0])
				self.rmse=float(l[6][1])
				self.function_changed()
				self.fit_toggle='inactive'
				self.points_toggle=False
				self.plotting()
			finally:
				f.close()
			#self.plotting()
			file_chooser.destroy()
		else : 
			file_chooser.destroy()

	def on_method_changed(self,cb):
		model = cb.get_model()
		index = cb.get_active()
		cb.set_active(index)
		self.method = model[index][0]
Esempio n. 53
0
class realTimeVisualisation(gtk.Window):

    def __init__(self,networkVariables):
        '''

        '''
        super(realTimeVisualisation,self).__init__()

        self.set_size_request(640,690)
        self.set_position(gtk.WIN_POS_CENTER)
        self.connect("destroy", gtk.main_quit)

        self.fig = Figure(figsize=(5,4), dpi=100)
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(640,690)

        vbox = gtk.VBox(False,1)
        alignIm = gtk.Alignment(0, 1 , 1, 0)
        alignIm.add(self.canvas)
        vbox.pack_start(alignIm)


        self.add(vbox)

        self.initNetworkVariables(networkVariables)
        self.createGraph()
        updateTime = 1 #len(self.quantitiesToPlot) ## if this time is to fast, it will show nothing
        gobject.timeout_add(updateTime,self.updateGraph)

        self.show_all()


    def initNetworkVariables(self,networkVariables):
        '''

        '''
        self.dt               = 0.01
        self.filename         = '../.realtime.viz'
        self.quantitiesToPlot = ['Pressure','Flow']
        self.initialValues    = [0,0,0,0,0]

        #TODO: Try Except Pass should be fixed
        try:
            self.dt               =  networkVariables['dt']
            self.filename         =  networkVariables['filename']
            self.quantitiesToPlot =  networkVariables['quantitiesToPlot']
            self.initialValues    =  networkVariables['initialValues']
        except: pass

    def updateGraph(self):
        '''

        '''

        #TODO: Try Except Pass should be fixed
        try:
            with open(''.join([cur,'/',self.filename]),'r') as dataFile:
                for dataLine in dataFile:
                    dataString = dataLine
                    break
            os.remove(''.join([cur,'/',self.filename]))
        except: pass

        dataDict = {}

        #TODO: Try Except Pass should be fixed
        try:
            dataDict = eval(dataString)
        except:
            try:
                if dataString == 'STOP':
                    return False
            except: pass
            pass


        #TODO: Try Except Pass should be fixed
        try:
            for quantity in self.quantitiesToPlot:
                newValue = dataDict[quantity]
                ## update y values
                yvals = self.lines[quantity].get_ydata()
                yvalsn = np.append(yvals,newValue)
                self.lines[quantity].set_ydata(yvalsn)
                ## update x values
                timeOld = self.lines[quantity].get_xdata()
                time = np.append(timeOld,[timeOld[-1]+self.dt])
                self.lines[quantity].set_xdata(time)
                ## adjust limits
                self.adjustAxis(self.axis[quantity],time,yvalsn)

            # update view()
            self.canvas.figure = self.fig
            self.fig.set_canvas(self.canvas)
            self.canvas.queue_resize()
        except: pass

        return True


    def adjustAxis(self,axis,xVals,yVals):
        '''

        '''
        mmF = 0.1
        #get values for y
        yMaxVals = np.max(yVals)
        yMinVals = np.min(yVals)
        yMinAx,yMaxAx = axis.get_ylim()

        #check and correct if necessary
        if yMaxVals > yMaxAx-mmF*abs(yMaxAx):
            yMaxAx = yMaxVals+mmF*abs(yMaxVals)
        if yMinVals < yMinAx+mmF*abs(yMinAx):
            yMinAx = yMinVals-mmF*abs(yMinVals)
        #apply y values

        axis.set_ylim([yMinAx,yMaxAx])
        #get values for x
        xMinVals = np.min(xVals)
        xMaxVals = np.max(xVals)
        xMinAx,xMaxAx = axis.get_xlim()
        #check and correct if necessary
        if xMaxVals > xMaxAx-mmF*abs(xMaxAx):
            xMaxAx = xMaxVals+mmF*abs(xMaxVals)
        if xMinVals < xMinAx+mmF*abs(xMinAx):
            xMinAx = xMinVals-mmF*abs(xMinVals)
        #apply y values
        axis.set_xlim([xMinAx,xMaxAx])

    def createGraph(self):
        '''

        '''
        numberOfQuantities = len(self.quantitiesToPlot)

        self.fig.subplots_adjust(hspace  = 0.4)
        self.fig.subplots_adjust(right   = 0.85)
        self.fig.subplots_adjust(top     = 0.98)
        self.fig.subplots_adjust(bottom  = 0.2)
        self.fig.subplots_adjust(hspace  = 0.5)
        self.fig.set_figwidth(8.27)
        self.fig.set_figheight((11.69/3)*numberOfQuantities)

        self.lines = {}
        self.axis = {}

        i = 0
        colors = ['b','r','m','g','k']
        for quantity in self.quantitiesToPlot:
            self.axis[quantity] = self.fig.add_subplot(numberOfQuantities,1,i+1, ylabel=quantity, xlabel='Time', ylim = [self.initialValues[i],self.initialValues[i]-0.001], xlim = [0,0.0001])
            self.lines[quantity] = self.axis[quantity].plot(0,self.initialValues[i],color=colors[i] ,linestyle = '-',label=quantity, linewidth = 1.)[0]
            i = i+1

        # update view()
        self.canvas.figure = self.fig
        self.fig.set_canvas(self.canvas)
        self.canvas.queue_resize()
Esempio n. 54
0
class Correl:
    def __init__(self,w=None):
        self.prefix="SH"
        if w==None:
            self.win=gtk.Window()
            self.win.set_title("LGS correlation tool for AO-LAB on %s"%socket.gethostname())
            self.win.set_icon_from_file(os.path.join(os.path.split(__file__)[0],"logouc.png"))
            self.win.connect("delete-event",self.quit)
        else:
            self.win=w
        self.img=None
        self.pad=0
        self.hbox=gtk.HBox()
        vbox=gtk.VBox()
        self.win.add(self.hbox)
        self.hbox.pack_start(vbox,False)
        h=gtk.HBox()
        vbox.pack_start(h,False)
        i=gtk.Image()
        i.set_from_file(os.path.join(os.path.split(__file__)[0],"logouc.png"))
        h.pack_start(i,False)
        b=gtk.Button("Grab")
        b.set_tooltip_text("Grab calibrated images")
        h.pack_start(b,False)
        e=gtk.Entry()
        e.set_width_chars(4)
        e.set_text("100")
        e.set_tooltip_text("Number of frames to average")
        h.pack_start(e,False)
        b.connect("clicked",self.grab,e)
        b=gtk.Button("Update")
        b.set_tooltip_text("Gets current darc state")
        b.connect("clicked",self.update)
        h.pack_start(b,False)
        b=gtk.Button("Reset")
        b.set_tooltip_text("Resets to CoG, refslopes to 0")
        b.connect("clicked",self.reset)
        h.pack_start(b,False)
        h=gtk.HBox()
        vbox.pack_start(h,False)
        b=gtk.Button("Save ref")
        b.set_tooltip_text("Gets ref slopes from darc and saves")
        b.connect("clicked",self.saveRef)
        h.pack_start(b,False)
        e=gtk.Entry()
        e.set_width_chars(10)
        if os.path.exists("/Canary"):
            e.set_text("/Canary/data/")
        else:
            e.set_text("data/")
        e.set_tooltip_text("Directory for ref slopes")
        self.dataDirEntry=e
        h.pack_start(e,True)
        h=gtk.HBox()
        vbox.pack_start(h,False)
        b=gtk.Button("Load")
        b.set_tooltip_text("Loads ref slopes and sets in darc")
        b.connect("clicked",self.loadRef)
        h.pack_start(b,False)
        e=gtk.Entry()
        e.set_width_chars(10)
        e.set_tooltip_text("Filename for loading ref slopes")
        self.entrySlopesFilename=e
        h.pack_start(e,True)

        h=gtk.HBox()
        vbox.pack_start(h,False)
        b=gtk.Button("Compute slopes")
        b.set_tooltip_text("Computes slopes related to this image")
        h.pack_start(gtk.Label("Padding:"),False)
        e=gtk.Entry()
        e.set_width_chars(4)
        e.set_text("8")
        e.set_tooltip_text("FFT padding")
        self.entryPad=e
        h.pack_start(e,False)
        b.connect("clicked",self.computeSlopes,e)
        h.pack_start(b,False)
        b=gtk.Button("RTD")
        b.set_tooltip_text("Start a RTD looking at correlation (this will need restarting if padding changes)")
        b.connect("clicked",self.rtd)
        h.pack_start(b,False)
        h=gtk.HBox()
        vbox.pack_start(h,False)
        b=gtk.Button("Upload img")
        b.set_tooltip_text("upload the correlation image (but don't change centroiding mode")
        b.connect("clicked",self.upload,e)
        h.pack_start(b,False)

        b=gtk.RadioButton(None,"Set to CoG")
        self.setCoGButton=b
        b.set_tooltip_text("Set to CoG mode, will restore ref slopes to CoG slopes.")
        self.setCoGHandle=b.connect("toggled",self.setCoG,e)
        h.pack_start(b,False)
        b=gtk.RadioButton(b,"Set to Corr")
        self.setCorrButton=b
        b.set_tooltip_text("Set to Correlation mode (LGS only).  Updates ref slopes.  Doesn't upload new correlation image.")
        h.pack_start(b,False)


        fig1=Figure()
        self.fig1=FigureCanvas(fig1)
        self.fig1.set_size_request(300,300)
        self.im=fig1.add_subplot(2,1,1)
        self.im2=fig1.add_subplot(2,1,2)
        self.hbox.pack_start(self.fig1,True)
        
        vbox.pack_start(gtk.Label("""Instructions: Click "update".
Grab some data by clicking grab. This is
calibrated pixels.  Choose your padding and
compute slopes.  Then upload img.  Then set
to correlation.  This should automagically
update the refslopes so that the AO
correction should be unaffected.
When you want to update the correlation
image, grab some more data, click compute
slopes and then upload img.  This can be
done when already in correlation mode.  It
will update the ref slopes as necessary.
When finished, go back to CoG mode, and
you should find the ref slopes are 
returned to what they were at the start 
(with maybe slight differences due to
floating point rounding error).
Clicking reset sets to CoG, and zeros the
ref slopes.  Clicking load will load the
ref slopes from disk and set in darc.  
Save will save the ref slopes (so do this
at the start).
Padding should be such that fft wrapping
doesn't occur in the RTD image"""),False)

        self.win.show_all()
    def quit(self,w,e=None):
        gtk.main_quit()
    def grab(self,w,e):
        nfr=int(e.get_text())
        self.img=getImg(nfr)
        img=self.img[256**2:]
        img.shape=128,128
        self.im.cla()
        self.im.set_title("rtcCalPxlBuf")
        self.im.imshow(img)
        self.fig1.draw()

    def update(self,w):
        d=darc.Control(self.prefix)
        cm=d.Get("centroidMode")
        if type(cm)==numpy.ndarray and numpy.any(cm[-49:]):#in correlation mode.
            cur=getCurrentImg()
            cog=0
            print "In correlation mode"
        else:
            cur=makeIdent()
            cog=1
            print "In CoG mode"
        self.setCoGButton.handler_block(self.setCoGHandle)
        if cog:
            self.setCoGButton.set_active(True)
        else:
            self.setCorrButton.set_active(True)
        self.setCoGButton.handler_unblock(self.setCoGHandle)
        self.img=getCurrentImg()
        print self.img.shape
        img=self.img[256**2:]
        img.shape=128,128
        self.im.cla()
        self.im.set_title("Currently used image")
        self.im.imshow(img)
        self.fig1.draw()
        #self.computeSlopes(None,self.entryPad)

    def reset(self,w):
        d=darc.Control(self.prefix)
        d.Set(["centroidMode","refCentroids","corrFFTPattern","corrSubapLoc","corrNpxlx","corrNpxlCum"],["CoG",None,None,None,d.Get("npxlx"),numpy.insert(numpy.cumsum(d.Get("npxlx")*d.Get("npxly")),0,0).astype(numpy.int32)])

    def makefilename(self,dironly=0):
        fdir=self.dataDirEntry.get_text()
        if not os.path.exists(fdir):
            rel=""
            if fdir[0]=='/':
                rel="/"
            dirs=fdir.split("/")
            for d in dirs:
                rel+=d+"/"
                if not os.path.exists(rel):
                    print "Making directory %s"%rel
                    os.mkdir(rel)
        if dironly:
            return fdir
        else:
            return os.path.join(fdir,"corr"+time.strftime("%y%m%d_%H%M%S_"))

    def saveRef(self,w):
        d=darc.Control(self.prefix)
        rf=d.Get("refCentroids")
        if rf!=None:
            fn=self.makefilename()
            fn2=fn+self.prefix+"refCentroids.fits"
            FITS.Write(rf,fn2)
            self.entrySlopesFilename.set_text(os.path.split(fn2)[1])
        else:
            print "No ref slopes to save"
    def loadRef(self,w):
        dd=self.makefilename(dironly=1)
        e=self.entrySlopesFilename
        fname=e.get_text()
        if len(fname)==0:
            fname=None
        else:
            fname=os.path.join(dd,fname)
            flist=glob.glob(fname)
            flist.sort()
            if len(flist)==0:
                #file selection
                fname=None
            else:
                fname=flist[-1]#chose latest.
                e.set_text(os.path.split(fname)[1])
        if fname==None:
            #pop up file selection.
            f=gtk.FileChooserDialog("Load ref slopes",self.win,action=gtk.FILE_CHOOSER_ACTION_OPEN,buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_REJECT,gtk.STOCK_OK,gtk.RESPONSE_ACCEPT))
            f.set_current_folder(dd)
            f.set_modal(True)
            fil=gtk.FileFilter()
            fil.set_name("Ref slopes files")
            fil.add_pattern("corr*_*_*refCentroids.fits")
            f.add_filter(fil)
            f.set_filter(fil)
            fil=gtk.FileFilter()
            fil.set_name("All files")
            fil.add_pattern("*")
            f.add_filter(fil)
            resp=f.run()
            if resp==gtk.RESPONSE_ACCEPT:
                fname=f.get_filename()
            f.destroy()
        if fname!=None:
            print "Reading %s"%fname
            data=FITS.Read(fname)[1]
            d=darc.Control(self.prefix)
            d.Set("refCentroids",data)
            self.entrySlopesFilename.set_text(os.path.split(fname)[1])

    def computeSlopes(self,w,e):
        pad=int(e.get_text())
        self.newslopes,usernow,self.corr=getSlopes(self.img,pad,1)
        img=self.corr["correlation"]
        img=img[self.corr["corrNpxlCum"][2]:]
        img.shape=self.corr["corrNpxly"][2],self.corr["corrNpxlx"][2]
        self.pad=pad
        self.im.cla()
        self.im.set_title("Correlated img")
        self.im.imshow(img)
        self.im2.cla()
        self.im2.set_title("Update to slopes")
        self.im2.plot(self.newslopes[288:])
        self.fig1.draw()
        
    def upload(self,w,e):
        pad=int(e.get_text())
        if pad!=self.pad:
            self.computeSlopes(None,e)
            d=gtk.Dialog("Padding changed",self.win,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_CANCEL,gtk.RESPONSE_REJECT,gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
            d.vbox.pack_start(gtk.Label("Padding has changed since you last computed slopes.\nThese have been recomputed for you to check.\nClick OK to continue."))
            d.show_all()
            resp=d.run()
            d.destroy()
            if resp==gtk.RESPONSE_ACCEPT:
                self.pad=pad
        if self.pad==pad:
            newslopes,usenow=getSlopes(self.img,pad)
            newcorr=makefft(self.img,pad)
            d=darc.Control(self.prefix)
            if usenow:#currently in corr mode, so update the slopes...
                refSlopes=d.Get("refCentroids")
                if refSlopes==None:
                    refSlopes=-newslopes
                else:
                    refSlopes-=newslopes
                newcorr["refCentroids"]=refSlopes
            d.Set(newcorr.keys(),newcorr.values())
    def setCoG(self,w,e):
        d=darc.Control(self.prefix)
        if w.get_active():
            #has set to cog mode.  So change back to cog mode.
            cm=numpy.zeros((49*5,),numpy.int32)
            #so get current correlation image, and compute the ref slopes offset.
            img=makeIdent()
            #compute padding currently used.
            sl=d.Get("subapLocation")
            try:
                sl2=d.Get("corrSubapLoc")
            except:
                sl2=sl.copy()
            sl.shape=sl.size//6,6
            sl2.shape=sl2.size//6,6
            padarr=(sl2[:,1::3]-sl2[:,::3])/numpy.where(sl2[:,2::3]==0,1000,sl2[:,2::3])-(sl[:,1::3]-sl[:,::3])/numpy.where(sl[:,2::3]==0,1000,sl[:,2::3])
            padused=numpy.max(padarr)//2
            print "Calculated currently used padding as %d"%padused
            slopes,usenow=getSlopes(img,padused)
            refSlopes=d.Get("refCentroids")
            if refSlopes==None:
                refSlopes=-slopes
            else:
                refSlopes-=slopes
            d.Set(["centroidMode","refCentroids"],[cm,refSlopes])
        else:
            #has set to corr mode (but currently in cog mode).
            img=getCurrentImg()
            slopes,usenow=getSlopes(img,self.pad)
            refSlopes=d.Get("refCentroids")
            if refSlopes==None:
                refSlopes=-slopes
            else:
                refSlopes-=slopes
            cm=numpy.zeros((49*5,),numpy.int32)
            cm[-49:]=1
            d.Set(["centroidMode","refCentroids"],[cm,refSlopes])

    def rtd(self,w):
        d=darc.Control(self.prefix)
        try:
            npxlx=d.Get("corrNpxlx")
        except:
            npxlx=d.Get("npxlx")
        try:
            npxly=d.Get("corrNpxly")
        except:
            npxly=d.Get("npxly")
        off=(npxlx*npxly)[:-1].sum()
        os.system("""darcplot --prefix=SH rtcCorrBuf 25 "-mdata=data[%d:];data.shape=%d,%d" &"""%(off,npxly[-1],npxlx[-1])) 
Esempio n. 55
0
class Iverplot_window(object):
    """
    Iverplot_window---main Iverplot GUI object

    Parameters
    -----------

    Notes
    ------

    """
    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file('iverplot.glade')
        self.builder.connect_signals(self)
        self.window = self.builder.get_object('main_window')

        # add matplotlib figure canvas
        w, h = self.window.get_size()
        self.fig = Figure(figsize=(6, 4))
        self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
        self.canvas.set_size_request(w - 150, -1)

        vbox = gtk.VBox()
        toolbar = NavigationToolbar(self.canvas, self.window)
        vbox.pack_start(self.canvas, True, True)
        vbox.pack_start(toolbar, False, False)

        # a little hacky for packing hpane with figure canvas first then tool
        # bar---not sure if glade is to blame---first, remove tool_vbox then
        # repack
        plot_hpaned = self.builder.get_object('plot_hpaned')
        self.tool_vbox = self.builder.get_object('tool_vbox')
        plot_hpaned.remove(self.tool_vbox)

        #plot_hpaned.pack1 (self.canvas, resize=True, shrink=False)
        plot_hpaned.pack1(vbox, resize=True, shrink=False)
        plot_hpaned.pack2(self.tool_vbox)

        # data
        self.uvclog = None
        self.lcmlog = None

        # plot limits
        self.xlimits = [None, None]
        self.xlimits_abs = [None, None]

        # add single plot item
        self.plotdex = {}
        self.plot_items = []
        self.plot_items.append(
            Plot_item(self.tool_vbox, self.on_plot_item_selected, self.uvclog,
                      self.lcmlog))
        self.update_subplots()

        # setwin
        self.setwin = None

        # set some defaults
        self.cd_saveas = os.getcwd()
        self.cd_open = os.getcwd()

        self.window.show_all()

    def on_setwin_clicked(self, widget):
        if self.setwin is None:
            self.setwin = Setwin(self.canvas, self.fig,
                                 self.on_setwin_complete)

    def on_setwin_complete(self, xmin, xmax):
        self.xlimits = [xmin, xmax]
        for p in self.plot_items:
            ax = self.fig.axes[self.plotdex[p]]
            p.plot_type.set_limits(ax, *self.xlimits)
        self.canvas.draw()
        self.setwin = None

    def on_setwin_reset(self, widget):
        if not self.setwin is None: return
        self.xlimits = [x for x in self.xlimits_abs]
        for p in self.plot_items:
            ax = self.fig.axes[self.plotdex[p]]
            p.plot_type.set_limits(ax, *self.xlimits)
        self.canvas.draw()

    def update_subplots(self):
        self.fig.clear()
        n = len(self.plot_items)
        for i, p in enumerate(self.plot_items):
            p.plot_type.uvclog = self.uvclog
            p.plot_type.lcmlog = self.lcmlog
            ax = self.fig.add_subplot(n, 1, i + 1)
            p.plot_type.plot(ax, *self.xlimits)
            self.plotdex[p] = i
        self.canvas.draw()

    def on_plot_item_selected(self, combo, item):
        ax = self.fig.axes[self.plotdex[item]]
        item.plot_type.plot(ax, *self.xlimits)
        self.canvas.draw()

    def update_window(self):
        while gtk.events_pending():
            gtk.main_iteration_do(True)

    def on_add_subplot_clicked(self, widget):
        if len(self.plot_items) >= 3:
            return

        self.plot_items.append(
            Plot_item(self.tool_vbox, self.on_plot_item_selected, self.uvclog,
                      self.lcmlog))
        self.update_subplots()
        self.update_window()

    def on_remove_subplot_clicked(self, widget):
        if len(self.plot_items) <= 1:
            return

        item = self.plot_items.pop(-1)
        item.remove()
        self.update_subplots()
        self.update_window()

    def run_open_dialog(self):
        open_dlg = self.builder.get_object('open_dialog')
        #open_dlg.set_current_folder (self.cd_open)
        open_dlg.set_current_folder(
            '/home/jeff/data/UMBS_0513/iver28/2013-06-01-dive.046')

        if len(open_dlg.list_filters()) == 0:
            all_filter = gtk.FileFilter()
            all_filter.set_name('All files')
            all_filter.add_pattern('*')
            open_dlg.add_filter(all_filter)

            lcm_filter = gtk.FileFilter()
            lcm_filter.set_name('LCM logs')
            lcm_filter.add_pattern('lcmlog*')
            open_dlg.add_filter(lcm_filter)

            uvc_filter = gtk.FileFilter()
            uvc_filter.set_name('UVC logs')
            uvc_filter.add_pattern('*.log')
            open_dlg.add_filter(uvc_filter)

        response = open_dlg.run()
        fname = None
        if response == gtk.RESPONSE_OK:
            fname = open_dlg.get_filename()
            self.cd_open = os.path.dirname(fname)

        open_dlg.hide()
        return fname

    def on_open_lcm_clicked(self, widget):
        fname = self.run_open_dialog()
        if fname: print 'selected', fname

    def on_open_uvc_clicked(self, widget):
        fname = self.run_open_dialog()
        if fname:
            print 'selected', fname
            try:
                self.uvclog = UVCLog(fname)
                self.xlimits_abs = [
                    self.uvclog.utime[0], self.uvclog.utime[-1]
                ]
                self.xlimits = [x for x in self.xlimits_abs]
                self.update_subplots()
            except:
                print 'could not load correctly'

    def on_save_as_clicked(self, widget):
        save_as_dlg = self.builder.get_object('save_as_dialog')
        save_as_dlg.set_current_folder(self.cd_saveas)
        save_as_dlg.set_current_name('iverplot.png')

        if len(save_as_dlg.list_filters()) == 0:
            all_filter = gtk.FileFilter()
            all_filter.set_name('All files')
            all_filter.add_pattern('*')
            save_as_dlg.add_filter(all_filter)

            img_filter = gtk.FileFilter()
            img_filter.set_name('All images')
            img_filter.add_pattern('*.png')
            img_filter.add_pattern('*.jpg')
            img_filter.add_pattern('*.pdf')
            save_as_dlg.add_filter(img_filter)

        response = save_as_dlg.run()
        if response == gtk.RESPONSE_OK:
            fname = save_as_dlg.get_filename()
            self.fig.savefig(fname, dpi=self.fig.dpi)
            self.cd_saveas = os.path.dirname(fname)
        save_as_dlg.hide()

    def on_about_clicked(self, widget):
        about = self.builder.get_object('about_dialog')
        about.run()
        about.hide()

    def on_main_window_destroy(self, widget):
        gtk.main_quit()
Esempio n. 56
0
class Image_MovieFrames__GUI(MovieFrames):
    """
    Base class for GUI version of Movie Frames
    ---> needs matplotlib.backends.backend_gtkagg!
         do not clear axes each time for the next animation frame
    -------------
    Contains:
    -------------
    self.redraw_flag -- nedeed by MovieEngine
    """

    def __init__(self, seq_plotter):
        # initialize base class 
        MovieFrames.__init__(self, seq_plotter)
        # GUI specific members -------
        self.main_Window = None
        # set redraw_flag 
        self.redraw_flag=False

    def _setup_figure_and_axes(self, mfs):
        """
        Creates figure and axes accordinng to sized in class mfs
        -------
        Params:
        -------
        mfs
          quasi MovieFrames_Sizes class instance, contains figure sizes and axes boxes
        """
        # set MFS
        self.MFS = mfs
        # plot window ----------------------------
        # self.figure = Figure(facecolor='white',dpi=self.MFS.dpi)
        self.figure = Figure(facecolor='white')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.set_size_request( *self.MFS.figsize_points )
        # axes -----------------------------------
        # add as many axes as there are entries in mfs.axes_boxes
        for box in self.MFS.axes_boxes:
            self.ax.append( self.figure.add_axes(box) )

    def __erase_axes(self):
        for A in self.ax:
            A.set_frame_on(False)
            A.xaxis.set_visible(False)
            A.yaxis.set_visible(False)
            
    def plot(self,**kwargs):
        """
        Makes initial plot and set text for the timelabel
        """
        MovieFrames.plot(self,**kwargs)
        self.__erase_axes()

    def replot(self,**kwargs):
        """
        - plotters' plot
        - erase axes
        """
        # do plot
        MovieFrames.plot(self,animated=True,**kwargs)
        self.__erase_axes()

    def animation_update(self,i_frame):
        """
        Updates plot and timelabel
        """
        for P,A in zip(self.seq_plotter,self.ax):
            P.animation_update( A, i_frame )

    def set_animated(self,val):
        """
        changes *animated* attribute for all changing entries
        """
        for P in self.seq_plotter:
            P.set_animated(val)

    def set_main_window(self,window):
        "Sets the main window for matplotlib widget"
        self.main_Window=window
Esempio n. 57
0
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()