def plot_dco_values(ax, values, color="k"): interpol1 = {"temperature": values["temperature"][0:7], "values": values["values"][0:7]} fit1 = pylab.polyfit(interpol1["temperature"], interpol1["values"], 1) print "m={} b={}".format(fit1[0], fit1[1]) fit_fn1 = pylab.poly1d(fit1) interpol2 = {"temperature": values["temperature"][6:14], "values": values["values"][6:14]} fit2 = pylab.polyfit(interpol2["temperature"], interpol2["values"], 1) print "m={} b={}".format(fit2[0], fit2[1]) fit_fn2 = pylab.poly1d(fit2) plot = ax.plot( interpol1["temperature"], fit_fn1(interpol1["temperature"]), "k-", interpol2["temperature"], fit_fn2(interpol2["temperature"]), "k-", # values['temperature'], values['values'], '{}-'.format(color), values["temperature"], values["values"], "{}o".format(color), markersize=5, ) pylab.setp(plot[0], linewidth=2) pylab.setp(plot[1], linewidth=2) return plot
def trace(data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1, num=1, last=True, fontmap = None, verbose=1): """ Generates trace plot from an array of data. :Arguments: data: array or list Usually a trace from an MCMC sample. name: string The name of the trace. datarange: tuple or list Preferred y-range of trace (defaults to (None,None)). format (optional): string Graphic output format (defaults to png). suffix (optional): string Filename suffix. path (optional): string Specifies location for saving plots (defaults to local directory). fontmap (optional): dict Font map for plot. """ if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4} # Stand-alone plot or subplot? standalone = rows==1 and columns==1 and num==1 if standalone: if verbose>0: print_('Plotting', name) figure() subplot(rows, columns, num) pyplot(data.tolist()) ylim(datarange) # Plot options title('\n\n %s trace'%name, x=0., y=1., ha='left', va='top', fontsize='small') # Smaller tick labels tlabels = gca().get_xticklabels() setp(tlabels, 'fontsize', fontmap[rows/2]) tlabels = gca().get_yticklabels() setp(tlabels, 'fontsize', fontmap[rows/2]) if standalone: if not os.path.exists(path): os.mkdir(path) if not path.endswith('/'): path += '/' # Save to file savefig("%s%s%s.%s" % (path, name, suffix, format))
def bar_plot_raw(inF): ouF = inF + '.pdf' X = [] Y = [] inFile = open(inF) for line in inFile: line = line.strip() fields = line.split('\t') X.append(int(fields[0])) #Y.append(math.log(int(fields[1])+1,2)) Y.append(int(fields[1])) fig = pl.figure() N = len(X) ax = fig.add_subplot(111) ax.set_xlim(0,N + 1) ax.set_xticks(range(0,N+2)) ax.set_xticklabels([0,1] + ['']*(N-1) + [max(X)]) ax.bar(range(1,N+1), Y, align='center') ax.set_xlabel('Start position in the protein') ax.set_ylabel('Number of peptides') pl.setp(ax.get_xticklines(),visible=False) pl.setp(ax.get_xticklabels(),fontsize=6) ax.get_children()[2].set_color('g') ax.get_children()[3].set_color('r') pl.savefig(ouF) inFile.close()
def barGraph(data, **kw): """Draws a bar graph for the given data""" from pylab import bar kw.setdefault('barw', 0.5) kw.setdefault('log', 0) kw.setdefault('color', 'blue') xs = [i+1 for i, row in enumerate(data)] names, ys = zip(*data) names = [n.replace('_', '\n') for n in names] #print 'got xs %s, ys %s, names %s' % (xs, ys, names) bar(xs, ys, width=kw['barw'], color=kw['color'], align='center', log=kw['log']) ax = pylab.gca() def f(x, pos=None): n = int(x) - 1 if n+1 != x: return '' if n < 0: return '' try: return names[n] except IndexError: return '' ax.xaxis.set_major_formatter(pylab.FuncFormatter(f)) ax.xaxis.set_major_locator(pylab.MultipleLocator(1)) ax.set_xlim(0.5, len(names)+0.5) for l in ax.get_xticklabels(): pylab.setp(l, rotation=90) start = 0.08, 0.18 pos = (start[0], start[1], 0.99-start[0], 0.95-start[1]) ax.set_position(pos)
def cmap_plot(cmdLine): pylab.figure(figsize=[5,10]) a=outer(ones(10),arange(0,1,0.01)) subplots_adjust(top=0.99,bottom=0.00,left=0.01,right=0.8) maps=[m for m in cm.datad if not m.endswith("_r")] maps.sort() l=len(maps)+1 for i, m in enumerate(maps): print m subplot(l,1,i+1) pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[]) imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower") pylab.text(100.85,0.5,m,fontsize=10) # render plot if cmdLine: pylab.show(block=True) else: pylab.ion() pylab.plot([]) pylab.ioff() status = 1 return status
def init_plot(self): self.dpi = 100 self.fig = Figure((8.0, 8.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') self.axes.set_ylabel('Encoder Values', fontsize = 15) self.axes.set_xlabel('Reading Step', fontsize = 15) pylab.setp(self.axes.get_xticklabels(), fontsize = 8) pylab.setp(self.axes.get_yticklabels(), fontsize = 8) self.plot_data = self.axes.plot( self.data, linewidth = 1, color=(0, 1, 0), label = "Left Encoder" )[0] self.plot_data2 = self.axes.plot( self.data2, linewidth = 1, color = (1, 0, 0), label = "Right Encoder" )[0] self.axes.legend(bbox_to_anchor = (0.5, 1.0), loc = 8, prop = {'size' : 10.0}, borderaxespad = 0.)
def _add_graph(self, data): x = False if self._decimate: x, data = self._decimate_data(data, self._bins) ax = self._fig.add_axes([self._margin * 2, # left 1 - self._margin - self._client_space / self._total_height * (self._counter + 1), # bottom self._client_space - self._margin, # width self._client_space / self._total_height * 0.9 # height ], **self._axprops) if x: ax.plot(x, data) else: ax.plot(data) self._counter += 1 if self._counter == 1: self._axprops['sharex'] = ax if self._counter < self._total_height: pylab.setp(ax.get_xticklabels(), visible=False) return ax
def _draw_solution(self): """ plot the current solution on our optional visualization """ myg = self.grids[self.current_level].grid v = self.grids[self.current_level].get_var("v") pylab.imshow( numpy.transpose(v[myg.ilo : myg.ihi + 1, myg.jlo : myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax], ) # pylab.xlabel("x") pylab.ylabel("y") if self.current_level == self.nlevels - 1: pylab.title(r"solving $L\phi = f$") else: pylab.title(r"solving $Le = r$") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, "ymajorticklabels") pylab.setp(cl, fontsize="small")
def _draw_main_error(self): """ plot the error with respect to the true solution on our optional visualization """ myg = self.grids[self.nlevels - 1].grid v = self.grids[self.nlevels - 1].get_var("v") e = v - self.true_function(myg.x2d, myg.y2d) pylab.imshow( numpy.transpose(e[myg.ilo : myg.ihi + 1, myg.jlo : myg.jhi + 1]), interpolation="nearest", origin="lower", extent=[self.xmin, self.xmax, self.ymin, self.ymax], ) pylab.xlabel("x") pylab.ylabel("y") pylab.title(r"current fine grid error") formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(format=formatter, shrink=0.5) cb.ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(cb.ax, "ymajorticklabels") pylab.setp(cl, fontsize="small")
def group_plots(ylist, ncols, x = None, titles = None, suptitle = None, ylabels = None, figsize = None, sameyscale = True, order='C', imkw={}): import pylab as pl nrows = np.ceil(len(ylist)/float(ncols)) figsize = ifnot(figsize, (2*ncols,2*nrows)) fh, axs = pl.subplots(int(nrows), int(ncols), sharex=True, sharey=bool(sameyscale), figsize=figsize) ymin,ymax = data_range(ylist) axlist = axs.ravel(order=order) for i,f in enumerate(ylist): x1 = ifnot(x, range(len(f))) _im = axlist[i].plot(x1,f,**imkw) if titles is not None: pl.setp(axlist[i], title = titles[i]) if ylabels is not None: pl.setp(axlist[i], ylabel=ylabels[i]) if suptitle: pl.suptitle(suptitle) return
def plot_commerror(name1,logfile1,name2,logfile2): file1 = open(str(logfile1),'r').readlines() data1 = [float(line.split()[1]) for line in file1] iso1 = data1[0::3] aniso1 = data1[1::3] ml1 = data1[2::3] file2 = open(str(logfile2),'r').readlines() data2 = [float(line.split()[1]) for line in file2] iso2 = data2[0::3] aniso2 = data2[1::3] ml2 = data2[2::3] # x axis x=[8,16,32,64,128] xlabels=['A','B','C','D','E'] orderone = [1,.5,.25,.125,.0625] ordertwo = [i**2 for i in orderone] plot1 = pylab.figure(figsize = (6, 6.5)) size = 15 ax = pylab.subplot(111) ax.plot(x,iso1, linestyle='solid',color='red',lw=2) ax.plot(x,aniso1, linestyle='dashed',color='red',lw=2) ax.plot(x,ml1, linestyle='dashdot',color='red',lw=2) ax.plot(x,iso2, linestyle='solid',color='blue',lw=2) ax.plot(x,aniso2, linestyle='dashed',color='blue',lw=2) ax.plot(x,ml2, linestyle='dashdot',color='blue',lw=2) #ax.plot(x,orderone, linestyle='solid',color='black',lw=2) #ax.plot(x,ordertwo, linestyle='dashed',color='black') #pylab.legend((str(name1)+'_iso',str(name1)+'_aniso',str(name2)+'_iso',str(name2)+'_aniso','order 1'),loc="best") pylab.legend((str(name1)+'_iso',str(name1)+'_aniso',str(name1)+'_ml',str(name2)+'_iso',str(name2)+'_aniso',str(name2)+'_ml'),loc="best") leg = pylab.gca().get_legend() ltext = leg.get_texts() pylab.setp(ltext, fontsize = size, color = 'black') frame=leg.get_frame() frame.set_fill(False) frame.set_visible(False) #ax.grid("True") for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(size) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(size) # set axes to logarithmic pylab.gca().set_xscale('log',basex=2) pylab.gca().set_yscale('log',basex=2) pylab.axis([8,128,1.e-4,2]) ax.set_xticks(x) ax.set_xticklabels(xlabels) #pylab.axis([1,5,1.e-6,1.]) ax.set_xlabel('Mesh resolution', ha="center",fontsize=size) ax.set_ylabel('commutation error',fontsize=size) pylab.savefig('commerrorplot.eps') pylab.savefig('commerrorplot.pdf') return
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 init_plot(self): self.dpi = 150 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') self.axes.set_title('Accelerometer Values', size=12) 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_data1 = self.axes.plot( self.data1, linewidth=1, color=(1, 1, 0), )[0] self.plot_data2 = self.axes.plot( self.data2, linewidth=1, color=(1, 0, 1), )[0] self.plot_data3 = self.axes.plot( self.data3, linewidth=1, color=(0, 1, 1), )[0]
def __init__(self,parent): self.data_t = [0] self.data_y = [0] self.data_y2 = [0] self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) pylab.setp(self.axes.get_xticklabels(), fontsize=10) pylab.setp(self.axes.get_yticklabels(), fontsize=10) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data_t,self.data_y,'y', self.data_t,self.data_y2,'c', ) ymin = -30 ymax = 30 self.axes.set_ybound(lower=ymin, upper=ymax) self.axes.set_xlim(0, 20) self.axes.grid(True) FigCanvas.__init__(self, parent, -1, self.fig) self.drawing = False
def draw_plot(self): if len(self.data_t) < 2: return if self.data_t[-1] < self.data_t[-2]: del self.data_t[:-1] del self.data_y[:-1] del self.data_y2[:-1] self.axes.set_xlim(self.data_t[-1],self.data_t[-1]+20) return T1 = self.data_t[-1] xmin, xmax = self.axes.get_xlim() if T1 > xmax: self.axes.set_xlim(xmax,xmax+20) del self.data_t[:-2] del self.data_y[:-2] del self.data_y2[:-2] pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data[0].set_data(self.data_t, self.data_y) self.plot_data[1].set_data(self.data_t, self.data_y2) if not self.drawing: self.drawing = True self.draw() self.drawing = False
def default_frame31shareX(self, data_label, x_tpl, y1_tpl, y2_tpl, y3_tpl, pltstyle_dict): x, labelx = x_tpl y1, label1 = y1_tpl y2, label2 = y2_tpl y3, label3 = y3_tpl pylab.subplots_adjust(hspace=0.001) self.ax1 = pylab.subplot(311) self.ax1.plot(x, y1, label=data_label, **pltstyle_dict) pylab.ylabel(label1, fontsize=20, horizontalalignment='left') pylab.yticks(fontsize=13) #self.ax1.yaxis.set_label_coords(-.12, 0.5) self.ax1.yaxis.set_label_coords(-.10, 0.25) pylab.ylim(-30, -10) self.ax1.legend() self.ax2 = pylab.subplot(312, sharex=self.ax1) self.ax2.plot(x, y2, **pltstyle_dict) self.ax2.yaxis.tick_right() pylab.ylim(0, 3) self.ax2.yaxis.set_label_coords(1.12, 0.5) pylab.ylabel(label2, fontsize=20) self.ax3 = pylab.subplot(313, sharex=self.ax1) self.ax3.plot(x, y3, **pltstyle_dict) xticklabels = self.ax1.get_xticklabels()+self.ax2.get_xticklabels() pylab.setp(xticklabels, visible=False) pylab.ylabel(label3, fontsize=20) pylab.xlabel(labelx, fontsize=20) pylab.xticks(fontsize=13)
def __init__(self, ticker): gtk.VBox.__init__(self) startdate = datetime.date(2001, 1, 1) today = enddate = datetime.date.today() date1 = datetime.date(2011, 1, 1) date2 = datetime.date.today() mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter("%b %d") # Eg, Jan 12 dayFormatter = DateFormatter("%d") # Eg, 12 quotes = quotes_historical_yahoo(ticker, date1, date2) if len(quotes) == 0: raise SystemExit fig = Figure(facecolor="white", figsize=(5, 4), dpi=100) fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) candlestick(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment="right") canvas = FigureCanvas(fig) # a gtk.DrawingArea self.pack_start(canvas) toolbar = NavigationToolbar(canvas, win) self.pack_start(toolbar, False, False)
def plot_tide_gauge(fname,gaugeno='?'): if gaugeno=='?': try: gaugeno = int(fname[:7]) except: pass t,tsec,predicted,residual = read_tide_gauge(fname) fig = pylab.figure(1) pylab.clf() ax1 = pylab.subplot(211) pylab.plot(t,predicted,'k') pylab.plot(t,predicted+residual,'b') t1 = t[0] t1s = '%s/%s/%s' % (t1.month,t1.day,t1.year) t2 = t[-1] t2s = '%s/%s/%s' % (t2.month,t2.day,t2.year) # rotate and align the tick labels so they look better pylab.title('Gauge %s, From %s to %s' % (gaugeno,t1s,t2s)) #pylab.legend(['Predicted','Observed']) pylab.setp( ax1.get_xticklabels(), visible=False) pylab.subplot(212,sharex=ax1) pylab.plot(t,residual,'k') fig.autofmt_xdate() pylab.title('Residual')
def plot_aggregate_results(wf_name, data): aggr = lambda results: int(interval_statistics(results if len(results) > 0 else [0.0])[0]) # aggr = lambda results: len(results) data = data[wf_name] bins = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] value_map = {b: [] for b in bins} for d in data: fcount = d["result"]["overall_failed_tasks_count"] makespan = d["result"]["makespan"] value_map[fcount].append(makespan) values = [bin for bin, values in sorted(value_map.items(), key=lambda x: x[0]) for _ in values] plt.grid(True) n, bins, patches = pylab.hist(values, bins, histtype='stepfilled') pylab.setp(patches, 'facecolor', 'g', 'alpha', 0.75) values = [aggr(values) for bin, values in sorted(value_map.items(), key=lambda x: x[0])] rows = [[str(v) for v in values]] the_table = plt.table(cellText=rows, rowLabels=None, colLabels=bins, loc='bottom') pass
def plot_the_correlation(): # First, delete any existing regression line plots from the figure global handle_of_regression_line_plot pylab.setp(handle_of_regression_line_plot,visible=False) #### Next, calculate and plot the stats number_of_points = scipy.shape(coords_array)[0] x_coords = coords_array[:,0] # Python starts counting from zero y_coords = coords_array[:,1] #### To get the best-fit line, we'll do a regression slope, y_intercept, r_from_regression, p_from_regression, std_err = ( scipy.stats.linregress(x_coords,y_coords) ) #### Plot the best-fit line in red handle_of_regression_line_plot = pylab.plot(axis_range*scipy.array([-1,1]), y_intercept + slope*axis_range*scipy.array([-1,1]),'r-') #### Uncomment the next two lines if you want to verify #### that the stats we get from regression and from correlation are the same. # r_from_corr,p_from_corr = scipy.stats.pearsonr(x_coords,y_coords) # print r_from_regression,r_from_corr,p_from_regression,p_from_corr #### In order to make the p-values format nicely #### even when they have a bunch of zeros at the start, we do this: p_value_string = "%1.2g" % p_from_regression pylab.xlabel(str(number_of_points) + ' points: ' + ' p-value of corr = ' + p_value_string + ' Correlation, r = ' + str(round(r_from_regression,2)) ) # The ',2' means show 2 decimal places # Set the axis back to its original value, in case Python has changed it during plotting pylab.axis('equal') # Make the tick-marks equally spaced on x- and y-axes pylab.axis(axis_range*scipy.array([-1, 1, -1, 1]))
def buildAtmos(self, secz, xlim=[300, 1100], doPlot=False): """Generate the total atmospheric transmission profile at this airmass, using the coefficients C.""" # Burke paper says atmosphere put together as # Trans_total (alt/az/time) = Tgray * (e^-Z*tau_aerosol(alt/az/t)) * # * (1 - C_mol * BP(t)/BPo * A_mol(Z)) -- line 2 # * (1 - sqrt(C_mol * BP(t)/BPo) * A_mol(Z)) -- 3 # * (1 - C_O3 * A_O3(A) ) # * (1 - C_H2O(alt/az/time) * A_H2O(Z)) # Tau_aerosol = trans['aerosol'] ... but replace with power law (because here all 1's) # typical power law index is about tau ~ lambda^-1 # A_mol = trans['O2'] # secz = secz of this observation # wavelen / atmo_templates == building blocks of atmosphere, with seczlist / atmo_ind keys # C = coeffsdictionary = to, t1, t2, alpha0 (for aerosol), C_mol, BP, C_O3, C_H2O values if (abs(secz - self.secz) > interplimit): print "Generating interpolated atmospheric absorption profiles for this airmass %f" %(secz) self.interpolateSecz(secz) BP0 = 782 # mb # set aerosol appropriately with these coefficients self.atmo_abs['aerosol'] = 1.0 - numpy.exp(-secz * (self.C['t0'] + self.C['t1']*0.0 + self.C['t2']*0.0) * (self.wavelen/675.0)**self.C['alpha']) # set total transmission, with appropriate coefficients self.trans_total = numpy.ones(len(self.wavelen), dtype='float') self.trans_total = self.trans_total * (1.0 - self.C['mol'] * self.C['BP']/BP0 * self.atmo_abs['rayleigh']) \ * ( 1 - numpy.sqrt(self.C['mol'] * self.C['BP']/BP0) * self.atmo_abs['O2']) \ * ( 1 - self.C['O3'] * self.atmo_abs['O3']) \ * ( 1 - self.C['H2O'] * self.atmo_abs['H2O']) \ * ( 1 - self.atmo_abs['aerosol']) # now we can plot the atmosphere if doPlot: pylab.figure() pylab.subplot(212) colorindex = 0 for comp in self.atmo_ind: pylab.plot(self.wavelen, self.atmo_abs[comp], colors[colorindex], label='%s' %(comp)) colorindex = self._next_color(colorindex) leg =pylab.legend(loc=(0.88, 0.3), fancybox=True, numpoints=1, shadow=True) ltext = leg.get_texts() pylab.setp(ltext, fontsize='small') coefflabel = "" for comp in ('mol', 't0', 'alpha', 'O3', 'H2O'): coefflabel = coefflabel + "C[%s]:%.2f " %(comp, self.C[comp]) if (comp=='alpha') | (comp=='mol'): coefflabel = coefflabel + "\n" pylab.figtext(0.2, 0.35, coefflabel, fontsize='small') pylab.xlim(xlim[0], xlim[1]) pylab.ylim(0, 1.0) pylab.xlabel("Wavelength (nm)") pylab.subplot(211) pylab.plot(self.wavelen, self.atmo_trans[self.seczToString(1.2)]['comb'], 'r-', label='Standard X=1.2 (no aerosols)') pylab.plot(self.wavelen, self.trans_total, 'k-', label='Observed') leg = pylab.legend(loc=(0.12, 0.05), fancybox=True, numpoints=1, shadow=True) ltext = leg.get_texts() pylab.setp(ltext, fontsize='small') pylab.xlim(xlim[0], xlim[1]) pylab.ylim(0, 1.0) pylab.title("Example Atmosphere at X=%.2f" %(secz)) return
def trace(data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1, num=1, last=True, fontmap = {1:10, 2:8, 3:6, 4:5, 5:4}, verbose=1): # Internal plotting specification for handling nested arrays # Stand-alone plot or subplot? standalone = rows==1 and columns==1 and num==1 if standalone: if verbose>0: print 'Plotting', name figure() subplot(rows, columns, num) pyplot(data.tolist()) ylim(datarange) # Plot options if last: xlabel('Iteration', fontsize='x-small') ylabel(name, fontsize='x-small') # Smaller tick labels tlabels = gca().get_xticklabels() setp(tlabels, 'fontsize', fontmap[rows]) tlabels = gca().get_yticklabels() setp(tlabels, 'fontsize', fontmap[rows]) if standalone: if not os.path.exists(path): os.mkdir(path) if not path.endswith('/'): path += '/' # Save to file savefig("%s%s%s.%s" % (path, name, suffix, format))
def plot_data(data_, O, P, save=False): assert len(data_) == 2 # Coarse, fine. colors = ["r", "b"] i = 0 p.figure() p.xlabel("$\mu \, (\mathrm{GeV})$", fontsize=16) label = str(O + 1) + str(P + 1) p.ylabel("$\sigma_{0}$".format("{" + label + "}"), fontsize=16) legend = () # Interpolate raw data. for data in data_: x_, y_, s_, x, y, s = interpolation(data, O, P) dada = p.plot(x, y, "o", x_, y_(x_), "-") # , # x_, y_(x_)+s_(x_), '--', x_, y_(x_)-s_(x_), '--') legend += (dada[1],) p.setp(dada, color=colors[i]) i += 1 # Continuum extrapolate interpolated data. x_, y, s = continuum_extrap(data_[0], data_[1], O, P) dada = p.plot(x_, y, "-") # , x_, y+s, '--', x_, y-s, '--') legend += (dada[0],) p.setp(dada, color="green") p.legend(legend, ("$a=0.116 \, \mathrm{fm}$", "$a=0.088 \, \mathrm{fm}$", "$a=0$"), "best") # Output. if save: root = "/Users/atlytle/Dropbox/TeX_docs/soton/SUSY_BK/exceptional/figs" p.savefig(root + "/sigma_exceptional_{0}.pdf".format(label)) else: p.show()
def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = [] for n in range(self.numplots): self.axes.append(self.fig.add_subplot(1,self.numplots,n)) self.axes[n].set_title('SAS Temperature Data', size=12) pylab.setp(self.axes[n].get_xticklabels(), fontsize=8) pylab.setp(self.axes[n].get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = [] labels = self.datagen.labels for n in range(len(self.data)): self.plot_data.append([]) for i in range(len(self.data[n])): self.plot_data[n].append(self.axes[n].plot(np.arange(10), linewidth=1, label=labels[n][i], #color=(1, 1, 0), #let it auto-select colors )[0]) self.axes[n].legend(loc='best',fontsize=6,ncol=6) self.plot_index = 0
def plot_data(yRange=None): ''' Plots and saves the cell measurement data. Returns nothing. ''' fig = plt.figure(figsize=(18,12)) ax = plt.subplot(111) plt.errorbar(range(len(avgCells.index)), avgCells[column], yerr=stdCells[column], fmt='o') ax = plt.gca() ax.set(xticks=range(len(avgCells.index)), xticklabels=avgCells.index) xlims = ax.get_xlim() ax.set_xlim([lim-1 for lim in xlims]) # adjust yRange if it was specified if yRange!=None: ax.set_ylim(yRange) fileName = column + ' exlcuding outliers' else: fileName = column plt.subplots_adjust(bottom=0.2, right=0.98, left=0.05) plt.title(column) plt.ylabel('mm') locs, labels = plt.xticks() plt.setp(labels, rotation=90) mng = plt.get_current_fig_manager() mng.window.state('zoomed') #plt.show() path1 = 'Y:/Test data/ACT02/vision inspection/plot_100_cells/' path2 = 'Y:/Nate/git/nuvosun-python-lib/vision system/plot_100_cells/' fig.savefig(path1 + fileName, bbox_inches = 'tight') fig.savefig(path2 + fileName, bbox_inches = 'tight') plt.close()
def plot_clusters(locations, idx, centroids): locations = np.array(locations) print "the cluster labels ", idx plot( locations[idx == 0, 0], locations[idx == 0, 1], "ob", locations[idx == 1, 0], locations[idx == 1, 1], "or", locations[idx == 2, 0], locations[idx == 2, 1], "ok", locations[idx == 3, 0], locations[idx == 3, 1], "oc", locations[idx == 4, 0], locations[idx == 4, 1], "oy", locations[idx == 5, 0], locations[idx == 5, 1], "om", locations[idx == 6, 0], locations[idx == 6, 1], "og", ) plot(centroids[:, 0], centroids[:, 1], "sg", markersize=8) setp(gca(), "ylim", reversed(getp(gca(), "ylim"))) show()
def ConfigCAngles(): pylab.figure(figsize=(3.5, 3.5)) pylab.axes((0.0, 0.0, 1.0, 1.0)) geo = ps.LoadGeo() phi_i0 = geo.phi_i0 phi_is = geo.phi_is phi_ie = geo.phi_ie phi_o0 = geo.phi_o0 phi_os = geo.phi_os phi_oe = geo.phi_oe phi1 = np.linspace(phi_is, phi_ie, 1000) phi2 = np.linspace(phi_i0, phi_is, 1000) phi3 = np.linspace(phi_os, phi_oe, 1000) phi4 = np.linspace(phi_o0, phi_os, 1000) (xi1, yi1) = ps.coords_inv(phi1, geo, 0, "fi") (xi2, yi2) = ps.coords_inv(phi2, geo, 0, "fi") (xo1, yo1) = ps.coords_inv(phi3, geo, 0, "fo") (xo2, yo2) = ps.coords_inv(phi4, geo, 0, "fo") #### Inner and outer involutes pylab.plot(xi1, yi1, "k", lw=1) pylab.plot(xi2, yi2, "k:", lw=1) pylab.plot(xo1, yo1, "k", lw=1) pylab.plot(xo2, yo2, "k:", lw=1) ### Innver involute labels pylab.plot(xi2[0], yi2[0], "k.", markersize=5, mew=2) pylab.text(xi2[0], yi2[0] + 0.0025, "$\phi_{i0}$", size=8, ha="right", va="bottom") pylab.plot(xi1[0], yi1[0], "k.", markersize=5, mew=2) pylab.text(xi1[0] + 0.002, yi1[0], "$\phi_{is}$", size=8) pylab.plot(xi1[-1], yi1[-1], "k.", markersize=5, mew=2) pylab.text(xi1[-1] - 0.002, yi1[-1], " $\phi_{ie}$", size=8, ha="right", va="center") ### Outer involute labels pylab.plot(xo2[0], yo2[0], "k.", markersize=5, mew=2) pylab.text(xo2[0] + 0.002, yo2[0], "$\phi_{o0}$", size=8, ha="left", va="top") pylab.plot(xo1[0], yo1[0], "k.", markersize=5, mew=2) pylab.text(xo1[0] + 0.002, yo1[0], "$\phi_{os}$", size=8) pylab.plot(xo1[-1], yo1[-1], "k.", markersize=5, mew=2) pylab.text(xo1[-1] - 0.002, yo1[-1], " $\phi_{oe}$", size=8, ha="right", va="center") ### Base circle t = np.linspace(0, 2 * pi, 100) pylab.plot(geo.rb * np.cos(t), geo.rb * np.sin(t), "b-") pylab.plot(np.r_[0, geo.rb * np.cos(9 * pi / 8)], np.r_[0, geo.rb * np.sin(9 * pi / 8)], "k-") pylab.text( geo.rb * np.cos(9 * pi / 8) + 0.0005, geo.rb * np.sin(9 * pi / 8) + 0.001, "$r_b$", size=8, ha="right", va="top" ) pylab.axis("equal") pylab.setp(pylab.gca(), "ylim", (min(yo1) - 0.005, max(yo1) + 0.005)) pylab.axis("off") pylab.savefig("FixedScrollAngles.png", dpi=600) pylab.savefig("FixedScrollAngles.eps") pylab.savefig("FixedScrollAngles.pdf") pylab.close()
def init_plot(self): self.fig = Figure((4.0, 2.0), dpi=100) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('black') #self.axes.set_title('Rotation', size=12) 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.plotLinex = self.axes.plot( self.pldatLineX, linewidth=1, color=(1, 0, 0), )[0] self.plotLiney = self.axes.plot( self.pldatLineY, linewidth=1, color=(0, 1, 0), )[0] self.plotLinez = self.axes.plot( self.pldatLineZ, linewidth=1, color=(0, 0, 1), )[0] self.xmin = 0 self.xmax = 0 self.ymin = -10 self.ymax = 10
def plot_count(fname, dpi=70): # Load data date, libxc, c, code, test, doc = np.loadtxt(fname, unpack=True) zero = pl.zeros_like(date) fig = pl.figure(1, figsize=(10, 5), dpi=dpi) ax = fig.add_subplot(111) polygon(date, c + libxc + code + test, c + libxc + code + test + doc, facecolor="m", label="Documentation") polygon(date, c + libxc + code, c + libxc + code + test, facecolor="y", label="Tests") polygon(date, c + libxc, c + libxc + code, facecolor="g", label="Python-code") polygon(date, c, c + libxc, facecolor="c", label="LibXC-code") polygon(date, zero, c, facecolor="r", label="C-code") polygon(date, zero, zero, facecolor="b", label="Fortran-code") months = pl.MonthLocator() months4 = pl.MonthLocator(interval=4) month_year_fmt = pl.DateFormatter("%b '%y") ax.xaxis.set_major_locator(months4) ax.xaxis.set_minor_locator(months) ax.xaxis.set_major_formatter(month_year_fmt) labels = ax.get_xticklabels() pl.setp(labels, rotation=30) pl.axis("tight") pl.legend(loc="upper left") pl.title("Number of lines") pl.savefig(fname.split(".")[0] + ".png", dpi=dpi)
def draw_plot(self): """ Redraws the plot """ # when xmin is on auto, it "follows" xmax to produce a # sliding window effect. therefore, xmin is assigned after # xmax. # if self.xmax_control.is_auto(): xmax = len(self.data) if len(self.data) > 50 else 50 else: xmax = int(self.xmax_control.manual_value()) if self.xmin_control.is_auto(): xmin = xmax - 50 else: xmin = int(self.xmin_control.manual_value()) # for ymin and ymax, find the minimal and maximal values # in the data set and add a mininal margin. # # note that it's easy to change this scheme to the # minimal/maximal value in the current display, and not # the whole data set. # # if self.ymin_control.is_auto(): # ymin = round(min(self.data), 0) - 1 # else: # ymin = int(self.ymin_control.manual_value()) # # if self.ymax_control.is_auto(): # ymax = round(max(self.data), 0) + 1 # else: # ymax = int(self.ymax_control.manual_value()) ymin, ymax = 10.0**-1, 10.0**3 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # anecdote: axes.grid assumes b=True if any other flag is # given even if b is set to False. # so just passing the flag into the first statement won't # work. # if self.cb_grid.IsChecked(): self.axes.grid(True, color='gray') else: self.axes.grid(False) # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=self.cb_xlab.IsChecked()) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw()
img_b = np.minimum(1.0, 0.7 * peak + aura) canvas = np.concatenate((img_r, img_g, img_b), axis=2) c_field = ndimage.interpolation.zoom(secy_u[:, :, 0], 0.25, order=3, mode='wrap') c_field = ndimage.filters.gaussian_filter(c_field, 8.0, mode='wrap') c_field = ndimage.interpolation.zoom(c_field, 4.0, order=3, mode='wrap') pylab.rcParams['figure.figsize'] = (canvas_size_x / img_shrink, canvas_size_y / img_shrink) pylab.clf() pylab.imshow(canvas) if sys.argv[1] == 'big': CS = pylab.contour(c_field, [0.5], colors='blue') #pylab.clabel(CS,fontsize=0) for c in CS.collections: pylab.setp(c, linewidth=4) if t == 262144: pylab.gca().add_patch( patches.Rectangle((10200, 1450), 2000, 2000, fill=False, edgecolor='white', linewidth=8)) pylab.title('t = {}'.format(t)) pylab.savefig('images-K/{:06}.png'.format(t))
def __init__(self, parent, id, data, extent, titles, axLabel, vlimit, selMask, scale='log'): wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) FIGPROPS = dict(figsize=(5.0, (5.0 / 1.618)), dpi=64) #self.SetBackgroundColour('red') ADJUSTPROPS = dict(left=0.1, bottom=0.1, right=0.97, top=0.94, wspace=0.01, hspace=0.01) viewIdx = argwhere(selMask).flatten() viewCount = size(viewIdx) self.plotFigure = Figure(frameon=True, **FIGPROPS) self.plotFigure.set_facecolor('.82') self.plotCanvas = FigureCanvas(self, -1, self.plotFigure) self.plotFigure.subplots_adjust(**ADJUSTPROPS) fm = FigureManagerBase(self.plotCanvas, 0) _pylab_helpers.Gcf.set_active(fm) if (scale == 'linear'): plotData = data vmin = vlimit[0] vmax = vlimit[1] elif (scale == 'log'): plotData = log10(data) vmin = log10(vlimit[0]) vmax = log10(vlimit[1]) for i in range(viewCount): plotData[viewIdx[i]][data[viewIdx[i]] == 0.0] = vmin depth = ceil(float(viewCount / 2.0)) self.axes = [None] * int(viewCount) self.im = [None] * int(viewCount) if (viewCount == 1): col = 1 row = 1 elif (viewCount == 5): col = 3 row = 2 elif (viewCount % 3.0 == 0.0): col = 3 row = (int(viewCount / 3.0)) elif (viewCount % 2.0 == 0.0): col = 2 row = (int(viewCount / 2.0)) else: print 'Plot Layout Could Not Be Built' for i in range(viewCount): if i == 0: self.axes[i] = self.plotFigure.add_subplot(row, col, i + 1) else: self.axes[i] = self.plotFigure.add_subplot(row, col, i + 1, sharex=self.axes[0], sharey=self.axes[0]) self.im[i] = self.axes[i].imshow(plotData[viewIdx[i]].T, origin='lower', interpolation='nearest', extent=extent, aspect='auto', vmin=vmin, vmax=vmax) self.axes[i].set_gid(viewIdx[i]) if viewCount > 1: self.axes[i].text(0.01, .92, titles[viewIdx[i]], fontsize=14, bbox=dict(facecolor='white', alpha=0.5), transform=self.axes[i].transAxes) self.plotFigure.text(0.54, 0.01, axLabel[0], ha='center', va='bottom', fontsize=14) self.plotFigure.text(0.01, .5, axLabel[1], ha='left', va='center', rotation='vertical', fontsize=14) else: self.axes[i].set_title(titles[viewIdx[i]]) self.axes[i].set_xlabel(axLabel[0], fontsize=14) self.axes[i].set_ylabel(axLabel[1], fontsize=14) self.plotFigure.colorbar(self.im[i]) if i + 1 <= viewCount - col: setp(self.axes[i].get_xticklabels(), visible=False) if ((i + 1) % (viewCount / row) == 0.0 and viewCount != 1): setp(self.axes[i].get_yticklabels(), visible=False) self.box = Toolbar(self.plotCanvas) self.box.Hide() multiViewSizer = wx.BoxSizer(wx.HORIZONTAL) multiViewVert = wx.BoxSizer(wx.VERTICAL) multiViewSizer.Add(self.plotCanvas, 1, wx.EXPAND | wx.RIGHT | wx.LEFT, border=1) multiViewVert.Add(multiViewSizer, 1, wx.EXPAND | wx.TOP | wx.BOTTOM, border=1) self.SetSizer(multiViewVert) return
def main(): parser = Parser(description='To trace boxplot.') parser.add_argument('--prefix', '-p', help='monitor prefix name', default='result') parser.add_argument('--islands', '-n', help='number of islands', type=int, default=4) parser.add_argument('--times', '-t', help='number of times', type=int, default=30) parser.add_argument('--runs', '-r', help='number of runs', type=int, default=21) parser.add_argument('--column', '-c', help='column to select', type=int, default=2) parser.add_argument('--notplot', '-np', help='disable plotting', action='store_true') parser.add_argument('--space', '-s', help='padding between each boxplot', type=float, default=.15) parser.add_argument( '--colors', '-C', help= 'colors used in order to color each boxplot, use a comma to add more than one color', default='green,black,orange,red,blue,gray,yellow') args = parser() V = [] for i in range(args.islands): files = [] if not args.runs: fn = "%s_monitor_%d" % (args.prefix, i) logger.info("Pre-opening of run files... %s" % fn) f = open(fn) files += [(fn, f)] f.readline() # to ignore first line else: for r in range(args.runs): fn = "%s_%d_monitor_%d" % (args.prefix, r + 1, i) logger.info("Pre-opening of run files... %s" % fn) f = open(fn) files += [(fn, f)] f.readline() # to ignore first line T = [] for t in range(args.times): R = [] for fn, f in files: nbindi = int(f.readline().split()[args.column]) logger.info("Reading... %s with time... %d and nbindi %d" % (fn, t, nbindi)) R += [nbindi] T += [R] V += [T] logger.debug(V) if not args.notplot: import pylab as pl import numpy as np colors = args.colors.split(',') pos = np.linspace(args.islands / 2 * args.space, -args.islands / 2 * args.space, args.islands).T for i in range(args.islands): r = pl.boxplot(V[i], positions=[x - pos[i] for x in range(args.times)], widths=0.1) for value in r.values(): pl.setp(value, color=colors[i % len(colors)]) pl.legend( ["isl %s (%s)" % (i, colors[i]) for i in range(args.islands)]) pl.xlabel('Time') pl.ylabel('Nb individuals') pl.xticks([x for x in range(args.times)]) pl.xlim(-args.islands / 2 * args.space * 2, (args.times - 1) + args.islands / 2 * args.space * 2) pl.show()
def surface(cs, i, f, opt_ri, opt_zi, style, iplot=0): # contour_lines( F, np.arange(nx).astype(float), np.arange(ny).astype(float), # levels=[start_f]) # cs=contour( g.r, g.z, g.psi, levels=[f]) # proxy = [Rectangle((0,0),1,1,fc = 'b') # for pc in cs.collections] # # legend(proxy, ["q="+np.str(i)]) p = cs.collections[i].get_paths() # # You might get more than one contours for the same start_f. We need to keep the # closed one # vn = np.zeros(np.size(p)) # find the closed contour for k in range(np.size(p)): v = p[k].vertices vx = v[:, 0] vy = v[:, 1] if [vx[0], vy[0]] == [vx[-1], vy[-1]]: xx = vx yy = vy x = xx y = yy # v = p[0].vertices # vn[0]=np.shape(v)[0] # xx=v[:,0] # yy=v[:,1] # if np.shape(vn)[0] > 1: # for i in xrange(1,np.shape(vn)[0]): # v = p[i].vertices # vn[i]=np.shape(v)[0] # xx = [xx,v[:,0]] # yy = [yy,v[:,1]] # if np.shape(vn)[0] > 1 : # # Find the surface closest to the o-point # ind = closest_line(np.size(xx), xx, yy, opt_ri, opt_zi) # x=xx[ind] # y=yy[ind] # else: # ind = 0 # x=xx # y=yy # if iplot == 0: # plot the start_f line zc = cs.collections[i] setp(zc, linewidth=4, linestyle=style[i]) clabel(cs, [f], inline=1, fmt="%9.6f", fontsize=14) # label the level # annotate('q= '+np.str(i+1),(x[0]+.1,y[0]+.1)) draw() show(block=False) return x, y
# plot RK4 solution -- we need a step of 1.e-3 or smaller to get this # right, because that is the fastest timescale. If you go above 2.e-3, # it blows up severely tRK4, yRK4 = rk4(y0, 1.e-3, 1.0) pylab.plot(tRK4, yRK4, label=r"R-K 4, $\tau = 10^{-3}$") pylab.xlim(0.0, 0.1) pylab.xlabel("t") pylab.ylabel("y") leg = pylab.legend() ltext = leg.get_texts() pylab.setp(ltext, fontsize='small') leg.draw_frame(0) pylab.savefig("stiff-rk4-dt-1e-3.png") # now do dt = 2.5e-3 pylab.clf() pylab.plot(tt, analytic(tt), label="analytic solution") tRK4, yRK4 = rk4(y0, 2.5e-3, 1.0) pylab.plot(tRK4, yRK4, label=r"R-K 4, $\tau = 2.5\times 10^{-3}$") pylab.xlim(0.0, 0.1)
def box_plot_eigs(simResult,T=1000,N=100,estimators=['sample'],qtile=5): # function plots an inquiry of the form (estimator,T,N) with all nonzero elements # it compares the distribution of each eigenvalue with the true eigenvalue # simresult = output from simulate_eigs # estimators = estimator used to find the covariance matrix # T,N = number of samples and number of stocks # qtile = quantile of eigenvalues which to display (for visualization purposes) # convert daily variances into annualized std in % true_eigs = sd_annual(simResult[1]) for i in estimators: inq = read_inquiry((i,T,N)) if inq not in simResult[0].keys(): raise Exception('No simulations run for '+inq+' estimator') else: est_eigs = np.vstack(simResult[0][inq]) est_eigs = sd_annual(est_eigs) #@if print(est_eigs) # choose eigenvalues on qtile quantiles xcoord = np.rint(np.linspace(0,N-1,qtile)).astype(int) box_medians = np.median(est_eigs,0) # plotting part violet = "#462066" bamboo = "#DC5C05" orange = "#FF9000" fig_w = 7 fig_h = 6 lw = 1.5 plt.figure(figsize=(fig_w, fig_h), dpi=100) bp = plt.boxplot(est_eigs[:,xcoord], notch=True, widths=np.repeat(0.2,len(xcoord)).tolist(), patch_artist=True, showfliers=False, zorder=1) # change boxplots for j in range(qtile): setp(bp['boxes'][j], edgecolor=violet, fill=False, linewidth=lw) setp(bp['medians'][j], color=orange, linewidth=lw) setp(bp['whiskers'][j], color=violet, linewidth=lw,linestyle='--') setp(bp['whiskers'][j+qtile], color=violet, linewidth=lw,linestyle='--') setp(bp['caps'][j], color=violet, linewidth=lw) setp(bp['caps'][j+qtile], color=violet, linewidth=lw) #@for # draw a line with true eigenvalues plt.plot(list(range(1,qtile+1)), true_eigs[xcoord], marker="o", markerfacecolor=bamboo, markeredgecolor=bamboo, markersize=3, zorder=2) # draw titles, axes and etc. plt.title('Estimator= '+ i + ', N = ' + str(N)+', T= ' + str(T), y=1.01, fontsize=18, color='black') plt.xticks(list(range(1,qtile+1)), ['${\\lambda_{'+ str(i) + '}(\hat{\Sigma})}$' for i in xcoord+1]) plt.ylabel('Ann.Volatility(%)') # show the difference between true eigenvalues and centers of boxplots plt.fill_between(list(range(1,qtile+1)), box_medians[xcoord], true_eigs[xcoord], color='grey', alpha='0.5') # draw legend vleg = mlines.Line2D([], [], markeredgecolor=bamboo, markerfacecolor=bamboo, marker='o', linestyle='-', markersize=4, label='$\\lambda(\Sigma)$') mleg = mlines.Line2D([], [], color='grey', alpha=0.5, markeredgecolor='None', marker='s', linestyle='None', markersize=10, label='Bias') plt.legend(handles=[vleg,mleg], numpoints=1, fancybox=True, framealpha=0.25) plt.show()
def draw_plot(self): """ Redraws the plot """ # when xmin is on auto, it "follows" xmax to produce a # sliding window effect. therefore, xmin is assigned after # xmax. # if self.xmax_control.is_auto(): xmaxv = xmaxc = len(self.datav) if len(self.datav) > 50 else 50 else: xmaxv = float(self.xmax_control.manual_value()) xmaxc = float(self.xmax_control.manual_value()) if self.xmin_control.is_auto(): xminv = xminc = xmaxv - 50 else: xminv = float(self.xmin_control.manual_value()) xminc = float(self.xmin_control.manual_value()) # for ymin and ymax, find the minimal and maximal values # in the data set and add a mininal margin. # # note that it's easy to change this scheme to the # minimal/maximal value in the current display, and not # the whole data set. # if self.ymin_control.is_auto(): yminv = min(self.datav[int(xminv):int(xmaxv)]) yminc = min(self.datac[int(xminc):int(xmaxc)]) else: yminv = float(self.ymin_control.manual_value()) yminc = float(self.ymin_control.manual_value()) if self.ymax_control.is_auto(): ymaxv = max(self.datav[int(xminv):int(xmaxv)]) ymaxc = max(self.datac[int(xminc):int(xmaxc)]) else: ymaxv = float(self.ymax_control.manual_value()) ymaxc = float(self.ymax_control.manual_value()) self.axesv.set_xbound(lower=xminv, upper=xmaxv) self.axesv.set_ybound(lower=yminv, upper=ymaxv) self.axesc.set_xbound(lower=xminc, upper=xmaxc) self.axesc.set_ybound(lower=yminc, upper=ymaxc) # anecdote: axes.grid assumes b=True if any other flag is # given even if b is set to False. # so just passing the flag into the first statement won't # work. # if self.cb_grid.IsChecked(): self.axesv.grid(True, color='gray') self.axesc.grid(True, color='gray') else: self.axesv.grid(False) self.axesc.grid(False) # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axesv.get_xticklabels(), visible=self.cb_xlab.IsChecked()) pylab.setp(self.axesc.get_xticklabels(), visible=self.cb_xlab.IsChecked()) self.plot_datav.set_xdata(np.arange(len(self.datav))) self.plot_datav.set_ydata(np.array(self.datav)) self.plot_datac.set_xdata(np.arange(len(self.datac))) self.plot_datac.set_ydata(np.array(self.datac)) self.canvas.draw()
def create_grid(F, R, Z, in_settings, critical, boundary=None, iter=None, fpsi=None, fast=None): #, # f(psi) = R*Bt current function #nrad_flexible, #single_rad_grid, #xpt_mindist, xpt_mul, strictbndry,debug): # if size(nrad_flexible) == 0 : # nrad_flexible = 0 if iter == None: iter = 0 if iter > 3: print("ERROR: Too many iterations") return #, {error:1} #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; # Check the settings # If a setting is missing, set a default value # inspect.getargspec(create_grid) # if N_PARAMS() LT 3 THEN BEGIN # PRINT, "ERROR: Need at least a 2D array of psi values, R and Z arrays" # RETURN, {error:1} #ENDIF ELSE IF N_PARAMS() LT 4 THEN BEGIN # ; Settings omitted. Set defaults # print "Settings not given -> using default values" # settings = {psi_inner:0.9, # psi_outer:1.1, # nrad:36, # npol:64, # rad_peaking:0.0, # pol_peaking:0.0, # parweight:0.0} # ENDIF ELSE BEGIN # print "Checking settings" settings = in_settings # So the input isn't changed # str_check_present, settings, 'psi_inner', 0.9 # str_check_present, settings, 'psi_outer', 1.1 # str_check_present, settings, 'nrad', 36 # str_check_present, settings, 'npol', 64 # str_check_present, settings, 'rad_peaking', 0.0 # str_check_present, settings, 'pol_peaking', 0.0 # str_check_present, settings, 'parweight', 0.0 #ENDELSE s = numpy.ndim(F) s1 = numpy.shape(F) if s != 2: print("ERROR: First argument must be 2D array of psi values") return #, {error:1} nx = s1[0] ny = s1[1] s = numpy.ndim(R) s1 = numpy.size(R) if s != 1 or s1 != nx: print("ERROR: Second argument must be 1D array of major radii") return # {error:1} s = numpy.ndim(Z) s1 = numpy.size(Z) if s != 1 or s1 != ny: print("ERROR: Second argument must be 1D array of heights") return # {error:1} # Get an even number of points for efficient FFTs if nx % 2 == 1: # odd number of points in R. Cut out last point #R = R[0:(nx-1)] # H.SETO (QST) #F = F[0:(nx-1), :] # H.SETO (QST) R = R[:-1] F = F[:-1, :] nx = nx - 1 if ny % 2 == 1: # odd number of points in Z. Cut out last point #Z = Z[0:(ny-1)] # H.SETO (QST) #F = F[:,0:(ny-1)] # H.SETO (QST) Z = Z[:-1] F = F[:, :-1] ny = ny - 1 #if boundary != None:# for python3 H.SETO (QST) if not boundary is None: s = numpy.ndim(boundary) s1 = numpy.shape(boundary) if s != 2 or s1[0] != 2: print("WARNING: boundary must be a 2D array: [2, n]. Ignoring") boundary = 0 else: # Calculate indices #bndryi = numpy.zeros((2,1188)) #bndryi[0,:] = numpy.interp(bndryi[0,:], R, numpy.arange(0.,nx)) #bndryi[1,:] = numpy.interp(bndryi[1,:], Z, numpy.arange(0.,ny)) bndryi = numpy.zeros(boundary.shape, dtype=float) # H.SETO (QST) bndryi[0, :] = numpy.interp(boundary[0, :], R, numpy.arange(0., nx)) bndryi[1, :] = numpy.interp(boundary[1, :], Z, numpy.arange(0., ny)) #print(bndryi[0,:]*(R[-1]-R[0])/(nx-1.)+R[0]-boundary[0,:]) #print(bndryi[1,:]*(Z[-1]-Z[0])/(ny-1.)+Z[0]-boundary[1,:]) #if bndryi == None : # for python3 H.SETO (QST) if bndryi is None: bndryi = numpy.zeros((2, 4)) #bndryi[0,:] = [1, nx-1, nx-1, 1] # H.SETO (QST) #bndryi[1,:] = [1, 1, ny-1, ny-1] # H.SETO (QST) bndryi[0, :] = [1, nx - 2, nx - 2, 1] bndryi[1, :] = [1, 1, ny - 2, ny - 2] #;;;;;;;;;;;;;; Psi interpolation data ;;;;;;;;;;;;;; interp_data = Bunch(nx=nx, ny=ny, method=0, f=F) # Always include function if fast == 'fast': print("Using Fast settings") interp_data.method = 2 #;;;;;;;;;;;;;;; First plot ;;;;;;;;;;;;;;;; #nlev = 100 #minf = numpy.min(F) #maxf = numpy.max(F) #levels = numpy.arange(numpy.float(nlev))*(maxf-minf)/numpy.float(nlev-1) + minf Rr = numpy.tile(R, ny).reshape(ny, nx).T Zz = numpy.tile(Z, nx).reshape(nx, ny) #contour( Rr, Zz, F, levels=levels) # arrange the plot on the screen #mngr = get_current_fig_manager() #geom = mngr.window.geometry() #x,y,dx,dy = geom.getRect() #mngr.window.setGeometry(100, 100, dx, dy) #if boundary != None : #if not boundary is None : # plot(boundary[0,:],boundary[1,:],'r--') #show(block=False) #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; n_opoint = critical.n_opoint n_xpoint = critical.n_xpoint primary_opt = critical.primary_opt inner_sep = critical.inner_sep opt_ri = critical.opt_ri opt_zi = critical.opt_zi opt_f = critical.opt_f xpt_ri = numpy.array(critical.xpt_ri).flatten() xpt_zi = numpy.array(critical.xpt_zi).flatten() xpt_f = numpy.array(critical.xpt_f).flatten() # Refining x-point location is omitted H.SETO (QST) # Overplot the separatrices, O-points # oplot_critical, F, R, Z, critical # Psi normalisation factors faxis = opt_f[primary_opt] fnorm = xpt_f[inner_sep] - opt_f[primary_opt] # From normalised psi, get range of f f_inner = faxis + numpy.min(settings.psi_inner) * fnorm f_outer = faxis + numpy.max(settings.psi_outer) * fnorm # Check the number of x-points #if critical.n_xpoint == 0 : if n_xpoint == 0: #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; # Grid entirely in the core print("Generating grid entirely in the core") print("Now pyGridGen can hadle only the core") #H.SETO (QST) nrad = numpy.sum(settings.nrad) # Add up all points npol = numpy.sum(settings.npol) rad_peaking = settings.rad_peaking[0] # Just the first region pol_peaking = settings.pol_peaking[0] # work out where to put the surfaces in the core fvals = radial_grid(nrad, f_inner, f_outer, 1, 1, [xpt_f[inner_sep]], rad_peaking) fvals = fvals.flatten() # Create a starting surface (midpoint in radial direction) sind = numpy.int(old_div(nrad, 2)) start_f = fvals[sind] # contour_lines( F, numpy.arange(nx).astype(float), numpy.arange(ny).astype(float), levels=[start_f]) cs = contour(Rr, Zz, F, levels=[start_f]) p = cs.collections[0].get_paths() # # You might get more than one contours for the same start_f. We need to keep the closed one vn = numpy.zeros(numpy.size(p)) v = p[0].vertices vn[0] = numpy.shape(v)[0] xx = [v[:, 0]] yy = [v[:, 1]] if numpy.shape(vn)[0] > 1: for i in range(1, numpy.shape(vn)[0]): v = p[i].vertices vn[i] = numpy.shape(v)[0] xx.append(v[:, 0]) yy.append(v[:, 1]) #xx = [xx,v[:,0]] #yy = [yy,v[:,1]] print("PRIMARY: ", primary_opt, opt_ri[primary_opt], opt_zi[primary_opt]) if numpy.shape(vn)[0] > 1: # Find the surface closest to the o-point opt_r = numpy.interp(opt_ri[primary_opt], numpy.arange(len(R)), R) opt_z = numpy.interp(opt_zi[primary_opt], numpy.arange(len(Z)), Z) ind = closest_line(xx, yy, opt_r, opt_z) x = xx[ind] y = yy[ind] print("Contour: ", ind, opt_r, opt_z) else: ind = 0 x = xx[0] y = yy[0] # plot the start_f line zc = cs.collections[0] setp(zc, linewidth=1) clabel( cs, [start_f], # label the level inline=1, fmt='%9.6f', fontsize=14) draw() show(block=False) # ans = query_yes_no('Press enter to create grid') if ans != 1: #show() # remove unnecessary show() to prevent hang-up H.SETO sys.exit() start_ri, start_zi = transform_xy(x, y, R, Z) ## Make sure that the line goes clockwise # m = numpy.argmax( numpy.interp(start_zi, numpy.arange(Z.size).astype(float), Z)) if (numpy.gradient( numpy.interp(start_ri, numpy.arange(R.size).astype(float), R)))[m] < 0.0: # R should be increasing at the top. Need to reverse start_ri = start_ri[::-1] start_zi = start_zi[::-1] print('points reversed') ## Last point should be the same as the first # # Smooth and refine the starting location np = numpy.size(start_ri) s = 3 ar = numpy.append(numpy.append(start_ri[(np - s - 1):(np - 1)], start_ri), start_ri[1:s + 1]) start_ri = SMOOTH(ar, window_len=s)[s + 1:(np + s + 1)] az = numpy.append(numpy.append(start_zi[(np - s - 1):(np - 1)], start_zi), start_zi[1:s + 1]) start_zi = SMOOTH(az, window_len=s)[s + 1:(np + s + 1)] #r_smooth = numpy.interp(start_ri, numpy.arange(len(R)), R) #z_smooth = numpy.interp(start_zi, numpy.arange(len(Z)), Z) #plot(r_smooth,z_smooth,'r--') #draw() #raw_input() for i in range(np): ri1 = 0. # not used H.SETO zi1 = 0. # not used H.SETO out = follow_gradient(interp_data, R, Z, start_ri[i], start_zi[i], start_f, ri1, zi1) status = out.status ri1 = out.rinext # rinext = ri + integral of dri/df from start_f to target_f zi1 = out.zinext # zinext = zi + integral of dzi/df from start_f to target_f start_ri[i] = ri1 start_zi[i] = zi1 # now start_ri and start_zi on target_f-line a = grid_region(interp_data, R, Z, start_ri, start_zi, fvals, sind, npol, boundary=boundary, fpsi=fpsi, parweight=settings.parweight, oplot='oplot') # H.SETO plot(numpy.append(a.rxy[0, :], a.rxy[0, 0]), numpy.append(a.zxy[0, :], a.zxy[0, 0]), 'r') for i in range(1, nrad): plot(numpy.append(a.rxy[i, :], a.rxy[i, 0]), numpy.append(a.zxy[i, :], a.zxy[i, 0]), 'r') for i in range(0, npol - 1): plot(a.rxy[:, i], a.zxy[:, i], 'r') draw() # Get other useful variables psixy = numpy.zeros((nrad, npol)) for i in range(0, npol): psixy[:, i] = old_div((fvals - faxis), fnorm) # to get normalised psi # Calculate magnetic field components dpsidR = numpy.zeros((nrad, npol)) dpsidZ = numpy.zeros((nrad, npol)) interp_data.method = 2 for i in range(nrad): for j in range(npol): out = local_gradient(interp_data, a.rixy[i, j], a.zixy[i, j], status=0, dfdr=0., dfdz=0.) status = out.status dfdr = out.dfdr[0][0] dfdz = out.dfdz[0][0] # dfd* are derivatives wrt the indices. Need to multiply by dr/di etc dpsidR[i, j] = old_div( dfdr, numpy.interp(a.rixy[i, j], numpy.arange(R.size).astype(float), numpy.gradient(R))) dpsidZ[i, j] = old_div( dfdz, numpy.interp(a.zixy[i, j], numpy.arange(Z.size).astype(float), numpy.gradient(Z))) # Set topology to connect in the core yup_xsplit = [nrad] ydown_xsplit = [nrad] yup_xin = [0] yup_xout = [-1] ydown_xin = [0] ydown_xout = [-1] #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; # Create result structure result = Bunch( error=0, # Signal success psi_inner=settings.psi_inner, psi_outer=settings.psi_outer, # Unchanged psi range #nrad=nrad, npol=npol, #Number of points in radial and poloidal direction nrad=[nrad], npol=[ npol ], # Number of points in radial and poloidal direction (must be array) Rixy=a.rixy, Zixy=a.zixy, # Indices into R and Z of each point Rxy=a.rxy, Zxy=a.zxy, # Location of each grid point psixy=psixy, # Normalised psi for each point dpsidR=dpsidR, dpsidZ=dpsidZ, # Psi derivatives (for Bpol) faxis=faxis, fnorm=fnorm, # Psi normalisation factors settings=settings, # Settings used to create grid critical=critical, # Critical points yup_xsplit= yup_xsplit, # X index where domain splits (number of points in xin) ydown_xsplit=ydown_xsplit, yup_xin=yup_xin, yup_xout=yup_xout, # Domain index to connect to ydown_xin=ydown_xin, ydown_xout=ydown_xout) return result
def testCloudMaker(stnr, startDate, endDate, method): """Gets data from a eKlima station and smooths the data depending on which method we wish to test. We find the nash-sutcliffe to observations of clouds. And we plot and save the result to Plots folder. :param stnr: eKlima station where there is cloud cover for testing method. :param startDate: simulations and reference data from this data :param endDate: simulations and reference data to this data :param method: specify which method to be tested :return: Available methods to test: cc_from_prec ccFromAveragePrec ccFromAverageObsCc ccGammaPrec ccGammaTemp ccGammaPrecAndTemp""" wsTemp = getMetData(stnr, 'TAM', startDate, endDate, 0, 'list') wsPrec = getMetData(stnr, 'RR', startDate, endDate, 0, 'list') wsCC = getMetData(stnr, 'NNM', startDate, endDate, 0, 'list') temp, date = strip_metadata(wsTemp, get_dates=True) prec = strip_metadata(wsPrec) clouds = strip_metadata(wsCC) dayShift = 1 clouds = __shiftClouds(clouds, dayShift) if method == 'ccFromRandomThomas': estClouds = dpz.clouds_from_precipitation(prec, method='Random Thomas') gammaFigtext = 'No gamma smoothing and dayshift = {0}'.format(dayShift) elif method == 'ccFromPrec': estClouds = dpz.clouds_from_precipitation(prec, method='Binary') gammaFigtext = 'No gamma smoothing and dayshift = {0}'.format(dayShift) elif method == 'ccFromAveragePrec': estClouds = dpz.clouds_from_precipitation(prec, method='Average') gammaFigtext = 'No gamma smoothing and dayshift = {0}'.format(dayShift) elif method == 'ccFromPrecAndAveragePrec': estClouds = dpz.clouds_from_precipitation(prec, method='Binary and average') gammaFigtext = ''.format() elif method == 'ccFromAverageObsCc': estClouds = [sum(clouds)/float(len(clouds))] * len(clouds) gammaFigtext = ''.format() elif method == 'ccGammaPrec': gammaPrec = [2.8, 2., 0.3, 0.4] estClouds = dpz.clouds_from_precipitation(prec, method='Binary') estClouds = dgc.cc_gamma_smoothing(estClouds, gammaPrec) gammaFigtext = "gamma smoothing prec = {0} and dayshift = {1}".format(gammaPrec, dayShift) elif method == 'ccGammaTempChange': gammaTemp = [4.8, 1., 5., 0.03] estClouds = dgc.cc_gamma_temp(temp, gammaTemp) gammaFigtext = "gamma smoothing temp = {0} and dayshift = {1}".format(gammaTemp, dayShift) elif method == 'ccGammaPrecAndTempChange': gammaPrec = [2.8, 2., 0.3, 0.4] gammaTemp = [4.8, 1., 5., 0.03] estClouds = dgc.cc_gamma_prec_and_temp_change(prec, temp, gammaPrec, gammaTemp) gammaFigtext = "prec = {0} and temp = {1} and dayshift = {2}".format(gammaPrec, gammaTemp, dayShift) fileName = "{3} {0} {1} {2}.png".format(stnr, startDate[0:7], endDate[0:7], method) # What is the root mean square of estimatet vs observed clouds? # rms = np.sqrt(((np.array(estClouds) - np.array(clouds)) ** 2).mean()) # Nash–Sutcliffe model efficiency coefficient from # https://en.wikipedia.org/wiki/Nash%E2%80%93Sutcliffe_model_efficiency_coefficient numerator = 0 denominator = 0 mean_clouds = sum(clouds)/float(len(clouds)) for i in range(0, len(clouds), 1): numerator += (clouds[i] - estClouds[i])**2 denominator += (clouds[i] - mean_clouds)**2 nash_sutcliffe = 1 - numerator/denominator # Figure dimensions fsize = (16, 10) plt.figure(figsize=fsize) plt.clf() # plot total snowdepth on land plt.bar(date, prec, width=1, color="0.4") # plot the estimated cloud cover for i in range(0, len(estClouds) - 1, 1): if estClouds[i] > 0: plt.hlines(max(prec) * 1.2, date[i], date[i + 1], lw=45, color=str(-(estClouds[i] - 1.))) elif estClouds[i] == None: plt.hlines(max(prec) * 1.2, date[i], date[i + 1], lw=45, color="pink") else: plt.hlines(max(prec) * 1.2, date[i], date[i + 1], lw=45, color=str(-(estClouds[i] - 1.))) # plot cloud cover from met for i in range(0, len(clouds) - 1, 1): if clouds[i] > 0: plt.hlines(max(prec) * 1.1, date[i], date[i + 1], lw=45, color=str(-(clouds[i] - 1.))) elif clouds[i] == None: plt.hlines(max(prec) * 1.1, date[i], date[i + 1], lw=45, color="pink") else: plt.hlines(max(prec) * 1.1, date[i], date[i + 1], lw=45, color=str(-(clouds[i] - 1.))) # this plots temperature on separate right side axis plt.twinx() temp_pluss = [] temp_minus = [] for i in range(0, len(temp), 1): if temp[i] >= 0: temp_pluss.append(temp[i]) temp_minus.append(np.nan) else: temp_minus.append(temp[i]) temp_pluss.append(np.nan) plt.plot(date, temp, "black") plt.plot(date, temp_pluss, "red") plt.plot(date, temp_minus, "blue") # title and text fields plt.title("{3} {0} {1} {2}".format(stnr, startDate[0:7], endDate[0:7], method)) plt.text(date[len(date)/2], min(temp)*1.2, 'gamma smoothing [shape, scale, days back, amplification]') plt.text(date[len(date)/2], min(temp)*1.3, gammaFigtext) # this is a scatter plot of modelled and estimated cloud cover xfrac = 0.15 yfrac = (float(fsize[0])/float(fsize[1])) * xfrac xpos = 0.95-xfrac ypos = 0.42-yfrac a = plt.axes([xpos, ypos, xfrac, yfrac]) a.scatter(clouds, estClouds) plt.setp(a, xticks=[0, 0.5, 1], yticks=[0, 0.5, 1]) plt.text(0.0, 0.1, 'na_su = {0}'.format(round(nash_sutcliffe, 2)), color='yellow', bbox={'facecolor':'black'}) plt.savefig("{0}{1}".format(plot_folder, fileName)) return nash_sutcliffe
extent=(0, 2.0, MJDSTART, MJDSTOP), aspect=2.0 / (MJDSTOP - MJDSTART)) pylab.xlabel('Pulse Phase') pylab.ylabel('Time (MJD)') # This axis is the summed profile plot ax2 = pylab.axes([0.15, 0.65, 0.75, 0.3]) bbins = np.concatenate((profbins, profbins[1:] + 1.0)) ax2.step(bbins, np.concatenate((fullprof, fullprof, np.array([fullprof[0]]))), where='post', color='k', lw=1.5) py = np.concatenate((fullprof, fullprof)) pylab.ylabel('Photons') pylab.setp(ax2.get_xticklabels(), visible=False) pymin = py.min() - 0.1 * (py.max() - py.min()) pymax = py.max() + 0.1 * (py.max() - py.min()) #pylab.ylim(ymin=0.0) pylab.ylim((pymin, pymax)) pylab.xlim((0.0, 2.0)) #ax2.set_xticks(np.arange(20.0)/10.0) ax2.minorticks_on() #pylab.xlabel('Pulse Phase') # Add radio profile if options.radio is not None: x, y = np.loadtxt(options.radio, unpack=True) #import psr_utils #x = np.arange(len(y))/len(y) #y = psr_utils.fft_rotate(y,0.2498*len(x))
def graphData(stock, MA1, MA2): ''' Use this to dynamically pull a stock: ''' try: print('Currently Pulling', stock) urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=10y/csv' stockFile = [] try: sourceCode = urllib.request.urlopen(urlToVisit).read().decode() splitSource = sourceCode.split('\n') for eachLine in splitSource: splitLine = eachLine.split(',') if len(splitLine) == 6: if 'values' not in eachLine: stockFile.append(eachLine) except Exception as e: print(str(e), 'failed to organize pulled data.') except Exception as e: print(str(e), 'failed to pull pricing data') try: date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',', unpack=True, converters={0: bytespdate2num('%Y%m%d')}) x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x] newAr.append(appendLine) x += 1 Av1 = movingaverage(closep, MA1) Av2 = movingaverage(closep, MA2) SP = len(date[MA2 - 1:]) fig = plt.figure(facecolor='#07000d') ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='#07000d') candlestick_ohlc(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717') Label1 = str(MA1) + ' SMA' Label2 = str(MA2) + ' SMA' ax1.plot(date[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5) ax1.plot(date[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5) ax1.grid(True, color='w') ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax1.yaxis.label.set_color("w") ax1.spines['bottom'].set_color("#5998ff") ax1.spines['top'].set_color("#5998ff") ax1.spines['left'].set_color("#5998ff") ax1.spines['right'].set_color("#5998ff") ax1.tick_params(axis='y', colors='w') plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax1.tick_params(axis='x', colors='w') plt.ylabel('Stock price and Volume') maLeg = plt.legend(loc=9, ncol=2, prop={'size': 7}, fancybox=True, borderaxespad=0.) maLeg.get_frame().set_alpha(0.4) textEd = pylab.gca().get_legend().get_texts() pylab.setp(textEd[0:5], color='w') volumeMin = 0 ax0 = plt.subplot2grid((6, 4), (0, 0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') rsi = rsiFunc(closep) rsiCol = '#c1f9f7' posCol = '#386d13' negCol = '#8f2020' ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5) ax0.axhline(70, color=negCol) ax0.axhline(30, color=posCol) ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:] >= 70), facecolor=negCol, edgecolor=negCol, alpha=0.5) ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:] <= 30), facecolor=posCol, edgecolor=posCol, alpha=0.5) ax0.set_yticks([30, 70]) ax0.yaxis.label.set_color("w") ax0.spines['bottom'].set_color("#5998ff") ax0.spines['top'].set_color("#5998ff") ax0.spines['left'].set_color("#5998ff") ax0.spines['right'].set_color("#5998ff") ax0.tick_params(axis='y', colors='w') ax0.tick_params(axis='x', colors='w') plt.ylabel('RSI') ax1v = ax1.twinx() ax1v.fill_between(date[-SP:], volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4) ax1v.axes.yaxis.set_ticklabels([]) ax1v.grid(False) ###Edit this to 3, so it's a bit larger ax1v.set_ylim(0, 3 * volume.max()) ax1v.spines['bottom'].set_color("#5998ff") ax1v.spines['top'].set_color("#5998ff") ax1v.spines['left'].set_color("#5998ff") ax1v.spines['right'].set_color("#5998ff") ax1v.tick_params(axis='x', colors='w') ax1v.tick_params(axis='y', colors='w') ax2 = plt.subplot2grid((6, 4), (5, 0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') fillcolor = '#00ffe8' nslow = 26 nfast = 12 nema = 9 emaslow, emafast, macd = computeMACD(closep) ema9 = ExpMovingAverage(macd, nema) ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2) ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1) ax2.fill_between(date[-SP:], macd[-SP:] - ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor) plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax2.spines['bottom'].set_color("#5998ff") ax2.spines['top'].set_color("#5998ff") ax2.spines['left'].set_color("#5998ff") ax2.spines['right'].set_color("#5998ff") ax2.tick_params(axis='x', colors='w') ax2.tick_params(axis='y', colors='w') plt.ylabel('MACD', color='w') ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper')) for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) plt.suptitle(stock.upper(), color='w') plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ax1.annotate('Big news!', (date[510], Av1[510]), xytext=(0.8, 0.9), textcoords='axes fraction', arrowprops=dict(facecolor='white', shrink=0.05), fontsize=14, color='w', horizontalalignment='right', verticalalignment='bottom') plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0) plt.show() fig.savefig('example.png', facecolor=fig.get_facecolor()) except Exception as e: print('main loop', str(e))
def test(N, mesh_no): figure_folder = "../report/figures/" # N = total number of points surrouding a centroid AND including the centroid itself mesh_abs_tol = 10**(-8) xc, yc = 0., 0. # centroid location # Analytical functions phi = lambda X, Y: np.cos(2 * X - 2 * Y - np.pi / 4.) + X + Y dphi_dx = lambda X, Y: 1. - 2. * np.sin(2 * X - 2 * Y - np.pi / 4.) dphi_dy = lambda X, Y: 1. - 2. * np.sin(2 * Y - 2 * X + np.pi / 4.) d2phi_dx2 = lambda X, Y: -4. * np.cos(2 * X - 2 * Y - np.pi / 4.) d2phi_dy2 = lambda X, Y: -4. * np.cos(2 * Y - 2 * X + np.pi / 4.) # Exact values phi_exact = phi(xc, yc) dphidx_exact = dphi_dx(xc, yc) dphidy_exact = dphi_dy(xc, yc) d2phidx2_exact = d2phi_dx2(xc, yc) d2phidy2_exact = d2phi_dy2(xc, yc) error = { 'phi_x': [], 'phi_y': [], 'dphi_dx': [], 'dphi_dy': [], 'd2phi_dx2': [], 'd2phi_dy2': [] } mesh_size = np.logspace(1., -5, 100) # for delta_x in mesh_size: delta_y = np.abs(dphidx_exact / dphidy_exact * delta_x) ## Around a Circle theta = np.linspace(0., 2 * np.pi, N - 1, endpoint=False) theta_off = 0. * np.pi / 3. xn, yn = delta_x * np.cos(theta + theta_off), delta_y * np.sin(theta + theta_off) ## Manual Input # xn = np.array([-3.0/2.0*delta_x,-delta_x/2.0,delta_x/2.0,+3.0/2.0*delta_x, -delta_x/2.0,delta_x/2.0,-delta_x/2.0,delta_x/2.0]) # yn = np.array([0., 0. ,0. ,0., delta_y,delta_y,-delta_y,-delta_y]) n_nodes = len(xn) xc_eff = xc + np.random.randn() * mesh_abs_tol #*delta_x yc_eff = yc + np.random.randn() * mesh_abs_tol #*delta_y xn += np.random.randn(n_nodes) * mesh_abs_tol yn += np.random.randn(n_nodes) * mesh_abs_tol phi_num_x, dphidx_num, d2phidx2_num = fit.BiVarPolyFit_X( xc_eff, yc_eff, xn, yn, phi(xn, yn)) phi_num_y, dphidy_num, d2phidy2_num = fit.BiVarPolyFit_Y( xc_eff, yc_eff, xn, yn, phi(xn, yn)) if delta_x == mesh_size[-1]: weights_dx = np.zeros(n_nodes) weights_dy = np.zeros(n_nodes) weights_dx2 = np.zeros(n_nodes) weights_dy2 = np.zeros(n_nodes) for ino in range(0, n_nodes): phi_base = np.zeros(n_nodes) phi_base[ino] = 1.0 _, weights_dx[ino], weights_dx2[ino] = fit.BiVarPolyFit_X( xc_eff, yc_eff, xn, yn, phi_base) _, weights_dy[ino], weights_dy2[ino] = fit.BiVarPolyFit_Y( xc_eff, yc_eff, xn, yn, phi_base) error['phi_x'].append(np.abs(phi_exact - phi_num_x)) error['phi_y'].append(np.abs(phi_exact - phi_num_y)) error['dphi_dx'].append(np.abs(dphidx_exact - dphidx_num)) error['dphi_dy'].append(np.abs(dphidy_exact - dphidy_num)) error['d2phi_dx2'].append(np.abs(d2phidx2_exact - d2phidx2_num)) error['d2phi_dy2'].append(np.abs(d2phidy2_exact - d2phidy2_num)) #set_trace() ############################################# ############### Plotting #################### ############################################# # LaTeX preamble from matplotlib import rc as matplotlibrc matplotlibrc('text.latex', preamble='\usepackage{color}') matplotlibrc('text', usetex=True) matplotlibrc('font', family='serif') # Reference decay rates ref_error_2nd = mesh_size * mesh_size ref_error_2nd /= ref_error_2nd[0] ref_error_1nd = mesh_size ref_error_1nd /= ref_error_1nd[0] inv_mesh_size = 1. / mesh_size ######################################## figwidth, figheight = 8, 8 lineWidth = 3 fontSize = 25 gcafontSize = 21 fig = plt.figure(0, (figwidth, figheight)) ax = fig.add_subplot(1, 1, 1) ax.plot(xn / delta_x, yn / delta_y, 'ko', markersize=12) ax.plot(xc / delta_x, yc / delta_y, 'x', markersize=12) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.set_xlabel(r"$x/\Delta x$", fontsize=fontSize) ax.set_ylabel(r"$y/\Delta y$", fontsize=fontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.grid(True) plt.tight_layout() plt.savefig('Points_Arragement.pdf') plt.close() ######################################## figwidth, figheight = 14, 12 fig = plt.figure(1, (figwidth, figheight)) ax = fig.add_subplot(2, 3, 1) error_plot = error['phi_x'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"X direction interpolation", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.set_ylabel(r"error", fontsize=fontSize) ax.grid(True) ax = fig.add_subplot(2, 3, 2) error_plot = error['dphi_dx'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"dphi/dx", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.grid(True) ax = fig.add_subplot(2, 3, 3) error_plot = error['d2phi_dx2'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"d2phi/dx2", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.grid(True) ax = fig.add_subplot(2, 3, 4) error_plot = error['phi_y'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"Y direction interpolation", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.set_ylabel(r"error", fontsize=fontSize) ax.grid(True) ax = fig.add_subplot(2, 3, 5) error_plot = error['dphi_dy'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"dphi/dy", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.grid(True) ax = fig.add_subplot(2, 3, 6) error_plot = error['d2phi_dy2'] ax.loglog(inv_mesh_size, error_plot, linewidth=lineWidth) ax.loglog(inv_mesh_size, ref_error_1nd * error_plot[0], ':k') ax.loglog(inv_mesh_size, 1e-1 * ref_error_2nd * error_plot[0], ':k') ax.set_title(r"d2phi/dy2", fontsize=gcafontSize) plt.setp(ax.get_xticklabels(), fontsize=gcafontSize) plt.setp(ax.get_yticklabels(), fontsize=gcafontSize) ax.set_xlabel(r"$1/h$", fontsize=fontSize) ax.grid(True) fig_name = figure_folder + 'Mesh ' + str( mesh_no) + ', Error_vs_invMeshSize (N=' + str(N) + ').pdf' plt.tight_layout() plt.show() plt.savefig(fig_name) plt.close()
def plot_basics(data, data_inst, fig, units): from powerlaw import plot_pdf, Fit, pdf annotate_coord = (-.4, .95) ax1 = fig.add_subplot(n_graphs,n_data,data_inst) plot_pdf(data[data>0], ax=ax1, linear_bins=True, color='r', linewidth=.5) x, y = pdf(data, linear_bins=True) ind = y>0 y = y[ind] x = x[:-1] x = x[ind] ax1.scatter(x, y, color='r', s=.5) plot_pdf(data[data>0], ax=ax1, color='b', linewidth=2) from pylab import setp setp( ax1.get_xticklabels(), visible=False) #ax1.set_xticks(ax1.get_xticks()[::2]) ax1.set_yticks(ax1.get_yticks()[::2]) locs,labels = yticks() #yticks(locs, map(lambda x: "%.0f" % x, log10(locs))) if data_inst==1: ax1.annotate("A", annotate_coord, xycoords="axes fraction", fontsize=14) from mpl_toolkits.axes_grid.inset_locator import inset_axes ax1in = inset_axes(ax1, width = "30%", height = "30%", loc=3) ax1in.hist(data, normed=True, color='b') ax1in.set_xticks([]) ax1in.set_yticks([]) ax2 = fig.add_subplot(n_graphs,n_data,n_data+data_inst, sharex=ax1) plot_pdf(data, ax=ax2, color='b', linewidth=2) fit = Fit(data, xmin=1, discrete=True) fit.power_law.plot_pdf(ax=ax2, linestyle=':', color='g') p = fit.power_law.pdf() #ax2.set_ylim(min(p), max(p)) ax2.set_xlim(ax1.get_xlim()) fit = Fit(data, discrete=True) fit.power_law.plot_pdf(ax=ax2, linestyle='--', color='g') from pylab import setp setp( ax2.get_xticklabels(), visible=False) #ax2.set_xticks(ax2.get_xticks()[::2]) if ax2.get_ylim()[1] >1: ax2.set_ylim(ax2.get_ylim()[0], 1) ax2.set_yticks(ax2.get_yticks()[::2]) #locs,labels = yticks() #yticks(locs, map(lambda x: "%.0f" % x, log10(locs))) if data_inst==1: ax2.annotate("B", annotate_coord, xycoords="axes fraction", fontsize=14) ax2.set_ylabel(r"$p(X)$")# (10^n)") ax3 = fig.add_subplot(n_graphs,n_data,n_data*2+data_inst)#, sharex=ax1)#, sharey=ax2) fit.power_law.plot_pdf(ax=ax3, linestyle='--', color='g') fit.exponential.plot_pdf(ax=ax3, linestyle='--', color='r') fit.plot_pdf(ax=ax3, color='b', linewidth=2) #p = fit.power_law.pdf() ax3.set_ylim(ax2.get_ylim()) ax3.set_yticks(ax3.get_yticks()[::2]) ax3.set_xlim(ax1.get_xlim()) #locs,labels = yticks() #yticks(locs, map(lambda x: "%.0f" % x, log10(locs))) if data_inst==1: ax3.annotate("C", annotate_coord, xycoords="axes fraction", fontsize=14) #if ax2.get_xlim()!=ax3.get_xlim(): # zoom_effect01(ax2, ax3, ax3.get_xlim()[0], ax3.get_xlim()[1]) ax3.set_xlabel(units)
ax6.axis([0, years, 0, 1]) ax6.set_ylabel('% Domestic-Type Millet') ax7 = ax6.twinx() ax7.axis([0, years, mpatch/1000., (maxpatch/1000.)]) ax7.set_ylabel('Millet Patch Density (10^3)', color = 'r') for tl in ax7.get_yticklabels(): tl.set_color('r') ax6.set_xlabel('Years') p1, = ax1.plot(yr, hpop, 'k-') #Note the comma!!! Very important to have the comma!!! p2, = ax2.plot(yr, dpop, 'k-') #Note the comma!!! Very important to have the comma!!! p3, = ax3.plot(yr, mpop, 'r-') #Note the comma!!! Very important to have the comma!!! p4, = ax4.plot(yr, dkil, 'k-') #Note the comma!!! Very important to have the comma!!! p5, = ax5.plot(yr, mexp, 'r-') #Note the comma!!! Very important to have the comma!!! p6, = ax6.plot(yr, mdom, 'k-') #Note the comma!!! Very important to have the comma!!! p7, = ax7.plot(yr, mdens, 'r-') #Note the comma!!! Very important to have the comma!!! plt.setp( ax1.get_xticklabels(), visible=False) # show the plot window, pop up a command window, and wait for user input to start the simulation plt.show() msg = "Simulation initialized, do you want to run the simulation now?" title = "Simulation start." if eg.ccbox(msg, title): # show a Continue/Cancel dialog pass # user chose Continue else: # user chose Cancel sys.exit(0) ####### The simulation starts here. for year in range(1,years+1): #this is the outer loop, that does things at an annual resolution, counting the years down for the simulation print "Year: %s" % year kcalneed = people * hkcal # find the number of kcals needed by the band this year htimebudget = people * fhours * hgratio # find the hunting time budget for the band this year gtimebudget = people * fhours * (1/hgratio) # find the gathering time budget for the band this year ##NOTE- excess hunting time will be used for gathering deer_now = deer #set up a variable to track deer population exploitation this year
for infile in infile_list: theta, enc_int, enc_int_norm = np.loadtxt(os.path.join(datadir, infile), unpack=True, usecols=[0, 1, 2]) ### plot enclosed intensity vs. angle pl.plot(np.log10(theta), enc_int_norm, lw=3.0) ### add legend legend = pl.legend( ([r"$%.2f$" % j for j in plaw_exp]), frameon=False, loc='upper left', handlelength=1.5, title="$\mathrm{power}$-$\mathrm{law}$ \n $\mathrm{exponent}$") pl.setp(legend.get_title(), fontsize='xx-small') ### add line marking enclosed intensity at theta = 1 deg pl.axvline(np.log10(1.), color='k', linestyle='--', lw=1.5) ### minor ticks xminticks = MultipleLocator(0.1) yminticks = MultipleLocator(0.05) pl.gca().xaxis.set_minor_locator(xminticks) pl.gca().yaxis.set_minor_locator(yminticks) pl.xlim([-2., 2.]) pl.xlabel(r'$\mathrm{log}(\theta) \ [\mathrm{deg}]$') pl.ylabel(r'$\mathrm{Normalized \ Enclosed \ Intensity}$') #pl.title(r'$\mathrm{%i \ Layer \ Luneburg \ Lens}$'%layers)
sns.regplot(np.arange(2, 7), dots[k, 1:6], ax=axes[k], color=cm('FB'), line_kws={'alpha': 0.7}, ci=None, truncate=True) if len(keys) == 7: axes[k].plot([1, 7], dots[k, [0, 6]], c=cm('Baseline'), alpha=0.7, linewidth=3) titles = [ 'Mean envelope', 'Time in % for all mu-states', 'Number of mu-states per minute', 'Mean mu-state length [s]', 'Mean mu-state envelope', 'Mean lag' ] for ax, title in zip(axes, titles): ax.set_title(title) ax.set_xlim(0, len(keys) + 1) plt.setp(ax.xaxis.get_majorticklabels(), rotation=70) ax.set_xticks(range(1, len(keys) + 1)) ax.set_xticklabels(keys) plt.suptitle('S{} Day{} Band: {}-{} Hz'.format(subj, day + 1, *mu_band)) plt.savefig('S{}_Day{}_stats'.format(subj, day + 1)) #plt.show() plt.close()
def kepbls(infile, outfile, datacol, errcol, minper, maxper, mindur, maxdur, nsearch, nbins, plot, clobber, verbose, logfile, status, cmdLine=False): # startup parameters numpy.seterr(all="ignore") status = 0 labelsize = 32 ticksize = 18 xsize = 16 ysize = 8 lcolor = '#0000ff' lwidth = 1.0 fcolor = '#ffff00' falpha = 0.2 # log the call hashline = '----------------------------------------------------------------------------' kepmsg.log(logfile, hashline, verbose) call = 'KEPBLS -- ' call += 'infile=' + infile + ' ' call += 'outfile=' + outfile + ' ' call += 'datacol=' + str(datacol) + ' ' call += 'errcol=' + str(errcol) + ' ' call += 'minper=' + str(minper) + ' ' call += 'maxper=' + str(maxper) + ' ' call += 'mindur=' + str(mindur) + ' ' call += 'maxdur=' + str(maxdur) + ' ' call += 'nsearch=' + str(nsearch) + ' ' call += 'nbins=' + str(nbins) + ' ' plotit = 'n' if (plot): plotit = 'y' call += 'plot=' + plotit + ' ' overwrite = 'n' if (clobber): overwrite = 'y' call += 'clobber=' + overwrite + ' ' chatter = 'n' if (verbose): chatter = 'y' call += 'verbose=' + chatter + ' ' call += 'logfile=' + logfile kepmsg.log(logfile, call + '\n', verbose) # start time kepmsg.clock('KEPBLS started at', logfile, verbose) # is duration greater than one bin in the phased light curve? if float(nbins) * maxdur / 24.0 / maxper <= 1.0: message = 'WARNING -- KEPBLS: ' + str( maxdur) + ' hours transit duration < 1 phase bin when P = ' message += str(maxper) + ' days' kepmsg.warn(logfile, message) # test log file logfile = kepmsg.test(logfile) # clobber output file if clobber: status = kepio.clobber(outfile, logfile, verbose) if kepio.fileexists(outfile): message = 'ERROR -- KEPBLS: ' + outfile + ' exists. Use clobber=yes' status = kepmsg.err(logfile, message, verbose) # open input file if status == 0: instr, status = kepio.openfits(infile, 'readonly', logfile, verbose) if status == 0: tstart, tstop, bjdref, cadence, status = kepio.timekeys( instr, infile, logfile, verbose, status) # fudge non-compliant FITS keywords with no values if status == 0: instr = kepkey.emptykeys(instr, file, logfile, verbose) # read table structure if status == 0: table, status = kepio.readfitstab(infile, instr[1], logfile, verbose) # filter input data table if status == 0: work1 = numpy.array( [table.field('time'), table.field(datacol), table.field(errcol)]) work1 = numpy.rot90(work1, 3) work1 = work1[~numpy.isnan(work1).any(1)] # read table columns if status == 0: intime = work1[:, 2] + bjdref indata = work1[:, 1] inerr = work1[:, 0] # test whether the period range is sensible if status == 0: tr = intime[-1] - intime[0] if maxper > tr: message = 'ERROR -- KEPBLS: maxper is larger than the time range of the input data' status = kepmsg.err(logfile, message, verbose) # prepare time series if status == 0: work1 = intime - intime[0] work2 = indata - numpy.mean(indata) # start period search if status == 0: srMax = numpy.array([], dtype='float32') transitDuration = numpy.array([], dtype='float32') transitPhase = numpy.array([], dtype='float32') dPeriod = (maxper - minper) / nsearch trialPeriods = numpy.arange(minper, maxper + dPeriod, dPeriod, dtype='float32') complete = 0 print(' ') for trialPeriod in trialPeriods: fracComplete = float(complete) / float(len(trialPeriods) - 1) * 100.0 txt = '\r' txt += 'Trial period = ' txt += str(int(trialPeriod)) txt += ' days [' txt += str(int(fracComplete)) txt += '% complete]' txt += ' ' * 20 sys.stdout.write(txt) sys.stdout.flush() complete += 1 srMax = numpy.append(srMax, 0.0) transitDuration = numpy.append(transitDuration, numpy.nan) transitPhase = numpy.append(transitPhase, numpy.nan) trialFrequency = 1.0 / trialPeriod # minimum and maximum transit durations in quantized phase units duration1 = max(int(float(nbins) * mindur / 24.0 / trialPeriod), 2) duration2 = max( int(float(nbins) * maxdur / 24.0 / trialPeriod) + 1, duration1 + 1) # 30 minutes in quantized phase units halfHour = int(0.02083333 / trialPeriod * nbins + 1) # compute folded time series with trial period work4 = numpy.zeros((nbins), dtype='float32') work5 = numpy.zeros((nbins), dtype='float32') phase = numpy.array( ((work1 * trialFrequency) - numpy.floor(work1 * trialFrequency)) * float(nbins), dtype='int') ptuple = numpy.array([phase, work2, inerr]) ptuple = numpy.rot90(ptuple, 3) phsort = numpy.array(sorted(ptuple, key=lambda ph: ph[2])) for i in range(nbins): elements = numpy.nonzero(phsort[:, 2] == float(i))[0] work4[i] = numpy.mean(phsort[elements, 1]) work5[i] = math.sqrt( numpy.sum(numpy.power(phsort[elements, 0], 2)) / len(elements)) # extend the work arrays beyond nbins by wrapping work4 = numpy.append(work4, work4[:duration2]) work5 = numpy.append(work5, work5[:duration2]) # calculate weights of folded light curve points sigmaSum = numpy.nansum(numpy.power(work5, -2)) omega = numpy.power(work5, -2) / sigmaSum # calculate weighted phased light curve s = omega * work4 # iterate through trial period phase for i1 in range(nbins): # iterate through transit durations for duration in range(duration1, duration2 + 1, int(halfHour)): # calculate maximum signal residue i2 = i1 + duration sr1 = numpy.sum(numpy.power(s[i1:i2], 2)) sr2 = numpy.sum(omega[i1:i2]) sr = math.sqrt(sr1 / (sr2 * (1.0 - sr2))) if sr > srMax[-1]: srMax[-1] = sr transitDuration[-1] = float(duration) transitPhase[-1] = float((i1 + i2) / 2) # normalize maximum signal residue curve bestSr = numpy.max(srMax) bestTrial = numpy.nonzero(srMax == bestSr)[0][0] srMax /= bestSr transitDuration *= trialPeriods / 24.0 BJD0 = numpy.array(transitPhase * trialPeriods / nbins, dtype='float64') + intime[0] - 2454833.0 print('\n') # clean up x-axis unit if status == 0: ptime = copy(trialPeriods) xlab = 'Trial Period (days)' # clean up y-axis units if status == 0: pout = copy(srMax) ylab = 'Normalized Signal Residue' # data limits xmin = ptime.min() xmax = ptime.max() ymin = pout.min() ymax = pout.max() xr = xmax - xmin yr = ymax - ymin ptime = insert(ptime, [0], [ptime[0]]) ptime = append(ptime, [ptime[-1]]) pout = insert(pout, [0], [0.0]) pout = append(pout, 0.0) # plot light curve if status == 0 and plot: plotLatex = True try: params = { 'backend': 'png', 'axes.linewidth': 2.5, 'axes.labelsize': labelsize, 'axes.font': 'sans-serif', 'axes.fontweight': 'bold', 'text.fontsize': 12, 'legend.fontsize': 12, 'xtick.labelsize': ticksize, 'ytick.labelsize': ticksize } rcParams.update(params) except: plotLatex = False if status == 0 and plot: pylab.figure(figsize=[xsize, ysize]) pylab.clf() # plot data ax = pylab.axes([0.06, 0.10, 0.93, 0.87]) # force tick labels to be absolute rather than relative pylab.gca().xaxis.set_major_formatter( pylab.ScalarFormatter(useOffset=False)) pylab.gca().yaxis.set_major_formatter( pylab.ScalarFormatter(useOffset=False)) # rotate y labels by 90 deg labels = ax.get_yticklabels() pylab.setp(labels, 'rotation', 90) # plot curve if status == 0 and plot: pylab.plot(ptime[1:-1], pout[1:-1], color=lcolor, linestyle='-', linewidth=lwidth) pylab.fill(ptime, pout, color=fcolor, linewidth=0.0, alpha=falpha) pylab.xlabel(xlab, {'color': 'k'}) pylab.ylabel(ylab, {'color': 'k'}) pylab.grid() # plot ranges if status == 0 and plot: pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01) if ymin >= 0.0: pylab.ylim(ymin - yr * 0.01, ymax + yr * 0.01) else: pylab.ylim(1.0e-10, ymax + yr * 0.01) # render plot if status == 0 and plot: if cmdLine: pylab.show() else: pylab.ion() pylab.plot([]) pylab.ioff() # append new BLS data extension to the output file if status == 0: col1 = Column(name='PERIOD', format='E', unit='days', array=trialPeriods) col2 = Column(name='BJD0', format='D', unit='BJD - 2454833', array=BJD0) col3 = Column(name='DURATION', format='E', unit='hours', array=transitDuration) col4 = Column(name='SIG_RES', format='E', array=srMax) cols = ColDefs([col1, col2, col3, col4]) instr.append(new_table(cols)) instr[-1].header.cards['TTYPE1'].comment = 'column title: trial period' instr[-1].header.cards[ 'TTYPE2'].comment = 'column title: trial mid-transit zero-point' instr[-1].header.cards[ 'TTYPE3'].comment = 'column title: trial transit duration' instr[-1].header.cards[ 'TTYPE4'].comment = 'column title: normalized signal residue' instr[-1].header.cards['TFORM1'].comment = 'column type: float32' instr[-1].header.cards['TFORM2'].comment = 'column type: float64' instr[-1].header.cards['TFORM3'].comment = 'column type: float32' instr[-1].header.cards['TFORM4'].comment = 'column type: float32' instr[-1].header.cards['TUNIT1'].comment = 'column units: days' instr[-1].header.cards[ 'TUNIT2'].comment = 'column units: BJD - 2454833' instr[-1].header.cards['TUNIT3'].comment = 'column units: hours' instr[-1].header.update('EXTNAME', 'BLS', 'extension name') instr[-1].header.update('PERIOD', trialPeriods[bestTrial], 'most significant trial period [d]') instr[-1].header.update('BJD0', BJD0[bestTrial] + 2454833.0, 'time of mid-transit [BJD]') instr[-1].header.update('TRANSDUR', transitDuration[bestTrial], 'transit duration [hours]') instr[-1].header.update('SIGNRES', srMax[bestTrial] * bestSr, 'maximum signal residue') # history keyword in output file if status == 0: status = kepkey.history(call, instr[0], outfile, logfile, verbose) instr.writeto(outfile) # close input file if status == 0: status = kepio.closefits(instr, logfile, verbose) # print best trial period results if status == 0: print(' Best trial period = %.5f days' % trialPeriods[bestTrial]) print(' Time of mid-transit = BJD %.5f' % (BJD0[bestTrial] + 2454833.0)) print(' Transit duration = %.5f hours' % transitDuration[bestTrial]) print(' Maximum signal residue = %.4g \n' % (srMax[bestTrial] * bestSr)) # end time if (status == 0): message = 'KEPBLS completed at' else: message = '\nKEPBLS aborted at' kepmsg.clock(message, logfile, verbose)
# <codecell> subplot(2,2,1) for a in theoretical_alphas: y_vals = df.ix['continuous', a]['alpha_mean'] error = df.ix['continuous', a]['alpha_sd'] plot(theoretical_xmins, y_vals, label=a) fill_between(theoretical_xmins, y_vals-error, y_vals+error, alpha=.1) xscale('log') #xlabel(r"$x_{min}$") ylabel(r"Fitted $\alpha$") yticks(theoretical_alphas) setp(gca().get_xticklabels(), visible=False) title("Continuous") ######### subplot(2,2,2) for a in theoretical_alphas: y_vals = df.ix['discrete', a]['alpha_mean'] error = df.ix['discrete', a]['alpha_sd'] plot(theoretical_xmins, y_vals, label=a) fill_between(theoretical_xmins, y_vals-error, y_vals+error, alpha=.1) xscale('log') #xlabel(r"$x_{min}$") #ylabel(r"Fitted $\alpha$") setp(gca().get_xticklabels(), visible=False)
def plot_commerror(name1, logfile1, name2, logfile2): file1 = open(str(logfile1), 'r').readlines() data1 = [float(line.split()[1]) for line in file1] iso1 = data1[0::3] aniso1 = data1[1::3] ml1 = data1[2::3] file2 = open(str(logfile2), 'r').readlines() data2 = [float(line.split()[1]) for line in file2] iso2 = data2[0::3] aniso2 = data2[1::3] ml2 = data2[2::3] # x axis x = [8, 16, 32, 64, 128] xlabels = ['A', 'B', 'C', 'D', 'E'] orderone = [1, .5, .25, .125, .0625] ordertwo = [i**2 for i in orderone] plot1 = pylab.figure(figsize=(6, 6.5)) size = 15 ax = pylab.subplot(111) ax.plot(x, iso1, linestyle='solid', color='red', lw=2) ax.plot(x, aniso1, linestyle='dashed', color='red', lw=2) ax.plot(x, ml1, linestyle='dashdot', color='red', lw=2) ax.plot(x, iso2, linestyle='solid', color='blue', lw=2) ax.plot(x, aniso2, linestyle='dashed', color='blue', lw=2) ax.plot(x, ml2, linestyle='dashdot', color='blue', lw=2) #ax.plot(x,orderone, linestyle='solid',color='black',lw=2) #ax.plot(x,ordertwo, linestyle='dashed',color='black') #pylab.legend((str(name1)+'_iso',str(name1)+'_aniso',str(name2)+'_iso',str(name2)+'_aniso','order 1'),loc="best") pylab.legend( (str(name1) + '_iso', str(name1) + '_aniso', str(name1) + '_ml', str(name2) + '_iso', str(name2) + '_aniso', str(name2) + '_ml'), loc="best") leg = pylab.gca().get_legend() ltext = leg.get_texts() pylab.setp(ltext, fontsize=size, color='black') frame = leg.get_frame() frame.set_fill(False) frame.set_visible(False) #ax.grid("True") for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(size) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(size) # set axes to logarithmic pylab.gca().set_xscale('log', basex=2) pylab.gca().set_yscale('log', basex=2) pylab.axis([8, 128, 1.e-4, 2]) ax.set_xticks(x) ax.set_xticklabels(xlabels) #pylab.axis([1,5,1.e-6,1.]) ax.set_xlabel('Mesh resolution', ha="center", fontsize=size) ax.set_ylabel('commutation error', fontsize=size) pylab.savefig('commerrorplot.eps') pylab.savefig('commerrorplot.pdf') return
edge=True, linewidth=2, label='HERA-331, foreground avoidance') plot(HERA331['opt'], 'black', linestyle='-', edge=True, linewidth=2, label='HERA-331, foreground modeling') plot(cosmoSig, 'black', linestyle='--', label='Mesinger et al. 2011', linewidth=1.5) p.setp(p.gca().get_xticklabels(), fontsize=20) p.setp(p.gca().get_yticklabels(), fontsize=20) p.gca().set_yscale('log', nonposy='clip') p.gca().set_xscale('log', nonposy='clip') p.tick_params(axis='both', which='major', length=8) p.tick_params(axis='both', which='minor', length=4) p.xlabel(r'$k\ [h\ {\rm Mpc}^{-1}]$', fontsize=20) #p.ylabel(r'$k^3/2\pi^2\ P(k)\ [{\rm mK}^2]$') p.ylabel(r'$\Delta^2(k)\ [{\rm mK}^2]$', fontsize=20) p.ylim(3e-1**2, 1e3) p.xlim(.01, 2.0) p.legend(loc='best', fontsize=14) p.grid() #p.savefig('eor_pspec_2014.png', bbox='tight') p.show()