def __init__(self): self.data_x = [] self.data_y = [] self.data_i = [] self.data_v = [] self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(550, 700) self.window.connect("delete_event", self.destroy) self.window.connect("destroy", self.destroy) self.vbox = gtk.VBox(False, 0) self.window.add(self.vbox) self.plotfig_i = Figure(figsize=(100, 100), dpi=75) self.plotfig_v = Figure(figsize=(100, 100), dpi=75) self.plotax_i = self.plotfig_i.add_subplot(111) self.plotax_v = self.plotfig_v.add_subplot(111) self.plotlines_i = self.plotax_i.plot(self.data_x, self.data_i, ".") self.plotlines_v = self.plotax_v.plot(self.data_x, self.data_v, ".") self.plotax_i.set_ylim(-15, 15) self.plotax_v.set_ylim(0, 178) self.plotcanvas_i = FigureCanvasGTK(self.plotfig_i) self.plotcanvas_v = FigureCanvasGTK(self.plotfig_v) self.plotcanvas_i.show() self.plotcanvas_v.show() self.vbox.pack_start(self.plotcanvas_i, True, True, 0) self.vbox.pack_end(self.plotcanvas_v, True, True, 0) self.vbox.show()
def __init__(self): self.data_x = [] self.data_y = [] self.data_i = [] self.data_v = [] self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(550, 700) self.window.connect("delete_event", self.destroy) self.window.connect("destroy", self.destroy) self.vbox = gtk.VBox(False, 0) self.window.add(self.vbox) self.plotfig_i = Figure(figsize=(100, 100), dpi=75) self.plotfig_v = Figure(figsize=(100, 100), dpi=75) self.plotax_i = self.plotfig_i.add_subplot(111) self.plotax_v = self.plotfig_v.add_subplot(111) self.plotlines_i = self.plotax_i.plot(self.data_x, self.data_i, '.') self.plotlines_v = self.plotax_v.plot(self.data_x, self.data_v, '.') self.plotax_i.set_ylim(-15, 15) self.plotax_v.set_ylim(0, 178) self.plotcanvas_i = FigureCanvasGTK(self.plotfig_i) self.plotcanvas_v = FigureCanvasGTK(self.plotfig_v) self.plotcanvas_i.show() self.plotcanvas_v.show() self.vbox.pack_start(self.plotcanvas_i, True, True, 0) self.vbox.pack_end(self.plotcanvas_v, True, True, 0) self.vbox.show()
def __init__(self): self.data_x = [] self.data_y = [] self.data_i = [] self.data_v = [] self.data_x.append([0]) self.data_y.append([0]) self.data_i.append([0]) self.data_v.append([0]) self.colors = ['r', 'b', 'c', 'm', 'g', 'y'] self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(550, 700) self.window.connect("delete_event", self.destroy) self.window.connect("destroy", self.destroy) self.vbox = [] self.vbox.append(gtk.VBox(False, 0)) self.hbox = gtk.HBox(False, 0) self.hbox.pack_start(self.vbox[0], True, True, 0) self.window.add(self.hbox) self.plotfig_i = Figure(figsize=(100, 100), dpi=75) self.plotfig_v = Figure(figsize=(100, 100), dpi=75) self.plotax_i = [] self.plotax_v = [] self.plotax_i.append(self.plotfig_i.add_subplot(111)) self.plotax_v.append(self.plotfig_v.add_subplot(111)) self.plotlines_i = [] self.plotlines_v = [] self.plotlines_i.append(self.plotax_i[0].plot(self.data_x[0], self.data_i[0], '.')) self.plotlines_v.append(self.plotax_v[0].plot(self.data_x[0], self.data_v[0], '.')) self.plotax_i[0].set_ylim(-10, 10) self.plotax_v[0].set_ylim(0, 178) self.plotcanvas_i = [] self.plotcanvas_v = [] self.plotcanvas_i.append(FigureCanvasGTK(self.plotfig_i)) self.plotcanvas_v.append(FigureCanvasGTK(self.plotfig_v)) self.plotcanvas_i[0].show() self.plotcanvas_v[0].show() self.vbox[0].pack_start(self.plotcanvas_i[0], True, True, 0) self.vbox[0].pack_end(self.plotcanvas_v[0], True, True, 0) self.vbox[0].show() self.hbox.show()
def drawDefault(self): logging.debug('>>') self.axis = self.figure.add_subplot(111) self.axis.set_xlabel('Yepper') self.axis.set_ylabel('Flabber') self.axis.set_title('An Empty Graph') self.axis.grid(True) self.canvas.destroy() self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea self.canvas.show() self.vbox.pack_start(self.canvas, True, True) logging.debug('<<')
def setup_canvas(remote): """ Setup the canvas, for use by the other functions that popluate it with plots. """ global f, canvas, degreeChar, num_plots degreeChar = u'\N{DEGREE SIGN}' num_plots = 38 plot_height = 200 f = Figure(dpi=100) f.hold(False) if remote == True: canvas = FigureCanvasGTK(f) # a gtk.DrawingArea else: canvas = FigureCanvasGTKAgg(f) # a gtk.DrawingArea # the size request sets the size of the area for the plots. Second number is the height canvas.set_size_request(800, num_plots * plot_height) app.viewport_matplotlib.add(canvas) canvas.show()
def drawPlot(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None, xzones=None, ylimits=None, y1_linewidth=None): logging.debug('>>') logging.debug("Type: plot | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) logging.debug('xlabel: ' + str(xlabel) + ' | ylabel: ' + str(ylabel) + ' | title: ' + str(title)) self.removeVboxChildren() figure = plt.Figure() logging.debug("Figure: %s" % str(figure)) #figure.clf() i = 0 for value in xvalues: if i < 1: logging.debug("i: %d, value: (%s) %s %s" % (i, str(value), str(xvalues), str(yvalues))) axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) line = axis.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis plotted, Line: %s" % str(line)) if y1_linewidth is not None: line[0].set_linewidth(y1_linewidth) linewidth = line[0].get_linewidth() axis.grid(True) logging.debug("Axis grid on") for tl in axis.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Ticklabels color set") #Draw zones on graph, eg for each lap if xzones is not None: logging.debug("Setting xzones") for xzone in xzones: if xzones.index(xzone) % 2: zonecolor = 'b' else: zonecolor = 'g' axis.axvspan(xzone[0], xzone[1], alpha=0.25, facecolor=zonecolor) maxX = max(xvalues[i]) if i >= 1: ax2 = axis.twinx() logging.debug("Axis2: Axis: %s" % str(ax2)) ax2.plot(xvalues[i], yvalues[i], color=color[i]) logging.debug("Axis2: plotted") for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[i]) logging.debug("Axis2: Ticklabels color set") maxXt = max(xvalues[i]) if maxXt > maxX: maxX = maxXt axis.set_xlabel(xlabel[i]) logging.debug("X label set") i += 1 axis.set_xlim(0, maxX) if (len(xvalues) > 1): axis.set_title("%s vs %s" % (ylabel[0], ylabel[1])) else: axis.set_title("%s" % (ylabel[0])) ylim_min, ylim_max = axis.get_ylim() if ylimits is not None: logging.debug("Using ylimits: %s" % str(ylimits)) if ylimits[0] is not None: ylim_min = ylimits[0] if ylimits[1] is not None: ylim_max = ylimits[1] axis.set_ylim(ylim_min, ylim_max) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Canvas: %s" % str(canvas)) canvas.show() self.vbox.pack_start(canvas, True, True) toolbar = NavigationToolbar(canvas, self.window) self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<') return { 'y1_min': ylim_min, 'y1_max': ylim_max, 'y1_linewidth': linewidth }
class DataPlotter: def __init__(self): self.data_x = [] self.data_y = [] self.data_i = [] self.data_v = [] self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(550, 700) self.window.connect("delete_event", self.destroy) self.window.connect("destroy", self.destroy) self.vbox = gtk.VBox(False, 0) self.window.add(self.vbox) self.plotfig_i = Figure(figsize=(100, 100), dpi=75) self.plotfig_v = Figure(figsize=(100, 100), dpi=75) self.plotax_i = self.plotfig_i.add_subplot(111) self.plotax_v = self.plotfig_v.add_subplot(111) self.plotlines_i = self.plotax_i.plot(self.data_x, self.data_i, '.') self.plotlines_v = self.plotax_v.plot(self.data_x, self.data_v, '.') self.plotax_i.set_ylim(-15, 15) self.plotax_v.set_ylim(0, 178) self.plotcanvas_i = FigureCanvasGTK(self.plotfig_i) self.plotcanvas_v = FigureCanvasGTK(self.plotfig_v) self.plotcanvas_i.show() self.plotcanvas_v.show() self.vbox.pack_start(self.plotcanvas_i, True, True, 0) self.vbox.pack_end(self.plotcanvas_v, True, True, 0) self.vbox.show() def destroy(self, widget, data=None): gtk.main_quit() sigint_handler(0, 0) def data_adjust(self): x = -1 y = -1 self.data_i = [] self.data_v = [] self.data_y.pop(0) self.data_x.pop(0) for i in range(len(self.data_y)): if (i % 2 == 0): self.data_y[i] *= (170000 / 4300.) / 1000 if (y != -1): self.data_v.append((y + self.data_y[i]) / 2) else: self.data_v.append(self.data_y[i]) self.data_v.append(self.data_y[i]) y = self.data_y[i] else: self.data_y[i] -= 2500 self.data_y[i] /= 100 if (x != -1): self.data_i.append((x + self.data_y[i]) / 2) else: self.data_i.append(self.data_y[i]) self.data_i.append(self.data_y[i]) x = self.data_y[i] power = 0 # Perform a numerical integration on this power for i in range(len(self.data_i)): power += abs(self.data_i[i]) * self.data_v[i] # Divide by the time length for the average power power /= (len(self.data_y)) # Divide by two since we took the absolute value of # both I and V #power /= 2. # Subtract our "idle" power value #power -= 18.30 #if (power < 0): # power = 0 # Push this power to our list powers.insert(0, power) # Pop off the first if we've reached 6 powers if (len(powers) == 6): powers.pop() # Print out current list of powers print "Power:", avgpower = 0 for i in range(len(powers)): if (i == 0): print "[%f]" % powers[i], else: print "%f" % powers[i], avgpower += powers[i] print "watts" # Calculate and print the average power avgpower /= (len(powers) + 0.0) print "Average Power: %f" % avgpower, "watts" print "Latest Power Reading: %f" % power, "watts\n\n" def replot(self): if (dataLog.new_data > 0): self.data_x = dataLog.back_axis_time[:] self.data_y = dataLog.back_axis_voltage[:] self.data_adjust() self.plotlines_i[0].set_xdata(self.data_x) self.plotlines_v[0].set_xdata(self.data_x) self.plotlines_i[0].set_ydata(self.data_i) self.plotlines_v[0].set_ydata(self.data_v) self.plotlines_i[0].set_color('r') self.plotlines_v[0].set_color('r') self.plotax_i.set_xlim(self.data_x[0], self.data_x[-1]) self.plotax_v.set_xlim(self.data_x[0], self.data_x[-1]) dataLog.new_data = 0 self.plotcanvas_i.draw_idle() self.plotcanvas_v.draw_idle() return True def main(self): self.window.show() gobject.idle_add(self.replot) gtk.main()
def create_ui(self): self.widget = gtk.Assistant() self.widget.connect("prepare", self.assistant_prepared) self.widget.connect("cancel", self.cancel_button_clicked) self.widget.connect("close", self.close_button_clicked) self.widget.connect("apply", self.apply_button_clicked) # # Introduction # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_INTRO) self.widget.set_page_title(box, "Introduction") content = ('This wizard will guide you through the process of ' 'calibrating the high-voltage reference load feedback ' 'measurement circuit. This feedback circuit is used to ' 'measure the output voltage of the amplifier on the control' 'board.\n\nSee ' r'<a href="http://microfluidics.utoronto.ca/trac/dropbot/wiki/Control board calibration#high-voltage-attenuation-calibration">' 'here</a> for more details.') label = gtk.Label(content) label.set_use_markup(True) label.set_line_wrap(True) image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/reference_feedback_intro.png') image.set_from_file(str(img_path)) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Connect hardware # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Connect hardware") label = gtk.Label(' - Connect DropBot "<tt>Out to Amp</tt>" to amplifier input.\n' ' - Use T-splitter to connect amplifier output to:\n' ' 1) DropBot "<tt>In from Amp</tt>".\n' ' 2) Oscilloscope input.') image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/reference_feedback_setup.png') image.set_from_file(str(img_path)) label.set_line_wrap(True) label.set_use_markup(True) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Select frequencies # minimum = self.control_board.min_waveform_frequency maximum = self.control_board.max_waveform_frequency form = Form.of( Integer.named('start_frequency').using( default=minimum, optional=True, validators=[ValueAtLeast(minimum=minimum), ]), Integer.named('end_frequency').using( default=maximum, optional=True, validators=[ValueAtLeast(minimum=minimum), ]), Integer.named('number_of_steps').using( default=10, optional=True, validators=[ValueAtLeast(minimum=2), ]), ) box = gtk.HBox() self.form_view = create_form_view(form) self.form_view.form.proxies.connect('changed', display) box.pack_start(self.form_view.widget, fill=False, padding=40) self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Select calibration frequencies") self.widget.set_page_complete(box, True) # # Record measurements # box1 = gtk.VBox() self.widget.append_page(box1) self.widget.set_page_type(box1, gtk.ASSISTANT_PAGE_PROGRESS) self.widget.set_page_title(box1, "Record measurements") self.measurements_label = gtk.Label('Ready') self.measurements_label.set_line_wrap(True) self.measure_progress = gtk.ProgressBar() self.measure_progress.set_size_request(300, 40) box1.pack_start(self.measurements_label, True, True, 0) box1.pack_start(self.measure_progress, expand=False, fill=False, padding=15) self.box1 = box1 # # Confirm fitted parameters # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONFIRM) self.widget.set_page_title(box, "Confirm fitted parameters") figure = Figure(figsize=(14, 8), dpi=60) self.canvas = FigureCanvasGTK(figure) toolbar = NavigationToolbar(self.canvas, self.widget) self.axis = figure.add_subplot(111) box.pack_start(self.canvas) box.pack_start(toolbar, False, False) self.widget.set_page_complete(box, True) # # Summary # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_SUMMARY) self.widget.set_page_title(box, "Summary") label = gtk.Label('Calibration of reference load feedback circuit is ' 'complete. The high-voltage output from amplifier ' 'should now be measured accurately by the control ' 'board.') label.set_line_wrap(True) box.pack_start(label, True, True, 0) self.widget.set_page_complete(box, True)
def drawBars(self, xvalues, yvalues, xlabel, ylabel, title, color): logging.debug('>>') logging.debug("Type: bars | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) numCols = len(xvalues[0]) xmod = 0.4 self.showGraph = False axis = figure.add_subplot(111) logging.debug("Axis: %s" % str(axis)) if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 logging.debug("One axis, barWidth %f, barOffset %f" % (barWidth, barOffset)) elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 logging.debug("Twin axes, barWidth %f, barOffset %f" % (barWidth, barOffset)) else: #Error logging.debug("Error: invalid number of axes") return axis.set_xlabel(xlabel[0]) axis.set_ylabel(ylabel[0]) logging.debug("Labels set x: %s, y: %s" % (xlabel[0], ylabel[0])) xvals = [x + barOffset for x in range(0, numCols)] yvals = [0] * numCols for i in range(0, numCols): yval = yvalues[0][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Drawing bars") axis.bar(xvals, yvals, barWidth, color=color[0], align='edge') else: #Only zero results logging.debug("No results to draw") pass axis.grid(True) axis.set_title("%s" % (title[0])) logging.debug("Setting title to: %s" % title[0]) for tl in axis.get_yticklabels(): logging.debug("Setting ticklabel color %s" % color[0]) tl.set_color('%s' % color[0]) if len(xvalues) == 2: #Display twin axis ax2 = axis.twinx() logging.debug("Axis 2: Twin axis: %s " % str(ax2)) xvals = [x + barOffset + barWidth for x in range(0, numCols)] for i in range(0, numCols): yval = yvalues[1][i] if float(yval) > 0.0: self.showGraph = True else: yval = self.NEARLY_ZERO yvals[i] = yval if self.showGraph: logging.debug("Axis 2: Drawing bars") ax2.bar(xvals, yvals, barWidth, color=color[1], align='edge') logging.debug("Axis 2: Label set y: %s" % (ylabel[1])) ax2.set_ylabel(ylabel[1]) else: #Only zero results logging.debug("Axis 2: No results to draw") pass for tl in ax2.get_yticklabels(): tl.set_color('%s' % color[1]) logging.debug("Axis 2: Setting ticklabel color %s" % color[1]) _title = "%s vs %s" % (title[0], title[1]) logging.debug("Axis 2: Setting title to: %s" % _title) axis.set_title(_title) logging.debug("Setting x ticks") tickLocations = [x + 0.5 for x in xrange(0, numCols)] axis.set_xticks(tickLocations) axis.set_xticklabels(xvalues[0]) logging.debug("Setting x limits") axis.set_xlim(0, numCols) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea logging.debug("Got canvas: %s" % (str(canvas))) canvas.show() logging.debug("Adding canvas to vbox") self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<')
def setup_canvas(self): self._canvas = FigureCanvasGTK(self.figure)
class HurricaneUI: def __init__(self): gladefile = "HurricaneUI.glade" builder = gtk.Builder() builder.add_from_file(gladefile) self.window = builder.get_object("mainWindow") builder.connect_signals(self) self.figure = Figure(figsize=(10, 10), dpi=75) self.axis = self.figure.add_subplot(111) self.lat = 50 self.lon = -100 self.globe = globDisp.GlobeMap(self.axis, self.lat, self.lon) self.canvas = FigureCanvasGTK(self.figure) self.canvas.show() self.canvas.set_size_request(500, 500) self.globeview = builder.get_object("map") self.globeview.pack_start(self.canvas, True, True) self.navToolbar = NavigationToolbar(self.canvas, self.globeview) self.navToolbar.lastDir = '/var/tmp' self.globeview.pack_start(self.navToolbar) self.navToolbar.show() self.gridcombo = builder.get_object("gridsize") cell = gtk.CellRendererText() self.gridcombo.pack_start(cell, True) self.gridcombo.add_attribute(cell, 'text', 0) #self.gridcombo.set_active(2) # read menu configuration self.gridopt = builder.get_object("gridopt").get_active() self.chkDetected = builder.get_object("detectedopt") self.detectedopt = self.chkDetected.get_active() self.chkHurricane = builder.get_object("hurricaneopt") self.hurricaneopt = self.chkHurricane.get_active() model = builder.get_object("liststore1") index = self.gridcombo.get_active() self.gridsize = model[index][0] radio = [ r for r in builder.get_object("classifieropt1").get_group() if r.get_active() ][0] self.sClassifier = radio.get_label() self.start = builder.get_object("startdate") self.end = builder.get_object("enddate") self.chkUndersample = builder.get_object("undersample") self.chkGenKey = builder.get_object("genKey") # disable unimplemented classifier selection builder.get_object("classifieropt2").set_sensitive(False) builder.get_object("classifieropt3").set_sensitive(False) builder.get_object("classifieropt4").set_sensitive(False) self.btnStore = builder.get_object("store") self.datapath = 'GFSdat' self.trackpath = 'tracks' builder.get_object("btnDatapath").set_current_folder(self.datapath) builder.get_object("btnTrackpath").set_current_folder(self.trackpath) self.btnDetect = builder.get_object("detect") # current operation status self.stormlocs = None self.detected = None self.clssfr = None # for test drawing functions if os.path.exists('demo.detected'): with open('demo.detected', 'r') as f: self.detected = pickle.load(f) self.stormlocs = pickle.load(f) self.chkHurricane.set_label( str(self.stormlocs.shape[0]) + " Hurricanes") self.chkDetected.set_label( str(self.detected.shape[0]) + " Detected") self.setDisabledBtns() # draw Globe self.drawGlobe() def setDisabledBtns(self): self.chkDetected.set_sensitive(self.detected != None) self.chkHurricane.set_sensitive(self.stormlocs != None) self.btnStore.set_sensitive(self.clssfr != None) self.btnDetect.set_sensitive(self.clssfr != None) def drawGlobe(self): self.globe.drawGlobe(self.gridsize, self.gridopt) if self.hurricaneopt: self.globe.drawHurricanes(self.stormlocs) if self.detectedopt: self.globe.fillGrids(self.detected) def main(self): self.window.show_all() gtk.main() def redraw(self): self.axis.cla() self.drawGlobe() self.canvas.draw_idle() def gtk_main_quit(self, widget): gtk.main_quit() ############################################################################### # # utility functions (dialogs) # def getFilenameToRead(self, stitle, save=False, filter='all'): chooser = gtk.FileChooserDialog( title=stitle, parent=self.window, action=gtk.FILE_CHOOSER_ACTION_OPEN if not save else gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN if not save else gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) if filter == 'mat' or filter == 'mdat': filter = gtk.FileFilter() filter.set_name("Matrix files") filter.add_pattern("*.mat") chooser.add_filter(filter) if filter == 'svm': filter = gtk.FileFilter() filter.set_name("SVM") filter.add_pattern("*.svm") chooser.add_filter(filter) if filter == 'dat' or filter == 'mdat': filter = gtk.FileFilter() filter.set_name("Data") filter.add_pattern("*.dat") chooser.add_filter(filter) filter = gtk.FileFilter() filter.set_name("All files") filter.add_pattern("*") chooser.add_filter(filter) chooser.set_current_folder(os.getcwd()) response = chooser.run() if response == gtk.RESPONSE_OK: filen = chooser.get_filename() else: filen = None chooser.destroy() return filen def showMessage(self, msg): md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, msg) md.run() md.destroy() ############################################################################### # # read data files and convert into a training matrix input # def on_btnTrackpath_current_folder_changed(self, widget): self.trackpath = widget.get_current_folder() def on_btnDatapath_current_folder_changed(self, widget): self.datapath = widget.get_current_folder() def on_createMat_clicked(self, widget): filen = self.getFilenameToRead("Save converted matrix for training", True, filter='mat') if filen is not None: start = self.start.get_text() end = self.end.get_text() bundersmpl = self.chkUndersample.get_active() bgenkey = self.chkGenKey.get_active() ### FIX ME: currently gridsize for classification is fixed 1 (no clustering of grids - 2x2) if os.path.exists(filen): os.unlink( filen ) # createMat append existing file, so delete it if exist gdtool.createMat(self.datapath, self.trackpath, start, end, store=filen, undersample=bundersmpl, genkeyf=bgenkey) self.showMessage("Matrix has been stored to " + filen) ############################################################################### # # train the selected classifier # def on_train_clicked(self, widget): # FOR NOW, only SVM is supported if self.sClassifier == "SVM": filen = self.getFilenameToRead("Open training data", filter='mat') if filen is not None: data = ml.VectorDataSet(filen, labelsColumn=0) self.clssfr = ml.SVM() self.clssfr.train(data) # train finished. need to update button status self.setDisabledBtns() self.showMessage("Training SVM is done.") else: self.showMessage("The classifier is not supported yet!") def on_classifieropt_toggled(self, widget, data=None): self.sClassifier = widget.get_label() ############################################################################### # # Classify on test data # def on_detect_clicked(self, widget): if self.clssfr is not None: filen = self.getFilenameToRead("Open hurricane data", filter='mdat') if filen is not None: fname = os.path.basename(filen) key, ext = os.path.splitext(fname) if ext == '.dat': key = key[1:] # take 'g' out #testData = gdtool.createMat(self.datapath, self.trackpath, key, key) #result = self.clssfr.test(ml.VectorDataSet(testData,labelsColumn=0)) tmpfn = 'f__tmpDetected__' if os.path.exists(tmpfn): os.unlink(tmpfn) # for DEMO, undersampled the normal data -- without undersampling there are too many candidates gdtool.createMat(self.datapath, self.trackpath, key, key, store=tmpfn, undersample=True, genkeyf=True) bneedDel = True else: tmpfn = fname bneedDel = False result = self.clssfr.test( ml.VectorDataSet(tmpfn, labelsColumn=0)) gdkeyfilen = ''.join([tmpfn, '.keys']) with open(gdkeyfilen, 'r') as f: gridkeys = pickle.load(f) self.stormlocs = pickle.load(f) predicted = result.getPredictedLabels() predicted = np.array(map(float, predicted)) self.detected = np.array(gridkeys)[predicted == 1] if bneedDel: os.unlink(tmpfn) os.unlink(gdkeyfilen) snstroms = str(self.stormlocs.shape[0]) sndetected = str(self.detected.shape[0]) self.chkHurricane.set_label(snstroms + " Hurricanes") self.chkDetected.set_label(sndetected + " Detected") self.showMessage(''.join([ sndetected, "/", snstroms, " grids are predicted to have hurricane." ])) if False: with open('demo.detected', 'w') as f: pickle.dump(self.detected, f) pickle.dump(self.stormlocs, f) # test data tested. update buttons self.setDisabledBtns() self.redraw() else: self.showMessage("There is no trained classifier!") ############################################################################### # # load and store trained classifier # def on_load_clicked(self, widget): filen = self.getFilenameToRead("Load Classifier", filter='svm') if filen is not None: #db = shelve.open(filen) #if db.has_key('clssfr'): # self.clssfr = db['clssfr'] #else: # self.showMessage("Cannot find a classifier!") #db.close() #with open(filen, 'wb') as f: # self.clssfr = pickle.load(f) datfn = self.getFilenameToRead("Open Training Data", filter='mat') if datfn is not None: data = ml.VectorDataSet(datfn, labelsColumn=0) self.clssfr = loadSVM(filen, data) ## Why do I need to feed data ??? #self.clssfr = loadSVM(filen,None) ## edited PyML for this # classifier has been loaded. need to update button status self.setDisabledBtns() self.showMessage("The classifier has been loaded!") def on_store_clicked(self, widget): if self.clssfr is not None: filen = self.getFilenameToRead("Store Classifier", True, filter='svm') if filen is not None: #with open(filen, 'wb') as f: # pickle.dump(self.clssfr,f) #db = shelve.open(filen) #db['clssfr'] = self.clssfr #db.close() self.clssfr.save(filen) self.showMessage("The classifier has been saved!") else: self.showMessage("There is no trained classifier!") ############################################################################### # # Display Globe # def on_right_clicked(self, widget): self.lon += 10 # rotate Globe def on_left_clicked(self, widget): self.lon -= 10 # rotate Globe def gridsize_changed_cb(self, widget): model = widget.get_model() index = widget.get_active() if index > -1: self.gridsize = model[index][0] self.redraw() def on_gridopt_toggled(self, widget): self.gridopt = not self.gridopt self.redraw() def on_Hurricane_toggled(self, widget): self.hurricaneopt = not self.hurricaneopt self.redraw() def on_detected_toggled(self, widget): self.detectedopt = not self.detectedopt self.redraw()
def replot(self): if (dataLog.new_data > 0): cindex = dataLog.new_data - 1 # If this is a new meter, add it to our data / plotline arrays while (dataLog.new_data > len(self.data_x)): newMemberID = len(self.data_x) #print "new member!" self.data_x.append([0]) self.data_y.append([0]) self.data_i.append([0]) self.data_v.append([0]) self.vbox.append(gtk.VBox(False, 0)) pi = Figure(figsize=(100, 100), dpi=75) pv = Figure(figsize=(100, 100), dpi=75) self.plotax_i.append(pi.add_subplot(111)) self.plotax_v.append(pv.add_subplot(111)) self.plotlines_i.append(self.plotax_i[newMemberID].plot( self.data_x[newMemberID], self.data_i[newMemberID], '.')) self.plotlines_v.append(self.plotax_v[newMemberID].plot( self.data_x[newMemberID], self.data_v[newMemberID], '.')) self.plotax_i[newMemberID].set_ylim(-10, 10) self.plotax_v[newMemberID].set_ylim(0, 178) self.plotcanvas_i.append(FigureCanvasGTK(pi)) self.plotcanvas_v.append(FigureCanvasGTK(pv)) self.plotcanvas_i[newMemberID].show() self.plotcanvas_v[newMemberID].show() self.vbox[newMemberID].pack_start( self.plotcanvas_i[newMemberID], True, True, 0) self.vbox[newMemberID].pack_end(self.plotcanvas_v[newMemberID], True, True, 0) self.vbox[newMemberID].show() self.hbox.pack_end(self.vbox[newMemberID], True, True, 0) self.hbox.show() powers.append([]) self.data_x[cindex] = dataLog.back_axis_time[cindex][:] self.data_y[cindex] = dataLog.back_axis_voltage[cindex][:] if (len(self.data_x[cindex]) % 2 != 0 or len(self.data_y[cindex]) % 2 != 0): dataLog.new_data = 0 return True #print "index: %d len x: %d len y: %d" % (cindex, len(self.data_x[cindex]), len(self.data_y[cindex])) self.data_adjust(cindex) for i in range(len(self.plotlines_i)): self.plotlines_i[i][0].set_xdata(self.data_x[i]) self.plotlines_v[i][0].set_xdata(self.data_x[i]) self.plotlines_i[i][0].set_ydata(self.data_i[i]) self.plotlines_v[i][0].set_ydata(self.data_v[i]) self.plotlines_i[i][0].set_color(self.colors[i]) self.plotlines_v[i][0].set_color(self.colors[i]) self.plotax_i[cindex].set_xlim(self.data_x[cindex][0], self.data_x[cindex][-1]) self.plotax_v[cindex].set_xlim(self.data_x[cindex][0], self.data_x[cindex][-1]) dataLog.new_data = 0 for i in range(len(self.plotcanvas_i)): self.plotcanvas_i[i].draw_idle() self.plotcanvas_v[i].draw_idle() return True
def draw(self, datalist=None, box=None, figure=None, title=None, y2=False, xgrid=False, ygrid=False): ''' Draw a graph using supplied information into supplied gtk.box datalist = populated graphdata class (required) box = gtk.box object (required) figure = matplotlib figure (optional) if supplied will add graph to this figure title = y2 = return = figure ''' logging.debug('>>') if box is None: logging.error("Must supply a vbox or hbox to display the graph") return #Check if have a graph object if figure is None: #No figure, so create figure figure = plt.figure() self.ax1 = plt.axes() #Reset second axis self.ax2 = None #Remove any existing plots for child in box.get_children(): logging.debug('Removing box child: ' + str(child)) box.remove(child) if datalist is None: logging.debug("drawPlot called with no data") return figure if y2 and self.ax2 is None: self.ax2 = plt.twinx() #Create canvas canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() #Display title etc if datalist.xlabel is not None: plt.xlabel(datalist.xlabel) if title is not None: plt.title(title) #Display grid if y2 and ygrid: self.ax2.grid(True) elif self.ax1 and ygrid: self.ax1.grid(True) plt.gca().xaxis.grid(xgrid) #Removed as now in legend #plt.ylabel(datalist.ylabel) #Determine graph type.... #print "Got graphtype: %s" % datalist.graphType #print datalist.x_values #print datalist.y_values #print datalist.linewidth #print datalist.linecolor #print datalist.ylabel if datalist.graphType == "plot": #Plot data if not y2: #plt.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.linecolor, label=datalist.ylabel ) self.ax1.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.linecolor, label=datalist.ylabel) else: self.ax2.plot(datalist.x_values, datalist.y_values, linewidth=datalist.linewidth, color=datalist.y2linecolor, label=datalist.ylabel) elif datalist.graphType == "bar": if not y2: self.ax1.bar(datalist.x_values, datalist.y_values, datalist.bar_widths, datalist.bar_bottoms, color=datalist.linecolor, label=datalist.ylabel, alpha=0.5) else: self.ax2.bar(datalist.x_values, datalist.y_values, datalist.bar_widths, datalist.bar_bottoms, color=datalist.y2linecolor, label=datalist.ylabel, alpha=0.5) elif datalist.graphType == "vspan": i = 0 while i < len(datalist.x_values): #print datalist.x_values[i] , datalist.bar_widths[i] if not y2: self.ax1.axvspan(datalist.x_values[i], datalist.x_values[i] + datalist.bar_widths[i], alpha=0.15, facecolor=datalist.linecolor) else: self.ax2.axvspan(datalist.x_values[i], datalist.x_values[i] + datalist.bar_widths[i], alpha=0.15, facecolor=datalist.y2linecolor) i += 1 elif datalist.graphType == "hspan": i = 0 while i < len(datalist.x_values): #print datalist.x_values[i] , datalist.y_values[i], datalist.labels[i], datalist.colors[i] if not y2: self.ax1.axhspan(datalist.x_values[i], datalist.y_values[i], alpha=0.25, facecolor=datalist.colors[i], label=datalist.labels[i]) else: self.ax2.axhspan(datalist.x_values[i], datalist.y_values[i], alpha=0.25, facecolor=datalist.colors[i], label=datalist.labels[i]) i += 1 elif datalist.graphType == "date": if not y2: self.ax1.plot_date(datalist.x_values, datalist.y_values, color=datalist.linecolor, label=datalist.ylabel, alpha=0.5) else: self.ax2.plot_date(datalist.x_values, datalist.y_values, color=datalist.y2linecolor, label=datalist.ylabel, alpha=0.5) else: print "Unknown/unimplemented graph type: %s" % datalist.graphType return figure #Set axis limits #plt.axis([datalist.min_x_value, datalist.max_x_value, datalist.min_y_value, datalist.max_y_value]) if self.ax1 is not None: self.ax1.legend(loc='upper left', bbox_to_anchor=(0, 1)) if self.ax2 is not None: self.ax2.legend(loc='upper right', bbox_to_anchor=(1, 1)) #axis.set_xlim(0, data.max_x_value) #axis.set_ylim(0, data.max_y_value) #Display plot box.pack_start(canvas, True, True) logging.debug("<<") return figure
def drawStackedBars(self, xvalues, yvalues, ylabel, title, valuesAreTime=False, colors={}): '''function to draw stacked bars xvalues needs to be a list of lists of strings, e.g. [0]["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] yvalues needs to be a list of dicts e.g. [0]{'Kayak': {'Tue': 10.08, 'Fri': 17.579999999999998, 'Thu': 15.66, 'Sat': 30.619999999999997}, {'Run': {'Mon': 9.65, 'Sun': 15.59}} ''' #TODO tidy logging.debug('>>') logging.debug("Title: %s", (title, )) logging.debug("X values received: %s", str(xvalues)) logging.debug("Y values received: %s", str(yvalues)) self.removeVboxChildren() #Check how many axes to draw if len(xvalues) == 1: #One axis barWidth = 0.8 barOffset = 0.1 elif len(xvalues) == 2: #Twin axes barWidth = 0.4 barOffset = 0.1 else: #Error return keys = yvalues[0].keys() # days of the week numRows = len(keys) numCols = len(xvalues[0]) if numRows == 0: return width = .8 #figure = plt.figure(figsize=(6,4), dpi=72) figure = plt.figure() logging.debug("Figure: %s" % str(figure)) axis = plt.subplot(111) ybottoms = [0] * numCols yheights = [0] * numCols inds = xrange(0, numCols) xvals = [x + barOffset for x in range(0, numCols)] cellText = [] self.showGraph = False for k in colors: if colors[k] == None: colors[k] = '' #Display first axis xticks = [] for key in keys: logging.debug("Day of the week: %s", str(key)) for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[0][key]: height = yvalues[0][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height cellText.append( [self.fmtTableText(x, valuesAreTime[0]) for x in yheights]) if self.showGraph: axis.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results pass axis.set_xticklabels('' * len(xvalues[0])) axis.set_ylabel(ylabel[0]) if len(xvalues) == 1: plt.title(title[0]) axis.legend(loc=0) axis.set_xlim(0, numCols) logging.debug("X values first axis: %s", str(xvals)) logging.debug("Y values first axis: %s", str(yheights)) #Display twin axis if len(xvalues) == 2: self.showGraph = False ax2 = axis.twinx() keys = yvalues[1].keys() ybottoms = [0] * numCols yheights = [self.NEARLY_ZERO] * numCols for key in keys: for ind in inds: ybottoms[ind] += yheights[ind] yheights[ind] = 0.0 #Zero heights color = "#" + colors.get(key, '') if len(color) < 2: color = self.getColor(keys.index(key)) for xvalue in xvalues[0]: index = xvalues[0].index(xvalue) if xvalue in yvalues[1][key]: height = yvalues[1][key][xvalue] if float(height) > 0.0: self.showGraph = True else: height = self.NEARLY_ZERO yheights[index] = height textToAdd = self.fmtTableText(height, valuesAreTime[1]) if textToAdd is not ' ': row = keys.index(key) col = index cellText[row][col] += " | %s" % (self.fmtTableText( height, valuesAreTime[1])) #print "Would add %s to %s %s" % (self.fmtTableText(height, valuesAreTime[1]), index, keys.index(key)) if self.showGraph: xvals = [ x + barOffset + barWidth for x in range(0, numCols) ] #print "ax2", xvals, yheights, ybottoms ax2.bar(xvals, yheights, bottom=ybottoms, width=barWidth, color=color, align='edge', label=key) else: #Only zero results ax2.bar(xvals, [0] * numCols, bottom=[0] * numCols, width=barWidth, color=color, align='edge', label=key) pass ax2.set_xticklabels('' * len(xvalues[1])) ax2.set_xlim(0, numCols) ax2.set_ylabel(ylabel[1]) ax2.legend(loc=0) plt.title("%s vs %s" % (title[0], title[1])) ## try to do some table stuff colLabels = xvalues[0] rowLabels = keys axis.table(cellText=cellText, cellLoc='center', rowLabels=rowLabels, colLabels=colLabels, loc='bottom') plt.subplots_adjust(left=0.15, bottom=0.08 + (0.03 * numRows)) axis.grid(True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() self.vbox.pack_start(canvas, True, True) #toolbar = NavigationToolbar(canvas, self.window) #self.vbox.pack_start(toolbar, False, False) for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) logging.debug('<<')
def create_ui(self): self.widget = gtk.Assistant() self.widget.connect("prepare", self.assistant_prepared) self.widget.connect("cancel", self.cancel_button_clicked) self.widget.connect("close", self.close_button_clicked) self.widget.connect("apply", self.apply_button_clicked) # # Introduction # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_INTRO) self.widget.set_page_title(box, "Introduction") content = ( 'This wizard will guide you through the process of ' 'calibrating the device load feedback measurement circuit. ' 'This feedback circuit is used to measure the impedance ' 'between the actuated area and ground. This impedance is ' 'related to the volume of liquid between the actuated area' '\n\nSee ' r'<a href="http://microfluidics.utoronto.ca/trac/dropbot/wiki/Control board calibration#device-load-impedance-calibration">' 'here</a> for more details.') label = gtk.Label(content) label.set_use_markup(True) label.set_line_wrap(True) image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/impedance_feedback_intro.png') image.set_from_file(str(img_path)) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Connect hardware # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Connect hardware") label = gtk.Label( ' - Connect DropBot "<tt>Out to Amp</tt>" to amplifier input.\n' ' - Connect amplifier output to DropBot "<tt>In from Amp</tt>".\n' ' - Connect DropBot "<tt>0-39</tt>" to test board.') image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/impedance_feedback_setup.png') image.set_from_file(str(img_path)) label.set_line_wrap(True) label.set_use_markup(True) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Select frequencies # form = Form.of( Integer.named('start_frequency').using( default=self.control_board.min_waveform_frequency, optional=True, validators=[ ValueAtLeast( minimum=self.control_board.min_waveform_frequency), ValueAtMost( maximum=self.control_board.max_waveform_frequency) ]), Integer.named('end_frequency').using( default=self.control_board.max_waveform_frequency, optional=True, validators=[ ValueAtLeast( minimum=self.control_board.min_waveform_frequency), ValueAtMost( maximum=self.control_board.max_waveform_frequency) ]), Integer.named('number_of_steps').using(default=10, optional=True, validators=[ ValueAtLeast(minimum=2), ]), Integer.named('RMS_voltage').using( default=min(100, self.control_board.max_waveform_voltage), optional=True, validators=[ ValueAtLeast(minimum=10), ValueAtMost( maximum=self.control_board.max_waveform_voltage) ])) box = gtk.HBox() self.form_view = create_form_view(form) box.pack_start(self.form_view.widget, fill=False, padding=40) self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Select calibration frequencies") self.widget.set_page_complete(box, True) ## # Record measurements # box1 = gtk.VBox() self.widget.append_page(box1) self.widget.set_page_type(box1, gtk.ASSISTANT_PAGE_PROGRESS) self.widget.set_page_title(box1, "Record measurements") self.measurements_label = gtk.Label('Ready.') self.measurements_label.set_line_wrap(True) self.measure_progress = gtk.ProgressBar() box1.pack_start(self.measurements_label, True, True, 0) box1.pack_start(self.measure_progress, expand=False, fill=False, padding=15) self.box1 = box1 # # Confirm fitted parameters # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONFIRM) self.widget.set_page_title(box, "Confirm fitted parameters") self.figure = Figure(dpi=72) self.canvas = FigureCanvasGTK(self.figure) toolbar = NavigationToolbar(self.canvas, self.widget) #self.axis = figure.add_subplot(111) box.pack_start(self.canvas) box.pack_start(toolbar, False, False) self.widget.set_page_complete(box, True) ## # Summary # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_SUMMARY) self.widget.set_page_title(box, "Summary") label = gtk.Label('Calibration of device load feedback circuit is ' 'complete. The impedance between actuated device ' 'area and ground should now be measured accurately ' 'by the control board.') label.set_line_wrap(True) box.pack_start(label, True, True, 0) self.widget.set_page_complete(box, True)
def __init__(self): gladefile = "HurricaneUI.glade" builder = gtk.Builder() builder.add_from_file(gladefile) self.window = builder.get_object("mainWindow") builder.connect_signals(self) self.figure = Figure(figsize=(10,10), dpi=75) self.axis = self.figure.add_subplot(111) self.lat = 50 self.lon = -100 self.globe= globDisp.GlobeMap(self.axis, self.lat, self.lon) self.canvas = FigureCanvasGTK(self.figure) self.canvas.show() self.canvas.set_size_request(500,500) self.globeview = builder.get_object("map") self.globeview.pack_start(self.canvas, True, True) self.navToolbar = NavigationToolbar(self.canvas, self.globeview) self.navToolbar.lastDir = '/var/tmp' self.globeview.pack_start(self.navToolbar) self.navToolbar.show() self.gridcombo = builder.get_object("gridsize") cell=gtk.CellRendererText() self.gridcombo.pack_start(cell,True) self.gridcombo.add_attribute(cell, 'text', 0) #self.gridcombo.set_active(2) # read menu configuration self.gridopt = builder.get_object("gridopt").get_active() self.chkDetected = builder.get_object("detectedopt") self.detectedopt = self.chkDetected.get_active() self.chkHurricane = builder.get_object("hurricaneopt") self.hurricaneopt = self.chkHurricane.get_active() model = builder.get_object("liststore1") index = self.gridcombo.get_active() self.gridsize = model[index][0] radio = [ r for r in builder.get_object("classifieropt1").get_group() if r.get_active() ][0] self.sClassifier = radio.get_label() self.start = builder.get_object("startdate") self.end = builder.get_object("enddate") self.chkUndersample = builder.get_object("undersample") self.chkGenKey = builder.get_object("genKey") # disable unimplemented classifier selection builder.get_object("classifieropt2").set_sensitive(False) builder.get_object("classifieropt3").set_sensitive(False) builder.get_object("classifieropt4").set_sensitive(False) self.btnStore = builder.get_object("store") self.datapath = 'GFSdat' self.trackpath = 'tracks' builder.get_object("btnDatapath").set_current_folder(self.datapath) builder.get_object("btnTrackpath").set_current_folder(self.trackpath) self.btnDetect = builder.get_object("detect") # current operation status self.stormlocs = None self.detected = None self.clssfr = None # for test drawing functions if os.path.exists('demo.detected'): with open('demo.detected','r') as f: self.detected = pickle.load(f) self.stormlocs = pickle.load(f) self.chkHurricane.set_label(str(self.stormlocs.shape[0])+" Hurricanes") self.chkDetected.set_label(str(self.detected.shape[0])+" Detected") self.setDisabledBtns() # draw Globe self.drawGlobe()
class HurricaneUI: def __init__(self): gladefile = "HurricaneUI.glade" builder = gtk.Builder() builder.add_from_file(gladefile) self.window = builder.get_object("mainWindow") builder.connect_signals(self) self.figure = Figure(figsize=(10,10), dpi=75) self.axis = self.figure.add_subplot(111) self.lat = 50 self.lon = -100 self.globe= globDisp.GlobeMap(self.axis, self.lat, self.lon) self.canvas = FigureCanvasGTK(self.figure) self.canvas.show() self.canvas.set_size_request(500,500) self.globeview = builder.get_object("map") self.globeview.pack_start(self.canvas, True, True) self.navToolbar = NavigationToolbar(self.canvas, self.globeview) self.navToolbar.lastDir = '/var/tmp' self.globeview.pack_start(self.navToolbar) self.navToolbar.show() self.gridcombo = builder.get_object("gridsize") cell=gtk.CellRendererText() self.gridcombo.pack_start(cell,True) self.gridcombo.add_attribute(cell, 'text', 0) #self.gridcombo.set_active(2) # read menu configuration self.gridopt = builder.get_object("gridopt").get_active() self.chkDetected = builder.get_object("detectedopt") self.detectedopt = self.chkDetected.get_active() self.chkHurricane = builder.get_object("hurricaneopt") self.hurricaneopt = self.chkHurricane.get_active() model = builder.get_object("liststore1") index = self.gridcombo.get_active() self.gridsize = model[index][0] radio = [ r for r in builder.get_object("classifieropt1").get_group() if r.get_active() ][0] self.sClassifier = radio.get_label() self.start = builder.get_object("startdate") self.end = builder.get_object("enddate") self.chkUndersample = builder.get_object("undersample") self.chkGenKey = builder.get_object("genKey") # disable unimplemented classifier selection builder.get_object("classifieropt2").set_sensitive(False) builder.get_object("classifieropt3").set_sensitive(False) builder.get_object("classifieropt4").set_sensitive(False) self.btnStore = builder.get_object("store") self.datapath = 'GFSdat' self.trackpath = 'tracks' builder.get_object("btnDatapath").set_current_folder(self.datapath) builder.get_object("btnTrackpath").set_current_folder(self.trackpath) self.btnDetect = builder.get_object("detect") # current operation status self.stormlocs = None self.detected = None self.clssfr = None # for test drawing functions if os.path.exists('demo.detected'): with open('demo.detected','r') as f: self.detected = pickle.load(f) self.stormlocs = pickle.load(f) self.chkHurricane.set_label(str(self.stormlocs.shape[0])+" Hurricanes") self.chkDetected.set_label(str(self.detected.shape[0])+" Detected") self.setDisabledBtns() # draw Globe self.drawGlobe() def setDisabledBtns(self): self.chkDetected.set_sensitive(self.detected!=None) self.chkHurricane.set_sensitive(self.stormlocs!=None) self.btnStore.set_sensitive(self.clssfr!=None) self.btnDetect.set_sensitive(self.clssfr!=None) def drawGlobe(self): self.globe.drawGlobe(self.gridsize, self.gridopt) if self.hurricaneopt : self.globe.drawHurricanes(self.stormlocs) if self.detectedopt : self.globe.fillGrids(self.detected) def main(self): self.window.show_all() gtk.main() def redraw(self): self.axis.cla() self.drawGlobe() self.canvas.draw_idle() def gtk_main_quit(self,widget): gtk.main_quit() ############################################################################### # # utility functions (dialogs) # def getFilenameToRead(self, stitle, save=False, filter='all'): chooser = gtk.FileChooserDialog(title=stitle, parent=self.window, action=gtk.FILE_CHOOSER_ACTION_OPEN if not save else gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN if not save else gtk.STOCK_SAVE,gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) if filter=='mat' or filter=='mdat': filter = gtk.FileFilter() filter.set_name("Matrix files") filter.add_pattern("*.mat") chooser.add_filter(filter) if filter=='svm': filter = gtk.FileFilter() filter.set_name("SVM") filter.add_pattern("*.svm") chooser.add_filter(filter) if filter=='dat' or filter=='mdat': filter = gtk.FileFilter() filter.set_name("Data") filter.add_pattern("*.dat") chooser.add_filter(filter) filter = gtk.FileFilter() filter.set_name("All files") filter.add_pattern("*") chooser.add_filter(filter) chooser.set_current_folder(os.getcwd()) response = chooser.run() if response == gtk.RESPONSE_OK: filen = chooser.get_filename() else: filen = None chooser.destroy() return filen def showMessage(self,msg): md = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, msg) md.run() md.destroy() ############################################################################### # # read data files and convert into a training matrix input # def on_btnTrackpath_current_folder_changed(self,widget): self.trackpath = widget.get_current_folder() def on_btnDatapath_current_folder_changed(self,widget): self.datapath = widget.get_current_folder() def on_createMat_clicked(self,widget): filen = self.getFilenameToRead("Save converted matrix for training", True, filter='mat') if filen is not None: start = self.start.get_text() end = self.end.get_text() bundersmpl = self.chkUndersample.get_active() bgenkey = self.chkGenKey.get_active() ### FIX ME: currently gridsize for classification is fixed 1 (no clustering of grids - 2x2) if os.path.exists(filen): os.unlink(filen) # createMat append existing file, so delete it if exist gdtool.createMat(self.datapath, self.trackpath, start, end, store=filen, undersample=bundersmpl, genkeyf=bgenkey) self.showMessage("Matrix has been stored to "+filen) ############################################################################### # # train the selected classifier # def on_train_clicked(self, widget): # FOR NOW, only SVM is supported if self.sClassifier == "SVM": filen = self.getFilenameToRead("Open training data",filter='mat') if filen is not None: data = ml.VectorDataSet(filen,labelsColumn=0) self.clssfr = ml.SVM() self.clssfr.train(data) # train finished. need to update button status self.setDisabledBtns() self.showMessage("Training SVM is done.") else : self.showMessage("The classifier is not supported yet!") def on_classifieropt_toggled(self,widget, data=None): self.sClassifier = widget.get_label() ############################################################################### # # Classify on test data # def on_detect_clicked(self, widget): if self.clssfr is not None: filen = self.getFilenameToRead("Open hurricane data", filter='mdat') if filen is not None: fname = os.path.basename(filen) key, ext = os.path.splitext(fname) if ext == '.dat': key = key[1:] # take 'g' out #testData = gdtool.createMat(self.datapath, self.trackpath, key, key) #result = self.clssfr.test(ml.VectorDataSet(testData,labelsColumn=0)) tmpfn = 'f__tmpDetected__' if os.path.exists(tmpfn): os.unlink(tmpfn) # for DEMO, undersampled the normal data -- without undersampling there are too many candidates gdtool.createMat(self.datapath, self.trackpath, key, key, store=tmpfn, undersample=True, genkeyf=True) bneedDel = True else: tmpfn = fname bneedDel = False result = self.clssfr.test(ml.VectorDataSet(tmpfn,labelsColumn=0)) gdkeyfilen = ''.join([tmpfn,'.keys']) with open(gdkeyfilen, 'r') as f: gridkeys = pickle.load(f) self.stormlocs = pickle.load(f) predicted = result.getPredictedLabels() predicted = np.array(map(float,predicted)) self.detected = np.array(gridkeys)[predicted==1] if bneedDel: os.unlink(tmpfn) os.unlink(gdkeyfilen) snstroms = str(self.stormlocs.shape[0]) sndetected = str(self.detected.shape[0]) self.chkHurricane.set_label(snstroms+" Hurricanes") self.chkDetected.set_label(sndetected+" Detected") self.showMessage(''.join([sndetected,"/",snstroms," grids are predicted to have hurricane."])) if False: with open('demo.detected','w') as f: pickle.dump(self.detected,f) pickle.dump(self.stormlocs,f) # test data tested. update buttons self.setDisabledBtns() self.redraw() else: self.showMessage("There is no trained classifier!") ############################################################################### # # load and store trained classifier # def on_load_clicked(self, widget): filen = self.getFilenameToRead("Load Classifier",filter='svm') if filen is not None: #db = shelve.open(filen) #if db.has_key('clssfr'): # self.clssfr = db['clssfr'] #else: # self.showMessage("Cannot find a classifier!") #db.close() #with open(filen, 'wb') as f: # self.clssfr = pickle.load(f) datfn = self.getFilenameToRead("Open Training Data",filter='mat') if datfn is not None: data = ml.VectorDataSet(datfn,labelsColumn=0) self.clssfr = loadSVM(filen,data) ## Why do I need to feed data ??? #self.clssfr = loadSVM(filen,None) ## edited PyML for this # classifier has been loaded. need to update button status self.setDisabledBtns() self.showMessage("The classifier has been loaded!") def on_store_clicked(self, widget): if self.clssfr is not None: filen = self.getFilenameToRead("Store Classifier", True, filter='svm') if filen is not None: #with open(filen, 'wb') as f: # pickle.dump(self.clssfr,f) #db = shelve.open(filen) #db['clssfr'] = self.clssfr #db.close() self.clssfr.save(filen) self.showMessage("The classifier has been saved!") else: self.showMessage("There is no trained classifier!") ############################################################################### # # Display Globe # def on_right_clicked(self,widget): self.lon += 10 # rotate Globe def on_left_clicked(self,widget): self.lon -= 10 # rotate Globe def gridsize_changed_cb(self, widget): model = widget.get_model() index = widget.get_active() if index > -1: self.gridsize = model[index][0] self.redraw() def on_gridopt_toggled(self, widget): self.gridopt = not self.gridopt self.redraw() def on_Hurricane_toggled(self, widget): self.hurricaneopt = not self.hurricaneopt self.redraw() def on_detected_toggled(self, widget): self.detectedopt = not self.detectedopt self.redraw()
def create_ui(self): self.widget = gtk.Assistant() self.widget.connect("prepare", self.assistant_prepared) self.widget.connect("cancel", self.cancel_button_clicked) self.widget.connect("close", self.close_button_clicked) self.widget.connect("apply", self.apply_button_clicked) # # Introduction # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_INTRO) self.widget.set_page_title(box, "Introduction") content = ('This wizard will guide you through the process of ' 'testing the channels of a single switching board.') label = gtk.Label(content) label.set_use_markup(True) label.set_line_wrap(True) image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/channels_intro.png') image.set_from_file(str(img_path)) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Connect hardware # box = gtk.HBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Connect hardware") label = gtk.Label( ' - Connect DropBot "<tt>Out to Amp</tt>" to amplifier input.\n' ' - Connect amplifier output to DropBot "<tt>In from Amp</tt>".\n' ' - Connect a bank of DropBot channels to test board.') image = gtk.Image() img_path = pkg_resources.resource_filename( 'dmf_control_board_firmware', 'gui/impedance_feedback_setup.png') image.set_from_file(str(img_path)) label.set_line_wrap(True) label.set_use_markup(True) box.pack_start(label, True, False, padding=15) box.pack_start(image, True, True, padding=5) self.widget.set_page_complete(box, True) # # Select frequencies # self.radio_buttons = [ gtk.RadioButton(label='Channels %d-%d' % (c, c + self.channels_per_board - 1)) for c in xrange(0, self.channel_count, self.channels_per_board) ] for b in self.radio_buttons[1:]: b.set_group(self.radio_buttons[0]) box = gtk.VBox() for b in self.radio_buttons: box.pack_start(b, expand=False, fill=False, padding=20) self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONTENT) self.widget.set_page_title(box, "Select bank of test channels") self.widget.set_page_complete(box, True) ## # Record measurements # box1 = gtk.VBox() self.widget.append_page(box1) self.widget.set_page_type(box1, gtk.ASSISTANT_PAGE_PROGRESS) self.widget.set_page_title(box1, "Record measurements") self.measurements_label = gtk.Label('Ready.') self.measurements_label.set_line_wrap(True) self.measure_progress = gtk.ProgressBar() box1.pack_start(self.measurements_label, True, True, 0) box1.pack_start(self.measure_progress, expand=False, fill=False, padding=15) self.box1 = box1 ## # Display readings # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_CONFIRM) self.widget.set_page_title(box, "Channel readings") self.figure = Figure(dpi=72) self.canvas = FigureCanvasGTK(self.figure) toolbar = NavigationToolbar(self.canvas, self.widget) box.pack_start(self.canvas) box.pack_start(toolbar, False, False) self.widget.set_page_complete(box, True) ### # Summary # box = gtk.VBox() self.widget.append_page(box) self.widget.set_page_type(box, gtk.ASSISTANT_PAGE_SUMMARY) self.widget.set_page_title(box, "Summary") label = gtk.Label('Testing of selected channels complete.') label.set_line_wrap(True) box.pack_start(label, True, True, 0) self.widget.set_page_complete(box, True)
def drawPie(self, xvalues, yvalues, xlabel, ylabel, title, color, zones=None): logging.debug('>>') logging.debug("Type: pie | title: " + str(title) + " | col: " + str(color) + " | xlabel: " + str(xlabel) + " | ylabel: " + str(ylabel)) self.removeVboxChildren() #figure = Figure(figsize=(6,4), dpi=72) figure = Figure() logging.debug("Figure: %s" % str(figure)) axis = figure.add_subplot(111) labels = [] colors = [] frac0 = 0 frac1 = 0 frac2 = 0 frac3 = 0 frac4 = 0 frac5 = 0 for zone in zones: labels.insert(0, zone[3]) colors.insert(0, zone[2]) labels.insert(0, _("rest")) colors.insert(0, "#ffffff") for value in yvalues[0]: if value <= zones[4][0]: frac0 += 1 elif value > zones[4][0] and value <= zones[4][1]: frac1 += 1 elif value > zones[3][0] and value <= zones[3][1]: frac2 += 1 elif value > zones[2][0] and value <= zones[2][1]: frac3 += 1 elif value > zones[1][0] and value <= zones[1][1]: frac4 += 1 elif value > zones[0][0] and value <= zones[0][1]: frac5 += 1 fracs = [] explode = [] if frac5 == 0: labels.pop(5) colors.pop(5) else: fracs.insert(0, frac5) explode.insert(0, 0) if frac4 == 0: labels.pop(4) colors.pop(4) else: fracs.insert(0, frac4) explode.insert(0, 0) if frac3 == 0: labels.pop(3) colors.pop(3) else: fracs.insert(0, frac3) explode.insert(0, 0) if frac2 == 0: labels.pop(2) colors.pop(2) else: fracs.insert(0, frac2) explode.insert(0, 0) if frac1 == 0: labels.pop(1) colors.pop(1) else: fracs.insert(0, frac1) explode.insert(0, 0) if frac0 == 0: labels.pop(0) colors.pop(0) else: fracs.insert(0, frac0) explode.insert(0, 0) axis.pie(fracs, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) canvas = FigureCanvasGTK(figure) # a gtk.DrawingArea canvas.show() for child in self.vbox.get_children(): logging.debug('Child available: ' + str(child)) self.vbox.pack_start(canvas, True, True) logging.debug('<<')
def __init__(self): gladefile = "HurricaneUI.glade" builder = gtk.Builder() builder.add_from_file(gladefile) self.window = builder.get_object("mainWindow") builder.connect_signals(self) self.figure = Figure(figsize=(10, 10), dpi=75) self.axis = self.figure.add_subplot(111) self.lat = 50 self.lon = -100 self.globe = globDisp.GlobeMap(self.axis, self.lat, self.lon) self.canvas = FigureCanvasGTK(self.figure) self.canvas.show() self.canvas.set_size_request(500, 500) self.globeview = builder.get_object("map") self.globeview.pack_start(self.canvas, True, True) self.navToolbar = NavigationToolbar(self.canvas, self.globeview) self.navToolbar.lastDir = '/var/tmp' self.globeview.pack_start(self.navToolbar) self.navToolbar.show() self.gridcombo = builder.get_object("gridsize") cell = gtk.CellRendererText() self.gridcombo.pack_start(cell, True) self.gridcombo.add_attribute(cell, 'text', 0) #self.gridcombo.set_active(2) # read menu configuration self.gridopt = builder.get_object("gridopt").get_active() self.chkDetected = builder.get_object("detectedopt") self.detectedopt = self.chkDetected.get_active() self.chkHurricane = builder.get_object("hurricaneopt") self.hurricaneopt = self.chkHurricane.get_active() model = builder.get_object("liststore1") index = self.gridcombo.get_active() self.gridsize = model[index][0] radio = [ r for r in builder.get_object("classifieropt1").get_group() if r.get_active() ][0] self.sClassifier = radio.get_label() self.start = builder.get_object("startdate") self.end = builder.get_object("enddate") self.chkUndersample = builder.get_object("undersample") self.chkGenKey = builder.get_object("genKey") # disable unimplemented classifier selection builder.get_object("classifieropt2").set_sensitive(False) builder.get_object("classifieropt3").set_sensitive(False) builder.get_object("classifieropt4").set_sensitive(False) self.btnStore = builder.get_object("store") self.datapath = 'GFSdat' self.trackpath = 'tracks' builder.get_object("btnDatapath").set_current_folder(self.datapath) builder.get_object("btnTrackpath").set_current_folder(self.trackpath) self.btnDetect = builder.get_object("detect") # current operation status self.stormlocs = None self.detected = None self.clssfr = None # for test drawing functions if os.path.exists('demo.detected'): with open('demo.detected', 'r') as f: self.detected = pickle.load(f) self.stormlocs = pickle.load(f) self.chkHurricane.set_label( str(self.stormlocs.shape[0]) + " Hurricanes") self.chkDetected.set_label( str(self.detected.shape[0]) + " Detected") self.setDisabledBtns() # draw Globe self.drawGlobe()
class DataPlotter: def __init__(self): self.data_x = [] self.data_y = [] self.data_i = [] self.data_v = [] self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(550, 700) self.window.connect("delete_event", self.destroy) self.window.connect("destroy", self.destroy) self.vbox = gtk.VBox(False, 0) self.window.add(self.vbox) self.plotfig_i = Figure(figsize=(100, 100), dpi=75) self.plotfig_v = Figure(figsize=(100, 100), dpi=75) self.plotax_i = self.plotfig_i.add_subplot(111) self.plotax_v = self.plotfig_v.add_subplot(111) self.plotlines_i = self.plotax_i.plot(self.data_x, self.data_i, ".") self.plotlines_v = self.plotax_v.plot(self.data_x, self.data_v, ".") self.plotax_i.set_ylim(-15, 15) self.plotax_v.set_ylim(0, 178) self.plotcanvas_i = FigureCanvasGTK(self.plotfig_i) self.plotcanvas_v = FigureCanvasGTK(self.plotfig_v) self.plotcanvas_i.show() self.plotcanvas_v.show() self.vbox.pack_start(self.plotcanvas_i, True, True, 0) self.vbox.pack_end(self.plotcanvas_v, True, True, 0) self.vbox.show() def destroy(self, widget, data=None): gtk.main_quit() sigint_handler(0, 0) def data_adjust(self): x = -1 y = -1 self.data_i = [] self.data_v = [] self.data_y.pop(0) self.data_x.pop(0) for i in range(len(self.data_y)): if i % 2 == 0: self.data_y[i] *= (170000 / 4300.0) / 1000 if y != -1: self.data_v.append((y + self.data_y[i]) / 2) else: self.data_v.append(self.data_y[i]) self.data_v.append(self.data_y[i]) y = self.data_y[i] else: self.data_y[i] -= 2500 self.data_y[i] /= 100 if x != -1: self.data_i.append((x + self.data_y[i]) / 2) else: self.data_i.append(self.data_y[i]) self.data_i.append(self.data_y[i]) x = self.data_y[i] power = 0 # Perform a numerical integration on this power for i in range(len(self.data_i)): power += abs(self.data_i[i]) * self.data_v[i] # Divide by the time length for the average power power /= len(self.data_y) # Divide by two since we took the absolute value of # both I and V # power /= 2. # Subtract our "idle" power value # power -= 18.30 # if (power < 0): # power = 0 # Push this power to our list powers.insert(0, power) # Pop off the first if we've reached 6 powers if len(powers) == 6: powers.pop() # Print out current list of powers print "Power:", avgpower = 0 for i in range(len(powers)): if i == 0: print "[%f]" % powers[i], else: print "%f" % powers[i], avgpower += powers[i] print "watts" # Calculate and print the average power avgpower /= len(powers) + 0.0 print "Average Power: %f" % avgpower, "watts" print "Latest Power Reading: %f" % power, "watts\n\n" def replot(self): if dataLog.new_data > 0: self.data_x = dataLog.back_axis_time[:] self.data_y = dataLog.back_axis_voltage[:] self.data_adjust() self.plotlines_i[0].set_xdata(self.data_x) self.plotlines_v[0].set_xdata(self.data_x) self.plotlines_i[0].set_ydata(self.data_i) self.plotlines_v[0].set_ydata(self.data_v) self.plotlines_i[0].set_color("r") self.plotlines_v[0].set_color("r") self.plotax_i.set_xlim(self.data_x[0], self.data_x[-1]) self.plotax_v.set_xlim(self.data_x[0], self.data_x[-1]) dataLog.new_data = 0 self.plotcanvas_i.draw_idle() self.plotcanvas_v.draw_idle() return True def main(self): self.window.show() gobject.idle_add(self.replot) gtk.main()