class plotWindow: def __init__(self, title): #title is the title of the window. self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) #mod for win: try: self.window.set_icon_from_file( os.path.join(ICON_PATH, "Shim-icon" + ICON_EXTENSION)) except: pass vbox = gtk.VBox(False) self.window.add(vbox) self.window.set_size_request(600, 400) self.window.set_title(title) self.fig = Figure(figsize=(4, 3), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.set_position([0.2, 0.2, 0.7, 0.7]) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea vbox.pack_start(self.canvas, True, True, 0) self.ax.set_xlabel("Shim dial value") self.ax.set_ylabel("FWQM") def updatePlot(self, xmin, xmax, ymin, ymax, xvals, yvals, name): plotWin.ax.cla() # clear out what was there. plotWin.ax.set_xlim([xmin, xmax]) plotWin.ax.set_ylim([ymin, ymax]) plotWin.ax.set_xlabel(name + " shim dial value") plotWin.ax.set_ylabel("FWQM") plotWin.ax.plot(xvals, yvals, 'bo') self.canvas.draw_idle() return False
class plotWindow: #multipurpose plot window used for live streaming, sweep, and noise spectrum def __init__(self, title, tfbutton=False, trigButton=False): #title is the title of the window. self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) try: print('trying to load icon: ', os.path.join(ICON_PATH, "FuncGen-icon" + ICON_EXTENSION)) self.window.set_icon_from_file( os.path.join(ICON_PATH, "FuncGen-icon" + ICON_EXTENSION)) except: pass vbox = gtk.VBox(False) self.window.add(vbox) # self.window.set_size_request(600, 400) self.window.set_default_size(600, 400) self.window.set_title(title) self.fig = Figure(figsize=(4, 3), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.set_position([0.2, 0.2, 0.7, 0.7]) self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea vbox.pack_start(self.canvas, True, True, 0) # toolbar = NavigationToolbar(self.canvas, self.window) toolbar = MyToolbar(self.canvas, self.window) vbox.pack_start(toolbar, False, False, 0) hbox = gtk.HBox(True) vbox.pack_start(hbox, False, True, 0) self.lowerLim = gtk.Label() hbox.pack_start(self.lowerLim, True, True, 0) self.upperLim = gtk.Label() hbox.pack_start(self.upperLim, True, True, 0) self.RMSLabel = gtk.Label() hbox.pack_start(self.RMSLabel, True, True, 0) if trigButton: self.triggeringButton = gtk.ToggleButton("Triggering") hbox.pack_start(self.triggeringButton, True, True, 0) if tfbutton: self.autoScaleButton = gtk.Button("AutoScale") self.autoScaleButton.connect_object("clicked", self.autoScale, None) hbox.pack_start(self.autoScaleButton, True, True, 0) self.logLinButton = gtk.ToggleButton("Log/Linear") self.logLinButton.connect_object("clicked", self.logLin, None) hbox.pack_start(self.logLinButton, True, True, 0) self.logLinButton.set_sensitive(False) self.tfbutton = gtk.ToggleButton("Time/Freq") self.tfbutton.connect_object("clicked", self.timeFreq, None) hbox.pack_start(self.tfbutton, True, True, 0) self.saveButton = gtk.Button("Save") vbox.pack_start(self.saveButton, False, True, 0) self.saveButton.connect_object("clicked", self.save, None) #data stored here: self.txvals = None self.tyvals = None self.fxvals = None self.fyvals = None # time or freq domain? self.view = "freq" #initial limits self.txlims = None self.tylims = None self.fxlims = None self.fylims = None def calcXvals(self, np, rate): self.txvals = numpy.arange(np) / float(rate) * 1000 self.fxvals = numpy.fft.fftfreq(np, 1 / float(rate))[0:np // 2 + 1] if self.fxvals[-1] < 0: self.fxvals[-1] *= -1 self.rate = rate def logLin(self, button): # change the y axes from log to linear # print ' in logLin' (min, max) = self.ax.get_ylim() if self.logLinButton.get_active(): self.fylims = (min, max) self.ax.set_ylim(self.fyloglims) self.ax.set_yscale('log') else: self.fyloglims = (min, max) self.ax.set_yscale('linear') self.ax.set_ylim(self.fylims) self.canvas.draw_idle() def autoScale(self, button): # find the limits of what we're viewing (minX, maxX) = self.ax.get_xlim() #need to find which points correspond to those limits if self.view == 'freq': if minX > self.fxvals[-1]: return if maxX < self.fxvals[0]: return if minX < self.fxvals[0]: minXpt = 0 else: # so minX is in range minXpt = numpy.argmax(self.fxvals >= minX) if maxX > self.fxvals[-1]: maxXpt = self.fxvals.size else: maxXpt = numpy.argmax(self.fxvals >= maxX) if minXpt == 0: minXpt = 1 min = numpy.amin(self.fyvals[minXpt:maxXpt]) max = numpy.amax(self.fyvals[minXpt:maxXpt]) else: #time domain if minX > self.txvals[-1]: return if maxX < self.txvals[0]: return if minX < self.txvals[0]: minXpt = 0 else: minXpt = numpy.argmax(self.txvals >= minX) if maxX > self.txvals[-1]: maxXpt = self.txvals.size else: maxXpt = numpy.argmax(self.txvals >= maxX) min = numpy.amin(self.tyvals[minXpt:maxXpt]) max = numpy.amax(self.tyvals[minXpt:maxXpt]) # print '' # print 'using min pt',minXpt # print 'using max pt',maxXpt # print 'got min and max of:',min,max if self.logLinButton.get_active(): #can only be active in freq mode. if min <= 0: min = 1e-4 if max <= min: max = min * 10 min = min / 2. max = max * 2. self.ax.set_ylim(min, max) else: (min, max) = calc_lims(min, max) self.ax.set_ylim((min, max)) self.canvas.draw_idle() def timeFreq(self, button): #change from time to freq domain or back if self.tfbutton.get_active() and self.view == 'time': self.view = 'freq' self.txlims = self.ax.get_xlim() self.tylims = self.ax.get_ylim() if self.fxlims is None: self.wasLog = False min = numpy.amin(self.fxvals) max = numpy.amax(self.fxvals) (min, max) = calc_lims(min, max) self.ax.set_xlim((min, max)) min = numpy.amin(self.fyvals) max = numpy.amax(self.fyvals) (min, max) = calc_lims(min, max) self.ax.set_ylim((min, max)) # now for log: if min <= 0: min = 1e-4 if max <= min: max = min * 10 min = min / 2. max = max * 2. self.fyloglims = (min, max) else: self.ax.set_xlim(self.fxlims) self.ax.set_ylim(self.fylims) self.ax.set_xlabel("Frequency (Hz)") self.ax.set_ylabel("Amplitude") self.logLinButton.set_sensitive(True) if self.wasLog: self.logLinButton.set_active(True) self.line.set_data(self.fxvals, self.fyvals) self.canvas.draw_idle() elif not self.tfbutton.get_active( ) and self.view == 'freq': # going to time tomain self.wasLog = self.logLinButton.get_active() self.logLinButton.set_active( False) #will store the loglims if was log self.view = 'time' self.fxlims = self.ax.get_xlim() self.fylims = self.ax.get_ylim() self.logLinButton.set_sensitive(False) if self.txlims is None: min = numpy.amin(self.txvals) max = numpy.amax(self.txvals) (min, max) = calc_lims(min, max) self.ax.set_xlim((min, max)) min = numpy.amin(self.tyvals) max = numpy.amax(self.tyvals) (min, max) = calc_lims(min, max) self.ax.set_ylim((min, max)) else: self.ax.set_xlim(self.txlims) self.ax.set_ylim(self.tylims) self.ax.set_xlabel("Time (ms)") self.ax.set_ylabel("Amplitude") self.line.set_data(self.txvals, self.tyvals) self.canvas.draw_idle() return #used for live streaming and noise spectrum def updatePlot(self): # print 'in updatePlot, view is',self.view # print 'ylims: ',self.ax.get_ylim() # print 'yscale is:',self.ax.get_yscale() if self.view == 'time': # do some 'triggering' #Strategy: find the transition from < 5 to > 5 that is nearest the middle #then relabel the xvals so that the transition appears at 0. if self.triggeringButton.get_active(): i = self.tyvals.size / 2 lval = numpy.argmax( self.tyvals[i:] < 5 ) # ival is the index of the first point past halfway that is <5 gval = numpy.argmax( self.tyvals[lval + i:] > 5) #look for next rise through 5. #so, we want lval+i+gval as our trigger point! #if there is no transition from low to high, lval = 0 and gval = 0 shifted_txvals = self.txvals - (self.txvals[i + lval + gval] - self.txvals[i]) else: shifted_txvals = self.txvals self.line.set_data(shifted_txvals, self.tyvals) rms = numpy.sqrt( numpy.sum(self.tyvals * self.tyvals) / self.tyvals.size) self.RMSLabel.set_text("rms: " + str(round(rms, 2))) self.lowerLim.set_text("min: " + str(round(numpy.amin(self.tyvals)))) self.upperLim.set_text("max: " + str(round(numpy.amax(self.tyvals)))) else: maxindex = numpy.argmax(self.fyvals) self.RMSLabel.set_text("") self.lowerLim.set_text("max: " + str(round(self.fyvals[maxindex], 2))) self.upperLim.set_text("at: " + str(round(self.fxvals[maxindex], 1)) + " Hz") self.line.set_data(self.fxvals, self.fyvals) self.canvas.draw_idle() return False #this is an idle function, must return False def save(self, dummy): # make a copy of the data so we get what we asked for. if self.view == 'time': yvals = self.tyvals.copy() xvals = self.txvals.copy() else: yvals = self.fyvals.copy() xvals = self.fxvals.copy() fileChooser = gtk.FileChooserDialog( title="Save file...", parent=None, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=("Cancel", gtk.RESPONSE_CANCEL, "Save", gtk.RESPONSE_OK)) response = fileChooser.run() fileName = fileChooser.get_filename() fileChooser.destroy() if response == gtk.RESPONSE_CANCEL: return elif response == gtk.RESPONSE_OK: if fileName[-4:] != ".txt": fileName = fileName + ".txt" try: #check if fileName exists inFile = open(fileName, "r") inFile.close() #prompt if want to overwrite dialog = gtk.Dialog("Attention!") label = gtk.Label("Duplicate file found! Overwrite?") dialog.vbox.pack_start(label, True, True, 0) dialog.add_buttons("Yes", gtk.RESPONSE_YES, "No", gtk.RESPONSE_NO) dialog.show_all() response = dialog.run() # -8 is yes, and -9 is no dialog.hide() dialog.destroy() if (response == -8): #delete stuff try: os.remove(fileName) except: #meh. pass elif (response == -9): #do not overwrite. abort return except: #file does not currently exist. Okay. pass #save outFile = open(fileName, "w") for i in range(xvals.size): #assuming they're of the same length outFile.write(str(xvals[i]) + ' ' + str(yvals[i]) + '\n') outFile.close() return else: return
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()
class Panoptikum(object): def __init__(self): # assign gtk-Layout builder = gtk.Builder() builder.add_from_file("panoptikum.glade") builder.connect_signals(self) self.window = builder.get_object("window1") self.windowMessage = builder.get_object("messagedialog1") self.filechooserProject = builder.get_object("filechooserdialog1") self.filefilter = builder.get_object("filefilter1") self.filefilter.add_pattern("*.cfg") self.large_atom_check_button = builder.get_object("large_atom_check_button") self.live_mode_check_button = builder.get_object("live_mode_check_button") self.roiOnly_check_button = builder.get_object("roiOnly_check_button") self.sameID_check_button = builder.get_object("sameID_check_button") self.radio_buttons_imageCategory = builder.get_object("action1") self.window.connect("destroy", self.__del__) self.statusbar = builder.get_object("statusbar1") self.hbox_Rb = builder.get_object("hboxRb") self.vbox_Rb = builder.get_object("vboxRb") self.vbox_RbLast10 = builder.get_object("vboxRbLast10") self.hbox_Li = builder.get_object("hboxLi") self.vbox_Li = builder.get_object("vboxLi") self.www_Rb = builder.get_object("togglebuttonRbWww") self.www_Li = builder.get_object("togglebuttonLiWww") # global Variables self.MessageType = "N_Li" self.maxImageSize = array([0, 1392, 0, 1040]) ######### TODO ############ """ self.TEST = builder.get_object('filechooserbutton1Rb') self.TEST2 = builder.get_object('entry1') #import time #self.time_start = 0 #self.time_end = 0 try: print p['pixelSizeTextField'].get_value() print self.TEST.get_filename() self.TEST.set_filename('rb_recenta.fit') self.TEST2.set_text(str(p['part'])[1:-1]) except: pass """ """ self.time_start = time.clock() self.time_end = time.clock() print self.time_end - self.time_start """ ######### TODO ############ # matplotlib self.whiteCMap = loadColormap.whiteCMap() self.initNav() self.shiftPressed = False # Rb __init__ self.figure_Rb = plt.figure() gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) ax1 = plt.subplot(gs[0]) ax1.set_xlabel(u"\u00b5m") ax1.set_ylabel(u"\u00b5m") ax1.xaxis.set_label_coords(0.97, -0.06) ax3 = plt.subplot(gs[1]) ax3.xaxis.set_label_coords(0.97, -0.16) canvas_Rb = FigCanvas(self.figure_Rb) plt.subplots_adjust(hspace=0.25, bottom=0.05, right=0.95) nav_Rb = Nav(canvas_Rb, self.window) self.vbox_Rb.pack_start(nav_Rb, False, False) self.vbox_Rb.pack_start(canvas_Rb) self.figure_RbLast10 = plt.figure() self.ax1Last10 = plt.subplot(111) self.canvas_RbLast10 = FigCanvas(self.figure_RbLast10) self.vbox_RbLast10.pack_start(self.canvas_RbLast10) RbValues2calc = [ "N_Rb", "T_Rb", "fwhmV_Rb", "fwhmH_Rb", "PosV_Rb", "PosH_Rb", "AmpV_Rb", "AmpH_Rb", "OffV_Rb", "OffH_Rb", "______AUTOMATISIERUNG_", "AUTO_N_POS", "AUTO_STEP_POS", "AUTO_START", "AUTO_STEP", "AUTO_BREAK", "ABB_TOF_RB", ] RbIndexLst = [s.lower().strip("_" + "rb") for s in RbValues2calc] self.RbParameters = { "pixelSize": 6.57e-6, "pixelSizeTextField": builder.get_object("spinbutton1"), "axScale": 1e6, "species": "Rb", "folder": "F:\\INBOX\\Apogee\\", "filenames": ["rb_recenta.fit", "rb_recentb.fit", "rb_recentc.fit"], "adwinfile": "..\\ADwin\\adwin_code_recent.acm", "savefilename": "rb_result.png", "fullFrame": zeros(2), "partAtomCount": array([550, 750, 500, 800]), "partLumCorr": array([550, 750, 800, 950]), "part": self.maxImageSize, "xylim": [(0, 6826), (9138, 0)], "Marker1Pos": (0, 0), "Marker2Pos": (0, 0), "imageAx": ax1, "linescanAx": ax3, "canvasObj": canvas_Rb, "ODmaxAuto": builder.get_object("checkbuttonRbAutoOD"), "ODmaxLabel": builder.get_object("labelRbOD"), "ODmax": builder.get_object("hscaleRbOD"), "adwinID": builder.get_object("adwinIDRb"), "imageCategory": "opt. Dichte", "values2calc": RbValues2calc, "indexLst": RbIndexLst, "last10": pd.DataFrame(index=RbIndexLst), } # Li __init__ self.figure_Li = plt.figure() gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) ax0 = plt.subplot(gs[0]) ax0.set_xlabel(u"\u00b5m") ax0.set_ylabel(u"\u00b5m") ax0.xaxis.set_label_coords(0.97, -0.06) ax2 = plt.subplot(gs[1]) ax2.xaxis.set_label_coords(0.97, -0.16) canvas_Li = FigCanvas(self.figure_Li) plt.subplots_adjust(hspace=0.25, bottom=0.05, right=0.95) nav_Li = Nav(canvas_Li, self.window) self.vbox_Li.pack_start(nav_Li, False, False) self.vbox_Li.pack_start(canvas_Li) LiValues2calc = [ "N_Li", "T_Li", "fwhmV_Li", "fwhmH_Li", "PosV_Li", "PosH_Li", "AmpV_Li", "AmpH_Li", "OffV_Li", "OffH_Li", "______AUTOMATISIERUNG_", "AUTO_N_POS", "AUTO_STEP_POS", "AUTO_START", "AUTO_STEP", "AUTO_BREAK", "ABB_TOF_LI", ] LiIndexLst = [s.lower().strip("_" + "li") for s in LiValues2calc] self.LiParameters = { "pixelSize": 6.57e-6, "axScale": 1e6, "species": "Li", "folder": "F:\\INBOX\\Apogee\\", "filenames": ["li_recenta.fit", "li_recentb.fit", "li_recentc.fit"], "adwinfile": "..\\ADwin\\adwin_code_recent.acm", "savefilename": "li_result.png", "fullFrame": zeros(2), "partAtomCount": array([550, 750, 500, 800]), "partLumCorr": array([550, 750, 800, 950]), "part": self.maxImageSize, "xylim": [(0, 6826), (9138, 0)], "Marker1Pos": (0, 0), "Marker2Pos": (0, 0), "imageAx": ax0, "linescanAx": ax2, "canvasObj": canvas_Li, "ODmaxAuto": builder.get_object("checkbuttonLiAutoOD"), "ODmaxLabel": builder.get_object("labelLiOD"), "ODmax": builder.get_object("hscaleLiOD"), "adwinID": builder.get_object("adwinIDLi"), "imageCategory": "opt. Dichte", "values2calc": LiValues2calc, "indexLst": LiIndexLst, "last10": pd.DataFrame(index=LiIndexLst), } # reload Parameters of last Session try: with open("restoreLastSession.pickle", "rb") as infile: parameterFromStorage = pickle.load(infile) self.RbParameters["part"] = parameterFromStorage[0] self.RbParameters["partAtomCount"] = parameterFromStorage[1] self.RbParameters["partLumCorr"] = parameterFromStorage[2] self.RbParameters["xylim"] = parameterFromStorage[3] self.RbParameters["Marker1Pos"] = parameterFromStorage[4] self.RbParameters["Marker2Pos"] = parameterFromStorage[5] self.LiParameters["part"] = parameterFromStorage[6] self.LiParameters["partAtomCount"] = parameterFromStorage[7] self.LiParameters["partLumCorr"] = parameterFromStorage[8] self.LiParameters["xylim"] = parameterFromStorage[9] self.LiParameters["Marker1Pos"] = parameterFromStorage[10] self.LiParameters["Marker2Pos"] = parameterFromStorage[11] except: print "Cannot load last Session!" # set working directory os.chdir(self.RbParameters["folder"]) # draw matplotlib stuff self.initLines(self.RbParameters) self.initLines(self.LiParameters) self.updateFullFrameImage(self.RbParameters) self.updateFullFrameImage(self.LiParameters) self.last10Rb = self.drawImageArea(self.RbParameters) self.last10Li = self.drawImageArea(self.LiParameters) # show gtk-window self.window.set_default_size(1024, 800) self.window.set_size_request(600, 800) self.window.set_title("Panoptikum - LiRb-Lab Image Analyse") self.window.show_all() # self.statusbar1_text_pushed('Li image updated... waiting for images...') # GTK-event handlers self.window.connect("key_press_event", self.on_key_press) self.window.connect("key_release_event", self.on_key_released) # matplotlib-event handlers canvas_Rb.mpl_connect("button_press_event", self.mouse_press_callback_Rb) canvas_Rb.mpl_connect("button_release_event", self.mouse_release_callback_Rb) canvas_Rb.mpl_connect("scroll_event", self.mouse_scrolled_callback_Rb) canvas_Li.mpl_connect("button_press_event", self.mouse_press_callback_Li) canvas_Li.mpl_connect("button_release_event", self.mouse_release_callback_Li) canvas_Li.mpl_connect("scroll_event", self.mouse_scrolled_callback_Li) rectprops = dict(facecolor="black", edgecolor="black", alpha=0.1, fill=True) self.RS_Rb = RectangleSelector( ax1, self.RectangleSelector_callback_Rb, drawtype="box", useblit=True, button=[1, 3], minspanx=10, minspany=10, spancoords="pixels", rectprops=rectprops, ) self.RS_Li = RectangleSelector( ax0, self.RectangleSelector_callback_Li, drawtype="box", useblit=True, button=[1, 3], minspanx=10, minspany=10, spancoords="pixels", rectprops=rectprops, ) # GIO-event handlers fileRb = gio.File(self.RbParameters["filenames"][-1]) self.monitorRb = fileRb.monitor_file() self.monitorRbID = self.monitorRb.connect("changed", self.file_changedRb) fileLi = gio.File("li_recentc.fit") self.monitorLi = fileLi.monitor_file() self.monitorLiID = self.monitorLi.connect("changed", self.file_changedLi) def initLines(self, parameters): p = parameters p["imageObj"] = p["imageAx"].imshow(random([2, 2]), self.whiteCMap, interpolation="none", aspect="auto") p["lineFitH"], = p["imageAx"].plot( array([0, 1040]) * p["pixelSize"] * p["axScale"], [-1e5, -1e5], ":", lw=2, color="0.15" ) p["lineFitV"], = p["imageAx"].plot( [-1e5, -1e5], array([0, 1392]) * p["pixelSize"] * p["axScale"], ":", lw=2, color="0.15" ) p["lineMarker1H"], = p["imageAx"].plot( array([0, 1040]) * p["pixelSize"] * p["axScale"], [-1e5, -1e5], "k-", lw=1 ) p["lineMarker1V"], = p["imageAx"].plot( [-1e5, -1e5], array([0, 1382]) * p["pixelSize"] * p["axScale"], "k-", lw=1 ) self.drawCrosshair(p["lineMarker1H"], p["lineMarker1V"], p["Marker1Pos"]) p["lineMarker2H"], = p["imageAx"].plot( array([0, 1040]) * p["pixelSize"] * p["axScale"], [-1e5, -1e5], "r-", lw=1 ) p["lineMarker2V"], = p["imageAx"].plot( [-1e5, -1e5], array([0, 1382]) * p["pixelSize"] * p["axScale"], "r-", lw=1 ) self.drawCrosshair(p["lineMarker2H"], p["lineMarker2V"], p["Marker2Pos"]) p["imageAx"].set_xlim(p["xylim"][0]) p["imageAx"].set_ylim(p["xylim"][1]) p["imageAx"].set_xlabel(u"\u00b5m") p["imageAx"].set_ylabel(u"\u00b5m") if not self.roiOnly_check_button.get_active(): lc = p["partLumCorr"] * p["pixelSize"] * p["axScale"] ac = p["partAtomCount"] * p["pixelSize"] * p["axScale"] rectLumCorr = plt.Rectangle((lc[2], lc[0]), lc[3] - lc[2], lc[1] - lc[0], ec="red", fc="none", ls="dotted") rectAtomCount = plt.Rectangle( (ac[2], ac[0]), ac[3] - ac[2], ac[1] - ac[0], ec="black", fc="none", ls="dashed" ) p["imageAx"].add_patch(rectLumCorr) p["imageAx"].add_patch(rectAtomCount) def initNav(self): home = Nav.home def new_home(self, *args, **kwargs): home(self, *args, **kwargs) Panoptikum_.nav_callback("home") Nav.home = new_home back = Nav.back def new_back(self, *args, **kwargs): back(self, *args, **kwargs) Panoptikum_.nav_callback("back") Nav.back = new_back forward = Nav.forward def new_forward(self, *args, **kwargs): forward(self, *args, **kwargs) Panoptikum_.nav_callback("forward") Nav.forward = new_forward def drawImageArea(self, parameters): p = parameters ImageScale = array(p["part"]) * p["pixelSize"] * p["axScale"] data = pd.Series(zeros(len(p["values2calc"])), index=p["indexLst"], dtype=float) # image field if p["imageCategory"] == "opt. Dichte" or p["imageCategory"] == "ROI": image = p["fullFrame"][p["part"][0] : p["part"][1], p["part"][2] : p["part"][3]] if (p["part"][1] - p["part"][0] < 800 and p["part"][3] - p["part"][2] < 800) or p["imageCategory"] == "ROI": data = pd.Series( imageAnalyse.analyseShot(p["adwinfile"], p["values2calc"], image), index=p["indexLst"], dtype=float ) imageAtomCount = p["fullFrame"][ p["partAtomCount"][0] : p["partAtomCount"][1], p["partAtomCount"][2] : p["partAtomCount"][3] ] data["n"] = imageAnalyse.analyseShot(p["adwinfile"], [p["values2calc"][0]], imageAtomCount) if p["ODmaxAuto"].get_active(): p["ODmax"].set_value(imageAtomCount.max()) if data["n"] < 1e6: title1 = p["imageAx"].set_title( (r"N(" + p["species"] + r") = ${:,.2f}\,\times\,10^3$").format(data["n"] / 1e3) ) if ( self.MessageType == "N_Li" and p["species"] == "Li" or self.MessageType == "N_Rb" and p["species"] == "Rb" ): self.windowMessage.set_markup( u'<span font="120">N(' + p["species"] + r")= " + u"%.2f\u00d710\u00b3</span>" % (data["n"] / 1e3) ) else: title1 = p["imageAx"].set_title( (r"N(" + p["species"] + r") = ${:,.2f}\,\times\,10^6$").format(data["n"] / 1e6) ) if ( self.MessageType == "N_Li" and p["species"] == "Li" or self.MessageType == "N_Rb" and p["species"] == "Rb" ): self.windowMessage.set_markup( u'<span font="120">N(' + p["species"] + r")= " + u"%.2f\u00d710\u2076</span>" % (data["n"] / 1e6) ) else: if p["imageCategory"] == "Atomrohbild": image = apogee.singleImage(p["filenames"][0], p["part"]) elif p["imageCategory"] == "Hellrohbild": image = apogee.singleImage(p["filenames"][1], p["part"]) elif p["imageCategory"] == "Dunkelrohbild": image = apogee.singleImage(p["filenames"][2], p["part"]) title1 = p["imageAx"].set_title(p["species"] + r": " + p["imageCategory"]) if p["ODmaxAuto"].get_active(): p["ODmax"].set_value(image.max()) p["imageObj"].set_data(image) p["imageObj"].set_extent([ImageScale[2], ImageScale[3], ImageScale[1], ImageScale[0]]) p["imageObj"].set_clim(0, p["ODmax"].get_value()) title1.set_fontsize(32) title1.set_y(1.04) if not data["t"] == 0 and not math.isnan(float(data["t"] * 1e6)): self.drawCrosshair( p["lineFitH"], p["lineFitV"], [ data["posh"] * p["pixelSize"] * p["axScale"] + ImageScale[2], data["posv"] * p["pixelSize"] * p["axScale"] + ImageScale[0], ], ) else: self.drawCrosshair(p["lineFitH"], p["lineFitV"], [-1e5, -1e5]) # linescan gaussian fit p["linescanAx"].cla() p["linescanAx"].plot(linspace(ImageScale[2], ImageScale[3], size(image, 1)), imageAnalyse.linescan(image)) p["linescanAx"].plot( linspace(ImageScale[2], ImageScale[3], size(image, 0)), imageAnalyse.linescan(image, dir=1), color="0.85" ) if math.isnan(float(data["t"] * 1e6)): title3 = p["linescanAx"].set_title(u"T(" + p["species"] + r") uneindeutig") p["linescanAx"].text( 0.02, 0.05, u"TOF = {:.2f}ms".format(data["abb_tof"] / 1e3), transform=p["linescanAx"].transAxes ) elif data["t"] == 0: title3 = p["linescanAx"].set_title("") else: title3 = p["linescanAx"].set_title(u"T(" + p["species"] + u") = {:.2f}\u00b5K".format(data["t"] * 1e6)) p["linescanAx"].text( 0.02, 0.85, u"H-Pos: {:.2f}\u00b5m".format(data["posh"] * p["pixelSize"] * p["axScale"] + ImageScale[2]), transform=p["linescanAx"].transAxes, ) p["linescanAx"].text( 0.02, 0.7, u"H-FWHM: {:.2f}\u00b5m".format(data["fwhmh"] * p["axScale"]), transform=p["linescanAx"].transAxes, ) p["linescanAx"].text( 0.98, 0.85, u"V-Pos: {:.2f}\u00b5m".format(data["posv"] * p["pixelSize"] * p["axScale"] + ImageScale[0]), transform=p["linescanAx"].transAxes, color="0.7", horizontalalignment="right", ) p["linescanAx"].text( 0.98, 0.7, u"V-FWHM: {:.2f}\u00b5m".format(data["fwhmv"] * p["axScale"]), transform=p["linescanAx"].transAxes, color="0.7", horizontalalignment="right", ) p["linescanAx"].plot( linspace(ImageScale[2], ImageScale[3], size(image, 1)), imageAnalyse.gauss( range(0, size(image.conj().transpose(), 0)), data["amph"], data["posh"], imageAnalyse.fwhm(data["fwhmh"], reverse=1), data["offh"], ), "--", ) p["linescanAx"].plot( linspace(ImageScale[2], ImageScale[3], size(image, 0)), imageAnalyse.gauss( range(0, size(image.conj().transpose(), 1)), data["ampv"], data["posv"], imageAnalyse.fwhm(data["fwhmv"], reverse=1), data["offv"], ), "--", color="0.85", ) p["linescanAx"].plot( [ data["posh"] * p["pixelSize"] * p["axScale"] + ImageScale[2], data["posh"] * p["pixelSize"] * p["axScale"] + ImageScale[2], ], p["linescanAx"].get_ylim(), "k:", ) posVrelAxH = (data["posv"] * p["pixelSize"] * p["axScale"]) / (ImageScale[1] - ImageScale[0]) * ( ImageScale[3] - ImageScale[2] ) + ImageScale[2] p["linescanAx"].plot([posVrelAxH, posVrelAxH], p["linescanAx"].get_ylim(), ":", color="0.5") p["linescanAx"].plot([p["Marker1Pos"][0], p["Marker1Pos"][0]], p["linescanAx"].get_ylim(), "k-") posVrelAxHMarker1 = (p["Marker1Pos"][1] - ImageScale[0]) / (ImageScale[1] - ImageScale[0]) * ( ImageScale[3] - ImageScale[2] ) + ImageScale[2] p["linescanAx"].plot([posVrelAxHMarker1, posVrelAxHMarker1], p["linescanAx"].get_ylim(), "-", color="0.85") p["linescanAx"].text( 0.02, 0.05, u"TOF = {:.2f}ms".format(data["abb_tof"] / 1e3), transform=p["linescanAx"].transAxes ) if not data["automatisierung"] == 0: p["linescanAx"].text( 0.98, 0.05, u"auto: {:.0f}/{:.0f} #{:.0f}".format( data["auto_step_pos"], abs(data["auto_break"]), data["auto_n_pos"] ), transform=p["linescanAx"].transAxes, horizontalalignment="right", ) p["linescanAx"].set_xlim((ImageScale[2], ImageScale[3])) p["linescanAx"].grid(True, color="0.5") p["linescanAx"].set_xlabel(u"\u00b5m") p["linescanAx"].ticklabel_format(style="sci", axis="y", scilimits=(0, 3)) title3.set_fontsize(18) title3.set_y(1.06) p["canvasObj"].draw_idle() return data def updateADwinID(self, parameters): p = parameters if not self.live_mode_check_button.get_active(): ID = float(p["adwinID"].get_value()) else: with open(p["adwinfile"] + ".id") as adwinIDfile: ID = float(adwinIDfile.read()) p["adwinID"].set_range(0, 1e6) p["adwinID"].set_value(ID) def updateFullFrameImage(self, parameters): p = parameters if p["imageCategory"] == "ROI": p["fullFrame"] = apogee.singleImage(p["filenames"][0], self.maxImageSize) x, y = shape(p["fullFrame"]) p["part"] = array([0, x, 0, y]) else: p["fullFrame"] = apogee.odTriple(p["filenames"], self.maxImageSize, p["partLumCorr"], p["partAtomCount"]) self.updateADwinID(parameters) def drawCrosshair(self, line1, line2, position): line1.set_ydata(position[1]) line2.set_xdata(position[0]) def on_togglebuttonLiHide_toggled(self, button): if button.get_active(): self.hbox_Li.hide() else: self.hbox_Li.show() def on_togglebuttonRbHide_toggled(self, button): if button.get_active(): self.hbox_Rb.hide() else: self.hbox_Rb.show() def radiobuttonRb_toggled(self, button): if button.get_active(): if button.get_label() == "opt. Dichte": self.RbParameters["ODmax"].set_range(0.05, 3) self.RbParameters["ODmax"].set_digits(2) self.RbParameters["ODmaxLabel"].set_text("max opt. Dichte:") else: self.RbParameters["ODmax"].set_range(0.05, 65536) self.RbParameters["ODmax"].set_digits(0) self.RbParameters["ODmaxLabel"].set_text("max Belichtung:") self.RbParameters["ODmaxAuto"].set_active(True) self.RbParameters["imageCategory"] = button.get_label() self.drawImageArea(self.RbParameters) def radiobuttonLi_toggled(self, button): if button.get_active(): if button.get_label() == "opt. Dichte": self.LiParameters["ODmax"].set_range(0.05, 3) self.LiParameters["ODmax"].set_digits(2) self.LiParameters["ODmaxLabel"].set_text("max opt. Dichte:") else: self.LiParameters["ODmax"].set_range(0.05, 65536) self.LiParameters["ODmax"].set_digits(0) self.LiParameters["ODmaxLabel"].set_text("max Belichtung:") self.LiParameters["ODmaxAuto"].set_active(True) self.LiParameters["imageCategory"] = button.get_label() self.drawImageArea(self.LiParameters) def radiobuttonMessage_toggled(self, button): if button.get_active(): if button.get_label() == "N(Li)": self.MessageType = "N_Li" self.drawImageArea(self.LiParameters) elif button.get_label() == "N(Rb)": self.MessageType = "N_Rb" self.drawImageArea(self.RbParameters) def hscaleRbOD_adj_value_changed(self, slider): self.RbParameters["imageObj"].set_clim(0, slider.get_value()) self.RbParameters["canvasObj"].draw_idle() def hscaleLiOD_adj_value_changed(self, slider): self.LiParameters["imageObj"].set_clim(0, slider.get_value()) self.LiParameters["canvasObj"].draw_idle() def filechooserbutton1Rb_selection_changed(self, event): print self.TEST.get_filename() def checkbuttonRbAutoOD_toggled(self, button): if button.get_active(): self.RbParameters["ODmax"].set_sensitive(False) self.drawImageArea(self.RbParameters) else: self.RbParameters["ODmax"].set_sensitive(True) def checkbuttonLiAutoOD_toggled(self, button): if button.get_active(): self.LiParameters["ODmax"].set_sensitive(False) self.drawImageArea(self.LiParameters) else: self.LiParameters["ODmax"].set_sensitive(True) def mouse_scrolled_callback_Rb(self, event): self.xlimChange(event, self.RbParameters) def mouse_scrolled_callback_Li(self, event): self.xlimChange(event, self.LiParameters) def xlimChange(self, event, parameters): p = parameters if event.inaxes == p["imageAx"]: if event.button == "up": x0 = p["xylim"][0][0] x1 = p["xylim"][0][1] removeFromX = (x1 - x0) * 0.03 mouseXrel = (event.xdata - x0) / (x1 - x0) x0 = x0 + removeFromX * mouseXrel x1 = x1 - removeFromX * (-mouseXrel + 1) y0 = p["xylim"][1][0] y1 = p["xylim"][1][1] removeFromY = (y1 - y0) * 0.03 mouseYrel = (event.ydata - y0) / (y1 - y0) y0 = y0 + removeFromY * mouseYrel y1 = y1 - removeFromY * (-mouseYrel + 1) else: x0 = p["xylim"][0][0] x1 = p["xylim"][0][1] addToX = (x1 - x0) * 0.03 mouseXrel = (event.xdata - x0) / (x1 - x0) x0 = x0 - addToX * mouseXrel x1 = x1 + addToX * (-mouseXrel + 1) y0 = p["xylim"][1][0] y1 = p["xylim"][1][1] addToY = (y1 - y0) * 0.03 mouseYrel = (event.ydata - y0) / (y1 - y0) y0 = y0 - addToY * mouseYrel y1 = y1 + addToY * (-mouseYrel + 1) p["xylim"] = [(x0, x1), (y0, y1)] p["imageAx"].set_xlim(p["xylim"][0]) p["imageAx"].set_ylim(p["xylim"][1]) p["canvasObj"].draw_idle() def mouse_press_callback_Rb(self, event): return def mouse_press_callback_Li(self, event): return def mouse_release_callback_Rb(self, event): self.mouse_release_callback(event, self.RbParameters) def mouse_release_callback_Li(self, event): self.mouse_release_callback(event, self.LiParameters) def mouse_release_callback(self, event, parameter): p = parameter if event.button == 2: if event.inaxes != p["imageAx"]: event.xdata, event.ydata = -1e5, -1e5 if self.shiftPressed == False: p["Marker1Pos"] = (event.xdata, event.ydata) self.drawCrosshair(p["lineMarker1H"], p["lineMarker1V"], p["Marker1Pos"]) else: p["Marker2Pos"] = (event.xdata, event.ydata) self.drawCrosshair(p["lineMarker2H"], p["lineMarker2V"], p["Marker2Pos"]) self.drawImageArea(p) else: self.ImageAxisChanged(p) def ImageAxisChanged(self, parameters, fullframe=False): p = parameters if p["xylim"] != [p["imageAx"].get_xlim(), p["imageAx"].get_ylim()]: if fullframe: if not p["imageCategory"] == "ROI": p["part"] = self.maxImageSize p["xylim"] = [ (1, p["part"][3] * p["pixelSize"] * p["axScale"] - 1), (p["part"][1] * p["pixelSize"] * p["axScale"] - 1, 1), ] p["imageAx"].set_xlim(p["xylim"][0]) p["imageAx"].set_ylim(p["xylim"][1]) else: p["xylim"] = [p["imageAx"].get_xlim(), p["imageAx"].get_ylim()] newX = map(int, array(p["xylim"][0]) / p["pixelSize"] / p["axScale"]) newY = map(int, array(p["xylim"][1]) / p["pixelSize"] / p["axScale"]) p["part"] = array([newY[::-1], newX]).flatten() + [-1, 1, -1, 1] p["part"] = p["part"].clip(1, 1391) if p["part"][3] > 1039: p["part"][3] = 1039 data = self.drawImageArea(p) self.updateLast10(p, data) def updateLast10(self, parameters, data, isNew=False): p = parameters if p["species"] == "Rb": if isNew == True: p["last10"].columns = p["last10"].columns + 1 p["last10"][0] = pd.DataFrame( data ) # , index = ['n', 't', 'fwhmv', 'fwhmh', 'posv', 'posh', 'ampv', 'amph', 'offv', 'offh', 'automatisierung', 'auto_n_pos', 'auto_step_pos', 'auto_start', 'auto_step', 'auto_break', 'abb_tof']) if p["last10"].shape[1] > 10: print p["last10"] del p["last10"][10] print p["last10"] df = p["last10"].copy() df.columns = df.columns * (-1) print df.loc["n"] self.ax1Last10.cla() df.loc["n"].plot(ax=self.ax1Last10) self.canvas_RbLast10.draw_idle() def RectangleSelector_callback_Rb(self, eclick, erelease): self.RectangleSelected(self.RbParameters, eclick, erelease) def RectangleSelector_callback_Li(self, eclick, erelease): self.RectangleSelected(self.LiParameters, eclick, erelease) def RectangleSelected(self, parameters, eclick, erelease): p = parameters if not self.roiOnly_check_button.get_active(): coordinates = array([eclick.ydata, erelease.ydata, eclick.xdata, erelease.xdata]) coordinateScaled = array(map(int, coordinates / p["pixelSize"] / p["axScale"])) coordinateScaled = sort(coordinateScaled.reshape(2, 2), axis=1).flatten() p["imageAx"].cla() if erelease.button == 1: p["partAtomCount"] = coordinateScaled elif erelease.button == 3: p["partLumCorr"] = coordinateScaled self.updateFullFrameImage(p) self.initLines(p) self.drawCrosshair(p["lineMarker1H"], p["lineMarker1V"], p["Marker1Pos"]) data = self.drawImageArea(p) self.updateLast10(p, data) # print p['species'], p['partAtomCount'], p['partLumCorr'] def file_changedRb(self, monitor, file, unknown, event): if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT: self.updateFullFrameImage(self.RbParameters) data = self.drawImageArea(self.RbParameters) self.updateLast10(self.RbParameters, data, isNew=True) if self.www_Rb.get_active(): self.figure_Rb.savefig(self.RbParameters["savefilename"], dpi=50) def file_changedLi(self, monitor, file, unknown, event): if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT: self.updateFullFrameImage(self.LiParameters) data = self.drawImageArea(self.LiParameters) self.updateLast10(self.LiParameters, data, isNew=True) if self.www_Li.get_active(): self.figure_Li.savefig(self.LiParameters["savefilename"], dpi=50) def statusbar1_text_pushed(self, message): ##self.statusbar.push(self.statusbar.get_context_id(message), message) return def nav_callback(self, button): if button == "home": fullframe = True else: fullframe = False self.ImageAxisChanged(self.RbParameters, fullframe) self.ImageAxisChanged(self.LiParameters, fullframe) def on_key_press(self, widget, event): if event.state & gtk.gdk.SHIFT_MASK: self.shiftPressed = True def on_key_released(self, widget, event): if event.keyval == 65505: self.shiftPressed = False def open_toggle(self, event): self.filechooserProject.run() self.live_mode_check_button.set_active(False) def live_mode(self, widget): if widget.active: self.RbParameters["filenames"] = ["rb_recenta.fit", "rb_recentb.fit", "rb_recentc.fit"] self.LiParameters["filenames"] = ["li_recenta.fit", "li_recentb.fit", "li_recentc.fit"] self.monitorRbID = self.monitorRb.connect("changed", self.file_changedRb) self.monitorLiID = self.monitorLi.connect("changed", self.file_changedLi) self.sameID_check_button.set_sensitive(False) self.roiOnly_check_button.set_sensitive(False) self.roiOnly_check_button.set_active(False) for p in [self.RbParameters, self.LiParameters]: p["folder"] = "F:\\INBOX\\Apogee\\" os.chdir(p["folder"]) p["adwinfile"] = "..\\ADwin\\adwin_code_recent.acm" p["adwinID"].set_sensitive(False) self.updateFullFrameImage(p) p["imageAx"].cla() self.initLines(p) self.drawCrosshair(p["lineMarker1H"], p["lineMarker1V"], p["Marker1Pos"]) data = self.drawImageArea(p) else: self.monitorRb.disconnect(self.monitorRbID) self.monitorLi.disconnect(self.monitorLiID) if self.filechooserProject.get_filename() is None: self.filechooserProject.run() self.sameID_check_button.set_sensitive(True) self.roiOnly_check_button.set_sensitive(True) self.parse_config_file() def roiOnly_toggled(self, widget): if widget.active: self.RbParameters["filenames"] = ["rb_roi.fit"] self.LiParameters["filenames"] = ["li_roi.fit"] self.RbParameters["imageCategory"] = "ROI" self.LiParameters["imageCategory"] = "ROI" self.RbParameters["partAtomCount"] = self.maxImageSize self.LiParameters["partAtomCount"] = self.maxImageSize self.radio_buttons_imageCategory.set_sensitive(False) else: self.RbParameters["imageCategory"] = "opt. Dichte" self.LiParameters["imageCategory"] = "opt. Dichte" self.radio_buttons_imageCategory.set_sensitive(True) self.RbParameters["part"] = self.maxImageSize self.LiParameters["part"] = self.maxImageSize self.adwinID_change(self.RbParameters) self.adwinID_change(self.LiParameters) def project_file_clicked(self, event): self.filechooserProject.hide() def parse_config_file(self): import ConfigParser import codecs configFile = self.filechooserProject.get_filename() projectFolder = os.path.dirname(configFile) Config = ConfigParser.ConfigParser() try: Config.readfp(codecs.open(configFile, "r", "utf8")) if "li" in Config.sections() and not self.roiOnly_check_button.get_active(): self.LiParameters["filenames"] = Config.get("li", "filenames").split() self.LiParameters["adwinfile"] = "adwin_code.acm" self.LiParameters["partAtomCount"] = array(map(int, Config.get("li", "part").split())) self.LiParameters["partLumCorr"] = array(map(int, Config.get("li", "partLumCorr").split())) dirListLi = map( float, [name for name in os.listdir(projectFolder) if os.path.isdir(os.path.join(projectFolder, name))], ) # self.LiParameters['adwinID'].set_value(min(dirListLi)) self.LiParameters["adwinID"].set_range(min(dirListLi), max(dirListLi)) self.LiParameters["adwinID"].set_sensitive(True) else: print "No Li in project folder config-file!" if "rb" in Config.sections(): self.RbParameters["filenames"] = Config.get("rb", "filenames").split() self.RbParameters["adwinfile"] = "adwin_code.acm" self.RbParameters["partAtomCount"] = array(map(int, Config.get("rb", "part").split())) self.RbParameters["partLumCorr"] = array(map(int, Config.get("rb", "partLumCorr").split())) dirListRb = map( float, [name for name in os.listdir(projectFolder) if os.path.isdir(os.path.join(projectFolder, name))], ) # self.RbParameters['adwinID'].set_value(min(dirListRb)) self.RbParameters["adwinID"].set_range(min(dirListRb), max(dirListRb)) self.RbParameters["adwinID"].set_sensitive(True) else: print "No Rb in project folder config-file!" except: self.live_mode_check_button.set_active(True) print "Opening of project failed!" def adwinIDRb_changed_value(self, event): self.adwinID_change(self.RbParameters) if self.sameID_check_button.get_active(): if not self.RbParameters["adwinID"].get_value() == self.LiParameters["adwinID"].get_value(): self.LiParameters["adwinID"].set_value(self.RbParameters["adwinID"].get_value()) def adwinIDLi_changed_value(self, event): self.adwinID_change(self.LiParameters) if self.sameID_check_button.get_active(): if not self.RbParameters["adwinID"].get_value() == self.LiParameters["adwinID"].get_value(): self.RbParameters["adwinID"].set_value(self.LiParameters["adwinID"].get_value()) def adwinID_change(self, parameters): p = parameters if not self.live_mode_check_button.get_active(): if not self.roiOnly_check_button.get_active(): self.parse_config_file() dir = os.path.dirname(self.filechooserProject.get_filename()) p["folder"] = os.path.join(dir, str(int(p["adwinID"].get_value()))) os.chdir(p["folder"]) self.updateFullFrameImage(p) p["imageAx"].cla() self.initLines(p) self.drawCrosshair(p["lineMarker1H"], p["lineMarker1V"], p["Marker1Pos"]) data = self.drawImageArea(p) def quit_toggle(self, event): self.__del__(event) def on_clicked_about(self, widget): about = gtk.AboutDialog() about.set_program_name("Panoptikum") about.set_version("0.3") about.set_copyright(u"\u00a9 Reinhardt A.W. Maier") about.set_comments("Panoptikum is a tool for analysing cold atoms images") about.set_website("http://www.zaehlwerk.net") # about.set_logo(gtk.gdk.pixbuf_new_from_file('battery.png')) about.run() about.destroy() def large_atomnumber(self, widget): if widget.active: self.windowMessage.show() else: self.windowMessage.hide() def large_atomnumber_button(self, button, *opt): self.large_atom_check_button.set_active(False) self.windowMessage.hide() return True def stay_on_top(self, widget): if widget.active: self.window.set_keep_above(True) else: self.window.set_keep_above(False) def __del__(self, event): if self.live_mode_check_button.get_active(): with open("restoreLastSession.pickle", "wb") as outfile: parameterToStore = array( [ self.RbParameters["part"], self.RbParameters["partAtomCount"], self.RbParameters["partLumCorr"], self.RbParameters["xylim"], self.RbParameters["Marker1Pos"], self.RbParameters["Marker2Pos"], self.LiParameters["part"], self.LiParameters["partAtomCount"], self.LiParameters["partLumCorr"], self.LiParameters["xylim"], self.LiParameters["Marker1Pos"], self.LiParameters["Marker2Pos"], ] ) pickle.dump(parameterToStore, outfile) gtk.main_quit()
class Figure(gtk.VBox): def __init__(self): print "Starting up SamFigure!" gtk.VBox.__init__(self) self.figure = MPLFigure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect("button_press_event", self.on_click) self.ax = self.figure.add_subplot(111) self.ax2 = None self.mode = TWODPLOT self.new_data() self.xlabel = '' self.y1label = '' self.y2label = '' self.xsize = 0 self.ysize = 0 self.packed = False self.count_since_replot = 0 self.set_colors() def on_click(self, event): # If left button, if event.button == 1: # screen coordinates of click xclick, yclick = event.x, event.y top_ax = event.inaxes if top_ax is None: return # display coordinates of nearest point in ax data1=self.ax.transData.transform(\ zip(self.listing.getX(),self.listing.getY(1))) distances1=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data1] ind_sel1 = numpy.argmin(distances1) dist1 = distances1[ind_sel1] xsel, ysel = data1[ind_sel1] label_ax = self.ax label_color = 'b' # if DUAL, then also check ax2 for nearer points if self.mode == DUALTWODPLOT: data2=self.ax2.transData.transform(\ zip(self.listing.getX(),self.listing.getY(2))) distances2=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data2] ind_sel2 = numpy.argmin(distances2) dist2 = distances2[ind_sel2] if dist2 < dist1: xsel, ysel = data2[ind_sel2] label_color = 'g' label_ax = self.ax2 # Clear off old labels if hasattr(self, "label_text"): self.label_text.remove() self.label_point.remove() del (self.label_text) # Coordinates to show ( data coordinates of the selected axes) xlabel, ylabel = label_ax.transData.inverted().transform( (xsel, ysel)) # Coordinates to place label (on top set of axes) xloc, yloc = top_ax.transData.inverted().transform((xsel, ysel)) # Label the point if (xloc > sum(self.ax.get_xlim()) / 2): h_align = 'right' else: h_align = 'left' self.label_text=\ top_ax.text(xloc,yloc,'({0:.3g},{1:.3g})'\ .format(xlabel,ylabel),\ backgroundcolor='white', color=label_color,\ verticalalignment='bottom', horizontalalignment=h_align,\ bbox={'facecolor': 'white', 'boxstyle': 'round'},zorder=100 ) self.label_point,=\ top_ax.plot(xloc,yloc,'ro',\ zorder=self.label_text.get_zorder()+1) self.repaint() # Otherwise, just clear off old labels else: self.label_text.remove() self.label_point.remove() del (self.label_text) self.repaint() def replot(self): if self.mode == TWODPLOT: self.ax.clear() self.ax.plot(self.listing.getX(), self.listing.getY(1), self.color1 + '.-') self.count_since_replot = 0 elif self.mode == DUALTWODPLOT: self.ax.clear() self.ax2.clear() self.ax.plot(self.listing.getX(), self.listing.getY(1), self.color1 + '.-') self.ax2.plot(self.listing.getX(), self.listing.getY(2), self.color2 + '.-') self.count_since_replot = 0 def show(self): try: if not self.packed: self.pack_start(self.canvas, expand=True) toolbar = NavigationToolbar(self.canvas, self.get_parent_window()) next = 8 button = gtk.Button('Lin y') button.show() button2 = gtk.Button('Lin x') button2.show() # linear/log def clicked(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_yscale() == 'log': button.set_label('Lin y') self.ax.set_yscale('linear') else: button.set_label('Log y') self.ax.set_yscale('log') self.show() def clicked2(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_xscale() == 'log': button.set_label('Lin x') self.ax.set_xscale('linear') else: button.set_label('Log x') self.ax.set_xscale('log') self.show() button.connect('clicked', clicked) button2.connect('clicked', clicked2) toolitem = gtk.ToolItem() toolitem.show() toolitem.add(button) toolbar.insert(toolitem, next) next += 1 toolitem2 = gtk.ToolItem() toolitem2.show() toolitem2.add(button2) toolbar.insert(toolitem2, next) self.pack_start(toolbar, expand=False) self.packed = True super(Figure, self).show() except Exception, e: print 'Exception: ', e raise
class 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()
class Figure(gtk.VBox): def __init__(self): print "Starting up SamFigure!" gtk.VBox.__init__(self) self.figure = MPLFigure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect("button_press_event", self.on_click) self.ax = self.figure.add_subplot(111) self.ax2 = None self.mode = TWODPLOT self.new_data() self.xlabel = '' self.y1label = '' self.y2label = '' self.xsize = 0 self.ysize = 0 self.packed = False self.count_since_replot=0 self.set_colors() def on_click(self,event): # If left button, if event.button==1: # screen coordinates of click xclick,yclick= event.x, event.y top_ax=event.inaxes if top_ax is None: return # display coordinates of nearest point in ax data1=self.ax.transData.transform(\ zip(self.listing.getX(),self.listing.getY(1))) distances1=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data1] ind_sel1=numpy.argmin(distances1) dist1 = distances1[ind_sel1] xsel,ysel= data1[ind_sel1] label_ax=self.ax label_color='b' # if DUAL, then also check ax2 for nearer points if self.mode==DUALTWODPLOT: data2=self.ax2.transData.transform(\ zip(self.listing.getX(),self.listing.getY(2))) distances2=\ [(x-xclick)**2+(y-yclick)**2 \ for (x,y) in data2] ind_sel2=numpy.argmin(distances2) dist2 = distances2[ind_sel2] if dist2<dist1: xsel,ysel= data2[ind_sel2] label_color='g' label_ax=self.ax2 # Clear off old labels if hasattr(self,"label_text"): self.label_text.remove() self.label_point.remove() del(self.label_text) # Coordinates to show ( data coordinates of the selected axes) xlabel,ylabel=label_ax.transData.inverted().transform((xsel,ysel)) # Coordinates to place label (on top set of axes) xloc,yloc=top_ax.transData.inverted().transform((xsel,ysel)) # Label the point if (xloc > sum(self.ax.get_xlim())/2): h_align='right' else: h_align='left' self.label_text=\ top_ax.text(xloc,yloc,'({0:.3g},{1:.3g})'\ .format(xlabel,ylabel),\ backgroundcolor='white', color=label_color,\ verticalalignment='bottom', horizontalalignment=h_align,\ bbox={'facecolor': 'white', 'boxstyle': 'round'},zorder=100 ) self.label_point,=\ top_ax.plot(xloc,yloc,'ro',\ zorder=self.label_text.get_zorder()+1) self.repaint() # Otherwise, just clear off old labels else: self.label_text.remove() self.label_point.remove() del(self.label_text) self.repaint() def replot(self): if self.mode == TWODPLOT: self.ax.clear() self.ax.plot(self.listing.getX(),self.listing.getY(1),self.color1+'.-') self.count_since_replot=0 elif self.mode == DUALTWODPLOT: self.ax.clear() self.ax2.clear() self.ax.plot(self.listing.getX(),self.listing.getY(1),self.color1+'.-') self.ax2.plot(self.listing.getX(),self.listing.getY(2),self.color2+'.-') self.count_since_replot=0 def show(self): try: if not self.packed: self.pack_start(self.canvas, expand=True) toolbar = NavigationToolbar(self.canvas, self.get_parent_window()) next = 8 button = gtk.Button('Lin y') button.show() button2 = gtk.Button('Lin x') button2.show() # linear/log def clicked(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_yscale() == 'log': button.set_label('Lin y') self.ax.set_yscale('linear') else: button.set_label('Log y') self.ax.set_yscale('log') self.show() def clicked2(button): self.adjust_axis_margins() self.set_axis_labels() self.color_labels() self.canvas.draw_idle() self.canvas.show() if self.ax.get_xscale() == 'log': button.set_label('Lin x') self.ax.set_xscale('linear') else: button.set_label('Log x') self.ax.set_xscale('log') self.show() button.connect('clicked', clicked) button2.connect('clicked', clicked2) toolitem=gtk.ToolItem() toolitem.show() toolitem.add(button) toolbar.insert(toolitem, next) next +=1 toolitem2=gtk.ToolItem() toolitem2.show() toolitem2.add(button2) toolbar.insert(toolitem2, next) self.pack_start(toolbar, expand=False) self.packed = True super(Figure, self).show() except Exception, e: print 'Exception: ', e raise