class MyWindow(Gtk.ApplicationWindow): def __init__(self): Gtk.Window.__init__(self, title="Toolbar Example") self.set_size_request(700, 500) self.box = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL) self.add(self.box) self.fig = Figure() self.ax = self.fig.add_subplot(211) self.ax.set_xlim(0, 50) self.ax.set_ylim(0, 20) self.ydata = [0] * 50 self.line, = self.ax.plot(self.ydata, label='ydata') self.ax.legend() self.ax2 = self.fig.add_subplot(212) self.ydata2 = [0] * 50 self.color_plot2 = "red" self.line2, = self.ax2.plot(self.ydata2, label='ydata2', color=self.color_plot2) self.ax2.legend() self.f = FigureCanvas(self.fig) self.box.pack_start(self.f, True, True, 0) self.button = Gtk.Button("Click Me") self.button.connect("clicked", self.on_click_me_clicked) self.box.pack_start(self.button, False, True, 0) def on_click_me_clicked(self, button): print "Toller Button"
class MplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): matplotlib.rcParams['font.size'] = 8 self.figure = Figure(figsize=(width, height), dpi=dpi) self.axes = self.figure.add_subplot(111) FigureCanvas.__init__(self, self.figure) self.setParent(parent) self.toolbar = NavigationToolbar(self, parent) self.toolbar.setIconSize(QSize(16, 16)) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def getToolbar(self): return self.toolbar def clear(self): self.figure.clear() self.axes = self.figure.add_subplot(111) def test(self): self.axes.plot([1,2,3,4]) def saveAs(self, fname): self.figure.savefig(fname)
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
class MplCanvas(FigureCanvas): def __init__(self, nsubplots=1): self.dpi=100 self.fig = Figure(dpi=self.dpi, tight_layout=True) if nsubplots==2: # self.fig, (self.ax, self.ax2) = plt.subplots(1,2, sharey=True) # self.fig.set_tight_layout(True) self.gs= gridspec.GridSpec(1, 2, width_ratios=[5, 1]) self.gs.update(left=0.15, right=0.97, bottom=0.22, top=0.94, wspace=0.07) self.ax = self.fig.add_subplot(self.gs[0]) self.ax2 = self.fig.add_subplot(self.gs[1], sharey=self.ax) self.ax.hold(False) self.ax2.hold(False) else: self.ax = self.fig.add_subplot(1,1,1) self.ax.hold(False) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding ) FigureCanvas.updateGeometry(self)
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 save_plotSpectrum(y,Fs,image_name): """ Plots a Single-Sided Amplitude Spectrum of y(t) """ fig = Figure(linewidth=0.0) fig.set_size_inches(fig_width,fig_length, forward=True) Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace) n = len(y) # length of the signal _subplot = fig.add_subplot(2,1,1) print "Fi" _subplot.plot(arange(0,n),y) xlabel('Time') ylabel('Amplitude') _subploti_2=fig.add_subplot(2,1,2) k = arange(n) T = n/Fs frq = k/T # two sides frequency range frq = frq[range(n/2)] # one side frequency range Y = fft(y)/n # fft computing and normalization Y = Y[range(n/2)] _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum xlabel('Freq (Hz)') ylabel('|Y(freq)|') print "here" canvas = FigureCanvasAgg(fig) if '.eps' in outfile_name: canvas.print_eps(outfile_name, dpi = 110) if '.png' in outfile_name: canvas.print_figure(outfile_name, dpi = 110)
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
class SplinePlotter(QDialog): def __init__(self, spline, points=1000, parent=None): super(SplinePlotter, self).__init__(parent=parent) self.fig = Figure() self.y_axes = self.fig.add_subplot(3,1,1) self.dy_axes = self.fig.add_subplot(3,1,2) self.ddy_axes = self.fig.add_subplot(3,1,3) self.plot_widget = FigureCanvas(self.fig) self.toolbar = NavigationToolbar(self.plot_widget, self) panel = QVBoxLayout() panel.addWidget(self.toolbar) panel.addWidget(self.plot_widget) self.setLayout(panel) xmin = min(spline.x_points) xmax = max(spline.x_points) spline = spline x = [ xmin + float(i)/points*(xmax-xmin) for i in range(points) ] y = [spline.y(xi) for xi in x] dy = [spline.dy(xi) for xi in x] ddy = [spline.ddy(xi) for xi in x] self.y_axes.plot(spline.x_points, spline.y_points, 'o') self.y_axes.plot(x, y) self.dy_axes.plot(x,dy) self.ddy_axes.plot(x, ddy)
def startup_cost(): import datetime import StringIO import random import base64 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig=Figure(facecolor='#ffffff') ax=fig.add_subplot(211) ax2=fig.add_subplot(212, axisbg='y') 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')) ax2.plot_date(x, y, '-') ax2.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) image=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def __init__(self, master, queue, endCommand): self.queue = queue # Set up the GUI console = Tkinter.Button(master, text='Done', command=endCommand) console.pack() # make some plots f = Figure() self.axis = f.add_subplot(121) self.x_data = np.zeros(50) self.y_data = np.zeros(50) self.line1, = self.axis.plot(self.x_data, self.y_data) self.axis.set_ylim([-70, 0]) self.start = time.time() self.axis_rot = f.add_subplot(122, polar=True) self.headings = np.zeros(50) self.gains = np.zeros(50) self.axis_rot.set_ylim(-70, -10) self.axis_rot.set_yticks(np.arange(-70, -10, 6)) self.axis_rot.set_xticks(np.arange(0, 2 * np.pi, np.pi / 6)) self.axis_rot.grid(True) self.gain_line, = self.axis_rot.plot(self.headings, self.gains, marker="x", linestyle="-", linewidth=2) self.headings = np.zeros(50) self.gains = np.zeros(50) # add a canvas self.canvas = FigureCanvasTkAgg(f, master=master) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) # not sure what this line does
def plot_haven(infect_prob_free, infect_prob_safe, infect_duration, latent_period, kill_prob, time_to_shelter): """ Plot Haven, return canvas """ haven = Haven( infect_prob_free, infect_prob_safe, infect_duration, latent_period, kill_prob, time_to_shelter) figure = Figure() canvas = FigureCanvasAgg(figure) axes = figure.add_subplot(2, 1, 1) if haven is not False: axes.plot(haven[0], haven[1], 'g--', linewidth=3) axes.plot(haven[0], haven[2], '-.b', linewidth=3) axes.plot(haven[0], haven[3], ':m', linewidth=3) axes.plot(haven[0], haven[4], 'r-', linewidth=3) axes.set_xlabel("Time (days)") axes.set_ylabel("Percent of Population") axes.set_title("Zombie Epidemic with Safe Haven") axes.grid(True) axes.legend( ("Wandering", "Safe Survivors", "Latent", "Infected"), shadow=True, fancybox=True) axes = figure.add_subplot(2, 1, 2) axes.plot(haven[0], haven[5], 'k--', linewidth=3) axes.plot(haven[0], haven[6], '-.b', linewidth=3) axes.set_xlabel("Time (days)") axes.set_ylabel("Percent of Population") axes.grid(True) axes.legend(("Culled", "Dead"), shadow=True, fancybox=True) else: ab = error() axes.set_title("Sorry, there has been an error.") axes.add_artist(ab) return canvas
def make_Histogram(self): self.read_table() functions.process(self.dispData, self.dicData) self.make_CorrFigs() self.make_TMSFig() on = self.dicData['hdf5_on'] # this one contains all the histogram axis res = self.dicData['res'] # this contains the calculation results fig1 = Figure(facecolor='white', edgecolor='white') ax1 = fig1.add_subplot(2, 2, 1) ax2 = fig1.add_subplot(2, 2, 2) ax3 = fig1.add_subplot(2, 2, 3) ax4 = fig1.add_subplot(2, 2, 4) ax1.imshow(res.IQmapM_avg[0], interpolation='nearest', origin='low', extent=[on.xII[0], on.xII[-1], on.yII[0], on.yII[-1]], aspect='auto') ax2.imshow(res.IQmapM_avg[1], interpolation='nearest', origin='low', extent=[on.xQQ[0], on.xQQ[-1], on.yQQ[0], on.yQQ[-1]], aspect='auto') ax3.imshow(res.IQmapM_avg[2], interpolation='nearest', origin='low', extent=[on.xIQ[0], on.xIQ[-1], on.yIQ[0], on.yIQ[-1]], aspect='auto') ax4.imshow(res.IQmapM_avg[3], interpolation='nearest', origin='low', extent=[on.xQI[0], on.xQI[-1], on.yQI[0], on.yQI[-1]], aspect='auto') fig1.tight_layout() ax1.set_title('IIc') ax2.set_title('QQc') ax3.set_title('IQc') ax4.set_title('QIc') self.update_page_1(fig1) # send figure to the show_figure terminal self.read_table()
class Canvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100, nD = 2): # plt.xkcd() self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.dim = nD if self.dim is 2: self.axes = self.fig.add_subplot(1, 1, 1) pass else: self.axes = self.fig.add_subplot(1, 1, 1, projection='3d') pass self.axes.hold(False) self.compute_initial_figure() self.setParent(parent) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass def export_pdf(self): fname='export.pdf' self.fig.savefig(fname) def export_jpg(self): fname='export.jpg' self.fig.savefig(fname)
def plot_DVARS(title, DVARS_file, mean_DVARS_distribution=None, figsize=(11.7,8.3)): DVARS = np.loadtxt(DVARS_file) fig = Figure(figsize=figsize) FigureCanvas(fig) if mean_DVARS_distribution: grid = GridSpec(2, 4) else: grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0,:-1]) ax.plot(DVARS) ax.set_xlim((0, len(DVARS))) ax.set_ylabel("DVARS") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0,-1]) sns.distplot(DVARS, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_DVARS_distribution: ax = fig.add_subplot(grid[1,:]) sns.distplot(mean_DVARS_distribution, ax=ax) ax.set_xlabel("Mean DVARS (over all subjects) [std]") MeanFD = DVARS.mean() label = "Mean DVARS = %g"%MeanFD plot_vline(MeanFD, label, ax=ax) fig.suptitle(title, fontsize='14') return fig
class MatplotlibWidget(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): super(MatplotlibWidget, self).__init__(Figure()) # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.setParent(parent) self.figure = Figure(figsize=(width, height), dpi=dpi) self.canvas = FigureCanvas(self.figure) # FigureCanvas.setSizePolicy(self, # QtGui.QSizePolicy.Expanding, # QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.axes = self.figure.add_subplot(111) self.setMinimumSize(self.size()*0.3) print("---------------------- done") def subplot(self,label='111'): self.axes=self.figure.add_subplot(label) def plot(self,*args,**args2): self.axes.plot(*args,**args2) self.draw() def clf(self): self.figure.clf()
class plotwidget(FigureCanvas): def __init__(self, parent, width=12, height=6, dpi=72, projection3d=False): #plotdata can be 2d array for image plot or list of 2 1d arrays for x-y plot or 2d array for image plot or list of lists of 2 1D arrays self.fig=Figure(figsize=(width, height), dpi=dpi) if projection3d: self.axes=self.fig.add_subplot(111, navigate=True, projection='3d') else: self.axes=self.fig.add_subplot(111, navigate=True) self.axes.hold(True) FigureCanvas.__init__(self, self.fig) self.setParent(parent) #self.parent=parent FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) #NavigationToolbar(self, parent) NavigationToolbar(self, self) self.mpl_connect('button_press_event', self.myclick) self.clicklist=[] def myclick(self, event): if not (event.xdata is None or event.ydata is None): arrayxy=[event.xdata, event.ydata] print 'clicked on image: array indeces ', arrayxy, ' using button', event.button self.clicklist+=[arrayxy] self.emit(SIGNAL("genericclickonplot"), [event.xdata, event.ydata, event.button, event.inaxes])
class CanvasPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() def show_data(self,fbfile,fields=['cond','imu_a']): if fbfile.data is None: return self.figure.clear() axs=[] for axi,varname in enumerate(fields): if axi==0: sharex=None else: sharex=axs[0] ax=self.figure.add_subplot(len(fields),1,axi+1,sharex=sharex) axs.append(ax) ax.plot_date( fbfile.data['dn_py'], fbfile.data[varname], 'g-') self.figure.autofmt_xdate() # Not sure how to trigger it to actually draw things. self.canvas.draw() self.Fit()
def __init__(self): wx.Frame.__init__(self, None, -1, "CanvasFrame", size=(550, 350)) N = 10 M = 20 x = [1 for n in xrange(N)] x_extend = x + [0 for n in xrange(M + 1)] h = [0.5 * n for n in xrange(M)] h_extend = h + [0 for n in xrange(N + 1)] y = [0 for n in xrange(N + M)] print x, h, y for n in xrange(N + M): for m in xrange(n + 1): y[n] = y[n] + x_extend[m] * h_extend[n - m] figure = Figure() axes = figure.add_subplot(3, 1, 1) myplot(axes, x, "x") axes = figure.add_subplot(3, 1, 2) myplot(axes, h, "h") axes = figure.add_subplot(3, 1, 3) myplot(axes, y, "y") self.canvas = FigureCanvas(self, -1, figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit()
def end_use(request): N=12 ind = np.arange(N) # the x locations for the groups width=0.35 fig=Figure(figsize=(9,5),facecolor='w', edgecolor='w') ax=fig.add_subplot(221) actual=[9,9,6,3,1,0,0,0,1,2,6,9] ax.bar(ind,actual,0.35,alpha=1,color='b') ax.set_xticks(ind+width) ax.set_xticklabels(('E','F','M','A','M','J','J','A','S','O','N','D')) ax=fig.add_subplot(222) actual=[0,0,0,0,2,3,6,6,3,2,1,0] ax.bar(ind,actual,0.35,alpha=1,color='r') ax.set_xticks(ind+width) ax.set_xticklabels(('E','F','M','A','M','J','J','A','S','O','N','D')) ax=fig.add_subplot(223) actual=[4,4,5,5,6,6,7,6,5,4,4,4] ax.bar(ind,actual,0.35,alpha=1,color='y') ax.set_xticks(ind+width) ax.set_xticklabels(('E','F','M','A','M','J','J','A','S','O','N','D')) ax=fig.add_subplot(224) actual=[2,3,2,3,3,3,3,3,2,3,2,2] ax.bar(ind,actual,0.35,alpha=1,color='m') ax.set_xticks(ind+width) ax.set_xticklabels(('E','F','M','A','M','J','J','A','S','O','N','D')) canvas=FigureCanvas(fig) response=HttpResponse(content_type='image/png') canvas.print_png(response) return response
class MyMplCanvas(FigureCanvas): """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" def __init__(self, parent=None, width=5, height=4, dpi=100): self.fig1 = Figure(figsize=(width, height), dpi=dpi) self.fig2 = Figure(figsize=(width, height), dpi=dpi) fig3 = Figure(figsize=(width, height), dpi=dpi) self.axes1 = self.fig1.add_subplot(223) print self.axes1.__class__.__name__ self.axes2 = self.fig2.add_subplot(221) # We want the axes cleared every time plot() is called #self.axes.hold(False) #self.axes2.hold(False) self.compute_initial_figure() # FigureCanvas.__init__(self, self.fig1) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) t = arange(0.0, 1.0, 0.01) s = sin(2*pi*t) axes3 = fig3.add_subplot(1, 2, 2) axes3.plot(t,s) axes3.set_figure(self.fig1) self.fig1.add_axes(axes3) def compute_initial_figure(self): pass
def graph_data(self): if bool(self.preferences_twoplot_var.get()) is False: f = Figure(figsize=(15,6), dpi=100,) self.graph = f.add_subplot(111) self.plot_data, = self.graph.plot(0,0) self.graph_canvas = FigureCanvasTkAgg(f, self) self.graph_canvas.show() self.graph_canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(self.graph_canvas, self) toolbar.update() self.graph_canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True) else: f = Figure(figsize=(15,6), dpi=100,) self.graph1 = f.add_subplot(211) self.graph2 = f.add_subplot(212) self.plot_data_1, = self.graph1.plot(0,0) self.plot_data_2, = self.graph2.plot(0,0) self.graph_canvas = FigureCanvasTkAgg(f, self) self.graph_canvas.show() self.graph_canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(self.graph_canvas, self) toolbar.update() self.graph_canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True) self.update_graph()
def plotThreeWay(hist, title, filename=None, x_axis_title=None, minimum=None, maximum=None, bins=101): # the famous 3 way plot (enhanced) if minimum is None: minimum = 0 elif minimum == 'minimum': minimum = np.ma.min(hist) if maximum == 'median' or maximum is None: median = np.ma.median(hist) maximum = median * 2 # round_to_multiple(median * 2, math.floor(math.log10(median * 2))) elif maximum == 'maximum': maximum = np.ma.max(hist) maximum = maximum # round_to_multiple(maximum, math.floor(math.log10(maximum))) if maximum < 1 or hist.all() is np.ma.masked: maximum = 1 x_axis_title = '' if x_axis_title is None else x_axis_title fig = Figure() FigureCanvas(fig) fig.patch.set_facecolor('white') ax1 = fig.add_subplot(311) create_2d_pixel_hist(fig, ax1, hist, title=title, x_axis_title="column", y_axis_title="row", z_min=minimum if minimum else 0, z_max=maximum) ax2 = fig.add_subplot(312) create_1d_hist(fig, ax2, hist, bins=bins, x_axis_title=x_axis_title, y_axis_title="#", x_min=minimum, x_max=maximum) ax3 = fig.add_subplot(313) create_pixel_scatter_plot(fig, ax3, hist, x_axis_title="channel=row + column*336", y_axis_title=x_axis_title, y_min=minimum, y_max=maximum) fig.tight_layout() if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def create_input_graph(self, parent, sizer): """ Creates a graph that plots the input It returns a timer what starts the plotting """ graph_panel = wx.Panel(parent, size=(320,0)) self.input_data_generator = DataGen(self) self.data_input = [] dpi = 160 fig = Figure((2.0, 1.0), dpi=dpi) self.axes_input = fig.add_subplot(111) fig.add_subplot() fig.subplots_adjust(bottom=0.009,left=0.003,right=0.997, top=0.991) self.axes_input.set_axis_bgcolor('black') pylab.setp(self.axes_input.get_xticklabels(), fontsize=4) pylab.setp(self.axes_input.get_yticklabels(), fontsize=4) self.plot_data_input = self.axes_input.plot(self.data_input, linewidth=1, color=(1, 0, 0), )[0] self.axes_input.grid(True, color='gray') self.canvas_input = FigCanvas(graph_panel, -1, fig) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.canvas_input, 0) graph_panel.SetSizer(vbox) sizer.Add(graph_panel, 0, wx.TOP | wx.BOTTOM, 5) self.axes_input.set_xbound(lower=0, upper=100) self.axes_input.set_ybound(lower=-1.0, upper=1.0) redraw_timer_input = MyThread(self.graph_refresh_time, self.on_redraw_graph, self) #wx.Timer(self) return redraw_timer_input
def plots( ndata, peaks ) : n,bins = np.histogram(ndata,256) fig = Figure(figsize=(8.5,11)) # plot the histogram ax = fig.add_subplot(211) ax.grid() # don't plot min/max (avoid the clipped pixels) # ax.plot(n[1:255]) ax.plot(n) # plot the peaks x = peaks y = [ n[p] for p in peaks ] ax.plot( x, y, 'rx' ) ax = fig.add_subplot(212) ax.grid() ax.plot( np.diff(n) ) # plot the row avg down the page # ax = fig.add_subplot(313) # ax.grid() # ax.plot([ np.mean(row) for row in ndata[:,]]) outfilename = "out.png" canvas = FigureCanvasAgg(fig) canvas.print_figure(outfilename) print "wrote",outfilename
def create_output_graph(self, parent, sizer): """ Creates a graph that plots the output """ graph_panel = wx.Panel(parent, size=(320,0)) self.data_output = [] dpi = 160 fig = Figure((2.0, 1.0), dpi=dpi) self.axes_output = fig.add_subplot(111) fig.add_subplot() fig.subplots_adjust(bottom=0.009,left=0.003,right=0.997, top=0.991) self.axes_output.set_axis_bgcolor('black') pylab.setp(self.axes_output.get_xticklabels(), fontsize=4) pylab.setp(self.axes_output.get_yticklabels(), fontsize=4) self.plot_data_output = self.axes_output.plot(self.data_output, linewidth=1, color=(0, 0, 1), )[0] self.axes_output.grid(True, color='gray') self.canvas_output = FigCanvas(graph_panel, -1, fig) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.canvas_output, 0) graph_panel.SetSizer(vbox) sizer.Add(graph_panel, 0, wx.TOP | wx.BOTTOM, 5) self.axes_output.set_xbound(lower=0, upper=100) self.axes_output.set_ybound(lower=-1.0, upper=1.0)
def main(A): delta, pos, id = getforest(A, Zmin=2.0, Zmax=2.2, RfLamMin=1040, RfLamMax=1185, combine=4) print len(pos) print pos, delta data = correlate.field(pos, value=delta) DD = correlate.paircount(data, data, correlate.RBinning(160000, 40)) r = DD.centers xi = DD.sum1 / DD.sum2 print r.shape, xi.shape numpy.savez(os.path.join(A.datadir, 'delta-corr1d-both.npz'), r=r, xi=xi) figure = Figure(figsize=(4, 5), dpi=200) ax = figure.add_subplot(311) ax.plot(r / 1000, (r / 1000) ** 2 * xi[0], 'o ', label='$dF$ RSD') ax.set_ylim(-0.4, 1.0) ax.legend() ax = figure.add_subplot(312) ax.plot(r / 1000, (r / 1000) ** 2 * xi[1], 'o ', label='$dF$ Real') ax.set_ylim(-0.4, 1.0) ax.legend() ax = figure.add_subplot(313) ax.plot(r / 1000, (r / 1000) ** 2 * xi[2], 'o ', label=r'$dF$ Broadband') ax.set_ylim(-20, 60) ax.legend() canvas = FigureCanvasAgg(figure) figure.savefig(os.path.join(A.datadir, 'delta-corr-both.svg'))
def plotgraph(window): global df2, indexes, f, a, b f = Figure() plot_df = df2.ix[indexes] plot_df = plot_df.set_index('Particulars') if graph == 1: a = f.add_subplot(211) b = f.add_subplot(212) a.clear() b.clear() plot_df1 = plot_df.T plot_df1.plot(ax=a, title='% Change of Particulars in Income Statement as Trends') plot_df1.plot(ax=b, kind='barh', title='% Change of Particulars in Income Statement as Bars') f.subplots_adjust(left=0.2,bottom=0.2,hspace=0.5) elif graph == 2: a = f.add_subplot(111) a.clear() plot_df.plot(ax=a, kind='barh', title='% Change of Particulars in Income Statement as Bars') f.subplots_adjust(left=0.2,bottom=0.2,hspace=0.5) canvas = FigureCanvasTkAgg(f, window) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, window) toolbar.update() canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
def draw_graph(): fig=Figure() # histogram ax=fig.add_subplot(211) hist_x=np.arange(0, 1, bin_size) ax.bar(hist_x, fidelity_bins, width=bin_size, facecolor='#6666ff') ax.set_xlabel('Fidelity') ax.set_ylabel('Frequency') ax.set_xlim(minf*0.95, maxf) label='Mean Fidelity=%.4f' % fidelity_mean ax.text(0.025, 0.95, label, transform=ax.transAxes, fontsize=10, va='top') label='Worst Fidelity=%.4f' % minf ax.text(0.025, 0.85, label, transform=ax.transAxes, fontsize=10, va='top') # trace ax=fig.add_subplot(212) N=len(data_coincidences) if N>2: t=range(N) (ar,br)=np.polyfit(t,data_coincidences,1) xr=np.polyval([ar,br],t) ax.plot(xr, '--', color='#aaaaaa') ax.plot(data_coincidences, 'b.') ax.plot(data_coincidences, 'b-') ax.plot(data_accidentals, 'r.') ax.plot(data_accidentals, 'r-') ax.set_ylabel('Coincidences') ax.set_xlabel('Time') canvas = FigureCanvasAgg(fig) canvas.print_figure('output/%s.pdf' % start_time, dpi=100)
class Canvas(FigureCanvas): """Matplotlib Figure widget to display CPU utilization""" def __init__(self, parent, ionCatalogArray, ionSwapCatalog): self.parent = parent self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.ax1 = self.fig.add_subplot(131) self.ax2 = self.fig.add_subplot(132) self.ax3 = self.fig.add_subplot(133) self.setHist(self.ax2, ionCatalogArray[0], label = 'initial') self.setHist(self.ax3, ionCatalogArray[1], label = 'final') self.ax1.set_xlabel('Number Of Dark Ions') self.ax1.text(.35, .75, str((len(np.where(np.array(ionCatalogArray[0]) == 1)[0])/float(len(ionCatalogArray[0])))*100) + ' percent w/ one ion dark', fontsize=12, transform = self.ax1.transAxes) self.ax1.text(.35, .8, 'Mean: ' + str(np.mean(ionCatalogArray[0])) + ' ions dark', transform = self.ax1.transAxes) self.ax1.set_ylim(0, 1) self.ax2.set_xlabel('Number Of Dark Ions') self.ax2.text(.35, .75, str((len(np.where(np.array(ionCatalogArray[1]) == 1)[0])/float(len(ionCatalogArray[1])))*100) + ' percent w/ one ion dark', fontsize=12, transform = self.ax2.transAxes) self.ax2.text(.35, .8, 'Mean: ' + str(np.mean(ionCatalogArray[1])) + ' ions dark', transform = self.ax2.transAxes) self.ax2.set_ylim(0, 1) self.ax3.hist(ionSwapCatalog, bins=range(self.parent.parent.expectedNumberOfIonsSpinBox.value() + 1), align='left', normed = True, label = 'Ion Swaps' ) self.ax3.legend(loc='best') self.ax3.set_xlabel('Distance of Ion Movement') self.ax3.text(.25, .8, 'Number Ion Swaps: ' + str(len(np.where(np.array(ionSwapCatalog) == 1)[0])), transform = self.ax3.transAxes) self.ax3.text(0.025, .75, '1 ion dark in both shine729 and final: ' + str(len(ionSwapCatalog)/float(len(ionCatalogArray[0]))*100) + ' %', transform = self.ax3.transAxes) self.ax3.text(0.10, .70, 'Probability of Ion Swap: ' + str(len(np.where(np.array(ionSwapCatalog) == 1)[0])/float(len(ionSwapCatalog))), transform = self.ax3.transAxes) def setHist(self, ax, data, label): ax.hist(data, bins=range(10), align='left', normed=True, label = label) ax.legend(loc='best')
def drawFFTAndPath(frame, x, y, freq, amp, titleCoP, titleFFT): f = Figure() gs = gridspec.GridSpec(1,2,width_ratios=[1,1],height_ratios=[1,1]) a = f.add_subplot(gs[0]) img = imread("Images/Wii.JPG") a.imshow(img, zorder=0, extent=[-216 - 26, 216 + 26, -114 - 26, 114 + 26]) a.plot(x, y) a.set_title(titleCoP, fontsize=13) a.set_xlim([-216 - 30, 216 + 30]) a.set_ylim([-114 - 30, 114 + 30]) a.set_ylim([-114 - 30, 114 + 30]) a.set_xlabel("CoPx (mm)", fontsize=12) a.set_ylabel("CoPy (mm)", fontsize=12) if amp[0] == 0: titleFFT = titleFFT + ' (0Hz filtered)' b = f.add_subplot(gs[1]) b.plot(freq, amp) ttl = b.title ttl.set_position([.5, 1.05]) b.set_title(titleFFT, fontsize=12) b.set_xlabel("Frequency (Hz)", fontsize=12) b.set_ylabel("Amplitude", fontsize=12) canvas = FigureCanvasTkAgg(f, frame) toolbar = NavigationToolbar2TkAgg(canvas, frame) canvas.show() canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True) toolbar.update() canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True)
class EmbeddedGraph(QtWidgets.QWidget): def __init__(self, graph_widget, computed_data): super().__init__(parent=graph_widget) self.logger = logging.getLogger(__name__) self.graph_widget = graph_widget self.computed_data = computed_data self.current_plot_index = 0 self.current_list_entry = None self.current_item = None self.figure, self.toolbar, self.axes = None, None, None self.colourbar = None self._setup_canvas() self._setup_layouts() def _setup_canvas(self): self.figure = Figure() self.axes = self.figure.add_subplot() self.figure_canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.figure_canvas, self) def _setup_layouts(self): parent_layout = QtWidgets.QGridLayout() parent_layout.addWidget(self.toolbar) parent_layout.addWidget(self) graph_layout = QtWidgets.QGridLayout() graph_layout.addWidget(self.figure_canvas) self.setLayout(graph_layout) self.graph_widget.setLayout(parent_layout) def reset(self): self.current_plot_index = 0 self.current_list_entry = None def _plot_line(self, x, y, title, xlabel, ylabel, legend=None, line_style="-"): self.axes.plot(x, y, line_style) self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel) self.axes.set_title(title) if legend is not None: self.axes.legend(legend) def _plot_image(self, x, y, z, title, xlabel, ylabel): # TODO overhaul colour bar selection either through a dropdown list or use some check colour_map = self.computed_data.colourmap cmap = cm.get_cmap(colour_map) cf = self.axes.contourf(x, y, z, cmap=cmap) self.colourbar = self.figure.colorbar(cf) self.axes.set_title(title) self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel) # self.axes.show() # A method to plot the 2D system as a wireframe. def _plot_wireframe(self, x, y, z, title, xlabel, ylabel, zlabel): fig = self.figure ax = fig.gca(projection="3d") ax.plot_wireframe(x, y, z) ax.set_zlabel(zlabel) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # ax.show() # A method to plot the 2D system as a surface plot. def _plot_surface(self, x, y, z, title, xlabel, ylabel, zlabel): colour_map = self.computed_data.colourmap cmap = cm.get_cmap(colour_map) fig = self.figure ax = fig.gca(projection="3d") surf = ax.plot_surface(x, y, z, cmap=cmap) self.colourbar = fig.colorbar(surf, ax=ax) ax.set_zlabel(zlabel) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # ax.show() # A method to plot the 3d system as a 3D scatter plot. def _plot_3D_scatter(self, x, y, z, vals, title, xlabel, ylabel, zlabel): colour_map = self.computed_data.colourmap fig = self.figure ax = fig.gca(projection='3d') p = ax.scatter3D(x, y, zs=z, c=vals, cmap=colour_map) self.colourbar = fig.colorbar(p, ax=ax) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_zlabel(zlabel)
class CustomFigCanvas(FigureCanvas): def __init__(self): Y = np.zeros(30) X = np.linspace(1, 30, 30) self.fig = Figure(tight_layout=True) super().__init__(self.fig) plt.rcParams['axes.unicode_minus'] = False self.amp = self.fig.add_subplot(121) self.l11, = self.amp.plot(X, Y, color='#DC143C', linestyle='-', linewidth=2, marker='o', label='at1') self.l21, = self.amp.plot(X, Y, color='#000079', linestyle='-', linewidth=2, marker='H', label='at2') self.l31, = self.amp.plot(X, Y, color='#006000', linestyle='-', linewidth=2, marker='s', label='at3') self.amp.set_xlim(1, 30) self.amp.set_ylim(0, 35) self.amp.set_autoscale_on(False) self.amp.set_xlabel('子信道编号') self.amp.set_ylabel('信噪比 (dB)') self.amp.set_title('幅度信息') self.amp.legend() self.phase = self.fig.add_subplot(122) self.l12, = self.phase.plot(X, Y, color='#00BFFF', linestyle='-', linewidth=2, marker='o', label='1&2') self.l22, = self.phase.plot(X, Y, color='#F4A460', linestyle='-', linewidth=2, marker='H', label='2&3') self.l32, = self.phase.plot(X, Y, color='#800080', linestyle='-', linewidth=2, marker='s', label='3&1') self.phase.set_xlim(1, 30) self.phase.set_ylim(-1, 1) self.phase.set_autoscale_on(False) self.phase.set_xlabel('子信道编号') self.phase.set_ylabel('') self.phase.set_title('相位差信息') self.phase.legend() FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) def updateAni(self, data): """绘制动画的时候每一次都会调用这个函数来更新. data: 每一次要绘制的数据 """ Y1, Y2, Y3, Y4, Y5, Y6 = data self.l11.set_ydata(Y1) self.l21.set_ydata(Y2) self.l31.set_ydata(Y3) self.l12.set_ydata(Y4) self.l22.set_ydata(Y5) self.l32.set_ydata(Y6) self.fig.canvas.draw()
def setUpGraphPage(self): if self.gettingFluroscentIntensity == False: fig1 = Figure() f1 = fig1.add_subplot(111) f1.scatter( self.fluorscentIntensity.sharpData[ 0:len(self.fluorscentIntensity.sharpData), 0], self.fluorscentIntensity.sharpData[ 0:len(self.fluorscentIntensity.sharpData), 1], 1) f1.set_title('Sharp Fluorscent Intensity vs Time') f1.set_xlabel('Seconds') f1.set_ylabel('Fluorscent Intensity') fig2 = Figure() f2 = fig2.add_subplot(111) f2.scatter( self.fluorscentIntensity.sharpData[ 0:len(self.fluorscentIntensity.sharpData), 0], self.fluorscentIntensity.sharpData[ 0:len(self.fluorscentIntensity.sharpData), 2], 1) f2.set_title('Sharp Edge-Sharpness vs Time') f2.set_xlabel('Seconds') f2.set_ylabel('Edge-Sharpness') fig3 = Figure() f3 = fig3.add_subplot(111) f3.scatter( self.fluorscentIntensity.allData[ 0:len(self.fluorscentIntensity.allData), 0], self.fluorscentIntensity.allData[ 0:len(self.fluorscentIntensity.allData), 1], 1) f3.set_title('Fluorscent Intensity vs Time') f3.set_xlabel('Seconds') f3.set_ylabel('Fluorscent Intensity') fig4 = Figure() f4 = fig4.add_subplot(111) f4.scatter( self.fluorscentIntensity.allData[ 0:len(self.fluorscentIntensity.allData), 0], self.fluorscentIntensity.allData[ 0:len(self.fluorscentIntensity.allData), 2], 1) f4.set_title('Edge-Sharpness vs Time') f4.set_xlabel('Seconds') f4.set_ylabel('Edge-Sharpness') fig5 = Figure() f5 = fig5.add_subplot(111) f5.scatter(self.X, self.y, 1, c='b') f5.plot(self.line_X, self.line_y_ransac, color='r') f5.set_title('RANSAC Best fit of selected ROI') f5.set_xlabel('Seconds') f5.set_ylabel('Fluorscent Intensity') self.graph = GraphPage() self.graph.addfig('Sharp Fluorscent Intensity vs Time', fig1) self.graph.addfig('Sharp Edge-Sharpness vs Time', fig2) self.graph.addfig('Fluorscent Intensity vs Time', fig3) self.graph.addfig('Edge-Sharpness vs Time', fig4) self.graph.addfig('RANSAC Best Fit', fig5) self.graph.show()
def plot_univ_on_GUI(self): if not self.current_simulation or not self.current_simulation.results: return if len(self.current_simulation.results) == self.last_results_plotted: return self.last_results_plotted = len(self.current_simulation.results) current_var = self.current_simulation.vars_to_change[0] results = pd.concat(self.current_simulation.results).sort_index() fig_list =[] var_fig = Figure(figsize = (3,3), facecolor=[240/255,240/255,237/255], tight_layout=True) a = var_fig.add_subplot(111) num_bins = 15 _, bins, _ = a.hist(self.simulation_dist[current_var], num_bins, facecolor='blue', alpha=0.1) a.hist(results[current_var], bins=bins, facecolor='blue', alpha=0.7) a.set_title(current_var) fig_list.append(var_fig) mfsp_fig = Figure(figsize = (3,3), facecolor=[240/255,240/255,237/255], tight_layout=True) b = mfsp_fig.add_subplot(111) b.hist(results['MFSP'], num_bins, facecolor='blue', alpha=0.85) b.set_title('MFSP - ' + current_var) fig_list.append(mfsp_fig) figs_to_plot = self.finished_figures[:] + fig_list if len(self.current_simulation.results) == self.current_simulation.tot_sim: self.finished_figures += fig_list if self.univar_row_num != 0: row_num = 17 else: row_num = 10 frame_canvas = ttk.Frame(self.current_tab) frame_canvas.grid(row=row_num, column=1, columnspan = 3,pady=(5, 0)) frame_canvas.grid_rowconfigure(0, weight=1) frame_canvas.grid_columnconfigure(0, weight=1) frame_canvas.config(height = '10c', width='12c') main_canvas = Canvas(frame_canvas) main_canvas.grid(row=0, column=0, sticky="news") main_canvas.config(height = '10c', width='12c') vsb = ttk.Scrollbar(frame_canvas, orient="vertical", command=main_canvas.yview) vsb.grid(row=0, column=1,sticky = 'ns') main_canvas.configure(yscrollcommand=vsb.set) figure_frame = ttk.Frame(main_canvas) main_canvas.create_window((0, 0), window=figure_frame, anchor='nw') figure_frame.config(height = '10c', width='12c') row_num = 0 column = False for figs in figs_to_plot: figure_canvas = FigureCanvasTkAgg(figs, master=figure_frame) if column: col = 4 else: col = 1 #figure_canvas.draw() figure_canvas.get_tk_widget().grid( row=row_num, column=col,columnspan=2, rowspan = 5, pady = 5,padx = 8, sticky=E) #figure_canvas._tkcanvas.grid(row=row_num, column = 0,columnspan = 10, rowspan = 10, sticky= W+E+N+S, pady = 5,padx = 5) if column: row_num += 5 column = not column figure_frame.update_idletasks() frame_canvas.config(width='12c', height='10c') # Set the canvas scrolling region main_canvas.config(scrollregion=figure_frame.bbox("all"))
class plotGrainData(PyQt5.QtWidgets.QMainWindow): """ Constructor Parmeters: - grainsData: a object of type grainPlotData, defined in testGrainsPeaks, for which input files have been read - grainN: the grain number to start with (put 1 if unknown) - plotwhat: what to plot, choice of "etavsttheta", "omegavsttheta", or default ("svsf") """ def __init__(self, grainsData, grainN, plotwhat, parent=None): PyQt5.QtWidgets.QMainWindow.__init__(self, parent) self.annotation = "" self.grainsData = grainsData self.ngrains = self.grainsData.getNGrains() self.graintoplot = grainN - 1 self.whatoplot = plotwhat self.create_main_frame() self.on_draw() self.show() """ Builds up the GUI """ def create_main_frame(self): self.main_frame = PyQt5.QtWidgets.QWidget() self.fig = Figure((8.0, 8.0), dpi=100, tight_layout=True, edgecolor='w', facecolor='w') grainLabel = PyQt5.QtWidgets.QLabel("Grain (1-%d) : " % self.ngrains, self) self.grainNBox = PyQt5.QtWidgets.QLineEdit( "%d" % (self.graintoplot + 1), self) self.grainNBox.returnPressed.connect(self.new_grain) buttonP = PyQt5.QtWidgets.QPushButton('Previous', self) buttonP.setToolTip('Move to previous grain') buttonP.clicked.connect(self.handle_backward) buttonN = PyQt5.QtWidgets.QPushButton('Next', self) buttonN.setToolTip('Move to next grain') buttonN.clicked.connect(self.handle_forward) plotLabel = PyQt5.QtWidgets.QLabel("Plot", self) self.plotWhatBox = PyQt5.QtWidgets.QComboBox() self.plotWhatBox.addItem("s vs f", "svsf") self.plotWhatBox.addItem("Eta vs. 2 theta", "etavsttheta") self.plotWhatBox.addItem("Omega vs. 2 theta", "omegavsttheta") self.plotWhatBox.currentIndexChanged.connect(self.plotselectionchange) hlay = PyQt5.QtWidgets.QHBoxLayout() hlay.addWidget(grainLabel) hlay.addWidget(buttonP) hlay.addWidget(self.grainNBox) hlay.addWidget(buttonN) hlay.addItem( PyQt5.QtWidgets.QSpacerItem(300, 10, PyQt5.QtWidgets.QSizePolicy.Expanding)) hlay.addWidget(plotLabel) hlay.addWidget(self.plotWhatBox) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.canvas.setFocusPolicy(PyQt5.QtCore.Qt.StrongFocus) self.canvas.setFocus() self.canvas.mpl_connect('pick_event', self.on_pick) self.fig.canvas.mpl_connect('forward_event', self.handle_forward) self.fig.canvas.mpl_connect('backward_event', self.handle_backward) self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.mpl_toolbar.forward = new_forward self.mpl_toolbar.back = new_backward windowLabel = PyQt5.QtWidgets.QLabel( "This is part of the TIMEleSS tools <a href=\"http://timeless.texture.rocks/\">http://timeless.texture.rocks/</a>", self) windowLabel.setOpenExternalLinks(True) windowLabel.setAlignment(PyQt5.QtCore.Qt.AlignRight | PyQt5.QtCore.Qt.AlignVCenter) vbox = PyQt5.QtWidgets.QVBoxLayout() vbox.addLayout(hlay) vbox.addWidget(self.canvas) # the matplotlib canvas vbox.addWidget(self.mpl_toolbar) vbox.addWidget(windowLabel) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame) """ Draws or redraws the plot """ def on_draw(self): # Getting plot data [title, xlabel, ylabel, xmeasured, ymeasured, xpred, ypred, rings] = self.grainsData.getPlotData(self.graintoplot, self.whatoplot) # Clearing plot self.fig.clear() self.axes = self.fig.add_subplot(111) # Plotting diffraction rings for ring in rings: self.axes.plot(ring[1], ring[0], color='black', linestyle='solid', linewidth=0.5, alpha=0.5) # Adding indexed peaks g1 = self.axes.scatter(xmeasured, ymeasured, s=60, marker='o', facecolors='r', edgecolors='r') g2 = self.axes.scatter( xpred, ypred, s=80, marker='s', facecolors='none', edgecolors='b', picker=5) # Picker to allow users to pick on a point # Title and labels self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel) self.axes.set_title(title, loc='left') if (self.whatoplot == "svsf"): self.axes.set_aspect(1.0) self.axes.autoscale(tight=True) else: self.axes.set_aspect('auto') self.axes.autoscale(tight=False) # Legend self.axes.legend([g1, g2], ['Measured', 'Predicted'], loc='upper right', ncol=2, scatterpoints=1, frameon=True, markerscale=1, borderpad=0.2, labelspacing=0.2, bbox_to_anchor=(1., 1.05)) # Ready to draw self.annotation = "" # No annotation yet. Important for dealing with picking events self.canvas.draw() """ Event processing to change the plot type """ def plotselectionchange(self, index): self.whatoplot = self.plotWhatBox.itemData(index) self.on_draw() """ Event processing: we need to change grain based on text input """ def new_grain(self): try: i = int(self.grainNBox.text()) - 1 self.graintoplot = (i) % self.ngrains self.grainNBox.setText("%d" % (self.graintoplot + 1)) self.on_draw() except ValueError: PyQt5.QtWidgets.QMessageBox.critical(self, "Error", "Not an integer") """ Event processing when left arrow is click (move to previous grain) """ def handle_backward(self, evt): self.graintoplot = (self.graintoplot - 1) % self.ngrains self.grainNBox.setText("%d" % (self.graintoplot + 1)) self.on_draw() """ Event processing when right arrow is click (move to next grain) """ def handle_forward(self, evt): self.graintoplot = (self.graintoplot + 1) % self.ngrains self.grainNBox.setText("%d" % (self.graintoplot + 1)) self.on_draw() """ Picking events on data in plot - Locates the peak that is being selected - Pulls out indexing information for this peak (h, k, l, predicted and measured angles) - Displays information in the plot, next to the peak Parameters event """ def on_pick(self, event): # print('you picked on data') thisdataset = event.artist index = event.ind posX = (thisdataset.get_offsets())[index][0][0] posY = (thisdataset.get_offsets())[index][0][1] text = self.grainsData.getPeakInfo(self.graintoplot, index[0]) if (self.annotation != ""): self.annotation.remove() # Add the peak information to the plot self.annotation = self.axes.text(posX, posY, text, fontsize=9, bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 1., 1.), alpha=0.9)) self.canvas.draw()
class PlotCanvas(FigureCanvas): def __init__(self, linenumber, ownsizes=None, parent=None, width=5, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) super().__init__(self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, Wid.QSizePolicy.Expanding, Wid.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.ldict = {} lcolors = () lmarkers = () lcolors = ('purple', 'red', 'green', 'orange', 'yellow') lmarkers = ('o', 'o', '*', 'o', 'o') if ownsizes is None: lsizes = (2, 2, 2, 2, 2) else: lsizes = ownsizes for i in range(0, linenumber): key = 'line' + str(i) self.ldict[key] = lines.Line2D([], [], marker=lmarkers[i], color=lcolors[i], linestyle='', markersize=lsizes[i]) self.draw() self.axes.grid() self.axes.set_ylabel('y') self.axes.set_xlabel('x') def scalePlot(self, scale='linear'): self.axes.set_yscale(scale) def limitPlot(self, xvalues, yvalues): # Replot with new scales. self.axes.set_xlim(xvalues) self.axes.set_ylim(yvalues) self.fig.canvas.draw() self.flush_events() def getData(self): for key in self.ldict: print(self.ldict[key].get_data()) def updatePlot(self, *args): for data, key in zip(args, self.ldict): self.ldict[key].set_data(data) self.axes.add_line(self.ldict[key]) self.fig.canvas.draw() self.flush_events() def updatexyLabels(self, xlabel, ylabel): self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel) def savePlot(self, name): self.fig.savefig(name)
class Window(QtGui.QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = Figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method self.button = QtGui.QPushButton('Start') self.button.clicked.connect(self.plot) self.button2 = QtGui.QPushButton('Play') self.button2.clicked.connect(self.play) # set the layout layout = QtGui.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) layout.addWidget(self.button2) self.setLayout(layout) def play(self): def update_line(num, line): i = X_VALS[num] line.set_data( [i, i], [Y_MIN, Y_MAX]) return line, Y_MIN = min(self.rgdSamples) Y_MAX = max(self.rgdSamples) l , v = self.ax.plot(0, Y_MIN, 10, Y_MAX, linewidth=2, color= 'red') line_anim = animation.FuncAnimation(self.figure, update_line, len(X_VALS), fargs=(l, ), interval=100, blit=True, repeat=False) CHUNK = 1024 here = sys.path[0] sound_path = os.path.join(here, "test.wav") wf = wave.open(sound_path, 'rb') p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(CHUNK) while data != '': stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate() def plot(self): ''' plot some random stuff ''' # random data #print DWF version print("DWF Version: " + dwf.FDwfGetVersion()) #constants HZ_ACQ = 20e3 N_SAMPLES = 200000 #open device print("Opening first device") dwf_ao = dwf.DwfAnalogOut() print("Preparing to read sample...") print("Generating sine wave...") dwf_ao.nodeEnableSet(0, dwf_ao.NODE.CARRIER, True) dwf_ao.nodeFunctionSet(0, dwf_ao.NODE.CARRIER, dwf_ao.FUNC.SINE) dwf_ao.nodeFrequencySet(0, dwf_ao.NODE.CARRIER, 1.0) dwf_ao.nodeAmplitudeSet(0, dwf_ao.NODE.CARRIER, 2.0) dwf_ao.configure(0, True) #set up acquisition dwf_ai = dwf.DwfAnalogIn(dwf_ao) dwf_ai.channelEnableSet(0, True) dwf_ai.channelRangeSet(0, 5.0) dwf_ai.acquisitionModeSet(dwf_ai.ACQMODE.RECORD) dwf_ai.frequencySet(HZ_ACQ) dwf_ai.recordLengthSet(N_SAMPLES/HZ_ACQ) #wait at least 2 seconds for the offset to stabilize time.sleep(2) #begin acquisition dwf_ai.configure(False, True) print(" waiting to finish") self.rgdSamples = [] cSamples = 0 fLost = False fCorrupted = False while cSamples < N_SAMPLES: sts = dwf_ai.status(True) if cSamples == 0 and sts in (dwf_ai.STATE.CONFIG, dwf_ai.STATE.PREFILL, dwf_ai.STATE.ARMED): # Acquisition not yet started. continue cAvailable, cLost, cCorrupted = dwf_ai.statusRecord() cSamples += cLost if cLost > 0: fLost = True if cCorrupted > 0: fCorrupted = True if cAvailable == 0: continue if cSamples + cAvailable > N_SAMPLES: cAvailable = N_SAMPLES - cSamples # get samples self.rgdSamples.extend(dwf_ai.statusData(0, cAvailable)) cSamples += cAvailable print("Recording finished") if fLost: print("Samples were lost! Reduce frequency") if cCorrupted: print("Samples could be corrupted! Reduce frequency") with open("record.csv", "w") as f: for v in self.rgdSamples: f.write("%s\n" % v) """plt.show()""" scaled = np.int16(self.rgdSamples/np.max(np.abs(self.rgdSamples)) * 32767) write('test.wav', 20000, scaled) # create an axis self.ax = self.figure.add_subplot(2,1,1) # discards the old graph self.ax.clear() # plot data sample_time = np.arange(len(self.rgdSamples))/HZ_ACQ self.ax.plot(sample_time, self.rgdSamples) samplingFrequency, signalData = wavfile.read('test.wav') self.bx = self.figure.add_subplot(2,1,2) self.bx.specgram(signalData,Fs=samplingFrequency) # refreshs canvas self.canvas.draw()
def richness_all_samples(self, working_samples, samples_list, tax_level): self.create_window() self.top.title('Richness') self.top.title('overview of richness of all samples on ' + tax_level + ' level') self.inner_frame = Frame(self.frame) self.inner_frame.grid(row=1, column=0, columnspan=4) top_space = 20 width = 600 if len(samples_list) > 20: width = 1000 start_idx = len(self.all_tax_levels) - list( self.all_tax_levels).index(tax_level) if self.abundance_df.groupAbsoluteSamples() is not None: absolute_working_samples = self.abundance_df.groupAbsoluteSamples() absolute_working_samples = absolute_working_samples[ samples_list].astype('int') richness = absolute_working_samples.astype(bool).sum(axis=0) else: richness = working_samples.astype(bool).sum(axis=0)[start_idx:-2] fig = Figure(figsize=(4, 6), dpi=120) #, tight_layout=True) ax = fig.add_subplot(211) bp = ax.boxplot(richness) for val in richness: x = np.random.normal(1, 0.04, 1) ax.scatter(x, val, c='grey', marker='.', alpha=0.4) ax.set_xticklabels(['']) ax.set_ylabel('number of ' + tax_level) ax = fig.add_subplot(212) for i, val in enumerate(richness): ax.scatter(richness.index[i], val, marker='.') ax.set_xticklabels(richness.index, fontsize=8, rotation='vertical') ax.set_xlabel('samples') ax.set_ylabel('number of ' + tax_level) fig.subplots_adjust(left=0.1, right=0.98, bottom=0.2, top=0.95, hspace=0.2, wspace=0.2) matplotlib_frame = Frame(self.frame) matplotlib_frame.grid(row=2, column=0, rowspan=2, columnspan=2) canvas = FigureCanvasTkAgg(fig, matplotlib_frame) canvas.draw() canvas.get_tk_widget().grid(row=1, column=0, columnspan=4) save_button = Button( self.inner_frame, text="Save (high resolution)", command=lambda fig=fig, title='Richness', initialfile= 'richness_all_samples': self.save_high_resolution_figure( fig, title, initialfile)) save_button.grid(row=1, column=0)
#Make a matplotlib plot in a tkinter window root = tk.Tk() root.title('Matplotlib in window') #make fake data x = np.arange(0, 4, 0.01) y = x**2 #make plot fig = Figure() #can also do tight layout option here, if needed fig.tight_layout() #how to create plot and add to it MyPlot = fig.add_subplot() MyPlot.plot(x, y, label='this is data') MyPlot.set_xlabel('x axis') MyPlot.set_title('title') MyPlot.legend(loc='best') MyPlot.tick_params(direction='in') canvas = FigureCanvasTkAgg(fig, master=root) canvas.draw() canvas.get_tk_widget().grid(row=0, column=0, columnspan=2) #making a button to check b = tk.Button(root, text='quit here', command=root.destroy) b.grid(row=1, column=0) b2 = tk.Button(root,
def shannon_diversity_all_samples(self, working_samples, samples_list, tax_level): from skbio.diversity.alpha import shannon self.create_window() self.top.title('Shannon diversity') self.top.title('overview of Shannon index of all samples on ' + tax_level + ' level') self.inner_frame = Frame(self.frame) self.inner_frame.grid(row=1, column=0, columnspan=4) top_space = 20 width = 600 if len(samples_list) > 20: width = 1000 #shannon index (alpha diversity) if self.abundance_df.groupAbsoluteSamples() is not None: absolut_working_samples = self.abundance_df.groupAbsoluteSamples() absolut_working_samples = absolut_working_samples[ samples_list].astype('int') shannon0 = absolut_working_samples.loc[[ tax + '_' for tax in list(working_samples[tax_level]) ]].apply(shannon) else: shannon0 = [] for sample in samples_list: shannon0.append( shannon_index(working_samples[sample].as_matrix())) shannon0 = pd.Series(shannon0, index=samples_list) fig = Figure(figsize=(4, 6), dpi=120) #, tight_layout=True) ax = fig.add_subplot(211) bp = ax.boxplot(shannon0) for val, in zip(shannon0): x = x = np.random.normal(1, 0.04, 1) ax.scatter(x, val, c='grey', marker='.', alpha=0.4) ax.set_xticklabels(['Shannon diversity']) #ax.set_ylabel('number of species') ax = fig.add_subplot(212) for i, val in enumerate(shannon0): ax.scatter(shannon0.index[i], val, marker='.') ax.set_xticklabels(shannon0.index, fontsize=8, rotation='vertical') ax.set_xlabel('samples') ax.set_ylabel('Shannon diversity index') fig.subplots_adjust(left=0.1, right=0.98, bottom=0.2, top=0.95, hspace=0.3, wspace=0.3) matplotlib_frame = Frame(self.frame) matplotlib_frame.grid(row=2, column=0, rowspan=2, columnspan=2) canvas = FigureCanvasTkAgg(fig, matplotlib_frame) canvas.draw() canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True) save_button = Button( self.inner_frame, text="Save (high resolution)", command=lambda fig=fig, title='Shannon diversity', initialfile= 'shannon_all_samples': self.save_high_resolution_figure( fig, title, initialfile)) save_button.grid(row=1, column=0)
class Graph3(FigureCanvas): def __init__(self, parent=None, width=10, height=5, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) self.fig.patch.set_visible(False) FigureCanvas.__init__(self, self.fig) # self.alarmsPerHost: stores IPAddresses of the hosts and the correspondents severity alarms counters self.alarmsPerHost = defaultdict(lambda: defaultdict(int)) # self.totalAlarmsPerSeverity: keys are the severities while the items are correspondent counters self.totalAlarmsPerSeverity = defaultdict(lambda: []) # self.percentage: keys are the host IpAddresses or a key='Overall alarms' for the cumulative scenario, while items # are the various percentages of the severity levels self.percentage = defaultdict(int) self.setParent(parent) self.axes.invert_yaxis() self.axes.xaxis.set_visible(False) self.axes.set_title("Percentage of the various alarms ", color='white') self.axes.text(0.5, 0.5, "No data", horizontalalignment='center', verticalalignment='center', fontsize=20) #RefreshButton has been clicked:redo the graph def reFreshGraph3(self): self.alarmsPerHost.clear() self.totalAlarmsPerSeverity.clear() self.percentage.clear() getNewData = CommonFunctions() results = getNewData.fetchDataFromDB() try: if (len(results) == 0): raise Exception("No plot of graph 3") self.alarmsPerHost = getNewData.organizeAlarmsPerHost(results) self.totalAlarmsPerSeverity = getNewData.organizeTotalAlarmsPerSeverity( results) self.plotGraph3(self.axes) except Exception as e: logging.log(logging.ERROR, "The alarm table is empty: " + str(e)) self.axes.text(0.5, 0.5, "Error loading data", horizontalalignment='center', verticalalignment='center', fontsize=20) def plotGraph3(self, ax): ax.invert_yaxis() ax.xaxis.set_visible(False) ax.set_title("Percentage of the various alarms ", color='white') ax.tick_params(axis='x', colors='white') ax.tick_params(axis='y', colors='white') getData = CommonFunctions() descriptionList, totalFractions = [], [] totAlarms = self.countAlarms(self.totalAlarmsPerSeverity) for key, item in sorted(self.totalAlarmsPerSeverity.items()): descriptionList.append(getData.getInfo(key)) totFraction = item / totAlarms totalFractions.append(totFraction * 100) self.percentage['Overall Alarms'] = totalFractions for host in sorted(self.alarmsPerHost): singleFractions = [] totPerHostAlarms = self.countAlarms(self.alarmsPerHost[host]) for ele in sorted(self.alarmsPerHost[host]): singleFractions.append( (self.alarmsPerHost[host][ele] / totPerHostAlarms) * 100) self.percentage[host] = singleFractions labels = list(self.percentage.keys()) data = np.array(list(self.percentage.values())) data_cum = data.cumsum(axis=1) colors_list = [ 'yellowgreen', 'orange', 'red', 'rebeccapurple', 'dodgerblue', 'brown' ] try: if (len(colors_list) < len(totalFractions)): raise Exception( "If you want to plot, you have to define more colors in the colors_list" ) colors = colors_list[0:len(totalFractions)] ax.invert_yaxis() ax.xaxis.set_visible(False) ax.set_xlim(0, np.sum(data, axis=1).max()) for i, (colname, color) in enumerate(zip(descriptionList, colors)): widths = data[:, i] starts = data_cum[:, i] - widths ax.barh(labels, widths, left=starts, height=0.5, label=colname, color=color) xcenters = starts + widths / 2 for y, (x, c) in enumerate(zip(xcenters, widths)): cString = str(round(c, 1)) if (round(c, 1) < 1): showPercentage = "" else: showPercentage = cString + "%" ax.text(x, y, showPercentage, ha='center', va='center') ax.legend(ncol=len(descriptionList), bbox_to_anchor=(0, -0.1), loc='lower left', fontsize='small') infoRefresh = "Last reFresh at time:" + datetime.datetime.now( ).strftime('%Y-%m-%d %H:%M:%S') ax.text(0, -0.12, infoRefresh, verticalalignment='center', color='white', transform=ax.transAxes) except Exception as e: logging.log(logging.ERROR, "Cannot plot: " + str(e)) #The user has required to save either this graph or all the graphs def saveGraph3(self, directory): path = directory + "\graph3.png" saveObject = CommonFunctions() saveObject.saveSingleGraph(path, self.fig, 3) def countAlarms(self, dict): totAlarms = 0 for key, item in sorted(dict.items()): totAlarms = totAlarms + item return totAlarms
def _plot_gaussian_baseline(self, full_x, full_y, sigma, x, y, y_pred): from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas figure = Figure() canvas = FigureCanvas(figure) axes = figure.add_subplot(1, 1, 1, axisbg='whitesmoke') # Adds a 95% confidence interval to the plot ExperimentMicroCal._plot_confidence_interval(axes, full_x, sigma, y_pred) # Entire set of data axes.plot(full_x, full_y, 'o', markersize=2, lw=1, color='deepskyblue', alpha=.5, label='Raw data') # Points for fit axes.plot(x, y, 'o', color='crimson', markersize=2, alpha=.8, label='Fitted data') # Prediction axes.plot(full_x, y_pred, 'o', markersize=1, mec='w', mew=1, color='k', alpha=.5, label='Predicted baseline') # Plot injection time markers. [ymin, ymax] = axes.get_ybound() for injection in self.injections: # timepoint at start of syringe injection last_index = injection.first_index t = self.filter_period_end_time[last_index] / ureg.second axes.plot([t, t], [ymin, ymax], '-', color='crimson') # Adjust axis to zoom in on baseline. ymax = self.baseline_power.max() / (ureg.microcalorie / ureg.second) ymin = self.baseline_power.min() / (ureg.microcalorie / ureg.second) width = ymax - ymin ymax += width / 2 ymin -= width / 2 axes.set_ybound(ymin, ymax) axes.set_xlabel('time (s)') axes.set_ylabel(r'differential power ($\mu$cal / s)') axes.legend(loc='upper center', bbox_to_anchor=(0.5, 0.1), ncol=4, fancybox=True, shadow=True, markerscale=3, prop={'size': 6}) axes.set_title(self.data_filename) canvas.print_figure(self.name + '-baseline.png', dpi=500)
class mainWindow(Frame): today=str(datetime.today().date()) lastday=today filePath="/home/prashant/01050007/01050007_Data/" if os.path.exists(filePath+str(today)+".csv"): f=open(filePath+str(today)+".csv","a") else: f=open(filePath+str(today)+".csv","w") f.write("Time,Vac1,Vac2,Vac3,Vpv1,Vpv2,Iac1,Iac2,Iac3,Ipv1,Ipv2,Pnow,Etoday,Eall,Fault Code\n") f.close() deviceId=1 Time=[] Vac1=0 Vac2=0 Vac3=0 Vpv1=0 Vpv2=0 Iac1=0 Iac2=0 Iac3=0 Ipv1=0 Ipv2=0 Pnow=0 Etoday=0 Eall=0 faultData=0 def __init__(self,instrument,root): Frame.__init__(self,root) self.menu=Menu(self) root.config(menu=self.menu) self.today=datetime.today().date() self.lastday=self.today self.optionMenu = Menu(self.menu) self.menu.add_cascade(label="Options", menu=self.optionMenu) self.optionMenu.add_command(label="Site Details",command=self.showSiteDetails) self.historyMenu=Menu(self.optionMenu) self.optionMenu.add_cascade(label="History",menu=self.historyMenu) self.historyMenu.add_command(label="Daily",command=self.dailyDataPlot) self.historyMenu.add_command(label="Monthly",command=self.monthlyDataResult) self.historyMenu.add_command(label="Yearly",command=self.yearlyDataResult) self.Xtick=np.arange(0,23*60,30) #self.Xtick=range(0,40) self.Xticklabels=[] for r in range(0,23): self.Xticklabels.append(str(r)+":"+"00") self.Xticklabels.append(str(r)+":"+"30") ######Edit axis limits for actual time, time.sleep(),yticks,xticks,xticklabels ###### ###### self.fig = Figure(figsize=(4,4), dpi=100) #f.add_axes([0,100,0,100]) #self.fig.autofmt_xdate(bottom=0.2, rotation=180, ha='right') self.fig.set_tight_layout(True) self.a = self.fig.add_subplot(111,xlabel="Time -->",ylabel="Pnow(KW)-->",xticks=self.Xtick,xticklabels=self.Xticklabels,yticks=range(0,1000,100)) ####Graph axis parameters self.a.axis([4*60,21*60,0,5000]) for label in self.a.get_xmajorticklabels(): label.set_rotation(70) label.set_horizontalalignment("right") #self.a.axhline(y=0) #self.a.axvline(x=0) self.a.spines['left'].set_smart_bounds(True) self.a.spines['bottom'].set_smart_bounds(True) self.canvas = FigureCanvasTkAgg(self.fig,master=self) self.canvas.draw() self.canvas.get_tk_widget().grid(row=3,column=0,columnspan=3,sticky="N")#.pack(side="right", fill="both", expand=True) ########### ########### ########### self.labelId=Label(self,text="Device Id : "+ str(self.deviceId),fg="black",bg="white") self.labelId.grid(padx=10,pady=5,ipadx=40,row=1,column=1,sticky="N") self.labelCap=Label(self,text=" INSTALLED CAPACITY 05 KW ",fg="black",bg="white") self.labelCap.grid(padx=10,pady=5,ipadx=10,row=2,column=1,sticky="W") self.labelDT=Label(self,text=" Date and Time : " + str(self.Time),fg="blue",bg="white") self.labelDT.grid(padx=10,pady=5,row=2,column=0,sticky="W") self.labelVac=Label(self,text=" Vac : "+ str(self.Vac1)+"V / "+str(self.Vac2)+"V / "+str(self.Vac3)+"V",fg="blue",bg="white") self.labelVac.grid(padx=10,pady=5,ipadx=20,row=5,column=0,sticky="W") self.labelVpv=Label(self,text=" Vpv : "+ str(self.Vpv1)+"V / "+str(self.Vpv2)+"V",fg="red",bg="white") self.labelVpv.grid(padx=10,pady=5,ipadx=20,row=6,column=0,sticky="W") self.labelIac=Label(self,text=" Iac : "+ str(self.Iac1)+"A / "+str(self.Iac2)+"A / "+str(self.Iac3)+"A",fg="green",bg="white") self.labelIac.grid(padx=10,pady=5,ipadx=20,row=7,column=0,sticky="W") self.labelIpv=Label(self,text=" Ipv : "+ str(self.Ipv1)+"A / "+str(self.Ipv2)+"A",fg="magenta",bg="white") self.labelIpv.grid(padx=10,pady=5,ipadx=20,row=8,column=0,sticky="W") self.labelPnow=Label(self,text=" Pnow : "+str(self.Pnow)+"kW",fg="yellow",bg="white") self.labelPnow.grid(padx=10,pady=5,ipadx=20,row=5,column=2,sticky="W") self.labelEtoday=Label(self,text=" Etoday : "+str(self.Etoday)+"kW",fg="brown",bg="white") self.labelEtoday.grid(padx=10,pady=5,ipadx=20,row=6,column=2,sticky="W") self.labelEall=Label(self,text=" Eall : "+str(self.Eall)+"kW",fg="purple",bg="white") self.labelEall.grid(padx=10,pady=5,ipadx=20,row=7,column=2,sticky="W") ######### ######### ######### def showSiteDetails(self): print "Site Details:" siteFile=open(self.filePath+"siteDetails.txt","r") info=siteFile.read() tp=Toplevel(self) Label(tp,text=info,fg="white",bg="black").pack(fill=X) def blank(self): print "oops!!!!!!!!!!!!!!!!!! blank" def dailyDataPlot(self): dateMax=31 def getAndPlot(): #path="/home/prashant/pythonGeneratedFiles/" m=int(mm.get()) d=int(dd.get()) fileName=yyyy.get() if m<10: fileName=fileName+"-0"+str(m)+"-" else: fileName=fileName+"-"+str(m)+"-" if d<10: fileName=fileName+"0"+str(d) else: fileName=fileName+str(d) print fileName fp=open(self.filePath+fileName+".csv","r") index=10 #First row specifies particular parameter name print fp.readline() Xdata=[] Ydata=[] xtick=[] splitedData=fp.readline().split(",") Ydata.append(int(splitedData[index])) time=datetime.strptime(splitedData[0],"%H:%M") startTime=time Xdata.append(time.hour*60+time.minute) xtick.append(str(startTime.hour)+":"+str(startTime.minute)) for row in fp: splitedData=row.split(",") Ydata.append(int(splitedData[index])) time=datetime.strptime(splitedData[0],"%H:%M") Xdata.append(time.hour*60+time.minute) if ((time.hour-startTime.hour)*60+(time.minute-startTime.minute))>29: startTime=time xtick.append(str(startTime.hour)+":"+str(startTime.minute)) Etoday=splitedData[11] runTime=time-datetime.strptime(xtick[0],"%H:%M") print runTime fig=plt.figure("Device Id:"+str(self.deviceId)+" Date:"+fileName) plt.scatter(Xdata,Ydata) temp= np.arange(min(Xdata), max(Xdata), 30) plt.xlabel("Time\nRun Time :"+str(runTime)+"\nEtoday = "+str(Etoday)+" KWh") plt.ylabel("Power") plt.tight_layout() plt.grid(True) plt.xticks(temp,xtick,rotate=70) plt.plot(Xdata,Ydata) plt.show() def updateMaxDate(): global dateMax y=int(yyyy.get()) m=int(mm.get()) if m == 1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: dateMax=31 elif m==2: if y%4==0: if y%400==0 and y%100!=0: dateMax=29 else: dateMax=28 else: dateMax=28 else: dateMax=30 dd.config(to=dateMax) win= Toplevel(self) Label(win,text="DD:").grid(row=2,column=1)#.pack(side="left")#.grid(row=2,column=2) dd = Spinbox(win, from_=1, to=dateMax, state="readonly",width=2) dd.grid(row=2,column=1)#.pack(side="left")#grid(row=2,column=1) Label(win,text="MM:").grid(row=2,column=2)#.pack(side="left")#.grid(row=2,column=2) mm = Spinbox(win, from_=1, to=12, state="readonly",command=updateMaxDate,width=2) mm.grid(row=2,column=2)#.pack(side="left")#.grid(row=2,column=2) Label(win,text="YYYY:").grid(row=2,column=3)#.pack(side="left")#.grid(row=2,column=3) yyyy = Spinbox(win, from_=2005, to=2050, state="readonly",command=updateMaxDate,width=5) yyyy.grid(row=2,column=3)#.pack(side="left")#.grid(row=2,column=3) button=Button(win,text=" PLOT ",command=getAndPlot) button.grid(row=3,column=2)#.pack(side="left")#.grid(row=3,column=2) #self.updateGUItasks() def createMonthlyDataFile(self): path="/home/prashant/pythonGeneratedFiles/" year="2015" powerIndex=10 for m in range(1,13): totalEnergy=0 temp=datetime(1900,1,1,0,0,0) duration=datetime(1900,1,1,0,0,0) peak=0 mFile=year if m<10: mFile=mFile+"-0"+str(m) else: mFile=mFile+"-"+str(m) fm=open(mFile+".csv","w") fm.write("Total energy,Peak,Duration\n") print "Creating Month :",m," File..............." if m == 1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: dateMax=31 elif m==2: dateMax=28 else: dateMax=30 for d in range(1,dateMax+1): fileName=year if m<10: fileName=fileName+"-0"+str(m)+"-" else: fileName=fileName+"-"+str(m)+"-" if d<10: fileName=fileName+"0"+str(d) else: fileName=fileName+str(d) if os.path.exists(path+fileName+".csv"): fp=open(path+fileName+".csv","r") print fp.readline().split(",") startTime=datetime.strptime(fp.readline().split(",")[0],"%H:%M") for fileData in fp: singleData=fileData.split(",") if int(singleData[powerIndex]) > peak: peak=singleData[powerIndex] endTime=datetime.strptime(singleData[0],"%H:%M") temp=endTime-startTime duration=duration + temp fp.close() totalEnergy=totalEnergy+int(singleData[11]) print "Month :"+ str(m)+"-"+year print "Total Energy=",totalEnergy print "Duration :",duration print "Peak :",peak fm.write(str(totalEnergy)) fm.write(",") fm.write(str(peak)) fm.write(",") fm.write(str(duration)) fm.close() def createYearlyDataFile(self): energy=0 peak=0 duration=datetime(1900,1,1,0,0,0) temp=datetime(1900,1,1,0,0,0) fname="2015"#str(datetime.today().year) fy=open(fname+".csv","w") fy.write("Total energy,Peak,Duration\n") for m in range(1,13):#int(datetime.today().month)+1): fname="2015" if m<10: fname=fname+"-0"+str(m) else: fname=fname+"-"+str(m) #print fname fm=open(fname+".csv","r") fm.readline() data=fm.readline().split(",") if int(data[1])>peak: peak=int(data[1]) energy=energy+int(data[0]) # temp= #print temp #print duration temp=datetime.strptime(data[2],"%Y-%m-%d %H:%M:%S")-datetime(1900,1,1,0,0,0) duration=duration + temp fy.write(str(energy)) fy.write(",") fy.write(str(peak)) fy.write(",") fy.write(str(duration)) fy.close() #### Add duration #### #### """ def updateYearlyData(self): #duration=datetime(1900,1,1,0,0,0) fname=str(datetime.today().year) if os.path.exists(self.filePath+fname+".csv"): fy=open(self.filePath+fname+".csv","r") fy.readline() data=fy.readline().split(",") fy.close() totalEnergy=int(data[0])+self.Etoday peak=int(data[1]) else: totalEnergy=0 peak=0 if m=int(datetime.today().month) if m<10: fname=fname+"-0"+str(m) else: fname=fname+"-"+str(m) fm=open(fname+".csv","r") fm.readline() data=fm.readline().split(",") if int(data[1])>peak: peak=int(data[1]) #duration=datetime.strptime(data[2],"%Y-%m-%d %H:%M:%S")#+duration fy=open(self.filePath+str(datetime.today().year)+".csv","w") fy.write("Total energy,Peak,Duration\n") fy.write(str(totalEnergy)) fy.write(",") fy.write(str(peak)) #fy.write(",") #fy.write(str(duration)) fy.close() """ def updateMonthlyData(self): y,m,d=self.lastday.split("-") if os.path.exists(self.filePath+y+"-"+m+".csv"): fm=open(self.filePath+y+"-"+m+".csv","r") print fm.readline() data=fm.readline().split(",") fm.close() totalEnergy=int(data[0])+self.Etoday peak=int(data[1]) mDur=datetime.strptime(data[2],"%Y-%m-%D %H:%M:%S") else: totalEnergy=self.Etoday peak=0 mDur=datetime(1900,1,1,0,0,0) print self.f.readline() startTime=datetime.strptime(self.f.readline().split(",")[0],"%H:%M") for p in self.f: splittedData=p.split(",") temp=int(splittedData[10]) if peak<temp: peak=temp duration=datetime.strptime(splittedData[0],"%H:%M")-startTime totDur=mDur+duration fm=open(self.filePath+y+"-"+m+".csv","w") fm.write("Total energy,Peak,Duration\n") fm.write(str(totalEnergy)) fm.write(",") fm.write(str(peak)) fm.write(",") fm.write(str(totDur)) fm.close() def yearlyDataResult(self): monthList=[31,59,90,120,151,181,212,243,273,304,334,365] fileName="2015" filePath=self.filePath+fileName+".csv" readFile=open(filePath,"r") readFile.readline() data=readFile.readline().split(",") Eyear=data[0] peak=data[1] duration=datetime.strptime(data[2],"%Y-%m-%d %H:%M:%S") tp=Toplevel(self) tp.title("Year : 2015") Label(tp,text="Total Energy used = "+Eyear+" W\nPeak Power used in Year = "+peak+" W\n Total duration energy generated = "+str(monthList[duration.month-1]*24+duration.hour+duration.day*24)+" hours "+str(duration.minute)+" minutes",bg="white",fg="blue").pack(side="top",fill=X) def monthlyDataResult(self): def findEnergyUsed(): m=month.get() if int(m)<10: strM="0"+str(m) else: strM=str(m) fileName="2015-"+strM filePath=self.filePath+fileName+".csv" readFile=open(filePath,"r") readFile.readline() data=readFile.readline().split(",") Emonth=data[0] peak=data[1] duration=datetime.strptime(data[2],"%Y-%m-%d %H:%M:%S") #tp=Toplevel(self) #tp.title("Year : 2015") Label(win,text="Total Energy used = "+Emonth+" W\nPeak Power in Month = "+peak+" W\n Duration energy generated = "+str(int(duration.hour)+int(duration.day)*24)+" hours "+str(duration.minute)+" minutes",bg="white",fg="blue").grid(column=0,row=2,columnspan=2,sticky="N") win= Toplevel(self) win.title("Year : 2015") Label(win,text="Select Month:",bg="white").grid(row=0,column=0,sticky="W") month=Spinbox(win, from_=1, to=12, state="readonly",width=2,bg="white") month.grid(row=0,column=1,sticky="E") button=Button(win,text=" DONE ",command=findEnergyUsed) button.grid(row=1,column=0,sticky="E") def fetchBasicData(self,data): self.faultData=data[faultCodeAddr] self.Vac1=data[Vac1Addr]/10 self.Vac2=data[Vac2Addr]/10 self.Vac3=data[Vac3Addr]/10 self.Vpv1=data[Vpv1Addr]/10 self.Vpv2=data[Vpv2Addr]/10 self.Iac1=data[Iac1Addr]/10 self.Iac2=data[Iac2Addr]/10 self.Iac3=data[Iac3Addr]/10 self.Ipv1=(data[Ipv1AddrL]+data[Ipv1AddrH]*65535)/10 self.Ipv2=(data[Ipv2AddrL]+data[Ipv2AddrH]*65535)/10 self.Pnow=(data[PnowAddrL]+data[PnowAddrH]*65535)/10 self.Etoday=(data[EtodayAddrL]+data[EtodayAddrH]*65535)/10 self.Eall=(data[EallAddrL]+data[EallAddrH]*65535)/10 self.Time=str(datetime.today().hour)+":"+str(datetime.today().minute) def guiUpdate(self): self.labelDT.config(text=" Date and Time : " + str(self.Time)) self.labelVac.config(text=" Vac : "+ str(self.Vac1)+" V / "+str(self.Vac2)+" V / "+str(self.Vac3)+" V") self.labelVpv.config(text=" Vpv : "+ str(self.Vpv1)+" V / "+str(self.Vpv2)+" V") self.labelIac.config(text=" Iac : "+ str(self.Iac1)+" A / "+str(self.Iac2)+" A / "+str(self.Iac3)+" A") self.labelIpv.config(text=" Ipv : "+ str(self.Ipv1)+" A / "+str(self.Ipv2)+" A") self.labelPnow.config(text=" Pnow : "+str(self.Pnow)+" W") self.labelEtoday.config(text=" Etoday : "+str(self.Etoday)+" KWh") self.labelEall.config(text=" Eall : "+str(self.Eall)+" KWh") self.update_idletasks() self.update() def makeCSVfile(self): self.today = str(datetime.today().date()) if(str(self.today)==str(self.lastday)): self.f=open(self.filePath+str(self.today)+".csv","a") self.f.write(str(self.Time)+","+str(self.Vac1)+","+str(self.Vac2)+","+str(self.Vac3)+","+str(self.Vpv1)+","+str(self.Vpv2)+","+str(self.Iac1)+","+str(self.Iac2)+","+str(self.Iac3)+","+str(self.Ipv1)+","+str(self.Ipv2)+",") self.f.write(str(self.Pnow)+","+str(self.Etoday)+","+str(self.Eall)+",") self.f.write(str(self.faultData)) self.f.write("\n") self.f.close() else: self.f.close() self.f=open(self.filePath+str(self.lastday)+".csv","r") self.updateMonthlyData() self.f.close() #self.updateYearlyData() self.f=open(self.filePath+str(self.today)+".csv","a") self.f.write("Time,Vac1,Vac2,Vac3,Vpv1,Vpv2,Iac1,Iac2,Iac3,Ipv1,Ipv2,Pnow,Etoday,Eall,Fault Code\n") self.lastday=self.today def updateGUItasks(self): self.update_idletasks() self.update() def plotDataLive1(self,xdata,ydata): i=0 xtick=[] for j in range(7,20): xtick.append(str(j)+":"+"00") xtick.append(str(j)+":"+"30") xtickBand=np.arange(420,20*60+30,30) print xtick plt.axis([420,20*60+30,0,65535]) plt.xticks(xtickBand,xtick) plt.grid(True) plt.tight_layout() plt.ion() y=[] x=[] while i<600: y.append() plt.pause(0.05) plt.plot(x,y) #plt.show() #plt.draw() i=i+1 #plt.show() plt.ioff() plt.show() def mainFunction(self,startingAddr,totalRegisters,registerType): def animate(): #xList.append(count) #yList.append(self.Pnow) #### Live graph............... #### xList.append(int(datetime.today().second)) #xList.append(int(self.Time.split(":")[0])*60+int(self.Time.split(":")[1])-420) yList.append(int(self.Pnow)/10000000) self.a.scatter(xList,yList) self.a.plot(xList,yList) self.fig.canvas.draw() #self.createMonthlyDataFile() #self.createYearlyDataFile() ############################################################### Main loop count=0 xList=[] yList=[] while True:#count<40: dataArray=[] print " count = " + str(count) +"\n" reg=startingAddr while reg<totalRegisters+startingAddr: try: dataReceived = instrument.read_register(reg,0,registerType) dataArray.append(dataReceived) reg=reg+1 self.updateGUItasks() except ValueError,TypeError: reg=reg+1 dataArray.append(-1) except IOError: #print "no response" while True: try: print "no response" instrument.read_registers(0,1,4) except IOError: continue except ValueError,TypeError: print "", break
class MyMplCanvas(FigureCanvas): """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" def __init__(self, parent=None, subplotNb=1, width=5, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) super(MyMplCanvas, self).__init__(self.fig) self.yAxe = numpy.array([0]) self.xAxe = numpy.array([0]) self.axes = [] if subplotNb == 1: self.axes.append(self.fig.add_subplot(111)) elif subplotNb == 2: self.axes.append(self.fig.add_subplot(211)) self.axes.append(self.fig.add_subplot(212)) elif subplotNb == 3: self.axes.append(self.fig.add_subplot(221)) self.axes.append(self.fig.add_subplot(222)) self.axes.append(self.fig.add_subplot(223)) elif subplotNb == 4: self.axes.append(self.fig.add_subplot(221)) self.axes.append(self.fig.add_subplot(222)) self.axes.append(self.fig.add_subplot(223)) self.axes.append(self.fig.add_subplot(224)) #self.axes.autoscale(False) # We want the axes cleared every time plot() is called #self.axes.hold(False) self.compute_initial_figure() # FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass def update_figure(self, name, data, nb_probes, lstProbes): self.xAxe = data[0].tolist() for j in range(nb_probes - 1): if (lstProbes[j].status == "on"): self.yAxe = data[j + 1].tolist() lbl = name + "_s" + str(j) self.axes[lstProbes[j].subplot_id - 1].plot(self.xAxe, self.yAxe, label=lbl) self.axes[lstProbes[j].subplot_id - 1].legend( loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0.0, ncol=1, fancybox=True, shadow=True, prop={ 'size': 'medium', 'style': 'italic' }) def update_figure_listing(self, name, data, nb_probes, lstProbes): self.xAxe = data[0].tolist() for j in range(nb_probes - 1): if (lstProbes[j].status == "on"): self.yAxe = data[j + 1].tolist() lbl = "t res. " + name[j] self.axes[lstProbes[j].subplot_id - 1].plot(self.xAxe, self.yAxe, label=lbl) self.axes[lstProbes[j].subplot_id - 1].legend( loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0.0, ncol=1, fancybox=True, shadow=True, prop={ 'size': 'medium', 'style': 'italic' }) def drawFigure(self): for it in range(len(self.axes)): self.axes[it].grid(True) self.axes[it].set_xlabel("time (s)") self.axes[0].set_yscale('log') self.fig.canvas.draw() def clear(self): for plt in range(len(self.axes)): self.axes[plt].clear() def setSubplotNumber(self, subplotNb): self.fig.clear() for it in range(len(self.axes)): self.axes.remove(self.axes[0]) if subplotNb == 1: self.axes.append(self.fig.add_subplot(111)) elif subplotNb == 2: self.axes.append(self.fig.add_subplot(211)) self.axes.append(self.fig.add_subplot(212)) elif subplotNb == 3: self.axes.append(self.fig.add_subplot(221)) self.axes.append(self.fig.add_subplot(222)) self.axes.append(self.fig.add_subplot(223)) elif subplotNb == 4: self.axes.append(self.fig.add_subplot(221)) self.axes.append(self.fig.add_subplot(222)) self.axes.append(self.fig.add_subplot(223)) self.axes.append(self.fig.add_subplot(224))
class WingEditor(tk.Tk): def __init__(self, *args, **kwargs): # Backend Initialization self.wing = Wing() self.wing.set_span_discretization(np.linspace(0, 10, 21)) self.wing.set_chord(lambda y: 6 - 5.5 * y / self.wing.b) self.wing.set_twist(0) self.wing.set_airfoil('e1213') self.wing.set_dihedral(6) self.wing.set_sweep(lambda y: 45 if y < 4 else 40 if 4 <= y < 6 else 50) self.wing.construct() # Setting up Frontend super().__init__(*args, **kwargs) tk.Tk.wm_title(self, "WingGeo Editor") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=10) self.grid_columnconfigure(1, weight=10) self.grid_columnconfigure(2, weight=2) # Menu Bar Creation self.menubar = tk.Menu(self) self.config(menu=self.menubar) # File Menu fileMenu = tk.Menu(self.menubar) fileMenu.config(tearoff=False) fileMenu.add_command(label="New", command=lambda: None) fileMenu.add_command(label="Save", command=lambda: self.__save()) fileMenu.add_command(label="Load", command=lambda: self.__load()) fileMenu.add_command(label="Import", command=lambda: self.__import()) fileMenu.add_command(label="Export", command=lambda: self.__export()) fileMenu.add_command(label="Exit", command=lambda: self.__exit()) self.menubar.add_cascade(label="File", menu=fileMenu) # Edit Menu editMenu = tk.Menu(self.menubar) editMenu.config(tearoff=False) editMenu.add_command(label="Design Wing", command=lambda: self.__design()) editMenu.add_command(label="Configuration", command=lambda: self.__configure()) editMenu.add_command(label="Clear Plots", command=lambda: self.__clear_plots()) editMenu.add_command(label="Update Plots", command=lambda: self.__plot()) self.menubar.add_cascade(label="Edit", menu=editMenu) # Editing Windows self.design_window = DesignWindow(self) self.config_window = ConfigurationWindow(self) self.design_window.iconify() self.config_window.iconify() # 3D Plot self.plot3d_container = tk.Frame(self) self.plot3d_container.grid_columnconfigure(0, weight=1) self.plot3d_container.grid_rowconfigure(0, weight=1) self.plot3d_container.grid(row=0, column=0, sticky='NSEW') self.fig_3d = Figure(figsize=(5, 5), dpi=100) canvas3d = FigureCanvasTkAgg(self.fig_3d, self.plot3d_container) canvas3d.draw() self.plot3d = self.fig_3d.add_subplot(111, projection="3d") toolbar = NavigationToolbar2Tk(canvas3d, self.plot3d_container) toolbar.update() canvas3d._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) canvas3d.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) # 2D Plot Creation self.plot2d_container = tk.Frame(self) self.plot2d_container.grid_columnconfigure(0, weight=10) self.plot2d_container.grid_columnconfigure(1, weight=1) self.plot2d_container.grid_rowconfigure(0, weight=1) self.plot2d_container.grid(row=0, column=1, sticky='NSEW') self.fig_2d = Figure(figsize=(5, 5), dpi=100) canvas2d = FigureCanvasTkAgg(self.fig_2d, self.plot2d_container) canvas2d.draw() self.plots2d = {} self.top_plot2d = self.fig_2d.add_subplot(311) self.front_plot2d = self.fig_2d.add_subplot(312, sharex=self.top_plot2d) self.side_plot2d = self.fig_2d.add_subplot(313) self.plots2d['topdown'] = self.top_plot2d self.plots2d['front'] = self.front_plot2d self.plots2d['side'] = self.side_plot2d for key, plot in self.plots2d.items(): plot.grid() plot.autoscale(False) toolbar = NavigationToolbar2Tk(canvas2d, self.plot2d_container) toolbar.update() canvas2d._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) # Slider self.button_frame = tk.Frame(self) nrows = 3 for row in range(nrows): self.button_frame.grid_rowconfigure(row, weight=1) self.button_frame.grid_columnconfigure(0, weight=1) self.button_frame.grid(row=0, column=2, sticky='NSEW') self.span_slider = ttkw.TickScale(self.button_frame, from_=0, to=10, tickinterval=0.5, orient=tk.VERTICAL # resolution=0.2 ) self.span_slider.grid(row=2, column=1, sticky='NSEW') self.display = tk.Label(self.button_frame, text=str(round(self.span_slider.get(), 4))) self.display.grid(row=1, column=0, sticky='SE') self.parameter_label_texts = [ 'Span', 'Airfoil Steps', 'Span Distr.', 'Airfoils', 'Chord', 'Sweep', 'Twist', 'Dihedral', ] # Finally self.__plot() self.animation_3d = animation.FuncAnimation(self.fig_3d, lambda _: self.__plot_3d(), interval=1000) self.animation_2d = animation.FuncAnimation(self.fig_2d, lambda _: self.__plot_2d(), interval=300) width, height = self.winfo_screenwidth(), self.winfo_screenheight() self.geometry('%dx%d+0+0' % (width, height - 100)) self.bind('<Escape>', lambda e: self.__exit()) def __clear_plots(self): self.wing = Wing() self.plot3d.clear() for plot in self.plots2d.values(): plot.clear() plot.grid(True) def __design(self): self.design_window.deiconify() def __configure(self): self.config_window.deiconify() def __export(self): pass def __import(self): pass def __save(self): pass def __load(self): pass def __exit(self): confirmation = tk.Toplevel(self) confirmation.grid_rowconfigure(0, weight=1) confirmation.grid_rowconfigure(1, weight=1) confirmation.grid_columnconfigure(0, weight=1) txt = tk.Label(confirmation, text="Are you sure?") txt.grid(row=0, column=0, sticky='NSEW') btnframe = tk.Frame(confirmation) btnframe.grid(row=1, column=0, sticky='NSEW') yesbtn = ttk.Button(btnframe, text="Yes", command=lambda: self.destroy()) nobtn = ttk.Button(btnframe, text="No", command=lambda: confirmation.destroy()) yesbtn.grid(row=0, column=0, sticky='NSEW') nobtn.grid(row=0, column=1, sticky='NSEW') def __find_closest(self, yi, keys): i = 0 mindiff = float('inf') while True: if yi >= self.wing.get_span(): return keys[-1] try: diff = abs(yi - keys[i]) except IndexError: return keys[-1] if diff < mindiff: mindiff = float(diff) i += 1 continue return keys[i] def project_in_2d(self, array, dictionary, yi=None): topdown_coordinates = array[(1, 0), :] front_coordinates = array[(1, 2), :] side_coordinates = [[], []] try: side_coordinates[0] = list(dictionary[yi]['x']) side_coordinates[1] = list(dictionary[yi]['z']) except KeyError: data = dictionary[self.__find_closest(yi, list(dictionary.keys()))] side_coordinates[0] = list(data['x']) side_coordinates[1] = list(reversed(data['z'])) return { 'topdown': topdown_coordinates, 'front': front_coordinates, 'side': np.array(side_coordinates) } def __plot_3d(self): if self.plot3d.collections: xlim, ylim = self.plot3d.get_xlim(), self.plot3d.get_ylim() self.plot3d.clear() self.plot3d.set_xlim(*xlim) self.plot3d.set_ylim(*ylim) else: self.plot3d.clear() arr = self.wing.data_container.get_array() dictionary = self.wing.data_container.get_dictionary() if arr is not None and arr.size > 0: self.projections = self.project_in_2d(arr, dictionary, yi=self.span_slider.get()) self.plot3d.scatter(arr[0, :], arr[1, :], arr[2, :], c='r', marker='o') else: self.projections = None self.wing.axisEqual3D(self.plot3d) self.plot3d.set_xlabel('X [m]') self.plot3d.set_ylabel('Y [m]') self.plot3d.set_zlabel('Z [m]') def __plot_2d(self): for key, plot in self.plots2d.items(): if plot.lines: xlim, ylim = plot.get_xlim(), plot.get_ylim() plot.clear() plot.set_xlim(*xlim) plot.set_ylim(*ylim) else: plot.axis('equal') plot.grid(True) if key == 'side': plot.set_xlabel('X [m]') plot.set_ylabel('Z [m]') else: plot.set_xlabel('Y [m]') if key == 'front': plot.set_ylabel('Z [m]') else: plot.set_ylabel('X [m]') self.display.config(text=str(round(self.span_slider.get(), 4)) + ' [m]') if self.projections is not None: self.plots2d['topdown'].plot(self.projections['topdown'][0, :], self.projections['topdown'][1, :], 'ro') self.plots2d['front'].plot(self.projections['front'][0, :], self.projections['front'][1, :], 'ro') self.plots2d['side'].plot(self.projections['side'][0, :], self.projections['side'][1, :], 'ro') def __plot(self): self.__plot_3d() self.__plot_2d() self.update()
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)
class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Indoor Air Assistant', size=(800, 600)) panel = wx.Panel(self) self.backgroundcolour = '#F5F5F5' #whitesmoke panel.SetBackgroundColour(self.backgroundcolour) self.paneldraw = wx.Panel(panel, wx.ID_ANY, style=wx.NO_BORDER, pos=(200, 340), size=wx.Size(560, 190)) self.paneldraw.SetBackgroundColour(self.backgroundcolour) self.paneldraw.Show(False) self.panellogo = wx.Panel(panel, wx.ID_ANY, style=wx.NO_BORDER, pos=(500, 8), size=wx.Size(283, 54)) self.SetMaxSize((800, 600)) #fix the frame size self.SetMinSize((800, 600)) #fix the frame size self.statusbar = self.CreateStatusBar() self.statusbar.SetStatusText('Welcome to Indoor Air Assistant...') #information self.info = wx.StaticText( panel, -1, 'Version: 1.1.0.20170310_release\nReleased by Air Lab in NJU\nAll rights reserved by author', (10, 490)) self.info.SetForegroundColour('grey') ifont = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL) self.info.SetFont(ifont) #show logo image image = wx.Image("newlogo.jpg", wx.BITMAP_TYPE_JPEG) logo = wx.StaticBitmap(self.panellogo, -1, wx.BitmapFromImage(image)) #your city citylabel1 = wx.StaticText(panel, -1, 'Your City:', (20, 15)) try: ip = IPToLocation() cityname = ip.city().decode('utf-8') self.city = wx.StaticText(panel, -1, cityname, (50, 40), (80, -1)) self.statusbar.SetStatusText('Welcome to Indoor Air Assistant...') except: self.city = wx.StaticText(panel, -1, 'Offline', (50, 40), (80, -1)) self.statusbar.SetStatusText( 'You are offline! Please check your internet connection...') #outdoor ozone self.outppb = wx.SpinCtrl(panel, -1, 'Outdoor Ozone', (30, 100), (80, -1)) self.outppb.SetRange(0, 10000) outppblabel1 = wx.StaticText(panel, -1, 'Outdoor Ozone:', (20, 75)) outppblabel2 = wx.StaticText(panel, -1, 'ppb', (115, 100)) self.outppb.Bind(wx.EVT_TEXT, self.OutPpb) try: webozone = GetAQI(cityname) webozone = int(webozone.ozone()) self.outppb.SetValue(webozone) self.statusbar.SetStatusText('Welcome to Indoor Air Assistant...') except: self.outppb.SetValue(100) self.statusbar.SetStatusText( 'You are offline! Please check your internet connection...') #air change rate self.ach = wx.Slider(panel, -1, 5, 0, 50, (20, 160), (90, -1), style=wx.SL_HORIZONTAL | wx.SL_TOP) self.ach.Bind(wx.EVT_SCROLL, self.ACHScroll) self.achvalue = wx.TextCtrl(panel, -1, str(self.ach.GetValue() / 10.0), (110, 160), (35, -1)) self.achvalue.Bind(wx.EVT_TEXT, self.ACHText) self.achlabel1 = wx.StaticText(panel, -1, 'Air Change Per Hour:', (20, 135)) self.achlabel2 = wx.StaticText(panel, -1, '/h', (150, 160)) #indoor source self.indoorsource = wx.TextCtrl(panel, -1, '0', (30, 220), (80, -1)) self.indoorsource.Bind(wx.EVT_TEXT, self.IndoorSourceText) indoorsourcelabel1 = wx.StaticText(panel, -1, 'Indoor Source:', (20, 195)) indoorsourcelabel2 = wx.StaticText(panel, -1, 'mg/h', (115, 220)) #disinfection self.disinfection = wx.CheckBox(panel, -1, 'Disinfection', pos=(20, 255), size=(100, -1)) self.disinfection.Bind(wx.EVT_CHECKBOX, self.Disinfection) self.disinfectionlabel = wx.StaticText(panel, -1, 'Disinfection Settings', (20, 290)) self.disinfectionlabel.SetForegroundColour('red') dfont = wx.Font(11, wx.ROMAN, wx.NORMAL, wx.BOLD) self.disinfectionlabel.SetFont(dfont) self.disinfectionlabel.Enable(False) #disinfection time self.dtime = wx.SpinCtrl(panel, -1, 'Disinfection Time', (30, 340), (80, -1)) self.dtime.SetRange(0, 300) self.dtime.SetValue(30) self.dtimelabel1 = wx.StaticText(panel, -1, 'Disinfection Time:', (20, 315)) self.dtimelabel2 = wx.StaticText(panel, -1, 'min', (115, 340)) self.dtime.Bind(wx.EVT_TEXT, self.DTime) self.dtime.Enable(False) self.dtimelabel1.Enable(False) self.dtimelabel2.Enable(False) #ach during disinfection self.achd1 = wx.Slider(panel, -1, 5, 0, 50, (20, 400), (90, -1), style=wx.SL_HORIZONTAL | wx.SL_TOP) self.achd1.Bind(wx.EVT_SCROLL, self.ACHD1Scroll) self.achvalued1 = wx.TextCtrl(panel, -1, str(self.ach.GetValue() / 10.0), (110, 400), (35, -1)) self.achvalued1.Bind(wx.EVT_TEXT, self.ACHD1Text) self.achd1label1 = wx.StaticText(panel, -1, 'ACH During Disinfection:', (20, 375)) self.achd1label2 = wx.StaticText(panel, -1, '/h', (150, 400)) self.achd1.Enable(False) self.achvalued1.Enable(False) self.achd1label1.Enable(False) self.achd1label2.Enable(False) #ach after disinfection self.achd2 = wx.Slider(panel, -1, 5, 0, 50, (20, 460), (90, -1), style=wx.SL_HORIZONTAL | wx.SL_TOP) self.achd2.Bind(wx.EVT_SCROLL, self.ACHD2Scroll) self.achvalued2 = wx.TextCtrl(panel, -1, str(self.ach.GetValue() / 10.0), (110, 460), (35, -1)) self.achvalued2.Bind(wx.EVT_TEXT, self.ACHD2Text) self.achd2label1 = wx.StaticText(panel, -1, 'ACH After Disinfection:', (20, 435)) self.achd2label2 = wx.StaticText(panel, -1, '/h', (150, 460)) self.achd2.Enable(False) self.achvalued2.Enable(False) self.achd2label1.Enable(False) self.achd2label2.Enable(False) #room volume self.volume = wx.TextCtrl(panel, -1, '45', (200, 40), (80, -1)) self.volume.Bind(wx.EVT_TEXT, self.VolumeText) volumelabel1 = wx.StaticText(panel, -1, 'Room Volume:', (190, 15)) volumelabel2 = wx.StaticText(panel, -1, 'm3', (285, 40)) #material 1 materiallist = list(material.keys()) self.material1 = wx.Choice(panel, -1, pos=(200, 100), size=(180, -1), choices=materiallist) self.material1.SetSelection(13) self.area1 = wx.TextCtrl(panel, -1, '15', (390, 100), (40, -1)) materiallabel1 = wx.StaticText(panel, -1, 'Floor:', (190, 75)) arealabel1 = wx.StaticText(panel, -1, 'm2', (435, 100)) self.material1.Bind(wx.EVT_CHOICE, self.ChooseMaterial1) self.area1.Bind(wx.EVT_TEXT, self.AreaText1) #material 2 self.material2 = wx.Choice(panel, -1, pos=(200, 160), size=(180, -1), choices=materiallist) self.material2.SetSelection(21) self.area2 = wx.TextCtrl(panel, -1, '15', (390, 160), (40, -1)) materiallabel2 = wx.StaticText(panel, -1, 'Ceiling:', (190, 135)) arealabel2 = wx.StaticText(panel, -1, 'm2', (435, 160)) self.material2.Bind(wx.EVT_CHOICE, self.ChooseMaterial2) self.area2.Bind(wx.EVT_TEXT, self.AreaText2) #material 3 self.material3 = wx.Choice(panel, -1, pos=(200, 220), size=(180, -1), choices=materiallist) self.material3.SetSelection(19) self.area3 = wx.TextCtrl(panel, -1, '30', (390, 220), (40, -1)) materiallabel3 = wx.StaticText(panel, -1, 'Wall1:', (190, 195)) arealabel3 = wx.StaticText(panel, -1, 'm2', (435, 220)) self.material3.Bind(wx.EVT_CHOICE, self.ChooseMaterial3) self.area3.Bind(wx.EVT_TEXT, self.AreaText3) #material 4 self.material4 = wx.Choice(panel, -1, pos=(200, 280), size=(180, -1), choices=materiallist) self.material4.SetSelection(21) self.area4 = wx.TextCtrl(panel, -1, '18', (390, 280), (40, -1)) materiallabel4 = wx.StaticText(panel, -1, 'Wall2:', (190, 255)) arealabel4 = wx.StaticText(panel, -1, 'm2', (435, 280)) self.material4.Bind(wx.EVT_CHOICE, self.ChooseMaterial4) self.area4.Bind(wx.EVT_TEXT, self.AreaText4) #material 5 self.material5 = wx.Choice(panel, -1, pos=(500, 100), size=(180, -1), choices=materiallist) self.material5.SetSelection(39) self.area5 = wx.TextCtrl(panel, -1, '15', (690, 100), (40, -1)) materiallabel5 = wx.StaticText(panel, -1, 'Surface:', (490, 75)) arealabel5 = wx.StaticText(panel, -1, 'm2', (735, 100)) self.material5.Bind(wx.EVT_CHOICE, self.ChooseMaterial5) self.area5.Bind(wx.EVT_TEXT, self.AreaText5) #material 6 self.material6 = wx.Choice(panel, -1, pos=(500, 160), size=(180, -1), choices=materiallist) self.material6.SetSelection(45) self.area6 = wx.TextCtrl(panel, -1, '10', (690, 160), (40, -1)) materiallabel6 = wx.StaticText(panel, -1, 'Surface:', (490, 135)) arealabel6 = wx.StaticText(panel, -1, 'm2', (735, 160)) self.material6.Bind(wx.EVT_CHOICE, self.ChooseMaterial6) self.area6.Bind(wx.EVT_TEXT, self.AreaText6) #material 7 self.material7 = wx.Choice(panel, -1, pos=(500, 220), size=(180, -1), choices=materiallist) self.material7.SetSelection(0) self.area7 = wx.TextCtrl(panel, -1, '0', (690, 220), (40, -1)) materiallabel7 = wx.StaticText(panel, -1, 'Surface:', (490, 195)) arealabel7 = wx.StaticText(panel, -1, 'm2', (735, 220)) self.material7.Bind(wx.EVT_CHOICE, self.ChooseMaterial7) self.area7.Bind(wx.EVT_TEXT, self.AreaText7) #material 8 self.material8 = wx.Choice(panel, -1, pos=(500, 280), size=(180, -1), choices=materiallist) self.material8.SetSelection(0) self.area8 = wx.TextCtrl(panel, -1, '0', (690, 280), (40, -1)) materiallabel8 = wx.StaticText(panel, -1, 'Surface:', (490, 255)) arealabel8 = wx.StaticText(panel, -1, 'm2', (735, 280)) self.material8.Bind(wx.EVT_CHOICE, self.ChooseMaterial8) self.area8.Bind(wx.EVT_TEXT, self.AreaText8) #show inppb result self.inppb = wx.StaticText(panel, -1, 'Ozone', pos=(350, 410), size=(200, -1), style=wx.ALIGN_RIGHT) self.inppb.SetForegroundColour('blue') font = wx.Font(30, wx.ROMAN, wx.NORMAL, wx.BOLD) self.inppb.SetFont(font) inppblabel = wx.StaticText(panel, -1, 'Indoor Ozone: ', (190, 315)) #draw disinfection ppb curve def DrawPpb(self): inppbresults = [] ta = 5 * self.dtime.GetValue() for t in xrange(ta + 1): inppbresults.append( eqdynamic( float(self.outppb.GetValue()), self.achd1.GetValue() / 10.0, self.achd2.GetValue() / 10.0, float(self.volume.GetValue()), float(self.indoorsource.GetValue()), getsumvda( material.get(self.material1.GetStringSelection()), float(self.area1.GetValue()), material.get(self.material2.GetStringSelection()), float(self.area2.GetValue()), material.get(self.material3.GetStringSelection()), float(self.area3.GetValue()), material.get(self.material4.GetStringSelection()), float(self.area4.GetValue()), material.get(self.material5.GetStringSelection()), float(self.area5.GetValue()), material.get(self.material6.GetStringSelection()), float(self.area6.GetValue()), material.get(self.material7.GetStringSelection()), float(self.area7.GetValue()), material.get(self.material8.GetStringSelection()), float(self.area8.GetValue()), getvt(self.ach.GetValue() / 10.0)), t / 60., self.dtime.GetValue() / 60.)) t_score = numpy.arange(0, ta + 1, 1) s_score = numpy.array(inppbresults) self.figure_score = Figure() self.figure_score.set_facecolor(self.backgroundcolour) self.figure_score.set_figheight(2.4) self.figure_score.set_figwidth(7.2) self.axes_score = self.figure_score.add_subplot( 111 ) #seperate the window into 1*1 matrix (subwindows), occupied the 1st subwindow self.axes_score.plot(t_score, s_score, 'b') self.axes_score.axhline(y=140, color='r') #self.axes_score.set_title('Indoor Ozone') self.axes_score.grid(True) self.axes_score.set_xlabel('Time (min)') self.axes_score.set_ylabel('Indoor Ozone (ppb)') FigureCanvas(self.paneldraw, -1, self.figure_score) #show indoor ppb result def ShowPpb(self): return self.inppb.SetLabel( str( eqsteady( float(self.outppb.GetValue()), self.ach.GetValue() / 10.0, float(self.volume.GetValue()), float(self.indoorsource.GetValue()), getsumvda( material.get(self.material1.GetStringSelection()), float(self.area1.GetValue()), material.get(self.material2.GetStringSelection()), float(self.area2.GetValue()), material.get(self.material3.GetStringSelection()), float(self.area3.GetValue()), material.get(self.material4.GetStringSelection()), float(self.area4.GetValue()), material.get(self.material5.GetStringSelection()), float(self.area5.GetValue()), material.get(self.material6.GetStringSelection()), float(self.area6.GetValue()), material.get(self.material7.GetStringSelection()), float(self.area7.GetValue()), material.get(self.material8.GetStringSelection()), float(self.area8.GetValue()), getvt(self.ach.GetValue() / 10.0)))) + ' ppb') def OutPpb(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def ACHScroll(self, event): self.achvalue.SetValue(str(self.ach.GetValue() / 10.0)) self.ShowPpb() self.statusbar.SetStatusText('') def ACHText(self, event): try: if float(self.achvalue.GetValue()) > 20.0: self.ach.SetValue(200) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') elif float(self.achvalue.GetValue()) < 0.0: self.ach.SetValue(0) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') else: self.ach.SetValue(int(float(self.achvalue.GetValue()) * 10)) self.statusbar.SetStatusText('') self.ShowPpb() except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number from 0 to 5...') def ACHD1Scroll(self, event): self.achvalued1.SetValue(str(self.achd1.GetValue() / 10.0)) self.DrawPpb() self.statusbar.SetStatusText('') def ACHD1Text(self, event): try: if float(self.achvalued1.GetValue()) > 20.0: self.achd1.SetValue(200) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') elif float(self.achvalued1.GetValue()) < 0.0: self.achd1.SetValue(0) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') else: self.achd1.SetValue(int( float(self.achvalued1.GetValue()) * 10)) self.statusbar.SetStatusText('') self.DrawPpb() except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number from 0 to 5...') def ACHD2Scroll(self, event): self.achvalued2.SetValue(str(self.achd2.GetValue() / 10.0)) self.DrawPpb() self.statusbar.SetStatusText('') def ACHD2Text(self, event): try: if float(self.achvalued2.GetValue()) > 20.0: self.achd2.SetValue(200) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') elif float(self.achvalued2.GetValue()) < 0.0: self.achd2.SetValue(0) self.statusbar.SetStatusText( 'RangeError! Air change rate ranges from 0 to 5...') else: self.achd2.SetValue(int( float(self.achvalued2.GetValue()) * 10)) self.statusbar.SetStatusText('') self.DrawPpb() except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number from 0 to 20...') def IndoorSourceText(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def DTime(self, event): self.DrawPpb() self.statusbar.SetStatusText('') def VolumeText(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial1(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText1(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial2(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText2(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial3(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText3(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial4(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText4(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial5(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText5(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial6(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText6(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial7(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText7(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def ChooseMaterial8(self, event): if self.disinfection.IsChecked(): self.DrawPpb() else: self.ShowPpb() self.statusbar.SetStatusText('') def AreaText8(self, event): if self.disinfection.IsChecked(): try: self.DrawPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') else: try: self.ShowPpb() self.statusbar.SetStatusText('') except ValueError: self.statusbar.SetStatusText( 'ValueError! Please input a number...') def Disinfection(self, event): if self.disinfection.IsChecked(): self.dtime.Enable(True) self.achd1.Enable(True) self.achvalued1.Enable(True) self.achd2.Enable(True) self.achvalued2.Enable(True) self.achd1label1.Enable(True) self.achd1label2.Enable(True) self.achd2label1.Enable(True) self.achd2label2.Enable(True) self.dtimelabel1.Enable(True) self.dtimelabel2.Enable(True) self.disinfectionlabel.Enable(True) self.paneldraw.Show(True) self.ach.Enable(False) self.achvalue.Enable(False) self.achlabel1.Enable(False) self.achlabel2.Enable(False) self.inppb.Show(False) else: self.dtime.Enable(False) self.achd1.Enable(False) self.achvalued1.Enable(False) self.achd2.Enable(False) self.achvalued2.Enable(False) self.achd1label1.Enable(False) self.achd1label2.Enable(False) self.achd2label1.Enable(False) self.achd2label2.Enable(False) self.dtimelabel1.Enable(False) self.dtimelabel2.Enable(False) self.disinfectionlabel.Enable(False) self.paneldraw.Show(False) self.ach.Enable(True) self.achvalue.Enable(True) self.achlabel1.Enable(True) self.achlabel2.Enable(True) self.inppb.Show(True)
class MyFrame(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'scrollable plot', style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER, size=(800, 400)) self.panel = wx.Panel(self, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self.panel, -1, self.fig) self.scroll_range = 400 self.canvas.SetScrollbar(wx.HORIZONTAL, 0, 5, self.scroll_range) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, -1, wx.EXPAND) self.panel.SetSizer(sizer) self.panel.Fit() self.init_data() self.init_plot() self.canvas.Bind(wx.EVT_SCROLLWIN, self.OnScrollEvt) def init_data(self): # Generate some data to plot: self.dt = 0.01 self.t = arange(0, 5, self.dt) self.x = sin(2 * pi * self.t) # Extents of data sequence: self.i_min = 0 self.i_max = len(self.t) # Size of plot window: self.i_window = 100 # Indices of data interval to be plotted: self.i_start = 0 self.i_end = self.i_start + self.i_window def init_plot(self): self.axes = self.fig.add_subplot(111) self.plot_data = \ self.axes.plot(self.t[self.i_start:self.i_end], self.x[self.i_start:self.i_end])[0] def draw_plot(self): # Update data in plot: self.plot_data.set_xdata(self.t[self.i_start:self.i_end]) self.plot_data.set_ydata(self.x[self.i_start:self.i_end]) # Adjust plot limits: self.axes.set_xlim((min(self.t[self.i_start:self.i_end]), max(self.t[self.i_start:self.i_end]))) self.axes.set_ylim((min(self.x[self.i_start:self.i_end]), max(self.x[self.i_start:self.i_end]))) # Redraw: self.canvas.draw() def OnScrollEvt(self, event): # Update the indices of the plot: self.i_start = self.i_min + event.GetPosition() self.i_end = self.i_min + self.i_window + event.GetPosition() self.draw_plot()
class MplCanvas(FigureCanvasQTAgg_modified): """Class to represent the FigureCanvas widget""" def __init__(self): # setup Matplotlib Figure and Axis self.fig = Figure() bbox = self.fig.get_window_extent().transformed( self.fig.dpi_scale_trans.inverted()) width, height = bbox.width * self.fig.dpi, bbox.height * self.fig.dpi self.fig.subplots_adjust( left=50 / width, #40 / width, bottom=30 / height, #20 / height right=1 - 20 / width, # 1 - 5 / width, top=1 - 30 / height, hspace=0.0) # left=0.07, right=0.98, # top=0.94, bottom=0.07, hspace=0.0) self._define_axes(1) self.set_toNight(True) FigureCanvasQTAgg_modified.__init__(self, self.fig) FigureCanvasQTAgg_modified.setSizePolicy( self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvasQTAgg_modified.updateGeometry(self) def _define_axes(self, h_cake): self.gs = GridSpec(100, 1) self.ax_pattern = self.fig.add_subplot(self.gs[h_cake + 1:99, 0]) self.ax_cake = self.fig.add_subplot(self.gs[0:h_cake, 0], sharex=self.ax_pattern) self.ax_pattern.set_ylabel('Intensity (arbitrary unit)') self.ax_pattern.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2)) self.ax_pattern.get_yaxis().get_offset_text().set_position( (-0.04, -0.1)) def resize_axes(self, h_cake): self.fig.clf() self._define_axes(h_cake) if h_cake == 1: self.ax_cake.tick_params(axis='y', colors=self.objColor, labelleft=False) self.ax_cake.spines['right'].set_visible(False) self.ax_cake.spines['left'].set_visible(False) self.ax_cake.spines['top'].set_visible(False) self.ax_cake.spines['bottom'].set_visible(False) elif h_cake >= 10: self.ax_cake.set_ylabel("Azimuth (degrees)") def set_toNight(self, NightView=True): if NightView: try: mplstyle.use( os.path.join(os.path.curdir, 'mplstyle', 'night.mplstyle')) except: mplstyle.use('dark_background') self.bgColor = 'black' self.objColor = 'white' else: try: mplstyle.use( os.path.join(os.path.curdir, 'mplstyle', 'day.mplstyle')) except: mplstyle.use('classic') self.bgColor = 'white' self.objColor = 'black' # self.fig.clf() # self.ax_pattern.cla() # Cursor(self.ax, useblit=True, color=self.objColor, linewidth=2 ) self.fig.set_facecolor(self.bgColor) self.ax_cake.tick_params(which='both', axis='x', colors=self.objColor, direction='in', labelbottom=False, labeltop=False) #self.ax_cake.tick_params(axis='both', which='both', length=0) self.ax_cake.tick_params(axis='x', which='both', length=0) self.ax_pattern.xaxis.set_label_position('bottom')
class MainWindow(QMainWindow): """ 程序主窗口程序,UI文件为UI_MainWindow """ def __init__(self): super().__init__() # 定义内部变量 self.data = None # 分析数据 self.comp_data = None # 对比数据 self.file_name = None # 文件名 self.table_name = None # 表名 self.spindle_id = None # 当前拧紧枪id self.comp_spindle_id = None # 对比用拧紧枪id self.spcwindow = None self.time_period = [None, None] # 分析时间段,[开始时间,结束时间] # 当前数据的起始组数 self.current_start_num = None # 当前数据的结束组数 self.current_end_num = None # 当前数据的起始时间 self.current_start_time = None # 当前数据的结束时间 self.current_end_time = None self.ui = Ui_MainWindow() self.ui.setupUi(self) # 状态信息显示在状态栏中 self.text_out = self.ui.statusBar.showMessage # 消息connect self.ui.actionOpen.triggered.connect(self.load) self.ui.actionChange_Spindle_ID.triggered.connect(self.change_spindle_id) self.ui.actionAddSpindle.triggered.connect(self.add_comp_spindle) self.ui.actionClear_ALL.triggered.connect(self.clear_all) self.ui.actionClearTorque.triggered.connect(self.clear_torque) self.ui.button_time.clicked.connect(self.plot_by_time) self.ui.button_num.clicked.connect(self.plot_by_part) self.ui.button_detial_time.clicked.connect(self.plot_detail_time) self.ui.button_detial_num.clicked.connect(self.plot_detail_num) self.ui.actionspc_xr.triggered.connect(self.spc_show) self.ui.actionPartNum.triggered.connect(self.set_series_num) self.ui.actionReverseTime.triggered.connect(self.set_reverse_month) self.ui.actionDefaultReadTime.triggered.connect(self.set_divide_time) self.ui.actionDefaultLatestNum.triggered.connect(self.set_default_latest_num) self.ui.actionPlotSpecgram.triggered.connect(self.plot_specgram) self.ui.actionPlotFFT.triggered.connect(self.plot_fft) # 生产量信息图表,包括生产量子图和生产合格率子图 self.figure_production = Figure() self.ax_production = self.figure_production.add_subplot(211) self.ax_qualification = self.figure_production.add_subplot(212) self.figure_canvas_production = FigureCanvas(self.figure_production) # 扭矩信息图表,包括扭矩平均值子图,标准差子图,扭矩分布直方图 self.figure_torque = Figure() self.ax_torque_mean = self.figure_torque.add_subplot(311) self.ax_torque_std = self.figure_torque.add_subplot(312) self.ax_torque_hist = self.figure_torque.add_subplot(313) self.figure_canvas_torque = FigureCanvas(self.figure_torque) # 添加图表 layout_production = QtWidgets.QVBoxLayout() layout_production.addWidget(self.figure_canvas_production) self.ui.figure_production.setLayout(layout_production) layout_figure = QtWidgets.QVBoxLayout() layout_figure.addWidget(self.figure_canvas_torque) self.ui.figure_torque.setLayout(layout_figure) self.setWindowState(Qt.WindowMaximized) self.show() def spc_show(self): from db_process.spc_process import SPCWindow self.spcwindow = SPCWindow(self.data.total_normal_data) @staticmethod def plot_detail(*args, **kwargs): plt.close() try: plt.figure(1) plt.plot(args, kwargs) plt.legend() plt.show() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText("错误:{}".format(err)) msg_box.exec_() return def plot_detail_time(self): """ 利用matplotlit的pyplot做出以时间为横轴的详细数据图,包括生产量数据子图(每日产量和每日合格率),扭矩数据子图(分 组扭矩均值和标准差) :return: """ plt.close() try: plt.figure(1) plt.subplot(211) plt.plot(self.data.part_date[self.current_start_num:self.current_end_num], self.data.part_mean[self.current_start_num:self.current_end_num], label="ID {} mean".format(self.spindle_id)) plt.plot(self.data.part_date[self.current_start_num:self.current_end_num], self.data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.spindle_id)) if self.comp_data is not None: plt.plot(self.comp_data.part_date[self.current_start_num:self.current_end_num], self.comp_data.part_mean[self.current_start_num:self.current_end_num], label="ID {} mean".format(self.comp_spindle_id)) plt.plot(self.comp_data.part_date[self.current_start_num:self.current_end_num], self.comp_data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.comp_spindle_id)) plt.legend() plt.subplot(212) plt.plot(self.data.daily_production[self.current_start_time:self.current_end_time], label="Daily Production".format(self.spindle_id)) plt.fill_between( self.data.daily_production[self.current_start_time:self.current_end_time].index, self.data.daily_qualified_production[self.current_start_time:self.current_end_time], label="Qualification Production") plt.legend() plt.show() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText("错误:{}".format(err)) msg_box.exec_() return def plot_detail_num(self): """ 利用matplotlit的pyplot做出以组数为横轴的详细数据图,包括扭矩数据子图(分组扭矩均值和标准差),组数与时间对应关系 子图 :return: """ plt.close() try: plt.figure(1) plt.subplot(211) plt.plot(range(self.current_start_num, self.current_end_num), self.data.part_mean[self.current_start_num:self.current_end_num], label="ID {} mean".format(self.spindle_id)) plt.plot(range(self.current_start_num, self.current_end_num), self.data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.spindle_id)) if self.comp_data is not None: plt.plot(range(self.current_start_num, self.current_end_num), self.comp_data.part_mean[self.current_start_num:self.current_end_num], label="ID {} mean".format(self.comp_spindle_id)) plt.plot(range(self.current_start_num, self.current_end_num), self.comp_data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.comp_spindle_id)) plt.legend() plt.subplot(212) plt.plot(self.data.part_date[self.current_start_num:self.current_end_num]) plt.show() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText("错误:{}".format(err)) msg_box.exec_() return def load_fatigue(self): """ 开启疲劳计算模块 :return: """ file_name, ok = QtWidgets.QFileDialog.getOpenFileName( self, caption=self.tr("打开数据库"), filter=self.tr("Database Files (*.accdb)")) if not ok: return table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return while True: import pypyodbc from db_process.fatigue_mssql import FatigueDialog try: self.fatigue_dialog = FatigueDialog(file_name, table_name, text_out=self.text_out) return True except pypyodbc.Error as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n可能为数据表名称错误,请重新输入".format(err))) msg_box.exec_() self.text_out("请等待重新输入") table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return def load_comp(self): """ 读取数据库以对比拧紧枪 :return: """ file_name, ok = QtWidgets.QFileDialog.getOpenFileName( self, caption=self.tr("打开数据库"), filter=self.tr("Database Files (*.accdb)")) if not ok: return table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return while True: import pypyodbc from db_process.multi import SelectDialog try: self.select_dialog = SelectDialog(file_name, table_name, text_out=self.text_out) self.select_dialog.show() return True except pypyodbc.Error as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n可能为数据表名称错误,请重新输入".format(err))) msg_box.exec_() self.text_out("请等待重新输入") table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return def load(self): """ 读取数据库 :return: """ self.clear_all() file_name, ok = QtWidgets.QFileDialog.getOpenFileName( self, caption=self.tr("打开数据库"), filter=self.tr("Database Files (*.accdb)")) if not ok: return False table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return False spindle_id, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("查询枪号"), 1, 1, 22) if not ok: return False self.time_period = [None, None] while True: import pypyodbc try: self.data = ScrewingDataProcess( file_name, table_name, spindle_id, self.time_period, text_out=self.ui.statusBar.showMessage) break except pypyodbc.Error as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n可能为数据表名称错误,请重新输入".format(err))) msg_box.exec_() self.text_out("请等待重新输入") table_name, ok = QtWidgets.QInputDialog.getText(self, self.tr("请输入"), self.tr("表名")) if not (ok and table_name): return False except IndexError as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n本段时间内数据量可能为空,请重新输入".format(err))) msg_box.exec_() self.text_out("请等待重新输入") self.time_period = [None, None] DateWindow(self, self.time_period).exec() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}".format(err))) msg_box.exec_() return False self.text_out("完成") self.file_name = file_name self.table_name = table_name self.spindle_id = spindle_id try: # 设置程序控件值的范围与当前默认值 self.ui.start_time.setMinimumDate( QDate.fromString(str(self.data.part_date[0].date()), "yyyy-MM-dd")) self.ui.start_time.setMaximumDate( QDate.fromString(str(self.data.part_date[-1].date()), "yyyy-MM-dd")) self.ui.start_time.setDate( QDate.fromString(str(self.data.part_date[0].date()), "yyyy-MM-dd")) self.ui.end_time.setMinimumDate( QDate.fromString(str(self.data.part_date[0].date()), "yyyy-MM-dd")) self.ui.end_time.setMaximumDate( QDate.fromString(str(self.data.part_date[-1].date()), "yyyy-MM-dd")) self.ui.end_time.setDate( QDate.fromString(str(self.data.part_date[-1].date()), "yyyy-MM-dd")) self.ui.start_num.setMinimum(0) self.ui.start_num.setMaximum(len(self.data.part_date) - 1) self.ui.start_num.setValue(0) self.ui.end_num.setMinimum(0) self.ui.end_num.setMaximum(len(self.data.part_date) - 1) self.ui.end_num.setValue(len(self.data.part_date) - 1) # 激活控件 self.ui.actionChange_Spindle_ID.setEnabled(True) self.ui.actionAddSpindle.setEnabled(True) self.ui.centralWidget.setEnabled(True) self.ui.centralWidget.setEnabled(True) self.ui.menuBar.setEnabled(True) self.ui.menuspc_figure.setEnabled(True) self.ui.menuPlotFrequence.setEnabled(True) self.ui.menuSetting.setEnabled(True) self.comp_data = None # 以时间为横轴作图 self.plot_by_time() except IndexError as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n可能为分组量过大,无法生成有效分组".format(err))) msg_box.exec_() self.text_out("请重新设定分组数,并重新打开数据库") self.time_period = [None, None] self.data = None except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}".format(err))) msg_box.exec_() return False return True def change_spindle_id(self): """ 改变拧紧枪号 :return: """ self.clear_all() spindle_id, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("查询枪号"), 1, 1, 22) if spindle_id == self.spindle_id: self.text_out("与当前存储数据ID相同") return self.spindle_id = spindle_id self.data = ScrewingDataProcess( self.file_name, self.table_name, self.spindle_id, self.time_period, text_out=self.ui.statusBar.showMessage) self.comp_data = None self.text_out("完成") self.plot_by_time() def add_comp_spindle(self): """ 添加对比拧紧枪 :return: """ spindle_id, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("对比枪号"), 1, 1, 22) if spindle_id == self.spindle_id: self.text_out("与当前分析拧紧枪ID相同") return if spindle_id == self.comp_spindle_id: self.text_out("与当前对比拧紧枪ID相同") return self.comp_spindle_id = spindle_id self.comp_data = ScrewingDataProcess( self.file_name, self.table_name, self.comp_spindle_id, self.time_period, text_out=self.ui.statusBar.showMessage) self.text_out("完成") self.plot_by_time() def update_number(self): """ 更新显示数字的控件内容 :return: """ if self.data is None: return self.ui.spindle.setText(format(self.spindle_id, '<')) self.ui.total_qualification.setText( "{:<.2f}%".format(len(self.data.total_normal_data[self.current_start_time:self.current_end_time]) / len(self.data.total_data[self.current_start_time:self.current_end_time]) * 100)) self.ui.total_production.setText( format(len(self.data.total_data[self.current_start_time:self.current_end_time]), '<')) self.ui.total_mean.setText( format(self.data.total_normal_data[self.current_start_time:self.current_end_time].mean(), '<.2f')) self.ui.total_std.setText( format(self.data.total_normal_data[self.current_start_time:self.current_end_time].std(), '<.2f')) self.ui.current_start_time.setText(str(self.current_start_time)) self.ui.current_end_time.setText(str(self.current_end_time)) self.ui.current_start_num.setText(str(self.current_start_num)) self.ui.current_end_num.setText(str(self.current_end_num)) self.ui.start_time.setDate(QDate.fromString(str(self.current_start_time.date()), "yyyy-MM-dd")) self.ui.end_time.setDate(QDate.fromString(str(self.current_end_time.date()), "yyyy-MM-dd")) self.ui.start_num.setValue(self.current_start_num) self.ui.end_num.setValue(self.current_end_num) self.ui.label_total_start.setText(str(self.data.part_date[0])) self.ui.label_total_end.setText(str(self.data.part_date[-1])) self.ui.label_total_num.setNum(len(self.data.part_date)) if self.comp_data is not None: self.ui.label_comp_spindle_id.setNum(self.comp_spindle_id) self.ui.label_correlation.setNum(self.data.total_normal_data.corr(self.comp_data.total_normal_data)) else: self.ui.label_comp_spindle_id.setText("NaN") self.ui.label_correlation.setText("NaN") def update_var_by_time(self): """ 以时间为标准,改变内部变量的值 :return: """ if self.ui.start_time.date() >= self.ui.end_time.date(): raise ValueError("开始日期请小于结束日期") start_time = self.ui.start_time.date().toString("yyyy-MM-dd") end_time = self.ui.end_time.date().toString("yyyy-MM-dd") self.current_start_time, self.current_end_time, self.current_start_num, self.current_end_num = \ self.series_between_time(start_time, end_time, self.data.part_date) def update_var_by_part(self): """ 以组数为标准,改变内部变量的值 :return: """ if self.ui.start_num.value() >= self.ui.end_num.value(): raise ValueError("开始组数请小于结束组数") self.current_start_num = self.ui.start_num.value() self.current_end_num = self.ui.end_num.value() self.current_start_time = self.data.part_date[self.current_start_num] self.current_end_time = self.data.part_date[self.current_end_num] def clear_torque(self): """ 清除扭矩图像 :return: """ self.ax_torque_std.clear() self.ax_torque_mean.clear() self.ax_torque_hist.clear() self.figure_canvas_torque.draw() self.ui.actionClearTorque.setEnabled(False) def clear_all(self): """ 清除所有图像 :return: """ self.ax_production.clear() self.ax_qualification.clear() self.figure_canvas_production.draw() self.clear_torque() self.ui.actionClear_ALL.setEnabled(False) def plot_by_time(self): """ 以时间为横轴作图 :return: """ self.clear_all() try: self.update_var_by_time() self.update_number() self.plot_production() self.plot_torque_time() except ValueError as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n请重新输入".format(err))) msg_box.exec_() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}".format(err))) msg_box.exec_() return def plot_by_part(self): """ 以组数为横轴作图(产量图仍然以时间为横轴) :return: """ self.clear_all() try: self.update_var_by_part() self.update_number() self.plot_production() self.plot_torque_part() except ValueError as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}\n请重新输入".format(err))) msg_box.exec_() except Exception as err: msg_box = QtWidgets.QMessageBox() msg_box.setText(self.tr("错误:{}".format(err))) msg_box.exec_() return @staticmethod def series_between_time(start_time, end_time, date_list): """ 功能静态函数,确定一个时间Series中start_time到end_time之间的最大区间 :param start_time: 起始时间 :param end_time: 结束时间 :param date_list: 在start_time与end_time之间的最大区间的序列起始时间,序列结束时间,序列起始组数,序列结束组数 :return: """ start_time = pd.to_datetime(start_time) end_time = pd.to_datetime(end_time) part_start_time = None part_end_time = date_list[-1] start_num = None end_num = len(date_list) - 1 for i, date in enumerate(date_list): if date > start_time and part_start_time is None: part_start_time = date start_num = i if date > end_time: part_end_time = date end_num = i break if part_start_time is None: part_start_time = date_list[0] start_num = 0 return part_start_time, part_end_time, start_num, end_num def plot_torque_time(self): """ 以时间为横轴绘制扭矩图 :return: """ self.ax_torque_mean.plot(self.data.part_date[self.current_start_num:self.current_end_num], self.data.part_mean[self.current_start_num:self.current_end_num], label="ID {} Mean".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_mean.plot(self.comp_data.part_date[self.current_start_num:self.current_end_num], self.comp_data.part_mean[self.current_start_num:self.current_end_num], label="ID {} Mean".format(self.comp_spindle_id)) self.ax_torque_mean.legend() self.ax_torque_std.plot(self.data.part_date[self.current_start_num:self.current_end_num], self.data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_std.plot(self.comp_data.part_date[self.current_start_num:self.current_end_num], self.comp_data.part_std[self.current_start_num:self.current_end_num], label="ID {} Mean".format(self.comp_spindle_id)) self.ax_torque_std.legend() self.ax_torque_hist.hist(self.data.total_normal_data[self.current_start_num:self.current_end_num], np.arange(12., 25., 0.2), histtype="stepfilled", label="ID {} Hist".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_hist.hist(self.comp_data.total_normal_data[self.current_start_num:self.current_end_num], np.arange(12., 25., 0.2), histtype="stepfilled", label="ID {} Hist".format(self.comp_spindle_id)) self.ax_torque_std.legend() self.figure_canvas_torque.draw() self.ui.actionClear_ALL.setEnabled(True) self.ui.actionClearTorque.setEnabled(True) def plot_torque_part(self): """ 以组数为横轴绘制扭矩图 :return: """ self.ax_torque_mean.plot(range(self.current_start_num, self.current_end_num), self.data.part_mean[self.current_start_num:self.current_end_num], label="ID {} Mean".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_mean.plot(range(self.current_start_num, self.current_end_num), self.comp_data.part_mean[self.current_start_num:self.current_end_num], label="ID {} Mean".format(self.comp_spindle_id)) self.ax_torque_mean.legend() self.ax_torque_std.plot(range(self.current_start_num, self.current_end_num), self.data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_std.plot(range(self.current_start_num, self.current_end_num), self.comp_data.part_std[self.current_start_num:self.current_end_num], label="ID {} std".format(self.comp_spindle_id)) self.ax_torque_std.legend() self.ax_torque_hist.hist(self.data.total_normal_data[self.current_start_num:self.current_end_num], np.arange(12., 25., 0.2), histtype="stepfilled", label="ID {} Hist".format(self.spindle_id)) if self.comp_data is not None: self.ax_torque_hist.hist(self.comp_data.total_normal_data[self.current_start_num:self.current_end_num], np.arange(12., 25., 0.2), histtype="stepfilled", label="ID {} Hist".format(self.comp_spindle_id)) self.ax_torque_std.legend() self.figure_canvas_torque.draw() self.ui.actionClear_ALL.setEnabled(True) self.ui.actionClearTorque.setEnabled(True) def plot_production(self): """ 绘制产量图 :return: """ self.ax_production.plot(self.data.daily_production[self.current_start_time:self.current_end_time], label="Daily Production") self.ax_production.legend() self.ax_qualification.fill_between( self.data.daily_production[self.current_start_time:self.current_end_time].index, self.data.daily_qualified_production[self.current_start_time:self.current_end_time] / self.data.daily_production[self.current_start_time:self.current_end_time], label="Qualification") self.ax_qualification.set_ylim(0.8, 1.0) self.ax_qualification.legend() self.figure_canvas_production.draw() self.ui.actionClear_ALL.setEnabled(True) def set_divide_time(self): divide, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("每组数据中最大间隔时间(分钟)"), cf.divide_time, 1, 1440) if ok: cf.divide_time = divide def set_series_num(self): series_num, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("每组数据量(设置太大可能会导致无分组)"), cf.series_num, 10, 100) if ok: cf.series_num = series_num def set_reverse_month(self): reverse, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("默认回溯月数(在确认数据库读取时间段时,\n" "默认的开始日期为当前日期之前的前几个月"), cf.reverse_month, 1, 12) if ok: cf.reverse_month = reverse def set_default_latest_num(self): num, ok = QtWidgets.QInputDialog.getInt(self, self.tr("请输入"), self.tr("默认最新读取数据量(设置读取最新数据时,\n" "(每把拧紧枪)需要读取多少行数据"), cf.default_latest_num, 100, 1000000) if ok: cf.default_latest_num = num def plot_specgram(self): from math import log2 nfft = 2 << (1 + int(log2(len(self.data.part_mean)))) plt.close() plt.specgram(self.data.part_mean, NFFT=nfft, Fs=cf.series_num, noverlap=10) plt.show() def plot_fft(self): fft = np.fft.rfft(self.data.part_mean) plt.close() plt.plot(abs(fft)) plt.ylim(0.0, abs(fft[1])) plt.show()
def stovna_geo_okid(frame, root, db_info): for widget in frame.winfo_children(): widget.destroy() Label(frame, text='Stovna nýtt Geografiskt økið', font='Helvetica 18 bold').pack(side=TOP) mainFrame = Frame(frame) mainFrame.pack(side=TOP, fill=BOTH, expand=TRUE, anchor=N) lframe = Frame(mainFrame) lframe.pack(side=LEFT, fill=BOTH, expand=TRUE, anchor=N) rframe = Frame(mainFrame) rframe.pack(side=LEFT, fill=BOTH, expand=TRUE, anchor=N) controlsFrame = Frame(lframe) controlsFrame.pack(fill=BOTH, expand=True, side=TOP, anchor=W) buttonsFrame = Frame(controlsFrame) buttonsFrame.pack(side=TOP, fill=X) teknaButton = Button( buttonsFrame, text='Tekna', command=lambda: tekna(fig, canvas, latminEntry.get(), latmaxEntry.get( ), lonminEntry.get(), lonmaxEntry.get())) teknaButton.pack(side=LEFT, anchor=N) stovnaButton = Button( buttonsFrame, text='Stovna Økið', command=lambda: innset(navnEntry.get(), styttingEntry.get( ), latminEntry.get(), latmaxEntry.get(), lonminEntry.get(), lonmaxEntry.get(), db_info, punktir)) stovnaButton.pack(side=RIGHT, anchor=N) strikaButton = Button( buttonsFrame, text='Strika Økið', command=lambda: strika(navnEntry.get(), db_info, punktir)) strikaButton.pack(side=RIGHT, anchor=N) navnFrame = Frame(controlsFrame) navnFrame.pack(side=TOP, anchor=W) Label(navnFrame, text='Navn:').pack(side=LEFT) navnEntry = Entry(navnFrame, width=50) navnEntry.pack(side=LEFT) styttingFrame = Frame(controlsFrame) styttingFrame.pack(side=TOP, anchor=W) Label(styttingFrame, text='Stytting:').pack(side=LEFT) styttingEntry = Entry(styttingFrame, width=10) styttingEntry.pack(side=LEFT) latFrame = Frame(controlsFrame) latFrame.pack(side=TOP, anchor=W) Label(latFrame, text='Latmin:').pack(side=LEFT) latminEntry = Entry(latFrame, width=10) latminEntry.pack(side=LEFT) latminEntry.insert(0, "61.35") Label(latFrame, text='Latmax:').pack(side=LEFT) latmaxEntry = Entry(latFrame, width=10) latmaxEntry.pack(side=LEFT) latmaxEntry.insert(0, "62.4") lonFrame = Frame(controlsFrame) lonFrame.pack(side=TOP, anchor=W) Label(lonFrame, text='Lonmin:').pack(side=LEFT) lonminEntry = Entry(lonFrame, width=10) lonminEntry.pack(side=LEFT) lonminEntry.insert(0, "-7.7") Label(lonFrame, text='Lonmax:').pack(side=LEFT) lonmaxEntry = Entry(lonFrame, width=10) lonmaxEntry.pack(side=LEFT) lonmaxEntry.insert(0, "-6.2") kortFrame = Frame(lframe) kortFrame.pack(fill=BOTH, expand=True, side=TOP, anchor=W) punktir = ttk.Treeview(rframe) punktir.bind( "<Double-1>", lambda event, arg=punktir: OnDoubleClick( event, arg, navnEntry, styttingEntry, latminEntry, latmaxEntry, lonminEntry, lonmaxEntry, db_info, fig, canvas)) scrollbar = Scrollbar(rframe, orient=VERTICAL) scrollbar.config(command=punktir.yview) scrollbar.pack(side=RIGHT, fill=Y) #fig = Figure(figsize=(5, 6), dpi=100) fig = Figure() ax = fig.add_subplot(111) canvas = FigureCanvasTkAgg(fig, master=kortFrame) db_connection = db.connect(**db_info) cursor = db_connection.cursor() log_frame = Frame(frame, height=300) log_frame.pack(fill=X, expand=False, side=BOTTOM, anchor=W) gerlog(log_frame, root) cursor.execute("SELECT * FROM WL_Geografisk_okir") result = cursor.fetchall() kolonnir = cursor.column_names punktir["columns"] = kolonnir[1::] #punktir.column("#0", width=100) for i in range(1, len(kolonnir)): punktir.heading(kolonnir[i], text=kolonnir[i]) #punktir.column("#" + str(i), width=100) dagfor_tree(result, punktir) tekstur = """ clf landlitur=green Tekna kort linjuSlag=eingin longdarlinjur=5 breiddarlinjur=6 """ Processing.tekna_kort.les_og_tekna(tekstur, fig, canvas, False) db_connection.disconnect() print(cursor.column_names) print(result)
class ROISelect: def __init__(self, video=None, roi_size=(11, 11), noverlap=0, polygon=None): self.verbose = 0 self.shift_is_held = False self.roi_size = roi_size self.noverlap = int(noverlap) self.cent_dist_0 = self.roi_size[0] - self.noverlap self.cent_dist_1 = self.roi_size[1] - self.noverlap if polygon is None: self.polygon = [[], []] else: self.polygon = polygon self.deselect_polygon = [[], []] self.points = [[], []] root = tk.Tk() root.title('Selection') self.show_box = tk.IntVar() self.screen_width = root.winfo_screenwidth() self.screen_height = root.winfo_screenheight() root.geometry( f'{int(0.9*self.screen_width)}x{int(0.9*self.screen_height)}') self.options = SelectOptions(root, self) button1 = tk.Button(root, text='Open options', command=lambda: self.open_options(root)) button1.pack(side='top') button2 = tk.Button(root, text='Confirm selection', command=lambda: self.on_closing(root)) button2.pack(side='top') self.fig = Figure(figsize=(10, 7)) self.ax = self.fig.add_subplot(111) self.ax.grid(False) self.ax.imshow(video.mraw[0], cmap='gray') # Initiate polygon self.line, = self.ax.plot(self.polygon[1], self.polygon[0], 'C1.-') self.line_deselect, = self.ax.plot(self.deselect_polygon[1], self.deselect_polygon[0], 'k.-') self.line2, = self.ax.plot([], [], 'C0x') plt.show(block=False) # Embed figure in tkinter winodw canvas = FigureCanvasTkAgg(self.fig, root) canvas.get_tk_widget().pack(side='top', fill='both', expand=1, padx=5, pady=5) NavigationToolbar2Tk(canvas, root) if self.verbose: print( 'SHIFT + LEFT mouse button to pick a pole.\nRIGHT mouse button to erase the last pick.' ) # Connecting functions to event manager self.fig.canvas.mpl_connect('key_press_event', self.on_key_press) self.fig.canvas.mpl_connect('key_release_event', self.on_key_release) self.update_variables() root.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(root)) tk.mainloop() def _mode_selection_polygon(self, get_rois=True): """Select polygon to compute the points based on ROI size and ROI overlap.""" def onclick(event): if event.button == 1 and self.shift_is_held: if event.xdata is not None and event.ydata is not None: if self.polygon[0]: del self.polygon[1][-1] del self.polygon[0][-1] self.polygon[1].append(int(np.round(event.xdata))) self.polygon[0].append(int(np.round(event.ydata))) if self.polygon[0]: self.polygon[1].append(self.polygon[1][0]) self.polygon[0].append(self.polygon[0][0]) if self.verbose: print( f'y: {np.round(event.ydata):5.0f}, x: {np.round(event.xdata):5.0f}' ) elif event.button == 3 and self.shift_is_held: if self.verbose: print('Deleted the last point...') del self.polygon[1][-2] del self.polygon[0][-2] self.line.set_xdata(self.polygon[1]) self.line.set_ydata(self.polygon[0]) self.fig.canvas.draw() if get_rois: self.plot_selection() self.cid = self.fig.canvas.mpl_connect('button_press_event', onclick) def _mode_selection_deselect_polygon(self): """Select polygon to compute the points based on ROI size and ROI overlap.""" def onclick(event): if event.button == 1 and self.shift_is_held: if event.xdata is not None and event.ydata is not None: if self.deselect_polygon[0]: del self.deselect_polygon[1][-1] del self.deselect_polygon[0][-1] self.deselect_polygon[1].append(int(np.round(event.xdata))) self.deselect_polygon[0].append(int(np.round(event.ydata))) if self.deselect_polygon[0]: self.deselect_polygon[1].append( self.deselect_polygon[1][0]) self.deselect_polygon[0].append( self.deselect_polygon[0][0]) if self.verbose: print( f'y: {np.round(event.ydata):5.0f}, x: {np.round(event.xdata):5.0f}' ) elif event.button == 3 and self.shift_is_held: if self.verbose: print('Deleted the last point...') del self.deselect_polygon[1][-2] del self.deselect_polygon[0][-2] self.line_deselect.set_xdata(self.deselect_polygon[1]) self.line_deselect.set_ydata(self.deselect_polygon[0]) self.fig.canvas.draw() self.plot_selection() self.cid = self.fig.canvas.mpl_connect('button_press_event', onclick) def _mode_selection_manual_roi(self): """Select polygon to compute the points based on ROI size and ROI overlap.""" def onclick(event): if event.button == 1 and self.shift_is_held: if event.xdata is not None and event.ydata is not None: self.points[0].append(int(np.round(event.ydata))) self.points[1].append(int(np.round(event.xdata))) elif event.button == 3 and self.shift_is_held: del self.points[1][-1] del self.points[0][-1] self.fig.canvas.draw() self.plot_selection() self.cid = self.fig.canvas.mpl_connect('button_press_event', onclick) def on_key_press(self, event): """Function triggered on key press (shift).""" if event.key == 'shift': self.shift_is_held = True def on_key_release(self, event): """Function triggered on key release (shift).""" if event.key == 'shift': self.shift_is_held = False def update_variables(self): self.line2.set_xdata([]) self.line2.set_ydata([]) self.fig.canvas.draw() self.mode = self.options.combobox.get() if SELECTION_MODES[self.mode] == 0: self._disconnect_mpl_onclick() self._mode_selection_polygon() self.roi_size = [ int(self.options.roi_entry_y.get()), int(self.options.roi_entry_x.get()) ] self.noverlap = int(self.options.noverlap_entry.get()) self.cent_dist_0 = self.roi_size[0] - self.noverlap self.cent_dist_1 = self.roi_size[1] - self.noverlap self.plot_selection() elif SELECTION_MODES[self.mode] == 1: if len(self.points[0]) == 0: tk.messagebox.showwarning("Warning", "No points have been selected yet.") else: self._disconnect_mpl_onclick() self._mode_selection_deselect_polygon() self.plot_selection() elif SELECTION_MODES[self.mode] == 2: self._disconnect_mpl_onclick() self._mode_selection_polygon(get_rois=False) elif SELECTION_MODES[self.mode] == 3: self._disconnect_mpl_onclick() self._mode_selection_manual_roi() self.roi_size = [ int(self.options.roi_entry_y.get()), int(self.options.roi_entry_x.get()) ] self.plot_selection() else: raise Exception('Non existing mode...') self.options.description.configure( text=MODE_DESCRIPTION[SELECTION_MODES[self.mode]]) def _disconnect_mpl_onclick(self): try: self.fig.canvas.mpl_disconnect(self.cid) except: pass def plot_selection(self): if len(self.polygon[0]) > 2 and len(self.polygon[1]) > 2: self.points = get_roi_grid(self.polygon, self.roi_size, self.noverlap, self.deselect_polygon).T if len(self.points[0]) >= 1 and len(self.points[1]) >= 1: self.line2.set_xdata(np.array(self.points).T[:, 1]) self.line2.set_ydata(np.array(self.points).T[:, 0]) self.options.nr_points_label.configure( text=f'{len(np.array(self.points).T)}') # if SELECTION_MODES[self.mode] == 3: if self.show_box.get(): [p.remove() for p in reversed(self.ax.patches)] self.rectangles = [] for i, (p0, p1) in enumerate(zip(self.points[0], self.points[1])): self.rectangles.append( patches.Rectangle((p1 - self.roi_size[1] / 2, p0 - self.roi_size[0] / 2), self.roi_size[1], self.roi_size[0], fill=False, color='C2', linewidth=2)) self.ax.add_patch(self.rectangles[-1]) else: [p.remove() for p in reversed(self.ax.patches)] self.fig.canvas.draw() def clear_selection(self): self.polygon = [[], []] self.deselect_polygon = [[], []] self.points = [[], []] self.options.nr_points_label.configure(text='0') self.clear_plot() def clear_plot(self): self.line.set_xdata([]) self.line.set_ydata([]) self.line_deselect.set_xdata([]) self.line_deselect.set_ydata([]) self.line2.set_xdata([]) self.line2.set_ydata([]) [p.remove() for p in reversed(self.ax.patches)] self.fig.canvas.draw() def open_options(self, root): if not self.options.running_options: self.options = SelectOptions(root, self) else: self.options.root1.lift() def on_closing(self, root): self.points = np.array(self.points) if self.points.shape[0] == 2: self.points = self.points.T root.destroy()
class Scissor: def __init__(self, master): # Create a container frame = Tkinter.Frame(master) self.root = master self.curPath = os.getcwd() # Create 2 buttons self.button_img_open = Tkinter.Button(frame, text="open file", command=self.fileOpen) self.button_img_open.pack(side="left") # self.button_save_contour = Tkinter.Button(frame, text="save_contour", command=self.save_contour) self.button_save_contour.pack(side="left") self.button_loadContour = Tkinter.Button(frame, text="load contour", command=self.loadContour) self.button_loadContour.pack(side="left") self.button_img_only = Tkinter.Button(frame, text="Hide Contour", command=self.hidden_contour) self.button_img_only.pack(side="left") self.button_img_only = Tkinter.Button(frame, text="show contour drawn before", command=self.show_contour) self.button_img_only.pack(side="left") self.button_draw_contour = Tkinter.Button(frame, text="draw contour", command=self.draw_contour) self.button_draw_contour.pack(side="left") self.button_stop_contour = Tkinter.Button(frame, text="stop drawing", command=self.stop_contour) self.button_stop_contour.pack(side="left") self.button_remove_old_contour = Tkinter.Button( frame, text="remove old contour", command=self.remove_old_contour) self.button_remove_old_contour.pack(side="left") # self.button_cropImage = Tkinter.Button(frame, text="cropImage", command=self.cropImage) self.button_cropImage.pack(side="left") # self.button_saveCropped = Tkinter.Button(frame, text="Save Cropped Image", command=self.saveCropped) self.button_saveCropped.pack(side="left") # self.button_scaleDown = Tkinter.Button(frame, text="Scale Down Image", # command=self.saveCropped) # self.button_scaleDown.pack(side="left") # # # self.button_pathTree = Tkinter.Button(frame, text="Path Tree", # command=self.pathTree) # self.button_pathTree.pack(side="left") # # # self.button_minPath = Tkinter.Button(frame, text="Minimal Path", # command=self.minPath) # self.button_minPath.pack(side="left") self.imgPath = None self.imgFileName = None self.img = None self.contour = [] self.imgTk = None self.imgPIL = None self.grayImgNp = None self.colorImgNp = None self.croppedImage = None self.fig1 = Figure() self.ax1 = self.fig1.add_subplot(131) self.ax1.set_axis_off() # pixelNode self.ax2 = self.fig1.add_subplot(132) self.ax2.set_axis_off() # CostGraph self.ax3 = self.fig1.add_subplot(133) self.ax3.set_axis_off() self.canvas = FigureCanvasTkAgg(self.fig1, master=master) self.canvas.mpl_connect('button_press_event', self.on_click) self.mouseEvent = self.canvas.mpl_connect('motion_notify_event', self.get_cursor_position) self.canvas.show() self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) self.startDrawContour = False self.shownContour = False self.firstpt = True self.currentPath = [] self.lastClickPt = None self.savedClicked = [] self.pixelGraphTemplate = None self.pixelGraphSP = None self.ann_cross = [] self.ann_line = [] self.gettingPath = False self.testPt = [] self.temp_line = [] self.colorbar = [] self.cropped = False frame.pack() def reInit(self): self.cropped = False self.startDrawContour = False self.shownContour = False self.firstpt = True self.currentPath = [] self.lastClickPt = None self.savedClicked = [] self.pixelGraphTemplate = None self.pixelGraphSP = None self.ann_cross = [] self.ann_line = [] self.gettingPath = False self.testPt = [] self.temp_line = [] for bar in self.colorbar: bar.remove() self.colorbar = [] # self.ax2.clear() # self.ax3.clear() def closeContour(self): if self.contour[0][0] != self.contour[-1][0] or self.contour[0][ 1] != self.contour[-1][1]: if len(self.temp_line) > 0: self.temp_line[-1].remove() else: print len(self.temp_line) self.pixelGraphSP = self.Pixelgraph(self.grayImgNp, self.colorImgNp) self.pixelGraphSP.buildMST(self.contour[-1][0], self.contour[-1][1]) y, x = self.contour[0][1], self.contour[0][0] self.currentPath = self.pixelGraphSP.findShortestPath(x, y) self.contour = self.contour + self.currentPath self.ax1.hold('on') line, = self.ax1.plot([pt[1] for pt in self.currentPath], [pt[0] for pt in self.currentPath], color='blue') self.temp_line.append(line) self.canvas.draw() def cropImage(self): if self.cropped is False: self.closeContour() mask = np.zeros(self.grayImgNp.shape) tempContour = np.array(self.contour) tempContour[:, [0, 1]] = tempContour[:, [1, 0]] cv2.drawContours(mask, [tempContour], 0, 255, -1) self.croppedImage = np.ones(self.colorImgNp.shape) * 255 self.croppedImage[mask == 255, :] = self.colorImgNp[mask == 255, :] self.croppedImage = self.croppedImage.astype('uint8') self.ax1.clear() self.ax1.imshow(self.croppedImage) self.ax1.set_axis_off() self.temp_line = [] self.canvas.draw() self.cropped = True def saveCropped(self): self.cropImage() imgFilenameList = self.imgFileName.split('.') initialfile = imgFilenameList[0].split( '/')[-1] + '_cropped.' + imgFilenameList[-1] filename = tkFileDialog.asksaveasfilename(initialdir=self.imgPath, initialfile=initialfile, title="Save file") cv2.imwrite(filename, cv2.cvtColor(self.croppedImage, cv2.COLOR_BGR2RGB)) # def readtestPt(self): # csvFile = 'test.csv' # self.testPt = [] # with open(csvFile, 'r') as csvin: # csvreader = csv.reader(csvin, delimiter=',') # for line in csvreader: # self.testPt.append((int(line[0]), int(line[1]))) def loadContour(self): if self.imgPath is not None: filename = tkFileDialog.askopenfilename( initialdir=self.imgPath, title="Select Contour File", filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) self.contour = np.loadtxt(filename) self.ax1.plot([pt[1] for pt in self.contour], [pt[0] for pt in self.contour], color='blue') def pathTree(self): print 'pathTree' def minPath(self): print 'minPath' def draw_contour(self): self.startDrawContour = True def stop_contour(self): print 'stop drawing' self.startDrawContour = False def hidden_contour(self): print 'hidden contour' if self.startDrawContour is False: if self.shownContour is True: for cross in self.ann_cross: cross.set_visible(not cross.get_visible()) for line in self.ann_line: line.set_visible(not line.get_visible()) self.canvas.draw() self.shownContour = False def show_contour(self): if self.shownContour is False: for cross in self.ann_cross: cross.set_visible(not cross.get_visible()) for line in self.ann_line: line.set_visible(not line.get_visible()) self.canvas.draw() self.shownContour = True self.canvas.draw() def remove_old_contour(self): self.contour = [] self.startDrawContour = False self.currentPath = [] self.savedClicked = [] self.lastClickPt = None self.pixelGraphSP = None self.shownContour = False for cross in self.ann_cross: cross.remove() for line in self.ann_line: line.remove() self.canvas.draw() def on_click(self, event): if event.dblclick: # end drawing print 'end drawing' if event.inaxes is not None: self.startDrawContour = False else: if event.inaxes is not None: if self.startDrawContour: self.shownContour = True print 'start drawing' y, x = int(event.xdata), int(event.ydata) print x, y for bar in self.colorbar: bar.remove() self.colorbar = [] self.pixelGraphSP = self.Pixelgraph( self.grayImgNp, self.colorImgNp) self.pixelGraphSP.buildMST(x, y) # print self.contour # print self.currentPath self.contour = self.contour + self.currentPath self.currentPath = [] cross, = self.ax1.plot(y, x, '+', color='red') costMap = self.pixelGraphSP.costMap() im = self.ax3.imshow(costMap) bar = self.fig1.colorbar(im) self.ax2.clear() neighborMap = self.pixelGraphSP.nodeNeighbor(x, y) self.ax2.imshow(neighborMap) self.ax2.set_title('Node and cost') self.ax2.set_axis_off() # self.ax2.grid(True) # self.ax2.grid(which='minor', color='black', linestyle='-', linewidth=2) self.colorbar.append(bar) self.ax3.set_title('Cost to each pixel') self.ax3.set_axis_off() self.canvas.draw() self.lastClickPt = (x, y) self.ann_cross.append(cross) self.savedClicked.append([y, x]) self.ann_line.append(self.temp_line[-1]) self.temp_line = [] self.canvas.draw() # self.ann_cross.append(cross) # self.ax2.imshow(self.pixelGraphSP.costMap()) # self.fig1.colorbar(im) # self.canvas.draw() else: print 'Clicked ouside axes bounds but inside plot window' # # def update_plot(self): # v = self.servo.getVelocity() # t = self.servo.getTorque() # self.add_point(self.velocity_line, v) # self.add_point(self.torque_line, t) # self.after(100, self.update_plot) # def draw_test(self): # self.readtestPt() # msttimeList = [] # pathtimeList = [] # for idx, pt in enumerate(self.testPt): # nextpt = None # if idx == (len(self.testPt) - 1): # nextpt = self.testPt[0] # else: # nextpt = self.testPt[idx + 1] # print idx, pt # mstTime, pathTime = self.plotPt(pt, nextpt) # msttimeList.append(mstTime) # pathtimeList.append(pathTime) # print 'MST time' # print msttimeList # print 'Path time' # print pathtimeList # def plotPt(self, pt, nextpt): # print 'start drawing' # # if self.lastClickPt is None: # self.pixelGraphSP = copy.deepcopy(self.pixelGraphTemplate) # mstT0 = time.time() # self.pixelGraphSP.buildMST(pt[0],pt[1]) # mstTime = time.time()-mstT0 # print self.currentPath # pathT0 = time.time() # self.currentPath = self.pixelGraphSP.findShortestPath(nextpt[0], nextpt[1]) # pathTime = time.time()-pathT0 # self.contour = self.contour + self.currentPath # cross = self.ax1.plot(nextpt[1], nextpt[0], '+', c='red') # line = self.ax1.plot([p[1] for p in self.currentPath], [p[0] for p in self.currentPath], c='blue') # self.canvas.draw() # time.sleep(10) # # return mstTime, pathTime def get_cursor_position(self, event): if self.startDrawContour: if self.lastClickPt is not None: if event.inaxes is not None: if self.gettingPath is False: self.gettingPath = True if len(self.temp_line) > 0: self.temp_line[-1].remove() else: print len(self.temp_line) print 'cursor:' y, x = int(event.xdata), int(event.ydata) self.currentPath = self.pixelGraphSP.findShortestPath( x, y) self.ax1.hold('on') line, = self.ax1.plot( [pt[1] for pt in self.currentPath], [pt[0] for pt in self.currentPath], color='blue') self.temp_line.append(line) self.canvas.draw() self.gettingPath = False else: print 'Cursor ouside axes bounds but inside plot window' def pil2cv(self): self.grayImgNp = np.array(self.imgPIL.convert('L')) self.colorImgNp = np.array(self.imgPIL.convert('RGB')) def fileOpen(self): self.reInit() filename = tkFileDialog.askopenfilename(initialdir=self.curPath, title="Select file") print filename path, fname = os.path.split(os.path.abspath(filename)) self.imgPath = path self.imgFileName = filename # print self.imgFileName self.imgPIL = Image.open(filename) self.imgTk = ImageTk.PhotoImage(self.imgPIL) self.pil2cv() # self.pixelGraphTemplate = self.Pixelgraph(self.grayImgNp, self.colorImgNp) # self.tkImg = PhotoImage(filename=filename) # print self.img self.show_img_only() self.showEdgeMap = False # # def tkimFromCv2(self, img): # if len(img.shape) == 3 and img.shape[2] == 3: # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # img = Image.fromarray(img) # img = ImageTk.PhotoImage(img) # self.tkImg = img # # # # # class pixel_Graph: # # def __init__(self, img): # def LiveWireDP(self, x, y): # pixelGraph = self.pixelGraph(self.grayImgNp) # # self.canvas.draw() def inBoundary(self, x, y): size = self.grayImgNp.shape if x > size[0] or x < 0: return False elif y > size[1] or y < 0: return False return True def save_contour(self): initialfile = self.imgFileName.split('.')[0].split( '/')[-1] + '_contour.csv' filename = tkFileDialog.asksaveasfilename(initialdir=self.imgPath, initialfile=initialfile, title="Save file") print filename np.savetxt(filename, self.contour, dtype=int) def show_img_only(self): # self.ax1.clear() # print self.img.shape # self.tkImg = self.tkimFromCv2(self.img) self.ax1.clear() # if self.grayImgNp.shape[0] * self.grayImgNp.shape[1] > (300*300): # if self.grayImgNp.shape[1] > self.grayImgNp.shape[0]: # self.grayImgNp = np.array(cv2.resize(self.grayImgNp, (300, self.grayImgNp.shape[1]*300/self.grayImgNp.shape[0]))) # self.colorImgNp = np.array(cv2.resize(self.colorImgNp, # (300, self.grayImgNp.shape[1] * 300 / self.grayImgNp.shape[0]))) # else: # self.grayImgNp = np.array(cv2.resize(self.grayImgNp, # (self.grayImgNp.shape[0] * 300 / self.grayImgNp.shape[1], 300))) # self.colorImgNp = np.array(cv2.resize(self.colorImgNp, # (self.grayImgNp.shape[0] * 300 / self.grayImgNp.shape[1], 300))) self.ax1.imshow(self.colorImgNp, 'gray', interpolation="nearest") self.ax1.set_axis_off() self.canvas.draw() # self.canvas.create_image(50, 10, image=self.tkImg, anchor=NW) # self.canvas.draw() # self.canvas.create_image(20,20, anchor=NW, image=self.imgTk) class Pixelgraph: class pixelNode: def __init__(self, x, y): self.x = x self.y = y self.neighbors = None # state: -1 = initial # 0 = expanded # 1 = active self.state = -1 self.totalCost = 0 self.prevNode = None self.drawn = False def __init__(self, grayimg, colorimg): self.grayimg = grayimg self.colorimg = colorimg self.pixelNodeList2D = {} self.startpt = None self.built_MST = False self.noNeighbor = 8 edgeDetectorList = np.array([ # (-1,-1) [ [[0, 1, 0], [-1, 0, 0], [0, 0, 0]], # (-1,0) [[1, 0, -1], [1, 0, -1], [0, 0, 0]], # (-1,1) [[0, 1, 0], [0, 0, -1], [0, 0, 0]] ], # (0,-1) [ [[1, 1, 0], [0, 0, 0], [-1, -1, 0]], # (0,0) [[1, 1, 1], [1, 1, 1], [1, 1, 1]], # (0,1) [[0, 1, 1], [0, 0, 0], [0, -1, -1]] ], # (1,-1) [ [[0, 0, 0], [1, 0, 0], [0, -1, 0]], # (1,0) [[0, 0, 0], [1, 0, -1], [1, 0, -1]], # (1,1) [[0, 0, 0], [0, 0, 1], [0, -1, 0]] ] ]).astype('float') # edgeDetectorListOrth = np.array([ # # (-1,-1) # [[[1, 0, 0], # [0, -1, 0], # [0, 0, 0]], # # (-1,0) # [[1, 1, 1], # [-1, -1, -1], # [0, 0, 0]], # # (-1,1) # [[0, 0, 1], # [0, -1, 0], # [0, 0, 0]]], # # (0,-1) # [[[1, -1, 0], # [1, -1, 0], # [1, -1, 0]], # # (0,0) # [[1, 1, 1], # [1, 1, 1], # [1, 1, 1]], # # (0,1) # [[0, 1, -1], # [0, 1, -1], # [0, 1, -1]]], # # (1,-1) # [[[0, 0, 0], # [0, -1, 0], # [1, 0, 0]], # # (1,0) # [[0, 0, 0], # [1, 1, 1], # [-1,-1, -1]], # # (1,1) # [[0, 0, 0], # [0, 1, 0], # [0, 0, -1]]]]).astype('float') def normalizationOfFilter(filter): sumOfFilter = 0 for r in filter: for c in r: sumOfFilter += abs(c) normalized = filter * (1 / sumOfFilter) # print normalized return normalized def multipleLength(filters): result = [] for r in range(3): tempEdgeList = [] for c in range(3): if abs(r - c) % 2 == 0: tempEdgeList.append( normalizationOfFilter(filters[r, c]) * np.sqrt(2)) else: tempEdgeList.append( normalizationOfFilter(filters[r, c])) result.append(tempEdgeList) return np.array(result) self.edgeDetector = multipleLength( normalizationOfFilter(edgeDetectorList)) # self.edgeDetectorOrth = multipleLength(normalizationOfFilter(edgeDetectorListOrth)) self.edgeMap = [] for r in range(3): tempEdgeList = [] for c in range(3): edgeCost = np.zeros(self.grayimg.shape) for color in range(3): convEdge = np.abs( signal.convolve2d(colorimg[:, :, color], self.edgeDetector[r, c], boundary='symm', mode='same')) edgeCost += (max(convEdge.ravel()) - convEdge) # convEdgeOrth = np.abs(signal.convolve2d(colorimg[:,:,color], self.edgeDetectorOrth[r,c], boundary='symm', mode='same')) # edgeCost += convEdgeOrth tempEdgeList.append(edgeCost / 3) self.edgeMap.append(tempEdgeList) self.edgeMap = np.array(self.edgeMap) # print self.edgeMap.shape for i in range(grayimg.shape[0]): for j in range(grayimg.shape[1]): pixelNode = self.pixelNode(i, j) pixelNode.neighbors = self.buildNeighbor(i, j) self.pixelNodeList2D[(i, j)] = pixelNode def buildNeighbor(self, i, j): neighbor = {} for r in range(3): x = i + r - 1 for c in range(3): y = j + c - 1 if not (r == 1 and c == 1): if self.inBoundary(x, y): neighbor[(x, y)] = self.edgeMap[r, c, i, j] return neighbor # using heapdict # def buildMST(self, startx, starty): # print 'building MST' # mstT0 = time.time() # heap = heapdict() # self.startpt = (startx, starty) # # entry_finder = {} # # REMOVED = '<removed-task>' # # counter = itertools.count() # # # # def remove_task(task): # # 'Mark an existing task as REMOVED. Raise KeyError if not found.' # # entry = entry_finder.pop(task) # # entry[-1] = REMOVED # # # # def add_task(task, priority=0): # # 'Add a new task or update the priority of an existing task' # # if task in entry_finder: # # remove_task(task) # # count = next(counter) # # entry = [priority, count, task] # # entry_finder[task] = entry # # heappush(pq, entry) # for neighCoor, neighCost in self.pixelNodeList2D[self.startpt].neighbors.iteritems(): # heap[neighCoor] = neighCost # self.pixelNodeList2D[neighCoor].totalCost = neighCost # self.pixelNodeList2D[neighCoor].prevNode = self.startpt # # while len(heap) > 0: # # print 'deq' # # deqt0 = time.time() # qCoor, qCost = heap.popitem() # # mark q as EXPANDED (state = 0) # self.pixelNodeList2D[qCoor].state = 0 # self.pixelNodeList2D[qCoor].totalCost = qCost # for rCoor, rCost in self.pixelNodeList2D[qCoor].neighbors.iteritems(): # rState = self.pixelNodeList2D[rCoor].state # if rState != 0: # if rState == -1: # self.pixelNodeList2D[rCoor].prevNode = qCoor # self.pixelNodeList2D[rCoor].totalCost = qCost + rCost # heap[rCoor] = qCost + rCost # self.pixelNodeList2D[rCoor].state = 1 # else: # if self.pixelNodeList2D[rCoor].totalCost > (self.pixelNodeList2D[qCoor].totalCost + rCost): # self.pixelNodeList2D[rCoor].prevNode = qCoor # self.pixelNodeList2D[rCoor].totalCost = qCost + rCost # heap[rCoor] = qCost + rCost # # deqTime = time.time() - deqt0 # # print deqTime # self.pixelNodeList2D[self.startpt].prevNode = None # mstTime = time.time() - mstT0 # print mstTime # self.built_MST = True def buildMST(self, startx, starty): print 'building MST' mstT0 = time.time() heap = Fibonacci_heap() self.startpt = (startx, starty) heapTempGraph = {} for neighCoor, neighCost in self.pixelNodeList2D[ self.startpt].neighbors.iteritems(): heapTempGraph[neighCoor] = heap.enqueue(value=neighCoor, priority=neighCost) self.pixelNodeList2D[neighCoor].totalCost = neighCost self.pixelNodeList2D[neighCoor].prevNode = self.startpt while heap.m_size != 0: # print 'deq' # deqt0 = time.time() q = heap.dequeue_min() # mark q as EXPANDED (state = 0) self.pixelNodeList2D[q.m_elem].state = 0 self.pixelNodeList2D[q.m_elem].totalCost = q.m_priority for rCoor, rCost in self.pixelNodeList2D[ q.m_elem].neighbors.iteritems(): rState = self.pixelNodeList2D[rCoor].state if rState != 0: if rState == -1: self.pixelNodeList2D[rCoor].prevNode = q.m_elem self.pixelNodeList2D[ rCoor].totalCost = self.pixelNodeList2D[ q.m_elem].totalCost + rCost heapTempGraph[rCoor] = heap.enqueue( value=rCoor, priority=self.pixelNodeList2D[rCoor].totalCost) self.pixelNodeList2D[rCoor].state = 1 else: if self.pixelNodeList2D[ rCoor].totalCost > self.pixelNodeList2D[ q.m_elem].totalCost + rCost: self.pixelNodeList2D[rCoor].prevNode = q.m_elem self.pixelNodeList2D[ rCoor].totalCost = self.pixelNodeList2D[ q.m_elem].totalCost + rCost heap.decrease_key( heapTempGraph[rCoor], self.pixelNodeList2D[rCoor].totalCost) # deqTime = time.time() - deqt0 # print deqTime self.pixelNodeList2D[self.startpt].prevNode = None mstTime = time.time() - mstT0 print mstTime self.built_MST = True # def buildMST(self, startx, starty): # print 'building MST' # mstT0 = time.time() # heap = FibonacciHeap() # self.startpt = (startx, starty) # for neighCoor, neighCost in self.pixelNodeList2D[self.startpt].neighbors.iteritems(): # print neighCoor, neighCost # heap.insert(key=neighCost, value=neighCoor) # self.pixelNodeList2D[neighCoor].totalCost = neighCost # self.pixelNodeList2D[neighCoor].prevNode = self.startpt # # # while heap is not None: # q = heap.extract_min() # # mark q as EXPANDED (state = 0) # self.pixelNodeList2D[q.value].state = 0 # self.pixelNodeList2D[q.value].totalCost = q.key # print 'q:' # print q.value, q.key # for rCoor, rCost in self.pixelNodeList2D[q.value].neighbors.iteritems(): # rState = self.pixelNodeList2D[rCoor].state # print 'r' # print rCoor, rCost # if rState != 0: # if rState == -1: # self.pixelNodeList2D[rCoor].prevNode = q.value # self.pixelNodeList2D[rCoor].totalCost = self.pixelNodeList2D[q.value].totalCost + rCost # heap.insert(key=self.pixelNodeList2D[rCoor].totalCost, value=rCoor) # self.pixelNodeList2D[rCoor].state = 1 # else: # if self.pixelNodeList2D[rCoor].totalCost > self.pixelNodeList2D[q.value].totalCost + rCost: # self.pixelNodeList2D[rCoor].prevNode = q.value # self.pixelNodeList2D[rCoor].totalCost = self.pixelNodeList2D[q.value].totalCost + rCost # heap.updateByValue(rCoor, self.pixelNodeList2D[rCoor].totalCost) # mstTime = time.time() - mstT0 # print mstTime # self.built_MST = True def findShortestPath(self, endx, endy): print 'Time for Shortest Path:' t0 = time.time() if self.built_MST: endpt = (endx, endy) nextpt = endpt pathTemp = [] numOfpt = 0 while (nextpt[0] != self.startpt[0] or nextpt[1] != self.startpt[1]): nextpt = self.pixelNodeList2D[nextpt].prevNode pathTemp.append(nextpt) numOfpt += 1 if nextpt is None: break path = [] while len(pathTemp) != 0: path.append(pathTemp.pop()) timeUsed = time.time() - t0 print timeUsed return path def costMap(self): costImg = np.zeros(self.grayimg.shape) for i in range(self.grayimg.shape[0]): for j in range(self.grayimg.shape[1]): costImg[i, j] = self.pixelNodeList2D[(i, j)].totalCost return costImg # # def neighborNode(self, x, y): # print 'test' # neighborImg = np.zeros((9,9,3)) # for i in range(9): # xq = i / 3 - 1 # for j in range(9): # yq = j / 3 - 1 # if i % 3 == 1 and j % 3 == 1: # neighborImg[i,j] = self.colorimg[x+xq,y+yq,:] # else: # xr = i % 3 - 1 # yr = j % 3 - 1 # edge = self.pixelNodeList2D[(x+xq,y+yq)].neighbors[(x+xr, y+yr)] # neighborImg[i,j] = np.repeat(edge, 3) # return neighborImg def nodeNeighbor(self, x, y): neighborImg = np.zeros((9, 9, 3)) for i in range(9): for j in range(9): if i % 3 == 1 and j % 3 == 1: neighborImg[i, j] = self.colorimg[(x - (i / 3) - 1), (y - (j / 3) - 1), :] else: neighborImg[i, j] = ( self.edgeMap[i % 3, j % 3, (x - (i / 3) - 1), (y - (j / 3) - 1)] * 255 / max(self.edgeMap[i % 3, j % 3].ravel()) * np.ones( (3, ))) return neighborImg.astype('uint8') def inBoundary(self, x, y): size = self.grayimg.shape if x >= size[0] or x < 0: return False elif y >= size[1] or y < 0: return False return True
def __init__(self): super(Window, self).__init__() self.setGeometry(0, 0, 1000, 800) mainLayout = QtWidgets.QGridLayout() self.l1 = QtWidgets.QLabel(self) self.l1.setText('File') self.l1_input = QtWidgets.QLineEdit(self) self.l1_b1 = QtWidgets.QPushButton('...', self) self.directory = self.l1_b1.clicked.connect(self.openFile) self.load_b3 = QtWidgets.QPushButton('Load Data', self) self.load_b3.clicked.connect(self.readFile) self.l2 = QtWidgets.QLabel(self) self.l2.setText('Signal') self.combo_box = QComboBox(self) self.combo_box.addItems(['Fx', 'Fx1', 'Fx2', 'Fx3', 'Thrust']) # self.signal = self.l2_cb.currentText() self.plot_b2 = QtWidgets.QPushButton('Plot', self) # self.plot_b2.clicked.connect(self.plot) self.plot_b2.pressed.connect(self.find) figure1 = Figure() figure2 = Figure() figure3 = Figure() figure4 = Figure() canvas1 = FigureCanvas(figure1) canvas2 = FigureCanvas(figure2) canvas3 = FigureCanvas(figure3) canvas4 = FigureCanvas(figure4) self.ax1 = figure1.add_subplot(111) self.ax2 = figure2.add_subplot(111) self.ax3 = figure3.add_subplot(111) self.ax4 = figure4.add_subplot(111) toolbar1 = NavigationToolbar(canvas1, self) toolbar2 = NavigationToolbar(canvas2, self) toolbar3 = NavigationToolbar(canvas3, self) toolbar4 = NavigationToolbar(canvas4, self) mainLayout.addWidget(self.l1, 0, 0) mainLayout.addWidget(self.l1_input, 0, 1) mainLayout.addWidget(self.l1_b1, 0, 2) mainLayout.addWidget(self.load_b3, 0, 3) mainLayout.addWidget(self.l2, 1, 0) mainLayout.addWidget(self.combo_box, 1, 1) mainLayout.addWidget(self.plot_b2, 1, 2) mainLayout.addWidget(toolbar1, 2, 0) mainLayout.addWidget(toolbar2, 2, 1) mainLayout.addWidget(toolbar3, 4, 0) mainLayout.addWidget(toolbar4, 4, 1) mainLayout.addWidget(canvas1, 3, 0) mainLayout.addWidget(canvas2, 3, 1) mainLayout.addWidget(canvas3, 5, 0) mainLayout.addWidget(canvas4, 5, 1) self.setLayout(mainLayout) self.setWindowTitle("Dashboard")
def vis_points(run=None, d=None, sdata_file=None, y_target=0, seed=None, blocksize=None, highlight_block=None): if d is None: d = exp_dir(run) if sdata_file is not None: with open(sdata_file, 'rb') as f: sdata = pickle.load(f) for fname in [ "true.xxx", ] + sorted(os.listdir(d)): if fname == "true.xxx": X = sdata.SX elif not fname.startswith("step") or not fname.endswith("_X.npy"): continue else: X = np.load(os.path.join(d, fname)) try: ix_fname = fname.replace("_X", "_IX") IX = np.load(os.path.join(d, ix_fname)) except: IX = None fig = Figure(dpi=144, figsize=(14, 14)) fig.patch.set_facecolor('white') ax = fig.add_subplot(111) cmap = "jet" sargs = {} if y_target == -1: # plot "wrongness" c = np.sqrt(np.sum((X - sdata.SX)**2, axis=1)) cmap = "hot" elif y_target == -2 or y_target == -3: # plot blocks c = np.zeros((X.shape[0])) if y_target == -2: np.random.seed(seed) sdata.cluster_rpc(blocksize) else: centers = grid_centers(blocksize) sdata.set_centers(centers) cmap = "prism" if highlight_block is not None: block_colors = np.ones((len(sdata.block_idxs), )) * 0.4 block_colors[highlight_block] = 0.0 else: block_colors = np.linspace(0.0, 1.0, len(sdata.block_idxs)) block_idxs = sdata.reblock(X) for i, idxs in enumerate(block_idxs): c[idxs] = block_colors[i] #c = np.sqrt(np.sum((X - sdata.SX)**2, axis=1)) elif sdata_file is None: c = None else: c = sdata.SY[:, y_target:y_target + 1].flatten() sargs['vmin'] = -3.0 sargs['vmax'] = 3.0 npts = len(X) xmax = np.sqrt(npts) X *= xmax if IX is not None: IX *= xmax ax.scatter(IX[:, 0], IX[:, 1], alpha=1.0, c="black", s=25, marker='o', linewidths=0.0, **sargs) ax.scatter(X[:, 0], X[:, 1], alpha=1.0, c=c, cmap=cmap, s=70, marker='.', linewidths=0.0, **sargs) ax.set_xlim((0, xmax)) ax.set_ylim((0, xmax)) ax.set_yticks([20, 40, 60, 80, 100]) ax.tick_params(axis='x', labelsize=30) ax.tick_params(axis='y', labelsize=30) canvas = FigureCanvasAgg(fig) out_name = os.path.join(d, fname[:-4] + ".png") fig.savefig(out_name, bbox_inches="tight") print "wrote", out_name print "generating movie...:" cmd = "avconv -f image2 -r 5 -i step_%05d_X.png -qscale 28 gprf.mp4".split( " ") import subprocess p = subprocess.Popen(cmd, cwd=d) p.wait() print "done"
def abrirArchivo(): direccionArchivo = askopenfilename() strDireccionArchivo.set("Direccion del archivo: " + direccionArchivo) tamanoSegmento = 0 tamanoLetras = 0 palabra = "" wavePalabra = read_wave(direccionArchivo) primerSegmentoLetras = [] primerSegmentoLetras.append(wavePalabra.segment(start=0, duration=0.5)) frecuenciasSegmentos = [300, 400, 500, 600] frecuenciasNumeroLetras = [2000, 2600, 2300, 3200, 3500, 2900, 3800] tolerancia = 10 for segmento in primerSegmentoLetras: espectroSegmento = segmento.make_spectrum() frecuenciasDominantes = [] i = 0 for amplitudEspectral in espectroSegmento.hs: if numpy.abs(amplitudEspectral) > 500: frecuenciasDominantes.append(espectroSegmento.fs[i]) i = i + 1 sizeSegmento = 0 cantidadLetras = 0 for frecuencia in frecuenciasDominantes: for frecuenciaDTMF in frecuenciasSegmentos: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: sizeSegmento = frecuenciaDTMF for frecuenciaDTMF in frecuenciasNumeroLetras: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: cantidadLetras = frecuenciaDTMF if sizeSegmento == 300: tamanoSegmento = 0.3 elif sizeSegmento == 400: tamanoSegmento = 0.4 elif sizeSegmento == 500: tamanoSegmento = 0.5 elif sizeSegmento == 600: tamanoSegmento = 0.6 if cantidadLetras == 2000: tamanoLetras = 2 elif cantidadLetras == 2600: tamanoLetras = 3 elif cantidadLetras == 2300: tamanoLetras = 4 elif cantidadLetras == 3200: tamanoLetras = 5 elif cantidadLetras == 3500: tamanoLetras = 6 elif cantidadLetras == 2900: tamanoLetras = 7 elif cantidadLetras == 3800: tamanoLetras = 8 segmentoLetras = [] for i in range(tamanoLetras): segmentoLetras.append( wavePalabra.segment(start=0.5 + i * tamanoSegmento, duration=tamanoSegmento)) frecuenciaLetras = [ 2000, 5600, 9200, 2400, 6000, 9600, 2800, 6400, 10000, 3200, 6800, 10400, 3600, 7200, 10800, 4000, 7600, 11200, 4400, 8000, 11600, 4800, 8400, 12000, 5200, 8800 ] for segmento in segmentoLetras: espectroSegmento = segmento.make_spectrum() frecuenciasDominantes = [] i = 0 for amplitudEspectral in espectroSegmento.hs: if numpy.abs(amplitudEspectral) > 500: frecuenciasDominantes.append(espectroSegmento.fs[i]) i = i + 1 letras = 0 for frecuencia in frecuenciasDominantes: for frecuenciaDTMF in frecuenciaLetras: if frecuencia > frecuenciaDTMF - tolerancia and frecuencia < frecuenciaDTMF + tolerancia: letras = frecuenciaDTMF if letras == 2000: palabra = palabra + "A" elif letras == 5600: palabra = palabra + "B" elif letras == 9200: palabra = palabra + "C" elif letras == 2400: palabra = palabra + "D" elif letras == 6000: palabra = palabra + "E" elif letras == 9600: palabra = palabra + "F" elif letras == 2800: palabra = palabra + "G" elif letras == 6400: palabra = palabra + "H" elif letras == 10000: palabra = palabra + "I" elif letras == 3200: palabra = palabra + "J" elif letras == 6800: palabra = palabra + "K" elif letras == 10400: palabra = palabra + "L" elif letras == 3600: palabra = palabra + "M" elif letras == 7200: palabra = palabra + "N" elif letras == 10800: palabra = palabra + "O" elif letras == 4000: palabra = palabra + "P" elif letras == 7600: palabra = palabra + "Q" elif letras == 11200: palabra = palabra + "R" elif letras == 4400: palabra = palabra + "S" elif letras == 8000: palabra = palabra + "T" elif letras == 11600: palabra = palabra + "U" elif letras == 4800: palabra = palabra + "V" elif letras == 8400: palabra = palabra + "W" elif letras == 12000: palabra = palabra + "X" elif letras == 5200: palabra = palabra + "Y" elif letras == 8800: palabra = palabra + "W" strSecuencia.set("Palabra contenida en el audio: " + palabra) figure = Figure(figsize=(5, 3), dpi=100) figure.add_subplot(111).plot(wavePalabra.ts, wavePalabra.ys) canvas = FigureCanvasTkAgg(figure, master=principal) canvas.draw() canvas.get_tk_widget().pack()
class GraphFrame(wx.Frame): """ The main frame of the application """ def __init__(self, state): wx.Frame.__init__(self, None, -1, state.title) self.state = state self.data = [] for i in range(len(state.fields)): self.data.append([]) self.paused = False self.create_main_panel() self.Bind(wx.EVT_IDLE, self.on_idle) self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(1000 * self.state.tickresolution) def create_main_panel(self): from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) self.close_button = wx.Button(self.panel, -1, "Close") self.Bind(wx.EVT_BUTTON, self.on_close_button, self.close_button) self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.close_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(1) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) def init_plot(self): self.dpi = 100 import pylab, numpy from matplotlib.figure import Figure self.fig = Figure((6.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = [] if len(self.data[0]) == 0: max_y = min_y = 0 else: max_y = min_y = self.data[0][0] for i in range(len(self.data)): p = self.axes.plot( self.data[i], linewidth=1, color=self.state.colors[i], label=self.state.fields[i], )[0] self.plot_data.append(p) if len(self.data[i]) != 0: min_y = min(min_y, min(self.data[i])) max_y = max(max_y, max(self.data[i])) # create X data self.xdata = numpy.arange(-self.state.timespan, 0, self.state.tickresolution) self.axes.set_xbound(lower=self.xdata[0], upper=0) if min_y == max_y: self.axes.set_ybound(min_y, max_y + 0.1) def draw_plot(self): """ Redraws the plot """ import numpy, pylab state = self.state if len(self.data[0]) == 0: print("no data to plot") return vhigh = max(self.data[0]) vlow = min(self.data[0]) for i in range(1, len(self.plot_data)): vhigh = max(vhigh, max(self.data[i])) vlow = min(vlow, min(self.data[i])) ymin = vlow - 0.05 * (vhigh - vlow) ymax = vhigh + 0.05 * (vhigh - vlow) if ymin == ymax: ymax = ymin + 0.1 ymin = ymin - 0.1 self.axes.set_ybound(lower=ymin, upper=ymax) self.axes.grid(True, color='gray') pylab.setp(self.axes.get_xticklabels(), visible=True) pylab.setp(self.axes.get_legend().get_texts(), fontsize='small') for i in range(len(self.plot_data)): ydata = numpy.array(self.data[i]) xdata = self.xdata if len(ydata) < len(self.xdata): xdata = xdata[-len(ydata):] self.plot_data[i].set_xdata(xdata) self.plot_data[i].set_ydata(ydata) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_close_button(self, event): self.redraw_timer.Stop() self.Destroy() def on_idle(self, event): import time time.sleep(self.state.tickresolution * 0.5) def on_redraw_timer(self, event): # if paused do not add data, but still redraw the plot # (to respond to scale modifications, grid change, etc.) # state = self.state if state.close_graph.wait(0.001): self.redraw_timer.Stop() self.Destroy() return while state.child_pipe.poll(): state.values = state.child_pipe.recv() if self.paused: return for i in range(len(self.plot_data)): if state.values[i] is not None: self.data[i].append(state.values[i]) while len(self.data[i]) > len(self.xdata): self.data[i].pop(0) for i in range(len(self.plot_data)): if state.values[i] is None or len(self.data[i]) < 2: return self.axes.legend(state.fields, loc='upper left', bbox_to_anchor=(0, 1.1)) self.draw_plot()
import numpy import sys matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure if sys.version_info[0] < 3: import Tkinter as Tk else: import tkinter as Tk root = Tk.Tk() f = Figure(figsize=(5, 4), dpi=100) ax = f.add_subplot(111) ax.set_xlabel("Parties") ax.set_ylabel("Votes") ax.set_xticks([0, 1, 2]) ax.set_xticklabels(['Democrats', 'Republicans', 'Swing']) _data = (data.blue, data.red, data.swing) ind = numpy.arange(3) width = .5 ax.bar(ind, _data, width) canvas = FigureCanvasTkAgg(f, master=root) canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) v = Tk.IntVar()
def doChooch(self, elt, edge, scan_directory, archive_directory, prefix): """ Descript. : """ symbol = "_".join((elt, edge)) scan_file_prefix = os.path.join(scan_directory, prefix) archive_file_prefix = os.path.join(archive_directory, prefix) if os.path.exists(scan_file_prefix + ".raw"): i = 1 while os.path.exists(scan_file_prefix + "%d.raw" % i): i = i + 1 scan_file_prefix += "_%d" % i archive_file_prefix += "_%d" % i scan_file_raw_filename = os.path.extsep.join((scan_file_prefix, "raw")) archive_file_raw_filename = os.path.extsep.join( (archive_file_prefix, "raw")) scan_file_efs_filename = os.path.extsep.join((scan_file_prefix, "efs")) archive_file_efs_filename = os.path.extsep.join( (archive_file_prefix, "efs")) scan_file_png_filename = os.path.extsep.join((scan_file_prefix, "png")) archive_file_png_filename = os.path.extsep.join( (archive_file_prefix, "png")) try: if not os.path.exists(scan_directory): os.makedirs(scan_directory) if not os.path.exists(archive_directory): os.makedirs(archive_directory) except: logging.getLogger("HWR").exception( "EMBLEnergyScan: could not create energy scan result directory." ) self.store_energy_scan() self.emit("energyScanFailed", ()) return try: scan_file_raw = open(scan_file_raw_filename, "w") archive_file_raw = open(archive_file_raw_filename, "w") except: logging.getLogger("HWR").exception( "EMBLEnergyScan: could not create energy scan result raw file") self.store_energy_scan() self.emit("energyScanFailed", ()) return else: scanData = [] for i in range(len(self.scanData)): x = float(self.scanData[i][0]) x = x < 1000 and x * 1000.0 or x y = float(self.scanData[i][1]) scanData.append((x, y)) scan_file_raw.write("%f,%f\r\n" % (x, y)) archive_file_raw.write("%f,%f\r\n" % (x, y)) scan_file_raw.close() archive_file_raw.close() self.scanInfo["scanFileFullPath"] = str(scan_file_raw_filename) pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = \ PyChooch.calc(scanData, elt, edge, scan_file_efs_filename) rm = (pk + 30) / 1000.0 pk = pk / 1000.0 savpk = pk ip = ip / 1000.0 comm = "" #IK TODO clear this self.scanInfo['edgeEnergy'] = 0.1 self.thEdge = self.scanInfo['edgeEnergy'] logging.getLogger("HWR").info( "th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" % (self.thEdge, pk, ip, rm)) #should be better, but OK for time being self.thEdgeThreshold = 0.01 if math.fabs(self.thEdge - ip) > self.thEdgeThreshold: pk = 0 ip = 0 rm = self.thEdge + 0.03 comm = "Calculated peak (%f) is more that 10eV away from the " + \ "theoretical value (%f). Please check your scan" % \ (savpk, self.thEdge) logging.getLogger("HWR").warning("EnergyScan: calculated peak " + \ "(%f) is more that 20eV %s the theoretical value (%f). " + \ "Please check your scan and choose the energies manually" % \ (savpk, (self.thEdge - ip) > 0.02 and "below" or "above", self.thEdge)) try: fi = open(scan_file_efs_filename) fo = open(archive_file_efs_filename, "w") except: self.store_energy_scan() self.emit("energyScanFailed", ()) return else: fo.write(fi.read()) fi.close() fo.close() self.scanInfo["peakEnergy"] = pk self.scanInfo["inflectionEnergy"] = ip self.scanInfo["remoteEnergy"] = rm self.scanInfo["peakFPrime"] = fpPeak self.scanInfo["peakFDoublePrime"] = fppPeak self.scanInfo["inflectionFPrime"] = fpInfl self.scanInfo["inflectionFDoublePrime"] = fppInfl self.scanInfo["comments"] = comm chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip( *chooch_graph_data) chooch_graph_x = list(chooch_graph_x) for i in range(len(chooch_graph_x)): chooch_graph_x[i] = chooch_graph_x[i] / 1000.0 #logging.getLogger("HWR").info("EMBLEnergyScan: Saving png" ) # prepare to save png files title = "%s %s %s\n%.4f %.2f %.2f\n%.4f %.2f %.2f" % \ ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) fig = Figure(figsize=(15, 11)) ax = fig.add_subplot(211) ax.set_title("%s\n%s" % (scan_file_efs_filename, title)) ax.grid(True) ax.plot(*(zip(*scanData)), **{"color": 'black'}) ax.set_xlabel("Energy") ax.set_ylabel("MCA counts") ax2 = fig.add_subplot(212) ax2.grid(True) ax2.set_xlabel("Energy") ax2.set_ylabel("") handles = [] handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue')) handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red')) canvas = FigureCanvasAgg(fig) self.scanInfo["jpegChoochFileFullPath"] = str( archive_file_png_filename) try: logging.getLogger("HWR").info("Rendering energy scan and Chooch " + \ "graphs to PNG file : %s", scan_file_png_filename) canvas.print_figure(scan_file_png_filename, dpi=80) except: logging.getLogger("HWR").exception("could not print figure") try: logging.getLogger("HWR").info("Saving energy scan to archive " +\ "directory for ISPyB : %s", archive_file_png_filename) canvas.print_figure(archive_file_png_filename, dpi=80) except: logging.getLogger("HWR").exception("could not save figure") self.store_energy_scan() logging.getLogger("HWR").info("<chooch> returning") self.emit('choochFinished', (pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title)) return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, \ chooch_graph_y1, chooch_graph_y2, title
# png 파일로 저장시 # plt.savefig("test1.png") # figure 생성 # First let's set the backend without using mpl.use() from the scripting layer # create a new figure fig = Figure() # fig 를 백엔드에 연결 # associate fig with the backend canvas = FigureCanvasAgg(fig) # subplot: figure 에 들어 있는 plot 들 # subplot 추가 한다. # add a subplot to the fig # ax = fig.add_subplot(111) # 2x1 에서 첫번째에 plot 추가한다. ax = fig.add_subplot(2, 1, 1) # 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') # 새 그래프 생성 # create a new figure plt.figure() # o 마커를 이용해서 x=3,y=2 지점에 점찍기 # plot the point (3,2) using the circle marker plt.plot(3, 2, 'o') # 현재 축(설정) 가져오기