def __init__(self, application): self.app = application #signal that experiment is running self.experiment_mode = False self.app.print_comment("Starting GUI interface:") self.app.print_comment("please wait while the application loads...") #build the GUI interface as a seperate window win = tk.Tk() Pmw.initialise(win) #initialize Python MegaWidgets win.withdraw() win.wm_title(WINDOW_TITLE) win.focus_set() #put focus on this new window self.win = win #handle the user hitting the 'X' button self.win.protocol("WM_DELETE_WINDOW", self._close) #FIXME bind some debugging keystrokes to the window #self.win.bind('<Control-f>', lambda e: self.app.force_experiment()) #build the left panel left_panel = tk.Frame(win) #capture controls tk.Label(left_panel, text="Capture Controls:", font = "Helvetica 14 bold").pack(side='top',fill='x', anchor="nw") self.change_settings_button = tk.Button(left_panel,text='Change Settings',command = self.change_settings) self.change_settings_button.pack(side='top',fill='x', anchor="sw") self.run_continually_button = tk.Button(left_panel,text='Run Continually',command = self.run_continually) self.run_continually_button.pack(side='top',fill='x', anchor="nw") self.stop_button = tk.Button(left_panel,text='Stop',command = self.stop, state='disabled') self.stop_button.pack(side='top',fill='x', anchor="nw") self.run_once_button = tk.Button(left_panel,text='Run Once',command = self.run_once) self.run_once_button.pack(side='top',fill='x', anchor="nw") self.export_data_button = tk.Button(left_panel,text='Export Data',command = self.export_data, state='disabled') self.export_data_button.pack(side='bottom',anchor="sw") left_panel.pack(fill='y',expand='no',side='left', padx = 10) #create an tk embedded figure for temperature display mid_panel = tk.Frame(win) self.temperature_plot_template = TemperaturePlot() self.temperature_figure_widget = EmbeddedFigure(mid_panel, figsize=TEMPERATURE_FIGSIZE) self.temperature_figure_widget.pack(side='left',fill='both', expand='yes') mid_panel.pack(fill='both', expand='yes',side='left') #build the right panel right_panel = tk.Frame(win) self.text_display = TextDisplayBox(right_panel,text_height=15, buffer_size = TEXT_BUFFER_SIZE) self.text_display.pack(side='left',fill='both',expand='yes') right_panel.pack(fill='both', expand='yes',side='right') #build the confirmation dialog self.settings_dialog = SettingsDialog(self.win) self.settings_dialog.withdraw() self._load_settings() #run modes self._is_running = False
class GUI(GUIBase): def build_window(self): GUIBase.build_window(self) #now size the window and center it sw = self._win.winfo_screenwidth() sh = self._win.winfo_screenheight() w = sw*WINDOW_TO_SCREENWIDTH_RATIO h = sh*WINDOW_TO_SCREENHEIGHT_RATIO x = (sw - w)/2 y = (sh - h)/2 self._win.geometry("%dx%d+%d+%d" % (w,h,x,y)) self._cv_plot_Xs = [] self._cv_plot_Ys = [] self._cv_plot_labels = [] self._vsweep_mode = None self._vsweep_stop = False def build_widgets(self): #FIXME bind some debugging keystrokes to the window #self._win.bind('<Control-f>', lambda e: self._app.) #----------------------------------------------------------------------- #build the left panel left_panel = tk.Frame(self._win) #voltage sweep controls tk.Label(left_panel, text="Voltage Sweep Controls:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") self.vsweep_settings_button = tk.Button(left_panel, text = 'Change Settings', command = self.change_vsweep_settings, width = BUTTON_WIDTH) self.vsweep_settings_button.pack(side='top', anchor="sw") self.vsweep_once_button = tk.Button(left_panel, text = 'Run Once', command = lambda: self.do_vsweep(mode = 'once'), width = BUTTON_WIDTH) self.vsweep_once_button.pack(side='top', anchor="nw") self.vsweep_continually_button = tk.Button(left_panel, text = 'Run Continually', command = lambda: self.do_vsweep(mode = 'continual'), width = BUTTON_WIDTH) self.vsweep_continually_button.pack(side='top', anchor="nw") self.vsweep_stop_button = tk.Button(left_panel, text = 'Stop', command = self.vsweep_stop, state = 'disabled', width = BUTTON_WIDTH) self.vsweep_stop_button.pack(side='top', anchor="nw") #build the capture settings dialog self.vsweep_settings_dialog = VoltageSweepSettingsDialog(self._win) self.vsweep_settings_dialog.withdraw() #finish the left panel left_panel.pack(fill='y',expand='no',side='left', padx = 10) #----------------------------------------------------------------------- #build the middle panel - a tabbed notebook mid_panel = tk.Frame(self._win) #mid_panel.pack(fill='both', expand='yes',side='left') nb = ttk.Notebook(mid_panel) nb.pack(fill='both', expand='yes',side='right') tab1 = tk.Frame(nb) tab1.pack(fill='both', expand='yes',side='right') nb.add(tab1, text = "Current vs. Voltage") #create an tk embedded figure for the current vs. voltage display self.cv_plot_template = CurrentVoltagePlot() self.cv_plot_template.configure(title = CV_PLOT_TITLE) self.cv_plot_figure_widget = EmbeddedFigure(tab1, figsize = CV_PLOT_FIGSIZE) self.cv_plot_figure_widget.pack(side='top',fill='both', expand='yes') self._update_cv_plot() #make an empty plot self.replot_cv_button = tk.Button(tab1,text='Replot',command = self.replot_cv, state='normal', width = BUTTON_WIDTH) self.replot_cv_button.pack(side='left',anchor="sw") self.clear_cv_button = tk.Button(tab1,text='Clear',command = self.clear_data, state='normal', width = BUTTON_WIDTH) self.clear_cv_button.pack(side='left',anchor="sw") self.export_data_button = tk.Button(tab1, text ='Export Data', command = self.export_data, state = 'disabled', width = BUTTON_WIDTH) self.export_data_button.pack(side='left',anchor="sw") #finish builing the middle pannel mid_panel.pack(fill='both', expand='yes',side='left') #----------------------------------------------------------------------- #build the right panel right_panel = tk.Frame(self._win) #Status variable display #tk.Label(right_panel, pady = SECTION_PADY).pack(side='top',fill='x', anchor="nw") #tk.Label(right_panel, text="Status:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") #self.condition_fields = ConditionFields(right_panel) #self.condition_fields.pack(side='top', anchor="w", expand='no') # Events text display tk.Label(right_panel, pady = SECTION_PADY).pack(side='top',fill='x', anchor="nw") tk.Label(right_panel, text="Events Monitoring:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") self.text_display = TextDisplayBox(right_panel, text_width = TEXTBOX_WIDTH, buffer_size = TEXTBOX_BUFFER_SIZE, ) self.text_display.pack(side='top',fill='both',expand='yes') #finish building the right panel right_panel.pack(fill='both', expand='yes',side='right', padx = 10) def close(self): self.cache_settings() GUIBase.close(self) def load_settings(self): if os.path.exists(SETTINGS_FILEPATH): self._app.print_comment("loading from settings file '%s'" % SETTINGS_FILEPATH) settings = shelve.open(SETTINGS_FILEPATH) self.vsweep_settings_dialog.form['v_start'] = settings.get('v_start', 0.0) self.vsweep_settings_dialog.form['v_end'] = settings.get('v_end', 1.5) self.vsweep_settings_dialog.form['v_rate'] = settings.get('v_rate', 0.25) self.vsweep_settings_dialog.form['samp_rate'] = settings.get('samp_rate', 10.0) self.vsweep_settings_dialog.form['cycles'] = settings.get('cycles', 1) self.vsweep_settings_dialog.current_range_level_var.set(settings.get('current_range_level', 0)) settings.close() else: self._app.print_comment("failed to find settings file '%s'" % SETTINGS_FILEPATH) def cache_settings(self): self._app.print_comment("caching to settings file '%s'" % SETTINGS_FILEPATH) settings = shelve.open(SETTINGS_FILEPATH) settings['v_start'] = self.vsweep_settings_dialog.form['v_start'] settings['v_end'] = self.vsweep_settings_dialog.form['v_end'] settings['v_rate'] = self.vsweep_settings_dialog.form['v_rate'] settings['samp_rate'] = self.vsweep_settings_dialog.form['samp_rate'] settings['cycles'] = self.vsweep_settings_dialog.form['cycles'] settings['current_range_level'] = self.vsweep_settings_dialog.current_range_level_var.get() settings.close() def busy(self): self.disable_control_buttons() self._win.config(cursor="watch") def not_busy(self): self.enable_control_buttons() self._win.config(cursor="") def print_to_text_display(self, text, eol='\n'): try: self.text_display.print_text(text, eol=eol) except AttributeError: #ignore missing text display widget pass def print_event(self, event, info = {}): buff = ["%s:" % event] for key,val in info.items(): buff.append("%s: %s" % (key,val)) buff = "\n".join(buff) self.print_to_text_display(buff) def disable_control_buttons(self): self.vsweep_settings_button.configure(state="disabled") self.vsweep_continually_button.configure(state="disabled") #self.capture_stop_button.configure(state="disabled") self.vsweep_once_button.configure(state="disabled") def enable_control_buttons(self): self.vsweep_settings_button.configure(state="normal") self.vsweep_continually_button.configure(state="normal") #self.vsweep_stop_button.configure(state="normal") self.vsweep_once_button.configure(state="normal") def change_vsweep_settings(self): choice = self.vsweep_settings_dialog.activate() if choice == "OK": self._app.print_comment("changing voltage sweep settings...") def do_vsweep(self, mode = 'once'): self._vsweep_mode = mode #disable all the control buttons, except the stop button self.disable_control_buttons() self.vsweep_stop_button.config(state='normal') if mode == 'once': self.vsweep_once_button.config(bg='green', relief='sunken') elif mode == 'continual': self.vsweep_continually_button.config(state='disabled', bg='green', relief="sunken") #get parameters v_start = float(self.vsweep_settings_dialog.form['v_start']) v_end = float(self.vsweep_settings_dialog.form['v_end']) v_rate = float(self.vsweep_settings_dialog.form['v_rate']) samp_rate = float(self.vsweep_settings_dialog.form['samp_rate']) cycles = int(self.vsweep_settings_dialog.form['cycles']) current_range_level = self.vsweep_settings_dialog.current_range_level_var.get() current_range_level, _ = current_range_level.split(",") current_range_level = int(current_range_level) self._app.print_comment("Running a voltage sweep:") self._app.print_comment(" v_start: %0.2f" % (v_start,)) self._app.print_comment(" v_end: %0.2f" % (v_end,)) self._app.print_comment(" v_rate: %0.2f" % (v_rate,)) self._app.print_comment(" samp_rate: %0.2f" % (samp_rate,)) self._app.print_comment(" cycles: %0.2f" % (cycles,)) #start the voltage sweep, SHOULD NOT BLOCK! self._app.start_voltage_sweep(v_start = v_start, v_end = v_end, v_rate = v_rate, samp_rate = samp_rate, cycles = cycles, current_range_level = current_range_level, ) self._win.after(LOOP_DELAY, self._wait_on_vsweep_loop) def _wait_on_vsweep_loop(self): voltage_sweep = self._app._load_controller('voltage_sweep') #read out all pending events while not voltage_sweep.event_queue.empty(): event, info = voltage_sweep.event_queue.get() self.print_event(event,info) if event == "VOLTAGE_SWEEP_SAMPLE": self._app._append_vsweep_data_record(info['control_voltage'], info['WEtoRE_voltage'], info['WE_current'], ) #use new data to update the plot V1 = self._app._vsweep_dataset['control_voltage'] V2 = self._app._vsweep_dataset['WEtoRE_voltage'] I = self._app._vsweep_dataset['WE_current'] self._update_cv_plot(X_now = V2, Y_now = I) if voltage_sweep.thread_isAlive(): #reschedule loop self._vsweep_after_id = self._win.after(VSWEEP_LOOP_DELAY,self._wait_on_vsweep_loop) else: #cycle is finished #cache the data for the plot V1 = self._app._vsweep_dataset['control_voltage'] V2 = self._app._vsweep_dataset['WEtoRE_voltage'] I = self._app._vsweep_dataset['WE_current'] self._cv_plot_Xs.append(V2) self._cv_plot_Ys.append(I) new_label = "Trial %d" % (len(self._cv_plot_labels) + 1,) self._cv_plot_labels.append(new_label) self.replot_cv() #finish up #self.not_busy() #re-enable all the buttons, except the stop button self.enable_control_buttons() self.export_data_button.config(state='normal') self._app.print_comment("voltage sweep completed") #self.export_data_button.config(state='normal') #data can now be exported if self._vsweep_mode == 'once': self.vsweep_once_button.config(bg='light gray', relief='raised') self.vsweep_stop_button.config(state='disabled') self._vsweep_stop = False elif self._vsweep_mode == 'continual': if self._vsweep_stop: self._vsweep_stop = False self._vsweep_mode = None self.vsweep_continually_button.config(bg='light gray', relief='raised') voltage_sweep.reset() else: #reschedule another voltage sweep self.do_vsweep(mode = 'continual') def vsweep_stop(self): self.vsweep_stop_button.config(state='disabled') voltage_sweep = self._app._load_controller('voltage_sweep') self._vsweep_stop = True #force it to stop right now instead of finishing sleep voltage_sweep.abort() # if not self._vsweep_after_id is None: # #cancel the next scheduled loop time # self._win.after_cancel(self._vsweep_after_id) # #then enter the loop one more time to clean up # self._wait_on_vsweep_loop() def replot_cv(self): voltage_sweep = self._app._load_controller('voltage_sweep') figure = self.cv_plot_figure_widget.get_figure() figure.clear() self.cv_plot_template._has_been_plotted = False #check to see if the current trial is still running if voltage_sweep.thread_isAlive(): #if so pass in the current trial data V1 = self._app._vsweep_dataset['control_voltage'] V2 = self._app._vsweep_dataset['WEtoRE_voltage'] I = self._app._vsweep_dataset['WE_current'] self._update_cv_plot(X_now = V2, Y_now = I) else: #otherwise just the completed data sets (i.e., avoid redundancy of last set) self._update_cv_plot() def export_data(self): self._app.print_comment("Exporting data...") dt_now = datetime.datetime.utcnow() dt_now_str = dt_now.strftime("%Y-%m-%d") #get some metadata for title v_start = float(self._app._vsweep_dataset.get_metadata('v_start')) v_end = float(self._app._vsweep_dataset.get_metadata('v_end')) v_rate = float(self._app._vsweep_dataset.get_metadata('v_rate')) default_filename = "%s_vsweep_%0.2f_to_%0.2fV_by_%0.2fVps.csv" % (dt_now_str,v_start,v_end,v_rate) fdlg = SaveFileDialog(self._win,title="Save Voltage Sweep Data") userdata_path = self._app._config['paths']['data_dir'] filename = fdlg.go(dir_or_file = userdata_path, pattern = "*.csv", default = default_filename, key = None, ) if filename: self._app.export_data(filename) self._app.print_comment("finished") def clear_data(self): self._cv_plot_Xs = [] self._cv_plot_Ys = [] self._cv_plot_labels = [] self.replot_cv() def _update_cv_plot(self, X_now = None, Y_now = None): figure = self.cv_plot_figure_widget.get_figure() plot_template = self.cv_plot_template #decide whether to plot the data (again) or update a current plot do_plot = False if not plot_template.has_been_plotted(): do_plot = True else: #check if the plot has moved out of the boundaries ax1 = figure.axes[0] xlim = ax1.get_xlim() ylim = ax1.get_ylim() if not xlim[0] <= X_now[-1] <= xlim[1]: do_plot = True if not ylim[0] <= Y_now[-1] <= ylim[1]: do_plot = True #do the update if do_plot: self._app.print_comment("Plotting the Current vs. Voltage.") Xs = self._cv_plot_Xs[:] #make copy to not mutate! if not X_now is None: Xs.append(X_now) else: Xs.append([]) Ys = self._cv_plot_Ys[:] #make copy to not mutate! if not Y_now is None: Ys.append(Y_now) else: Ys.append([]) #styles = CV_PLOT_STYLES labels = self._cv_plot_labels + ['Current Trial'] plot_template.plot(Xs, Ys, #styles = styles, labels = labels, figure = figure ) self.cv_plot_figure_widget.update() else: self._app.print_comment("Updating Current vs. Voltage plot.") #get the plot line from the figure FIXME is there an easier way? axis = figure.axes[0] last_line = axis.lines[-1] if not X_now is None: last_line.set_xdata(X_now) if not Y_now is None: last_line.set_ydata(Y_now) self.cv_plot_figure_widget.update()
def build_widgets(self): #FIXME bind some debugging keystrokes to the window #self._win.bind('<Control-f>', lambda e: self._app.) #----------------------------------------------------------------------- #build the left panel left_panel = tk.Frame(self._win) #voltage sweep controls tk.Label(left_panel, text="Voltage Sweep Controls:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") self.vsweep_settings_button = tk.Button(left_panel, text = 'Change Settings', command = self.change_vsweep_settings, width = BUTTON_WIDTH) self.vsweep_settings_button.pack(side='top', anchor="sw") self.vsweep_once_button = tk.Button(left_panel, text = 'Run Once', command = lambda: self.do_vsweep(mode = 'once'), width = BUTTON_WIDTH) self.vsweep_once_button.pack(side='top', anchor="nw") self.vsweep_continually_button = tk.Button(left_panel, text = 'Run Continually', command = lambda: self.do_vsweep(mode = 'continual'), width = BUTTON_WIDTH) self.vsweep_continually_button.pack(side='top', anchor="nw") self.vsweep_stop_button = tk.Button(left_panel, text = 'Stop', command = self.vsweep_stop, state = 'disabled', width = BUTTON_WIDTH) self.vsweep_stop_button.pack(side='top', anchor="nw") #build the capture settings dialog self.vsweep_settings_dialog = VoltageSweepSettingsDialog(self._win) self.vsweep_settings_dialog.withdraw() #finish the left panel left_panel.pack(fill='y',expand='no',side='left', padx = 10) #----------------------------------------------------------------------- #build the middle panel - a tabbed notebook mid_panel = tk.Frame(self._win) #mid_panel.pack(fill='both', expand='yes',side='left') nb = ttk.Notebook(mid_panel) nb.pack(fill='both', expand='yes',side='right') tab1 = tk.Frame(nb) tab1.pack(fill='both', expand='yes',side='right') nb.add(tab1, text = "Current vs. Voltage") #create an tk embedded figure for the current vs. voltage display self.cv_plot_template = CurrentVoltagePlot() self.cv_plot_template.configure(title = CV_PLOT_TITLE) self.cv_plot_figure_widget = EmbeddedFigure(tab1, figsize = CV_PLOT_FIGSIZE) self.cv_plot_figure_widget.pack(side='top',fill='both', expand='yes') self._update_cv_plot() #make an empty plot self.replot_cv_button = tk.Button(tab1,text='Replot',command = self.replot_cv, state='normal', width = BUTTON_WIDTH) self.replot_cv_button.pack(side='left',anchor="sw") self.clear_cv_button = tk.Button(tab1,text='Clear',command = self.clear_data, state='normal', width = BUTTON_WIDTH) self.clear_cv_button.pack(side='left',anchor="sw") self.export_data_button = tk.Button(tab1, text ='Export Data', command = self.export_data, state = 'disabled', width = BUTTON_WIDTH) self.export_data_button.pack(side='left',anchor="sw") #finish builing the middle pannel mid_panel.pack(fill='both', expand='yes',side='left') #----------------------------------------------------------------------- #build the right panel right_panel = tk.Frame(self._win) #Status variable display #tk.Label(right_panel, pady = SECTION_PADY).pack(side='top',fill='x', anchor="nw") #tk.Label(right_panel, text="Status:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") #self.condition_fields = ConditionFields(right_panel) #self.condition_fields.pack(side='top', anchor="w", expand='no') # Events text display tk.Label(right_panel, pady = SECTION_PADY).pack(side='top',fill='x', anchor="nw") tk.Label(right_panel, text="Events Monitoring:", font = HEADING_LABEL_FONT).pack(side='top',anchor="w") self.text_display = TextDisplayBox(right_panel, text_width = TEXTBOX_WIDTH, buffer_size = TEXTBOX_BUFFER_SIZE, ) self.text_display.pack(side='top',fill='both',expand='yes') #finish building the right panel right_panel.pack(fill='both', expand='yes',side='right', padx = 10)
def __init__(self, parent): Frame.__init__(self, parent) self.figure_widget = EmbeddedFigure(self, figsize=FIGSIZE) self.setup()
class DataPlotter(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.figure_widget = EmbeddedFigure(self, figsize=FIGSIZE) self.setup() def pack(self, **kwargs): self.figure_widget.pack(side='right',fill='both', expand='yes') Frame.pack(self,**kwargs) def setup(self): figure = self.figure_widget.get_figure() figure.clear() self.suptitle = figure.suptitle(DEFAULT_SUPTITLE) #temperature plot self.plot_ax1 = ax1 = figure.add_subplot(311) self.plot_line0, = ax1.plot([],[],'r-', label="measurementA") self.plot_line1, = ax1.plot([],[],'b-', label="measurementB") self.plot_line2, = ax1.plot([],[],'m-', label="measurementC") ax1.set_ylabel("Temperature ($^{\circ}$C)", fontproperties=LABEL_FONT_PROP) #setpoint plot self.plot_line3, = ax1.plot([],[],'r--', label="setpointA") self.plot_line4, = ax1.plot([],[],'b--', label="setpointB") #finish formatting the first axes ax1.set_xlim(0, 1) ax1.set_ylim(0, 30) ax1.get_xaxis().set_ticklabels([]) ax1.tick_params(axis='both', which='major', labelsize=LABEL_FONT_SIZE) ax1.tick_params(axis='both', which='minor', labelsize=LABEL_FONT_SIZE-2) #PID output self.plot_ax2 = ax2 = figure.add_subplot(312) self.plot_line5, = ax2.plot([],[],'r-', label="Chan A") self.plot_line6, = ax2.plot([],[],'b-', label="Chan B") ax2.set_ylabel("PID Output (duty cycle)", fontproperties=LABEL_FONT_PROP) #finish formatting the second axes ax2.set_xlim(0, 1) ax2.set_ylim(-1.1, 1.1) ax2.get_xaxis().set_ticklabels([]) ax2.tick_params(axis='both', which='major', labelsize=LABEL_FONT_SIZE) ax2.tick_params(axis='both', which='minor', labelsize=LABEL_FONT_SIZE-2) #Voltage self.plot_ax3 = ax3 = figure.add_subplot(313) self.plot_line7, = ax3.plot([],[],'c-') #finish formatting the third axes #ax3.set_xlabel("Time (seconds)", fontproperties=LABEL_FONT_PROP) ax3.set_ylabel("Voltage", fontproperties=LABEL_FONT_PROP) ax3.set_xlim(0, 1) ax3.set_ylim(-0.5, 0.5) ax3.tick_params(axis='both', which='major', labelsize=LABEL_FONT_SIZE) ax3.tick_params(axis='both', which='minor', labelsize=LABEL_FONT_SIZE-2) self.figure_widget.update() def update(self, data): t = array(data['timestamp']) if len(t) == 0: #skip update for empty data return t -= t[0] #Temperature Plot #line 0 y0 = array(data['temperatureA_measured']) self.plot_line0.set_xdata(t) self.plot_line0.set_ydata(y0) #line 1 y1 = array(data['temperatureB_measured']) self.plot_line1.set_xdata(t) self.plot_line1.set_ydata(y1) #line 2 y2 = array(data['temperatureC_measured']) self.plot_line2.set_xdata(t) self.plot_line2.set_ydata(y2) #line 3 y3 = array(data['temperatureA_target']) self.plot_line3.set_xdata(t) self.plot_line3.set_ydata(y3) #line 4 y4 = array(data['temperatureB_target']) self.plot_line4.set_xdata(t) self.plot_line4.set_ydata(y4) #adjust the plot window y_min = min(y0.min(),y1.min(),y2.min(), y3.min(), y4.min()) y_max = max(y0.max(),y1.max(),y2.max(), y3.max(), y4.max()) self.plot_ax1.set_ylim(y_min*0.9, y_max*1.1,) self.plot_ax1.set_xlim(0,t[-1]*1.1) self.plot_ax1.legend(loc="upper left", prop = LEGEND_FONT_PROP) #PID output plot y5 = array(data['chanA_output']) self.plot_line5.set_xdata(t) self.plot_line5.set_ydata(y5) y6 = array(data['chanB_output']) self.plot_line6.set_xdata(t) self.plot_line6.set_ydata(y6) self.plot_ax2.set_xlim(0, t[-1]*1.1) self.plot_ax2.legend(loc="upper left", prop = LEGEND_FONT_PROP) #obtain voltage y7 = array(data['voltage']) self.plot_line7.set_xdata(t) self.plot_line7.set_ydata(y7) y_min = y7.min() y_max = y7.max() if y_min < 0: y_min *= 1.1 else: y_min *= 0.9 if y_max > 0: y_max *= 1.1 else: y_max *= 0.9 self.plot_ax3.set_ylim(y_min, y_max,) self.plot_ax3.set_xlim(0, t[-1]*1.1) #done self.figure_widget.update() def change_title(self, new_title): figure = self.figure_widget.get_figure() figure.texts.remove(self.suptitle) self.suptitle = figure.suptitle(new_title) self.figure_widget.update()
class GUI: def __init__(self, application): self.app = application #signal that experiment is running self.experiment_mode = False self.app.print_comment("Starting GUI interface:") self.app.print_comment("please wait while the application loads...") #build the GUI interface as a seperate window win = tk.Tk() Pmw.initialise(win) #initialize Python MegaWidgets win.withdraw() win.wm_title(WINDOW_TITLE) win.focus_set() #put focus on this new window self.win = win #handle the user hitting the 'X' button self.win.protocol("WM_DELETE_WINDOW", self._close) #FIXME bind some debugging keystrokes to the window #self.win.bind('<Control-f>', lambda e: self.app.force_experiment()) #build the left panel left_panel = tk.Frame(win) #capture controls tk.Label(left_panel, text="Capture Controls:", font = "Helvetica 14 bold").pack(side='top',fill='x', anchor="nw") self.change_settings_button = tk.Button(left_panel,text='Change Settings',command = self.change_settings) self.change_settings_button.pack(side='top',fill='x', anchor="sw") self.run_continually_button = tk.Button(left_panel,text='Run Continually',command = self.run_continually) self.run_continually_button.pack(side='top',fill='x', anchor="nw") self.stop_button = tk.Button(left_panel,text='Stop',command = self.stop, state='disabled') self.stop_button.pack(side='top',fill='x', anchor="nw") self.run_once_button = tk.Button(left_panel,text='Run Once',command = self.run_once) self.run_once_button.pack(side='top',fill='x', anchor="nw") self.export_data_button = tk.Button(left_panel,text='Export Data',command = self.export_data, state='disabled') self.export_data_button.pack(side='bottom',anchor="sw") left_panel.pack(fill='y',expand='no',side='left', padx = 10) #create an tk embedded figure for temperature display mid_panel = tk.Frame(win) self.temperature_plot_template = TemperaturePlot() self.temperature_figure_widget = EmbeddedFigure(mid_panel, figsize=TEMPERATURE_FIGSIZE) self.temperature_figure_widget.pack(side='left',fill='both', expand='yes') mid_panel.pack(fill='both', expand='yes',side='left') #build the right panel right_panel = tk.Frame(win) self.text_display = TextDisplayBox(right_panel,text_height=15, buffer_size = TEXT_BUFFER_SIZE) self.text_display.pack(side='left',fill='both',expand='yes') right_panel.pack(fill='both', expand='yes',side='right') #build the confirmation dialog self.settings_dialog = SettingsDialog(self.win) self.settings_dialog.withdraw() self._load_settings() #run modes self._is_running = False def launch(self): #run the GUI handling loop IgnoreKeyboardInterrupt() self.win.deiconify() self.win.mainloop() NoticeKeyboardInterrupt() def change_settings(self): self.app.print_comment("changing capture settings...") self.settings_dialog.activate() def run_continually(self): #cache the GUI settings FIXME - is this necessary? self._cache_settings() #disable all the buttons, except the stop button self.run_once_button.config(state='disabled') self.run_continually_button.config(state='disabled') self.stop_button.config(state='normal') self._is_running = True self._run_continually_loop() def _run_continually_loop(self): if self._is_running: self.run_once() run_interval = int(1000*float(self.settings_dialog.form['run_interval'])) #convert to milliseconds #reschedule loop self.win.after(run_interval,self._run_continually_loop) else: #enable all the buttons, except the stop button self.run_once_button.config(state='normal') self.run_continually_button.config(state='normal') self.stop_button.config(state='disabled') #do not reschedule loop def run_once(self): self.app.acquire_temperature_sample() self._update_temperature_plot() self.export_data_button.config(state='normal') #data can now be exported def stop(self): self._is_running = False def export_data(self): self.app.print_comment("Exporting data...") dt_now = datetime.datetime.utcnow() dt_now_str = dt_now.strftime("%Y-%m-%d-%H_%m_%S") default_filename = "%s_temperature.csv" % (dt_now_str,) fdlg = SaveFileDialog(self.win,title="Save Temperature Data") userdata_path = self.app.config['paths']['data_dir'] filename = fdlg.go(dir_or_file = userdata_path, pattern="*.csv", default=default_filename, key = None ) if not filename: return #abort delim = "," comment_prefix = "#" eol = "\n" with open(filename, 'w') as f: #write header f.write(comment_prefix) keys = self.app.temperature_samples.keys() f.write(delim.join(keys)) f.write(eol) vals = self.app.temperature_samples.values() D = np.vstack(vals).transpose() np.savetxt(f, D, fmt=DATA_FORMAT, delimiter=delim) def _update_temperature_plot(self): figure = self.temperature_figure_widget.get_figure() figure.clear() t = np.array(self.app.timestamps) t -= t[0] t /= 3600.0 Xs = [] Ys = [] for key,temp_list in self.app.temperature_samples.items(): Xs.append(t) Ys.append(temp_list) self.temperature_plot_template.plot(Xs, Ys, figure = figure ) self.temperature_figure_widget.update() # def wait_on_experiment(self): # if self.app.check_experiment_completed(): # self.app.shutdown_experiment() # self.win.after(WAIT_DELAY,self.wait_on_experiment_shutdown) # else: # self.win.after(WAIT_DELAY,self.wait_on_experiment) def print_to_text_display(self, text, eol='\n'): self.text_display.print_text(text, eol=eol) def _load_settings(self): if os.path.exists(SETTINGS_FILEPATH): self.app.print_comment("loading from settings file '%s'" % SETTINGS_FILEPATH) settings = shelve.open(SETTINGS_FILEPATH) self.settings_dialog.form['run_interval'] = settings.get('run_interval', DEFAULT_RUN_INTERVAL) settings.close() else: self.app.print_comment("failed to find settings file '%s'" % SETTINGS_FILEPATH) def _cache_settings(self): self.app.print_comment("caching to settings file '%s'" % SETTINGS_FILEPATH) settings = shelve.open(SETTINGS_FILEPATH) settings['run_interval'] = self.settings_dialog.form['run_interval'] settings.close() def _close(self): #cache the GUI settings FIXME - is this necessary? self._cache_settings() self.win.destroy()