class TestDialog( QDialog, Ui_dlgMPLTest ): def __init__( self, parent = None ): super( TestDialog, self ).__init__( parent ) self.setupUi( self ) # initialize mpl plot self.figure = Figure() #self.figure.set_figsize_inches( ( 4.3, 4.2 ) ) self.axes = self.figure.add_subplot( 111 ) self.figure.suptitle( "Frequency distribution", fontsize = 12 ) self.axes.grid( True ) self.canvas = FigureCanvas( self.figure ) layout = QVBoxLayout() self.widgetPlot.setLayout(layout) layout.addWidget(self.canvas) #self.canvas.setParent( self.widgetPlot ) # draw mpl plot #self.axes.clear() #self.axes.grid( True ) #self.figure.suptitle( "Frequency distribution", fontsize = 12 ) self.axes.set_ylabel( "Count", fontsize = 8 ) self.axes.set_xlabel( "Values", fontsize = 8 ) x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ] n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" ) self.canvas.draw() self.setWindowTitle( self.tr( "MPL test" ) )
def _write_fig(self, plots, fig_label): fig = Figure() ax = fig.add_subplot(111) if self.legend is not None: plotlist = numpy.argsort(self.legend) else: plotlist = xrange(len(plots)) for i in plotlist: if plots[i].shape[0] != 2: raise ValueError, "Attempting to plot matrix with row count other than 2" if self.legend is not None: ax.plot(plots[i][0], plots[i][1], self.colours.next(), label=self.legend[i]) else: ax.plot(plots[i][0], plots[i][1], self.colours.next()) if self.legend is not None: ax.legend(loc='best') canvas = FigureCanvas(fig) canvas.figure.savefig(new_filename(fig_label, 'figure', '.png'))
def _plot(self, x,y): root = Tk.Tk() root.wm_title("") f = Figure(figsize=(6,6), dpi=100) a = f.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) a.plot(t,s) # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg( canvas, root ) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def _quit(): root.quit() # stops mainloop root.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate button = Tk.Button(master=root, text='Quit', command=_quit) button.pack(side=Tk.BOTTOM) Tk.mainloop() # If you put root.destroy() here, it will cause an error if # the window is closed with the window manager.
def configure_subplots(self, button): toolfig = Figure(figsize=(6, 3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) window = Gtk.Window() try: window.set_icon_from_file(window_icon) except Exception: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = Gtk.Box() vbox.set_property("orientation", Gtk.Orientation.VERTICAL) window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True, 0) window.show()
def plotSolarRadiationAgainstMonth(filename): trainRowReader = csv.reader(open(filename, 'rb'), delimiter=',') month_most_common_list = [] Solar_radiation_64_list = [] for row in trainRowReader: month_most_common = row[3] Solar_radiation_64 = row[6] month_most_common_list.append(month_most_common) Solar_radiation_64_list.append(Solar_radiation_64) #convert all elements in the list to float while skipping the first element for the 1st element is a description of the field. month_most_common_list = [float(i) for i in prepareList(month_most_common_list)[1:] ] Solar_radiation_64_list = [float(i) for i in prepareList(Solar_radiation_64_list)[1:] ] fig=Figure() ax=fig.add_subplot(111) title='Scatter Diagram of solar radiation against month of the year' ax.set_xlabel('Most common month') ax.set_ylabel('Solar Radiation') fig.suptitle(title, fontsize=14) try: ax.scatter(month_most_common_list, Solar_radiation_64_list) #it is possible to make other kind of plots e.g bar charts, pie charts, histogram except ValueError: pass canvas = FigureCanvas(fig) canvas.print_figure('solarRadMonth.png',dpi=500)
def init_window(self): if self.window: return self.window = Gtk.Window(title="Subplot Configuration Tool") try: self.window.window.set_icon_from_file(window_icon) except Exception: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass self.vbox = Gtk.Box() self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL) self.window.add(self.vbox) self.vbox.show() self.window.connect('destroy', self.destroy) toolfig = Figure(figsize=(6, 3)) canvas = self.figure.canvas.__class__(toolfig) toolfig.subplots_adjust(top=0.9) SubplotTool(self.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) self.window.set_default_size(w, h) canvas.show() self.vbox.pack_start(canvas, True, True, 0) self.window.show()
def plot(title='title',xlab='x',ylab='y',mode='plot', data={'xxx':[(0,0),(1,1),(1,2),(3,3)], 'yyy':[(0,0,.2,.2),(2,1,0.2,0.2),(2,2,0.2,0.2),(3,3,0.2,0.3)]}): fig=Figure() fig.set_facecolor('white') ax=fig.add_subplot(111) if title: ax.set_title(title) if xlab: ax.set_xlabel(xlab) if ylab: ax.set_ylabel(ylab) legend=[] keys=sorted(data) for key in keys: stream = data[key] (x,y)=([],[]) for point in stream: x.append(point[0]) y.append(point[1]) if mode=='plot': ell=ax.plot(x, y) legend.append((ell,key)) if mode=='hist': ell=ax.hist(y,20) if legend: ax.legend([x for (x,y) in legend], [y for (x,y) in legend], 'upper right', shadow=True) canvas=FigureCanvas(fig) stream=cStringIO.StringIO() canvas.print_png(stream) return stream.getvalue()
def __get_column_width(self): max_length = 0 max_column_text = '' flag = self.prefs.get('legend_numbers',True) unit = self.prefs.get('legend_unit',False) for label,num in self.labels: if not flag: num = None if num is not None: column_length = len(str(label)+str(num)) + 1 else: column_length = len(str(label)) + 1 if column_length > max_length: max_length = column_length if flag: if type(num) == types.IntType or type(num) == types.LongType: numString = str(num) else: numString = "%.1f" % float(num) max_column_text = '%s %s' % (str(label),numString) if unit: max_column_text += "%" else: max_column_text = '%s ' % str(label) figure = Figure() canvas = FigureCanvasAgg(figure) dpi = self.prefs['dpi'] figure.set_dpi( dpi ) l_size,l_padding = self.__get_legend_text_size() self.text_size = pixelToPoint(l_size,dpi) text = Text(0.,0.,text=max_column_text,size=self.text_size) text.set_figure(figure) bbox = text.get_window_extent(canvas.get_renderer()) self.column_width = bbox.width+6*l_size
class CoffeeCanvas(FigureCanvas): def __init__(self): self.fig = Figure() self.ax = self.fig.add_subplot(1,1,1) super().__init__(self.fig) self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.fig.canvas.draw() def show_bar_graph(self,data,date): self.ax.clear() data_dict = dict(data) for i, key in enumerate(data_dict): self.ax.bar(i,data_dict[key]) self.ax.set_xticks(np.arange(len(data_dict))+0.4) self.ax.set_xticklabels(list(data_dict.keys())) self.fig.autofmt_xdate() self.ax.set_title("Total Sales for {0}".format(date)) self.ax.set_xlabel("Product") self.ax.set_ylabel("Amount (£)") self.fig.canvas.draw() def show_pie_chart(self,data,date): self.ax.clear() data_dict = dict(data) data = list(data_dict.values()) labels = list(data_dict.keys()) self.ax.pie(data,labels=labels,autopct='%1.1f%%') self.ax.set_title("Percentage Sales for {0}".format(date)) self.fig.canvas.draw()
class WattrGraphPanel( WattrGUI.GraphPanel ): subplot = 0 plots = {} def __init__(self, parent, fgsize=None, dpi=None): super(WattrGraphPanel, self).__init__(parent) self.figure = Figure(fgsize, dpi) #Transparent figure face color self.figure.set_facecolor((0,0,0,0,)) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) # Now put all into a sizer sizer = self.GetSizer() # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW) # Best to allow the toolbar to resize! self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() sizer.Add(self.toolbar, 0, wx.GROW) self.Fit() def add_plot(self, x=1, y=1): self.subplot += 1 plot = self.figure.add_subplot(x, y, self.subplot) plot.ticklabel_format(axis='y', style='plain', useOffset=False) plot.ticklabel_format(axis='x', style='plain', useOffset=False) self.plots[self.subplot] = plot return plot def draw(self): self.canvas.draw()
def daily_timseries( ts ): fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig) ax = fig.add_axes((0,0,1,1)) ax.set_ylim( [ 0 , 500 ] ) preferspan = ax.axhspan( SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor = '#003333', linewidth=1 ) # XXX: gets a list of days. timestamps = glucose.get_days( ts.time ) halfday = dates.relativedelta( hours=12 ) soleday = dates.relativedelta( days=1 ) xmin, xmax = ( timestamps[ 0 ], timestamps[ 1 ] + soleday ) ax.set_xlim( [ xmin, xmax ] ) #fig.autofmt_xdate( ) #plot_glucose_stems( ax, ts ) plt.setp(ax.get_xminorticklabels(), visible=False ) plt.setp(ax.get_xmajorticklabels(), visible=False ) plt.setp(ax.get_ymajorticklabels(), visible=False ) plt.setp(ax.get_yminorticklabels(), visible=False ) ax.grid(True) xmin, xmax = ax.get_xlim( ) log.info( pformat( { 'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ], } ) ) return canvas
def __init__(self, viewer, selected): self.selected = selected self.ids = [str(i) + " - " + str(s) for i, s in enumerate(selected)] t2 = Tk.Toplevel(viewer) t2.title('Data Range Editor') t2.transient(viewer) # Image selection combobox sel_fr = Tk.Frame(master=t2) Tk.Label(sel_fr, text="Image:").pack(side=Tk.LEFT) self.imagesel = ttk.Combobox(sel_fr) self.imagesel['values'] = [str(s) for s in selected] self.imagesel.bind('<<ComboboxSelected>>', self.update) im = self.selected[0] self.imagesel.set(self.ids[0]) self.imagesel.pack(side=Tk.LEFT) sel_fr.pack(side=Tk.TOP) # Grid showing current vmin, vmax and original vmin,vmax lim_fr = Tk.Frame(master=t2) Tk.Label(lim_fr, text="Upper limit:").grid(row=1,column=1) Tk.Label(lim_fr, text="Lower limit:").grid(row=2,column=1) self.ulim_orig, self.llim_orig = Tk.StringVar(), Tk.StringVar() self.ulim, self.llim = Tk.StringVar(), Tk.StringVar() self.upper_limit = Tk.Entry(lim_fr, textvariable=self.ulim) self.lower_limit = Tk.Entry(lim_fr, textvariable=self.llim) self.upper_limit.grid(row=1,column=2) self.lower_limit.grid(row=2,column=2) upper_limit_orig = Tk.Entry(lim_fr, textvariable=self.ulim_orig, state=Tk.DISABLED) lower_limit_orig = Tk.Entry(lim_fr, textvariable=self.llim_orig, state=Tk.DISABLED) upper_limit_orig.grid(row=1,column=3) lower_limit_orig.grid(row=2,column=3) lim_fr.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0) # Button frame buttons = Tk.Frame(master=t2) self.all_images = Tk.BooleanVar() self.all_images.set(False) Tk.Checkbutton(buttons, text="Apply to all images", variable=self.all_images).pack(side=Tk.TOP) apply = Tk.Button(master=buttons, text='Apply', command=self.set_limits) apply.pack(side=Tk.RIGHT) reset = Tk.Button(master=buttons, text='Reset', command=self.reset) reset.pack(side=Tk.RIGHT) buttons.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0) # Matplotlib figure f = Figure(figsize=(5,4), dpi=100) self.a = f.add_subplot(111) self.canvas = FigureCanvasTkAgg(f, master=t2) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.update()
def getImage(self): ddict=self.fitresult try: fig = Figure(figsize=(6,3)) # in inches canvas = FigureCanvas(fig) ax = fig.add_axes([.15, .15, .8, .8]) ax.set_axisbelow(True) logplot = self.plotDict.get('logy', True) if logplot: axplot = ax.semilogy else: axplot = ax.plot axplot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5) axplot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5) legendlist = ['spectrum', 'continuum', 'fit'] axplot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5) fontproperties = FontProperties(size=8) if ddict['result']['config']['fit']['sumflag']: axplot(ddict['result']['energy'], ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5) legendlist.append('pileup') if matplotlib_version < '0.99.0': legend = ax.legend(legendlist,0, prop = fontproperties, labelsep=0.02) else: legend = ax.legend(legendlist,0, prop = fontproperties, labelspacing=0.02) except ValueError: fig = Figure(figsize=(6,3)) # in inches canvas = FigureCanvas(fig) ax = fig.add_axes([.15, .15, .8, .8]) ax.set_axisbelow(True) ax.plot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5) ax.plot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5) legendlist = ['spectrum', 'continuum', 'fit'] ax.plot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5) fontproperties = FontProperties(size=8) if ddict['result']['config']['fit']['sumflag']: ax.plot(ddict['result']['energy'], ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5) legendlist.append('pileup') if matplotlib_version < '0.99.0': legend = ax.legend(legendlist,0, prop = fontproperties, labelsep=0.02) else: legend = ax.legend(legendlist,0, prop = fontproperties, labelspacing=0.02) ax.set_xlabel('Energy') ax.set_ylabel('Counts') legend.draw_frame(False) outfile = self.outdir+"/"+self.outfile+".png" try: os.remove(outfile) except: pass canvas.print_figure(outfile) return self.__getFitImage(self.outfile+".png")
def graph_prices(x, y, gname): '''make a plot of the prices over time for a specific game' x is be the dates of the bins y is the prices gname is the name of the game ''' x_list = list(x) x_dt = [datetime.fromtimestamp(xx) for xx in x_list] fig=Figure(facecolor='white') ax=fig.add_subplot(111) ax.plot(x_dt,y,'r-') ax.set_ylim([0,np.max(y) + np.max(y) * 0.10]) #ax.set_title(gname) #ax.set_axis_bgcolor('red') formatter = FuncFormatter(money_format) ax.yaxis.set_major_formatter(formatter) #fig.autofmt_xdate() #xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') #ax.xaxis.set_major_formatter(xfmt) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def workDone(self, days=30): self.calcStats() for type in ["dayRepsNew", "dayRepsYoung", "dayRepsMature"]: self.addMissing(self.stats[type], -days, 0) fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) graph = fig.add_subplot(111) args = sum((self.unzip(self.stats[type].items(), limit=days, reverseLimit=True) for type in ["dayRepsMature", "dayRepsYoung", "dayRepsNew"][::-1]), []) self.varGraph(graph, days, [reviewNewC, reviewYoungC, reviewMatureC], *args) cheat = fig.add_subplot(111) b1 = cheat.bar(-3, 0, color = reviewNewC) b2 = cheat.bar(-4, 0, color = reviewYoungC) b3 = cheat.bar(-5, 0, color = reviewMatureC) cheat.legend([b1, b2, b3], [ "New", "Young", "Mature"], loc='upper left') graph.set_xlim(xmin=-days+1, xmax=1) graph.set_ylim(ymax=max(max(a for a in args[1::2])) + 10) graph.set_xlabel("Day (0 = today)") graph.set_ylabel("Cards Answered") return fig
def addedRecently(self, numdays=30, attr='created'): self.calcStats() days = {} fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) limit = self.endOfDay - (numdays) * 86400 res = self.deck.s.column0("select %s from cards where %s >= %f" % (attr, attr, limit)) for r in res: d = int((r - self.endOfDay) / 86400.0) days[d] = days.get(d, 0) + 1 self.addMissing(days, -numdays+1, 0) graph = fig.add_subplot(111) intervals = self.unzip(days.items()) if attr == 'created': colour = addedC else: colour = firstC self.varGraph(graph, numdays, colour, *intervals) graph.set_xlim(xmin=-numdays+1, xmax=1) graph.set_xlabel("Day (0 = today)") if attr == 'created': graph.set_ylabel("Cards Added") else: graph.set_ylabel("Cards First Answered") return fig
def simple(): # import datetime # import StringIO #get the polyline map using api: get_activity_map() from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure # from matplotlib.dates import DateFormatter import polyline m = session['map'] summary_lat_lon = polyline.decode(m.summary_polyline) fig=Figure() ax=fig.add_subplot(111) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] # x=[] # y=[] # now=datetime.datetime.now() # delta=datetime.timedelta(days=1) # for i in range(10): # x.append(now) # now+=delta # y.append(random.randint(0, 1000)) # ax.plot_date(x, y, '-') # ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.scatter(lons,lats) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def nextDue(self, days=30): self.calcStats() fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) graph = fig.add_subplot(111) dayslists = [self.stats['next'], self.stats['daysByType']['mature']] for dayslist in dayslists: self.addMissing(dayslist, self.stats['lowestInDay'], days) argl = [] for dayslist in dayslists: dl = [x for x in dayslist.items() if x[0] <= days] argl.extend(list(self.unzip(dl))) self.varGraph(graph, days, [dueYoungC, dueMatureC], *argl) cheat = fig.add_subplot(111) b1 = cheat.bar(0, 0, color = dueYoungC) b2 = cheat.bar(1, 0, color = dueMatureC) cheat.legend([b1, b2], [ "Young", "Mature"], loc='upper right') graph.set_xlim(xmin=self.stats['lowestInDay'], xmax=days+1) graph.set_xlabel("Day (0 = today)") graph.set_ylabel("Cards Due") return fig
def plot_frame_displacement(realignment_parameters_file, mean_FD_distribution=None, figsize=(11.7,8.3)): FD_power = calc_frame_dispalcement(realignment_parameters_file) fig = Figure(figsize=figsize) FigureCanvas(fig) if mean_FD_distribution: grid = GridSpec(2, 4) else: grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0,:-1]) ax.plot(FD_power) ax.set_xlim((0, len(FD_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0,-1]) sns.distplot(FD_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_FD_distribution: ax = fig.add_subplot(grid[1,:]) sns.distplot(mean_FD_distribution, ax=ax) ax.set_xlabel("Mean Frame Dispalcement (over all subjects) [mm]") MeanFD = FD_power.mean() label = "MeanFD = %g"%MeanFD plot_vline(MeanFD, label, ax=ax) return fig
def refreshTimeline(self): if not self.firstPlot: self.figureLayout.removeWidget(self.canvas) self.firstPlot = False fig = Figure((2.0, 1.5), dpi=100) self.canvas = FigureCanvas(fig) self.canvas.setParent(self) self.ax = fig.add_subplot(111) self.ax.clear() # levantar el controlDict y ver los tracers Tf = float(self.parsedData["endTime"]) T = float(self.currtime) dT = float(self.parsedData["deltaT"]) self.ax.set_ylim(0, 1.1) self.ax.set_xlim(-10 * dT, Tf) self.ax.plot([0, T - dT, T, T + dT, Tf], [0, 0, 1, 0, 0], "k", marker="o", label="Current Time") i = 0 for itracer in self.tracersData: Tini = float(itracer["startTime"]) if float(itracer["startTime"]) < T: Tini = T self.ax.plot([0, Tini, Tini + dT, Tf], [0, 0, 1, 1], self.colors[i % 6], label=itracer["name"]) i = i + 1 self.ax.set_title("Timeline") self.ax.set_xlabel("Time [s]") self.ax.set_ylabel("Event") self.ax.legend(loc=0, fontsize="small") self.figureLayout.addWidget(self.canvas)
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None): """ Saves a 2D :class:`numpy.array` as an image with one pixel per element. The output formats available depend on the backend being used. Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. *arr*: A 2D array. Keyword arguments: *vmin*/*vmax*: [ None | scalar ] *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. *cmap*: cmap is a colors.Colormap instance, eg cm.jet. If None, default to the rc image.cmap value. *format*: One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg. *origin* [ 'upper' | 'lower' ] Indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value. """ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False) canvas = FigureCanvas(fig) fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) fig.savefig(fname, dpi=1, format=format)
class Canvas(FigureCanvas): def __init__(self,parent,dpi=100.0): size = parent.size() self.dpi = dpi self.width = size.width() / dpi self.height = size.height() / dpi self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi, facecolor='w', edgecolor='k', frameon=False) self.figure.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, wspace=None, hspace=None) self.axes = self.figure.add_subplot(111) self.axes.axis((-1,1,-1,1)) FigureCanvas.__init__(self, self.figure) self.updateGeometry() self.draw() self.cc = self.copy_from_bbox(self.axes.bbox) self.particle_plot = None self.setParent(parent) self.blit(self.axes.bbox) def on_pre_draw(self): self.restore_region(self.cc) def on_draw(self): raise NotImplementedError def on_post_draw(self): self.blit(self.axes.bbox) def redraw(self): self.on_pre_draw() self.on_draw() self.on_post_draw()
def simple(request): import random import django import datetime from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter print "hello" #print form['subject'].value() fig=Figure() ax=fig.add_subplot(111) x=[] y=[] now=datetime.datetime.now() delta=datetime.timedelta(days=1) for i in range(10): x.append(now) now+=delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas=FigureCanvas(fig) response=django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response
def __init__(self): c = 3.0e+11 # speed of light, um/ms cs = 2.8e-11 # cross section, um^2 n = 1.5 self.WI = (c/n)*cs # 18.0, um^3/ms self.Nv = 5.0e+7 # 5.0e+7 1/um^3 - density of active particles self.W2 = 1./0.23 # 1/ms - 1/spontaneous emission lifetime (2->1 transitions) self.W3 = 1.e-3*self.W2 # 1/ms - 1/spontaneous emission lifetime (3->2 transitions) self.eta = 1.e-16 tb, te, self.ts = 0.0, 1.0, 1.0e-4 self.x = arange(tb,te,self.ts) self.Np = len(self.x) self.y1 = ndarray(shape=(self.Np), dtype='float') self.y2 = ndarray(shape=(self.Np), dtype='float') # self.y3 = ndarray(shape=(self.Np), dtype='float') self.y4 = ndarray(shape=(self.Np), dtype='float') self.PlotWindow = Tk.Toplevel() self.PlotWindow.title('numerical simulation of kinetic equations') fig = Figure(figsize=(10,6), dpi=100) self.g1 = fig.add_subplot(211) self.g2 = fig.add_subplot(212) self.canvas = FigureCanvasTkAgg(fig, self.PlotWindow) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.PlotWindow) self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
class DevPlot(Plot): def __init__(self,k1={'intel_snb' : ['intel_snb','intel_snb','intel_snb']},k2={'intel_snb':['LOAD_1D_ALL','INSTRUCTIONS_RETIRED','LOAD_OPS_ALL']},processes=1,**kwargs): self.k1 = k1 self.k2 = k2 super(DevPlot,self).__init__(processes=processes,**kwargs) def plot(self,jobid,job_data=None): self.setup(jobid,job_data=job_data) cpu_name = self.ts.pmc_type type_name=self.k1[cpu_name][0] events = self.k2[cpu_name] ts=self.ts n_events = len(events) self.fig = Figure(figsize=(8,n_events*2+3),dpi=110) do_rate = True scale = 1.0 if type_name == 'mem': do_rate = False scale=2.0**10 if type_name == 'cpu': scale=ts.wayness*100.0 for i in range(n_events): self.ax = self.fig.add_subplot(n_events,1,i+1) self.plot_lines(self.ax, [i], 3600., yscale=scale, do_rate = do_rate) self.ax.set_ylabel(events[i],size='small') self.ax.set_xlabel("Time (hr)") self.fig.subplots_adjust(hspace=0.5) #self.fig.tight_layout() self.output('devices')
def save(self, name, log=False, vrange=None): if self.imdict['X'].sum() == 0.0 and log: warn("can't plot {}, in log mode".format(name), RuntimeWarning, stacklevel=2) return fig = Figure(figsize=(8,6)) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="1.5%") if log: norm=LogNorm() else: norm=Normalize() if vrange: self.imdict['vmin'], self.imdict['vmax'] = vrange im = ax.imshow(norm=norm,**self.imdict) cb_dict = {'cax':cax} if log: cb_dict['ticks'] = LogLocator(10, np.arange(0.1,1,0.1)) cb_dict['format'] = LogFormatterMathtext(10) try: cb = plt.colorbar(im, **cb_dict) except ValueError: print self.imdict['X'].sum() raise ax.set_xlabel(self.x_label, x=0.98, ha='right') ax.set_ylabel(self.y_label, y=0.98, ha='right') if self.cb_label: cb.set_label(self.cb_label, y=0.98, ha='right') canvas.print_figure(name, bbox_inches='tight')
def player_wp(request, code): try: player = Player.objects.get(code=code) except Player.DoesNotExist: raise Http404 points = player.weekly_points.values_list('points', flat=True) response = HttpResponse(content_type='image/png') if points: weeks = list(player.weekly_points.values_list('week', flat=True)) fig = Figure(figsize=(0.4 * min(max(10, weeks[-1]), 22), 3), dpi=100, facecolor='white') ax = fig.add_subplot(111) rects = ax.bar(weeks, points, align='center', linewidth=1, color='#008ad1', width=1) ax.set_xlabel("Week") ax.set_ylabel("Points") ax.set_xticks(weeks) # add a tick for every week for p, rect in zip(points, rects): if p != 0: if p < 0: h = p * 2 - 1 elif p > 0: h = p + 1 ax.text(rect.get_x() + rect.get_width() / 2., h, str(p), fontsize=10, color='black', ha='center') ax.set_xlim((0.5, max(10, weeks[-1]) + 0.5)) else: fig = Figure(figsize=(1, 1), dpi=1, facecolor='white') # return one white pixel canvas = FigureCanvas(fig) canvas.print_png(response) return response
def plot_sfh(model_sfh, mock_sfh, plot_path): labels = {'lewis': r'ACS-MS', 'oir_all': r'OIR-ALL'} colors = {'lewis': 'dodgerblue', 'oir_all': 'maroon'} fig = Figure(figsize=(3.5, 3.5), frameon=False) canvas = FigureCanvas(fig) gs = gridspec.GridSpec(1, 1, left=0.18, right=0.95, bottom=0.15, top=0.95, wspace=None, hspace=None, width_ratios=None, height_ratios=None) ax = fig.add_subplot(gs[0]) for plane_key in ['lewis', 'oir_all']: if plane_key not in model_sfh['sfh'].keys(): continue plot_single_sfh_line(ax, model_sfh['sfh'][plane_key], label=labels[plane_key], color=colors[plane_key], drawstyle='steps-mid') _plot_mean_age(ax, model_sfh['sfh'][plane_key].attrs['mean_age'], c=colors[plane_key]) # plot_single_sfh_line(ax, model_sfh, label='Model', color='k') # print model_sfh['sfr'] _plot_mock_sfh(ax, mock_sfh, lw=1.5, c='k', label='Mock') _plot_mean_age(ax, mock_sfh.attrs['mean_age']) ax.legend(loc='lower left', fontsize=8, frameon=True) gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None) canvas.print_figure(plot_path + ".pdf", format="pdf")
def _test_determinism_save(filename, usetex): # This function is mostly copy&paste from "def test_visibility" # To require no GUI, we use Figure and FigureCanvasSVG # instead of plt.figure and fig.savefig from matplotlib.figure import Figure from matplotlib.backends.backend_svg import FigureCanvasSVG from matplotlib import rc rc('svg', hashsalt='asdf') rc('text', usetex=usetex) fig = Figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) ax.set_title('A string $1+2+\\sigma$') ax.set_xlabel('A string $1+2+\\sigma$') ax.set_ylabel('A string $1+2+\\sigma$') FigureCanvasSVG(fig).print_svg(filename)
def plot_activity(values): daysFmt = DateFormatter("%d-%B %H:00") fig=Figure() ax=fig.add_subplot(111) times = values.keys() times.sort() number_found = [values[key] for key in times] ax.plot_date(times, number_found, '-') #assert 0, '%s'%(values) # format the ticks ax.xaxis.set_major_locator(HourLocator(byhour=range(0,24,4))) ax.xaxis.set_major_formatter(daysFmt) ax.autoscale_view() ax.grid(True) ax.set_title('All devices') fig.autofmt_xdate() canvas=FigureCanvas(fig) response=HttpResponse(content_type='image/png') canvas.print_png(response) return response
import matplotlib as mpl mpl.get_backend() import matplotlib.pyplot as plt #plt.plot? plt.plot(3, 2) plt.plot(3, 2, '.') # First let's set the backend without using mpl.use() from the scripting layer from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure # create a new figure fig = Figure() # associate fig with the backend canvas = FigureCanvasAgg(fig) # add a subplot to the fig ax = fig.add_subplot(111) # plot the point (3,2) ax.plot(3, 2, '.') # save the figure to test.png # you can see this figure in your Jupyter workspace afterwards by going to # https://hub.coursera-notebooks.org/ canvas.print_png('test.png')
class SolenoidView(Tk.Tk): def __init__(self, title): super().__init__() self.deiconify() self.title(title) # UI Control Panel self.control_panel = ControlPanel(self) # UI Plot Widget # * Matplotlib Figure self.figure = Figure() self.axes = self.figure.add_axes((0.05, .05, .90, .90)) # * Canvas Widget self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1) self.canvas.draw() self.colorbar = None # UI Events pub.subscribe(self.update_view, 'update_view') pub.subscribe(self.save_dialog, 'save_dialog') def update_view(self, results): H, V = results['HV'][0], results['HV'][1] Bh, Bv = results["Bhv"] B_intensity = 2 * log(hypot(Bh, Bv)) self.axes.clear() self.canvas.draw() view_mode = self.control_panel.state['view_mode'] l = self.control_panel.state['turns'] h = self.control_panel.state['stretch'] if view_mode == 'yz' or view_mode == 'inf': self.axes.set_aspect('auto') # Plot of the field lines plot = self.axes.streamplot(H, V, Bh, Bv, color=B_intensity, cmap='viridis', density=1.5) # Plot of the solenoid coils ptsY = [h * (i/2 + 1/4) for i in range(2*l)] ptsX = [(-1)**(i) for i in range(2*l)] self.axes.plot(ptsX, ptsY, 'o', markersize=7, markerfacecolor='w', markeredgewidth=1.5, markeredgecolor=(0, 0, 0, 1)) if view_mode == 'inf': self.axes.set_xlim(-2, 2) self.axes.set_ylim(0.1*h, 0.7*h*l) self.axes.set_aspect('auto') elif view_mode == 'xy': self.axes.set_aspect('equal') # Plot of the field lines plot = self.axes.streamplot(H, V, Bh, Bv, color=B_intensity, cmap='viridis', density=2.0) # Plot of the solenoid coil start l = 0 self.axes.plot(-cos(2*pi*h*l), sin(2*pi*h*l), 'o', markersize=7, markerfacecolor='w', markeredgewidth=1.5, markeredgecolor=(0, 0, 0, 1)) # Colorbar fix if self.colorbar: self.colorbar.update_bruteforce(plot.lines) else: self.colorbar = self.figure.colorbar(plot.lines) self.canvas.draw() def save_dialog(self): ''' Opens a save dialog and save simulation results in a file ''' filename = filedialog.asksaveasfilename(initialdir=USER_HOME, filetypes=ALLOWED_FILES, title="Save simulation file") self.figure.savefig(filename) def open_running(self, task): ''' Displays a message while running the simulation ''' popup = Toplevel(self) x = self.winfo_x() y = self.winfo_y() popup.geometry("+%d+%d" % (x//2, y//2)) popup.title("Running") msg = Message(popup, text="Running simulation. Please Wait.") msg.pack() while task.is_alive(): popup.update() popup.destroy() # only when thread dies. def open(self): self.mainloop()
def populate(self): # Container for the progress bar/label fProgress = Frame(self) #, relief='solid', borderwidth=1) fProgress.grid(row=0, column=0, sticky=[E, W]) if fProgress: # Could put the label on top of the progressbar, but it has a non-transparent background # https://stackoverflow.com/questions/17039481/how-to-create-transparent-widgets-using-tkinter self.stage = StringVar() self.stage.set('Initialising Flux-nalysis Engine') l = Label(fProgress, textvariable=self.stage) l.grid(row=0, column=0) self.progress = IntVar() self.progress.set(0) pBar = Progressbar(fProgress, mode='determinate', variable=self.progress) pBar.grid(row=1, column=0, sticky=[E, W]) self.progressBar = pBar # Yeah look I don't know why I need this, but otherwise there's a bunch of wasted space fProgress.columnconfigure(0, weight=10000) # Left pane containing all calculated options for q pResults = Listbox(self, selectmode='extended') pResults.grid(row=2, column=0, sticky=[E, W, N, S]) pResults.bind('<<ListboxSelect>>', self.updateGraphs) self.results = pResults # TODO make a custom Listbox subclass and overhaul the selection system # Container for the buttons above the plotting figure fFitting = Frame(self) fFitting.grid(row=0, column=2, sticky=E) if fFitting: lFitting = Label(fFitting, text='Curve Fitting: ') lFitting.grid(row=0, column=0) self.fitChoice = StringVar() # Add all available fitting algorithms to the UI # Choices defined in curveFitting.FITTING_FUNCTIONS numFits = len(FITTING_FUNCTIONS) self.fitButtons = [] for i, fitAlg in enumerate(FITTING_FUNCTIONS): button = Radiobutton(fFitting, text=fitAlg.title(), indicatoron=0, variable=self.fitChoice, value=fitAlg, command=self.triggerCurveFit) button.grid(row=0, column=i + 1, padx=(0, WINDOW_PADDING)) button['state'] = 'disabled' self.fitButtons.append(button) bNone = Radiobutton(fFitting, text='No Fitting', indicatoron=0, variable=self.fitChoice, value=FITTING_NONE, command=self.triggerCurveFit) bSave = Button(fFitting, text='Save Data to Disk...', command=self.saveAllData) bNone.grid(row=0, column=numFits + 1, padx=(WINDOW_PADDING, WINDOW_PADDING * 4)) bSave.grid(row=0, column=numFits + 2) # matplotlib figure on the right pFigure = Figure(figsize=(10, 6), dpi=100) pFigure.set_tight_layout(True) # reduce the huge default margins self.mpl = pFigure.add_subplot(2, 1, 1, xmargin=0, ymargin=0.1) self.mpl.set_xscale('log') self.mpl.set_ylabel(r'$\Delta(\delta t)$') self.mpl.set_xlabel(r'$\delta t\ (s)$') self.mpl_d = pFigure.add_subplot(2, 1, 2, xmargin=0, ymargin=0.1) self.mpl_d.set_ylabel(r'$D\ (\mu m^2 s^{-1})$') self.mpl_d.set_xlabel(r'$q\ (\mu m^{-1})$') self.mpl_d.loaders = [] # container for loading text for curve fitting pCanvas = FigureCanvasTkAgg( pFigure, master=self) # tkinter portal for the MPL figure pCanvas.draw() self.rerender = pCanvas.draw # expose for access elsewhere pCanvas.get_tk_widget().grid(row=2, column=2) self.pc = pCanvas self.rowconfigure(1, minsize=WINDOW_PADDING) # buttons and list/canvas self.columnconfigure(0, weight=1, minsize=175) # allow for longer progress strings self.columnconfigure( 1, minsize=WINDOW_PADDING) # Gap between left and right sections self.columnconfigure(2, weight=3)
def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super(MplCanvas, self).__init__(fig)
import tkinter as tk from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) # Implement the default Matplotlib key bindings. from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure import numpy as np root = tk.Tk() root.title("你的银行卡") fig = Figure(figsize=(4, 3), dpi=100) t = np.arange(0, 3, .01) fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t)) canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea. canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) def on_key_press(event): print("you pressed {}".format(event.key)) key_press_handler(event, canvas, toolbar)
def initUI(self): centralwidget = QWidget() # create submenu option for later reference fileDiaglogue = QAction('&Open .mat file', self) # create instance of menu bar mainMenu = self.menuBar() # create menu option for opening file fileMenu = mainMenu.addMenu('&File') # add submenu option to tool bar fileMenu.addAction(fileDiaglogue) # connect openFile method to submenu selection fileDiaglogue.triggered.connect(self.openFile) # create dropdown menu gui self.dropLabel = QLabel('Channel Set', self) self.comboBox = QComboBox(self) self.comboBox.currentIndexChanged.connect(self.checkSet) self.comboBox.currentIndexChanged.connect(self.updateBtns) # create y-gap textbox self.yLabel = QLabel('Y Axis Gap', self) self.textbox = QLineEdit(self) # create graph all checkbox self.graphAll = QPushButton('Select All Channels', self) self.graphAll.clicked.connect(self.selectAll) # create update button update_btn = QPushButton('Update', self) update_btn.clicked.connect(self.update) # instantiate main plot canvas plot_canvas = FigureCanvas(Figure(figsize=(5, 5))) # add toolbar to layout self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(plot_canvas, self)) self._static_ax = plot_canvas.figure.subplots() # label graph axes xtext = self._static_ax.set_xlabel( 'my xdata') # returns a Text instance ytext = self._static_ax.set_ylabel('my ydata') # create grid for button layout self.grid = QGridLayout() # ensures no stretching occurs when maximizing/minimizing windows # self.grid.setSpacing(1) # assign grid position to each widget self.grid.addWidget(update_btn, 4, 0, 1, 5) self.grid.addWidget(self.yLabel, 1, 1) self.grid.addWidget(self.textbox, 1, 2) self.grid.addWidget(self.comboBox, 2, 2) self.grid.addWidget(self.dropLabel, 2, 1) self.grid.addWidget(self.graphAll, 3, 0, 1, 5) # create grid for channel button layout self.gridButtons = QGridLayout() self.gridButtons.setAlignment(Qt.AlignTop) # create layout for the graph canvas canvasBox = QHBoxLayout() canvasBox.addWidget(plot_canvas) # create main layout mainBox = QVBoxLayout() mainBox.addLayout(self.grid, 25) mainBox.addLayout(self.gridButtons, 75) mainBox.setAlignment(Qt.AlignHCenter) # create top layout topBox = QHBoxLayout() topBox.addLayout(canvasBox, 75) topBox.addLayout(mainBox, 25) centralwidget.setLayout(topBox) self.setCentralWidget(centralwidget) self.selected_SET = 0
qscroll = QtGui.QScrollArea(qwidget) qscroll.setGeometry(QtCore.QRect(0, 0, 500, 500)) qscroll.setFrameStyle(QtGui.QFrame.NoFrame) qlayout.addWidget(qscroll) qscrollContents = QtGui.QWidget() qscrollLayout = QtGui.QVBoxLayout(qscrollContents) qscrollLayout.setGeometry(QtCore.QRect(0, 0, 1000, 1000)) qscroll.setWidget(qscrollContents) qscroll.setWidgetResizable(True) for i in xrange(5): qfigWidget = QtGui.QWidget(qscrollContents) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.plot([1, 2, 3, 4]) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) # prevent the canvas to shrink beyond a point # original size looks like a good minimum size canvas.setMinimumSize(canvas.size())
def __init__(self, out_path=None, figsize=(5.0, 5.0 * 3 / 5), ext=None): self.fig = Figure(figsize) self.canvas = FigureCanvas(self.fig) self.ax = self.fig.add_subplot(1, 1, 1) self.out_path = out_path self.ext = ext
def __init__(self, parent): BasePanel.__init__(self, parent=parent) self.parent = parent self.img_filename = None self.input_phil = None self.sparams = None self.coord_filename = None self.mtz_filename = None self.stol_filename = None self.ref_img_filename = None self.dblclick = False self.project_folder = ct.InputCtrl(self, label='Project Folder: ', label_size=(150, -1), label_style='bold', value=os.path.abspath(os.curdir), buttons=True) self.project_title = ct.InputCtrl(self, label='Description', label_size=(150, -1), label_style='normal') self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE | wx.SP_3DSASH | wx.SP_NOBORDER) self.file_panel = wx.Panel(self.splitter, size=(-1, 200)) self.file_sizer = wx.BoxSizer(wx.VERTICAL) self.file_panel.SetSizer(self.file_sizer) self.preview_panel = wx.Panel(self.splitter, size=(-1, 500)) self.preview_sizer = wx.BoxSizer(wx.VERTICAL) self.preview_panel.SetSizer(self.preview_sizer) self.splitter.SplitHorizontally(self.file_panel, self.preview_panel, 200) self.input = FileListCtrl(self.file_panel) self.file_sizer.Add(self.input, 1, flag=wx.ALL | wx.EXPAND, border=10) # Image preview box w/ options prev_box = wx.GridBagSizer(5, 15) # self.opt_knb_start = ct.KnobCtrl(self.preview_panel, # label='start', # label_size=(40, -1), # spin_ctr_size=(50, -1), # knob_size=(120, 120), # values_start=0, # values_end=360, # values_step=1, # value=0) # # self.opt_knb_end = ct.KnobCtrl(self.preview_panel, # label='end', # label_size=(40, -1), # spin_ctr_size=(50, -1), # knob_size=(120, 120), # values_start=0, # values_end=360, # values_step=1, # value=360) self.opt_spc_start = ct.SpinCtrl(self.preview_panel, label='start:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='0', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=1) self.opt_spc_end = ct.SpinCtrl(self.preview_panel, label='finish:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='360', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=1) self.opt_spc_osc = ct.SpinCtrl(self.preview_panel, label='step:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='1.0', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=2) self.opt_btn_prev = wx.Button(self.preview_panel, label='PREVIEW IMAGE') self.opt_chk_bkg = wx.CheckBox(self.preview_panel, label='Add Background') self.opt_chk_bkg.SetValue(True) self.opt_chk_noise = wx.CheckBox(self.preview_panel, label='Add Noise') self.opt_chk_noise.SetValue(True) self.opt_chk_rand = wx.CheckBox(self.preview_panel, label='Randomize Orientation') self.opt_chk_rand.SetValue(True) self.opt_spc_scale = ct.SpinCtrl(self.preview_panel, label='Crystal size (um): ', label_size=(120, -1), ctrl_size=(100, -1), ctrl_min=1, ctrl_max=1000, ctrl_step=1, ctrl_value=30) self.img_figure = Figure(figsize=(3, 3)) self.img_axes = self.img_figure.add_subplot(111) self.img_axes.set_frame_on(False) self.img_axes.axis('off') self.img_axes.set_aspect('equal') self.img_figure.patch.set_visible(False) self.img_canvas = FigureCanvas(self.preview_panel, -1, self.img_figure) prev_box.Add(self.opt_spc_start, pos=(0, 0)) prev_box.Add(self.opt_spc_end, pos=(0, 1)) prev_box.Add(self.opt_spc_osc, pos=(1, 0)) prev_box.Add(self.opt_chk_bkg, flag=wx.EXPAND, pos=(4, 0), span=(1, 2)) prev_box.Add(self.opt_chk_noise, flag=wx.EXPAND, pos=(5, 0), span=(1, 2)) prev_box.Add(self.opt_chk_rand, flag=wx.EXPAND, pos=(6, 0), span=(1, 2)) prev_box.Add(self.opt_spc_scale, flag=wx.EXPAND, pos=(7, 0), span=(1, 2)) prev_box.Add(self.opt_btn_prev, flag=wx.EXPAND, pos=(8, 0), span=(1, 2)) prev_box.Add(self.img_canvas, pos=(0, 2), span=(9, 1), flag=wx.EXPAND) prev_box.AddGrowableCol(2) prev_box.AddGrowableRow(8) self.preview_sizer.Add(prev_box, 1, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.project_title, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.project_folder, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.splitter, 1, flag=wx.EXPAND) # Button bindings self.Bind(wx.EVT_BUTTON, self.onRunPreview, self.opt_btn_prev) # Thread bindings self.Bind(thr.EVT_NBDONE, self.onFinishedSimThread) # Image bindings xid = self.img_canvas.mpl_connect('button_press_event', self.on_button_press) xid = self.img_canvas.mpl_connect('button_release_event', self.on_button_release)
def __init__(self, parent, **kwargs): tk.Frame.__init__(self, parent) self.figure = Figure(**kwargs) self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().grid(column=0, row=0)
class canvas(FigureCanvas): def __init__(self, parent): # Se instancia el objeto figure self.fig = Figure() # Se define la grafica en coordenadas polares self.axes = self.fig.add_subplot(111) # Se define una grilla self.axes.grid(True) # se inicializa FigureCanvas FigureCanvas.__init__(self, self.fig) # se define el widget padre self.setParent(parent) self.fig.canvas.draw() self.cursors = [] # def axvlines(self, xs, **plot_kwargs): # import numpy as np # """ # Draw vertical lines on plot # :param xs: A scalar, list, or 1D array of horizontal offsets # :param plot_kwargs: Keyword arguments to be passed to plot # # """ # print (xs) # xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False) # lims = self.axes.get_ylim() # x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten() # y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten() # self.axes.plot(x_points, y_points, scaley = False, **plot_kwargs) def plotoma(self, espectro, plot_bkg=False, substract_bkg=False): self.axes.axes.cla() self.axes.grid(True) labels = [] x = espectro.x y = espectro.getSpec(substract_bkg) labels.append(espectro.fname) bkg = espectro.bkg # Dibujar Curva self.axes.plot(x, y, color='b') if plot_bkg: self.axes.plot(x, bkg, color='g') labels.append('Background') self.axes.legend(labels, ncol=4, loc='upper center', bbox_to_anchor=[0.5, 1.1], columnspacing=1.0, labelspacing=0.0, handletextpad=0.0, handlelength=1.5, fancybox=True, shadow=True) for c in self.cursors: self.axes.axvline(c.x, color=c.color) self.fig.canvas.draw() def multiplot(self, espectros=[], substract_bkg=False): self.axes.grid(True) if espectros: labels = [] for spec in espectros: self.axes.plot(spec.x, spec.y - spec.bkg if substract_bkg else spec.y) labels.append(spec.fname) self.axes.legend(labels, ncol=4, loc='upper center', bbox_to_anchor=[0.5, 1.1], columnspacing=1.0, labelspacing=0.0, handletextpad=0.0, handlelength=1.5, fancybox=True, shadow=True) for c in self.cursors: self.axes.axvline(c.x, color=c.color) self.fig.canvas.draw()
class TestSharedXTransform(TestCase): def setUp(self): # Expected pixel coordinates of the data range, # extracted from the GIMP self.x_pixel_range = (79, 576) self.top_y_pixel_range = (19, 199) self.bottom_y_pixel_range = (261, 442) self.xlims = (10, 90) self.ylims = (0, 1024) self.figure = Figure(figsize=(6, 5), dpi=100) self.axes = ( self.figure.add_subplot(211), self.figure.add_subplot(212), ) for axis in self.axes: axis.set( xlim=self.xlims, ylim=self.ylims, xlabel='X LABEL', ylabel='Y LABEL', ) self.figure.tight_layout() self.canvas = Canvas(self.figure) self.transform = SharedXTransform( canvas=self.canvas) def test_setup(self): assert len(self.axes) == 2 def test_rendering(self): filename = os.path.join( tempfile.gettempdir(), 'test_multi.png') self.canvas.print_figure(filename) assert os.path.isfile(filename) def test_number_of_regions(self): xvals = [10, 30, 80, 90] regions = list(self.transform.x_regions(xvals)) assert len(regions) == 6 def test_regions(self): xvals = [10, 30, 80, 90] regions = list(self.transform.x_regions(xvals)) top_transform = AxisTransform(canvas=self.canvas, axis=self.axes[0]) bottom_transform = AxisTransform(canvas=self.canvas, axis=self.axes[1]) # First 3 regions belong to the top axis # Last 3 regions belong to the bottom axis top_expected = [ Region( xmin=self.x_pixel_range[0], xmax=top_transform.transform_pixels(30, 0.)['x'][0], ymin=self.top_y_pixel_range[0], ymax=self.top_y_pixel_range[1], ), Region( xmin=top_transform.transform_pixels(30, 0)['x'][0], xmax=top_transform.transform_pixels(80, 0.)['x'][0], ymin=self.top_y_pixel_range[0], ymax=self.top_y_pixel_range[1], ), Region( xmin=top_transform.transform_pixels(80, 0)['x'][0], xmax=top_transform.transform_pixels(90, 0.)['x'][0], ymin=self.top_y_pixel_range[0], ymax=self.top_y_pixel_range[1], ), ] bottom_expected = [ Region( xmin=self.x_pixel_range[0], xmax=top_transform.transform_pixels(30, 0.)['x'][0], ymin=self.bottom_y_pixel_range[0], ymax=self.bottom_y_pixel_range[1], ), Region( xmin=top_transform.transform_pixels(30, 0)['x'][0], xmax=top_transform.transform_pixels(80, 0.)['x'][0], ymin=self.bottom_y_pixel_range[0], ymax=self.bottom_y_pixel_range[1], ), Region( xmin=top_transform.transform_pixels(80, 0)['x'][0], xmax=top_transform.transform_pixels(90, 0.)['x'][0], ymin=self.bottom_y_pixel_range[0], ymax=self.bottom_y_pixel_range[1], ), ] for region, expected in zip(regions, top_expected + bottom_expected): self.regions_close(region, expected) # Helper functions @staticmethod def integer_close(a, b): return abs(a - b) <= 1 def regions_close(self, a, b): return ( self.integer_close(a.xmin, b.xmin) & self.integer_close(a.xmax, b.xmax) & self.integer_close(a.ymin, b.ymin) & self.integer_close(a.ymax, b.ymax) )
class DummyGridScan(template): def __init__(self): super(DummyGridScan, self).__init__() self.estimated_step_time = 0.0005 self.fig = Figure() self.data = None def open_scan(self): self.fig.clear() self.data = np.zeros(self.grid_shape, dtype=np.float64) self.data.fill(np.nan) self.ax = self.fig.add_subplot(111) self.ax.set_aspect('equal') mult = 1. / self._unit_conversion[self.size_unit] x, y = (mult * self.scan_axes[-1], mult * self.scan_axes[-2]) self.ax.set_xlim(x.min(), x.max()) self.ax.set_ylim(y.min(), y.max()) def scan_function(self, *indices): time.sleep(0.0005) x, y = (self.scan_axes[-1][indices[-1]], self.scan_axes[-2][indices[-2]]) self.data[indices] = np.sin(2 * np.pi * 2e6 * x) * np.cos( 2 * np.pi * 2e6 * y) if self.num_axes == 2: self.check_for_data_request(self.data) elif self.num_axes == 3: self.check_for_data_request(self.data[indices[0], :, :]) #@profile #def start(self, rate=0.1): # super(DummyGridScanner, self).start(0.1) def run(self, rate=0.1): fname = 'profiling.stats' cProfile.runctx('super(DummyGridScan, self).run(%.2f)' % rate, globals(), locals(), filename=fname) stats = pstats.Stats(fname) stats.strip_dirs() stats.sort_stats('cumulative') stats.print_stats() def update(self, force=False): super(DummyGridScan, self).update(force) if self.data is None or self.fig.canvas is None: print 'no canvas or data' return if force: data = (self.data, ) else: data = self.request_data() if data is not False: data, = data if not np.any(np.isfinite(data)): return if not self.ax.collections: mult = 1. / self._unit_conversion[self.size_unit] self.ax.pcolormesh(mult * self.scan_axes[-1], mult * self.scan_axes[-2], data) cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick) cid = self.fig.canvas.mpl_connect('pick_event', self.onpick4) else: img, = self.ax.collections img.set_array(data[:-1, :-1].ravel()) try: img_min = data[np.isfinite(data)].min() img_max = data[np.isfinite(data)].max() except ValueError: print 'There may have been a NaN error' img_min = 0 img_max = 1 img.set_clim(img_min, img_max) self.ax.relim() self.fig.canvas.draw() def get_qt_ui(self): return DummyGridScanUI(self) def onclick(self, event): print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % ( event.button, event.x, event.y, event.xdata, event.ydata) init_scale = self._unit_conversion[ self.size_unit] / self._unit_conversion[self.init_unit] self.init[:2] = (event.xdata * init_scale, event.ydata * init_scale) self.init_updated.emit(self.init) def onpick4(self, event): artist = event.artist if isinstance(artist, matplotlib.image.AxesImage): im = artist A = im.get_array() print('onpick4 image', A.shape)
class TopPanel(BasePanel): def __init__(self, parent): BasePanel.__init__(self, parent=parent) self.parent = parent self.img_filename = None self.input_phil = None self.sparams = None self.coord_filename = None self.mtz_filename = None self.stol_filename = None self.ref_img_filename = None self.dblclick = False self.project_folder = ct.InputCtrl(self, label='Project Folder: ', label_size=(150, -1), label_style='bold', value=os.path.abspath(os.curdir), buttons=True) self.project_title = ct.InputCtrl(self, label='Description', label_size=(150, -1), label_style='normal') self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE | wx.SP_3DSASH | wx.SP_NOBORDER) self.file_panel = wx.Panel(self.splitter, size=(-1, 200)) self.file_sizer = wx.BoxSizer(wx.VERTICAL) self.file_panel.SetSizer(self.file_sizer) self.preview_panel = wx.Panel(self.splitter, size=(-1, 500)) self.preview_sizer = wx.BoxSizer(wx.VERTICAL) self.preview_panel.SetSizer(self.preview_sizer) self.splitter.SplitHorizontally(self.file_panel, self.preview_panel, 200) self.input = FileListCtrl(self.file_panel) self.file_sizer.Add(self.input, 1, flag=wx.ALL | wx.EXPAND, border=10) # Image preview box w/ options prev_box = wx.GridBagSizer(5, 15) # self.opt_knb_start = ct.KnobCtrl(self.preview_panel, # label='start', # label_size=(40, -1), # spin_ctr_size=(50, -1), # knob_size=(120, 120), # values_start=0, # values_end=360, # values_step=1, # value=0) # # self.opt_knb_end = ct.KnobCtrl(self.preview_panel, # label='end', # label_size=(40, -1), # spin_ctr_size=(50, -1), # knob_size=(120, 120), # values_start=0, # values_end=360, # values_step=1, # value=360) self.opt_spc_start = ct.SpinCtrl(self.preview_panel, label='start:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='0', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=1) self.opt_spc_end = ct.SpinCtrl(self.preview_panel, label='finish:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='360', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=1) self.opt_spc_osc = ct.SpinCtrl(self.preview_panel, label='step:', label_size=(50, -1), ctrl_size=(60, -1), ctrl_value='1.0', ctrl_max=360, ctrl_min=0, ctrl_step=0.1, ctrl_digits=2) self.opt_btn_prev = wx.Button(self.preview_panel, label='PREVIEW IMAGE') self.opt_chk_bkg = wx.CheckBox(self.preview_panel, label='Add Background') self.opt_chk_bkg.SetValue(True) self.opt_chk_noise = wx.CheckBox(self.preview_panel, label='Add Noise') self.opt_chk_noise.SetValue(True) self.opt_chk_rand = wx.CheckBox(self.preview_panel, label='Randomize Orientation') self.opt_chk_rand.SetValue(True) self.opt_spc_scale = ct.SpinCtrl(self.preview_panel, label='Crystal size (um): ', label_size=(120, -1), ctrl_size=(100, -1), ctrl_min=1, ctrl_max=1000, ctrl_step=1, ctrl_value=30) self.img_figure = Figure(figsize=(3, 3)) self.img_axes = self.img_figure.add_subplot(111) self.img_axes.set_frame_on(False) self.img_axes.axis('off') self.img_axes.set_aspect('equal') self.img_figure.patch.set_visible(False) self.img_canvas = FigureCanvas(self.preview_panel, -1, self.img_figure) prev_box.Add(self.opt_spc_start, pos=(0, 0)) prev_box.Add(self.opt_spc_end, pos=(0, 1)) prev_box.Add(self.opt_spc_osc, pos=(1, 0)) prev_box.Add(self.opt_chk_bkg, flag=wx.EXPAND, pos=(4, 0), span=(1, 2)) prev_box.Add(self.opt_chk_noise, flag=wx.EXPAND, pos=(5, 0), span=(1, 2)) prev_box.Add(self.opt_chk_rand, flag=wx.EXPAND, pos=(6, 0), span=(1, 2)) prev_box.Add(self.opt_spc_scale, flag=wx.EXPAND, pos=(7, 0), span=(1, 2)) prev_box.Add(self.opt_btn_prev, flag=wx.EXPAND, pos=(8, 0), span=(1, 2)) prev_box.Add(self.img_canvas, pos=(0, 2), span=(9, 1), flag=wx.EXPAND) prev_box.AddGrowableCol(2) prev_box.AddGrowableRow(8) self.preview_sizer.Add(prev_box, 1, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.project_title, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.project_folder, flag=wx.EXPAND | wx.ALL, border=10) self.main_sizer.Add(self.splitter, 1, flag=wx.EXPAND) # Button bindings self.Bind(wx.EVT_BUTTON, self.onRunPreview, self.opt_btn_prev) # Thread bindings self.Bind(thr.EVT_NBDONE, self.onFinishedSimThread) # Image bindings xid = self.img_canvas.mpl_connect('button_press_event', self.on_button_press) xid = self.img_canvas.mpl_connect('button_release_event', self.on_button_release) def onRunPreview(self, e): e.Skip() def generate_phil(self): coord_path = None FCalc_path = None bkg_path = None img_path = None # Grab inputs (if any) from file list control idxs = self.input.ctr.GetItemCount() inputs = [self.input.ctr.GetItemData(i) for i in range(idxs)] for idx in range(idxs): item = self.input.ctr.GetItemData(idx) item_type_sel = item.type_selection item_type = item.type.type.GetString(item_type_sel) if item_type == 'coordinates': coord_path = item.path elif item_type == 'structure factors': FCalc_path = item.path elif item_type == 'background': bkg_path = item.path elif item_type == 'raw image file': img_path = item.path simtbx_phil_string = '\n'.join([ 'description = {}'.format( noneset(self.project_title.ctr.GetValue())), 'output = {}'.format(noneset(self.project_folder.ctr.GetValue())), 'reference_coordinates = {}'.format(coord_path), 'reference_FCalc = {}'.format(FCalc_path), 'reference_image = {}'.format(img_path), 'radial_average_background = {}'.format(bkg_path), 'dataset', '{', ' start_phi = {}'.format(str(self.opt_spc_start.ctr.GetValue())), ' finish_phi = {}'.format(str(self.opt_spc_end.ctr.GetValue())), ' oscillation = {}'.format(str(self.opt_spc_osc.ctr.GetValue())), ' }' ]) self.input_phil = ip.parse(simtbx_phil_string) def run_simulator(self, init=None): pass def run_preview(self): img_filename = 'test_image.{}'.format(self.sparams.image_format) self.img_filename = os.path.join(self.sparams.output, img_filename) self.start_timer = time.time() self.sim = thr.nanoBraggThread( self, params=self.sparams, add_background=self.opt_chk_bkg.GetValue(), add_noise=self.opt_chk_noise.GetValue(), randomize=self.opt_chk_rand.GetValue(), pixel_scale=self.opt_spc_scale.ctr.GetValue(), preview=True) self.sim.start() def onFinishedSimThread(self, e): pixels = e.GetValue() self.display_image(pixels=pixels) print 'TOTAL TIME = ', time.time() - self.start_timer def display_image(self, pixels=None): if pixels is None: pixels = np.random.randint(low=0, high=1500000, size=(2576, 2576)) else: pixels = pixels.as_numpy_array() clim = (pixels.min(), np.percentile(pixels, 99)) self.img_axes.imshow( pixels, #interpolation='nearest', cmap='gray_r', clim=clim) self.img_figure.subplots_adjust(left=0, bottom=0, right=1, top=1) self.preview_panel.Layout() print 'DEBUG: AVERAGE PIXEL VALUE = ', np.mean(pixels) print 'DONE!' def on_button_press(self, e): if e.button == 1 and e.dblclick: self.dblclick = True else: self.dblclick = False def on_button_release(self, e): if e.button == 1 and self.dblclick: self.view_image() def view_image(self): viewer = thr.ImageViewerThread(self, file_string=self.img_filename) viewer.start()
class plotWindow(QtWidgets.QMainWindow): """ This class defines python plotting window, its features, buttons, colors, AC and DC analysis, plotting etc. """ def __init__(self, fpath, projectName): """This create constructor for plotWindow class.""" QtWidgets.QMainWindow.__init__(self) self.fpath = fpath self.projectName = projectName self.obj_appconfig = Appconfig() print("Complete Project Path : ", self.fpath) print("Project Name : ", self.projectName) self.obj_appconfig.print_info('Ngspice simulation is called : ' + self.fpath) self.obj_appconfig.print_info('PythonPlotting is called : ' + self.fpath) self.combo = [] self.combo1 = [] self.combo1_rev = [] # Creating Frame self.createMainFrame() def createMainFrame(self): self.mainFrame = QtWidgets.QWidget() self.dpi = 100 self.fig = Figure((7.0, 7.0), dpi=self.dpi) # Creating Canvas which will figure self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.mainFrame) self.axes = self.fig.add_subplot(111) self.navToolBar = NavigationToolbar(self.canvas, self.mainFrame) # LeftVbox hold navigation tool bar and canvas self.left_vbox = QtWidgets.QVBoxLayout() self.left_vbox.addWidget(self.navToolBar) self.left_vbox.addWidget(self.canvas) # right VBOX is main Layout which hold right grid(bottom part) and top # grid(top part) self.right_vbox = QtWidgets.QVBoxLayout() self.right_grid = QtWidgets.QGridLayout() self.top_grid = QtWidgets.QGridLayout() # Get DataExtraction Details self.obj_dataext = DataExtraction() self.plotType = self.obj_dataext.openFile(self.fpath) self.obj_dataext.computeAxes() self.a = self.obj_dataext.numVals() self.chkbox = [] # Generating list of colors : # ,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)] self.full_colors = ['r', 'b', 'g', 'y', 'c', 'm', 'k'] self.color = [] for i in range(0, self.a[0] - 1): if i % 7 == 0: self.color.append(self.full_colors[0]) elif (i - 1) % 7 == 0: self.color.append(self.full_colors[1]) elif (i - 2) % 7 == 0: self.color.append(self.full_colors[2]) elif (i - 3) % 7 == 0: self.color.append(self.full_colors[3]) elif (i - 4) % 7 == 0: self.color.append(self.full_colors[4]) elif (i - 5) % 7 == 0: self.color.append(self.full_colors[5]) elif (i - 6) % 7 == 0: self.color.append(self.full_colors[6]) # Color generation ends here # Total number of voltage source self.volts_length = self.a[1] self.analysisType = QtWidgets.QLabel() self.top_grid.addWidget(self.analysisType, 0, 0) self.listNode = QtWidgets.QLabel() self.top_grid.addWidget(self.listNode, 1, 0) self.listBranch = QtWidgets.QLabel() self.top_grid.addWidget(self.listBranch, self.a[1] + 2, 0) for i in range(0, self.a[1]): # a[0]-1 self.chkbox.append(QtWidgets.QCheckBox(self.obj_dataext.NBList[i])) self.chkbox[i].setStyleSheet('color') self.chkbox[i].setToolTip('<b>Check To Plot</b>') self.top_grid.addWidget(self.chkbox[i], i + 2, 0) self.colorLab = QtWidgets.QLabel() self.colorLab.setText('____') self.colorLab.setStyleSheet( self.colorName(self.color[i]) + '; font-weight = bold;') self.top_grid.addWidget(self.colorLab, i + 2, 1) for i in range(self.a[1], self.a[0] - 1): # a[0]-1 self.chkbox.append(QtWidgets.QCheckBox(self.obj_dataext.NBList[i])) self.chkbox[i].setToolTip('<b>Check To Plot</b>') self.top_grid.addWidget(self.chkbox[i], i + 3, 0) self.colorLab = QtWidgets.QLabel() self.colorLab.setText('____') self.colorLab.setStyleSheet( self.colorName(self.color[i]) + '; font-weight = bold;') self.top_grid.addWidget(self.colorLab, i + 3, 1) # Buttons for Plot, multimeter, plotting function. self.clear = QtWidgets.QPushButton("Clear") self.warnning = QtWidgets.QLabel() self.funcName = QtWidgets.QLabel() self.funcExample = QtWidgets.QLabel() self.plotbtn = QtWidgets.QPushButton("Plot") self.plotbtn.setToolTip('<b>Press</b> to Plot') self.multimeterbtn = QtWidgets.QPushButton("Multimeter") self.multimeterbtn.setToolTip( '<b>RMS</b> value of the current and voltage is displayed') self.text = QtWidgets.QLineEdit() self.funcLabel = QtWidgets.QLabel() self.palette1 = QtGui.QPalette() self.palette2 = QtGui.QPalette() self.plotfuncbtn = QtWidgets.QPushButton("Plot Function") self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function') self.palette1.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue) self.palette2.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.funcName.setPalette(self.palette1) self.funcExample.setPalette(self.palette2) # Widgets for grid, plot button and multimeter button. self.right_vbox.addLayout(self.top_grid) self.right_vbox.addWidget(self.plotbtn) self.right_vbox.addWidget(self.multimeterbtn) self.right_grid.addWidget(self.funcLabel, 1, 0) self.right_grid.addWidget(self.text, 1, 1) self.right_grid.addWidget(self.plotfuncbtn, 2, 1) self.right_grid.addWidget(self.clear, 2, 0) self.right_grid.addWidget(self.warnning, 3, 0) self.right_grid.addWidget(self.funcName, 4, 0) self.right_grid.addWidget(self.funcExample, 4, 1) self.right_vbox.addLayout(self.right_grid) self.hbox = QtWidgets.QHBoxLayout() self.hbox.addLayout(self.left_vbox) self.hbox.addLayout(self.right_vbox) self.widget = QtWidgets.QWidget() self.widget.setLayout(self.hbox) # finalvbox self.scrollArea = QtWidgets.QScrollArea() self.scrollArea.setWidgetResizable(True) self.scrollArea.setWidget(self.widget) ''' Right side box containing checkbox for different inputs and options of plot, multimeter and plot function. ''' self.finalhbox = QtWidgets.QHBoxLayout() self.finalhbox.addWidget(self.scrollArea) # Right side window frame showing list of nodes and branches. self.mainFrame.setLayout(self.finalhbox) self.showMaximized() self.listNode.setText("<font color='indigo'>List of Nodes:</font>") self.listBranch.setText( "<font color='indigo'>List of Branches:</font>") self.funcLabel.setText("<font color='indigo'>Function:</font>") self.funcName.setText("<font color='indigo'>Standard functions</font>\ <br><br>Addition:<br>Subtraction:<br>\ Multiplication:<br>Division:<br>Comparison:") self.funcExample.setText( "\n\nNode1 + Node2\nNode1 - Node2\nNode1 * Node2\nNode1 / Node2\ \nNode1 vs Node2") # Connecting to plot and clear function self.clear.clicked.connect(self.pushedClear) self.plotfuncbtn.clicked.connect(self.pushedPlotFunc) self.multimeterbtn.clicked.connect(self.multiMeter) # for AC analysis if self.plotType[0] == 0: self.analysisType.setText("<b>AC Analysis</b>") if self.plotType[1] == 1: self.plotbtn.clicked.connect(self.onPush_decade) else: self.plotbtn.clicked.connect(self.onPush_ac) # for transient analysis elif self.plotType[0] == 1: self.analysisType.setText("<b>Transient Analysis</b>") self.plotbtn.clicked.connect(self.onPush_trans) else: # For DC analysis self.analysisType.setText("<b>DC Analysis</b>") self.plotbtn.clicked.connect(self.onPush_dc) self.setCentralWidget(self.mainFrame) # definition of functions pushedClear, pushedPlotFunc. def pushedClear(self): self.text.clear() self.axes.cla() self.canvas.draw() def pushedPlotFunc(self): self.parts = str(self.text.text()) self.parts = self.parts.split(" ") if self.parts[len(self.parts) - 1] == '': self.parts = self.parts[0:-1] self.values = self.parts self.comboAll = [] self.axes.cla() self.plotType2 = self.obj_dataext.openFile(self.fpath) if len(self.parts) <= 2: self.warnning.setText("Too few arguments!\nRefer syntax below!") QtWidgets.QMessageBox.about( self, "Warning!!", "Too Few Arguments/SYNTAX Error!\ \n Refer Examples") return else: self.warnning.setText("") a = [] finalResult = [] # p = 0 for i in range(len(self.parts)): if i % 2 == 0: for j in range(len(self.obj_dataext.NBList)): if self.parts[i] == self.obj_dataext.NBList[j]: a.append(j) if len(a) != len(self.parts) // 2 + 1: QtWidgets.QMessageBox.about( self, "Warning!!", "One of the operands doesn't belong to " "the above list of Nodes!!") return for i in a: self.comboAll.append(self.obj_dataext.y[i]) for i in range(len(a)): if a[i] == len(self.obj_dataext.NBList): QtWidgets.QMessageBox.about( self, "Warning!!", "One of the operands doesn't belong " + "to the above list!!") self.warnning.setText( "<font color='red'>To Err Is Human!<br>One of the " + "operands doesn't belong to the above list!!</font>") return if self.parts[1] == 'vs': if len(self.parts) > 3: self.warnning.setText("Enter two operands only!!") QtWidgets.QMessageBox.about(self, "Warning!!", "Recheck the expression syntax!") return else: self.axes.cla() for i in range(len(self.obj_dataext.y[a[0]])): self.combo.append(self.obj_dataext.y[a[0]][i]) self.combo1.append(self.obj_dataext.y[a[1]][i]) self.axes.plot(self.combo, self.combo1, c=self.color[1], label=str(2)) # _rev if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') self.axes.set_xlabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.set_ylabel('Current(I)-->') elif max(a) >= self.volts_length and min(a) < self.volts_length: QtWidgets.QMessageBox.about( self, "Warning!!", "Do not combine Voltage and Current!!") return else: for j in range(len(self.comboAll[0])): for i in range(len(self.values)): if i % 2 == 0: self.values[i] = str(self.comboAll[i // 2][j]) re = " ".join(self.values[:]) try: finalResult.append(eval(re)) except ArithmeticError: QtWidgets.QMessageBox.about(self, "Warning!!", "Dividing by zero!!") return if self.plotType2[0] == 0: # self.setWindowTitle('AC Analysis') if self.plotType2[1] == 1: self.axes.semilogx(self.obj_dataext.x, finalResult, c=self.color[0], label=str(1)) else: self.axes.plot(self.obj_dataext.x, finalResult, c=self.color[0], label=str(1)) self.axes.set_xlabel('freq-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') elif self.plotType2[0] == 1: # self.setWindowTitle('Transient Analysis') self.axes.plot(self.obj_dataext.x, finalResult, c=self.color[0], label=str(1)) self.axes.set_xlabel('time-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') else: # self.setWindowTitle('DC Analysis') self.axes.plot(self.obj_dataext.x, finalResult, c=self.color[0], label=str(1)) self.axes.set_xlabel('I/P Voltage-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) self.canvas.draw() self.combo = [] self.combo1 = [] self.combo1_rev = [] # definition of functions onPush_decade, onPush_ac, onPush_trans,\ # onPush_dc, color and multimeter and getRMSValue. def onPush_decade(self): boxCheck = 0 self.axes.cla() for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 self.axes.semilogx(self.obj_dataext.x, self.obj_dataext.y[j], c=self.color[j], label=str(j + 1)) self.axes.set_xlabel('freq-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: QtWidgets.QMessageBox.about( self, "Warning!!", "Please select at least one Node OR Branch") return self.canvas.draw() def onPush_ac(self): self.axes.cla() boxCheck = 0 for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 self.axes.plot(self.obj_dataext.x, self.obj_dataext.y[j], c=self.color[j], label=str(j + 1)) self.axes.set_xlabel('freq-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: QtWidgets.QMessageBox.about( self, "Warning!!", "Please select at least one Node OR Branch") return self.canvas.draw() def onPush_trans(self): self.axes.cla() boxCheck = 0 for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 self.axes.plot(self.obj_dataext.x, self.obj_dataext.y[j], c=self.color[j], label=str(j + 1)) self.axes.set_xlabel('time-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: QtWidgets.QMessageBox.about( self, "Warning!!", "Please select at least one Node OR Branch") return self.canvas.draw() def onPush_dc(self): boxCheck = 0 self.axes.cla() for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 self.axes.plot(self.obj_dataext.x, self.obj_dataext.y[j], c=self.color[j], label=str(j + 1)) self.axes.set_xlabel('Voltage Sweep(V)-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: QtWidgets.QMessageBox.about( self, "Warning!!", "Please select atleast one Node OR Branch") return self.canvas.draw() def colorName(self, letter): return { 'r': 'color:red', 'b': 'color:blue', 'g': 'color:green', 'y': 'color:yellow', 'c': 'color:cyan', 'm': 'color:magenta', 'k': 'color:black' }[letter] def multiMeter(self): print("Function : MultiMeter") self.obj = {} boxCheck = 0 loc_x = 300 loc_y = 300 for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): print("Check box", self.obj_dataext.NBList[j]) boxCheck += 1 if self.obj_dataext.NBList[j] in self.obj_dataext.NBIList: voltFlag = False else: voltFlag = True # Initializing Multimeter self.obj[j] = MultimeterWidgetClass( self.obj_dataext.NBList[j], self.getRMSValue(self.obj_dataext.y[j]), loc_x, loc_y, voltFlag) loc_x += 50 loc_y += 50 # Adding object of multimeter to dictionary (self.obj_appconfig.dock_dict[ self.obj_appconfig.current_project['ProjectName']].append( self.obj[j])) if boxCheck == 0: QtWidgets.QMessageBox.about( self, "Warning!!", "Please select at least one Node OR Branch") def getRMSValue(self, dataPoints): getcontext().prec = 5 return np.sqrt(np.mean(np.square(dataPoints)))
def __init__(self): super(DummyGridScan, self).__init__() self.estimated_step_time = 0.0005 self.fig = Figure() self.data = None
class App: def __init__(self, masterWindow): self.masterWindow = masterWindow masterWindow.title("Relative position of transponder") timeFrame = tk.Frame(self.masterWindow, bd=1) timeFrame.pack(side=tk.TOP) timeTxtLabel = tk.Label(timeFrame, text="UTC Time:", font=("Courier", 16)) timeTxtLabel.pack(side=tk.LEFT) self.timeLabel = tk.Label(timeFrame, text="0:0:0", font=("Courier", 16)) self.timeLabel.pack(side=tk.RIGHT) sensorFrame = tk.Frame(self.masterWindow, bd=1) sensorFrame.pack(side=tk.TOP) sensorCntTxtLabel = tk.Label(sensorFrame, text="Transponder Count:", font=("Courier", 16)) sensorCntTxtLabel.pack(side=tk.LEFT) self.sensorCntLabel = tk.Label(sensorFrame, text="0", font=("Courier", 16)) self.sensorCntLabel.pack(side=tk.RIGHT) self.drawFrame = tk.Frame(self.masterWindow, bd=1) self.drawFrame.pack(side=tk.TOP) self.f = Figure(figsize=(5, 4), dpi=100) self.ax = self.f.add_subplot(111) v1 = (0, -5) v2 = (0, 5) soa = np.array([[0, 0, v1[0], v1[1]], [0, 0, v2[0], v2[1]]]) X, Y, U, V = zip(*soa) print(soa) print("X", X) print("Y", Y) print("U", U) print("V", V) self.ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color='gb') # self.ax.set_xlim([35.72034, 35.72038]) # self.ax.set_ylim([139.7555, 139.7559]) self.ax.set_xlim([-5, 5]) self.ax.set_ylim([-5, 5]) self.canvas = FigureCanvasTkAgg(self.f, master=self.drawFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1) yAxisLabel=tk.Label(self.drawFrame, text="Latitude NS (meter)", \ font=("Courier", 16), wraplength=1) yAxisLabel.pack(side=tk.LEFT) xAxisLabel = tk.Label(masterWindow, text="Longitude E/W (meter)", font=("Courier", 16)) xAxisLabel.pack(side=tk.BOTTOM) #initilize loop self.masterWindow.after(1000, self.update) self.angle = 0 tk.mainloop() def update(self): global g_t_pos, g_s_pos, g_time, g_draw, g_n_sensor self.timeLabel.config(text="%d:%d:%.2f" % (g_time[0], g_time[1], g_time[2])) self.sensorCntLabel.config(text="%d" % (g_n_sensor)) if g_draw: print("drawing") # self.f = Figure(figsize=(5, 4), dpi=100) self.ax.clear() self.ax = self.f.add_subplot(111) # v1 = (4*math.cos(self.angle), 4*math.sin(self.angle)) # v2 = (4*math.cos(-self.angle), 4*math.sin(-self.angle)) # if self.angle>=math.pi*2: # self.angle=self.angle-math.pi*2+0.5 # else: # self.angle=self.angle+0.2 # soa = np.array([[0, 0, v1[0], v1[1]], [0, 0, v2[0], v2[1]]]) # X, Y, U, V = zip(*soa) soa = 0 for i in range(1, g_n_sensor + 1): # print("i:%d"%i) mag = 111321 soa_a = np.array([ 0, 0, (g_t_pos[i, 0] - g_s_pos[0]) * mag, (g_t_pos[i, 1] - g_s_pos[1]) * mag ]) if i == 1: soa = soa_a else: soa = np.vstack((soa, soa_a)) # print("soa",soa) if soa.ndim == 1: X = soa[0] Y = soa[1] U = soa[2] V = soa[3] else: X, Y, U, V = zip(*soa) # print("X", X) # print("Y", Y) # print("U", U) # print("V", V) self.ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color='gb') # self.ax.set_xlim([35.72034, 35.72038]) # self.ax.set_ylim([139.7555, 139.7559]) space = 10 try: self.ax.set_xlim([ min(np.append(U, X)) - space, max(np.append(U, X)) + space ]) self.ax.set_ylim([ min(np.append(Y, V)) - space, max(np.append(Y, V)) + space ]) except TypeError: self.ax.set_xlim([U - space, U + space]) self.ax.set_ylim([V - space, V + space]) # self.canvas = FigureCanvasTkAgg(self.f, master=self.drawFrame) self.canvas.draw() # self.canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1) g_draw = False # print("Plotting update function") self.masterWindow.after(int(PLOT_T_INTERVAL * 1e3), self.update)
def createMainFrame(self): self.mainFrame = QtWidgets.QWidget() self.dpi = 100 self.fig = Figure((7.0, 7.0), dpi=self.dpi) # Creating Canvas which will figure self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.mainFrame) self.axes = self.fig.add_subplot(111) self.navToolBar = NavigationToolbar(self.canvas, self.mainFrame) # LeftVbox hold navigation tool bar and canvas self.left_vbox = QtWidgets.QVBoxLayout() self.left_vbox.addWidget(self.navToolBar) self.left_vbox.addWidget(self.canvas) # right VBOX is main Layout which hold right grid(bottom part) and top # grid(top part) self.right_vbox = QtWidgets.QVBoxLayout() self.right_grid = QtWidgets.QGridLayout() self.top_grid = QtWidgets.QGridLayout() # Get DataExtraction Details self.obj_dataext = DataExtraction() self.plotType = self.obj_dataext.openFile(self.fpath) self.obj_dataext.computeAxes() self.a = self.obj_dataext.numVals() self.chkbox = [] # Generating list of colors : # ,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)] self.full_colors = ['r', 'b', 'g', 'y', 'c', 'm', 'k'] self.color = [] for i in range(0, self.a[0] - 1): if i % 7 == 0: self.color.append(self.full_colors[0]) elif (i - 1) % 7 == 0: self.color.append(self.full_colors[1]) elif (i - 2) % 7 == 0: self.color.append(self.full_colors[2]) elif (i - 3) % 7 == 0: self.color.append(self.full_colors[3]) elif (i - 4) % 7 == 0: self.color.append(self.full_colors[4]) elif (i - 5) % 7 == 0: self.color.append(self.full_colors[5]) elif (i - 6) % 7 == 0: self.color.append(self.full_colors[6]) # Color generation ends here # Total number of voltage source self.volts_length = self.a[1] self.analysisType = QtWidgets.QLabel() self.top_grid.addWidget(self.analysisType, 0, 0) self.listNode = QtWidgets.QLabel() self.top_grid.addWidget(self.listNode, 1, 0) self.listBranch = QtWidgets.QLabel() self.top_grid.addWidget(self.listBranch, self.a[1] + 2, 0) for i in range(0, self.a[1]): # a[0]-1 self.chkbox.append(QtWidgets.QCheckBox(self.obj_dataext.NBList[i])) self.chkbox[i].setStyleSheet('color') self.chkbox[i].setToolTip('<b>Check To Plot</b>') self.top_grid.addWidget(self.chkbox[i], i + 2, 0) self.colorLab = QtWidgets.QLabel() self.colorLab.setText('____') self.colorLab.setStyleSheet( self.colorName(self.color[i]) + '; font-weight = bold;') self.top_grid.addWidget(self.colorLab, i + 2, 1) for i in range(self.a[1], self.a[0] - 1): # a[0]-1 self.chkbox.append(QtWidgets.QCheckBox(self.obj_dataext.NBList[i])) self.chkbox[i].setToolTip('<b>Check To Plot</b>') self.top_grid.addWidget(self.chkbox[i], i + 3, 0) self.colorLab = QtWidgets.QLabel() self.colorLab.setText('____') self.colorLab.setStyleSheet( self.colorName(self.color[i]) + '; font-weight = bold;') self.top_grid.addWidget(self.colorLab, i + 3, 1) # Buttons for Plot, multimeter, plotting function. self.clear = QtWidgets.QPushButton("Clear") self.warnning = QtWidgets.QLabel() self.funcName = QtWidgets.QLabel() self.funcExample = QtWidgets.QLabel() self.plotbtn = QtWidgets.QPushButton("Plot") self.plotbtn.setToolTip('<b>Press</b> to Plot') self.multimeterbtn = QtWidgets.QPushButton("Multimeter") self.multimeterbtn.setToolTip( '<b>RMS</b> value of the current and voltage is displayed') self.text = QtWidgets.QLineEdit() self.funcLabel = QtWidgets.QLabel() self.palette1 = QtGui.QPalette() self.palette2 = QtGui.QPalette() self.plotfuncbtn = QtWidgets.QPushButton("Plot Function") self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function') self.palette1.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue) self.palette2.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.funcName.setPalette(self.palette1) self.funcExample.setPalette(self.palette2) # Widgets for grid, plot button and multimeter button. self.right_vbox.addLayout(self.top_grid) self.right_vbox.addWidget(self.plotbtn) self.right_vbox.addWidget(self.multimeterbtn) self.right_grid.addWidget(self.funcLabel, 1, 0) self.right_grid.addWidget(self.text, 1, 1) self.right_grid.addWidget(self.plotfuncbtn, 2, 1) self.right_grid.addWidget(self.clear, 2, 0) self.right_grid.addWidget(self.warnning, 3, 0) self.right_grid.addWidget(self.funcName, 4, 0) self.right_grid.addWidget(self.funcExample, 4, 1) self.right_vbox.addLayout(self.right_grid) self.hbox = QtWidgets.QHBoxLayout() self.hbox.addLayout(self.left_vbox) self.hbox.addLayout(self.right_vbox) self.widget = QtWidgets.QWidget() self.widget.setLayout(self.hbox) # finalvbox self.scrollArea = QtWidgets.QScrollArea() self.scrollArea.setWidgetResizable(True) self.scrollArea.setWidget(self.widget) ''' Right side box containing checkbox for different inputs and options of plot, multimeter and plot function. ''' self.finalhbox = QtWidgets.QHBoxLayout() self.finalhbox.addWidget(self.scrollArea) # Right side window frame showing list of nodes and branches. self.mainFrame.setLayout(self.finalhbox) self.showMaximized() self.listNode.setText("<font color='indigo'>List of Nodes:</font>") self.listBranch.setText( "<font color='indigo'>List of Branches:</font>") self.funcLabel.setText("<font color='indigo'>Function:</font>") self.funcName.setText("<font color='indigo'>Standard functions</font>\ <br><br>Addition:<br>Subtraction:<br>\ Multiplication:<br>Division:<br>Comparison:") self.funcExample.setText( "\n\nNode1 + Node2\nNode1 - Node2\nNode1 * Node2\nNode1 / Node2\ \nNode1 vs Node2") # Connecting to plot and clear function self.clear.clicked.connect(self.pushedClear) self.plotfuncbtn.clicked.connect(self.pushedPlotFunc) self.multimeterbtn.clicked.connect(self.multiMeter) # for AC analysis if self.plotType[0] == 0: self.analysisType.setText("<b>AC Analysis</b>") if self.plotType[1] == 1: self.plotbtn.clicked.connect(self.onPush_decade) else: self.plotbtn.clicked.connect(self.onPush_ac) # for transient analysis elif self.plotType[0] == 1: self.analysisType.setText("<b>Transient Analysis</b>") self.plotbtn.clicked.connect(self.onPush_trans) else: # For DC analysis self.analysisType.setText("<b>DC Analysis</b>") self.plotbtn.clicked.connect(self.onPush_dc) self.setCentralWidget(self.mainFrame)
from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas #reference #http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html#commentform fig = Figure() canvas = FigureCanvas(fig) # first axes ax1 = fig.add_axes([0.1, 0.1, 0.2, 0.2]) line, = ax1.plot([0, 1], [0, 1]) ax1.set_title("ax1") # second axes ax2 = fig.add_axes([0.4, 0.3, 0.4, 0.5]) sca = ax2.scatter([1, 3, 5], [2, 1, 2]) ax2.set_title("ax2") canvas.print_figure('demo.jpg')
def __init__(self, masterWindow): self.masterWindow = masterWindow masterWindow.title("Relative position of transponder") timeFrame = tk.Frame(self.masterWindow, bd=1) timeFrame.pack(side=tk.TOP) timeTxtLabel = tk.Label(timeFrame, text="UTC Time:", font=("Courier", 16)) timeTxtLabel.pack(side=tk.LEFT) self.timeLabel = tk.Label(timeFrame, text="0:0:0", font=("Courier", 16)) self.timeLabel.pack(side=tk.RIGHT) sensorFrame = tk.Frame(self.masterWindow, bd=1) sensorFrame.pack(side=tk.TOP) sensorCntTxtLabel = tk.Label(sensorFrame, text="Transponder Count:", font=("Courier", 16)) sensorCntTxtLabel.pack(side=tk.LEFT) self.sensorCntLabel = tk.Label(sensorFrame, text="0", font=("Courier", 16)) self.sensorCntLabel.pack(side=tk.RIGHT) self.drawFrame = tk.Frame(self.masterWindow, bd=1) self.drawFrame.pack(side=tk.TOP) self.f = Figure(figsize=(5, 4), dpi=100) self.ax = self.f.add_subplot(111) v1 = (0, -5) v2 = (0, 5) soa = np.array([[0, 0, v1[0], v1[1]], [0, 0, v2[0], v2[1]]]) X, Y, U, V = zip(*soa) print(soa) print("X", X) print("Y", Y) print("U", U) print("V", V) self.ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color='gb') # self.ax.set_xlim([35.72034, 35.72038]) # self.ax.set_ylim([139.7555, 139.7559]) self.ax.set_xlim([-5, 5]) self.ax.set_ylim([-5, 5]) self.canvas = FigureCanvasTkAgg(self.f, master=self.drawFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1) yAxisLabel=tk.Label(self.drawFrame, text="Latitude NS (meter)", \ font=("Courier", 16), wraplength=1) yAxisLabel.pack(side=tk.LEFT) xAxisLabel = tk.Label(masterWindow, text="Longitude E/W (meter)", font=("Courier", 16)) xAxisLabel.pack(side=tk.BOTTOM) #initilize loop self.masterWindow.after(1000, self.update) self.angle = 0 tk.mainloop()
def initUI(self): graph_task = QLabel('Displaying Sizemometer Graph') graph_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.plot_txt = QLineEdit() self.button = QPushButton('Plot') self.button.clicked.connect(self.plot) power_task = QLabel('Calculating Max Power Generated') power_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") power_url_lbl = QLabel('DeepZoom Link:') power_url = QLineEdit('http://www.deepzoom.com/') p_calc_btn = QPushButton('Calculate Power') p_calc_btn.clicked.connect(self.calculate_p) blank = QLabel('') warning = QLabel('DO NOT USE ANY OF THE ARROWS IN THE CABLE AREA') num_tb_lbl = QLabel('Number of Turbines') density_lbl = QLabel('Density of Seawater (kg/m^3') diameter_lbl = QLabel('Diameter of One Rotor (m)') water_vel_lbl = QLabel('Velocity of Water (knots)') efficiency_lbl = QLabel('Efficiency of Turbines (%)') ans_lbl = QLabel('Answer - Maximum Power Generated (W)') self.num_tb = QDoubleSpinBox() self.num_tb.setRange(0, 30) self.num_tb.setValue(4) self.density = QDoubleSpinBox() self.density.setDecimals(3) self.density.setValue(1.025) self.diameter = QDoubleSpinBox() self.diameter.setRange(0, 50) self.water_vel = QDoubleSpinBox() self.water_vel.setRange(0, 20) self.efficiency = QDoubleSpinBox() self.efficiency.setRange(0, 100) self.p_ans = QDoubleSpinBox() self.p_ans.setRange(0, 20000) #display IMU and depth reading readings_task = QLabel('Readings - IMU and Depth') readings_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") imu_x_lbl = QLabel('IMU x Value:') imu_y_lbl = QLabel('IMU y Value:') self.imu_x = QLineEdit() self.imu_y = QLineEdit() depth_lbl = QLabel('Respective Depth Reading:') self.depth = QLineEdit() self.depth.setText('0') rec_depth_lbl = QLabel('Recorded Depth Reading:') self.rec_depth = QLineEdit() self.rec_depth.setText('0') depth_record_btn = QPushButton('Record Depth') depth_record_btn.clicked.connect(self.calculate_depth) #display gui for calculating location of a/c wreckage location_task = QLabel('Calculating Location of Wreckage') location_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") calc_btn_loc = QPushButton('Calculate Location') calc_btn_loc.clicked.connect(self.calculate_loc) tol_lbl = QLabel('Take-off Location') heading_lbl = QLabel('Heading (degrees)') asc_as_lbl = QLabel('Ascent Airspeed (m/s)') asc_rate_lbl = QLabel('Ascent Rate (m/s)') eng_fail_time_lbl = QLabel('Time of Engine Failure (s)') desc_as_lbl = QLabel('Descent Airspeed (m/s)') desc_rate_lbl = QLabel('Descent Rate (m/s)') w_direc_lbl = QLabel('Wind Blowing From (degrees)') w_eqn_lbl = QLabel('Wind Direction Equation') asc_dist_x_lbl = QLabel('Ascent Distance X (m)') asc_dist_y_lbl = QLabel('Ascent Distance Y (m)') desc_dist_x_lbl = QLabel('Descent Distance X (m)') desc_dist_y_lbl = QLabel('Descent Distance Y (m)') wind_dist_x_lbl = QLabel('Wind Distance X (m)') wind_dist_y_lbl = QLabel('Wind Distance Y (m)') total_dist_x_lbl = QLabel('Total Distance X (m)') total_dist_y_lbl = QLabel('Total Distance Y (m)') ans_distance_lbl = QLabel('Location: Distance (m)') ans_angle_lbl = QLabel('Location: Direction (degrees)' ) # zero degrees is east , 90 degrees is north ans_heading_lbl = QLabel('Location: Heading (degrees)' ) # zero degrees is north, 90 degrees is east self.tol = QDoubleSpinBox() self.heading = QDoubleSpinBox() self.heading.setRange(0, 360) self.asc_as = QDoubleSpinBox() self.asc_rate = QDoubleSpinBox() self.eng_fail_time = QDoubleSpinBox() self.eng_fail_time.setRange(0, 1000) self.desc_as = QDoubleSpinBox() self.desc_rate = QDoubleSpinBox() self.desc_rate.setValue(1) self.w_dir = QDoubleSpinBox() self.w_dir.setRange(0, 360) self.w_eqn = QLineEdit() self.w_eqn.setText('-(1/720)*(t**2) + 25') self.asc_dist_x = QDoubleSpinBox() self.asc_dist_x.setRange(-30000, 30000) self.asc_dist_y = QDoubleSpinBox() self.asc_dist_y.setRange(-30000, 30000) self.desc_dist_x = QDoubleSpinBox() self.desc_dist_x.setRange(-30000, 30000) self.desc_dist_y = QDoubleSpinBox() self.desc_dist_y.setRange(-30000, 30000) self.wind_dist_x = QDoubleSpinBox() self.wind_dist_x.setRange(-30000, 30000) self.wind_dist_y = QDoubleSpinBox() self.wind_dist_y.setRange(-30000, 30000) self.total_dist_x = QDoubleSpinBox() self.total_dist_x.setRange(-30000, 30000) self.total_dist_y = QDoubleSpinBox() self.total_dist_y.setRange(-30000, 30000) self.ans_dist = QDoubleSpinBox() self.ans_dist.setRange(-30000, 30000) self.ans_angle = QDoubleSpinBox() self.ans_angle.setRange(-360, 360) self.ans_heading = QDoubleSpinBox() self.ans_heading.setRange(-360, 360) # create graph layout container graph = QVBoxLayout() graph.addWidget(graph_task) graph.addWidget(self.canvas) graph.addWidget(self.plot_txt) graph.addWidget(self.button) # create centre layout container p_calc = QGridLayout() p_calc.addWidget(power_task, 0, 1, 1, 2) p_calc.addWidget(num_tb_lbl, 1, 1) p_calc.addWidget(self.num_tb, 1, 2) p_calc.addWidget(density_lbl, 2, 1) p_calc.addWidget(self.density, 2, 2) p_calc.addWidget(diameter_lbl, 3, 1) p_calc.addWidget(self.diameter, 3, 2) p_calc.addWidget(water_vel_lbl, 4, 1) p_calc.addWidget(self.water_vel, 4, 2) p_calc.addWidget(efficiency_lbl, 5, 1) p_calc.addWidget(self.efficiency, 5, 2) p_calc.addWidget(p_calc_btn, 6, 1, 1, 2) p_calc.addWidget(ans_lbl, 8, 1) p_calc.addWidget(self.p_ans, 8, 2) p_calc.addWidget(blank, 7, 1) p_calc.addWidget(power_url_lbl, 9, 1) p_calc.addWidget(power_url, 10, 1, 1, 2) p_calc.addWidget(blank, 11, 1) p_calc.addWidget(readings_task, 12, 1, 1, 2) p_calc.addWidget(imu_x_lbl, 13, 1) p_calc.addWidget(self.imu_x, 13, 2) p_calc.addWidget(imu_y_lbl, 14, 1) p_calc.addWidget(self.imu_y, 14, 2) p_calc.addWidget(blank, 15, 1) p_calc.addWidget(depth_record_btn, 17, 1) p_calc.addWidget(depth_lbl, 18, 1) p_calc.addWidget(self.depth, 18, 2) p_calc.addWidget(rec_depth_lbl, 19, 1) p_calc.addWidget(self.rec_depth, 19, 2) # create calculating location layout container loc_calc = QGridLayout() loc_calc.addWidget(location_task, 0, 0, 1, 4) loc_calc.addWidget(heading_lbl, 2, 0) loc_calc.addWidget(self.heading, 2, 1) loc_calc.addWidget(asc_as_lbl, 3, 0) loc_calc.addWidget(self.asc_as, 3, 1) loc_calc.addWidget(asc_rate_lbl, 4, 0) loc_calc.addWidget(self.asc_rate, 4, 1) loc_calc.addWidget(eng_fail_time_lbl, 5, 0) loc_calc.addWidget(self.eng_fail_time, 5, 1) loc_calc.addWidget(desc_as_lbl, 6, 0) loc_calc.addWidget(self.desc_as, 6, 1) loc_calc.addWidget(desc_rate_lbl, 7, 0) loc_calc.addWidget(self.desc_rate, 7, 1) loc_calc.addWidget(w_eqn_lbl, 8, 0) loc_calc.addWidget(self.w_eqn, 8, 1, 1, 2) loc_calc.addWidget(w_direc_lbl, 9, 0) loc_calc.addWidget(self.w_dir, 9, 1) loc_calc.addWidget(calc_btn_loc, 10, 0, 1, 4) loc_calc.addWidget(blank, 11, 0) loc_calc.addWidget(asc_dist_x_lbl, 12, 0) loc_calc.addWidget(self.asc_dist_x, 12, 1) loc_calc.addWidget(asc_dist_y_lbl, 12, 2) loc_calc.addWidget(self.asc_dist_y, 12, 3) loc_calc.addWidget(desc_dist_x_lbl, 13, 0) loc_calc.addWidget(self.desc_dist_x, 13, 1) loc_calc.addWidget(desc_dist_y_lbl, 13, 2) loc_calc.addWidget(self.desc_dist_y, 13, 3) loc_calc.addWidget(wind_dist_x_lbl, 14, 0) loc_calc.addWidget(self.wind_dist_x, 14, 1) loc_calc.addWidget(wind_dist_y_lbl, 14, 2) loc_calc.addWidget(self.wind_dist_y, 14, 3) loc_calc.addWidget(total_dist_x_lbl, 15, 0) loc_calc.addWidget(self.total_dist_x, 15, 1) loc_calc.addWidget(total_dist_y_lbl, 15, 2) loc_calc.addWidget(self.total_dist_y, 15, 3) loc_calc.addWidget(blank, 16, 0) loc_calc.addWidget(ans_distance_lbl, 17, 0) loc_calc.addWidget(self.ans_dist, 17, 1) loc_calc.addWidget(ans_angle_lbl, 18, 0) loc_calc.addWidget(self.ans_angle, 18, 1) loc_calc.addWidget(ans_heading_lbl, 19, 0) loc_calc.addWidget(self.ans_heading, 19, 1) # create horizontal box layout container hbox = QHBoxLayout() hbox.addLayout(graph) hbox.addLayout(p_calc) hbox.addLayout(loc_calc) self.setLayout(hbox) #Set the layout self.setGeometry(10, 100, 1600, 600) self.setWindowTitle('Co-pilot GUI') self.show()
def create_main_frame(self): self.main_frame = QWidget() # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 self.fig = Figure(dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # # Bind the 'pick' event for clicking on one of the bars # self.canvas.mpl_connect('pick_event', self.on_pick) # Create the navigation toolbar, tied to the canvas # self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Other GUI controls # self.textbox = QLineEdit() self.textbox.setMinimumWidth(200) self.connect(self.textbox, SIGNAL('editingFinished ()'), self.on_draw) self.draw_button = QPushButton("&Draw") self.connect(self.draw_button, SIGNAL('clicked()'), self.on_draw) self.grid_cb = QCheckBox("Show &Grid") self.grid_cb.setChecked(False) self.connect(self.grid_cb, SIGNAL('stateChanged(int)'), self.on_draw) slider_label = QLabel('Line width:') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(1, 10) self.slider.setValue(2) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) self.connect(self.slider, SIGNAL('valueChanged(int)'), self.on_draw) self.table = QTableWidget() plot_cb_label = QLabel("Variable to plot:") self.plot_combobox = QComboBox() self.plot_combobox.addItems(CycleStats.fields) self.connect(self.plot_combobox, SIGNAL('currentIndexChanged(int)'), self.on_draw) self.field_listbox = QListWidget() self.field_listbox.setSelectionMode(QAbstractItemView.NoSelection) self.field_listbox.addItems(CycleStats.fields) for index in xrange(self.field_listbox.count()): item = self.field_listbox.item(index) item.setCheckState(Qt.CheckState(0)) self.field_listbox.setMinimumWidth(self.field_listbox.sizeHintForColumn(0)) self.connect(self.field_listbox, SIGNAL('itemClicked(QListWidgetItem *)'), self.on_draw) toparea = QSplitter() toparea.addWidget(self.field_listbox) toparea.addWidget(self.canvas) # # Layout with box sizers # hbox = QHBoxLayout() for w in [ plot_cb_label, self.plot_combobox, self.grid_cb, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) plotsection = QVBoxLayout() plotsection.addWidget(self.mpl_toolbar) plotsection.addWidget(toparea) #plotsection.addLayout(hbox) plotsectionwidget = QWidget() plotsectionwidget.setLayout(plotsection) vbox = QSplitter(Qt.Orientation.Vertical) vbox.addWidget(plotsectionwidget) vbox.addWidget(self.table) bigbox = QVBoxLayout() bigbox.addWidget(vbox) self.main_frame.setLayout(bigbox) self.setCentralWidget(self.main_frame)
print("enter Float for tolS") tolSentry.delete(0, end) TOLsENTRY.INSERT(0, '1.0') return tolN, tolS def drawNewTree(): tolN, tolS = getInputs() reDraw(tolS, tolN) root = Tk() # Abandon in chapter 9_7_2 # Label(root, text= "Plot Place Holder").grid(row= 0, columnspan= 3) # Added in chapter 9_7_2 reDraw.f = Figure(figsize = (5, 1), dpi = 100) reDraw.canvas = FigureCanvasTkAgg(reDraw.f, master = root) reDraw.canvas.show() reDraw.canvas.get_tk_widget().grid(row = 0, columnspan = 3) Label(root, text= "tolN").grid(row = 1, column = 0) tolNentry = Entry(root) tolNentry.grid(row = 1, column = 1) tolNentry.insert(0, '10') Label(root, text = "tolS").grid(row = 2, column = 0) tolSentry = Entry(root) tolSentry.grid(row = 2, column = 1) tolSentry.insert(0, '1.0') Button(root, text = 'ReDraw', command = drawNewTree).grid(row = 1, column = 2, \ rowspan = 3) chkBtnVar = IntVar()
def __init__(self, title, figsize, main_window): super().__init__(Figure(figsize)) self.title = title self.tool_bar = NavigationToolbar(self, main_window) self._ax = self.figure.subplots()
class graph_page(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) photo = PhotoImage(file=resource_path("graph.gif")) photolab = Label(self, image=photo) photolab.image = photo photolab.grid(row=0, column=1, sticky='nwes') self.lis = [k for k in DATA.keys()] self.variable = StringVar(self) self.variable.set(self.lis[0]) self.variable2 = StringVar(self) self.variable2.set(self.lis[-1]) self.opt1 = OptionMenu(self, self.variable, *self.lis) self.opt2 = OptionMenu(self, self.variable2, *self.lis) l1 = Label(self, text="From :", font=("Courier", 12)) l2 = Label(self, text="To :", font=("Courier", 12)) l1.grid(row=3, column=0) self.opt1.grid(row=3, column=1) l2.grid(row=4, column=0) self.opt2.grid(row=4, column=1) refb = Button(self, text="Refresh!", font=("Courier", 12), command=self.refresh) refb.grid(row=5, column=1) self.fig = Figure(figsize=(3, 2)) self.a = self.fig.add_subplot(111) self.a.plot([], [], color="green") self.a.set_title("Visualise your expenses !", fontsize=10) self.a.set_ylabel("Amount") self.a.set_xlabel("Day") self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.get_tk_widget().grid(row=1, column=0, rowspan=2, columnspan=2) self.canvas.draw() def refresh(self): global cur global target self.date1 = self.variable.get() self.date2 = self.variable2.get() self.lis = [k for k in DATA.keys()] if self.date1 == self.date2: messagebox.showerror("Warning", "Interval is invalid!") elif self.date2 not in self.lis[self.lis.index(self.date1):]: messagebox.showerror("Warning", "Your date is invalid!") else: self.lis = self.lis[self.lis.index(self.date1):( self.lis.index(self.date2) + 1)] x = np.arange(len(self.lis)) y = np.array([]) for date in self.lis: tot = 0 for expen in DATA[date]: tot += float(expen[1]) y = np.append(y, [tot]) self.a.clear() self.a.plot(x, y, color="green", marker="o") self.a.set_title("Expnses from {} to {}".format( self.date1, self.date2), fontsize=10) self.a.set_ylabel("Amount") self.a.set_xlabel("Day") t = [float(target) for _ in range(len(self.lis))] self.a.plot(x, t, color="blue") self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.get_tk_widget().grid(row=1, column=0, rowspan=2, columnspan=2) self.canvas.draw()
class Gui(QWidget): #base class of all user interface objects. def __init__(self): super(Gui, self).__init__() self.initUI() self.frontend = ROV("127.0.0.1", 8000) def initUI(self): graph_task = QLabel('Displaying Sizemometer Graph') graph_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.plot_txt = QLineEdit() self.button = QPushButton('Plot') self.button.clicked.connect(self.plot) power_task = QLabel('Calculating Max Power Generated') power_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") power_url_lbl = QLabel('DeepZoom Link:') power_url = QLineEdit('http://www.deepzoom.com/') p_calc_btn = QPushButton('Calculate Power') p_calc_btn.clicked.connect(self.calculate_p) blank = QLabel('') warning = QLabel('DO NOT USE ANY OF THE ARROWS IN THE CABLE AREA') num_tb_lbl = QLabel('Number of Turbines') density_lbl = QLabel('Density of Seawater (kg/m^3') diameter_lbl = QLabel('Diameter of One Rotor (m)') water_vel_lbl = QLabel('Velocity of Water (knots)') efficiency_lbl = QLabel('Efficiency of Turbines (%)') ans_lbl = QLabel('Answer - Maximum Power Generated (W)') self.num_tb = QDoubleSpinBox() self.num_tb.setRange(0, 30) self.num_tb.setValue(4) self.density = QDoubleSpinBox() self.density.setDecimals(3) self.density.setValue(1.025) self.diameter = QDoubleSpinBox() self.diameter.setRange(0, 50) self.water_vel = QDoubleSpinBox() self.water_vel.setRange(0, 20) self.efficiency = QDoubleSpinBox() self.efficiency.setRange(0, 100) self.p_ans = QDoubleSpinBox() self.p_ans.setRange(0, 20000) #display IMU and depth reading readings_task = QLabel('Readings - IMU and Depth') readings_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") imu_x_lbl = QLabel('IMU x Value:') imu_y_lbl = QLabel('IMU y Value:') self.imu_x = QLineEdit() self.imu_y = QLineEdit() depth_lbl = QLabel('Respective Depth Reading:') self.depth = QLineEdit() self.depth.setText('0') rec_depth_lbl = QLabel('Recorded Depth Reading:') self.rec_depth = QLineEdit() self.rec_depth.setText('0') depth_record_btn = QPushButton('Record Depth') depth_record_btn.clicked.connect(self.calculate_depth) #display gui for calculating location of a/c wreckage location_task = QLabel('Calculating Location of Wreckage') location_task.setStyleSheet( " font: bold; qproperty-alignment: AlignCenter") calc_btn_loc = QPushButton('Calculate Location') calc_btn_loc.clicked.connect(self.calculate_loc) tol_lbl = QLabel('Take-off Location') heading_lbl = QLabel('Heading (degrees)') asc_as_lbl = QLabel('Ascent Airspeed (m/s)') asc_rate_lbl = QLabel('Ascent Rate (m/s)') eng_fail_time_lbl = QLabel('Time of Engine Failure (s)') desc_as_lbl = QLabel('Descent Airspeed (m/s)') desc_rate_lbl = QLabel('Descent Rate (m/s)') w_direc_lbl = QLabel('Wind Blowing From (degrees)') w_eqn_lbl = QLabel('Wind Direction Equation') asc_dist_x_lbl = QLabel('Ascent Distance X (m)') asc_dist_y_lbl = QLabel('Ascent Distance Y (m)') desc_dist_x_lbl = QLabel('Descent Distance X (m)') desc_dist_y_lbl = QLabel('Descent Distance Y (m)') wind_dist_x_lbl = QLabel('Wind Distance X (m)') wind_dist_y_lbl = QLabel('Wind Distance Y (m)') total_dist_x_lbl = QLabel('Total Distance X (m)') total_dist_y_lbl = QLabel('Total Distance Y (m)') ans_distance_lbl = QLabel('Location: Distance (m)') ans_angle_lbl = QLabel('Location: Direction (degrees)' ) # zero degrees is east , 90 degrees is north ans_heading_lbl = QLabel('Location: Heading (degrees)' ) # zero degrees is north, 90 degrees is east self.tol = QDoubleSpinBox() self.heading = QDoubleSpinBox() self.heading.setRange(0, 360) self.asc_as = QDoubleSpinBox() self.asc_rate = QDoubleSpinBox() self.eng_fail_time = QDoubleSpinBox() self.eng_fail_time.setRange(0, 1000) self.desc_as = QDoubleSpinBox() self.desc_rate = QDoubleSpinBox() self.desc_rate.setValue(1) self.w_dir = QDoubleSpinBox() self.w_dir.setRange(0, 360) self.w_eqn = QLineEdit() self.w_eqn.setText('-(1/720)*(t**2) + 25') self.asc_dist_x = QDoubleSpinBox() self.asc_dist_x.setRange(-30000, 30000) self.asc_dist_y = QDoubleSpinBox() self.asc_dist_y.setRange(-30000, 30000) self.desc_dist_x = QDoubleSpinBox() self.desc_dist_x.setRange(-30000, 30000) self.desc_dist_y = QDoubleSpinBox() self.desc_dist_y.setRange(-30000, 30000) self.wind_dist_x = QDoubleSpinBox() self.wind_dist_x.setRange(-30000, 30000) self.wind_dist_y = QDoubleSpinBox() self.wind_dist_y.setRange(-30000, 30000) self.total_dist_x = QDoubleSpinBox() self.total_dist_x.setRange(-30000, 30000) self.total_dist_y = QDoubleSpinBox() self.total_dist_y.setRange(-30000, 30000) self.ans_dist = QDoubleSpinBox() self.ans_dist.setRange(-30000, 30000) self.ans_angle = QDoubleSpinBox() self.ans_angle.setRange(-360, 360) self.ans_heading = QDoubleSpinBox() self.ans_heading.setRange(-360, 360) # create graph layout container graph = QVBoxLayout() graph.addWidget(graph_task) graph.addWidget(self.canvas) graph.addWidget(self.plot_txt) graph.addWidget(self.button) # create centre layout container p_calc = QGridLayout() p_calc.addWidget(power_task, 0, 1, 1, 2) p_calc.addWidget(num_tb_lbl, 1, 1) p_calc.addWidget(self.num_tb, 1, 2) p_calc.addWidget(density_lbl, 2, 1) p_calc.addWidget(self.density, 2, 2) p_calc.addWidget(diameter_lbl, 3, 1) p_calc.addWidget(self.diameter, 3, 2) p_calc.addWidget(water_vel_lbl, 4, 1) p_calc.addWidget(self.water_vel, 4, 2) p_calc.addWidget(efficiency_lbl, 5, 1) p_calc.addWidget(self.efficiency, 5, 2) p_calc.addWidget(p_calc_btn, 6, 1, 1, 2) p_calc.addWidget(ans_lbl, 8, 1) p_calc.addWidget(self.p_ans, 8, 2) p_calc.addWidget(blank, 7, 1) p_calc.addWidget(power_url_lbl, 9, 1) p_calc.addWidget(power_url, 10, 1, 1, 2) p_calc.addWidget(blank, 11, 1) p_calc.addWidget(readings_task, 12, 1, 1, 2) p_calc.addWidget(imu_x_lbl, 13, 1) p_calc.addWidget(self.imu_x, 13, 2) p_calc.addWidget(imu_y_lbl, 14, 1) p_calc.addWidget(self.imu_y, 14, 2) p_calc.addWidget(blank, 15, 1) p_calc.addWidget(depth_record_btn, 17, 1) p_calc.addWidget(depth_lbl, 18, 1) p_calc.addWidget(self.depth, 18, 2) p_calc.addWidget(rec_depth_lbl, 19, 1) p_calc.addWidget(self.rec_depth, 19, 2) # create calculating location layout container loc_calc = QGridLayout() loc_calc.addWidget(location_task, 0, 0, 1, 4) loc_calc.addWidget(heading_lbl, 2, 0) loc_calc.addWidget(self.heading, 2, 1) loc_calc.addWidget(asc_as_lbl, 3, 0) loc_calc.addWidget(self.asc_as, 3, 1) loc_calc.addWidget(asc_rate_lbl, 4, 0) loc_calc.addWidget(self.asc_rate, 4, 1) loc_calc.addWidget(eng_fail_time_lbl, 5, 0) loc_calc.addWidget(self.eng_fail_time, 5, 1) loc_calc.addWidget(desc_as_lbl, 6, 0) loc_calc.addWidget(self.desc_as, 6, 1) loc_calc.addWidget(desc_rate_lbl, 7, 0) loc_calc.addWidget(self.desc_rate, 7, 1) loc_calc.addWidget(w_eqn_lbl, 8, 0) loc_calc.addWidget(self.w_eqn, 8, 1, 1, 2) loc_calc.addWidget(w_direc_lbl, 9, 0) loc_calc.addWidget(self.w_dir, 9, 1) loc_calc.addWidget(calc_btn_loc, 10, 0, 1, 4) loc_calc.addWidget(blank, 11, 0) loc_calc.addWidget(asc_dist_x_lbl, 12, 0) loc_calc.addWidget(self.asc_dist_x, 12, 1) loc_calc.addWidget(asc_dist_y_lbl, 12, 2) loc_calc.addWidget(self.asc_dist_y, 12, 3) loc_calc.addWidget(desc_dist_x_lbl, 13, 0) loc_calc.addWidget(self.desc_dist_x, 13, 1) loc_calc.addWidget(desc_dist_y_lbl, 13, 2) loc_calc.addWidget(self.desc_dist_y, 13, 3) loc_calc.addWidget(wind_dist_x_lbl, 14, 0) loc_calc.addWidget(self.wind_dist_x, 14, 1) loc_calc.addWidget(wind_dist_y_lbl, 14, 2) loc_calc.addWidget(self.wind_dist_y, 14, 3) loc_calc.addWidget(total_dist_x_lbl, 15, 0) loc_calc.addWidget(self.total_dist_x, 15, 1) loc_calc.addWidget(total_dist_y_lbl, 15, 2) loc_calc.addWidget(self.total_dist_y, 15, 3) loc_calc.addWidget(blank, 16, 0) loc_calc.addWidget(ans_distance_lbl, 17, 0) loc_calc.addWidget(self.ans_dist, 17, 1) loc_calc.addWidget(ans_angle_lbl, 18, 0) loc_calc.addWidget(self.ans_angle, 18, 1) loc_calc.addWidget(ans_heading_lbl, 19, 0) loc_calc.addWidget(self.ans_heading, 19, 1) # create horizontal box layout container hbox = QHBoxLayout() hbox.addLayout(graph) hbox.addLayout(p_calc) hbox.addLayout(loc_calc) self.setLayout(hbox) #Set the layout self.setGeometry(10, 100, 1600, 600) self.setWindowTitle('Co-pilot GUI') self.show() def plot(self): #plot some random stuff OBS_points = eval(self.plot_txt.text()) # create an axis ax = self.figure.add_subplot(111) # discards the old graph ax.clear() ax.grid(which='both', linestyle='-') ax.set_xlabel('Time') ax.set_ylabel('Amplitude') ax.set_xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) ax.plot([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], OBS_points, 'x-') ''' here we will get the data from the C++ wrapper by importing it as a library/module and using a method from said library/module to get the sizemometer data. ''' # refresh canvas to actually display the graph self.canvas.draw() def calculate_p(self): #NEED TO CONVERT KNOTS TO M/S N = self.num_tb.value() p = self.density.value() d = self.diameter.value() a = (d / 2)**2 * math.pi print(a) V = round((33 / 64) * (self.water_vel.value()), 1) #either 463/900 or 33/64 Cp = self.efficiency.value() pwr = N / 2 * p * a * (V)**3 * Cp / 100 self.p_ans.setValue(pwr) def calculate_loc(self): at = self.eng_fail_time.value() h = 90 - self.heading.value() #convert heading-->cartesian hrad = ((h / 180) * math.pi) #convert deg-->rad aas = self.asc_as.value() ar = self.asc_rate.value() das = self.desc_as.value() dr = self.desc_rate.value() wd = 270 - self.w_dir.value() #convert wind origin-->cartesian wdrad = ((wd / 180) * math.pi) #convert d-->deg height = (at * ar) #height reached dt = (height / (dr)) #descent time eqn = str(self.w_eqn.text()) ax = (at * aas * math.cos(hrad)) ay = (at * aas * math.sin(hrad)) dx = (dt * das * math.cos(hrad)) dy = (dt * das * math.sin(hrad)) def integrand(t): return eval(eqn) #return -(t/720)**2 + 25# wd, err = quad(integrand, 0, dt) #wd, err = quad(integrand, at, at+dt) wx = (wd * math.cos(wdrad)) wy = (wd * math.sin(wdrad)) totalx = (ax + dx + wx) totaly = (ay + dy + wy) dist = (math.sqrt(totalx**2 + totaly**2)) if totaly >= 0 and totalx > 0: angle = ((math.atan(totaly / totalx)) * 180 / math.pi) elif totaly <= 0 and totalx > 0: angle = ((math.atan(totaly / totalx)) * 180 / math.pi) elif totaly >= 0 and totalx < 0: angle = ((math.atan(totaly / totalx)) * 180 / math.pi + 180) elif totaly <= 0 and totalx < 0: angle = ((math.atan(totaly / totalx)) * 180 / math.pi + 180) elif totaly == 0 and totalx == 0: angle = 0 elif totaly < 0 and totalx == 0: angle = 270 elif totaly > 0 and totalx == 0: angle = 90 heading_ans = 90 - angle if (heading_ans < 0): heading_ans_final = 360 + heading_ans elif (heading_ans >= 0): heading_ans_final = heading_ans self.asc_dist_x.setValue(ax) self.asc_dist_y.setValue(ay) self.desc_dist_x.setValue(dx) self.desc_dist_y.setValue(dy) self.wind_dist_x.setValue(wx) self.wind_dist_y.setValue(wy) self.total_dist_x.setValue(totalx) self.total_dist_y.setValue(totaly) self.ans_dist.setValue(dist) self.ans_angle.setValue(angle) self.ans_heading.setValue(heading_ans_final) def calculate_depth(self): recorded_depth = 0.0 current_depth = 0.0 recorded_depth = float(self.frontend.get_depth()) current_depth = self.frontend.get_depth() - recorded_depth self.depth.setText(str(current_depth)) self.rec_depth.setText(str(recorded_depth))
def build_graph(self, data): """ Creates a graph in a canvas, it can be of volume or incidents and will compare the data for 2016, 2017 and 2018 :param data: (str) the type of information to be displayed, volume or incidents :return: (canvas) Canvas widget displaying the results in a graph """ if data == "volume": years = { "2016": "TrafficFlow2016", "2017": "TrafficFlow2017", "2018": "TrafficFlow2018" } year_max = [] year_list = [] # Building a list for each year, from its respective file in database for year, collection in years.items(): volume_list = Lb.ListBuilder.build_list(data, collection, year, sort=True) # The year and its max volume will have the same index in both lists year_list.append(year) year_max.append(volume_list[0][4]) # creating the graph figure = Figure(figsize=(13, 12), dpi=100) figure.suptitle("Max Traffic Volume Per Year", fontsize=20) plot = figure.add_subplot(111) plot.plot(year_list, year_max, linewidth=3.0) plot.set_xlabel("Year", fontsize=15) plot.set_ylabel("Volume", fontsize=15) canvas = FigureCanvasTkAgg(figure, self.master) graph = canvas.get_tk_widget() return graph elif data == "incidents": incidents_2016 = [] incidents_2017 = [] incidents_2018 = [] max_incidents_per_year = [] year = ["2016", "2017", "2018"] results = Db.Query().query("TrafficIncidents") # Querying all the information from the same file, add each item to its respective list for item in results: if "2016" in item["start_time"]: incidents_2016.append((item["address"])) elif "2017" in item["start_time"]: incidents_2017.append((item["address"])) elif "2018" in item["start_time"]: incidents_2018.append((item["address"])) # Adding the maximum value for each year to max incidents per year list max_incidents_per_year.append( max(self.sum_incidents(incidents_2016).values())) max_incidents_per_year.append( max(self.sum_incidents(incidents_2017).values())) max_incidents_per_year.append( max(self.sum_incidents(incidents_2018).values())) # creating the graph figure = Figure(figsize=(13, 12), dpi=100) figure.suptitle("Max Incidents Per Year", fontsize=20) plot = figure.add_subplot(111) plot.plot(year, max_incidents_per_year, linewidth=3.0) plot.set_xlabel("Year", fontsize=15) plot.set_ylabel("Incidents", fontsize=15) canvas = FigureCanvasTkAgg(figure, self.master) graph = canvas.get_tk_widget() return graph
demonstrate adding a FigureCanvasGTK3Agg widget to a Gtk.ScrolledWindow using GTK3 accessed via pygobject """ from gi.repository import Gtk from matplotlib.figure import Figure from numpy import arange, sin, pi from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas win = Gtk.Window() win.connect("delete-event", Gtk.main_quit) win.set_default_size(400, 300) win.set_title("Embedding in GTK") f = Figure(figsize=(5, 4), dpi=100) a = f.add_subplot(111) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) a.plot(t, s) sw = Gtk.ScrolledWindow() win.add(sw) # A scrolled window border goes outside the scrollbars and viewport sw.set_border_width(10) canvas = FigureCanvas(f) # a Gtk.DrawingArea canvas.set_size_request(800, 600) sw.add_with_viewport(canvas) win.show_all()
class PlotResponses(QtGui.QWidget): """ the plot and list of stations """ def __init__(self, data_fn=None, resp_fn=None): super(PlotResponses, self).__init__() self.file_watcher = QtCore.QFileSystemWatcher() self.file_watcher.fileChanged.connect(self.file_changed) self.modem_data = None self.modem_resp = None self._modem_data_copy = None self.station = None self._plot_z = False self.plot_settings = PlotSettings() self._ax = None self._ax2 = None self._key = 'z' self._ax_index = 0 self.ax_list = None self.setup_ui() self._data_fn = data_fn self._resp_fn = resp_fn #------------------------------------------------ # make the data_fn and resp_fn properties so that if they are reset # they will read in the data to a new modem.Data object # trying to use decorators for syntactical sugar @property def data_fn(self): self._data_fn @data_fn.getter def data_fn(self): return self._data_fn @data_fn.setter def data_fn(self, data_fn): self._data_fn = data_fn self.file_watcher.addPath(self._data_fn) # create new modem data object self.modem_data = mtpy.modeling.modem.Data() self.modem_data.read_data_file(self._data_fn) # make a back up copy that will be unchanged # that way we can revert back self._modem_data_copy = copy.deepcopy(self.modem_data) self.dirpath = os.path.dirname(self._data_fn) # fill list of stations station_list = sorted(self.modem_data.mt_dict.keys()) self.list_widget.clear() for station in station_list: self.list_widget.addItem(station) if self.station is None: self.station = station_list[0] self.plot() @property def resp_fn(self): self._resp_fn @resp_fn.getter def resp_fn(self): return self._resp_fn @resp_fn.setter def resp_fn(self, resp_fn): self._resp_fn = resp_fn self.modem_resp = mtpy.modeling.modem.Data() self.modem_resp.read_data_file(self._resp_fn) self.plot() @property def plot_z(self): self._plot_z @plot_z.getter def plot_z(self): return self._plot_z @plot_z.setter def plot_z(self, value): self._plot_z = value self.plot() #---------------------------- def setup_ui(self): """ setup the user interface with list of stations on the left and the plot on the right. There will be a button for save edits. """ #make a widget that will be the station list self.list_widget = QtGui.QListWidget() self.list_widget.itemClicked.connect(self.get_station) self.list_widget.setMaximumWidth(150) self.save_edits_button = QtGui.QPushButton() self.save_edits_button.setText("Save Edits") self.save_edits_button.setStyleSheet("background-color: #42f489") self.save_edits_button.pressed.connect(self.save_edits) self.apply_edits_button = QtGui.QPushButton() self.apply_edits_button.setText('Apply Edits') self.apply_edits_button.setStyleSheet("background-color: #c6dcff") self.apply_edits_button.pressed.connect(self.apply_edits) # self.undo_edit_button = QtGui.QPushButton() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.figure = Figure(dpi=150) self.mpl_widget = FigureCanvas(self.figure) self.mpl_widget.setFocusPolicy(QtCore.Qt.ClickFocus) self.mpl_widget.setFocus() # be able to edit the data self.mpl_widget.mpl_connect('pick_event', self.on_pick) self.mpl_widget.mpl_connect('axes_enter_event', self.in_axes) #make sure the figure takes up the entire plottable space self.mpl_widget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) # this is the Navigation widget # it takes the Canvas widget and a parent self.mpl_toolbar = NavigationToolbar(self.mpl_widget, self) # set the layout for the plot mpl_vbox = QtGui.QVBoxLayout() mpl_vbox.addWidget(self.mpl_toolbar) mpl_vbox.addWidget(self.mpl_widget) left_layout = QtGui.QVBoxLayout() left_layout.addWidget(self.list_widget) left_layout.addWidget(self.apply_edits_button) left_layout.addWidget(self.save_edits_button) # set the layout the main window layout = QtGui.QHBoxLayout() layout.addLayout(left_layout) layout.addLayout(mpl_vbox) self.setLayout(layout) def get_station(self, widget_item): """ get the station name from the clicked station """ self.station = str(widget_item.text()) self.plot() def file_changed(self): """ data file changed outside the program reload it """ print('{0} changed'.format(self.data_fn)) self.data_fn = self._data_fn def save_edits(self): """ save edits to another file """ fn_dialog = QtGui.QFileDialog() save_fn = str( fn_dialog.getSaveFileName(caption='Choose File to save', filter='*.dat')) self.modem_data.write_data_file(save_path=os.path.dirname(save_fn), fn_basename=os.path.basename(save_fn), compute_error=False, fill=False, elevation=True) def apply_edits(self): self.plot() def plot(self): """ plot the data """ if self.station is None: return z_obj = self.modem_data.mt_dict[self.station].Z t_obj = self.modem_data.mt_dict[self.station].Tipper period = self.modem_data.period_list # need to make sure that resistivity and phase is computed z_obj.compute_resistivity_phase() z_obj.compute_resistivity_phase() plt.rcParams['font.size'] = self.plot_settings.fs fontdict = {'size': self.plot_settings.fs + 2, 'weight': 'bold'} #--> make key word dictionaries for plotting kw_xx = { 'color': self.plot_settings.cted, 'marker': self.plot_settings.mted, 'ms': self.plot_settings.ms, 'ls': ':', 'lw': self.plot_settings.lw, 'e_capsize': self.plot_settings.e_capsize, 'e_capthick': self.plot_settings.e_capthick, 'picker': 3 } kw_yy = { 'color': self.plot_settings.ctmd, 'marker': self.plot_settings.mtmd, 'ms': self.plot_settings.ms, 'ls': ':', 'lw': self.plot_settings.lw, 'e_capsize': self.plot_settings.e_capsize, 'e_capthick': self.plot_settings.e_capthick, 'picker': 3 } #convert to apparent resistivity and phase if self.plot_z == True: scaling = np.zeros_like(z_obj.z) for ii in range(2): for jj in range(2): scaling[:, ii, jj] = 1. / np.sqrt(z_obj.freq) plot_res = abs(z_obj.z.real * scaling) plot_res_err = abs(z_obj.z_err * scaling) plot_phase = abs(z_obj.z.imag * scaling) plot_phase_err = abs(z_obj.z_err * scaling) h_ratio = [1, 1, .5] elif self.plot_z == False: plot_res = z_obj.resistivity plot_res_err = z_obj.resistivity_err plot_phase = z_obj.phase plot_phase_err = z_obj.phase_err h_ratio = [1.5, 1, .5] #find locations where points have been masked nzxx = np.nonzero(z_obj.z[:, 0, 0])[0] nzxy = np.nonzero(z_obj.z[:, 0, 1])[0] nzyx = np.nonzero(z_obj.z[:, 1, 0])[0] nzyy = np.nonzero(z_obj.z[:, 1, 1])[0] ntx = np.nonzero(t_obj.tipper[:, 0, 0])[0] nty = np.nonzero(t_obj.tipper[:, 0, 1])[0] self.figure.clf() self.figure.suptitle(str(self.station), fontdict=fontdict) #set the grid of subplots if np.all(t_obj.tipper == 0.0) == True: self.plot_tipper = False else: self.plot_tipper = True gs = gridspec.GridSpec(3, 4, height_ratios=h_ratio) gs.update(wspace=self.plot_settings.subplot_wspace, left=self.plot_settings.subplot_left, top=self.plot_settings.subplot_top, bottom=self.plot_settings.subplot_bottom, right=self.plot_settings.subplot_right, hspace=self.plot_settings.subplot_hspace) axrxx = self.figure.add_subplot(gs[0, 0]) axrxy = self.figure.add_subplot(gs[0, 1], sharex=axrxx) axryx = self.figure.add_subplot(gs[0, 2], sharex=axrxx) axryy = self.figure.add_subplot(gs[0, 3], sharex=axrxx) axpxx = self.figure.add_subplot(gs[1, 0]) axpxy = self.figure.add_subplot(gs[1, 1], sharex=axrxx) axpyx = self.figure.add_subplot(gs[1, 2], sharex=axrxx) axpyy = self.figure.add_subplot(gs[1, 3], sharex=axrxx) axtxr = self.figure.add_subplot(gs[2, 0], sharex=axrxx) axtxi = self.figure.add_subplot(gs[2, 1], sharex=axrxx) axtyr = self.figure.add_subplot(gs[2, 2], sharex=axrxx) axtyi = self.figure.add_subplot(gs[2, 3], sharex=axrxx) self.ax_list = [ axrxx, axrxy, axryx, axryy, axpxx, axpxy, axpyx, axpyy, axtxr, axtxi, axtyr, axtyi ] # plot data response erxx = mtplottools.plot_errorbar(axrxx, period[nzxx], plot_res[nzxx, 0, 0], plot_res_err[nzxx, 0, 0], **kw_xx) erxy = mtplottools.plot_errorbar(axrxy, period[nzxy], plot_res[nzxy, 0, 1], plot_res_err[nzxy, 0, 1], **kw_xx) eryx = mtplottools.plot_errorbar(axryx, period[nzyx], plot_res[nzyx, 1, 0], plot_res_err[nzyx, 1, 0], **kw_yy) eryy = mtplottools.plot_errorbar(axryy, period[nzyy], plot_res[nzyy, 1, 1], plot_res_err[nzyy, 1, 1], **kw_yy) #plot phase epxx = mtplottools.plot_errorbar(axpxx, period[nzxx], plot_phase[nzxx, 0, 0], plot_phase_err[nzxx, 0, 0], **kw_xx) epxy = mtplottools.plot_errorbar(axpxy, period[nzxy], plot_phase[nzxy, 0, 1], plot_phase_err[nzxy, 0, 1], **kw_xx) epyx = mtplottools.plot_errorbar(axpyx, period[nzyx], plot_phase[nzyx, 1, 0], plot_phase_err[nzyx, 1, 0], **kw_yy) epyy = mtplottools.plot_errorbar(axpyy, period[nzyy], plot_phase[nzyy, 1, 1], plot_phase_err[nzyy, 1, 1], **kw_yy) #plot tipper if self.plot_tipper == True: ertx = mtplottools.plot_errorbar(axtxr, period[ntx], t_obj.tipper[ntx, 0, 0].real, t_obj.tipper_err[ntx, 0, 0], **kw_xx) erty = mtplottools.plot_errorbar(axtyr, period[nty], t_obj.tipper[nty, 0, 1].real, t_obj.tipper_err[nty, 0, 1], **kw_yy) eptx = mtplottools.plot_errorbar(axtxi, period[ntx], t_obj.tipper[ntx, 0, 0].imag, t_obj.tipper_err[ntx, 0, 0], **kw_xx) epty = mtplottools.plot_errorbar(axtyi, period[nty], t_obj.tipper[nty, 0, 1].imag, t_obj.tipper_err[nty, 0, 1], **kw_yy) #---------------------------------------------- # get error bar list for editing later if self.plot_tipper == False: try: self._err_list = [[erxx[1][0], erxx[1][1], erxx[2][0]], [erxy[1][0], erxy[1][1], erxy[2][0]], [eryx[1][0], eryx[1][1], eryx[2][0]], [eryy[1][0], eryy[1][1], eryy[2][0]], [epxx[1][0], epxx[1][1], epxx[2][0]], [epxy[1][0], epxy[1][1], epxy[2][0]], [epyx[1][0], epyx[1][1], epyx[2][0]], [epyy[1][0], epyy[1][1], epyy[2][0]]] line_list = [[erxx[0]], [erxy[0]], [eryx[0]], [eryy[0]]] except IndexError: print('Found no Z components for {0}'.format(self.station)) line_list = [[None], [None], [None], [None]] self._err_list = [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None]] else: try: line_list = [[erxx[0]], [erxy[0]], [eryx[0]], [eryy[0]], [ertx[0]], [erty[0]]] self._err_list = [[erxx[1][0], erxx[1][1], erxx[2][0]], [erxy[1][0], erxy[1][1], erxy[2][0]], [eryx[1][0], eryx[1][1], eryx[2][0]], [eryy[1][0], eryy[1][1], eryy[2][0]], [epxx[1][0], epxx[1][1], epxx[2][0]], [epxy[1][0], epxy[1][1], epxy[2][0]], [epyx[1][0], epyx[1][1], epyx[2][0]], [epyy[1][0], epyy[1][1], epyy[2][0]], [ertx[1][0], ertx[1][1], ertx[2][0]], [eptx[1][0], eptx[1][1], eptx[2][0]], [erty[1][0], erty[1][1], erty[2][0]], [epty[1][0], epty[1][1], epty[2][0]]] except IndexError: print('Found no Z components for {0}'.format(self.station)) line_list = [[None], [None], [None], [None], [None], [None]] self._err_list = [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None]] #------------------------------------------ # make things look nice # set titles of the Z components label_list = [['$Z_{xx}$'], ['$Z_{xy}$'], ['$Z_{yx}$'], ['$Z_{yy}$']] for ax, label in zip(self.ax_list[0:4], label_list): ax.set_title(label[0], fontdict={ 'size': self.plot_settings.fs + 2, 'weight': 'bold' }) # set legends for tipper components # fake a line l1 = plt.Line2D([0], [0], linewidth=0, color='w', linestyle='None', marker='.') t_label_list = ['Re{$T_x$}', 'Im{$T_x$}', 'Re{$T_y$}', 'Im{$T_y$}'] label_list += [['$T_{x}$'], ['$T_{y}$']] for ax, label in zip(self.ax_list[-4:], t_label_list): ax.legend([l1], [label], loc='upper left', markerscale=.01, borderaxespad=.05, labelspacing=.01, handletextpad=.05, borderpad=.05, prop={'size': max([self.plot_settings.fs, 5])}) #--> set limits if input if self.plot_settings.res_xx_limits is not None: axrxx.set_ylim(self.plot_settings.res_xx_limits) if self.plot_settings.res_xy_limits is not None: axrxy.set_ylim(self.plot_settings.res_xy_limits) if self.plot_settings.res_yx_limits is not None: axryx.set_ylim(self.plot_settings.res_yx_limits) if self.plot_settings.res_yy_limits is not None: axryy.set_ylim(self.plot_settings.res_yy_limits) if self.plot_settings.phase_xx_limits is not None: axpxx.set_ylim(self.plot_settings.phase_xx_limits) if self.plot_settings.phase_xy_limits is not None: axpxy.set_ylim(self.plot_settings.phase_xy_limits) if self.plot_settings.phase_yx_limits is not None: axpyx.set_ylim(self.plot_settings.phase_yx_limits) if self.plot_settings.phase_yy_limits is not None: axpyy.set_ylim(self.plot_settings.phase_yy_limits) #set axis properties for aa, ax in enumerate(self.ax_list): ax.tick_params(axis='y', pad=self.plot_settings.ylabel_pad) ylabels = ax.get_yticks().tolist() if aa < 8: ylabels[-1] = '' ylabels[0] = '' ax.set_yticklabels(ylabels) plt.setp(ax.get_xticklabels(), visible=False) if self.plot_z == True: ax.set_yscale('log', nonposy='clip') else: ax.set_xlabel('Period (s)', fontdict=fontdict) if aa < 4 and self.plot_z is False: ax.set_yscale('log', nonposy='clip') #set axes labels if aa == 0: if self.plot_z == False: ax.set_ylabel('App. Res. ($\mathbf{\Omega \cdot m}$)', fontdict=fontdict) elif self.plot_z == True: ax.set_ylabel('Re[Z (mV/km nT)]', fontdict=fontdict) elif aa == 4: if self.plot_z == False: ax.set_ylabel('Phase (deg)', fontdict=fontdict) elif self.plot_z == True: ax.set_ylabel('Im[Z (mV/km nT)]', fontdict=fontdict) elif aa == 8: ax.set_ylabel('Tipper', fontdict=fontdict) if aa > 7: if self.plot_settings.tipper_limits is not None: ax.set_ylim(self.plot_settings.tipper_limits) else: pass ax.set_xscale('log', nonposx='clip') ax.set_xlim(xmin=10**(np.floor(np.log10(period[0]))) * 1.01, xmax=10**(np.ceil(np.log10(period[-1]))) * .99) ax.grid(True, alpha=.25) ##---------------------------------------------- #plot model response if self.modem_resp is not None: resp_z_obj = self.modem_resp.mt_dict[self.station].Z resp_z_err = np.nan_to_num((z_obj.z - resp_z_obj.z) / z_obj.z_err) resp_z_obj.compute_resistivity_phase() resp_t_obj = self.modem_resp.mt_dict[self.station].Tipper resp_t_err = np.nan_to_num( (t_obj.tipper - resp_t_obj.tipper) / t_obj.tipper_err) #convert to apparent resistivity and phase if self.plot_z == True: scaling = np.zeros_like(resp_z_obj.z) for ii in range(2): for jj in range(2): scaling[:, ii, jj] = 1. / np.sqrt(resp_z_obj.freq) r_plot_res = abs(resp_z_obj.z.real * scaling) r_plot_phase = abs(resp_z_obj.z.imag * scaling) elif self.plot_z == False: r_plot_res = resp_z_obj.resistivity r_plot_phase = resp_z_obj.phase rms_xx = resp_z_err[nzxx, 0, 0].std() rms_xy = resp_z_err[nzxy, 0, 1].std() rms_yx = resp_z_err[nzyx, 1, 0].std() rms_yy = resp_z_err[nzyy, 1, 1].std() #--> make key word dictionaries for plotting kw_xx = { 'color': self.plot_settings.ctem, 'marker': self.plot_settings.mtem, 'ms': self.plot_settings.ms, 'ls': ':', 'lw': self.plot_settings.lw, 'e_capsize': self.plot_settings.e_capsize, 'e_capthick': self.plot_settings.e_capthick } kw_yy = { 'color': self.plot_settings.ctmm, 'marker': self.plot_settings.mtmm, 'ms': self.plot_settings.ms, 'ls': ':', 'lw': self.plot_settings.lw, 'e_capsize': self.plot_settings.e_capsize, 'e_capthick': self.plot_settings.e_capthick } # plot data response rerxx = mtplottools.plot_errorbar(axrxx, period[nzxx], r_plot_res[nzxx, 0, 0], None, **kw_xx) rerxy = mtplottools.plot_errorbar(axrxy, period[nzxy], r_plot_res[nzxy, 0, 1], None, **kw_xx) reryx = mtplottools.plot_errorbar(axryx, period[nzyx], r_plot_res[nzyx, 1, 0], None, **kw_yy) reryy = mtplottools.plot_errorbar(axryy, period[nzyy], r_plot_res[nzyy, 1, 1], None, **kw_yy) #plot phase repxx = mtplottools.plot_errorbar(axpxx, period[nzxx], r_plot_phase[nzxx, 0, 0], None, **kw_xx) repxy = mtplottools.plot_errorbar(axpxy, period[nzxy], r_plot_phase[nzxy, 0, 1], None, **kw_xx) repyx = mtplottools.plot_errorbar(axpyx, period[nzyx], r_plot_phase[nzyx, 1, 0], None, **kw_yy) repyy = mtplottools.plot_errorbar(axpyy, period[nzyy], r_plot_phase[nzyy, 1, 1], None, **kw_yy) #plot tipper if self.plot_tipper == True: rertx = mtplottools.plot_errorbar( axtxr, period[ntx], resp_t_obj.tipper[ntx, 0, 0].real, None, **kw_xx) rerty = mtplottools.plot_errorbar( axtyr, period[nty], resp_t_obj.tipper[nty, 0, 1].real, None, **kw_yy) reptx = mtplottools.plot_errorbar( axtxi, period[ntx], resp_t_obj.tipper[ntx, 0, 0].imag, None, **kw_xx) repty = mtplottools.plot_errorbar( axtyi, period[nty], resp_t_obj.tipper[nty, 0, 1].imag, None, **kw_yy) if self.plot_tipper == False: line_list[0] += [rerxx[0]] line_list[1] += [rerxy[0]] line_list[2] += [reryx[0]] line_list[3] += [reryy[0]] label_list[0] += ['$Z^m_{xx}$ ' + 'rms={0:.2f}'.format(rms_xx)] label_list[1] += ['$Z^m_{xy}$ ' + 'rms={0:.2f}'.format(rms_xy)] label_list[2] += ['$Z^m_{yx}$ ' + 'rms={0:.2f}'.format(rms_yx)] label_list[3] += ['$Z^m_{yy}$ ' + 'rms={0:.2f}'.format(rms_yy)] else: line_list[0] += [rerxx[0]] line_list[1] += [rerxy[0]] line_list[2] += [reryx[0]] line_list[3] += [reryy[0]] line_list[4] += [rertx[0]] line_list[5] += [rerty[0]] label_list[0] += ['$Z^m_{xx}$ ' + 'rms={0:.2f}'.format(rms_xx)] label_list[1] += ['$Z^m_{xy}$ ' + 'rms={0:.2f}'.format(rms_xy)] label_list[2] += ['$Z^m_{yx}$ ' + 'rms={0:.2f}'.format(rms_yx)] label_list[3] += ['$Z^m_{yy}$ ' + 'rms={0:.2f}'.format(rms_yy)] label_list[4] += [ '$T^m_{x}$ ' + 'rms={0:.2f}'.format(resp_t_err[ntx, 0, 0].std()) ] label_list[5] += [ '$T^m_{y}$' + 'rms={0:.2f}'.format(resp_t_err[nty, 0, 1].std()) ] legend_ax_list = self.ax_list[0:4] if self.plot_tipper == True: legend_ax_list += [self.ax_list[-4], self.ax_list[-2]] for aa, ax in enumerate(legend_ax_list): ax.legend( line_list[aa], label_list[aa], loc=self.plot_settings.legend_loc, bbox_to_anchor=self.plot_settings.legend_pos, markerscale=self.plot_settings.legend_marker_scale, borderaxespad=self.plot_settings.legend_border_axes_pad, labelspacing=self.plot_settings.legend_label_spacing, handletextpad=self.plot_settings.legend_handle_text_pad, borderpad=self.plot_settings.legend_border_pad, prop={'size': max([self.plot_settings.fs, 5])}) self.mpl_widget.draw() def on_pick(self, event): """ mask a data point when it is clicked on. """ data_point = event.artist data_period = data_point.get_xdata()[event.ind] data_value = data_point.get_ydata()[event.ind] # get the indicies where the data point has been edited p_index = np.where(self.modem_data.period_list == data_period)[0][0] s_index = np.where( self.modem_data.data_array['station'] == self.station)[0][0] if self._key == 'tip': data_value_2 = self.modem_data.mt_dict[self.station].Tipper.tipper[ p_index, self._comp_index_x, self._comp_index_y] if self._ax_index % 2 == 0: data_value_2 = data_value_2.imag else: data_value_2 = data_value_2.real elif self._key == 'z': if self.plot_z == True: data_value_2 = self.modem_data.mt_dict[self.station].Z.z[ p_index, self._comp_index_x, self._comp_index_y] if self._ax_index % 2 == 0: data_value_2 = data_value_2.imag else: data_value_2 = data_value_2.real elif self.plot_z == False and self._ax_index < 4: data_value_2 = self.modem_data.mt_dict[self.station].Z.phase[ p_index, self._comp_index_x, self._comp_index_y] elif self.plot_z == False and self._ax_index >= 4: data_value_2 = self.modem_data.mt_dict[ self.station].Z.resistivity[p_index, self._comp_index_x, self._comp_index_y] if event.mouseevent.button == 1: # mask the point in the data mt_dict self.modem_data.data_array[s_index][self._key][ p_index, self._comp_index_x, self._comp_index_y] = 0 + 0j if self._key == 'tip': self.modem_data.mt_dict[self.station].Tipper.tipper[ p_index, self._comp_index_x, self._comp_index_y] = 0 + 0j elif self._key == 'z': self.modem_data.mt_dict[self.station].Z.z[ p_index, self._comp_index_x, self._comp_index_y] = 0 + 0j # plot the points as masked self._ax.plot(data_period, data_value, color=(0, 0, 0), marker='x', ms=self.plot_settings.ms * 2, mew=4) self._ax2.plot(data_period, data_value_2, color=(0, 0, 0), marker='x', ms=self.plot_settings.ms * 2, mew=4) self._ax.figure.canvas.draw() self._ax2.figure.canvas.draw() # Increase error bars if event.mouseevent.button == 3: # make sure just checking the top plots #put the new error into the error array if self._key == 'tip': err = self.modem_data.mt_dict[self.station].Tipper.tipper_err[ p_index, self._comp_index_x, self._comp_index_y] err = err + abs(err) * self.plot_settings.t_err_increase self.modem_data.mt_dict[self.station].Tipper.tipper_err[ p_index, self._comp_index_x, self._comp_index_y] = err if self._key == 'z': err = self.modem_data.mt_dict[self.station].Z.z_err[ p_index, self._comp_index_x, self._comp_index_y] err = err + abs(err) * self.plot_settings.z_err_increase self.modem_data.mt_dict[self.station].Z.z_err[ p_index, self._comp_index_x, self._comp_index_y] = err self.modem_data.data_array[s_index][self._key + '_err'][ p_index, self._comp_index_x, self._comp_index_y] = err # make error bar array eb = self._err_list[ self._ax_index][2].get_paths()[p_index].vertices # make ecap array ecap_l = self._err_list[self._ax_index][0].get_data()[1][p_index] ecap_u = self._err_list[self._ax_index][1].get_data()[1][p_index] # change apparent resistivity error if self._key == 'tip': neb_u = eb[0, 1] - self.plot_settings.t_err_increase * abs( eb[0, 1]) neb_l = eb[1, 1] + self.plot_settings.t_err_increase * abs( eb[1, 1]) ecap_l = ecap_l - self.plot_settings.t_err_increase * abs( ecap_l) ecap_u = ecap_u + self.plot_settings.t_err_increase * abs( ecap_u) elif self._key == 'z': neb_u = eb[0, 1] - self.plot_settings.z_err_increase * abs( eb[0, 1]) neb_l = eb[1, 1] + self.plot_settings.z_err_increase * abs( eb[1, 1]) ecap_l = ecap_l - self.plot_settings.z_err_increase * abs( ecap_l) ecap_u = ecap_u + self.plot_settings.z_err_increase * abs( ecap_u) #set the new error bar values eb[0, 1] = neb_u eb[1, 1] = neb_l #reset the error bars and caps ncap_l = self._err_list[self._ax_index][0].get_data() ncap_u = self._err_list[self._ax_index][1].get_data() ncap_l[1][p_index] = ecap_l ncap_u[1][p_index] = ecap_u #set the values self._err_list[self._ax_index][0].set_data(ncap_l) self._err_list[self._ax_index][1].set_data(ncap_u) self._err_list[ self._ax_index][2].get_paths()[p_index].vertices = eb # need to redraw the figure self._ax.figure.canvas.draw() def in_axes(self, event): """ figure out which axes you just chose the point from """ ax_index_dict = { 0: (0, 0), 1: (0, 1), 2: (1, 0), 3: (1, 1), 4: (0, 0), 5: (0, 1), 6: (1, 0), 7: (1, 1), 8: (0, 0), 9: (0, 0), 10: (0, 1), 11: (0, 1) } ax_pairs = { 0: 4, 1: 5, 2: 6, 3: 7, 4: 0, 5: 1, 6: 2, 7: 3, 8: 9, 9: 8, 10: 11, 11: 10 } # make the axis an attribute self._ax = event.inaxes # find the component index so that it can be masked for ax_index, ax in enumerate(self.ax_list): if ax == event.inaxes: self._comp_index_x, self._comp_index_y = ax_index_dict[ ax_index] self._ax_index = ax_index self._ax2 = self.ax_list[ax_pairs[ax_index]] if ax_index < 8: self._key = 'z' else: self._key = 'tip'
class Gui(object): 'A simple gui for omron' def __init__(self, master, name=None, dbfile=None): self.master = master print name, dbfile # import omron # self.omron = omron.Omron() self.omron = None self.name = name self.data = None self.use_averaged = False self.use_am_pm = False self.dbfile = dbfile if self.dbfile: self.cb_open_file() # frame = tk.Frame(master) # frame.pack() menubar = tk.Menu(master) menubar.add_command(label="Quit", command = master.quit) menubar.add_command(label="Open", command = self.cb_open_file) menubar.add_command(label="Plot", command = self.cb_update_plot) menubar.add_command(label="Acquire", command = self.cb_acquire) menubar.add_command(label="Avg", command = self.cb_average) menubar.add_command(label="AM/PM", command = self.cb_am_pm) self.menubar = menubar #menubar.pack() master.config(menu=menubar) self.figure = Figure(figsize = (5,4), dpi = 100) self.canvas = FigureCanvasTkAgg(self.figure, master = master) self.canvas.show() self.canvas.get_tk_widget().pack(side = tk.TOP, fill = tk.BOTH, expand = 1) self.cb_update_plot() return def get_data(self): '''Return the current data to plot. Return a list of tuples. First value in each tuple is the time followed by 3 measurements (sys,dia,pulse)''' if self.use_averaged: return self.average() return self.data.all() def cb_open_file(self): 'If given a file, open it, else prompt user' import store if self.dbfile: print 'Loading DB file %s using name %s' % (self.dbfile, self.name) self.data = store.Data(self.dbfile, self.name) return from tkFileDialog import askopenfilename self.dbfile = askopenfilename() if not self.dbfile: print 'Canceled' return return self.cb_open_file() def cb_update_plot(self): 'Update the plot given current parameters' rows = self.get_data() if not rows: return import matplotlib.ticker as ticker import time # Convert row based to column based ts1 = list() sys1 = list() dia1 = list() pulse1 = list() if self.use_am_pm: # these will be pm ts2 = list() sys2 = list() dia2 = list() pulse2 = list() pass # sort out data for row in rows: if self.use_am_pm: hour = time.localtime(row[0])[3] if hour < 12: ts1.append(row[0]) sys1.append(row[1]) dia1.append(row[2]) pulse1.append(row[3]) else: ts2.append(row[0]) sys2.append(row[1]) dia2.append(row[2]) pulse2.append(row[3]) pass continue ts1.append(row[0]) sys1.append(row[1]) dia1.append(row[2]) pulse1.append(row[3]) continue self.figure.clear() axis = self.figure.add_subplot(111) axis.plot(ts1, sys1, 'k', ts1, dia1, 'b', ts1, pulse1, 'r') if self.use_am_pm: axis.plot(ts2, sys2, 'k--', ts2, dia2, 'b--', ts2, pulse2, 'r--') axis.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) self.figure.autofmt_xdate() self.canvas.show() return def cb_acquire(self): print 'Acquiring data' import store omron_obj = omron.Omron() if omron_obj.open() < 0: print 'Failed to open device' return ret = omron_obj.get_device_version() if not ret: print 'Failed to get device version' else: print 'Opened device version %s' % ret ret = omron_obj.get_bp_profile() if not ret: print 'Failed to get device profile' else: print 'Opened device with profile: %s' % ret data_count = omron_obj.get_daily_data_count() print 'Trying to get %d readings' % data_count def bad_data(data): return not data.day and not data.month and not data.year and \ not data.hour and not data.minute and not data.second and \ not data.sys and not data.dia and not data.pulse for ind in range(data_count-1, -1, -1): for trial in range(3): bp_data = omron_obj.get_daily_bp_data(ind) if bad_data(bp_data): continue break tsec = store.ymdhms2seconds(bp_data.year, bp_data.month, bp_data.day, bp_data.hour, bp_data.minute, bp_data.second) print trial, tsec, bp_data.sys, bp_data.dia, bp_data.pulse if bad_data(bp_data): continue self.data.add(tsec, bp_data.sys, bp_data.dia, bp_data.pulse) continue self.cb_update_plot() return def average(self, window=600, data=None): 'Respond to Avg button, average nearby data in window (seconds)' if data is None: rows = self.data.all() else: rows = data new_rows = [] count = 0 last_time = sys_sum = dia_sum = pulse_sum = 0 for row in rows: delta_t = row[0] - last_time last_time = row[0] if delta_t > window: # save accumulated and start new with current if count: # first time through new_rows.append((last_time, sys_sum/count, dia_sum/count, pulse_sum/count)) count = 1 sys_sum = row[1] dia_sum = row[2] pulse_sum = row[3] continue # we are inside window of last data, accumulate count += 1 sys_sum += row[1] dia_sum += row[2] pulse_sum += row[3] continue print 'Averaged %d values down to %d' % (len(rows), len(new_rows)) return new_rows def cb_average(self): 'Toggle Avg/All' if self.use_averaged: label = 'Avg' else: label = 'All' self.menubar.entryconfig(5, label=label) self.use_averaged = not self.use_averaged self.cb_update_plot() return def cb_am_pm(self): 'Toggle AM/PM and Combined' if self.use_am_pm: label = 'AM/PM' else: label = 'Full' self.menubar.entryconfig(6, label=label) self.use_am_pm = not self.use_am_pm self.cb_update_plot() return pass