def graphError(predictedPercentChanges, actualPercentChanges, title): # considering error and only considering it as error when the signs are different def computeSignedError(pred, actual): if (pred > 0 and actual > 0) or (pred < 0 and actual < 0): return 0 else: error = abs(pred - actual) # print 'pred: {0}, actual: {1}, error: {2}'.format(pred, actual, error) return error signedError = map( lambda pred, actual: computeSignedError(pred, actual), predictedPercentChanges, actualPercentChanges ) pl.figure(2) pl.title(title + " Error") pl.subplot(211) pl.plot(signedError) pl.xlabel("Time step") pl.ylabel("Error (0 if signs are same and normal error if signs are different)") pl.figure(3) pl.title(title + " Actual vs Predictions") pl.subplot(211) pl.plot( range(len(predictedPercentChanges)), predictedPercentChanges, "ro", range(len(actualPercentChanges)), actualPercentChanges, "bs", )
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 Xtest2(self): """ Test from Kate Marvel As the following code snippet demonstrates, regridding a cdms2.tvariable.TransientVariable instance using regridTool='regrid2' results in a new array that is masked everywhere. regridTool='esmf' and regridTool='libcf' both work as expected. This passes. """ import cdms2 as cdms import numpy as np filename = cdat_info.get_sampledata_path() + '/clt.nc' a=cdms.open(filename) data=a('clt')[0,...] print data.mask #verify this data is not masked GRID= data.getGrid() # input = output grid, passes test_data=data.regrid(GRID,regridTool='regrid2') # check that the mask does not extend everywhere... self.assertNotEqual(test_data.mask.sum(), test_data.size) if PLOT: pylab.subplot(2, 1, 1) pylab.pcolor(data[...]) pylab.title('data') pylab.subplot(2, 1, 2) pylab.pcolor(test_data[...]) pylab.title('test_data (interpolated data)') pylab.show()
def window_fn_matrix(Q,N,num_remov=None,save_tag=None,lms=None): Q = n.matrix(Q); N = n.matrix(N) Ninv = uf.pseudo_inverse(N,num_remov=None) # XXX want to remove dynamically #print Ninv info = n.dot(Q.H,n.dot(Ninv,Q)) M = uf.pseudo_inverse(info,num_remov=num_remov) W = n.dot(M,info) if save_tag!=None: foo = W[0,:] foo = n.real(n.array(foo)) foo.shape = (foo.shape[1]), print foo.shape p.scatter(lms[:,0],foo,c=lms[:,1],cmap=mpl.cm.PiYG,s=50) p.xlabel('l (color is m)') p.ylabel('W_0,lm') p.title('First Row of Window Function Matrix') p.colorbar() p.savefig('{0}/{1}_W.pdf'.format(fig_loc,save_tag)) p.clf() print 'W ',W.shape p.imshow(n.real(W)) p.title('Window Function Matrix') p.colorbar() p.savefig('{0}/{1}_W_im.pdf'.format(fig_loc,save_tag)) p.clf() return W
def Xtest3(self): """ Test from Kate Marvel As the following code snippet demonstrates, regridding a cdms2.tvariable.TransientVariable instance using regridTool='regrid2' results in a new array that is masked everywhere. regridTool='esmf' and regridTool='libcf' both work as expected. This is similar to the original test but we construct our own uniform grid. This should passes. """ import cdms2 as cdms import numpy as np filename = cdat_info.get_sampledata_path() + '/clt.nc' a=cdms.open(filename) data=a('clt')[0,...] print data.mask #verify this data is not masked GRID = cdms.grid.createUniformGrid(-90.0, 23, 8.0, -180.0, 36, 10.0, order="yx", mask=None) test_data=data.regrid(GRID,regridTool='regrid2') # check that the mask does not extend everywhere... self.assertNotEqual(test_data.mask.sum(), test_data.size) if PLOT: pylab.subplot(2, 1, 1) pylab.pcolor(data[...]) pylab.title('data') pylab.subplot(2, 1, 2) pylab.pcolor(test_data[...]) pylab.title('test_data (interpolated data)') pylab.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 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 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 benchmark(clf_class, params, name): print("parameters:", params) t0 = time() clf = clf_class(**params).fit(X_train, y_train) print("done in %fs" % (time() - t0)) if hasattr(clf, 'coef_'): print("Percentage of non zeros coef: %f" % (np.mean(clf.coef_ != 0) * 100)) print("Predicting the outcomes of the testing set") t0 = time() pred = clf.predict(X_test) print("done in %fs" % (time() - t0)) print("Classification report on test set for classifier:") print(clf) print() print(classification_report(y_test, pred, target_names=news_test.target_names)) cm = confusion_matrix(y_test, pred) print("Confusion matrix:") print(cm) # Show confusion matrix pl.matshow(cm) pl.title('Confusion matrix of the %s classifier' % name) pl.colorbar()
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 drawPr(tp,fp,tot,show=True): """ draw the precision recall curve """ det=numpy.array(sorted(tp+fp)) atp=numpy.array(tp) afp=numpy.array(fp) #pylab.figure() #pylab.clf() rc=numpy.zeros(len(det)) pr=numpy.zeros(len(det)) #prc=0 #ppr=1 for i,p in enumerate(det): pr[i]=float(numpy.sum(atp>=p))/numpy.sum(det>=p) rc[i]=float(numpy.sum(atp>=p))/tot #print pr,rc,p ap=0 for c in numpy.linspace(0,1,num=11): if len(pr[rc>=c])>0: p=numpy.max(pr[rc>=c]) else: p=0 ap=ap+p/11 if show: pylab.plot(rc,pr,'-g') pylab.title("AP=%.3f"%(ap)) pylab.xlabel("Recall") pylab.ylabel("Precision") pylab.grid() pylab.show() pylab.draw() return rc,pr,ap
def add_quad(self, name, X, fZ): """ Create a 4-panel figure name: title of the figure X: 1D axes data fZ: 2D data set (Fortran indexing) """ # Does not work on chipolata: (older matplotlib?) # i = 0 # fig, axs = pylab.subplots(2,2) # for ax in axs.ravel(): # pcm = ax.pcolormesh(F[i]) # ax.axis('tight') # fig.colorbar(pcm,ax=ax) # ax.set_title(name+','+str(i)) # i += 1 # The default ordering for 2D meshgrid is Fortran style title = name.replace(',', '_') self.figs.append((title, pylab.figure(title))) for i in range(4): fX, fY = numpy.meshgrid(X[i], X[i]) ax = pylab.subplot('22'+str(i+1)) pcm = ax.pcolormesh(fX, fY, fZ[i]) ax.axis('tight') self.figs[-1][1].colorbar(pcm) pylab.title(name+','+str(i))
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 drawPrfastscore(tp,fp,scr,tot,show=True): tp=numpy.cumsum(tp) fp=numpy.cumsum(fp) rec=tp/tot prec=tp/(fp+tp) #dif=numpy.abs(prec[1:]-rec[1:]) dif=numpy.abs(prec[::-1]-rec[::-1]) pos=dif.argmin() pos=len(dif)-pos-1 ap=0 for t in numpy.linspace(0,1,11): pr=prec[rec>=t] if pr.size==0: pr=0 p=numpy.max(pr); ap=ap+p/11; if show: pylab.plot(rec,prec,'-g') pylab.title("AP=%.3f EPRthr=%.3f"%(ap,scr[pos])) pylab.xlabel("Recall") pylab.ylabel("Precision") pylab.grid() pylab.show() pylab.draw() return rec,prec,scr,ap,scr[pos]
def plotEventFlop(library, num, eventNames, sizes, times, events, filename = None): from pylab import legend, plot, savefig, semilogy, show, title, xlabel, ylabel import numpy as np arches = sizes.keys() bs = events[arches[0]].keys()[0] data = [] names = [] for event, color in zip(eventNames, ['b', 'g', 'r', 'y']): for arch, style in zip(arches, ['-', ':']): if event in events[arch][bs]: names.append(arch+'-'+str(bs)+' '+event) data.append(sizes[arch][bs]) data.append(1e-3*np.array(events[arch][bs][event])[:,1]) data.append(color+style) else: print 'Could not find %s in %s-%d events' % (event, arch, bs) semilogy(*data) title('Performance on '+library+' Example '+str(num)) xlabel('Number of Dof') ylabel('Computation Rate (GF/s)') legend(names, 'upper left', shadow = True) if filename is None: show() else: savefig(filename) return
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 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 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 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 plotB3reg(): w=loadStanFit('revE2B3BHreg.fit') printCI(w,'mmu') printCI(w,'mr') for b in range(2): subplot(1,2,b+1) plt.title('') px=np.array(np.linspace(-0.5,0.5,101),ndmin=2) a0=np.array(w['mmu'][:,b],ndmin=2).T a1=np.array(w['mr'][:,b],ndmin=2).T y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)]) x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1)) plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red') #plt.plot([-1,1],[0.5,0.5],'grey') ax=plt.gca() ax.set_aspect(1) ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w')) y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)]) ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w')) man=np.array([-0.4,-0.2,0,0.2,0.4]) mus=[] for m in range(len(man)): mus.append(loadStanFit('revE2B3BH%d.fit'%m)['mmu'][:,b]) mus=np.array(mus).T errorbar(mus,x=man) ax.set_xticks(man) plt.xlim([-0.5,0.5]) plt.ylim([-0.4,0.8]) #plt.xlabel('Manipulated Displacement') if b==0: plt.ylabel('Perceived Displacemet') plt.gca().set_yticklabels([]) subplot_annotate() plt.text(-1.1,-0.6,'Pivot Displacement',fontsize=8);
def evaluate_result(data, target, result): assert(data.shape[0] == target.shape[0]) assert(target.shape[0] == result.shape[0]) correct = np.where( result == target ) miss = np.where( result != target ) class_rate = float(correct[0].shape[0]) / target.shape[0] print "Correct classification rate:", class_rate #get the 3s mask = np.where(target == wanted[0]) data_3_correct = data[np.intersect1d(mask[0],correct[0])] data_3_miss = data[np.intersect1d(mask[0],miss[0])] #get the 8s mask = np.where(target == wanted[1]) data_8_correct = data[np.intersect1d(mask[0],correct[0])] data_8_miss = data[np.intersect1d(mask[0],miss[0])] #plot plot.title("Scatter") plot.xlabel("x_0") plot.ylabel("x_1") size = 20 plot.scatter(data_3_correct[:,0], data_3_correct[:,1], marker = "x", c = "r", s = size ) plot.scatter( data_3_miss[:,0], data_3_miss[:,1], marker = "x", c = "b", s = size ) plot.scatter(data_8_correct[:,0], data_8_correct[:,1], marker = "o", c = "r", s = size ) plot.scatter( data_8_miss[:,0], data_8_miss[:,1], marker = "o", c = "b", s = size ) plot.show()
def plot_roc(self, roc=None): """Plot ROC curves .. plot:: :include-source: :width: 80% from dreamtools import rocs r = rocs.ROC() r.scores = [.9,.5,.6,.7,.1,.2,.6,.4,.7,.9, .2] r.classes = [1,0,1,0,0,1,1,0,0,1,1] r.plot_roc() """ if roc == None: roc = self.get_roc() from pylab import plot, xlim, ylim ,grid, title, xlabel, ylabel x = roc['fpr'] plot(x, roc['tpr'], '-o') plot([0,1], [0,1],'r') ylim([0, 1]) xlim([0, 1]) grid(True) title("ROC curve (AUC=%s)" % self.compute_auc(roc)) xlabel("FPR") ylabel("TPR")
def simulationWithDrug(): """ Runs simulations and plots graphs for problem 4. Instantiates a patient, runs a simulation for 150 timesteps, adds guttagonol, and runs the simulation for an additional 150 timesteps. total virus population vs. time and guttagonol-resistant virus population vs. time are plotted """ maxBirthProb = .1 clearProb = .05 resistances = {'guttagonal': False} mutProb = .005 total = [100] g = [0] badVirus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb) viruses = [badVirus]*total[0] maxPop = 1000 Bob = Patient(viruses, maxPop) for i in range(150): Bob.update() gVirus = 0 for v in Bob.viruses: if v.isResistantTo('guttagonal'): gVirus += 1 #print "g = ", gVirus #print "t = ", len(Bob.viruses) #print g += [gVirus] total += [len(Bob.viruses)] Bob.addPrescription('guttagonal') for i in range(150): Bob.update() gVirus = 0 for v in Bob.viruses: if v.isResistantTo('guttagonal'): gVirus += 1 g += [gVirus] total += [len(Bob.viruses)] pylab.title("Number of Viruses with Different Resistances to Guttagonal") pylab.xlabel("Number of Timesteps") pylab.ylabel("Number of Viruses") pylab.plot(g, '-r', label = 'Resistant') pylab.plot(total, '-b', label = 'Total') pylab.legend(loc = 'lower right') pylab.show()
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 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 plot_signal(x,y,title,labelx,labley,position): pylab.subplot (9, 1, position) pylab.plot(x,y) pylab.title(title) pylab.xlabel(labelx) pylab.ylabel(labley) pylab.grid(True)
def fixup_gauge(current_data): import pylab size = 34 pylab.title("Pressure at Gauge 0", fontsize=size) pylab.xticks([1.0, 1.5, 2.0, 2.5, 3.0], fontsize=size) pylab.yticks([-0.3, -0.1, 0.1, 0.3, 0.5], fontsize=size)
############################ obs = get_usual_observers(w) from common import RecordCoMPosition, RecordGforce obs.append(RecordGforce(lqpc)) ## SIMULATE from numpy import arange from arboris.core import simulate simulate(w, arange(0,1.5,0.01), obs) ########### # # # RESULTS # # # ########### print("end of the simulation") import pylab as pl pl.plot(obs[-1].get_record()) xlim = pl.xlim() pl.ylabel("Tau (N.m)") pl.xlabel("step") pl.title("Gforce Evolution") pl.show()
y_test = NP.multiply(y_test, y_ub - y_lb) + y_lb classes = NP.squeeze(model.predict(x_test)) classes = NP.multiply(classes, y_ub - y_lb) + y_lb mse = NP.mean((y_test - classes)**2, axis=0) rmse = NP.zeros((y_train.shape[1], 1)) for i in range(y_train.shape[1]): rmse[i] = NP.sqrt(mse[i]) print(zone + " RMSE: " + str(rmse[0])) P.subplot(2, 1, 1) P.plot(y_test[:, 0]) P.plot(classes[:, 0]) P.ylabel('SetPoint') P.legend(['ZoneTemp', 'NN']) P.title(zone) P.subplot(2, 1, 2) P.plot(vars()['u_AHU_' + zone]) # P.show() else: """ ---------------------------------------- Definition of the Neural Network ---------------------------------------- """ model = Sequential() model.add( Dense(units=x_train.shape[1], activation='tanh', input_dim=x_train.shape[1]))
def pattern_yearly(fnames,nbins,hmin,hmax,toMSL,\ waves_indices,waves_adjust,\ gaugeno,pdffile,cfile,pdfpng,cpng,\ commentsout,thisrun_directory,A=None,Gplot=None): hvals = linspace(hmin, hmax, nbins + 1) # endpoint values for the bins pdfhist = zeros(nbins) # space for the pdf histogram chist = zeros(nbins) # space for cumulative histogram #predicted is an array of the predicted tide every 60 sec. in [hmin, hmax) #We have a particular pattern of a tsunami described by the waves_indices #and waves_adjust lists as described earlier. We pass this pattern over the #tide data to determine the water level that can be exceeded and build #the following histograms and ultimately pdf and cumulative distributions. # #pdfhist is a histogram of the number of tidal value heights above MLLW in #each bin and chist is a cumulative histogram of tidal value heights above #above MLLW in each bin predicted = load(fnames) #relative to MLLW so far max_predicted = nanmax(predicted) min_predicted = nanmin(predicted) commentsout.write('\n') commentsout.write('max and min of predicted values ref to MLLW are ') commentsout.write('%s and %s \n\n' % (max_predicted, min_predicted)) commentsout.write('max and min of predicted values ref to MSL are ') commentsout.write('%s and %s \n\n ' % (max_predicted + toMSL, min_predicted + toMSL)) pdfhist,chist,valid_length_predicted=makebins(predicted,pdfhist,\ chist,hmin,hmax,nbins,waves_indices,\ waves_adjust,commentsout) #valid_length_predicted is length of colm of probabilities for this pattern totalnumber = valid_length_predicted commentsout.write('totalnumber of non-nan data is: %s \n\n' % totalnumber) #Turn the histograms above into a pdf and a cumulative distribution #by dividing by the total number of valid data entries. #Plot the pdf and cumulative distribution #Write the pdf and cumulative distribution to a file #pdfhist and chist are arrays of one colm and totalnumber is a scalar pdf = pdfhist / totalnumber cpdf = chist / totalnumber commentsout.write('sum of pdfhist is: %s \n\n' % sum(pdfhist)) commentsout.write('sum of chist is: %s \n\n' % sum(chist)) #double check reasonableness of pdf and cpdf bin_midpoints = (hvals[0:-1] + hvals[1:]) / 2.0 meanp = sum(bin_midpoints * pdf[:]) Eofxsqrd = sum((bin_midpoints) * (bin_midpoints) * pdf[:]) sigmap = sqrt(Eofxsqrd - meanp * meanp) commentsout.write('sum of pdf[:] is: %s \n\n' % sum(pdf[:])) commentsout.write('totalnumber is: %s \n\n' % totalnumber) commentsout.write('chist[0] is (matches totalnumber): %s \n\n' % chist[0]) commentsout.write('mean(MLLW) and standard deviation of pdf are ') commentsout.write('%s and %s \n\n' % (meanp, sigmap)) commentsout.write('mean(MSL) and standard deviation of pdf are ') commentsout.write('%s and %s \n\n' % (meanp + toMSL, sigmap)) ############ Convert the probability mass function above to real pdf ### ############ height of mass function must be divided by the binsize ### ##### so integration of the pdf is one. ### # binsize = (hmax - hmin) / float(nbins) pdf[:] = pdf[:] / binsize #### #### Calculate the pdf as the negative of the derivative of the cpdf ## # for plotting purposes # # Find derivatives at the center of the bins # Recall the cpdf values are at the bin left endpoints, and the # right endpoint of the last bin is always guaranteed to have no # value exceeding it, so the probability is 0 at this absent endpoint # Use 2.5 binsizes on each side of the bin-midpoint for smooth curve # deriv = zeros(nbins) #deriv[0],...deriv[nbins-1] deriv[0] = (cpdf[1] - cpdf[0]) / binsize #deriv at first bin center deriv[1] = (cpdf[2] - cpdf[1]) / binsize #deriv at second bin center deriv[2] = (cpdf[3] - cpdf[2]) / binsize #deriv at third bin center deriv[-1] = (0.0 - cpdf[-1]) / binsize #deriv at nbin-1 bin center deriv[-2] = (cpdf[-1] - cpdf[-2]) / binsize #deriv at nbin-2 bin center deriv[-3] = (cpdf[-2] - cpdf[-1]) / binsize #deriv at nbin-3 bin center for i in range(3, nbins - 3): #deriv for bins 4,..,nbin-4 centers deriv[i] = (cpdf[i + 3] - cpdf[i - 2]) / (5 * binsize) deriv = -deriv #################### ##### Calculate a normal pdf and associated cumulative distribution ##### using the same mean and standard deviation as our pattern pdf ##### Call these pdf_normal and cum_erf. They could be plotted. Not ##### being plotted or used at the moment. ##### w0 = meanp + toMSL w = hvals[:-1] + toMSL wmid = bin_midpoints + toMSL const = 1.0 / (sqrt(2 * pi) * sigmap) pdf_normal = const * exp(-(wmid - w0) * (wmid - w0) / (2 * sigmap * sigmap)) erfarg = (w - w0) / (sqrt(2) * sigmap) cum_erf = .5 * (1.0 - erf(erfarg)) #### #### if (A != None): #The A value is the amplitude for tsuanmi of interest. Use it to #calculate the pdf and cumulative distribution for the G-method #A is passed to this routine as a parameter. Below are typical #values that A may be: #The following 8 values are specific to Crescent City C = 1.044 Cprime = .707 alpha = .17 beta = .858 alphaprime = .056 betaprime = 1.119 sigma0 = .638 MHHW = .97 w0_MOF = C * MHHW * exp(-alpha * (A / sigma0)**beta) sigmap_MOF = sigma0 * (1.0 - Cprime * exp(-alphaprime * (A / sigma0)**betaprime)) commentsout.write('A used was: %s \n\n' % A) commentsout.write('w0_MOF mean of G-method tide cumulative ') commentsout.write('was: %s \n\n' % w0_MOF) commentsout.write('sigmap_MOF std of G-method tide cumulative ') commentsout.write('was: %s \n\n' % sigmap_MOF) const_MOF = 1.0 / (sqrt(2 * pi) * sigmap_MOF) pdf_MOF=const_MOF*exp(-(wmid-w0_MOF)*(wmid-w0_MOF)\ /(2*sigmap_MOF*sigmap_MOF)) erfarg_MOF = (w - w0_MOF) / (sqrt(2) * sigmap_MOF) cum_erf_MOF = .5 * (1.0 - erf(erfarg_MOF)) #Plot the pdf at Gauge 101 for the thisrun_directory tsunami figno = 0 fig = pylab.figure(figno + 1) patterngauge = 101 commentsout.write('Gplot was: %s \n\n' % Gplot) if ((Gplot == None) | (A == None)): pylab.plot(wmid, deriv[:], 'r-') pylab.legend(['Pattern'], 'upper left') pylab.title('Gauge %s: Probability Density Function for %s ' \ %(patterngauge,thisrun_directory)) pylab.xlabel('tidal stage above MSL') if ((Gplot == True) & (A != None)): pylab.plot(wmid, deriv[:], 'r-') pylab.plot(wmid, pdf_MOF[:], 'g--', linewidth=2) pylab.legend(['Pattern','G-Method'], \ 'upper left') pylab.title('Gauge %s: Probability Density Functions for %s ' \ %(patterngauge,thisrun_directory)) pylab.xlabel('tidal stage above MSL') savefig(pdfpng) #Plot the cumulative dist. at Gauge 101 for thisrun_directory tsunami fig = pylab.figure(figno + 2) pylab.axis([-2.0, 2.0, 0.0, 1.1]) if ((Gplot == None) | (A == None)): pylab.plot(w, cpdf[:], 'k-') pylab.legend(['Pattern'], 'lower left') pylab.title('Gauge %s: Cumulative Probability of Exceedance \ for %s ' % (patterngauge, thisrun_directory)) pylab.xlabel('tidal stage above MSL') pylab.ylabel('probability') if ((Gplot == True) & (A != None)): pylab.plot(w, cpdf[:], 'k-') pylab.plot(w, cum_erf_MOF[:], 'g--', linewidth=2) pylab.legend(['Pattern', 'G-Method'], 'lower left') pylab.title('Gauge %s: Cumulative Probability of Exceedance \ for %s ' % (patterngauge, thisrun_directory)) pylab.xlabel('tidal stage above MSL') pylab.ylabel('probability') savefig(cpng) #Write the pdf and cumulative distribution to a file outfile = open(pdffile, 'w') sh = shape(pdf) for i in range(sh[0]): tupleprint = (hvals[i] + toMSL, hvals[i + 1] + toMSL, pdf[i]) outfile.write(len(tupleprint) * '%7.3f ' % tupleprint) outfile.write('\n') outfile.close() outfile = open(cfile, 'w') for i in range(sh[0]): tupleprint = (hvals[i] + toMSL, cpdf[i]) outfile.write(len(tupleprint) * '%7.3f ' % tupleprint) outfile.write('\n') outfile.close()
# Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) for shrinkage in [None, 0.1]: # we create an instance of Neighbours Classifier and fit the data. clf = NearestCentroid(shrink_threshold=shrinkage) clf.fit(X, y) y_pred = clf.predict(X) print shrinkage, np.mean(y == y_pred) # Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) pl.figure() pl.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) pl.title("3-Class classification (shrink_threshold=%r)" % shrinkage) pl.axis('tight') pl.show()
plt.clf() dimshow(map, cmap='RdBu', vmin=-mx, vmax=mx) plt.xticks([]) plt.yticks([]) for chip in chipnames: x, y = ccd_map_center(chip) plt.text(x - 0.5, y - 0.5, chip, fontsize=8, color='k', ha='center', va='center') plt.colorbar() if cut is not None: col = '%s[%i]' % (col, cut) plt.title('Zeropoint diffs (mean %.3f) for %s, %i %s' % (meanzp, col, expnum, band)) ps.savefig() if not expnum in allzps: allzps[expnum] = (expnum, meanzp, im.exptime) if outfn: T = fits_table() T.expnum = np.array(allzps.keys()) T.ccdzpt = np.array([v[1] for v in allzps.values()]) T.exptime = np.array([v[2] for v in allzps.values()]) T.writeto(outfn) print 'Wrote', outfn
def plotResults(self): #### calculate stats on collected data and draw some plots #### import matplotlib.mlab as mlab from matplotlib.pyplot import axis, title, xlabel, hist, grid, show, ylabel, plot import pylab results= self.results durations=results[:,0] flips=results[1:,2] dmin=durations.min() dmax=durations.max() dmean=durations.mean() dstd=durations.std() fmean=flips.mean() fstd=flips.std() pylab.figure(figsize=[30,10]) pylab.subplot(1,3,1) # the histogram of the delay data n, bins, patches = hist(durations, 50, facecolor='blue', alpha=0.75) # add a 'best fit' line y = norm.pdf( bins, dmean, dstd) plot(bins, y, 'r--', linewidth=1) xlabel('ioHub getEvents Delay') ylabel('Percentage') title('ioHub Event Delay Histogram (msec.usec):\n'+r'$\ \min={0:.3f},\ \max={1:.3f},\ \mu={2:.3f},\ \sigma={3:.3f}$'.format( dmin, dmax, dmean, dstd)) axis([0, dmax+1.0, 0, 25.0]) grid(True) # graphs of the retrace data ( taken from retrace example in psychopy demos folder) intervalsMS = flips m=fmean sd=fstd distString= "Mean={0:.1f}ms, s.d.={1:.1f}, 99%CI={2:.1f}-{3:.1f}".format( m, sd, m - 3 * sd, m + 3 * sd) nTotal=len(intervalsMS) nDropped=sum(intervalsMS>(1.5*m)) droppedString = "Dropped/Frames = {0:d}/{1:d} = {2}%".format( nDropped, nTotal, int(nDropped) / float(nTotal)) pylab.subplot(1,3,2) #plot the frameintervals pylab.plot(intervalsMS, '-') pylab.ylabel('t (ms)') pylab.xlabel('frame N') pylab.title(droppedString) pylab.subplot(1,3,3) pylab.hist(intervalsMS, 50, histtype='stepfilled') pylab.xlabel('t (ms)') pylab.ylabel('n frames') pylab.title(distString) show()
fig = figure(1, (8, 8)) # plot the results subplot(221) map_z = sum(map, 2) mx = L_p(map_z.max()) imshow(L_p(map_z.T), vmax=mx, vmin=mx - 20, origin='lower', interpolation='nearest', extent=(g.x_min, g.x_max, g.y_min, g.y_max)) xlabel('x') ylabel('y') title('Top view (xy)') subplot(223) map_y = sum(map, 1) imshow(L_p(map_y.T), vmax=mx, vmin=mx - 20, origin='upper', interpolation='nearest', extent=(g.x_min, g.x_max, -g.z_max, -g.z_min)) xlabel('x') ylabel('z') title('Side view (xz)') subplot(222) map_x = sum(map, 0)
# determine min/max values umin = 0.9 * udata.min() umax = 1.1 * udata.max() vmin = 0.9 * vdata.min() vmax = 1.1 * vdata.max() wmin = 0.9 * wdata.min() wmax = 1.1 * wdata.max() minval = np.array([umin, vmin, wmin]).min() maxval = np.array([umax, vmax, wmax]).max() # plot the mesh plt.figure(1) plt.plot(mesh, 0.0 * mesh, 'o') plt.xlabel('x') plt.title('FEM mesh') plt.savefig('brusselator1D_FEM_mesh.png') # generate plots of results for tstep in range(nt): # set string constants for output plots, current time, mesh size pname = 'brusselator1D_FEM.' + repr(tstep).zfill(3) + '.png' tstr = repr(tstep) nxstr = repr(nx) # plot current solution and save to disk plt.figure(1) plt.plot(mesh, udata[tstep, :], label="u") plt.plot(mesh, vdata[tstep, :], label="v") plt.plot(mesh, wdata[tstep, :], label="w")
def plot_maglites_nightsum(fields,nitestr): #fields = FieldArray.load_database() #new = np.char.startswith(fields['DATE'],date) from obztak.utils.database import Database date = nite2utc(nitestr) new = (np.array(map(utc2nite,fields['DATE'])) == nitestr) new_fields = fields[new] old_fields = fields[~new] kwargs = dict(edgecolor='none', s=50, vmin=0, vmax=4) fig,basemap = makePlot(date=nitestr,name='nightsum',moon=False,airmass=False,center=(0,-90),bliss=False) plt.title('Coverage (%s)'%nitestr) kwargs['cmap'] = 'gray_r' proj = basemap.proj(old_fields['RA'], old_fields['DEC']) basemap.scatter(*proj, c=old_fields['TILING'],**kwargs) kwargs['cmap'] = 'summer_r' proj = basemap.proj(new_fields['RA'], new_fields['DEC']) basemap.scatter(*proj, c=new_fields['TILING'], **kwargs) colorbar = plt.colorbar() colorbar.set_label('Tiling') plt.plot(np.nan, np.nan,'o',color='green',mec='green',label='Observed tonight') plt.plot(np.nan, np.nan,'o',color='0.7',mec='0.7',label='Observed previously') plt.legend(fontsize=10,loc='lower left',scatterpoints=1) plt.savefig('nightsum_coverage_%s.png'%nitestr,bbox_inches='tight') db = Database() db.connect() query = """ select id, qc_fwhm as psf, qc_teff as teff from exposure where exptime = 90 and delivered = True and propid = '2016A-0366' and qc_teff is not NULL and qc_fwhm is not NULL and to_timestamp(utc_beg) %s '%s' """ new = db.query2recarray(query%('>',date)) old = db.query2recarray(query%('<',date)) nbins = 35 kwargs = dict(normed=True) step_kwargs = dict(kwargs,histtype='step',lw=3.5) fill_kwargs = dict(kwargs,histtype='stepfilled',lw=1.0,alpha=0.7) plt.figure() step_kwargs['bins'] = np.linspace(0.5,2.5,nbins) fill_kwargs['bins'] = np.linspace(0.5,2.5,nbins) plt.hist(new['psf'],color='green',zorder=10, label='Observed tonight', **fill_kwargs) plt.hist(new['psf'],color='green',zorder=10, **step_kwargs) plt.hist(old['psf'],color='0.5', label='Observed previously', **fill_kwargs) plt.hist(old['psf'],color='0.5', **step_kwargs) plt.axvline(1.20,ls='--',lw=2,color='gray') plt.legend() plt.title('Seeing (%s)'%nitestr) plt.xlabel('FWHM (arcsec)') plt.ylabel('Normalized Number of Exposures') plt.savefig('nightsum_psf_%s.png'%nitestr,bbox_inches='tight') plt.figure() step_kwargs['bins'] = np.linspace(0,1.5,nbins) fill_kwargs['bins'] = np.linspace(0,1.5,nbins) plt.hist(new['teff'],color='green',zorder=10,label='Observed tonight', **fill_kwargs) plt.hist(new['teff'],color='green',zorder=10, **step_kwargs) plt.hist(old['teff'],color='0.5',label='Observed previously', **fill_kwargs) plt.hist(old['teff'],color='0.5', **step_kwargs) plt.axvline(0.25,ls='--',lw=2,color='gray') plt.legend() plt.title('Effective Depth (%s)'%nitestr) plt.xlabel('Teff') plt.ylabel('Normalized Number of Exposures') plt.savefig('nightsum_teff_%s.png'%nitestr,bbox_inches='tight')
#%% pl.figure() poor_perf = np.where(np.logical_and(corrs > 0.85, corrs <= .9))[0] for poor in poor_perf[:]: pl.subplot(1, 2, 1) pl.cla() if idx_tp_comp[poor] < 300: continue # if idx_tp_gt[poor] not in [250,134,156,174]: # continue on, off = np.array(C_on_thr[idx_tp_comp[poor], :]).T, np.array( C_off_thr[idx_tp_gt[poor], :]).T pl.plot((on - np.min(on)) / (np.max(on) - np.min(on))) pl.plot((off - np.min(off)) / (np.max(off) - np.min(off))) pl.title(str(corrs[poor])) pl.legend(['Online', 'Offline']) pl.xlabel('Frames (eventually downsampled)') pl.ylabel('A.U.') pl.subplot(1, 2, 2) pl.cla() on, off = A_on_thr[:, idx_tp_comp[poor]].copy( ), A_off_thr[:, idx_tp_gt[poor]].copy() on = on / np.max(on) off = off / np.max(off) pl.imshow(Cn, cmap='gray', vmax=np.percentile(Cn, 90)) pl.imshow(on.reshape(dims_on, order='F'), cmap='Blues', alpha=.3, vmax=1) pl.imshow(off.reshape(dims_on, order='F'), cmap='hot', alpha=.3, vmax=3) print(idx_tp_gt[poor]) pl.rcParams['pdf.fonttype'] = 42 font = {'family': 'Myriad Pro', 'weight': 'regular', 'size': 20}
def labelPlot(): pylab.title('Measured Displacement of Spring') pylab.xlabel('|Force| (Newtons)') pylab.ylabel('Distance (meters)')
m1.append(max(p.mass1, p.mass2)) m2.append(min(p.mass1, p.mass2)) mt.append(p.mass1 + p.mass2) mc.append(p.mchirp) et.append(p.eta) s1z.append(p.spin1z) s2z.append(p.spin2z) print("Plotting bank %s" % fname) pb.figure(pi) pi += 1 pb.plot(m1, m2, 'x') pb.xlim([min(m1) - .5, max(m1) + .5]) pb.ylim([min(m2) - .5, max(m2) + .5]) pb.grid() pb.title('Bank %d' % idx) pb.xlabel('Mass ($M_{\odot}$)') pb.ylabel('Mass ($M_{\odot}$)') pb.savefig('plots/bank_m1m2_%d.png' % idx, dpi=300, format='png') pb.figure(pi) pi += 1 pb.plot(mc, et, 'x') pb.xlim([min(mc) - .5, max(mc) + .5]) pb.ylim([min(et) - .01, max(et) + .01]) pb.grid() pb.title('Bank %d' % idx) pb.xlabel('$\mathcal{M}_c$ ($M_{\odot}$)') pb.ylabel('$\eta$') pb.savefig('plots/bank_mcet_%d.png' % idx, dpi=300, format='png')
x = np.array([1, 2, 3, 4, 5]) import random err = x * 0.0 for i in range(len(x)): err[i] = 0.9 * (2 * random.random() - 1.0) y = 2.1 * x + err print "x = ", x print "y = ", y a_prop = propfit(y, x) print "propfit: ", a_prop from pylab import figure, plot, legend, show, title plot(x, y, 'ko', label='data') plot(x, a_prop * x, label='fit') legend() title('Proportional fit') #show() figure() y = 2.7 * x - 1.1 + err print "x = ", x print "y = ", y a, b = linfit(y, x) print "linfit: ", a, b from pylab import figure, plot, legend, show plot(x, y, 'ko', label='data') plot(x, a * x + b, label='fit') legend() title('Linear fit') show()
xClass, xRel, vClass, vRel = (xClass_10xc, xRel_10xc, vClass_10xc, vRel_10xc) x0 = 10 * xc #plot the two calculations as an overlay, for both x and v figure(j) subplot(2, 1, 1) plot(t, xRel, t, xClass) legend(('Relativistic', 'Classical')) xlabel('time(s)') subplot(2, 1, 2) plot(t, vRel, t, vClass) xlabel('time(s)') title('v') suptitle('x0 = ' + str(x0) + 'm') tight_layout() savefig('Lab03-Q1a-Fig' + str(j + 1) + '.png') #------------------------------------------------------------------------ # Relativistic period x0_range = linspace(1, 10 * xc, 1000) def g(x): return c*sqrt(((0.5*k*(x0**2-x**2)*(2.0*m*c**2+0.5*k*(x0**2-x**2))) \ /(m*c**2+0.5*k*(x0**2-x**2))**2)) def integrand(x): return 4.0 * g(x)**-1
from pylab import figure, title, ylim from pacal import * def plot_parallel_resistors(R1, R2): N = R1 * R2 D = R1 + R2 R = N / D M = TwoVarsModel(PiCopula([R1, R2]), R) r = M.eval() r.plot() ylim(ymin=0) r.summary() R1 = UniformDistr(0.5, 1.5) R2 = UniformDistr(1.5, 2.5) plot_parallel_resistors(R1, R2) title("R1~U(0.5, 1.5), R2~U(1.5, 2.5), R= (R1*R2) / (R1 + R2)") show() figure() R = 1 / (1 / R1 + 1 / R2) R.plot() R.summary() ylim(ymin=0) title("1/(1/R1 + 1/R2)") show()
import random, pylab nsamples = 100000 x_list, y_list = [], [] for sample in range(nsamples): x_list.append(random.gauss(0.0, 1.0)) y_list.append(random.gauss(0.0, 1.0)) # begin graphics output pylab.plot(x_list, y_list, marker='.', linestyle='') pylab.title('Samples from the 2D Gaussian distribution') pylab.xlabel('$x$', fontsize=14) pylab.ylabel('$y$', fontsize=14) pylab.xlim(-4.0, 4.0) pylab.ylim(-4.0, 4.0) #pylab.axes().set_aspect('equal') # set the aspect ratio of the plot pylab.axis('equal') pylab.savefig('plot-gauss_2d.png')
#chi_init = np.degrees(0.5*np.arctan2(stokesU,stokesQ)) #chi =chi_init + phi0 pl.subplot(111) pl.plot(nu, dataQ) pl.plot(nu, dataU) pl.xlabel('0.58 to 2.5GHz, RM=50') # string must be enclosed with quotes ' ' pl.ylabel('Q and U ') pl.title('Stokes parameters against Frequency') pl.legend(['stokesQ', 'stokesU']) pl.savefig('plot1.png') pl.show() pl.subplot(111) #pl.plot(nu,dataQ) pl.plot(nu, stokesQ) #pl.plot(nu,dataU)
#containers for the particles trajectory x = [i] y = [j] #seed the random number generator seed(time()) #compute the trajectory for k in range(N): i, j = move(i, j) x.append(i) y.append(j) #cast containers to arrays x = np.array(x) y = np.array(y) #plot trajectory of the particle plt.figure() plt.plot(x, y, label="trajectory") plt.plot(x[0], y[0], '.', label='start point', c='black') plt.plot(x[-1], y[-1], '.', label='finish point', c='red') plt.title("2D Brownian Motion Simulation") plt.ylabel("y position") plt.xlabel("x position") plt.xlim(0, 100) plt.ylim(0, 100) plt.grid() plt.legend() plt.savefig("../images/Brownian_motion.png", dpi=500)
def plot_3_targs(): #name three objects targNames = ['ob140613', 'ob150211', 'ob150029'] #object alignment directories an_dirs = [ '/g/lu/microlens/cross_epoch/OB140613/a_2018_09_24/prop/', '/g/lu/microlens/cross_epoch/OB150211/a_2018_09_19/prop/', '/g/lu/microlens/cross_epoch/OB150029/a_2018_09_24/prop/' ] align_dirs = ['align/align_t', 'align/align_t', 'align/align_t'] points_dirs = ['points_a/', 'points_d/', 'points_d/'] poly_dirs = ['polyfit_a/fit', 'polyfit_d/fit', 'polyfit_d/fit'] xlim = [1.2, 2.0, 1.5] ylim = [1.0, 7.0, 1.5] #Output file #filename = '/Users/jlu/doc/proposals/keck/uc/19A/plot_3_targs.png' filename = '/Users/jlu/plot_3_targs.png' #figsize = (15, 4.5) figsize = (10, 4.5) ps = 9.92 plt.close(1) plt.figure(1, figsize=figsize) Ntarg = len(targNames) - 1 for i in range(Ntarg): rootDir = an_dirs[i] starName = targNames[i] align = align_dirs[i] poly = poly_dirs[i] point = points_dirs[i] s = starset.StarSet(rootDir + align) s.loadPolyfit(rootDir + poly, accel=0, arcsec=0) names = s.getArray('name') mag = s.getArray('mag') x = s.getArray('x') y = s.getArray('y') ii = names.index(starName) star = s.stars[ii] pointsTab = Table.read(rootDir + point + starName + '.points', format='ascii') time = pointsTab[pointsTab.colnames[0]] x = pointsTab[pointsTab.colnames[1]] y = pointsTab[pointsTab.colnames[2]] xerr = pointsTab[pointsTab.colnames[3]] yerr = pointsTab[pointsTab.colnames[4]] if i == 0: print('Doing MJD') idx_2015 = np.where(time <= 57387) idx_2016 = np.where((time > 57387) & (time <= 57753)) idx_2017 = np.where((time > 57753) & (time <= 58118)) idx_2018 = np.where((time > 58119) & (time <= 58484)) else: idx_2015 = np.where(time < 2016) idx_2016 = np.where((time >= 2016) & (time < 2017)) idx_2017 = np.where((time >= 2017) & (time < 2018)) idx_2018 = np.where((time >= 2018) & (time < 2019)) fitx = star.fitXv fity = star.fitYv dt = time - fitx.t0 fitLineX = fitx.p + (fitx.v * dt) fitSigX = np.sqrt(fitx.perr**2 + (dt * fitx.verr)**2) fitLineY = fity.p + (fity.v * dt) fitSigY = np.sqrt(fity.perr**2 + (dt * fity.verr)**2) from matplotlib.ticker import FormatStrFormatter fmtX = FormatStrFormatter('%5i') fmtY = FormatStrFormatter('%6.2f') fontsize1 = 16 # Convert everything into relative coordinates: x -= fitx.p y -= fity.p fitLineX -= fitx.p fitLineY -= fity.p # Change plate scale. x = x * ps * -1.0 y = y * ps xerr *= ps yerr *= ps fitLineX = fitLineX * ps * -1.0 fitLineY = fitLineY * ps fitSigX *= ps fitSigY *= ps paxes = plt.subplot(1, Ntarg, i + 1) plt.errorbar(x[idx_2015], y[idx_2015], xerr=xerr[idx_2015], yerr=yerr[idx_2015], fmt='r.', label='2015') plt.errorbar(x[idx_2016], y[idx_2016], xerr=xerr[idx_2016], yerr=yerr[idx_2016], fmt='g.', label='2016') plt.errorbar(x[idx_2017], y[idx_2017], xerr=xerr[idx_2017], yerr=yerr[idx_2017], fmt='b.', label='2017') plt.errorbar(x[idx_2018], y[idx_2018], xerr=xerr[idx_2018], yerr=yerr[idx_2018], fmt='c.', label='2018') # if i==1: # plt.yticks(np.arange(np.min(y-yerr-0.1*ps), np.max(y+yerr+0.1*ps), 0.3*ps)) # plt.xticks(np.arange(np.min(x-xerr-0.1*ps), np.max(x+xerr+0.1*ps), 0.25*ps)) # else: # plt.yticks(np.arange(np.min(y-yerr-0.1*ps), np.max(y+yerr+0.1*ps), 0.15*ps)) # plt.xticks(np.arange(np.min(x-xerr-0.1*ps), np.max(x+xerr+0.1*ps), 0.15*ps)) paxes.tick_params(axis='both', which='major', labelsize=fontsize1) paxes.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) paxes.xaxis.set_major_formatter(FormatStrFormatter('%.2f')) plt.xlabel('X offset (mas)', fontsize=fontsize1) plt.ylabel('Y offset (mas)', fontsize=fontsize1) plt.plot(fitLineX, fitLineY, 'k-', label='_nolegend_') plt.plot(fitLineX + fitSigX, fitLineY + fitSigY, 'k--', label='_nolegend_') plt.plot(fitLineX - fitSigX, fitLineY - fitSigY, 'k--', label='_nolegend_') # Plot lines between observed point and the best fit value along the model line. for ee in range(len(time)): if ee in idx_2015[0].tolist(): color_line = 'red' if ee in idx_2016[0].tolist(): color_line = 'green' if ee in idx_2017[0].tolist(): color_line = 'blue' if ee in idx_2018[0].tolist(): color_line = 'cyan' plt.plot([fitLineX[ee], x[ee]], [fitLineY[ee], y[ee]], color=color_line, linestyle='dashed', alpha=0.8) plt.axis([xlim[i], -xlim[i], -ylim[i], ylim[i]]) plt.title(starName.upper()) if i == 0: plt.legend(loc=1, fontsize=12) plt.subplots_adjust(wspace=0.6, hspace=0.6, left=0.08, bottom=0.05, right=0.95, top=0.90) plt.tight_layout() plt.show() plt.savefig(filename) return
X /= X.std(axis=0) ################################################################################ # Shuffle the data because of non-stationarity np.random.seed(0) order = np.random.permutation(len(X)) X = X[order] y = y[order] from scikits.learn import linear_model, cross_val lasso = linear_model.LassoCV() scores = cross_val.cross_val_score(lasso, X, y, n_jobs=-1) lasso.fit(X, y) print n[lasso.coef_ != 0] ################################################################################ # Plot the time series import pylab as pl pl.plot(variation[names == 'Google'].squeeze()) pl.title('Google stock value') pl.xlabel('Time') pl.ylabel('Google quote daily increment') #_, labels, _ = cluster.k_means(X.T, 10) # #for i in range(labels.max()+1): # print 'Cluster %i: %s' % ((i+1), # ', '.join(n[labels==i]))
def plot_correlation_function(interp, comp='u', Title=None): EXT = [ np.min(interp._2pcf_dist[:, 0] / 60.), np.max(interp._2pcf_dist[:, 0] / 60.), np.min(interp._2pcf_dist[:, 1] / 60.), np.max(interp._2pcf_dist[:, 1] / 60.) ] CM = plt.cm.seismic MAX = np.max(interp._2pcf) N = int(np.sqrt(len(interp._2pcf))) plt.figure(figsize=(14, 8), frameon=False) plt.gca().patch.set_alpha(0) plt.subplots_adjust(wspace=0.5, hspace=0.3, left=0.07, right=0.95, bottom=0.1, top=0.92) plt.subplot(2, 3, 1) plt.imshow(interp._2pcf.reshape(N, N), extent=EXT, interpolation='nearest', origin='lower', vmin=-MAX, vmax=MAX, cmap=CM) cbar = plt.colorbar() cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() cbar.set_label('$\\xi$ (mas$^2$)', fontsize=16) plt.xlabel('$\Delta u$ (arcmin)', fontsize=16) plt.ylabel('$\Delta v$ (arcmin)', fontsize=16) plt.title('Measured 2-PCF', fontsize=16) plt.subplot(2, 3, 2) plt.imshow(interp._2pcf_fit.reshape(N, N), extent=EXT, interpolation='nearest', origin='lower', vmin=-MAX, vmax=MAX, cmap=CM) cbar = plt.colorbar() cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() cbar.set_label('$\\xi\'$ (mas$^2$)', fontsize=16) plt.xlabel('$\Delta u$ (arcmin)', fontsize=16) pull = (interp._2pcf.reshape(N, N) - interp._2pcf_fit.reshape(N, N) ) #/ np.sqrt(var) plt.title('Fitted 2-PCF', fontsize=16) plt.subplot(2, 3, 3) plt.imshow(pull, extent=EXT, interpolation='nearest', origin='lower', vmin=-MAX, vmax=MAX, cmap=CM) #, vmin=-5., vmax=+5., cmap=cm_residual) cbar = plt.colorbar() cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() cbar.set_label('$\\xi - \\xi\'$ (mas$^2$)', fontsize=16) plt.xlabel('$\Delta u$ (arcmin)', fontsize=16) plt.title('Difference', fontsize=16) MAX = 15 plt.subplot(2, 3, 4) plt.scatter(interp._u / 60., interp._v / 60., c=interp._y_meas, s=10, cmap=plt.cm.seismic, vmin=-MAX, vmax=MAX) cbar = plt.colorbar() cbar.set_label('d' + comp + ' measured (mas)', fontsize=16) plt.axis('equal') plt.title('Data', fontsize=16) plt.ylabel('v (arcmin)', fontsize=16) plt.xlabel('u (arcmin)', fontsize=16) plt.subplot(2, 3, 5) plt.scatter(interp._u / 60., interp._v / 60., c=interp._y_predict, s=10, cmap=plt.cm.seismic, vmin=-MAX, vmax=MAX) cbar = plt.colorbar() cbar.set_label('d' + comp + ' prediction (mas)', fontsize=16) plt.axis('equal') plt.title('GP prediction', fontsize=16) plt.xlabel('u (arcmin)', fontsize=16) plt.subplot(2, 3, 6) plt.scatter(interp._u / 60., interp._v / 60., c=interp._y_meas - interp._y_predict, s=10, cmap=plt.cm.seismic, vmin=-MAX, vmax=MAX) cbar = plt.colorbar() cbar.set_label('d' + comp + ' measured - d' + comp + ' prediction (mas)', fontsize=16) plt.axis('equal') plt.title('Residuals', fontsize=16) plt.xlabel('u (arcmin)', fontsize=16) if Title is not None: plt.suptitle(Title, fontsize=16)
import random, math, pylab, mpl_toolkits.mplot3d x_list, y_list, z_list = [], [], [] nsamples = 200000 for sample in range(nsamples): x, y, z = random.gauss(0.0, 1.0), random.gauss(0.0, 1.0), random.gauss(0.0, 1.0) length = random.uniform(0.0, 1.0)**(1.0 / 3.0) / math.sqrt(x**2 + y**2 + z**2) x, y, z = x * length, y * length, z * length if z < 0.075 and z > -0.075 or z > 0.85 or z < -0.85: x_list.append(x) y_list.append(y) z_list.append(z) # Graphics output fig = pylab.figure() ax = fig.gca(projection="3d") ax.set_aspect("auto") pylab.title( "Uniform sampling inside the sphere\n(only shown three intervals for z)") ax.set_xlabel("$x$", fontsize=14) ax.set_ylabel("$y$", fontsize=14) ax.set_zlabel("$z$", fontsize=14) pylab.plot(x_list, y_list, z_list, ".") pylab.savefig("images/direct_3d_movie.png") #pylab.show()
def showpatch(patch, ima): im = patch.patch h, w = im.shape ext = [patch.x0, patch.x0 + w, patch.y0, patch.y0 + h] plt.imshow(im, extent=ext, **ima) plt.title(patch.name)
Call[0,:],c='black',label='Mixing & Chemistry; surface sampling') #plt.plot(np.arange(0,tsteps,dtsteps)*usewind/1000.,\ # Call[np.squeeze(ind),:], c='red',label='Total: Mixing + Chemistry; Sampling @ 100 m') # Assuming here that we are using existing GC-MS instrumentation at the AGAGE sites which concentrates # a 2-liter volume air sample. We can detect 1 ppt with good precision, so that equates to 0.00139 ug/m3 # for HFC-41. ind = np.squeeze(np.where(Call[0, :] <= LoD)) print(xdistance[ind[0]]) plt.plot([0, 6000], [LoD, LoD], 'r--', label='LoD ' + compound) plt.title('Release height:' + str(release_height) + ' km; Emission = ' + str(source / 1e6) + ' g/s') #; LoD distance: '+str(xdistance[ind[0]])+' km') plt.plot([xdistance[ind[0]], xdistance[ind[0]]], [0, 0.25], 'r-.', label='Distance where X ~ LoD ' + compound) plt.ylim([0, 0.25]) plt.xlim([0, 2000]) #plt.plot(np.arange(tsteps)*usewind/1000.,Cmix,c='red',label='Mixing') plt.xlabel('Distance from source [km]') plt.ylabel('Pollutant concentration [$\mu$g/m$^3$]') plt.legend() plt.savefig('ts_gauss.png')
def plot(cond_v, cond_gsyn, cond_spikes, curr_v, curr_gsyn, curr_spikes, izk_v, izk_gsyn, izk_spikes): import pylab # deferred so unittest are not dependent on it # plot curr spikes if len(curr_spikes) != 0: print("curr spikes are {}".format(curr_spikes)) pylab.figure() pylab.plot([i[1] for i in curr_spikes], [i[0] for i in curr_spikes], ".") pylab.xlabel('Time/ms') pylab.ylabel('spikes') pylab.title('lif curr spikes') pylab.show() else: print("No curr spikes received") # plot cond spikes if len(cond_spikes) != 0: print("cond spikes are {}".format(cond_spikes)) pylab.figure() pylab.plot([i[1] for i in cond_spikes], [i[0] for i in cond_spikes], ".") pylab.xlabel('Time/ms') pylab.ylabel('spikes') pylab.title('lif cond spikes') pylab.show() else: print("No cond spikes received") # plot izk spikes if len(izk_spikes) != 0: print("izk spikes are {}".format(izk_spikes)) pylab.figure() pylab.plot([i[1] for i in izk_spikes], [i[0] for i in izk_spikes], ".") pylab.xlabel('Time/ms') pylab.ylabel('spikes') pylab.title('izk curr spikes') pylab.show() else: print("No izk spikes received") # plot curr gsyn if len(curr_gsyn) != 0: ticks = len(curr_gsyn) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('gsyn') pylab.title('lif curr gsyn') for pos in range(0, nNeurons, 20): gsyn_for_neuron = curr_gsyn[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in gsyn_for_neuron]) pylab.show() else: print("no curr gsyn received") # plot cond gsyn if len(cond_gsyn) != 0: ticks = len(cond_gsyn) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('gsyn') pylab.title('lif cond gsyn') for pos in range(0, nNeurons, 20): gsyn_for_neuron = cond_gsyn[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in gsyn_for_neuron]) pylab.show() else: print("no cond gsyn received") # plot izk gsyn if len(izk_gsyn) != 0: ticks = len(izk_gsyn) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('gsyn') pylab.title('izk curr gsyn') for pos in range(0, nNeurons, 20): gsyn_for_neuron = izk_gsyn[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in gsyn_for_neuron]) pylab.show() else: print("no izk gsyn received") # plot curr membrane voltage if len(curr_v) != 0: ticks = len(curr_v) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('v') pylab.title('lif curr v') for pos in range(0, nNeurons, 20): v_for_neuron = curr_v[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in v_for_neuron]) pylab.show() else: print("No curr voltage received") # plot cond membrane voltage if len(cond_v) != 0: ticks = len(cond_v) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('v') pylab.title('lif cond v') for pos in range(0, nNeurons, 20): v_for_neuron = cond_v[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in v_for_neuron]) pylab.show() else: print("no cond membrane voltage is recieved") # plot izk membrane voltage if len(izk_v) != 0: ticks = len(izk_v) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('v') pylab.title('izk curr v') for pos in range(0, nNeurons, 20): v_for_neuron = izk_v[pos * ticks: (pos + 1) * ticks] pylab.plot([i[2] for i in v_for_neuron]) pylab.show() else: print("no izk membrane voltage is recieved")
spikes = None #v = populations[0].get_v(compatible_output=True) #gsyn = populations[0].get_gsyn(compatible_output=True) spikes = populations[0].getSpikes(compatible_output=True) if spikes is not None: print spikes pylab.figure() pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], ".") pylab.xlabel('Time/ms') #pylab.xticks([0, 500, 1000, 2000, 3000, 4000, 5000]) pylab.xticks([0, 10, 20, 30, 40, 50]) pylab.yticks([0, 5, 10, 15, 20]) pylab.ylabel('neuron id') pylab.title('spikes') pylab.show() else: print "No spikes received" # Make some graphs if v is not None: ticks = len(v) / nNeurons pylab.figure() pylab.xlabel('Time/ms') pylab.ylabel('v') pylab.title('v') for pos in range(0, nNeurons, 20): v_for_neuron = v[pos * ticks:(pos + 1) * ticks] pylab.plot([i[1] for i in v_for_neuron], [i[2] for i in v_for_neuron])
def runEulerNtimes(N, dt, title, InitialType, dest, picDest): count = 0 changeParamEntry("param.cfg","InitialType",InitialType) changeParamEntry("param.cfg","runTime",dt) changeParamEntry("time.cfg","t",0) time = readParamEntry("time.cfg", "t") strTime = str(time) runEuler() count = count+1 numString = str(count) #copyResults(dest+"iter"+numString) fig1=pylab.figure() fig1.subplots_adjust(left=.125, bottom=.1, right=.9, top=.9, wspace=.4, hspace=.3) pylab.suptitle(title + "at time " + strTime) pylab.subplot(2,2,1) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/InitialRho.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Density") pylab.subplot(2,2,2) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Initialvx.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Px") pylab.subplot(2,2,3) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Initialvy.cfg") pylab.title("Py") pylab.xlabel("x") pylab.ylabel("y") pylab.subplot(2,2,4) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Initialpre.cfg") pylab.title("Pressure") pylab.xlabel("x") pylab.ylabel("y") pylab.savefig(picDest+strTime+".png") time = readParamEntry("time.cfg", "t") strTime = str(time) fig2=pylab.figure() fig2.subplots_adjust(left=.125, bottom=.1, right=.9, top=.9, wspace=.4, hspace=.3) pylab.suptitle(title + "at time " + strTime) pylab.subplot(2,2,1) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/FinalRho.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Density") pylab.subplot(2,2,2) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalvx.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Px") pylab.subplot(2,2,3) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalvy.cfg") pylab.title("Py") pylab.xlabel("x") pylab.ylabel("y") pylab.subplot(2,2,4) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalpre.cfg") pylab.title("Pressure") pylab.xlabel("x") pylab.ylabel("y") pylab.savefig(picDest+strTime+".png") changeParamEntry("param.cfg","InitialType",0) for i in range(N): runEuler() count = count+1 numString = str(count) #copyResults(dest+"iter"+numString) time = readParamEntry("time.cfg", "t") strTime = str(time) fig3=pylab.figure() fig3.subplots_adjust(left=.125, bottom=.1, right=.9, top=.9, wspace=.4, hspace=.3) pylab.suptitle(title + "at time " + strTime) pylab.subplot(2,2,1) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/FinalRho.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Density") pylab.subplot(2,2,2) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalvx.cfg") pylab.xlabel("x") pylab.ylabel("y") pylab.title("Px") pylab.subplot(2,2,3) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalvy.cfg") pylab.title("Py") pylab.xlabel("x") pylab.ylabel("y") pylab.subplot(2,2,4) plotValue("run/Finalx.cfg","run/Finaly.cfg","run/Finalpre.cfg") pylab.title("Pressure") pylab.xlabel("x") pylab.ylabel("y") pylab.savefig(picDest+strTime+".png")
# Plots ima = dict(interpolation='nearest', origin='lower', cmap='gray', vmin=-2 * noisesigma, vmax=5 * noisesigma) imchi = dict(interpolation='nearest', origin='lower', cmap='gray', vmin=-5, vmax=5) plt.clf() plt.subplot(2, 2, 1) plt.imshow(trueimage, **ima) plt.title('True image') plt.subplot(2, 2, 2) plt.imshow(image, **ima) plt.title('Image') plt.subplot(2, 2, 3) plt.imshow(mod0, **ima) plt.title('Tractor model') plt.subplot(2, 2, 4) plt.imshow(chi0, **imchi) plt.title('Chi') plt.savefig('1.png') # Freeze all image calibration params -- just fit source params tractor.freezeParam('images') # Save derivatives for later plotting...
data = parseout(opt.FILE) dat = [] B2H = np.array( [float(j[0]) for j in data['LHC.BQBBQ.UA43.FFT1_B2:TUNE_H'][1]]) B1H = np.array( [float(j[0]) for j in data['LHC.BQBBQ.UA47.FFT1_B1:TUNE_H'][1]]) B2V = np.array( [float(j[0]) for j in data['LHC.BQBBQ.UA43.FFT1_B2:TUNE_V'][1]]) B1V = np.array( [float(j[0]) for j in data['LHC.BQBBQ.UA47.FFT1_B1:TUNE_V'][1]]) #-- beam 1 SG filter a = SGfilter(B1H, win=51, order=4) b = SGfilter(B1V, win=51, order=4) pylab.subplot(2, 2, 1) pylab.title('SG Filter (4th order)') pylab.plot(B1H) pylab.plot(a, linewidth=2, label='Beam 1') pylab.plot(B1V) pylab.plot(b, linewidth=2) pylab.legend(loc=3) pylab.ylim(0.3, 0.325) pylab.ylabel("Tune") #-- beam 1 kalman filter a = kalman(B1H, R=0.01, Q=2.0e-4) b = kalman(B1V, R=0.01, Q=2.0e-4) pylab.subplot(2, 2, 2) pylab.ylim(0.3, 0.35) pylab.title('Kalman Filter') pylab.plot(B1H)
S = S.T # Mixing Matrix A = np.array([[1, 0.5], [0.5, 1]]) # Mix Signals X = np.dot(A, S) mixed_signals = RealFeatures(X) # Separating jedi = JediSep() signals = jedi.apply(mixed_signals) S_ = signals.get_feature_matrix() A_ = jedi.get_mixing_matrix() print A_ # Plot results pl.figure() pl.subplot(3, 1, 1) pl.plot(S.T) pl.title('True Sources') pl.subplot(3, 1, 2) pl.plot(X.T) pl.title('Mixed Sources') pl.subplot(3, 1, 3) pl.plot(S_.T) pl.title('Estimated Sources') pl.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.36) pl.show()