def histo(denlist): for d in denlist: h,bin_edges = N.histogram(N.log10(d.flatten()),normed=True,range=(-2,2),bins=50) M.semilogx(10.**(bin_edges),h) M.show()
def plot_curve(x, y, xlog=0, ylog=0, xname='x', yname='y', oplot=0, color='k', lineStyle='-', linewidth=1, xrange=None, yrange=None): if oplot == 0: win = Window() else: win = None marker = '%s%s' % (color, lineStyle) if xlog and ylog: pylab.loglog(x, y, marker, markersize=3, linewidth=linewidth) elif xlog: pylab.semilogx(x, y, marker, markersize=3, linewidth=linewidth) elif ylog: pylab.semilogy(x, y, marker, markersize=3, linewidth=linewidth) else: pylab.plot(x, y, marker, markersize=3, linewidth=linewidth) if not oplot: pylab.xlabel(xname) pylab.ylabel(yname) setAxis(xrange, yrange) return win
def plot_ex(ion, line): ''' Plot the collisions cross-section with electrons ''' global cst, iplot iplot += 1 ofname = format(iplot, '0>4')+'_ex.pdf' T = 5000. x0 = cst / line.lbd * Cst.Q / Cst.K / T x_vec_log = pl.linspace(-3, 4, 100) x_vec = 10**x_vec_log q0 = [sigma_weak_seaton(i, ion, line, T) for i in x_vec] q1 = [sigma_strong_seaton(i, ion, line, T) for i in x_vec] q = [sigma_seaton(i, ion, line, T) for i in x_vec] ll = line.lower ul = line.upper #title='Na I: '+str(ll.cfg)+' '+str(ll.term)+' [g='+str(ll.g)+'] <=> '+str(ul.cfg)+' '+str(ul.term)+' [g='+str(ul.g)+'], Ro = '+format(orbital_radius(ion, line.lower), '4.2f')+' a$_0$, f = '+str(line.f) title = SPE+' '+DEG+': '+str(ll.cfg)+' '+str(ll.term)+' [g='+str(ll.g)+'] '+str(ul.cfg)+' '+str(ul.term)+' [g='+str(ul.g)+'] Ro = '+str(orbital_radius(ion, line.lower))+' f = '+str(line.f) pl.figure(figsize=(12, 6), dpi=100, facecolor='w', edgecolor='k') pl.plot(x_vec*Cst.K*T/Cst.Q, q0, 'k', lw=1, label='Weak coupling') pl.plot(x_vec*Cst.K*T/Cst.Q, q1, 'k', lw=2, label='Strong coupling') pl.plot(x_vec*Cst.K*T/Cst.Q, q, 'r+', label='IPM (Seaton 1962)') pl.semilogx() #pl.semilogy() pl.xlim([1e-2, 1e4]) pl.xlabel('E [eV]') pl.ylabel('Cross-section [$\pi a_0^2$]') pl.legend(frameon=False, loc=0) pl.title(title) #bbox_inches='tight' pl.savefig(ofname, dpi=100, format='pdf', orientation='landscape', papertype='a4') pl.close()
def plot_cf(xx, sname=''): max_y = 0 n = 1 plt.figure() try: for x in xx: plt.fill_between(x[:, 0], x[:, 1] - x[:, 2], x[:, 1] + x[:, 2], alpha=0.5) plt.semilogx(x[:, 0], x[:, 1], '-', label='q ' + str(n)) #plt.semilogx(x[:,0],x[:,1],'o',label='q '+str(n)) #plt.errorbar(x[:,0],x[:,1],yerr=x[:,2]) if max_y < x[1, 1]: max_y = x[1, 1] * 1 n += 1 except: plt.fill_between(xx[:, 0], xx[:, 1] - xx[:, 2], xx[:, 1] + xx[:, 2], alpha=0.5) plt.semilogx(xx[:, 0], xx[:, 1], '-', label='q ' + str(0)) #plt.semilogx(x[:,0],x[:,1],'o',label='q '+str(n)) if max_y < xx[1, 1]: max_y = xx[1, 1] * 1 plt.xlabel(r"lag time $\tau$ (s)") plt.ylabel(r"g$^{(2)}$(q,$\tau$)") #plt.ylim((1,1+(max_y-1)*1.3)) try: plt.legend(loc=1, fontsize=10, ncol=n // 6) except: plt.legend(loc=1, fontsize=10) plt.title(sname) plt.tight_layout() plt.show()
def main(): print("[INFO] Loading channel data from graphviz file") xvec, yvec = [], [] runningMean, runningVar = 0.0, 0.0 inFile = sys.argv[1] csvFile = "%s.csv" % inFile f = open(csvFile, "w") f.write("time,n,mutual information\n") f.close() for n in np.logspace(1, 5, 20): print("Computing for sequence of length %s " % n) ch = Channel(inFile) t1 = time.time() inputSeq = np.random.choice(list(ch.inputAlphabets), n) outputSeq = ch.simulate(inputSeq) ixy = mutual_info(inputSeq, outputSeq) t = time.time() - t1 xvec.append(n) yvec.append(ixy) print("|- Mutual info %s, time taken %s" % (ixy, t)) print(abs(np.mean(yvec) - ixy), np.std(yvec)) with open(csvFile, "a") as f: f.write("%s,%s,%s\n" % (t, n, ixy)) pylab.semilogx(xvec, yvec) pylab.savefig('%s_mutual_info.png' % inFile)
def PLOT_DATA(arr, Xplot, Yplot, lb, Ef, Log, Plot_Label): p.xlabel(Plot_Label[Xplot][1] + Plot_Label[Xplot][3]) p.ylabel(Plot_Label[Yplot][1] + Plot_Label[Yplot][3]) p.title(Plot_Label[Yplot][1] + " as a function of " + Plot_Label[Xplot][1]) if Xplot == "E": x = (arr[:, Plot_Label[Xplot][0]] - Ef) * float(Plot_Label[Xplot][4]) else: x = arr[:, Plot_Label[Xplot][0]] * float(Plot_Label[Xplot][4]) if Yplot == "E": y = (arr[:, Plot_Label[Yplot][0]] - Ef) * float(Plot_Label[Yplot][4]) else: y = arr[:, Plot_Label[Yplot][0]] * float(Plot_Label[Yplot][4]) if Xplot == "N" and Log == "y": indn = p.where(x < 0) indp = p.where(x > 0) pp = raw_input("Plot electron or hole ? > ") if pp == "electron": p.semilogx(abs(x[indn]), y[indn], label=lb + "$ ; n-Type$") elif pp == "hole": p.semilogx(x[indp], y[indp], label=lb + "$ ; p-Type $") elif Yplot == "N" and Log == "y": indn = p.where(y < 0) indp = p.where(y > 0) pp = raw_input("Plot electron or hole ?? > ") if pp == "electron": p.semilogy(x[indn], abs(y[indn]), label=lb + "$ ; n-Type$") elif pp == "hole": p.semilogy(x[indp], y[indp], label=lb + "$ ; p-Type$") else: p.plot(x, y, label=lb)
def sums2nloop(model_input, images_input, iterations): """Run through a loop of calculating the summed S/N for a set of data. This is useful if you'd like to see how well we'd do as we keep adding more and more data together in order to attempt to extract a signal. """ if images_input == "simdata": header = model_input.simdata() else: header = getheaderinfo(images_input) # iterations = header['numexp'] snvec = numpy.zeros((iterations, 2)) for i in range(0, iterations): snvec[i] = models2n(i + 1, model_input, images_input) print snvec # GRAB EXPOSURE TIMES timearr = header["tstart"][0:iterations] # should be error bar from tstart to tstop # Plot the results pylab.semilogx(timearr, snvec[:, 1], linestyle="", marker="o") pylab.semilogx(timearr, snvec[:, 0], linestyle="", marker="x") pylab.xlim(50, 200000) pylab.xlabel("Time") pylab.ylabel("Summed S/N (not a lightcurve!)") plottitle = "Model: " + model_input.name + ", Data: " + images_input pylab.title(plottitle)
def flipPlot(minExp, maxExp): ratios, diffs, xAxis = [], [], [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.choice(('H', 'T')) == 'H': numHeads += 1 numTails = numFlips - numHeads try: ratios.append(numHeads / numTails) diffs.append(abs(numHeads - numTails)) except ZeroDivisionError: continue print("xAxis:", xAxis, "ratios:", ratios, "diffs:", diffs) pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of FLips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.semilogx() pylab.semilogy() pylab.plot(xAxis, diffs, 'ko') pylab.figure() pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('#Heads/#Tails') pylab.semilogx() pylab.semilogy() pylab.plot(xAxis, ratios, 'ko')
def plotevol(dir='test', var='radius', ymax=500.0, col='k', lab='test', fig=1, fhold=False, lloc='lower left'): [t, rs, fs] = dataset(dir=dir + '/', var=var) #if not fhold: pylab.close(fig) #figure = matplotlib.pyplot.figure(num=fig) pylab.semilogx(t, fs, col, linewidth=lw, label=lab) pylab.hold(fhold) #if var != 'Mach': # pylab.semilogx(t,rs,label='RS') #if var == 'velocity': # pylab.ylim([1.e1, 1.e4]) pylab.xlim([10.0, 5.0e3]) pylab.xlabel('t, years') ylab = var ylab = ylab.replace('_', '_{') if '_{' in ylab: ylab = ylab + '}' pylab.ylim([0.0, ymax]) pylab.ylabel('$\mathrm{' + ylab + '}$') pylab.legend(loc=lloc) var = var.replace('/', '_') print var if not fhold: matplotlib.pyplot.savefig(basedir + dir + '/' + var + '_t.eps')
def plot(): for time_filename, size_filename, f_label, f_style in lines_to_plot: time_file = open('parser_results/' + time_filename) size_file = open('parser_results/' + size_filename) times = {} for mark, _, _ in swarmsize_lines: times[mark] = [] for line in time_file: time = float(line.split()[0]) size = int(size_file.next().split()[0]) for mark, _, _ in swarmsize_lines: if size <= mark: times[mark].append(time) break for mark, m_label, m_style in reversed(swarmsize_lines): cum_values = cdf.cdf(times[mark]) x = [cum_value[1] for cum_value in cum_values] y = [cum_value[0] for cum_value in cum_values] pylab.semilogx(x, y, f_style+m_style, label=f_label+' '+m_label, markevery=markevery) pylab.legend(loc='lower right') pylab.savefig(output_filename) # pylab.close() print 'Output saved to:', output_filename
def _cumdist(sample, annotation='', color='k'): order = np.argsort(sample['giso_insol'].values)[::-1] w = np.cumsum(sample['weight'].values[order]) / num_stars n = np.array(range(len(sample['weight'].values))) / float(len(sample)) f = sample['giso_insol'].values[order] pl.step(f, n, 'k-', lw=2, linestyle='dashed', alpha=0.25, color=color, label=None) pl.step(f, w / np.max(w), 'k-', lw=2, color=color) aloc = (0.1, 0.85) #pl.annotate(annotation, xy=aloc, xycoords='axes fraction', fontsize=20, # horizontalalignment='left') pl.semilogx() pl.xlim(2000, 30) pl.ylim(0, 1) ax = pl.gca() ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.xaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%0.0f')) ax.xaxis.set_ticks([30, 100, 300, 1000, 3000]) pl.xlabel('Stellar light intensity relative to Earth (S)') # pl.ylabel('cumulative fraction of planet detections') pl.ylabel(r'Fraction of planets with S$_{\rm inc} < S$')
def filterresponse(b,a,fs=44100,scale='log',**kwargs): w, h = freqz(b,a) pl.subplot(2,1,1) pl.title('Digital filter frequency response') pl.plot(w/max(w)*fs/2, 20 * np.log10(abs(h)),**kwargs) pl.xscale(scale) # if scale=='log': # pl.semilogx(w/max(w)*fs/2, 20*np.log10(np.abs(h)), 'k') # else: # pl.plot(w/max(w)*fs/2, 20*np.log10(np.abs(h)), 'k') pl.ylabel('Gain (dB)') pl.xlabel('Frequency (rad/sample)') pl.axis('tight') pl.grid() pl.subplot(2,1,2) angles = np.unwrap(np.angle(h)) if scale=='log': pl.semilogx(w/max(w)*fs/2, angles, **kwargs) else: pl.plot(w/max(w)*fs/2, angles, **kwargs) pl.ylabel('Angle (radians)') pl.grid() pl.axis('tight') pl.xlabel('Frequency (rad/sample)')
def noise_data(self, chan=0, m=1, plot=False): NFFT = self.NFFT N = self.N lendata = self.lendata Fs = self.Fs pst = np.zeros(NFFT) cnt = 0 while cnt < m: data, addr = self.r.get_data_udp(N*lendata, demod=True) if self.use_r2 and ((not np.all(np.diff(addr)==2**21/N)) or data.shape[0]!=256*lendata): print "bad" else: ps, f = mlab.psd(data[:,chan], NFFT=NFFT, Fs=Fs/self.r.nfft) pst += ps cnt += 1 pst /= cnt pst = 10.*np.log10(pst) if plot: ind = f > 0 pl.semilogx(f[ind], pst[ind]) pl.xlabel('Hz') pl.ylabel('dB/Hz') pl.title('chan data psd') pl.grid() pl.show() return f, pst
def test_cross_validation(): np.random.seed(1) n_features = 3 func = get_test_model(n_features=n_features) dataset_train, labels_train = get_random_dataset(func, n_datapoints=5e3, n_features=n_features, noise_level=1.) alphas = 10**np.linspace(-3, 2, 10) # Fit scikit lasso lasso_scikit = lasso.SKLasso(alpha=0.001, max_iter=1000) lasso_scikit.fit_CV(dataset_train, labels_train[:,0], alphas=alphas, n_folds=5) # Fit tf lasso gen_lasso = gl.GeneralizedLasso(alpha=0.001, max_iter=1000, link_function=None) gen_lasso.fit_CV(dataset_train, labels_train[:,0], alphas=alphas, n_folds=5) pl.figure() pl.title('CV test. TF will have higher errors, since it is not exact') pl.semilogx(alphas, gen_lasso.alpha_mse, 'o-', label='tf') pl.semilogx(alphas, lasso_scikit.alpha_mse, '*-', label='scikit') pl.legend(loc='best') pl.xlabel('alpha') pl.ylabel('cost') pl.show()
def plot(self, marker='o', color='red', m=0, M=6000): """Plots the position / height of the peaks in the well .. plot:: :include-source: from fragment_analyser import Line, fa_data l = Line(fa_data("alternate/peaktable.csv")) well = l.wells[0] well.plot() """ import pylab if len(self.df) == 0: print("Nothing to plot (no peaks)") return x = self.df['Size (bp)'].astype(float).values y = self.df['RFU'].astype(float).values pylab.stem(x, y, marker=marker, color=color) pylab.semilogx() pylab.xlim([1, M]) pylab.ylim([0, max(y) * 1.2]) pylab.grid(True) pylab.xlabel("size (bp)") pylab.ylabel("RFU") return x, y
def PlotScaledPathLength_vs_pZL(LZarray, numtries=2, pZLarray=10.**numpy.arange(-1., 2.001, 0.25)): """ PlotScaledPathLength_vs_pZL(((L1,Z1),(L2,Z2),...), numtries, [pZLa,pZLb,pZLc...]) will plot the scaled path length for small world networks of size Li and neighbors Zi, at scaled rewiring probabilities pZLa, pZLb, ... Uses either MultiPlot.py to do the scaling, or rescales by hand, depending on the implementation chosen. To rescale, p is multiplied by Z*L and the mean path length ell is multiplied by 2*Z/L. """ pathlengthBar = {} pathlengthSigma = {} pdata = {} for L,Z in LZarray: # Shift evaluated points to good, scaled range pdata[L,Z] = pZLarray/(Z*L) pathlengthBar[L,Z], pathlengthSigma[L,Z] = \ GetPathLength_vs_p(L, Z, numtries, pdata[L,Z]) pylab.figure(1) MultiPlot.MultiPlot(pdata, pathlengthBar, xform='p->p', yform='ell->ell', yerrdata = pathlengthSigma, showIt=False) pylab.semilogx() pylab.figure(2) MultiPlot.MultiPlot(pdata, pathlengthBar, xform='p->p*Z*L', yform='ell->(2*ell*Z)/L', yerrdata=pathlengthSigma, yerrform='sig->(2*sig*Z)/L', keyNames=('L','Z'), loc = 3, showIt=False) pylab.semilogx() pylab.show()
def get_opt_theta(n, T, steps_range, which, label = 'label'): parameters = get_parameters(which) prob = Problem_FSI_1D(n = n, **parameters) dx = prob.dx N_steps = np.array([int(2**i) for i in np.linspace(0, 50, 1000)]) dts = T/N_steps CFL = [dt/(dx**2) for dt in dts] theta = [prob.DNWR_theta_opt(dt, dt) for dt in dts] lim_zero = parameters['alpha_2']/(parameters['alpha_1'] + parameters['alpha_2']) lim_inf = parameters['lambda_2']/(parameters['lambda_1'] + parameters['lambda_2']) pl.figure() pl.semilogx(CFL, theta, label = label) pl.axhline(lim_zero, ls = '--', color = 'k', label = r'$\theta_{c \rightarrow 0}$') pl.axhline(lim_inf, ls = ':', color = 'k', label = r'$\theta_{c \rightarrow \infty}$') pl.legend() pl.xlabel('c', labelpad = -30, position = (1.05, -1), fontsize = 20) lp = -50 if label == 'Air-Steel' else -20 pl.ylabel(r'$\theta_{opt}$', rotation = 0, labelpad = lp, position = (2., 1.), fontsize = 20) pl.title(label) pl.savefig('plots/CFL_vs_opt_theta_{}.png'.format(which), dpi = 100) return
def showFreqComplex(f, vector, title='Magnitude/Phase Frequency Plot'): """ @showFreqComplex showFreqComplex(f,vector,title) Linear frequency magnitude and phase plot Required parameters: f : Frequency vector (Hz) vector : Complex vector Optional parameters: title : Plot title Returns nothing """ fig = _plotStart() ax = _subplotStart(fig, 211, title, '', 'Magnitude') mag = np.absolute(vector) pl.semilogx(f, mag) _subplotEnd(ax) ax = _subplotStart(fig, 212, '', 'Frequency (Hz)', 'Phase') phase = np.angle(vector, deg=True) pl.semilogx(f, phase) _subplotEnd(ax) _plotEnd()
def array_plot(request): halo = halo_from_request(request) name = decode_property_name(request.matchdict['nameid']) val, property_info = halo.calculate(name, True) if len(val.shape) > 1: return image_plot(request, val, property_info) with _matplotlib_lock: start(request) p.plot(property_info.plot_x_values(val), val) if property_info.plot_xlog() and property_info.plot_ylog(): p.loglog() elif property_info.plot_xlog(): p.semilogx() elif property_info.plot_ylog(): p.semilogy() if property_info.plot_yrange(): p.ylim(*property_info.plot_yrange()) add_xy_labels(property_info, request) return finish(request)
def clust(Nclust=25,loadfile='/media/HD1_/Documents/AG3C/Results/formated_data.p',writefile='/media/HD1_/Documents/AG3C/Results/cluster_kmeans.p',plots=True): #load the formated data (avout,stdout,av_reference)=pickle.load(open(loadfile,'rb')) TFav=[] TFref=[] TFstd=[] #do k-means clustering (o,n)=kmeans2(np.array(avout),Nclust) #save the output pickle.dump((o,n),open(writefile,'wb')) if plots==True: #make the plots t=[3.,4.,5.,6.,8.,24.,48,7*24.,14*24.] plt.figure() for i in range(Nclust): idx=np.where(n==i)[0] plt.subplot(np.ceil(np.sqrt(Nclust)),np.ceil(np.sqrt(Nclust)),i+1) plt.hold(True) for j in range(len(idx)): plt.semilogx(t,avout[idx[j]]) plt.ylim([0,1]) plt.show()
def plotResults(self, titlestr="", ylimits=[0.5,1.05], plotfunc = pl.semilogx, ylimitsB=[0,101], legend_loc=3, show=True ): pl.figure(num=None, figsize=(15,5)) xvals = range(1, (1+len(self.removed)) ) #Two subplots. One the left is the test accuracy vs. iteration pl.subplot(1,2,1) plotfunc(xvals, self.test_acc_list, "b", label="Test Accuracy") pl.hold(True) plotfunc(xvals, self.getRollingAvgTestAcc(window_size=10), "r", label="Test Acc (rolling avg)") plotfunc(xvals, self.getRollingAvgTrainAcc(window_size=10), "g--", label="Train Acc (rolling avg)") pl.ylim(ylimits) if titlestr == "": pl.title("Iterative Feature Removal") else: pl.title(titlestr) pl.ylabel("Test Accuracy") pl.xlabel("Iteration") pl.legend(loc=legend_loc) #3=lower left pl.hold(False) #second subplot. On the right is the number of features removed per iteration pl.subplot(1,2,2) Ns = [ len(lst) for lst in self.removed ] pl.semilogx(xvals, Ns, "bo", label="#Features per Iteration") pl.xlabel("Iteration") pl.ylabel("Number of Features Selected") pl.title("Number of Features Removed per Iteration") pl.ylim(ylimitsB) pl.subplots_adjust(left=0.05, bottom=0.15, right=0.95, top=0.90, wspace=0.20, hspace=0.20) if show: pl.show()
def flipPlot(minExp,maxExp): '''假定minExp和maxExp是正整数,并且minExp<maxExp, 绘制出2**minExp到2**maxExp次抛硬币的结果''' ratios=[] diffs=[] xAxis=[] for exp in range(minExp,maxExp+1): xAxis.append(2**exp) for numFlips in xAxis: numHeads=0 for n in range(numFlips): if random.random()<0.5: numHeads+=1 numTails=numFlips-numHeads ratios.append(numHeads/float(numTails)) diffs.append(abs(numHeads-numTails)) pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.semilogx() pylab.semilogy() pylab.ylabel('Abs(#Heads-#Tails)') pylab.plot(xAxis,diffs,'bo') pylab.figure() pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.semilogx() pylab.ylabel('#Heads/#Tails') pylab.plot(xAxis,ratios,'bo')
def plot_passing_rate(depth): import pylab ax = pylab.gca() enu = numpy.logspace(3, 7, 101) for zenith, color in zip(reversed((0, 41.4, 69.5, 81.4)), colors): cos_theta = numpy.cos(numpy.radians(zenith)) emu = minimum_muon_energy(overburden(cos_theta, depth)) correlated = correlated_passing_rate(enu, emu, cos_theta) uncorr_numu = uncorrelated_passing_rate(enu, emu, cos_theta, kind='numu') uncorr_nue = uncorrelated_passing_rate(enu, emu, cos_theta, kind='nue') pylab.plot(enu, correlated, color=color, label='%d' % zenith) pylab.plot(enu, correlated * uncorr_numu, color=color, ls=':') pylab.plot(enu, uncorr_nue, color=color, ls='--') pylab.semilogx() pylab.ylim((0, 1)) pylab.ylabel('Passing fraction') pylab.xlabel('Neutrino energy [GeV]') olegend = pylab.legend(loc='lower left', title='Zenith [deg]') pylab.legend( ax.lines[:3], (r'$\nu_{\mu}$ (Correlated)', r'$\nu_{\mu}$ (Total)', r'$\nu_{e}$'), loc='center right', prop=dict(size='small')) ax.add_artist(olegend) pylab.title('Atmospheric neutrino self-veto at %d m depth' % (opts.depth)) pylab.show()
def plot(): (n, P, eP, A, eA, ALines) = numbers() pylab.subplot(2, 1, 1) pylab.errorbar(n, P, eP, ecolor='r', linewidth=3, fmt=None) pylab.semilogx() pylab.xticks([2, 4, 8, 16, 32, 64, 128], ['2', '4', '8', '16', '32', '64', '128']) pylab.axis([1, 256, 4, 18]) pylab.ylabel('Precision of 95% Confidence') pylab.title( 'Estimating Time Constant of RC circuit, Gaussian Noise, 1000 trials') pylab.subplot(2, 1, 2) pylab.plot(n, A, '*', color='r', markersize=12) #pylab.axhspan(ALines[0],ALines[0],color='b') pylab.axhspan(ALines[1], ALines[1], color='b') pylab.axhspan(ALines[2], ALines[2], color='b') pylab.semilogx() pylab.xticks([2, 4, 8, 16, 32, 64, 128], ['2', '4', '8', '16', '32', '64', '128']) pylab.axis([1, 256, 0.9, 1.0]) pylab.text(1.5, 0.95, 'Accurate') pylab.text(1.5, 0.99, 'Under-Confident') pylab.text(1.5, 0.91, 'Over-Confident') pylab.xlabel('Number of Data Points') pylab.ylabel('Accuracy of 95% Confidence') pylab.ion()
def prad_err_hist(): old = cksgaia.io.load_table('j17') new = cksgaia.io.load_table(full_sample) old['iso_prad_frac_err'] = cksgaia.errors.frac_err(old['iso_prad'], old['iso_prad_err1'], old['iso_prad_err2']) new['gdir_prad_frac_err'] = cksgaia.errors.frac_err( new['gdir_prad'], new['gdir_prad_err1'], new['gdir_prad_err2']) old['iso_prad_frac_err'] *= 100 new['gdir_prad_frac_err'] *= 100 print(len(old), len(new)) med_old = np.nanmedian(old['iso_prad_frac_err']) med_new = np.nanmedian(new['gdir_prad_frac_err']) xbins = np.logspace(np.log10(0.5), np.log10(50.0), 50) old['iso_prad_frac_err'].hist(bins=xbins, histtype='step', lw=2, color='0.7') new['gdir_prad_frac_err'].hist(bins=xbins, histtype='step', lw=2, color='k') pl.axvline(med_old, color='0.7', linestyle='dashed', lw=2) pl.axvline(med_new, color='k', linestyle='dashed', lw=2) pl.annotate("median = {:.0f}%".format(np.round(med_old)), xy=(med_old, 200), xycoords='data', xytext=(-15, 0), textcoords='offset points', rotation=90, verticalalignment='left') pl.annotate("median = {:.0f}%".format(np.round(med_new)), xy=(med_new, 200), xycoords='data', xytext=(-15, 0), textcoords='offset points', rotation=90, verticalalignment='left') pl.xlim(0.5, 40.0) # pl.ylim(0, 130) pl.ylabel('Number of Planets') pl.xlabel('Fractional Planet Radius Uncertainty [%]') # pl.title('NEA') pl.semilogx() ax = pl.gca() ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%0.1f')) pl.xticks([1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 30.0]) pl.grid(False) pl.legend(['Johnson+17', 'this work'], loc='upper left')
def plot_mass_magnitude(self, mag, savefile=None): """ Make a standard mass-luminosity relation plot for this isochrone. Parameters ---------- mag : string The name of the magnitude column to be plotted. savefile : string (default None) If a savefile is specified, then the plot will be saved to that file. """ plt.clf() plt.semilogx(self.points['mass'], self.points[mag], 'k.') plt.gca().invert_yaxis() plt.xlabel(r'Mass (M$_\odot$)') plt.ylabel(mag + ' (mag)') fmt_title = 'logAge={0:.2f}, d={1:.2f} kpc, AKs={2:.2f}' plt.title(fmt_title.format(self.points.meta['LOGAGE'], self.points.meta['DISTANCE']/1e3, self.points.meta['AKS'])) if savefile != None: plt.savefig(savefile) return
def check_recovered_positions(self, toleranceArcsec=12.0, SNRKey='SNR', SNRMax=10.0, plotLabel=None, plotsDir="plots"): """Blah """ inTab = self.inTab outTab = self.outTab rDeg = self.rDeg SNRs = outTab[SNRKey] medOffsetArcmin = np.median(rDeg) * 60 SNRMask = np.less(SNRs, SNRMax) medOffsetArcmin_SNR10 = np.median(rDeg[SNRMask]) * 60 #[SNRMask])*60 print('... median recovered position offset = %.2f" (full sample)' % (medOffsetArcmin * 60)) label = 'median recovered position offset = %.2f" (SNR < 10)' % ( medOffsetArcmin_SNR10 * 60) print("... %s" % (label)) if plotLabel is not None: plt.figure(figsize=(10, 8)) plt.plot(SNRs, rDeg * 3600., 'r.') plt.semilogx() plt.xlabel("SNR") plt.ylabel('Position offset (")') plt.title(label, fontdict={'size': plotTitleSize}) plt.savefig(plotsDir + os.path.sep + plotLabel + "_posRec.png") plt.close() if medOffsetArcmin_SNR10 * 60 > toleranceArcsec: self._status = "FAILED" else: self._status = "SUCCESS"
def flipPlot(minExp, maxExp): """Assumes minExp and maxExp positive integers; minExp < maxExp Plots results of 2**minExp to 2**maxExp coin flips""" ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2 ** exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.rcParams['lines.markersize'] = 10 pylab.semilogx() pylab.semilogy() pylab.plot(xAxis, diffs, 'bo') pylab.figure() pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('Heads/Tails') pylab.plot(xAxis, ratios)
def compare(self, x, precision, target, linear=False, diff="relative"): r""" Compare the different computation methods using the given precision. """ if precision == 'single': #n=11; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) #n=23; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) pass elif precision == 'double': #n=53; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) #n=83; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) pass plotdiff(x, target, self.call_numpy(x, precision), 'numpy ' + precision, diff=diff) plotdiff(x, target, self.call_ocl(x, precision, 0), 'OpenCL ' + precision, diff=diff) pylab.xlabel(self.xaxis) if diff == "relative": pylab.ylabel("relative error") elif diff == "absolute": pylab.ylabel("absolute error") else: pylab.ylabel(self.name) pylab.semilogx(x, target, '-', label="true value") if linear: pylab.xscale('linear')
def plotBode(f*g, lowerFreq, higherFreq = None): """' plot Bode diagram using matplotlib Default frequency width is 3 decades '""" import pylab as py #import pdb; pdb.set_trace() if ( higherFreq == None): rangeAt = 1000.0 # 3 decade else: assert higherFreq > lowerFreq rangeAt = float(higherFreq)/lowerFreq N = 128 lstScannAngFreqAt = [2*sc.pi*1j*lowerFreq*sc.exp( sc.log(rangeAt)*float(k)/N) for k in range(N)] t = [ lowerFreq*sc.exp(sc.log(rangeAt)*float(k)/N) for k in range(N)] py.subplot(211) py.loglog( t, [(abs(f*g(x))) for x in lstScannAngFreqAt] ) py.ylabel('gain') py.grid(True) py.subplot(212) py.semilogx( t, [sc.arctan2(f*g(zz).imag, f*g(zz).real) for zz in lstScannAngFreqAt]) py.ylabel('phase') py.grid(True) py.gca().xaxis.grid(True, which='minor') # minor grid on too py.show()
def flipPlot(minExp, maxExp): """ Assumes minExp and maxExp positive integers; minExp < maxExp Plots results of 2**minExp to 2**maxExp coin flips""" ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.title('Difference between heads and tails') pylab.xlabel('Number of flips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.plot(xAxis, diffs, 'bo') pylab.semilogx() pylab.semilogy() pylab.figure() pylab.title('Heads/Tails Ratio') pylab.xlabel('Number of flips') pylab.ylabel('#Heads/#Tails') pylab.plot(xAxis, ratios, 'bo') pylab.semilogx() pylab.show()
def print_ROC(multi_result, n_imgs, save_filename = None, show_curve = True, xmin = None, ymin = None, xmax = None, ymax = None, grid_major = False, grid_minor = False): points = [] n_imps = float(n_imgs) for result in multi_result: tp = float(result.n_true_positives()) fp = float(result.n_false_positives()) fn = float(result.n_false_negatives()) #n_imgs = float(len(result.images)) points.append((fp / n_imgs, tp / (tp + fn))) points.sort() if save_filename != None: f = open(save_filename, "w") cPickle.dump(points, f) f.close() if show_curve: pylab.semilogx([a[0] for a in points], [a[1] for a in points]) if xmin != None: pylab.axis(xmin = xmin) if xmax != None: pylab.axis(xmax = xmax) if ymin != None: pylab.axis(ymin = ymin) if ymax != None: pylab.axis(ymax = ymax) pylab.xlabel("False positives per image (FPPI)") pylab.ylabel("Detection rate") pylab.show()
def plotResistance(): dic = makeListResistanceSims(3) pl.close("all") colors = [] for k,key in enumerate(np.sort(dic.keys())): pl.figure(k,(11,7)) pl.title("starting property violation: %s"%key) low = 0 high = 0 if rootDir == '/Users/maithoma/work/compute/pgames_resistance/': range = np.arange(key,0.11,0.005) iter = 2000 elif rootDir == '/Users/maithoma/work/compute/pgames_resistance2/': range = np.arange(0.043,0.062,0.002) iter = 4000 color = np.linspace(0.7,0.3,len(range)) for i,s in enumerate(range): for j,jx in enumerate(dic[key]): if j==0: label = str(s) elif j>0: label = '_nolegend_' filename = 'iter_%s_l_100_h_100_d_0.500_cl_0.500_ns_4_il_1.000_q_0.000_M_5_m_0.000_s_%.4f_%s.csv'%(iter,s,jx) print filename #if s < 0.04 or s > 0.065: # continue try: x,y = coopLevel(filename) #print key,i,jx,s,y[-1],filename if float(y[-1]) < 0.7: pl.semilogx(x,y,alpha=1,lw= 1.,label=label,color=[color[i],color[i],1]) #pl.semilogx(x,y,alpha=1,lw= 1.,label=label,color='c') low +=1 elif float(y[-1]) > 0.7: pl.semilogx(x,y,alpha=1,lw= 1.,label=label,color=[color[i],1,color[i]]) #pl.semilogx(x,y,alpha=1,lw= 1.,label=label,color='m') high +=1 except: continue #pl.text(100000,0.85,"high:%s \n low:%s"%(high,low)) pl.legend(loc=0) pl.xlabel("Iterations (log10)") pl.ylabel("Cooperation Level") pl.xlim(xmax=5*10**8) pl.ylim(0.,1)
def flip_plot(min_exp, max_exp): """ 由min_exp,max_exp生成 一系列 2 ** min_exp, 2**(min_exp+1) .... 2 ** max_exp。 这些序列将作为 num_flips的实际参数 """ ratios, diffs, x_axis = [], [], [] for exp in range(min_exp, max_exp + 1): x_axis.append(2**exp) for num_flip in x_axis: num_heads = 0 for flip in range(num_flip): if 'H' == random.choice(["H", "T"]): num_heads += 1 num_tails = num_flip - num_heads try: ratios.append(num_heads / num_tails) diffs.append(abs(num_heads - num_tails)) except ZeroDivisionError: continue pylab.figure(1) pylab.semilogx(base=2) # 修改代码 pylab.semilogy() # 修改代码 pylab.title(" Difference Between Heads and Tails") pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.plot(x_axis, diffs, 'ko') # 修改代码 pylab.figure(2) pylab.semilogx(base=2) # 修改代码 pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips ') pylab.ylabel(' Heads/ #Tails') pylab.plot(x_axis, ratios, 'ko') # 修改代码 pylab.show()
def test_regularization(): np.random.seed(1) n_features = 5 func = get_test_model(n_features=n_features) dataset_train, labels_train = get_random_dataset(func, n_datapoints=1e3, n_features=n_features, noise_level=1.e-10) alphas = 10**np.linspace(-1, 3, 10) alpha_coeffs = np.zeros([n_features, len(alphas)]) for i, alpha in enumerate(alphas): gen_lasso = gl.GeneralizedLasso(alpha=alpha, max_iter=2000, link_function=None) gen_lasso.fit(dataset_train, labels_train[:,0]) alpha_coeffs[:,i] = gen_lasso.coeffs[:,0] # Plot results for i in range(n_features): pl.semilogx(alphas, alpha_coeffs[i,:], label='coeff no %d' % i) pl.semilogx(alphas, np.ones_like(alphas)*func.coeffs[i], ':') pl.legend(loc='best') pl.title('Test regularization') pl.ylabel('Coeff value') pl.xlabel('alpha') pl.show()
def logscale_rad(axis='y'): if axis == 'x': pl.semilogx() pl.xlabel('Planet Size [Earth radii]') pl.xticks([.7, 1.0, 1.3, 1.8, 2.4, 3.5, 4.5, 6, 8.0]) # pl.xticks(np.logspace(np.log10(0.7), np.log10(8), 6)) ax = pl.gca() ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.xaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%0.1f')) pl.xlim(0.7, 6.0) elif axis == 'y': pl.semilogy() pl.ylabel('Planet Size [Earth radii]') pl.yticks([.7, 1.0, 1.3, 1.8, 2.4, 3.5, 4.5, 6, 8.0]) # pl.xticks(np.logspace(np.log10(0.7), np.log10(8), 6)) ax = pl.gca() ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.yaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%0.1f')) pl.ylim(0.7, 6.0) else: print("Please specify x or y axis (default: x)") return ax
def flipPlot(minExp, maxExp): """minExpとmaxExpは minExp < maxExp を満たす正の整数とする 2**minExp から 2**maxExp 回のコイン投げの結果をプロットする""" ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.title('Difference Between Heads and Tails ') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.semilogx() pylab.semilogy() pylab.plot(xAxis, diffs, 'bo') pylab.figure() pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('#Heads/#Tails') pylab.semilogx() pylab.semilogy() pylab.plot(xAxis, ratios, 'bo')
def drunkTest(walkLengths, numTrials, dClass): """walkLength: 0 以上の整数シークエンス numTrials: 正の整数 dClass: Drunk型のサブクラス walkLength の各要素を酔歩の移動回数として, numTrials 回の酔歩を シミュレートする simWalks を実行し, 結果を出力する. """ means = [] for numSteps in walkLengths: distances = simWalks(numSteps, numTrials, dClass) print(dClass.__name__, 'random walk of', numSteps, 'steps') print(' Mean =', sum(distances) / len(distances), 'CV =', CV(distances)) print(' Max =', max(distances), 'Min =', min(distances)) means.append(sum(distances) / len(distances)) styleChoice = styleIterator(('b-', 'r:', 'm-.')) curStyle = styleChoice.nextStyle() pylab.plot(walkLengths, means, curStyle, label='Distance form origin') pylab.plot(walkLengths, [pow(x, 0.5) for x in walkLengths], styleChoice.nextStyle(), label='Square root of steps') pylab.title('Average Distance from Origine ({} trials)'.format(numTrials)) pylab.xlabel('Number of Steps') pylab.ylabel('Distance from Origin') pylab.legend(loc='best') pylab.semilogx() pylab.semilogy() pylab.show()
def chunked_timing(X, Y, axis=1, metric="euclidean", **kwargs): sizes = [20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000] t0 = time.time() original(X, Y, axis=axis, metric=metric, **kwargs) t1 = time.time() original_timing = t1 - t0 chunked_timings = [] for batch_size in sizes: print("batch_size: %d" % batch_size) t0 = time.time() chunked(X, Y, axis=axis, metric=metric, batch_size=batch_size, **kwargs) t1 = time.time() chunked_timings.append(t1 - t0) import pylab as pl pl.semilogx(sizes, chunked_timings, '-+', label="chunked") pl.hlines(original_timing, sizes[0], sizes[-1], color='k', label="original") pl.grid() pl.xlabel("batch size") pl.ylabel("execution time (wall clock)") pl.title("%s %d / %d (axis %d)" % ( str(metric), X.shape[0], Y.shape[0], axis)) pl.legend() pl.savefig("%s_%d_%d_%d" % (str(metric), X.shape[0], Y.shape[0], axis)) pl.show()
def flipPlot(minExp, maxExp): ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) print "xAxis: ", xAxis for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.figure() pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails') pylab.plot(xAxis, diffs, 'bo') #do not connect, show dot pylab.semilogx() pylab.semilogy() pylab.figure() pylab.plot(xAxis, ratios, 'bo') #do not connect, show dot pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('Heads/Tails') pylab.semilogx()
def tossPlot(minTrials, maxTrials): ratios, diffs, xaxis = [], [], [] #diffs = [] #xaxis = [] for n in range(minTrials, maxTrials + 1): xaxis.append(2**n) #print(xaxis) #the number of times coin is tossed for numFlips in xaxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads #print(numHeads, numTails) ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) #print(ratios, diffs) pylab.title('Difference between Heads and Tails') pylab.semilogx('Number of tosses') pylab.ylabel('abs(#ofHeads - #ofTails)') pylab.plot(xaxis, diffs, 'bo') pylab.figure() pylab.title('Heads/Tails ratios') pylab.semilogx('Number of tosses') pylab.ylabel('#ofHeads/#ofTails') pylab.plot(xaxis, ratios, 'bo')
def flipPlot(minExp,maxExp): ratios = [] diffs = [] xAxis = [] for exp in range(minExp,maxExp+1): xAxis.append(2 ** exp) print "xAxis: ", xAxis for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads/float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.figure() pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails') pylab.plot(xAxis, diffs, 'bo') #do not connect, show dot pylab.semilogx() pylab.semilogy() pylab.figure() pylab.plot(xAxis, ratios, 'bo') #do not connect, show dot pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('Heads/Tails') pylab.semilogx()
def figure(self, err=1e5): now_error, Minb, Maxa = self.error() if float(now_error) <= err: self.freq = np.linspace(100, 100 / np.sqrt(self.C2 * self.L2), 1E6) a = self.R1 + self.freq * complex("j") * self.L1 b = self.R2 + self.freq * complex("j") * self.L2 + 1 / ( self.freq * complex("j") * self.C2) self.impedance = abs(a * b / (a + b)) pylab.plot(self.freq, self.impedance) pylab.semilogx(self.freq, self.impedance) pylab.xlabel("Freq", color="red") pylab.ylabel("Impedance", color="red") pylab.text(1000, self.impendenceMin(max(Minb, Maxa)), 'Combination=' + self.Name) pylab.text(Minb, self.impendenceMin(Minb), 'Min') pylab.text(Maxa, self.impendenceMin(Maxa), 'Max') pylab.text( (Maxa + Minb) / 1000, 10 * self.impendenceMin(max(Minb, Maxa)), 'wave propagation = %s' % str(abs(self.impendenceMin(Maxa) - self.impendenceMin(Minb)))) pylab.title("Error: %s%%" % now_error, color="black") pylab.gca().spines['right'].set_color('none') pylab.gca().spines['top'].set_color('none') #pylab.savefig('figure_test\Nums-%s and Name-(%s).png' % (self.Num, self.Name)) pylab.show() #pylab.clf() return float(now_error) else: return False
def sums2nloop(model_input,images_input,iterations): '''Run through a loop of calculating the summed S/N for a set of data. This is useful if you'd like to see how well we'd do as we keep adding more and more data together in order to attempt to extract a signal. ''' if images_input == "simdata": header = model_input.simdata() else: header = getheaderinfo(images_input) # iterations = header['numexp'] snvec = numpy.zeros((iterations,2)) for i in range(0,iterations): snvec[i] = models2n(i+1,model_input,images_input) print snvec # GRAB EXPOSURE TIMES timearr = header['tstart'][0:iterations] # should be error bar from tstart to tstop # Plot the results pylab.semilogx(timearr,snvec[:,1],linestyle='',marker='o') pylab.semilogx(timearr,snvec[:,0],linestyle='',marker='x') pylab.xlim(50,200000) pylab.xlabel('Time') pylab.ylabel('Summed S/N (not a lightcurve!)') plottitle = 'Model: ' + model_input.name + ', Data: ' + images_input pylab.title(plottitle)
def flipPlot(minExp, maxExp, numTrials): meanRatios = [] meanDiffs = [] ratiosSDs = [] diffsSDs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: ratios = [] diffs = [] for t in range(numTrials): numHeads, numTails = runTrial(numFlips) ratios.append(numHeads/float(numTails)) diffs.append(abs(numHeads - numTails)) meanRatios.append(sum(ratios)/numTrials) meanDiffs.append(sum(diffs)/numTrials) ratiosSDs.append(stdDev(ratios)) diffsSDs.append(stdDev(diffs)) pylab.plot(xAxis, meanRatios, 'bo') pylab.title('Mean Heads/Tails Ratios (' + str(numTrials) + ' Trials)') pylab.xlabel('Number of Flips') pylab.ylabel('Mean Heads/Tails') pylab.semilogx() pylab.figure() pylab.plot(xAxis, ratiosSDs, 'bo') pylab.title('SD Heads/Tails Ratios (' + str(numTrials) + ' Trials)') pylab.xlabel('Number of Flips') pylab.ylabel('Standard Deviation') pylab.semilogx() pylab.semilogy()
def plot(self, marker='o', color='red', m=0, M=6000): """Plots the position / height of the peaks in the well .. plot:: :include-source: from fragment_analyser import Line, fa_data l = Line(fa_data("alternate/peaktable.csv")) well = l.wells[0] well.plot() """ import pylab if len(self.df) == 0: print("Nothing to plot (no peaks)") return x = self.df['Size (bp)'].astype(float).values y = self.df['RFU'].astype(float).values pylab.stem(x, y, marker=marker, color=color) pylab.semilogx() pylab.xlim([1, M]) pylab.ylim([0, max(y)*1.2]) pylab.grid(True) pylab.xlabel("size (bp)") pylab.ylabel("RFU") return x, y
def testScalingCollapse(): """Simple test of MakeScalingPlot and ScaleIt""" p = {} ell = {} sig = {} p[(100, 2)] = numpy.array([4., 8., 12.]) ell[(100, 2)] = numpy.array([10., 20., 30.]) sig[(100, 2)] = numpy.array([0.5, 0.5, 0.5]) p[(200, 4)] = numpy.array([1., 2., 3.]) ell[(200, 4)] = numpy.array([11., 18., 33.]) sig[(200, 4)] = numpy.array([1.0, 2.0, 3.0]) pylab.figure(1) MakeScalingPlot(p, ell, yerrdata=sig) pylab.figure(2) sig = {} sig[(100, 2)] = numpy.array([0.5, 0.5, 0.5]) sig[(200, 4)] = numpy.array([1.0, 2.0, 3.0]) p_sc, ell_sc, ellerr_sc = MakeScalingPlot(p, ell, yerrdata=sig, xform='p->p*Z*L', yform='ell->(2*ell*Z)/L', yerrform='sig->(2*sig*Z)/L', keyNames=('L', 'Z'), showIt=False, loc=3) pylab.semilogx() pylab.show() return p, ell
def extrapolate(n, y, tolerance=1e-15, plot=False, call_show=True): "Extrapolate functional value Y from sequence of values (n, y)." # Make sure we have NumPy arrays n = array(n) y = array(y) # Create initial "bound" Y0 = 0.99*y[-1] Y1 = 1.01*y[-1] # Compute initial interior points phi = (sqrt(5.0) + 1.0) / 2.0 Y2 = Y1 - (Y1 - Y0) / phi Y3 = Y0 + (Y1 - Y0) / phi # Compute initial values F0, e, nn, ee, yy = _eval(n, y, Y0) F1, e, nn, ee, yy = _eval(n, y, Y1) F2, e, nn, ee, yy = _eval(n, y, Y2) F3, e, nn, ee, yy = _eval(n, y, Y3) # Solve using direct search (golden ratio fraction) while Y1 - Y0 > tolerance: if F2 < F3: Y1, F1 = Y3, F3 Y3, F3 = Y2, F2 Y2 = Y1 - (Y1 - Y0) / phi F2, e, nn, ee, yy = _eval(n, y, Y2) else: Y0, F0 = Y2, F2 Y2, F2 = Y3, F3 Y3 = Y0 + (Y1 - Y0) / phi F3, e, nn, ee, yy = _eval(n, y, Y3) print Y0, Y1 # Compute reference value Y = 0.5*(Y0 + Y1) # Print results print print "Reference value:", Y # Plot result if plot: pylab.figure() pylab.subplot(2, 1, 1) pylab.title("Reference value: %g" % Y) pylab.semilogx(n, y, 'b-o') pylab.semilogx(nn, yy, 'g--') pylab.subplot(2, 1, 2) pylab.loglog(n, e, 'b-o') pylab.loglog(nn, ee, 'g--') pylab.grid(True) if call_show: pylab.show() return Y
def _plotBodeTrimmed(fvector, gvector): # Draw plot plt.figure(facecolor="white") # White border # Magnitude ax1 = pl.subplot(2, 1, 1) pl.semilogx(fvector, dB(np.absolute(gvector))) pl.xlabel('Frequency (Hz)') # Set X label pl.ylabel('Magnitude (dB)') # Set Y label pl.title('Bode response plot') # Set title pl.grid(True) # Remove high frequency phase hfreq = 1.0 / (min_sample * 20.0) fv = [] pv = [] for f, g in zip(fvector, gvector): if f < hfreq: fv.append(f) pv.append(np.angle(g, deg=True)) # Phase plot ax2 = pl.subplot(2, 1, 2, sharex=ax1) if fv != []: pl.semilogx(fv, pv) pl.xlabel('Frequency (Hz)') # Set X label pl.ylabel('Phase (deg)') # Set Y label pl.grid(True) pl.show() pl.close()
def show_blocking(self, plotfile=''): '''Print out the blocking data and show a graph of the behaviour of the standard error with block size. If plotfile is given, then the graph is saved to the specifed file rather than being shown on screen.''' # print blocking output # header... print '%-11s' % ('# of blocks'), fmt = '%-14s %-15s %-18s ' header = ('mean (X_%i)', 'std.err. (X_%i)', 'std.err.err. (X_%i)') for data in self.data: data_header = tuple(x % (data.data_col) for x in header) print fmt % data_header, for key in self.covariance: str = 'cov(X_%s,X_%s)' % tuple(key.split(',')) print '%-14s' % (str), for key in self.combination_stats: fmt = ['mean (X_%s'+self.combination+'X_%s)', 'std.err. (X_%s'+self.combination+'X_%s)'] strs = tuple([s % tuple(key.split(',')) for s in fmt]) print '%-16s %-18s' % strs, print # data block_fmt = '%-11i' fmt = '%-#14.12g %-#12.8e %-#18.8e ' for s in range(len(self.data[0].stats)): print block_fmt % (self.data[0].stats[s].block_size), for data in self.data: print fmt % (data.stats[s].mean, data.stats[s].se, data.stats[s].se_error), for cov in self.covariance.itervalues(): print '%+-#14.5e' % (cov[s]), for comb in self.combination_stats.itervalues(): print '%-#16.12f %-#18.12e' % (comb[s].mean, comb[s].se), print # plot standard error if PYLAB: # one sub plot per data set. nplots = len(self.data) for (i, data) in enumerate(self.data): pylab.subplot(nplots, 1, i+1) blocks = [stat.block_size for stat in data.stats] se = [stat.se for stat in data.stats] se_error = [stat.se_error for stat in data.stats] pylab.semilogx(blocks, se, 'g-', basex=2, label=r'$\sigma(X_{%s})$' % (data.data_col)) pylab.errorbar(blocks, se, yerr=se_error, fmt=None, ecolor='g') xmax = 2**pylab.ceil(pylab.log2(blocks[0]+1)) pylab.xlim(xmax, 1) pylab.ylabel('Standard error') pylab.legend(loc=2) if i != nplots - 1: # Don't label x axis points. ax = pylab.gca() ax.set_xticklabels([]) pylab.xlabel('# of blocks') if plotfile: pylab.savefig(plotfile) else: pylab.draw() pylab.show()
def check_C_testset(mss_id): import pylab import expenv import numpy from helper import Options from method_hierarchy_svm_new import Method #from method_augmented_svm_new import Method #costs = 10000 #[float(c) for c in numpy.exp(numpy.linspace(numpy.log(10), numpy.log(20000), 6))] costs = [float(c) for c in numpy.exp(numpy.linspace(numpy.log(0.4), numpy.log(10), 6))] print costs mss = expenv.MultiSplitSet.get(mss_id) train = mss.get_train_data(-1) test = mss.get_eval_data(-1) au_roc = [] au_prc = [] for cost in costs: #create mock param object by freezable struct param = Options() param.kernel = "WeightedDegreeStringKernel" param.wdk_degree = 10 param.transform = cost param.base_similarity = 1.0 param.taxonomy = mss.taxonomy param.id = 666 #param.cost = cost param.cost = 10000 param.freeze() # train mymethod = Method(param) mymethod.train(train) assessment = mymethod.evaluate(test) au_roc.append(assessment.auROC) au_prc.append(assessment.auPRC) print assessment assessment.destroySelf() pylab.title("auROC") pylab.semilogx(costs, au_roc, "-o") pylab.show() pylab.figure() pylab.title("auPRC") pylab.semilogx(costs, au_prc, "-o") pylab.show() return (costs, au_roc, au_prc)
def plotLitSersic(outSB=None,plot=True): # plots a variety of Sersic profiles with values from the literature # can return the profiles in an array, can specify central SB (mag/arcsec^2) # can turn off plotting if desired # literature values # [KB99, Courteau2011_E, Courteau2011_M, Dorman2013] # Sersic index n_b = np.array([2.19, 2.18, 1.83, 1.917]) # half-light radius, in kpc R_e_kpc = np.array([1.0, 0.82, 0.74, 0.778]) # in pc R_e = R_e_kpc*1000. # central surface brightness, in mag arcsec^-2 # [V, 3.6 um, I, I] (last two are same data set) if outSB is None: mu_e = np.array([17.55, 15.77, 17.73, 17.849]) else: mu_e = np.ones(4)*outSB # convert to central intensity I_e = 10.**(mu_e/(-2.5)) # radius to calculate for (radius of data is 2" - going out slightly further) radarcsec = 60. radpc = radarcsec*3.73 R = np.arange(radpc) #R = np.arange(radarcsec) I_b = np.zeros((len(n_b),len(R)),dtype=float) mu_b = np.zeros((len(n_b),len(R)),dtype=float) if plot: fig=py.figure(2) py.clf() for i in np.arange(len(n_b)): # from Cappaccioli 1989 b_n = 1.9992*n_b[i] - 0.3271 negb_n = -1. * b_n I_b[i,:] = I_e[i]*np.exp(negb_n*( ((R/R_e[i])**(1./n_b[i])) - 1.)) mu_b[i,:] = -2.5*np.log10(I_b[i,:]) if plot: py.semilogx(R[1:-1],mu_b[i,1:-1]) if plot: py.legend(('KB99 (V band)','C11_E (3.6 $\mu$m)','C11_M (I band)','D13 (I band)')) py.ylim(mu_b.max()+0.5,mu_b.min()-0.5) py.ylabel('$\mu$ (mag arcsec$^{-2}$)') py.xlabel('Radius (pc)') ax1 = fig.add_subplot(111) ax2 = ax1.twiny() ax2.set_xlim(ax1.get_xlim()) ax2.set_xscale('log') ax2.set_xticks(np.array([3.73,37.3,223.])) ax2.set_xticklabels(['1','10','60']) ax2.set_xlabel('Radius (arcsec)') return mu_b, I_b, R
def plot_precision(self): x = self.n_list y = [i - np.pi for i in self.pi_list] plt.figure() plt.semilogx(x,y,'o') plt.xlabel('n') plt.ylabel('pi estimate - pi') plt.show()
def Intensity(self,PhotonE=3e3, Rho=10.28, Distance=TestRange,Plot=True): MuRho = self.muValue(PhotonE) IAtten = exp(-MuRho*Rho*Distance*100.0) if Plot==True: # pl.loglog(Distance,IAtten) pl.semilogx(Distance,IAtten) pl.xlabel('Distance [m]') pl.ylabel('Relative Intensity [I/Io]') return Distance,IAtten
def main(): # Setup parameters for simulation and plotting simdt= 1e-2 plotDt= 1 # Factors to change in the dose concentration in log scale factorExponent = 10 ## Base: ten raised to some power. factorBegin = -20 factorEnd = 21 factorStepsize = 1 factorScale = 10.0 ## To scale up or down the factors # Load Model and set up the steady state solver. # model = sys.argv[1] # To load model from a file. model = './19085.cspace' modelPath, modelName, modelType = parseModelName(model) outputDir = modelPath modelId = moose.loadModel(model, 'model', 'ee') dosePath = '/model/kinetics/b/DabX' # The dose entity ksolve, state = setupSteadyState( simdt, plotDt) vol = moose.element( '/model/kinetics' ).volume iterInit = 1000 solutionVector = [] factorArr = [] enz = moose.element(dosePath) init = enz.kcat # Dose parameter # Change Dose here to . for factor in range(factorBegin, factorEnd, factorStepsize ): scale = factorExponent ** (factor/factorScale) enz.kcat = init * scale print(factor) for num in range(iterInit): stateType, solStatus, vector = getState( ksolve, state, vol) if solStatus == 0: solutionVector.append(vector[0]/sum(vector)) factorArr.append(scale) joint = np.array([factorArr, solutionVector]) joint = joint[:,joint[1,:].argsort()] # Plot dose response. fig0 = plt.figure() pylab.semilogx(joint[0,:],joint[1,:],marker="o",label = 'concA') pylab.xlabel('Dose') pylab.ylabel('Response') pylab.suptitle('Dose-Reponse Curve for a bistable system') pylab.legend(loc=3) #plt.savefig(outputDir + "/" + modelName +"_doseResponse" + ".png") plt.show() #plt.close(fig0) quit()
def plotResults(results): numFlips, avgLongestRuns = tuple(zip(*results)) pylab.figure(1) pylab.clf() pylab.title("Longest heads run") pylab.xlabel("Number of flips") pylab.ylabel("Average longest heads run") pylab.semilogx() pylab.plot(numFlips, avgLongestRuns, 'ro-')