def PlotLine(type): i=j=0 pylab.figure(type) if type==0: pylab.title("Geomagnetism") pylab.xlabel("Distance") pylab.ylabel("Value") elif type==1: pylab.title("Compass") pylab.xlabel("Distance") pylab.ylabel("Value") for path in pathlist: f = open(path) f.readline() data = np.loadtxt(f) dataAfterfilter = filters.median(data,10) if type == 0: pylab.plot(dataAfterfilter, color[i] ,label =lablelist[i]) i=i+1 pylab.legend() elif type == 1: pylab.plot(data[:,1], color[i] ,label =lablelist[i]) i=i+1 pylab.legend() pass
def test1(): import numpy as np import pylab from scipy import sparse from regreg.algorithms import FISTA from regreg.atoms import l1norm from regreg.container import container from regreg.smooth import quadratic Y = np.random.standard_normal(500); Y[100:150] += 7; Y[250:300] += 14 sparsity = l1norm(500, lagrange=1.0) #Create D D = (np.identity(500) + np.diag([-1]*499,k=1))[:-1] D = sparse.csr_matrix(D) fused = l1norm.linear(D, lagrange=19.5) loss = quadratic.shift(-Y, lagrange=0.5) p = container(loss, sparsity, fused) soln1 = blockwise([sparsity, fused], Y) solver = FISTA(p) solver.fit(max_its=800,tol=1e-10) soln2 = solver.composite.coefs #plot solution pylab.figure(num=1) pylab.clf() pylab.scatter(np.arange(Y.shape[0]), Y, c='r') pylab.plot(soln1, c='y', linewidth=6) pylab.plot(soln2, c='b', linewidth=2)
def simulationWithoutDrugNick(numViruses, maxPop, maxBirthProb, clearProb, numTrials): """ Run the simulation and plot the graph for problem 3 (no drugs are used, viruses do not have any drug resistance). For each of numTrials trial, instantiates a patient, runs a simulation for 300 timesteps, and plots the average virus population size as a function of time. numViruses: number of SimpleVirus to create for patient (an integer) maxPop: maximum virus population for patient (an integer) maxBirthProb: Maximum reproduction probability (a float between 0-1) clearProb: Maximum clearance probability (a float between 0-1) numTrials: number of simulation runs to execute (an integer) """ #Instantiate the viruses first, the patient second viruses= [ SimpleVirus(maxBirthProb, clearProb) for i in range(numViruses) ] patient = Patient(viruses, maxPop) #Execute the patient.update method 300 times for 100 trials steps = 300 countList = [0 for i in range(300)] for trial in range(numTrials): for timeStep in range(steps): countList[timeStep] += patient.update() avgList = [ countList[i]/float(numTrials) for i in range(steps) ] #Plot a diagram with xAxis=timeSteps, yAxis=average virus population xAxis = [ x for x in range(steps) ] pylab.figure(2) pylab.plot(xAxis, avgList, 'ro', label='Simple Virus') pylab.xlabel('Number of elapsed time steps') pylab.ylabel('Average size of the virus population') pylab.title('Virus growth in a patient without the aid of any drag') pylab.legend() pylab.show()
def T2_cpmg_process(folder_to_process,plot='y'): """Given a folder of images will process cpmg data and return fitted T2 values and associated uncertainties""" data=img_roi_signal([folder_to_process],['EchoTime']) rois=data[0][0] TEs=data[2][0] mean_signal_mat=data[3] serr_signal_mat=data[4] if plot=='y': plt.figure() spin_echo_fits=[] for jj in np.arange(len(rois)-2): mean_sig=mean_signal_mat[0,jj,:] #serr_sig=serr_signal_mat[0,jj,:] mean_noise=np.mean(mean_signal_mat[0,-2,:]) try: spin_echo_fit = SE_fit_new( np.array(TEs[0:]), mean_sig[0:], mean_noise, 'n' ) if plot=='y': TE_full=np.arange(0,400,1) plt.subplot(4,4,jj+1) plt.plot(np.array(TEs[0:]), mean_sig[0:],'o') plt.plot(TE_full,spin_echo_fit(TE_full)) spin_echo_fits.append(spin_echo_fit) except RuntimeError: print 'RuntimeError' spin_echo=fitting.model('M0*exp(-x/T2)+a',{'M0':0,'T2':0,'a':0}) spin_echo_fits.append(spin_echo) return spin_echo_fits
def embed_two_dimensions(data, vectorizer, size=10, n_components=5, colormap='YlOrRd'): if hasattr(data, '__iter__'): iterable = data else: raise Exception('ERROR: Input must be iterable') import itertools iterable_1, iterable_2 = itertools.tee(iterable) # get labels labels = [] for graph in iterable_2: label = graph.graph.get('id', None) if label: labels.append(label) # transform iterable into sparse vectors data_matrix = vectorizer.transform(iterable_1) # embed high dimensional sparse vectors in 2D from sklearn import metrics distance_matrix = metrics.pairwise.pairwise_distances(data_matrix) from sklearn.manifold import MDS feature_map = MDS(n_components=n_components, dissimilarity='precomputed') explicit_data_matrix = feature_map.fit_transform(distance_matrix) from sklearn.decomposition import TruncatedSVD pca = TruncatedSVD(n_components=2) low_dimension_data_matrix = pca.fit_transform(explicit_data_matrix) plt.figure(figsize=(size, size)) embed_dat_matrix_two_dimensions(low_dimension_data_matrix, labels=labels, density_colormap=colormap) plt.show()
def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None): if h2o.python_username!='kevin': return import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {'family' : 'normal', 'weight' : 'normal', 'size' : 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot (xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot (xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() if eList or fList: plt.show()
def plotear(xi,yi,zi): # mask inner circle interior1 = sqrt(((xi+1.5)**2) + (yi**2)) < 1.0 interior2 = sqrt(((xi-1.5)**2) + (yi**2)) < 1.0 zi[interior1] = ma.masked zi[interior2] = ma.masked p.figure(figsize=(16,10)) pyplot.jet() max=2.8 min=0.4 steps = 50 levels=list() labels=list() for i in range(0,steps): levels.append(int((max-min)/steps*100*i)*0.01+min) for i in range(0,steps/2): labels.append(levels[2*i]) CSF = p.contourf(xi,yi,zi,levels,norm=colors.LogNorm()) CS = p.contour(xi,yi,zi,levels, format='%.3f', labelsize='18') p.clabel(CS,labels,inline=1,fontsize=9) p.title('electrostatic potential of two spherical colloids, R=lambda/3',fontsize=24) p.xlabel('z-coordinate (3*lambda)',fontsize=18) p.ylabel('radial coordinate r (3*lambda)',fontsize=18) # add a vertical bar with the color values cbar = p.colorbar(CSF,ticks=labels,format='%.3f') cbar.ax.set_ylabel('potential (reduced units)',fontsize=18) cbar.add_lines(CS) p.show()
def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) pl.figure() ax = pl.subplot(111) for i in range(digits.data.shape[0]): pl.text( X[i, 0], X[i, 1], str(digits.target[i]), color=pl.cm.Set1(digits.target[i] / 10.0), fontdict={"weight": "bold", "size": 9}, ) if hasattr(offsetbox, "AnnotationBbox"): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1.0, 1.0]]) # just something big for i in range(digits.data.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(digits.images[i], cmap=pl.cm.gray_r), X[i]) ax.add_artist(imagebox) pl.xticks([]), pl.yticks([]) if title is not None: pl.title(title)
def showHistory(self, figNum): pylab.figure(figNum) plot = pylab.plot(self.history, label = 'Test Stock') plot pylab.title('Closing Price, Test ' + str(figNum)) pylab.xlabel('Day') pylab.ylabel('Price')
def plot_stress(self, block_ids=None, fignum=0): block_ids = self.check_block_ids_list(block_ids) # plt.figure(fignum) ax1=plt.gca() plt.clf() plt.figure(fignum) plt.clf() ax0=plt.gca() # for block_id in block_ids: rws = numpy.core.records.fromarrays(zip(*filter(lambda x: x['block_id']==block_id, self.shear_stress_sequences)), dtype=self.shear_stress_sequences.dtype) stress_seq = [] for rw in rws: stress_seq += [[rw['sweep_number'], rw['shear_init']]] stress_seq += [[rw['sweep_number'], rw['shear_final']]] X,Y = zip(*stress_seq) # ax0.plot(X,Y, '.-', label='block_id: %d' % block_id) # plt.figure(fignum+1) plt.plot(rws['sweep_number'], rws['shear_init'], '.-', label='block_id: %d' % block_id) plt.plot(rws['sweep_number'], rws['shear_final'], '.-', label='block_id: %d' % block_id) plt.figure(fignum) ax0.plot([min(self.shear_stress_sequences['sweep_number']), max(self.shear_stress_sequences['sweep_number'])], [0., 0.], 'k-') ax0.legend(loc=0, numpoints=1) plt.figure(fignum) plt.title('Block shear_stress sequences') plt.xlabel('sweep number') plt.ylabel('shear stress')
def posterior(kpl, pk, err, pkfold=None, errfold=None): k0 = n.abs(kpl).argmin() kpl = kpl[k0:] if pkfold is None: print 'Folding for posterior' pkfold = pk[k0:].copy() errfold = err[k0:].copy() pkpos,errpos = pk[k0+1:].copy(), err[k0+1:].copy() pkneg,errneg = pk[k0-1:0:-1].copy(), err[k0-1:0:-1].copy() pkfold[1:] = (pkpos/errpos**2 + pkneg/errneg**2) / (1./errpos**2 + 1./errneg**2) errfold[1:] = n.sqrt(1./(1./errpos**2 + 1./errneg**2)) #ind = n.logical_and(kpl>.2, kpl<.5) ind = n.logical_and(kpl>.15, kpl<.5) #ind = n.logical_and(kpl>.12, kpl<.5) #print kpl,pk.real,err kpl = kpl[ind] pk= kpl**3 * pkfold[ind]/(2*n.pi**2) err = kpl**3 * errfold[ind]/(2*n.pi**2) s = n.logspace(5.,6.5,100) data = [] for ss in s: data.append(n.exp(-.5*n.sum((pk.real - ss)**2 / err**2))) # print data[-1] data = n.array(data) #print data #print s #data/=n.sum(data) data /= n.max(data) p.figure(5) p.plot(s, data) p.plot(s, n.exp(-.5)*n.ones_like(s)) p.plot(s, n.exp(-.5*2**2)*n.ones_like(s)) p.show()
def geweke_plot(data, name, format='png', suffix='-diagnostic', path='./', fontmap = None, verbose=1): # Generate Geweke (1992) diagnostic plots if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4} # Generate new scatter plot figure() x, y = transpose(data) scatter(x.tolist(), y.tolist()) # Plot options xlabel('First iteration', fontsize='x-small') ylabel('Z-score for %s' % name, fontsize='x-small') # Plot lines at +/- 2 sd from zero pyplot((nmin(x), nmax(x)), (2, 2), '--') pyplot((nmin(x), nmax(x)), (-2, -2), '--') # Set plot bound ylim(min(-2.5, nmin(y)), max(2.5, nmax(y))) xlim(0, nmax(x)) # Save to file if not os.path.exists(path): os.mkdir(path) if not path.endswith('/'): path += '/' savefig("%s%s%s.%s" % (path, name, suffix, format))
def plot_matches(self, name, show_below = True, match_maximum = None): """ 対応点を線で結んで画像を表示する 入力: im1,im2(配列形式の画像)、locs1,locs2(特徴点座標) machescores(match()の出力)、 show_below(対応の下に画像を表示するならTrue)""" im1 = self._image_1.get_array_image() im2 = self._image_2.get_array_image() self.appendimages() im3 = self._append_image if self._match_score is None: self.match() locs1 = self._image_1.get_shift_location() locs2 = self._image_2.get_shift_location() if show_below: im3 = numpy.vstack((im3,im3)) pylab.figure(dpi=160) pylab.gray() pylab.imshow(im3, aspect = 'auto') cols1 = im1.shape[1] match_num = 0 for i,m in enumerate(self._match_score): if m > 0 : pylab.plot([locs1[i][0],locs2[m][0]+cols1], [locs1[i][1],locs2[m][1]], 'c') match_num = match_num + 1 if match_maximum is not None and match_num >= match_maximum: break pylab.axis('off') pylab.savefig(name, dpi=160)
def display(self, xaxis, alpha, new=True): """ E.display(xaxis, alpha = .8) :Arguments: xaxis, alpha Plots the CI region on the current figure, with respect to xaxis, at opacity alpha. :Note: The fill color of the envelope will be self.mass on the grayscale. """ if new: figure() if self.ndim == 1: if self.mass>0.: x = concatenate((xaxis,xaxis[::-1])) y = concatenate((self.lo, self.hi[::-1])) fill(x,y,facecolor='%f' % self.mass,alpha=alpha, label = ('centered CI ' + str(self.mass))) else: pyplot(xaxis,self.value,'k-',alpha=alpha, label = ('median')) else: if self.mass>0.: subplot(1,2,1) contourf(xaxis[0],xaxis[1],self.lo,cmap=cm.bone) colorbar() subplot(1,2,2) contourf(xaxis[0],xaxis[1],self.hi,cmap=cm.bone) colorbar() else: contourf(xaxis[0],xaxis[1],self.value,cmap=cm.bone) colorbar()
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 bilinear_interpolation(dataset_name, feat, unfeat, repo, nbt=3): tlist=np.linspace(0,1,nbt) _, _, test=get_data(dataset_name, repo) xtest1, _, _ = test n = xtest1.shape[-1] N = len(xtest1) tuple_index=np.random.permutation(N)[:4] embeddings = feat.predict(xtest1[tuple_index]) interp_array = np.zeros((nbt, nbt, n, n)) for i in range(nbt): for j in range(nbt): x = (tlist[i]*embeddings[0] + (1-tlist[0])*embeddings[1]) y = (tlist[i]*embeddings[2] + (1-tlist[0])*embeddings[3]) x_interp = unfeat.predict(((tlist[j]*x + (1-tlist[j])*y))[None]) interp_array[i,j]=x_interp[0,0] pl.figure(1) for i in range(nbt): for j in range(nbt): nb=i*nbt +j+1 pl.subplot(nbt*100+(nbt)*10 +nb) pl.imshow(interp_array[i,j], cmap='Blues',interpolation='nearest')
def plotHistogram(data, preTime): pylab.figure(1) pylab.hist(data, bins=10) pylab.xlabel("Virus Population At End of Simulation") pylab.ylabel("Number of Trials") pylab.title("{0} Time Steps Before Treatment Simulation".format(preTime)) pylab.show()
def simulation1(numTrials, numSteps, loc): results = {'UsualDrunk': [], 'ColdDrunk': [], 'EDrunk': [], 'PhotoDrunk': [], 'DDrunk': []} drunken_types = {'UsualDrunk': UsualDrunk, 'ColdDrunk': ColdDrunk, 'EDrunk': EDrunk, 'PhotoDrunk': PhotoDrunk, 'DDrunk': DDrunk} for drunken in drunken_types.keys(): #Create field initial_loc = Location(loc[0], loc[1]) field = Field() print "Simu", drunken drunk = Drunk(drunken) drunk_man = drunken_types[drunken](drunk) field.addDrunk(drunk_man, initial_loc) #print drunk_man for trial in range(numTrials): distance = walkVector(field, drunk_man, numSteps) results[drunken].append((round(distance[0], 1), round(distance[1], 1))) print drunken, "=", results[drunken] for result in results.keys(): # x, y = zip(*results[result]) # print "x", x # print "y", y pylab.plot(*zip(*results[result]), marker='o', color='r', ls='') pylab.title(result) pylab.xlabel('X coordinateds') pylab.ylabel('Y coordinateds') pylab.xlim(-100, 100) pylab.ylim(-100, 100) pylab.figure() pylab.show
def plot_Barycenter(dataset_name, feat, unfeat, repo): if dataset_name==MNIST: _, _, test=get_data(dataset_name, repo, labels=True) xtest1,_,_, labels,_=test else: _, _, test=get_data(dataset_name, repo, labels=False) xtest1,_,_ =test labels=np.zeros((len(xtest1),)) # get labels def bary_wdl2(index): return _bary_wdl2(index, xtest1, feat, unfeat) n=xtest1.shape[-1] num_class = (int)(max(labels)+1) barys=[bary_wdl2(np.where(labels==i)) for i in range(num_class)] pl.figure(1, (num_class, 1)) for i in range(num_class): pl.subplot(1,10,1+i) pl.imshow(barys[i][0,0,:,:],cmap='Blues',interpolation='nearest') pl.xticks(()) pl.yticks(()) if i==0: pl.ylabel('DWE Bary.') if num_class >1: pl.title('{}'.format(i)) pl.tight_layout(pad=0,h_pad=-2,w_pad=-2) pl.savefig("imgs/{}_dwe_bary.pdf".format(dataset_name))
def displayResults(self,res, cm=pylab.cm.gray, title='Specify a title'): if self.display: self.count=self.count+1 pylab.figure(self.count) pylab.imshow(res, cm, interpolation='nearest') pylab.colorbar() pylab.title(title)
def getOptCandGamma(cv_train, cv_label): print "Finding optimal C and gamma for SVM with RBF Kernel" C_range = 10.0 ** np.arange(-2, 9) gamma_range = 10.0 ** np.arange(-5, 4) param_grid = dict(gamma=gamma_range, C=C_range) cv = StratifiedKFold(y=cv_label, n_folds=40) # Use the svm.SVC() as the cost function to evaluate parameter choices # NOTE: Perhaps we should run computations in parallel if needed. Does it # do that already within the class? grid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv) grid.fit(cv_train, cv_label) score_dict = grid.grid_scores_ scores = [x[1] for x in score_dict] scores = np.array(scores).reshape(len(C_range), len(gamma_range)) pl.figure(figsize=(8,6)) pl.subplots_adjust(left=0.05, right=0.95, bottom=0.15, top=0.95) pl.imshow(scores, interpolation='nearest', cmap=pl.cm.spectral) pl.xlabel('gamma') pl.ylabel('C') pl.colorbar() pl.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45) pl.yticks(np.arange(len(C_range)), C_range) pl.show() print "The best classifier is: ", grid.best_estimator_
def plot_sphere_x( s, fname ): """ put plot of ionization fractions from sphere `s` into fname """ plt.figure() s.Edges.units = 'kpc' s.r_c.units = 'kpc' xx = s.r_c L = s.Edges[-1] plt.plot( xx, np.log10( s.xHe1 ), color='green', ls='-', label = r'$x_{\rm HeI}$' ) plt.plot( xx, np.log10( s.xHe2 ), color='green', ls='--', label = r'$x_{\rm HeII}$' ) plt.plot( xx, np.log10( s.xHe3 ), color='green', ls=':', label = r'$x_{\rm HeIII}$' ) plt.plot( xx, np.log10( s.xH1 ), color='red', ls='-', label = r'$x_{\rm HI}$' ) plt.plot( xx, np.log10( s.xH2 ), color='red', ls='--', label = r'$x_{\rm HII}$' ) plt.xlim( -L/20, L+L/20 ) plt.xlabel( 'r_c [kpc]' ) plt.ylim( -4.5, 0.2 ) plt.ylabel( 'log 10 ( x )' ) plt.grid() plt.legend(loc='best', ncol=2) plt.tight_layout() plt.savefig( 'doc/img/x_' + fname )
def Doplots_monthly(mypathforResults,PlottingDF,variable_to_fill, Site_ID,units,item): ANN_label=str(item+"_NN") #Do Monthly Plots print "Doing MOnthly plot" #t = arange(1, 54, 1) NN_label='Fc' Plottemp = PlottingDF[[NN_label,item]][PlottingDF['day_night']!=1] #Plottemp = PlottingDF[[NN_label,item]].dropna(how='any') figure(1) pl.title('Nightime ANN v Tower by year-month for '+item+' at '+Site_ID) try: xdata1a=Plottemp[item].groupby([lambda x: x.year,lambda x: x.month]).mean() plotxdata1a=True except: plotxdata1a=False try: xdata1b=Plottemp[NN_label].groupby([lambda x: x.year,lambda x: x.month]).mean() plotxdata1b=True except: plotxdata1b=False if plotxdata1a==True: pl.plot(xdata1a,'r',label=item) if plotxdata1b==True: pl.plot(xdata1b,'b',label=NN_label) pl.ylabel('Flux') pl.xlabel('Year - Month') pl.legend() pl.savefig(mypathforResults+'/ANN and Tower plots by year and month for variable '+item+' at '+Site_ID) #pl.show() pl.close() time.sleep(1)
def plotAllWarmJumps(): jumpAddrs = np.array(getAllWarmJumpsAddr()).reshape((8, 18)) figure() pcolor(jumpAddrs) for (x, y), v in np.ndenumerate(jumpAddrs): text(y + 0.125, x + 0.5, "0x%03x" % v) show()
def plot_cost(self): if self.show_cost not in self.train_outputs[0][0]: raise ShowNetError("Cost function with name '%s' not defined by given convnet." % self.show_cost) train_errors = [o[0][self.show_cost][self.cost_idx] for o in self.train_outputs] test_errors = [o[0][self.show_cost][self.cost_idx] for o in self.test_outputs] numbatches = len(self.train_batch_range) test_errors = numpy.row_stack(test_errors) test_errors = numpy.tile(test_errors, (1, self.testing_freq)) test_errors = list(test_errors.flatten()) test_errors += [test_errors[-1]] * max(0,len(train_errors) - len(test_errors)) test_errors = test_errors[:len(train_errors)] numepochs = len(train_errors) / float(numbatches) pl.figure(1) x = range(0, len(train_errors)) pl.plot(x, train_errors, 'k-', label='Training set') pl.plot(x, test_errors, 'r-', label='Test set') pl.legend() ticklocs = range(numbatches, len(train_errors) - len(train_errors) % numbatches + 1, numbatches) epoch_label_gran = int(ceil(numepochs / 20.)) # aim for about 20 labels epoch_label_gran = int(ceil(float(epoch_label_gran) / 10) * 10) # but round to nearest 10 ticklabels = map(lambda x: str((x[1] / numbatches)) if x[0] % epoch_label_gran == epoch_label_gran-1 else '', enumerate(ticklocs)) pl.xticks(ticklocs, ticklabels) pl.xlabel('Epoch') # pl.ylabel(self.show_cost) pl.title(self.show_cost)
def swi_histogram(self,dir,name,measure,dpi=80,width=8,height=6,b_left='0.1',b_bot='0.1',b_top='0.1',b_right='0.1',bins='20'): s=ccm.stats.Stats('%s/%s'%(dir,name)) data=s.get_raw(measure) bins=int(bins) pylab.figure(figsize=(float(width),float(height))) try: b_left=float(b_left) except: b_left=0.1 try: b_right=float(b_right) except: b_right=0.1 try: b_top=float(b_top) except: b_top=0.1 try: b_bot=float(b_bot) except: b_bot=0.1 pylab.axes((b_left,b_bot,1.0-b_left-b_right,1.0-b_top-b_bot)) pylab.hist(data,bins=bins) img=StringIO.StringIO() if type(dpi) is list: dpi=dpi[-1] pylab.savefig(img,dpi=int(dpi),format='png') return 'image/png',img.getvalue()
def plot_heatingrate(data_dict, filename, do_show=True): pl.figure(201) color_list = ['b','r','g','k','y','r','g','b','k','y','r',] fmtlist = ['s','d','o','s','d','o','s','d','o','s','d','o'] result_dict = {} for key in data_dict.keys(): x = data_dict[key][0] y = data_dict[key][1][:,0] y_err = data_dict[key][1][:,1] p0 = np.polyfit(x,y,1) fit = LinFit(np.array([x,y,y_err]).transpose(), show_graph=False) p1 = [0,0] p1[0] = fit.param_dict[0]['Slope'][0] p1[1] = fit.param_dict[0]['Offset'][0] print fit x0 = np.linspace(0,max(x)) cstr = color_list.pop(0) fstr = fmtlist.pop(0) lstr = key + " heating: {0:.2f} ph/ms".format((p1[0]*1e3)) pl.errorbar(x/1e3,y,y_err,fmt=fstr + cstr,label=lstr) pl.plot(x0/1e3,np.polyval(p0,x0),cstr) pl.plot(x0/1e3,np.polyval(p1,x0),cstr) result_dict[key] = 1e3*np.array(fit.param_dict[0]['Slope']) pl.xlabel('Heating time (ms)') pl.ylabel('nbar') if do_show: pl.legend() pl.show() if filename != None: pl.savefig(filename) return result_dict
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 T1_ir_bootstrap(folders_to_process,N=1000,plot='n'): """Given a folder of images will process IR data and return fitted T1 values and associated uncertainties. Uncertainties are obtained by bootstrapping pixels within each ROI""" images=[read_dicoms(folder,['InversionTime']) for folder in folders_to_process] all_rois=[load_ROIs(folder+'/rois') for folder in folders_to_process] TI_images=[img[0][0] for img in images] TIs=np.array([img[1][0]['InversionTime'] for img in images]) T1s=[] T1_errs=[] for kk in np.arange(len(all_rois[0])-2): rois=[roi_list[kk] for roi_list in all_rois] sig=np.zeros(len(rois)) T1bs=[] for mm, roi in enumerate(rois): sig[mm]=TI_images[mm][roi.get_indices()].mean() fit = IR_fit(TIs, sig) T1s.append(fit['T1'].value) if plot=='y': plt.figure() plt.plot(TIs,sig,'o') TI_full=np.arange(0,8000,10) plt.plot(TI_full,fit(TI_full)) if N>0: for nn in np.arange(N): for mm,roi in enumerate(rois): npix=len(roi.get_indices()[0]) pixels=roi.get_indices() ind=np.random.randint(npix,size=npix) sig[mm]=TI_images[mm][pixels[0][ind],pixels[1][ind]].mean() fit = IR_fit(TIs, sig) T1bs.append(fit['T1'].value) #T1s.append(np.mean(T1bs)) T1_errs.append(np.std(T1bs)) return T1s, T1_errs
def makeContourPlot(scores, average, HEIGHT, WIDTH, outputId, maskId, plt_title, outputdir, barcodeId=-1, vmaxVal=100): pylab.bone() #majorFormatter = FormatStrFormatter('%.f %%') #ax = pylab.gca() #ax.xaxis.set_major_formatter(majorFormatter) pylab.figure() ax = pylab.gca() ax.set_xlabel(str(WIDTH) + ' wells') ax.set_ylabel(str(HEIGHT) + ' wells') ax.autoscale_view() pylab.jet() pylab.imshow(scores,vmin=0, vmax=vmaxVal, origin='lower') pylab.vmin = 0.0 pylab.vmax = 100.0 ticksVal = getTicksForMaxVal(vmaxVal) pylab.colorbar(format='%.0f %%',ticks=ticksVal) print "'%s'" % average if(barcodeId!=-1): if(barcodeId==0): maskId = "No Barcode Match," else: maskId = "Barcode Id %d," % barcodeId if plt_title != '': maskId = '%s\n%s' % (plt_title,maskId) print "Checkpoint A" pylab.title('%s Loading Density (Avg ~ %0.f%%)' % (maskId, average)) pylab.axis('scaled') print "Checkpoint B" pngFn = outputdir+'/'+outputId+'_density_contour.png' print "Try save to", pngFn; pylab.savefig(pngFn, bbox_inches='tight') print "Plot saved to", pngFn;
def plot_predictions(self): data = self.get_next_batch(train=False)[2] # get a test batch num_classes = self.test_data_provider.get_num_classes() NUM_ROWS = 2 NUM_COLS = 4 NUM_IMGS = NUM_ROWS * NUM_COLS NUM_TOP_CLASSES = min(num_classes, 4) # show this many top labels label_names = self.test_data_provider.batch_meta['label_names'] if self.only_errors: preds = n.zeros((data[0].shape[1], num_classes), dtype=n.single) else: preds = n.zeros((NUM_IMGS, num_classes), dtype=n.single) rand_idx = nr.randint(0, data[0].shape[1], NUM_IMGS) data[0] = n.require(data[0][:, rand_idx], requirements='C') data[1] = n.require(data[1][:, rand_idx], requirements='C') data += [preds] # Run the model self.libmodel.startFeatureWriter(data, self.sotmax_idx) self.finish_batch() fig = pl.figure(3) fig.text( .4, .95, '%s test case predictions' % ('Mistaken' if self.only_errors else 'Random')) if self.only_errors: err_idx = nr.permutation( n.where(preds.argmax(axis=1) != data[1][0, :]) [0])[:NUM_IMGS] # what the net got wrong data[0], data[1], preds = data[0][:, err_idx], data[ 1][:, err_idx], preds[err_idx, :] data[0] = self.test_data_provider.get_plottable_data(data[0]) for r in xrange(NUM_ROWS): for c in xrange(NUM_COLS): img_idx = r * NUM_COLS + c if data[0].shape[0] <= img_idx: break pl.subplot(NUM_ROWS * 2, NUM_COLS, r * 2 * NUM_COLS + c + 1) pl.xticks([]) pl.yticks([]) img = data[0][img_idx, :, :, :] pl.imshow(img, interpolation='nearest') true_label = int(data[1][0, img_idx]) img_labels = sorted(zip(preds[img_idx, :], label_names), key=lambda x: x[0])[-NUM_TOP_CLASSES:] pl.subplot(NUM_ROWS * 2, NUM_COLS, (r * 2 + 1) * NUM_COLS + c + 1, aspect='equal') ylocs = n.array(range(NUM_TOP_CLASSES)) + 0.5 height = 0.5 width = max(ylocs) pl.barh(ylocs, [l[0]*width for l in img_labels], height=height, \ color=['r' if l[1] == label_names[true_label] else 'b' for l in img_labels]) pl.title(label_names[true_label]) pl.yticks(ylocs + height / 2, [l[1] for l in img_labels]) pl.xticks([width / 2.0, width], ['50%', '']) pl.ylim(0, ylocs[-1] + height * 2)
channels_fn = sys.argv[2] fn_out = sys.argv[3] with open(channels_fn, "r+") as f: channels = json.load(f) channels = channels['channels'] all_d1 = np.ravel([c['d1'] for c in channels]) all_d2 = np.ravel([c['d2'] for c in channels]) spike_data = np.loadtxt(fn_in) senders = spike_data[:, 0] times = spike_data[:, 1] mask_d1 = [nid in all_d1 for nid in senders] mask_d2 = [nid in all_d2 for nid in senders] f = pl.figure(figsize=[32, 10]) ax = f.add_subplot(1, 1, 1) ax.plot(times[mask_d1], senders[mask_d1], '.', color=colors.colors[0]) ax.plot(times[mask_d2], senders[mask_d2], '.', color=colors.colors[1]) ax.set_xticklabels(ax.get_xticks().astype('int') / 1000) ax.set_xlabel("Time (s)") ax.set_ylabel("Neuron id") pl.tight_layout() pl.savefig(fn_out)
else: raise (Exception("kind=%r but it must be in %r" % (kind, d.keys()))) if f_clean is not None: df = f_clean(df) var = df[var_name].values direction = df[direction_name].values ax = f_plot(direction=direction, var=var, **kwargs) if kind not in ['pdf']: ax.set_legend() return ax if __name__ == '__main__': from pylab import figure, show, setp, random, grid, draw vv = random(500) * 6 dv = random(500) * 360 fig = figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w') rect = [0.1, 0.1, 0.8, 0.8] ax = WindroseAxes(fig, rect, axisbg='w') fig.add_axes(ax) # ax.contourf(dv, vv, bins=np.arange(0,8,1), cmap=cm.hot) # ax.contour(dv, vv, bins=np.arange(0,8,1), colors='k') # ax.bar(dv, vv, normed=True, opening=0.8, edgecolor='white') ax.box(dv, vv, normed=True) l = ax.legend() setp(l.get_texts(), fontsize=8) draw() #print ax._info show()
def initfunc(vc, vars, weights, mask): vc.myfig = p.figure() p.figure(vc.myfig.number) h1 = hist1d(vars.var1[mask], n.linspace(-20, 20, 101), weights[mask]) c = d.bundle(sig="r", bg="k") h1.line(c=c)
import pylab as pl import numpy as np # Crear una figura de 8x6 puntos de tamaño, 80 puntos por pulgada (Se modifica a 16x8) pl.figure(figsize=(16, 8), dpi=100) # Crear una nueva subgráfica en una rejilla de 1x1 (se podrian crean una de dos graficas en una reijlla) pl.subplot(1, 1, 1) # Obtencion de datos para seno y coseno (Desde -2pi hasta 2pi) X = np.linspace(-2.1*np.pi, 2.1*np.pi, 256, endpoint=True) #el numero 256 es la cantidad de datos en ese intervalo C, S = np.cos(X), np.sin(X) # Graficar la función coseno con una línea continua azul de 1 pixel de grosor pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # Graficar la función seno con una línea continua verde de 1 pixel de grosor pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") # Establecer límites del eje x (Divisiones en X) pl.xlim(-8.0, 8.0) # Ticks en x(Impresión de intervalos, cantidad de datos mostrados en el eje) pl.xticks(np.linspace(-8, 8, 17, endpoint=True)) # Establecer límites del eje y (Divisiones en Y) pl.ylim(-1.0, 1.0) # Ticks en y (Impresión de intervalos, cantidad de datos mostrados en el eje) pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) '''Otra opcion de determinar los limites a imprimir
def plot_peak_offsets(offsets, filebase, doshow=False): """Plots the results of the peak offsets calculated.""" from pylab import figure, clf, xlim, ylim, savefig, plot, text, show, figtext, subplot, title #@type inst Instrument inst = instrument.inst numperpage = 6 # Initialize some stats rms = 0 rms_wl = 0 #@type po PeakOffset for po in offsets: #Square of the error distance error = (po.measured[0] - po.predicted[0])**2 + (po.measured[1] - po.predicted[1])**2 rms += error error = (po.wavelength_measured - po.wavelength_predicted)**2 rms_wl += error # Now do the root-mean rms = (rms / len(offsets))**0.5 rms_wl = (rms_wl / len(offsets))**0.5 print "Peak offsets RMS error is ", rms print "Peak offsets RMS wavelength error is ", rms_wl #@type det FlatDetector for (det_num, det) in enumerate(inst.detectors): if det_num % numperpage == 0: figure(det_num / numperpage, figsize=[8, 10]) clf() figtext( 0.5, 0.95, "Offset (black line) from predicted peak positions (red dot); wavelength in angstroms", horizontalalignment='center', verticalalignment='top') ax = subplot(3, 2, det_num % numperpage + 1) #Set the axes font sizes for xlabel_i in ax.get_xticklabels() + ax.get_yticklabels(): xlabel_i.set_fontsize(10) #@type po PeakOffset for po in offsets: if po.det_num == det_num: x = [po.measured[0], po.predicted[0]] y = [po.measured[1], po.predicted[1]] plot(po.predicted[0], po.predicted[1], 'r.') plot(x, y, '-k') text(po.predicted[0], po.predicted[1], ' %.1f' % po.wavelength_measured, size=5, verticalalignment='center') xlim(-det.width / 2, det.width / 2) ylim(-det.height / 2, det.height / 2) #axis('equal') title('Detector %s' % det.name) #-- Save to files -- for i in xrange((len(inst.detectors) + numperpage - 1) / numperpage): figure(i) savefig(filebase + "_%d.pdf" % i, papertype="letter") #-- combine -- os.system("pdftk %s_*.pdf cat output %s.pdf" % (filebase, filebase)) if doshow: show()
import pylab import skrf as rf # create a Network type from a touchstone file of a horn antenna ring_slot = rf.Network('ring slot array measured.s1p') # plot magnitude (in db) of S11 pylab.figure(1) pylab.title('WR-10 Ringslot Array, Mag') ring_slot.plot_s_db(m=0, n=0) # m,n are S-Matrix indecies pylab.figure(2) ring_slot.plot_s_db(m=0, n=0) # m,n are S-Matrix indecies # show the plots pylab.show()
def view_patches(Yr, A, C, b, f, d1, d2, YrA=None, secs=1): """view spatial and temporal components (secs=0 interactive) Parameters: ----------- Yr: np.ndarray movie in format pixels (d) x frames (T) A: sparse matrix matrix of spatial components (d x K) C: np.ndarray matrix of temporal components (K x T) b: np.ndarray spatial background (vector of length d) f: np.ndarray temporal background (vector of length T) d1,d2: np.ndarray frame dimensions YrA: np.ndarray ROI filtered residual as it is given from update_temporal_components If not given, then it is computed (K x T) secs: float number of seconds in between component scrolling. secs=0 means interactive (click to scroll) imgs: np.ndarray background image for contour plotting. Default is the image of all spatial components (d1 x d2) See Also: ------------ ..image:: doc/img/ """ pl.ion() nr, T = C.shape nb = f.shape[0] A2 = A.copy() A2.data **= 2 nA2 = np.sqrt(np.array(A2.sum(axis=0))).squeeze() if YrA is None: Y_r = np.array(A.T * np.matrix(Yr) - (A.T * np.matrix(b[:, np.newaxis])) * np.matrix( f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C) + C) else: Y_r = YrA + C A = A.todense() bkgrnd = np.reshape(b, (d1, d2) + (nb,), order='F') fig = pl.figure() thismanager = pl.get_current_fig_manager() thismanager.toolbar.pan() print('In order to scroll components you need to click on the plot') sys.stdout.flush() for i in range(nr + 1): if i < nr: ax1 = fig.add_subplot(2, 1, 1) pl.imshow(np.reshape(old_div(np.array(A[:, i]), nA2[i]), (d1, d2), order='F'), interpolation='None') ax1.set_title('Spatial component ' + str(i + 1)) ax2 = fig.add_subplot(2, 1, 2) pl.plot(np.arange(T), np.squeeze(np.array(Y_r[i, :])), 'c', linewidth=3) pl.plot(np.arange(T), np.squeeze(np.array(C[i, :])), 'r', linewidth=2) ax2.set_title('Temporal component ' + str(i + 1)) ax2.legend(labels=['Filtered raw data', 'Inferred trace']) if secs > 0: pl.pause(secs) else: pl.waitforbuttonpress() fig.delaxes(ax2) else: ax1 = fig.add_subplot(2, 1, 1) pl.imshow(bkgrnd[:, :, i - nr], interpolation='None') ax1.set_title('Spatial background ' + str(i - nr + 1)) ax2 = fig.add_subplot(2, 1, 2) pl.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :]))) ax2.set_title('Temporal background ' + str(i - nr + 1))
for i in t[1:n]: # initial conditions already included in pops new = dR_dt(x, y, i) # 2*1 array if new[0, 0] < 0: # doesn't allow density to drop below 0 new[0, 0] = 0 if new[0, 1] < 0: new[0, 1] = 0 pops = sc.concatenate((pops, new), axis=0) x = round(new[0, 0], 7) # rounds values so doesn't exceed memory y = round(new[0, 1], 7) prey, predators = pops.T # Transposes to form correct format final_prey = prey[-1] final_predator = predators[-1] f1 = p.figure() #Open empty figure object p.plot(t, prey, 'g-', label='Resource density') # Plot p.plot(t, predators, 'b-', label='Consumer density') p.annotate('Constants: r = %r , a = %r , z = %r , e = %r , K = %r' % (r, a, z, e, K), xy=(20, 5), color="red") p.annotate('Final prey = %.5s , Final predators = %.5s' % (final_prey, final_predator), xy=(25, 2), color="purple") p.grid() p.legend(loc='best') p.xlabel('Time') p.ylabel('Population') p.title('Consumer-Resource population dynamics')
def view_patches_bar(Yr, A, C, b, f, d1, d2, YrA=None, img=None): """view spatial and temporal components interactively Parameters: ----------- Yr: np.ndarray movie in format pixels (d) x frames (T) A: sparse matrix matrix of spatial components (d x K) C: np.ndarray matrix of temporal components (K x T) b: np.ndarray spatial background (vector of length d) f: np.ndarray temporal background (vector of length T) d1,d2: np.ndarray frame dimensions YrA: np.ndarray ROI filtered residual as it is given from update_temporal_components If not given, then it is computed (K x T) img: np.ndarray background image for contour plotting. Default is the image of all spatial components (d1 x d2) """ pl.ion() nr, T = C.shape nb = f.shape[0] A2 = A.copy() A2.data **= 2 nA2 = np.sqrt(np.array(A2.sum(axis=0))).squeeze() if YrA is None: Y_r = np.array(A.T * np.matrix(Yr) - (A.T * np.matrix(b[:, np.newaxis])) * np.matrix( f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C) + C) else: Y_r = YrA + C A = A * spdiags(old_div(1, nA2), 0, nr, nr) A = A.todense() imgs = np.reshape(np.array(A), (d1, d2, nr), order='F') if img is None: img = np.mean(imgs[:, :, :-1], axis=-1) bkgrnd = np.reshape(b, (d1, d2) + (nb,), order='F') fig = pl.figure(figsize=(10, 10)) axcomp = pl.axes([0.05, 0.05, 0.9, 0.03]) ax1 = pl.axes([0.05, 0.55, 0.4, 0.4]) # ax1.axis('off') ax3 = pl.axes([0.55, 0.55, 0.4, 0.4]) # ax1.axis('off') ax2 = pl.axes([0.05, 0.1, 0.9, 0.4]) # axcolor = 'lightgoldenrodyellow' # axcomp = pl.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) s_comp = Slider(axcomp, 'Component', 0, nr + nb - 1, valinit=0) vmax = np.percentile(img, 98) def update(val): i = np.int(np.round(s_comp.val)) print(('Component:' + str(i))) if i < nr: ax1.cla() imgtmp = imgs[:, :, i] ax1.imshow(imgtmp, interpolation='None', cmap=pl.cm.gray) ax1.set_title('Spatial component ' + str(i + 1)) ax1.axis('off') ax2.cla() ax2.plot(np.arange(T), np.squeeze(np.array(Y_r[i, :])), 'c', linewidth=3) ax2.plot(np.arange(T), np.squeeze(np.array(C[i, :])), 'r', linewidth=2) ax2.set_title('Temporal component ' + str(i + 1)) ax2.legend(labels=['Filtered raw data', 'Inferred trace']) ax3.cla() ax3.imshow(img, interpolation='None', cmap=pl.cm.gray, vmax=vmax) imgtmp2 = imgtmp.copy() imgtmp2[imgtmp2 == 0] = np.nan ax3.imshow(imgtmp2, interpolation='None', alpha=0.5, cmap=pl.cm.hot) ax3.axis('off') else: ax1.cla() ax1.imshow(bkgrnd[:, :, i - nr], interpolation='None') ax1.set_title('Spatial background ' + str(i + 1 - nr)) ax1.axis('off') ax2.cla() ax2.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :]))) ax2.set_title('Temporal background ' + str(i + 1 - nr)) def arrow_key_image_control(event): if event.key == 'left': new_val = np.round(s_comp.val - 1) if new_val < 0: new_val = 0 s_comp.set_val(new_val) elif event.key == 'right': new_val = np.round(s_comp.val + 1) if new_val > nr + nb: new_val = nr + nb s_comp.set_val(new_val) else: pass s_comp.on_changed(update) s_comp.set_val(0) fig.canvas.mpl_connect('key_release_event', arrow_key_image_control) pl.show()
from PIL import Image import numpy as np import pylab as pl from scipy.ndimage import filters, measurements, morphology from common import imtools # Apply the label() function to a thresholded image of your choice. Use histograms # and the resulting label image to plot the distribution of object sizes in the image. im = np.array(Image.open('data/aircraft-formation.jpg').convert('L')) im_bin = 1 * (im < 128) #labels, nbr_objects = measurements.label(im_bin) im_open = morphology.binary_opening(im_bin, np.ones((9, 5)), iterations=1) labels_open, nbr_objects_open = measurements.label(im_open) print('Number of objects:', nbr_objects_open) pl.figure('Labels') pl.subplot(1, 2, 1) pl.gray() pl.title('Labeled Image') pl.imshow(labels_open) pl.subplot(1, 2, 2) pl.title('Histogram') pl.hist(labels_open.flatten(), bins=nbr_objects_open, log=True) pl.show()
#coding=utf-8 import pandas as pd import time import csv import pylab as plt import numpy as np from keras.layers import Dense, Activation, Dropout from keras.layers import LSTM,GRU from keras.optimizers import RMSprop from keras.models import Sequential from keras.utils.np_utils import to_categorical from feature import * from keras.callbacks import EarlyStopping from lossHistory import LossHistory csvfile = file('new.csv', 'rb') reader = csv.reader(csvfile) y = [] i=0 x=[] for line in reader: x.append(i) y.append(float(line[1])) i=i+1 plt.figure(figsize=(8,4)) #创建绘图对象 plt.plot(x,y,linewidth=1) #在当前绘图对象绘图(X轴,Y轴,蓝色虚线,线宽度) plt.xlabel("Time") #X轴标签 plt.ylabel("Price") #Y轴标签 plt.show() #显示图 plt.savefig("line.jpg") #保存图 print 'h'
def plot(): print "Load tracking.txt" d = numpy.genfromtxt("tracking.txt", names=True) n = len(d) # one per particle print "Find unique inital particles" ids_source = unique_ids(d['ID0'], d['E0'], d['X0'], d['Y0'], d['Z0'], d['P0x'], d['P0y'], d['P0z'], d['ID1'], d['E1'], d['X1'], d['Y1'], d['Z1'], d['P1x'], d['P1y'], d['P1z']) nids_source = ids_source.max() + 1 print "Unique Source: ", nids_source # one per initial print "Find unique final particles" ids_particle = unique_ids(d['ID0'], d['E0'], d['X0'], d['Y0'], d['Z0'], d['P0x'], d['P0y'], d['P0z']) nids_particle = ids_particle.max() + 1 print "Unique Particle: ", nids_source # collect data print "Detect at different distances" select_1000kpc = numpy.ones(nids_source, dtype=int) * -1 select_500kpc = numpy.ones(nids_source, dtype=int) * -1 select_200kpc = numpy.ones(nids_source, dtype=int) * -1 select_100kpc = numpy.ones(nids_source, dtype=int) * -1 select_50kpc = numpy.ones(nids_source, dtype=int) * -1 select_closest = numpy.ones(nids_source, dtype=int) * -1 dist = ((d['X'] - 64)**2 + (d['Y'] - 64)**2 + (d['Z'] - 64)**2)**0.5 for i in xrange(nids_source): if i % 1000 == 0: sys.stdout.write(" %5.2f%%\r" % (100. * float(i) / nids_source)) sys.stdout.flush() # select i'th initial particle s = numpy.nonzero(ids_source == i)[0] s_d = d[s] s_dist = dist[s] # distances sorted by trajectory D_sort = numpy.argsort(s_d['D']) dist_sort = s_dist[D_sort] idx = numpy.nonzero(dist_sort < 1.000)[0] if len(idx) > 0: select_1000kpc[i] = s[D_sort[idx[0]]] idx = numpy.nonzero(dist_sort < 0.500)[0] if len(idx) > 0: select_500kpc[i] = s[D_sort[idx[0]]] idx = numpy.nonzero(dist_sort < 0.200)[0] if len(idx) > 0: select_200kpc[i] = s[D_sort[idx[0]]] idx = numpy.nonzero(dist_sort < 0.100)[0] if len(idx) > 0: select_100kpc[i] = s[D_sort[idx[0]]] idx = numpy.nonzero(dist_sort < 0.05)[0] if len(idx) > 0: select_50kpc[i] = s[D_sort[idx[0]]] select_closest[i] = s[numpy.argmin(s_dist)] # plot first 10 tracks first_ten = ids_source < 10 pylab.figure() pylab.scatter(d['X'][first_ten], d['Y'][first_ten], c=ids_source[first_ten], s=50*(d['Z'][first_ten]-63)) first_ten_1000kpc = select_1000kpc[:10] pylab.scatter(d['X'][first_ten_1000kpc], d['Y'][first_ten_1000kpc], marker='+', s=1000) first_ten_500kpc = select_500kpc[:10] pylab.scatter(d['X'][first_ten_500kpc], d['Y'][first_ten_500kpc], marker='+', s=500) first_ten_200kpc = select_200kpc[:10] pylab.scatter(d['X'][first_ten_200kpc], d['Y'][first_ten_200kpc], marker='+', s=200) first_ten_100kpc = select_100kpc[:10] pylab.scatter(d['X'][first_ten_100kpc], d['Y'][first_ten_100kpc], marker='+', s=100) first_ten_50kpc = select_50kpc[:10] pylab.scatter(d['X'][first_ten_50kpc], d['Y'][first_ten_50kpc], marker='+', s=50) first_ten_closest = select_closest[:10] pylab.scatter(d['X'][first_ten_closest], d['Y'][first_ten_closest], marker='x', s=50) pylab.xlim(63, 65) pylab.ylim(63, 65) pylab.savefig("scatter.png") pylab.show() pylab.close() # plot skplots x, y, z = -d['Px'], -d['Py'], -d['Pz'] phi = numpy.arctan2(y, x) theta = numpy.arctan2(z, (x * x + y * y) ** .5) plot_uhecrs(phi, theta, dist, cmap='jet_r') pylab.savefig("all.png") pylab.show() pylab.close() plot_uhecrs(phi, theta, 1./dist) pylab.savefig("all_w.png") pylab.show() pylab.close() plot_uhecrs(phi, theta, 1./(dist**2)) pylab.savefig("all_w2.png") pylab.show() pylab.close() plot_uhecrs(phi[select_1000kpc], theta[select_1000kpc], None) pylab.savefig("1000kpc.png") pylab.show() pylab.close() plot_uhecrs(phi[select_500kpc], theta[select_500kpc], None) pylab.savefig("500kpc.png") pylab.show() pylab.close() plot_uhecrs(phi[select_200kpc], theta[select_200kpc], None) pylab.savefig("200kpc.png") pylab.show() pylab.close() plot_uhecrs(phi[select_100kpc], theta[select_100kpc], None) pylab.savefig("100kpc.png") pylab.show() pylab.close() plot_uhecrs(phi[select_50kpc], theta[select_50kpc], None) pylab.savefig("50kpc.png") pylab.show() pylab.close() plot_uhecrs(phi[select_closest], theta[select_closest], None) pylab.savefig("closest.png") pylab.show() pylab.close() plot_uhecrs(phi[select_closest], theta[select_closest], 1./dist[select_closest]) pylab.savefig("closest_w.png") pylab.show() pylab.close() plot_uhecrs(phi[select_closest], theta[select_closest], 1./(dist[select_closest]**2)) pylab.savefig("closest_w2.png") pylab.show() pylab.close()
#--------------------------------# # destruction timescale t_dest = 1. / (K_rd) # formation timescale t_form = 1. / (K_ra * n) #plt.plot(t, 1./(K_rd)/t_exp) #plt.xscale('log') #plt.yscale('log') #plt.xlabel('$t$') #plt.ylabel(r'$t_{\rm eq} /t_{\rm exp}$') #plt.savefig('t_eq.png') plt.figure(figsize=(14, 8)) plt.subplot(231) plt.plot(t, n, color='black') plt.xscale('log') plt.yscale('log') plt.xlabel('$t$') plt.ylabel(r'$n_{\rm tot}$') plt.subplot(232) plt.plot(t, T_cs, color='black') plt.xscale('log') plt.yscale('log') plt.xlabel('$t$') plt.ylabel(r'$T_{\rm cs}$')
import pylab as pl import numpy as np data = np.loadtxt('contour.dat') fig = pl.figure() pl.contourf(data) pl.axis('tight') pl.show()
}).x elif opt in ('adam', 'rmsprop'): cb = lambda x, i: gl(x) for h in [0.1, 0.01, 0.001]: x0 = eval(opt)(cb, x0, step_size=h, num_iters=max_iter // 3) else: raise ValueError(opt) x0s[opt] = x0.copy() toc = time.time() - tic ll1 = np.log(loss(x0)) rll_eval = neval[0] / (ll0 - ll1) print(' %0.3f, %d feval, %0.3fs, %0.3f evals/rll' % (ll1, neval[0], toc, rll_eval)) # check optimized spectra against that for known parameters pl.figure(figsize=(10, 10)) pl.subplot(211) pl.plot(np.r_[:n_time] * dt * 1e-3, state[0].T + np.r_[:n_node], 'k', alpha=0.2) pl.subplot(212) Fs = np.fft.fftfreq(win.size, dt * 1e-3) Fsm = (Fs >= 0) * (Fs < 150) pl.loglog(Fs[Fsm], eeg.mean(axis=0)[Fsm], 'k', alpha=0.7) names = ['sim'] _, eeg_h = pred(x0_) pl.loglog(Fs[Fsm], eeg_h.mean(axis=0)[Fsm], alpha=0.2) names.append('sim perturb') for opt, x0 in x0s.items(): _, eeg_h = pred(x0)
else: spe = StreamPowerEroder(mg, input_file) for i in xrange(nt): # print 'loop ', i mg.at_node['topographic__elevation'][mg.core_nodes] += uplift_per_step mg = fr.route_flow(grid=mg) if DL_or_TL == 'TL': mg, _ = tle.erode(mg, dt) else: mg, _, _ = spe.erode(mg, dt=dt) if i % init_interval == 0: print 'loop ', i print 'max_slope', np.amax(mg.at_node['topographic__steepest_slope'][ mg.core_nodes]) pylab.figure("long_profiles_init") profile_IDs = prf.channel_nodes( mg, mg.at_node['topographic__steepest_slope'], mg.at_node['drainage_area'], mg.at_node['flow_receiver']) dists_upstr = prf.get_distances_upstream(mg, len(mg.at_node['topographic__steepest_slope']), profile_IDs, mg.at_node['links_to_flow_receiver']) prf.plot_profiles(dists_upstr, profile_IDs, mg.at_node['topographic__elevation']) print 'completed run to steady state...' if show_figs_in_run: show() #will cause a hang #save a copy of the init conditions: mg_init = deepcopy(mg)
n1 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=1 ) n2 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=2, rms=0.7 ) n3 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=3, rms=0.5 ) p1 = PointSource( signal=n1, mpos=mg, loc=(-0.1,-0.1,0.3) ) p2 = PointSource( signal=n2, mpos=mg, loc=(0.15,0,0.3) ) p3 = PointSource( signal=n3, mpos=mg, loc=(0,0.1,0.3) ) pa = Mixer( source=p1, sources=[p2,p3] ) wh5 = WriteH5( source=pa, name=h5savefile ) wh5.save() # analyze the data and generate map ts = TimeSamples( name=h5savefile ) ps = PowerSpectra( time_data=ts, block_size=128, window='Hanning' ) rg = RectGrid( x_min=-0.2, x_max=0.2, y_min=-0.2, y_max=0.2, z=0.3, \ increment=0.01 ) bb = BeamformerBase( freq_data=ps, grid=rg, mpos=mg ) pm = bb.synthetic( 8000, 3 ) Lm = L_p( pm ) # show map imshow( Lm.T, origin='lower', vmin=Lm.max()-10, extent=rg.extend(), \ interpolation='bicubic') colorbar() # plot microphone geometry figure(2) plt.plot(mg.mpos[0],mg.mpos[1],'o') axis('equal') show()
fig_size = [fig_width, fig_height] params = {'backend': 'ps', 'axes.labelsize': fs, 'text.fontsize': fs, \ 'legend.fontsize': fs2, 'xtick.labelsize': fs, 'ytick.labelsize': fs, \ 'text.usetex': True, 'figure.figsize': fig_size} xmin = 0 xmax = 1e2 ymin = 1e-4 ymax = 1e-1 dipsim = np.genfromtxt(dir + 'sim/dipole_0.dat') #, skip_header=9) diprdm = np.genfromtxt(dir + 'rdm/dipole_0.dat') #, skip_header=9) #diprha = np.genfromtxt(dir+'rha/dipole_0.dat')#, skip_header=9) py.rcParams.update(params) py.figure(1) py.clf() py.loglog(dipsim[:, 0], dipsim[:, 1], 'c', label=r"${\rm Sim}$") py.loglog(diprdm[:, 0], diprdm[:, 1], 'c--', label=r"${\rm Rec DM}$") py.xlabel(r"$r\ [{\rm Mpc}/h]$") #py.axes().set_xlim((xmin,xmax)) py.ylabel(r'${\rm Dipole \, Correlation}$') #py.axes().set_ylim((ymin,ymax)) py.axes().set_xlim((xmin, xmax)) py.axes().set_ylim((ymin, ymax)) lg = py.legend(loc="upper right", fancybox=True, numpoints=1) lg.draw_frame(False)
# Load data d1 = load_chain(fname1) d2 = load_chain(fname2) # Reshape into per-walker chains nw = np.max(d1['walker']).astype(int) + 1 for k in d1.keys(): d1[k] = d1[k].reshape((-1, nw)) for k in d2.keys(): d2[k] = d2[k].reshape((-1, nw)) #d2 = d2.reshape((d2.shape[0], -1, nw)) print(d1['walker'].shape, d2['walker'].shape) # Create Figure fig = plt.figure(constrained_layout=True) # Get parameter list params = ['omegaM', 'w0', 'h', 'deltaw', 'zc', 'deltaz'] # 'omegaB' pnames = [ r'$\Omega_{\rm M}$', r'$w_0$', r'$h$', r'$\Delta w$', r'$z_c$', r'$\Delta z$' ] fiducial = [0.3166, -1., 0.6727, None, None, None] # r'$\Omega_{\rm b}$' 0.04941 l1 = r'CMB + LSS' l2 = r' + Stage 2 ($3\times$PB)' deltaz1 = d1['deltaz'][-1000:].flatten() deltaz2 = d2['deltaz'][-1000:].flatten()
counts = {} ##use a dictionary to populate the bins for i in range(int(number)): for j in pvalues: if i / number < j <= (i + 1) / number: counts[i] = counts.get(i, 0) + 1 ##convert the dictionary to a list mylist = zip(counts.keys(), counts.values()) ##sort the list so that the bins are in order mylist.sort() ##plot the data with pylab fig = plt.figure() ax = fig.add_subplot(111) fig.subplots_adjust(bottom=.2) ax.bar([i[0] / number for i in mylist], [i[1] for i in mylist], color='b', width=1 / number, linewidth=2.0) ax.set_xlim((0, 1)) for item in ax.get_yticklabels(): item.set_fontsize(30) for item in ax.get_xticklabels(): item.set_fontsize(30)
def plot(ifiles, args): import pylab as pl from pylab import figure, NullFormatter, close, rcParams from PseudoNetCDF.coordutil import getsigmamid, getpresmid, getpresbnds, getsigmabnds rcParams['text.usetex'] = False from matplotlib.colors import LinearSegmentedColormap, BoundaryNorm, LogNorm map = not args.nomap scale = args.scale minmax = eval(args.minmax) minmaxq = eval(args.minmaxq) sigma = args.sigma maskzeros = args.maskzeros try: f, = ifiles except: raise ValueError('curtain plot expects one file when done. Try stack time --stack=time to concatenate') if sigma: vertcrd = getsigmabnds(f) else: vertcrd = getpresbnds(f, pref = 101325., ptop = getattr(f, 'VGTOP', 10000)) if vertcrd.max() > 2000: vertcrd /= 100. reversevert = not (np.diff(vertcrd) > 0).all() for var_name in args.variables: temp = defaultdict(lambda: 1) try: eval(var_name, None, temp) var = eval(var_name, None, f.variables)[:] except: temp[var_name] var = f.variables[var_name][:] if args.itertime: vars = [('time%02d' % vi, v) for vi, v in enumerate(var)] else: if var.shape[0] != 1: parser.print_help() sys.stderr.write('\n*****\n\nFile must have only one time or use the itertime options; to reduce file to one time, see the --slice and --reduce operators\n\n') exit() vars = [('', var[0])] for lstr, var in vars: bmap = None if maskzeros: var = np.ma.masked_values(var, 0) vmin, vmax = np.percentile(np.ma.compressed(var).ravel(), list(minmaxq)) if minmax[0] is not None: vmin = minmax[0] if minmax[1] is not None: vmax = minmax[1] if not args.normalize is None: norm = eval(args.normalize) if norm.scaled(): vmin = norm.vmin; vmax = norm.vmax else: if scale == 'log': bins = np.logspace(np.log10(vmin), np.log10(vmax), 11) elif scale == 'linear': bins = np.linspace(vmin, vmax, 11) elif scale == 'deciles': bins = np.percentile(np.ma.compressed(np.ma.masked_greater(np.ma.masked_less(var, vmin), vmax)).ravel(), [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) bins[0] = vmin; bins[-1] = vmax norm = BoundaryNorm(bins, ncolors = 256) if map: fig = pl.figure(figsize = (8, 8)) fig.subplots_adjust(hspace = .3, wspace = .3) axmap = fig.add_subplot(3,3,5) try: cmaqmap = getmap(f) cmaqmap.drawcoastlines(ax = axmap) cmaqmap.drawcountries(ax = axmap) if args.states: cmaqmap.drawstates(ax = axmap) if args.counties: cmaqmap.drawcounties(ax = axmap) cmaqmap.drawparallels(np.arange(-90, 100, 10), labels = [True, True, False, False], ax = axmap) cmaqmap.drawmeridians(np.arange(-180, 190, 20), labels = [False, False, True, True], ax = axmap) except Exception as e: warn('An error occurred and no map will be shown:\n%s' % str(e)) axn = fig.add_subplot(3,3,2, sharex = axmap) axw = fig.add_subplot(3,3,4, sharey = axmap) axe = fig.add_subplot(3,3,6, sharey = axmap) axs = fig.add_subplot(3,3,8, sharex = axmap) cax = fig.add_axes([.8, .7, .05, .25]) for ax in [axmap, axe]: ax.yaxis.set_major_formatter(NullFormatter()) for ax in [axmap, axn]: ax.xaxis.set_major_formatter(NullFormatter()) for ax in [axn, axs]: if sigma: ax.set_ylabel('sigma') else: ax.set_ylabel('pressure') for ax in [axe, axw]: if sigma: ax.set_xlabel('sigma') else: ax.set_xlabel('pressure') xyfactor = 1 else: fig = pl.figure(figsize = (16, 4)) fig.subplots_adjust(bottom=0.15) axw = fig.add_subplot(1,4,1) axn = fig.add_subplot(1,4,2) axe = fig.add_subplot(1,4,3) axs = fig.add_subplot(1,4,4) cax = fig.add_axes([.91, .1, .025, .8]) if sigma: axw.set_ylabel('sigma') else: axw.set_ylabel('pressure') xyfactor = 1e-3 # m -> km x = f.NCOLS + 1 y = f.NROWS + 1 start_south = 0 end_south = start_south + x start_east = end_south end_east = start_east + y start_north = end_east end_north = start_north + x start_west = end_north end_west = start_west + y X, Y = np.meshgrid(np.arange(x + 1) * f.XCELL * xyfactor, vertcrd) patchess = axs.pcolor(X, Y, var[:, start_south:end_south], cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) if not map: if reversevert: axs.set_ylim(*axs.get_ylim()[::-1]) axs.set_title('South') axs.set_xlabel('E to W km') axs.set_xlim(*axs.get_xlim()[::-1]) X, Y = np.meshgrid(np.arange(-1, x) * f.XCELL * xyfactor, vertcrd) patchesn = axn.pcolor(X, Y, var[:, start_north:end_north], cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) if reversevert: axn.set_ylim(*axn.get_ylim()[::-1]) if not map: axn.set_title('North') axn.set_xlabel('W to E km') if map: X, Y = np.meshgrid(vertcrd, np.arange(y + 1) * f.YCELL) patchese = axe.pcolor(X, Y, var[:, start_east:end_east].swapaxes(0,1), cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) if reversevert: axe.set_xlim(*axe.get_xlim()[::-1]) else: X, Y = np.meshgrid(np.arange(y + 1) * f.YCELL * xyfactor, vertcrd) patchese = axe.pcolor(X, Y, var[:, start_east:end_east], cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) if reversevert: axe.set_ylim(*axe.get_ylim()[::-1]) axe.set_title('East') axe.set_xlabel('N to S km') axe.set_xlim(*axe.get_xlim()[::-1]) if map: X, Y = np.meshgrid(vertcrd, np.arange(-1, y) * f.YCELL) patchesw = axw.pcolor(X, Y, var[:, start_west:end_west].swapaxes(0,1), cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) else: X, Y = np.meshgrid(np.arange(-1, y) * f.YCELL * xyfactor, vertcrd) patchesw = axw.pcolor(X, Y, var[:, start_west:end_west], cmap = bmap, vmin = vmin, vmax = vmax, norm = norm) if reversevert: axw.set_ylim(*axw.get_ylim()[::-1]) axw.set_title('West') axw.set_xlabel('S to N km') if map: for ax in [axe, axw]: ax.axis('tight', axis = 'x') pl.setp( ax.xaxis.get_majorticklabels(), rotation=90 ) for ax in [axs, axn]: ax.axis('tight', axis = 'y') else: for ax in [axe, axn, axw, axs] + ([axmap] if map else []): ax.axis('tight') if 'TFLAG' in f.variables.keys(): SDATE = f.variables['TFLAG'][:][0, 0, 0] EDATE = f.variables['TFLAG'][:][-1, 0, 0] STIME = f.variables['TFLAG'][:][0, 0, 1] ETIME = f.variables['TFLAG'][:][-1, 0, 1] if SDATE == 0: SDATE = 1900001 EDATE = 1900001 sdate = datetime.strptime('%07d %06d' % (SDATE, STIME), '%Y%j %H%M%S') edate = datetime.strptime('%07d %06d' % (EDATE, ETIME), '%Y%j %H%M%S') elif 'tau0' in f.variables.keys(): sdate = datetime(1985, 1, 1, 0) + timedelta(hours = f.variables['tau0'][0]) edate = datetime(1985, 1, 1, 0) + timedelta(hours = f.variables['tau1'][-1]) else: sdate = datetime(1900, 1, 1, 0) edate = datetime(1900, 1, 1, 0) try: title = '%s %s to %s' % (var_name, sdate.strftime('%Y-%m-%d'), edate.strftime('%Y-%m-%d')) except: title = var_name fig.suptitle(title.replace('O3', 'Ozone at Regional Boundaries')) if var.min() < vmin and var.max() > vmax: extend = 'both' elif var.min() < vmin: extend = 'min' elif var.max() > vmax: extend = 'max' else: extend = 'neither' fig.colorbar(patchesw, cax = cax, extend = extend) cax.set_xlabel('ppm') fig.savefig('%s_%s%s.%s' % (args.outpath, var_name, lstr, args.figformat)) pl.close(fig)
9 * c4) / 16.0 - c3 / 8.0 - (3 * c2) / 16.0 - (3 * c0) / 16.0 # node 2 qn[1:2 * nx:2, 1:2 * ny:2] = (3 * c7) / 16.0 + (9 * c6) / 16.0 + (9 * c5) / 16.0 + ( 3 * c4) / 16.0 - (3 * c3) / 16.0 - (3 * c1) / 16.0 - c0 / 8.0 # node 3 qn[0:2 * nx:2, 1:2 * ny:2] = (9 * c7) / 16.0 + (9 * c6) / 16.0 + (3 * c5) / 16.0 + ( 3 * c4) / 16.0 - (3 * c2) / 16.0 - c1 / 8.0 - (3 * c0) / 16.0 return Xn, Yn, qn fig = pylab.figure(2) fig.subplots_adjust(hspace=0.4) fig.subplots_adjust(wspace=0.4) pylab.subplot(2, 1, 1) tr_131 = pylab.loadtxt('../s131/s131-double-shear_totalEnergy') tr_132 = pylab.loadtxt('../s132/s132-double-shear_totalEnergy') tr_133 = pylab.loadtxt('../s133/s133-double-shear_totalEnergy') refTe = tr_131[0, 1] pylab.plot(tr_131[:, 0], tr_131[:, 1], label='CFL 0.2') pylab.plot(tr_132[:, 0], tr_132[:, 1], label='CFL 0.1') pylab.plot(tr_133[:, 0], tr_133[:, 1], label='CFL 0.05') pylab.legend(loc='lower left') pylab.title('Total Energy History') pylab.xlabel('Time [s]')
'#C03028', # Fighting '#F85888', # Psychic '#A8B820', # Bug '#A8A878', # Normal '#F8D030', # Electric '#E0C068', # Ground '#EE99AC', # Fairy '#B8A038', # Rock '#705898', # Ghost '#98D8D8', # Ice '#7038F8', # Dragon ] sns.set_style('whitegrid') #sns.set() fig = pl.figure(figsize=(11, 7)) i = 1 axes = {} data_all = pd.DataFrame() data_input = pd.DataFrame() # #for varkey in ['theta','q']: # EF =\ # c4gldata[key].frames['stats']['records_all_stations_ini'].BR/(1.+\ # c4gldata[key].frames['stats']['records_all_stations_ini'].BR) # EF[EF<0] = np.nan # EF[EF>1] = np.nan # c4gldata[key].frames['stats']['records_all_stations_ini']['EF'] = EF ikey = 0
# sample from model kf = KalmanFilter(transition_matrices=transition_matrix, observation_matrices=observation_matrix, transition_offsets=transition_offset, observation_offsets=observation_offset, initial_state_mean=initial_state_mean, random_state=0) states, observations_all = kf.sample(n_timesteps, initial_state=initial_state_mean) # label half of the observations as missing observations_missing = np.ma.array(observations_all, mask=np.zeros(observations_all.shape)) for t in range(n_timesteps): if t % 5 != 0: observations_missing[t] = np.ma.masked # estimate state with filtering and smoothing smoothed_states_all = kf.smooth(observations_all)[0] smoothed_states_missing = kf.smooth(observations_missing)[0] # draw estimates pl.figure() lines_true = pl.plot(states, color='b') lines_smooth_all = pl.plot(smoothed_states_all, color='r') lines_smooth_missing = pl.plot(smoothed_states_missing, color='g') pl.legend((lines_true[0], lines_smooth_all[0], lines_smooth_missing[0]), ('true', 'all', 'missing'), loc='lower right') pl.show()
points_plot.append([0, 0]) # Get default camera window size ret, frame = cap.read() Height, Width = frame.shape[:2] frame_count = 0 # Initialize time varaible then = time.time() #####################################Plot Start####################################### # Initialize plot parameters xAchse = pylab.arange(0, 100, 1) yAchse = pylab.array([0] * 100) fig = pylab.figure(1) ax = fig.add_subplot(121) ay = fig.add_subplot(122) ax.grid(True) ay.grid(True) ax.set_title("X vs Time") ay.set_title("Y vs Time") ax.set_xlabel("Time") ax.set_ylabel("X Value") ay.set_xlabel("Time") ay.set_ylabel("Y Value") ax.axis([0, 100, -1000, 1000]) ay.axis([0, 100, -1000, 1000]) line1 = ax.plot(xAchse, yAchse, 'b-')
kz = cosmo_units.eta2kparr(taulist * 1.E-9, z) #This function needs tau in Hz^-1 k, Pb = n.abs(n.array(kz)), n.abs(data) Deldata = k * k * k * Pb / 2 / (n.pi**2) print "Deldatashape", Deldata.shape #import IPython; IPython.embed() #print "shapes of arrays:", data1.shape, data2.shape #Bootstrap resampling B = 100 bootmean, booterr = boot_simple.bootstrap(B, Deldata) #print bootmean #plotting fig = p.figure() ax = fig.add_subplot(411) #plotp.P_v_Eta(ax,kz,P) ax.set_xlabel('kz') ax.set_ylabel(r'$P(k) K^{2} (h^{-1} Mpc)^{3}$') p.plot(kz, P, 'bo') p.plot(kz, Q, 'go') p.plot(kz, (10 * 2 * n.pi**2) / n.abs(kz)**3, 'ro') #input ax.set_yscale('log') ax = fig.add_subplot(412) #ax.errorbar(kz, n.abs(bootmean), yerr=booterr, fmt='ok', ecolor='gray', alpha=0.5) ax.errorbar(k, n.abs(bootmean), yerr=booterr, fmt='ok', ecolor='gray',
def plot_image(image, title, path): pl.figure() pl.imshow(image) pl.title(title) pl.savefig(path)
post2.name = 'unsmoothed' c = connection(pre, post, [1, 1]) c2 = connection(pre, post2, [1, 1]) sim = simulation(.3, dt=0.0001) sim.monitor(post, [ 'u', ], 0.001) sim.monitor(post2, [ 'u', ], 0.001) run_sim(sim, [pre, post, post2], [c, c2]) figure(figsize=(10, 3)) m = sim.monitors['u'] m.plot() m = sim.monitors['u [unsmoothed]'] m.plot() legend(['Smoothed', 'Unsmoothed']) # In[6]: pre = neurons.poisson_pattern([20]) pre.save_spikes_begin = 0.0 pre.save_spikes_end = 10 post = neurons.srm0(1) post.smoothed = True post.tau = 0.01
(net, sta, chan_pick, stamp_pick.isoformat())) trigs = trigger_onset(prob_S, min_proba, 0.1) for trig in trigs: if trig[1] == trig[0]: continue pick = np.argmax(ts[trig[0]:trig[1], 1]) + trig[0] stamp_pick = st[0].stats.starttime + tt[pick] chan_pick_s = st[0].stats.channel[0:2] + 'E' s_picks.append(stamp_pick) ofile.write( "%s %s %s S %s\n" % (net, sta, chan_pick_s, stamp_pick.isoformat())) if plot: fig = plt.figure(figsize=(8, 12)) ax = [] ax.append(fig.add_subplot(4, 1, 1)) ax.append( fig.add_subplot(4, 1, 2, sharex=ax[0], sharey=ax[0])) ax.append( fig.add_subplot(4, 1, 3, sharex=ax[0], sharey=ax[0])) ax.append(fig.add_subplot(4, 1, 4, sharex=ax[0])) for i in range(3): ax[i].plot(np.arange(st[i].data.size)*dt, st[i].data, c='k', \ lw=0.5) ax[3].plot(tt, ts[:, 0], c='r', lw=0.5) ax[3].plot(tt, ts[:, 1], c='b', lw=0.5) for p_pick in p_picks: for i in range(3): ax[i].axvline(p_pick - st[0].stats.starttime,