def plot_Bn_slice(Bn_List, q95_array, Bn_Div_Li_array, coil1_abs_array, coil1_angle_array, ROTE_value, probe): fig = pt.figure() ax = fig.add_subplot(211) ax2 = fig.add_subplot(212) color_list = ['bo-','ko-','yo-'] color_list2 = ['bx-','kx-','yx-'] for iii in range(0,len(Bn_List)): Bn_Div_Li_value = Bn_List[iii] q95_range = num.arange(2.5,6.6,0.1) Bn_Div_Li = num.ones(len(q95_range),dtype=float)*Bn_Div_Li_value interp_abs_line = griddata(q95_array, Bn_Div_Li_array, coil1_abs_array, q95_range,Bn_Div_Li, interp = 'linear')[0] interp_angle_line = griddata(q95_array, Bn_Div_Li_array, coil1_angle_array, q95_range, Bn_Div_Li, interp = 'linear')[0] ax.plot(q95_range, interp_abs_line,color_list[iii],label='Bn/Li='+str(Bn_Div_Li_value)) ax2.plot(q95_range, interp_angle_line,color_list[iii],label='Bn/Li='+str(Bn_Div_Li_value)) leg = ax.legend(loc=2, fancybox = True) leg.get_frame().set_alpha(0.5) leg = ax2.legend(loc=4, fancybox = True) leg.get_frame().set_alpha(0.5) ax.grid() ax2.grid() ax2.set_ylim([0,360]) ax.set_xlim([2,7]) ax2.set_xlim([2,7]) ax2.set_xlabel('q95') ax.set_title(str(ROTE_value) + 'deg ' + probe[iii]) ax.set_ylabel('abs(output)') ax.set_ylabel('Magnitude (G/kA)') ax2.set_ylabel('Phase (deg)') fig.canvas.draw() fig.show()
def plot_2d(xs,ys,zs,ax,zmax=None,logscale=False,cb=True,zmin_avg=True,shrink=0.7) : if zmax == None : zmax = max(zs) minx,maxx = min(xs),max(xs) miny,maxy = min(ys),max(ys) xi = np.linspace(minx,maxx,360) yi = np.linspace(miny,maxy,360) if zmax == 100 or not logscale : zi = griddata(xs,ys,zs,xi,yi) else : Z = [] zmin = 1e9 for z in zs : try : Z.append(log10(z)) if log10(z) < zmin : zmin = int(np.floor(log10(z))) except ValueError : Z.append(-20) except : print "Unknown error trying to take the log of %s"%z sys.exit() zi = griddata(xs,ys,Z,xi,yi) myplot = ax.pcolorfast(xi,yi,zi,cmap='RdBu') x0,x1 = ax.get_xlim() y0,y1 = ax.get_ylim() aspect_Ratio = (x1-x0)/(y1-y0) ax.set_aspect(aspect_Ratio) ax.set_xlim(-180,175) ax.set_ylim(-180,175) ax.set_xticks(range(-120,121,60)) ax.set_yticks(range(-120,121,60)) if zmax == 100 and not logscale : myplot.set_clim([0,100]) if cb : cbar = plt.colorbar(myplot,shrink=shrink,format='%i',ticks=range(0,101,20)) cbar.ax.set_yticklabels(['0%','20%','40%','60%','80%','>100%']) return ax, cbar elif logscale : # Set the minimum value to the average magnitude if zmin_avg : zmin=int(np.floor(log10(np.average(zs))))-1 myplot.set_clim(zmin,-1) if cb : cbar = plt.colorbar(myplot,shrink=shrink,format='%i',ticks=range(zmin,0,1)) cblabels = [] for i in range(zmin,0,1) : if i == zmin : cblabels.append('<1E%i'%i) else : cblabels.append('1E%i'%i) cbar.ax.set_yticklabels(cblabels) return ax,cbar else : if cb : cbar = plt.colorbar(myplot,shrink=shrink,format='%1.E') return ax,cbar return ax
def interpolateImagePoints(self, points, edges): t_row, t_col = np.ogrid[0:self._image.shape[0], 0:self._image.shape[1]] # get values for xCoords = [x[0] for x in points] yCoords = [x[1] for x in points] xValues = [self.getXAt(*p) for p in points] yValues = [self.getYAt(*p) for p in points] zValues = [self.getZAt(*p) for p in points] # get edge points edgeIndices = [(points.index(e[0]), points.index(e[1])) for e in edges] for p1, p2 in edgeIndices: p1v = np.array(points[p1]) p2v = np.array(points[p2]) mag = p2v-p1v mag = int(np.sqrt(mag.dot(mag))) interpU = np.interp(range(mag), [0, mag-1], [p1v[0], p2v[0]]).astype(np.int).tolist() interpV = np.interp(range(mag), [0, mag-1], [p1v[1], p2v[1]]).astype(np.int).tolist() interpX = np.interp(range(mag), [0, mag-1], [xValues[p1], xValues[p2]]).tolist() interpY = np.interp(range(mag), [0, mag-1], [yValues[p1], yValues[p2]]).tolist() interpZ = np.interp(range(mag), [0, mag-1], [zValues[p1], zValues[p2]]).tolist() xCoords.extend(interpU) yCoords.extend(interpV) xValues.extend(interpX) yValues.extend(interpY) zValues.extend(interpZ) # interpolate points interpX = griddata(xCoords, yCoords, xValues, t_col.ravel(), t_row.ravel(), "linear") self._image_points[t_row, t_col, 0] = interpX interpY = griddata(xCoords, yCoords, yValues, t_col.ravel(), t_row.ravel(), "linear") self._image_points[t_row, t_col, 1] = interpY interpZ = griddata(xCoords, yCoords, zValues, t_col.ravel(), t_row.ravel(), "linear") self._image_points[t_row, t_col, 2] = interpZ
def pcolor( lon, lat, lonn, latn, mag, nv, m, ax, norm, cmap, topology_type, fig, height, width, lonmin, latmin, lonmax, latmax, dataset, continuous, projection, ): from matplotlib.mlab import griddata if topology_type.lower() == "cell": lon, lat = m(lon, lat) lonn, latn = m(lonn, latn) else: lon, lat = m(lonn, latn) lonn, latn = lon, lat num = int((lonmax - lonmin) * 320) xi = np.arange(m.xmin, m.xmax, num) yi = np.arange(m.ymin, m.ymax, num) if topology_type.lower() == "node": n = np.unique(nv) zi = griddata(lon[n], lat[n], mag[n], xi, yi, interp="nn") else: zi = griddata(lon, lat, mag, xi, yi, interp="nn") fig, m, patch1 = cookie_cutter(dataset, fig, m, lonmin, latmin, lonmax, latmax, projection, continuous) # Should we draw anything? if patch1 is not None: m.imshow(zi, norm=norm, cmap=cmap, clip_path=patch1, interpolation="nearest") # from matplotlib.backends.backend_agg import FigureCanvasAgg # canvas = FigureCanvasAgg(fig) # canvas.print_png("testing_yay.png") return fig, m
def return_grid_data(q95_values, Bn_Div_Li_values,q95_array, Bn_Div_Li_array, coil1_angle_array, coil1_abs_array, xnew=None,ynew=None, interpolation='linear',deg_min=0, points = [100,100]): if xnew==None: xnew = num.linspace(q95_values[0], q95_values[1], points[0]) ynew = num.linspace(Bn_Div_Li_values[0], Bn_Div_Li_values[1],points[1]) for i in range(0,len(coil1_angle_array)): while coil1_angle_array[i]<deg_min or coil1_angle_array[i]>(deg_min+360): if coil1_angle_array[i]<deg_min: coil1_angle_array[i] += 360. if coil1_angle_array[i]>(deg_min+360): coil1_angle_array[i] -= 360. B1grid_data = griddata(q95_array, Bn_Div_Li_array, coil1_abs_array, xnew, ynew, interp = interpolation) interp_data_angle = griddata(q95_array, Bn_Div_Li_array, coil1_angle_array, xnew, ynew, interp = interpolation) return B1grid_data, interp_data_angle
def plot_current_field(xs,ys,vx,vy): ###define grid x_grid = np.linspace(xs.min(),xs.max(),200) y_grid = np.linspace(ys.min(),ys.max(),200) vxs = griddata(xs, ys, vx, x_grid, y_grid, interp='linear') vys = griddata(xs, ys, vy, x_grid, y_grid, interp='linear') speed = np.sqrt(vxs**2+vys**2) lw = 5*speed / speed.max() plt.figure() plt.streamplot(x_grid, y_grid, vxs,vys, color=lw, linewidth=2, cmap=plt.cm.autumn) plt.colorbar() plt.show()
def griddata_all(x,y,z,x1,y1,func='line_rbf'): ''' 把各种插值方法整合到一起 scipy_idw line_rbf Invdisttree nat_grid ''' xi, yi = np.meshgrid(x1, y1) if('nearest'==func): zi= griddata_nearest(x,y,z,xi,yi) if('griddata'==func): from matplotlib.mlab import griddata zi = griddata(x,y,z,x1,y1) if('kriging'==func): zi= griddata_kriging(x,y,z,xi,yi) if('scipy_idw'==func): zi= griddata_scipy_idw(x,y,z,xi,yi) if('line_rbf'==func): zi = griddata_linear_rbf(x,y,z,xi,yi) # grid3 = grid3.reshape((ny, nx)) print(zi.shape,x.shape,y.shape,z.shape,xi.shape,yi.shape) #sys.exit(0) if('line_rbf2'==func): zi = griddata_linear_rbf2(x,y,z,xi,yi) # grid3 = grid3.reshape((ny, nx)) if('Invdisttree'==func): #zi = df.griddata_Invdisttree(x,y,z,xi,yi,Nnear=15,p=3,eps=1) print(x.shape,y.shape,z.shape,x1.shape,y1.shape) #sys.exit(0) zi = griddata_Invdisttree(x,y,z,xi,yi,p=3)#,Nnear=10,eps=1) if('nat_grid'==func): from griddata import griddata, __version__ zi = griddata(x,y,z,xi,yi) #if('test'==func): # zi = griddata_scipy_spatial(x,y,z,xi,yi) return zi,xi,yi
def gridxyz(xcol, ycol, zcol, xystep=None, lib='scipy', method='cubic'): """ grid (X, Y, Z) 1D data on a 2D regular mesh Parameters ---------- xcol, ycol, zcol : 1D arrays repesenting the map (z is the intensity) xystep : the step size of the XY grid lib : library used for griddata [scipy] matplotlib method : interpolation method Returns ------- xgrid, ygrid : 1D arrays giving abscissa and ordinate of the map zz : 2D array with the gridded intensity map See also -------- - MultipleScanToMeshPlugin in PyMca """ if xystep is None: xystep = 0.05 warnings.warn("'xystep' not given: using a default value of {0}".format(xystep)) #create the XY meshgrid and interpolate the Z on the grid xgrid = np.linspace(xcol.min(), xcol.max(), (xcol.max()-xcol.min())/xystep) ygrid = np.linspace(ycol.min(), ycol.max(), (ycol.max()-ycol.min())/xystep) xx, yy = np.meshgrid(xgrid, ygrid) if ('matplotlib' in lib.lower()): try: from matplotlib.mlab import griddata except ImportError: print("Error: cannot load griddata from Matplotlib") return if not (method == 'nn' or method == 'nearest'): warnings.warn("method {0} not supported by {1}".format(method, lib)) print("Gridding data with {0}...".format(lib)) zz = griddata(xcol, ycol, zcol, xx, yy) return xgrid, ygrid, zz elif ('scipy' in lib.lower()): try: from scipy.interpolate import griddata except ImportError: print("Error: cannot load griddata from Scipy") return print("Gridding data with {0}...".format(lib)) zz = griddata((xcol, ycol), zcol, (xgrid[None,:], ygrid[:,None]), method=method) return xgrid, ygrid, zz
def grid (self,lgrid,mgrid,freqgrid): from matplotlib.mlab import griddata l = numpy.sin(lgrid); m = numpy.sin(mgrid); gridshape = (len(l),len(m),len(self.freq)); beamgrid = numpy.zeros(gridshape,complex); # figure out useful range of l/m coordinates lmin,lmax = l.min(),l.max(); mmin,mmax = m.min(),m.max(); dl = (lmax - lmin)/10; dm = (mmax - mmin)/10; lmin,lmax = lmin-dl,lmax+dl; mmin,mmax = mmin-dm,mmax+dm; dprint(3,"regridding in area from %f,%f to %f,%f deg"%(lmin/DEG,mmin/DEG,lmax/DEG,mmax/DEG)); # loop over all per-frequency patterns for ifreq,(beam,beam_ampl,lcoord,mcoord,freq) in enumerate(self._beams): # filter out values outside the range select = (lcoord < lmax)&(lcoord > lmin)&(mcoord < mmax)&(mcoord > mmin); dprint(3,"selection reduces beam from %d to %d points"%(len(lcoord),select.sum())); # regrid onto each frequency plane for ifreq in range(len(self.freq)): gbeam = beamgrid[:,:,ifreq]; gbeam.real = griddata(lcoord[select],mcoord[select],beam.real[select],l,m); gbeam.imag = griddata(lcoord[select],mcoord[select],beam.imag[select],l,m); if beam_ampl is not None: ampl = griddata(lcoord[select],mcoord[select],beam_ampl[select],l,m); ampl1 = abs(gbeam); wh = ampl1 != 0; gbeam[wh] = (gbeam[wh]/ampl1[wh])*ampl[wh]; # replace nans with zeroes beamgrid[numpy.isnan(beamgrid)] = 0; # interpolate onto frequency grid dprint(4,"interpolated data range",beamgrid.min(),beamgrid.max()); dprint(3,"interpolating frequencies"); l1,m1 = numpy.meshgrid(numpy.arange(len(l)),numpy.arange(len(m))); if len(self.freq) > 1: f1 = interpolate.interp1d(self.freq,range(len(self.freq)),'linear')(freqgrid); else: f1 = numpy.array(0.); l1,f1 = unite_shapes(l1,f1); m1,f1 = unite_shapes(m1,f1); coords = numpy.vstack((l1.ravel(),m1.ravel(),f1.ravel())); output_shape = (len(l),len(m),len(freqgrid)); output = numpy.zeros(output_shape,complex); output.real = interpolation.map_coordinates(beamgrid.real,coords,order=self._spline_order).reshape(output_shape); output.imag = interpolation.map_coordinates(beamgrid.imag,coords,order=self._spline_order).reshape(output_shape); dprint(3,"done"); return output;
def compareVars(self,histories): #find x,y in histories nameX=histories['vars'][0] nameY=histories['vars'][1] pathX=histories['varPaths'][0] pathY=histories['varPaths'][1] xs=np.zeros(histories['nRun'][-1]+1) ys=np.zeros(histories['nRun'][-1]+1) for e,edict in enumerate(histories['varVals']): xs[e]=edict[pathX] ys[e]=edict[pathY] zs=np.array(histories['soln']) xi=np.linspace(np.min(xs),np.max(xs),100) yi=np.linspace(np.min(ys),np.max(ys),100) plt.figure() zi=mlab.griddata(xs,ys,zs,xi,yi) plt.contour(xi,yi,zi,15,linewidth=0.5,colors='k') plt.pcolormesh(xi,yi,zi,cmap=plt.get_cmap('rainbow')) plt.colorbar() plt.scatter(xs,ys,marker='o',c='b',s=1,zorder=10) plt.xlim(np.min(xs),np.max(xs)) plt.ylim(np.min(ys),np.max(ys)) plt.xlabel(nameX) plt.ylabel(nameY) plt.title('Total Runs: '+str(len(xs)))
def velocity_map(self, output='test'): """ Contours instantaneous velocity given by the analyser instance passed to the plotting class. """ self.figure = figure(figsize=(10,3)) self.axes = self.figure.gca() xWindowLim = (self.analyst.windowSize[0], self.analyst.windowSize[1]) yWindowLim = (self.analyst.windowSize[2], self.analyst.windowSize[3]) # Generate contours for velocity magnitude xGrid = linspace(\ xWindowLim[0]*self.millimetersPerPixel, xWindowLim[1]*self.millimetersPerPixel, self.nbins) yGrid = linspace(\ yWindowLim[0]*self.millimetersPerPixel, yWindowLim[1]*self.millimetersPerPixel, self.nbins) magVelGrid = griddata(self.xs, self.ys, self.magVel, xGrid, yGrid) # csf = self.axes.contourf(xGrid, yGrid, magVelGrid, range(2,26,2), cmap=myColorMap) csf = self.axes.contourf(xGrid, yGrid, magVelGrid, cmap=myColorMap) cbar = self.figure.colorbar(csf) cbar.set_label("Velocity magnitude, px/s") # Generate arrow plot # q = self.axes.quiver(self.xs, self.ys, self.us, self.vs, # angles = 'xy', scale_units='xy', scale=2, pivot = 'mid') # self.axes.quiverkey(q, 0.9, 1.0, 10, "10 px/frame", coordinates='axes') # Save figure self.axes.set_aspect('equal') self.axes.set_xlim(*xWindowLim) self.axes.set_ylim(*yWindowLim) self.figure.savefig(output + '_velocity_map.pdf')
def run(self): figure = plt.figure(frameon=False) axes = figure.add_axes([0, 0, 1, 1]) axes.set_axis_off() figure.patch.set_alpha(0) axes.axesPatch.set_alpha(0) x, y, z = unique_locations(self._telemetry) east = max(x) west = min(x) north = max(y) south = min(y) width = east - west height = north - south if len(x) > 2 and len(y) > 2 and width >= 10 and height >= 10: figure.set_size_inches((6, 6. * height / width)) xi = numpy.linspace(west, east, IMAGE_SIZE) yi = numpy.linspace(south, north, IMAGE_SIZE) with warnings.catch_warnings(): warnings.simplefilter("ignore") zi = mlab.griddata(x, y, z, xi=xi, yi=yi, interp=self._settings.interpolation) axes.pcolormesh(xi, yi, zi, cmap=self._settings.heatmapColour) plt.axis([west, east, south, north]) self.__save(figure) self._signal.plotted.emit((north, south, east, west))
def getSlice(self,data,axis,res=600): if axis==0: xi = np.linspace(min(self.y),max(self.y),res) yi = np.linspace(min(self.z),max(self.z),res) index = np.nonzero(abs(np.array(self.x)) < 1e-2) x = np.array(self.y)[index[0]] y = np.array(self.z)[index[0]] if axis==1: xi = np.linspace(min(self.z),max(self.z),res) yi = np.linspace(min(self.x),max(self.x),res) index = np.nonzero(abs(np.array(self.y)) < 1e-8) x = np.array(self.z)[index[0]] y = np.array(self.x)[index[0]] if axis==2: xi = np.linspace(min(self.x),max(self.x),res) yi = np.linspace(min(self.y),max(self.y),res) index = np.nonzero(abs(np.array(self.z)) < 1e-8) x = np.array(self.x)[index[0]] y = np.array(self.y)[index[0]] d = np.array(data)[index[0]] Z = griddata(x,y,d,xi,yi, interp='linear') X, Y = np.meshgrid(xi,yi) #idx = nonzero( pow(array(X),2)+pow(array(Y),2) < pow(self.innerRadius,2)) #Z[idx[0]]=0.0 return X,Y,Z
def _redraw( self ): self.figure.clear() self.figure.add_axes( [0.1, 0.1, 0.8, 0.8] ) figure = self.figure axes = figure.axes[0] axes.clear() if self.sorted_on == True: scalar_arr = self.scalar_arr_sorted else: scalar_arr = self.scalar_arr xi = linspace( min( self.data.cut_x ), max( self.data.cut_x ), 100 ) x = ( ones_like( scalar_arr ) * self.data.cut_x ).flatten() ny_row = scalar_arr.shape[0] dy = max( diff( self.data.cut_x ) ) yi = linspace( 0, ny_row * dy, ny_row ) y = ( ones_like( scalar_arr ).T * linspace( 0, ny_row * dy, ny_row ) ).T.flatten() z = scalar_arr.flatten() zi = griddata( x, y, z, xi, yi, interp = 'nn' ) # contour the gridded data, plotting dots at the nonuniform data points #axes.contour( xi, yi, zi, 20, linewidths = .5, colors = 'k' ) # plotting filled contour axes.contourf( xi, yi, zi, 200, cmap = my_cmap_lin ) # my_cmap_lin scat = axes.scatter( x, y, marker = 'o', c = z, s = 20, linewidths = 0, cmap = my_cmap_lin ) figure.colorbar( scat ) self.data_changed = True
def plot3(): """visualizing nonuniform 2d data""" max_iter = 64 xmin, xmax, ymin, ymax = -2.2, 0.8, -1.5, 1.5 # randomly samples the mandelbrot set sample_count = 2 ** 12 # array a and b hold the coordinates of the samples A = uniform(xmin, xmax, sample_count) B = uniform(ymin, ymax, sample_count) # c contains the value for each of these samples C = [iter_count(complex(a, b), max_iter) for a, b in zip(A, B)] # produce a 2d array of data # from the nonuniform samples N = 512 # array `x` and `y` define a regular grid X = np.linspace(xmin, xmax, N) Y = np.linspace(ymin, ymax, N) # array `z` is a 2d array # built by interpolating the nonuniform samples Z = griddata(A, B, C, X, Y, interp="linear") plt.scatter(A, B, color=(0.0, 0.0, 0.0, 0.5), s=0.5) plt.imshow(Z, cmap=cm.binary, interpolation="bicubic", extent=(xmin, xmax, ymin, ymax)) plt.show()
def interp_2d_xy(x,y,data,xi,yi): try: di = griddata(x.reshape(x.size),y.reshape(y.size),data.reshape(data.size),xi,yi) except TypeError: di = np.zeros(xi.size) if x.ndim ==2 and y.ndim ==2: x_vec = x[0,:] y_vec = y[:,0] elif x.ndim == 3 and y.ndim == 3: x_vec = x[0,0,:] y_vec = y[0,:,0] else: x_vec = x y_vec = y xl = np.nonzero(x_vec <= xi)[0][-1] xh = np.nonzero(xi <= x_vec)[0][0] yl = np.nonzero(y_vec <= yi)[0][-1] yh = np.nonzero(yi <= y_vec)[0][0] if not x_vec[xl] == x_vec[xh]: xd = (xi-x_vec[xh])/(x_vec[xl]-x_vec[xh]) else: xd = 1. if not y_vec[yl] == y_vec[yh]: yd = (yi-y_vec[yh])/(y_vec[yl]-y_vec[yh]) else: yd = 1. w0 = data[yl,xl]*(1-yd) + data[yh,xl]*yd w1 = data[yl,xh]*(1-yd) + data[yh,xh]*yd di = w0*(1-xd) + w1*xd return di
def printcontourn (name,outdir,surf,num): ''' FUNCTION FOR PRINTING A CONTOURN OUT OF A FILE CONTAINING X, Y AND POTENTIAL COLUMNS ''' x = np.loadtxt(outdir+name+"_"+surf+".txt", usecols=[0], skiprows=1) y = np.loadtxt(outdir+name+"_"+surf+".txt", usecols=[1], skiprows=1) z = np.loadtxt(outdir+name+"_"+surf+".txt", usecols=[2], skiprows=1) dimx=int(x[:1]) dimy=int(y[:1]) uniques=len(np.unique(x))-1 xi = np.linspace(dimx,-dimx,uniques) yi = np.linspace(dimy,-dimy,uniques*2) zi = griddata(x,y,z,xi,yi,interp='nn') #limits=[] #limits.append(int(min(z))) #limits.append(int(max(z))) plt.subplot(num) #normal=matcol.Normalize(vmin=min(limits),vmax=max(limits)) normal=matcol.Normalize(vmin=-80,vmax=80) cmap=plt.cm.RdBu CS1 = plt.contour(xi,yi,zi,20,linewidths=0.5,colors='k') CS2 = plt.contourf(xi,yi,zi,20,cmap=cmap,norm=normal) cb=plt.colorbar(drawedges='TRUE') #plt.scatter(x,y,marker='o',c='b',s=0.1,zorder=10) plt.xlim(dimx,-dimx) plt.ylim(dimy,-dimy) plt.title(surf, fontsize=11, fontweight='bold')
def window3(x,y,z): fig = plt.figure() ax = fig.gca(projection='3d') x = x y = y z = z xi = np.linspace(1, 19)# axis values go here yi = np.linspace(1, 19) N, Y = np.meshgrid(xi, yi) Z = griddata(x, y, z, xi, yi) surf = ax.plot_surface(N, Y, Z, rstride=3, cstride=3, cmap=cm.jet, linewidth=0, antialiased=True) ax.set_zlim3d(np.min(Z), np.max(Z)) fig.colorbar(surf) def getMarker(i): # Use modulus in order not to have the index exceeding the lenght of the list (markers) return "$"+'\gamma'+"$" plt.xlabel('N', fontsize=18) plt.ylabel('Y', fontsize=18) plt.title("Intersection Error figure. \n View from top for heatmap") plt.show()
def computeGrid(self): x, y, z = self._data self.gridSpacing = math.sqrt((max(x) - min(x)) * (max(y) - min(y)) / len(x)) / 2.0 gridSpacing = self.gridSpacing if gridSpacing <= 0.0: raise ContourError("Grid spacing must be greater than 0") # make grid x0 = math.floor(min(x) / gridSpacing) * gridSpacing nx = int(math.floor((max(x) - x0) / gridSpacing)) + 1 gx = np.linspace(x0, x0 + gridSpacing * nx, nx) y0 = math.floor(min(y) / gridSpacing) * gridSpacing ny = int(math.floor((max(y) - y0) / gridSpacing)) + 1 gy = np.linspace(y0, y0 + gridSpacing * ny, ny) try: # interpolate values on grid gz = griddata(x, y, z, gx, gy) except: raise ContourError("Unable to generate a grid for this data set") self._gridData = (gx, gy, gz)
def dual_plot(self, n): fig = plt.figure() ax1 = fig.add_subplot(121, axisbg='k') ax1.set_xlabel("Theta") ax1.set_ylabel("R") ax1.imshow(self.data, cmap=cm.hot,origin="lower", \ extent=[0,2*np.pi,self.rmin,self.rmax]) r = np.arange(self.rmin,self.rmax,(self.rmax-self.rmin)/self.nrad) t = np.arange(0.,2.*np.pi,2.*np.pi/self.nsec) x = np.ndarray([self.nrad*self.nsec], dtype = float) y = np.ndarray([self.nrad*self.nsec], dtype = float) z = np.ndarray([self.nrad*self.nsec], dtype = float) k = 0 for i in range(self.nrad): for j in range(self.nsec): x[k] = r[i]*np.cos(t[j]) y[k] = r[i]*np.sin(t[j]) z[k] = self.data[i,j] k +=1 xx = np.arange(-self.rmax, self.rmax, (self.rmax-self.rmin)/n) yy = np.arange(-self.rmax, self.rmax, (self.rmax-self.rmin)/n) zz = griddata(x,y,z,xx,yy) ax2 = fig.add_subplot(122, axisbg='k') ax2.set_xlabel("X") ax2.set_ylabel("Y") ax2.imshow(zz, cmap=cm.hot,origin="lower" \ , extent=[-self.rmax,self.rmax,-self.rmax,self.rmax]) plt.show()
def _fit_topology(self, figure, topography, topography_data, color_bar_min, color_bar_max): """ Trim data, to make sure everything is inside the head contour. """ x_arr = topography_data["x_arr"] y_arr = topography_data["y_arr"] circle_x = topography_data["circle_x"] circle_y = topography_data["circle_y"] rad = topography_data["rad"] topo = griddata(topography_data["sproj"][:, 0], topography_data["sproj"][:, 1], numpy.ravel(numpy.array(topography)), x_arr, y_arr) if self.plot_contours: #draw the contours figure.gca().contour(x_arr, y_arr, topo, 10, colors='k', origin="lower", hold='on') # mask values outside the head if self.masked: notinhead = numpy.greater_equal((x_arr - circle_x) ** 2 + (y_arr - circle_y) ** 2, (1.0 * rad) ** 2) topo = numpy.ma.masked_where(notinhead, topo) # show surface map_surf = figure.gca().imshow(topo, origin="lower", extent=(-rad, rad, -rad, rad)) if not (color_bar_min == 0 and color_bar_max == 0): norm = colors.Normalize(vmin=color_bar_min, vmax=color_bar_max) map_surf.set_norm(norm) figure.colorbar(map_surf) figure.gca().set_axis_off() return map_surf
def get_plot_points(self, datalist): x = [] y = [] z = [] for sx, sy, data in datalist: x.append(sx) y.append(sy) z.append(data) # print sx, sy, data x = np.array(x) y = np.array(y) z = np.array(z) assert x.ndim == y.ndim == z.ndim == 1 and len(x) == len(y) == len(z) # Define grid and interpolate the rest xi = np.linspace(0.0, float(self.dim[0]-1), self.dim[0]) yi = np.linspace(0.0, float((self.dim[1]-1)*-1), self.dim[1]) # print "Length of xi, yi:", len(xi), len(yi) zi = mlab.griddata(x, y, z, xi, yi) # print "Shape of zi:", zi.shape # nmask = np.ma.count_masked(zi) # if nmask > 0: #print("info: griddata: %d of %d points are masked, not interpolated" % # (nmask, zi.size)) return zi
def pcolorRandom(): "Makes a pcolormesh plot of randomly generated data pts." # make up some randomly distributed data npts = 100 x = uniform(-3, 3, npts) y = uniform(-3, 3, npts) z = x * N.exp(-x ** 2 - y ** 2) # define grid. xi = N.arange(-3.1, 3.1, 0.05) yi = N.arange(-3.1, 3.1, 0.05) # grid the data. zi = griddata(x, y, z, xi, yi) # contour the gridded data, plotting dots at the randomly spaced data points. plt.pcolormesh(xi, yi, zi) #CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k') #CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) plt.colorbar() # draw colorbar # plot data points. plt.scatter(x, y, marker='o', c='b', s=5) plt.xlim(-3, 3) plt.ylim(-3, 3) plt.title('griddata test (%d points)' % npts) plt.show()
def regularlyGrid(xarr, yarr, zarr, xstart=None, xfinal=None, xstep=None, ystart=None, yfinal=None, ystep=None): "Returns the regularly grided xi, yi, and zi arrays from the initial data." # if xstart,xfinal,xstep,ystart,yfinal,ystep are NOT given, they are derived from the data if xstart == None: xstart = xarr.min() if xfinal == None: xfinal = xarr.max() if xstep == None: xstep = 1.0 * (xfinal - xstart) / len(xarr) if ystart == None: ystart = yarr.min() if yfinal == None: yfinal = yarr.max() if ystep == None: ystep = 1.0 * (yfinal - ystart) / len(yarr) xi = N.arange(xstart, xfinal, xstep) yi = N.arange(ystart, yfinal, ystep) ''' Programming note: linspace does (start, final, how many steps) arange does (start, final, step) ''' # grid the data. print len(xarr), len(yarr), len(zarr), len(xi), len(yi) xarr,yarr,zarr=remove_duplicates(xarr,yarr,zarr) zi = griddata(xarr, yarr, zarr, xi, yi) print "done gridding" return xi, yi, zi
def plot_horizon(xyz_data, xyz_titles, az_lims, el_lims): """Calculate and plot horizon. Parameters ---------- xyz_data : tuple of (azimuth, elevation, power_db) data lists Data to plot. xyz_titles : tuple of titles for (azimuth, elevation and power_db) axes Titles for axes. az_lims : tuple of (min azimuth, max azimuth) Azimuth limits for the plot. el_lims : tuple of (min elevation, max elevation) Elevation limits for the plot. pow_lims : tuple of (min power, max power) Power limits for the plot. """ azimuth, elevation, power_db = xyz_data az_title, el_title, pow_title = xyz_titles az_min, az_max = az_lims el_min, el_max = el_lims #pow_min, pow_max = pow_lims az_pos = np.linspace(az_min, az_max, (az_max - az_min) / 0.1) el_pos = np.linspace(el_min, el_max, (el_max - el_min) / 0.1) power_db_pos = mlab.griddata(azimuth[:,0], elevation[:,0], power_db[:,0], az_pos, el_pos) plt.imshow(power_db_pos, aspect='auto', origin='lower') #cs = plt.contour(az_pos, el_pos, power_db_pos, pow_levels) #plt.contourf(az_pos,el_pos, power_db_pos, pow_levels, antialiased=True) plt.colorbar() if az_title: plt.xlabel(az_title) if el_title: plt.ylabel(el_title) if pow_title: plt.title(pow_title)
def gridplot(z, npoints=1024, phi=None, theta=None, cbar=True, earthpt=None, vmin=None, vmax=None, aspect='auto', rasterized=False): importmpl() if phi == None: import gbm (phi, theta) = gbm.respgrid() p = np.linspace(0, 2*np.pi, npoints) t = np.linspace(0, np.pi, int(npoints/2)) idx = np.nonzero(phi == 0) pwrap = phi[idx] + 2 * np.pi twrap = theta[idx] zwrap = z[idx] (pp, tt) = np.meshgrid(p, t) zgrid = mlab.griddata(np.hstack((phi, pwrap)), np.hstack((theta, twrap)), np.hstack((z, zwrap)), pp, tt, interp='linear') if earthpt != None: occlimit = np.cos(67 * np.pi/180.) eagrid = np.sum(pt2xyz((pp.ravel(), tt.ravel())).T * pt2xyz(earthpt), axis=1).reshape(pp.shape) zgrid[eagrid > occlimit] = 0 h = plt.imshow(zgrid, extent=(0, 2*np.pi, np.pi, 0), vmin=vmin, vmax=vmax, aspect=aspect, rasterized=rasterized) if cbar: plt.colorbar(orientation='horizontal', aspect=30, shrink=1.0) if earthpt != None: plt.contourf(pp, tt, eagrid, [occlimit, 1.0], colors='0.75', label='Earth extent') plt.plot(earthpt[0], earthpt[1], marker=r'$\oplus$', ls='none', label='Earth') # plt.subplots_adjust(top=0.875) return (h, plt.gca())
def grid(x, y, z, resX=100, resY=100): "Convert 3 column data to matplotlib grid" xi = np.linspace(min(x), max(x), resX) yi = np.linspace(min(y), max(y), resY) Z = griddata(x, y, z, xi, yi) X, Y = np.meshgrid(xi, yi) return X, Y, Z
def polar(self, n, file='None'): r = np.arange(self.rmin,self.rmax,(self.rmax-self.rmin)/self.nrad) t = np.arange(0.,2.*np.pi,2.*np.pi/self.nsec) x = np.ndarray([self.nrad*self.nsec], dtype = float) y = np.ndarray([self.nrad*self.nsec], dtype = float) z = np.ndarray([self.nrad*self.nsec], dtype = float) k = 0 for i in range(self.nrad): for j in range(self.nsec): x[k] = r[i]*np.cos(t[j]) y[k] = r[i]*np.sin(t[j]) z[k] = self.data[i,j] k +=1 xx = np.arange(-self.rmax, self.rmax, (self.rmax-self.rmin)/n) yy = np.arange(-self.rmax, self.rmax, (self.rmax-self.rmin)/n) zz = griddata(x,y,z,xx,yy) fig_pol = plt.figure() ax1 = fig_pol.add_subplot(111, axisbg='k') ax1.set_xlabel("X") ax1.set_ylabel("Y") if(self.zmax!='None' and self.zmin!='None'): ax1.imshow(zz, cmap=cm.hot, origin="lower", \ extent=[-self.rmax,self.rmax, \ -self.rmax,self.rmax]) else: ax1.imshow(zz, cmap=cm.hot, origin="lower", \ extent=[-self.rmax,self.rmax, \ -self.rmax,self.rmax]) if(file!="None"): plt.savefig(file+".png",dpi=70, format="png" ) print file+".png done" else: plt.show()
def mapplot(xpos,ypos,z,nsteps=50): #ncontours=15 xmin,xmax=xpos.min(),xpos.max() ymin,ymax=ypos.min(),ypos.max() xi=numpy.linspace(xmin,xmax,nsteps) yi=numpy.linspace(ymin,ymax,nsteps) nplots=z.shape[0] nrows,ncols=nrows_ncols_from_nplots(nplots) # Default 'nn' interpolation of griddata requires package mpl_toolkits.natgrid, currently py2 only try: import mpl_toolkits.natgrid interpolation = 'nn' except ImportError: interpolation = 'linear' for thisplot in range(0,nplots): # cf. http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data zi=mlab.griddata(xpos,ypos,z[thisplot],xi,yi,interp=interpolation) # Don't mess with arranging plots on a page if we only have a single plot... if nplots>1: plt.subplot(nrows,ncols,thisplot+1) # pcolormesh is described to be much faster than pcolor # Note that the default for edgecolors appears to be 'None' resulting in transparent lines between faces... gplot=plt.pcolormesh(xi,yi,zi,norm=plt.Normalize(vmin=vmin,vmax=vmax),shading='flat',edgecolors='face',antialiaseds=False) #gplot=plt.contourf(g,ncontours) #plt.scatter(xpos,ypos,marker='o',c='black',s=5) # Draw sample points if isolines: plt.contour(xi,yi,zi,isolines,colors='black',linestyles='solid') gplot.axes.set_axis_off() gplot.axes.set_xlim(xmin,xmax) gplot.axes.set_ylim(ymin,ymax)
def ribbon3(spectra, alpha): matplotlib.rcParams.update({'font.size':10}) fig=figure() ax=fig.gca(projection='3d') for i in range(0,spectra.shape[1]): y=spectra[:,i] x=sorted(range(1,len(y)+1)*2) a=[i,i+1]*len(y) b=list(itertools.chain(*zip(y,y))) xi=np.linspace(min(x),max(x)) yi=np.linspace(min(a),max(a)) X,Y=np.meshgrid(xi/(len(x)*0.5),yi) Z=griddata(x,a,b,xi,yi) ax.plot_surface(X,Y,Z, rstride=50, cstride=1, cmap='Spectral') ax.set_zlim3d(np.min(Z),np.max(Z)) ax.grid(False) ax.w_xaxis.pane.set_visible(False) ax.w_yaxis.pane.set_visible(False) ax.w_zaxis.pane.set_color('gainsboro') ax.set_title('Pyramid Gradient MFS') ax.set_xlim3d(0,1) ax.set_xticks(alpha) ax.set_xticklabels(alpha) ax.set_xlabel(r'$\alpha$') #ax.set_yticks([0.5,1.5,2.5,3.5,4.5]) #ax.set_yticklabels(['1','2','3','4','5']) ax.set_ylabel('Resolution') ax.set_zlim3d(0,3) ax.set_zlabel(r'$f(\alpha)$') show()
# CREATE ASCE MAP # mymap = plt.tricontour(lon_asce,lat_asce, asce_705_mph, 10) # Make an artificial, regular grid, to be used later during interpolation. numcols, numrows = 30, 30 lon1Dinterp = np.linspace(min(lon_asce), max(lon_asce), numcols) lat1Dinterp = np.linspace(min(lat_asce), max(lat_asce), numrows) lon2Dinterp, lat2Dinterp = np.meshgrid(lon1Dinterp, lat1Dinterp) #print(lon2Dinterp) #-- Interpolate at the points in xi, yi # "griddata" expects "raw" numpy arrays, and it will output Z_2Dinterp.data and Z_2Dinterp.mask Z_2Dinterp = griddata( lon_asce, lat_asce, asce_705_mph, lon2Dinterp, lat2Dinterp, interp='linear' ) # Interpolate; there's also method='cubic' for 2-D data such as here #print (Z_2Dinterp) # PROJECT THE ASCE MAP ON THE BASEMAP X_2D, Y_2D = map(lon2Dinterp * 180. / np.pi, lat2Dinterp * 180. / np.pi) cs = map.contour(X_2D, Y_2D, Z_2Dinterp.data, 15, linewidths=1.5) ''' lon2D_asce, lat2D_asce = np.meshgrid(lon_asce,lat_asce) # Set up a regular 2D grid for use in contour asce2D_705_mph = griddata(lon_asce, lat_asce, asce_705_mph, lon2D_asce, lat2D_asce, interp='linear') # Interpolate; there's also method='cubic' for 2-D data such as here #asce2D_705_mph = scipy.interpolate.griddata((lon_asce, lat_asce), asce_705_mph, (lon2D_asce, lat2D_asce), method='linear') # Interpolate; there's also method='cubic' for 2-D data such as here # THE FOLLOWING LINE IS GIVING AN ERROR! map.contour(lon2D_asce, lat2D_asce, asce2D_705_mph) # Recall that contour uses 2D matrices for X and Y. If instead 1D vectors are used for X and Y ==> IndexError: too many indices for array ''' #plt.title('contour lines over filled continent background')
for i in range(Nx+1): nw1.append(n[i,j,Nt]) print len(wx) print len(wy) print len(nw1) quit() '''FIGURE''' import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from matplotlib.mlab import griddata xx = np.arange(0, (X+dx), dx) yy = np.arange(0, (Y+dy), dy) xx, yy = np.meshgrid(xx, yy) ZZ = griddata(wx, wy, nw, xx, yy) ZZsol = griddata(wx, wy, nw1, xx, yy) from mpl_toolkits.mplot3d import Axes3D fig1 = plt.figure() ax = plt.axes(projection='3d') ax.plot_surface(xx, yy, ZZ, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) plt.show() fig1 = plt.figure() ax = plt.axes(projection='3d') ax.plot_surface(xx, yy, ZZsol, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) plt.show()
# # a.set_title(titles[i], fontsize=12) # # a.grid(False) # # for a in ax.flat: # a.set_xlim([2.6, 3.1]) # a.set_ylim([ymin, ymax]) # a.set_axisbelow(False) # a.axes.set_axisbelow("True") levels = [0.1, 0.1, 0.1] label_levels = [1, 1, 1] Z = knn.predict_proba(data_fake)[:, 0] xi = np.linspace(xmin, xmax, 100) yi = np.linspace(ymin, ymax, 100) zi = ml.griddata(den_fake, mag_fake, Z, xi, yi, interp='linear') cf = ax[1, li].contourf(xi, yi, zi, np.arange(0.0, 1.01, .01), cmap='Blues', alpha=0.3) cs = ax[1, li].contour(xi, yi, zi, np.arange(0.0, 1.1, levels[li]), cmap='Greys', linestyles='-', linewidths=1, alpha=1) ax[1, li].clabel(cs,
linewidth=0.5) m.drawmeridians(arange(0., 360., xlabel), labels=[0, 0, 0, 1], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) # first make regular cartesian grid print 'Resampling data...' N = 500j extent = (minlon - mbuff_l, maxlon + mbuff_r, minlat - mbuff_r, maxlat + 0) xs, ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N] #resampled = griddata(lonlist, latlist, log10(hazvals), xs, ys, interp='linear') resampled = griddata(lonlist, latlist, hazvals, xs, ys, interp='linear') #resampled = griddata(lonlist, latlist, log10(hazvals), lonlist, latlist, interp='linear') # if this suddenly works, I have no idea why! # get 1D lats and lons for map transform lons = ogrid[extent[0]:extent[1]:N] lats = ogrid[extent[2]:extent[3]:N] # transform to map projection nx = int((m.xmax - m.xmin) / 3000.) + 1 ny = int((m.ymax - m.ymin) / 3000.) + 1 # differences in the way different machines deal with grids - weird! if cwd.startswith('/nas'): transhaz = m.transform_scalar(resampled.T, lons, lats, nx, ny) else: transhaz = m.transform_scalar(resampled.T, lons, lats, nx, ny)
x = data[:, 0] y = data[:, 1] z = data[:, 2] # Substracting the -2LogL minimum to form Delta(-2LogL) z2 = [] for z_el in z: z2.append(z_el - z.min()) # Interpolating the grid xi = np.linspace(x.min(), x.max(), grid_subdivisions) yi = np.linspace(y.min(), y.max(), grid_subdivisions) X, Y = np.meshgrid(xi, yi) Z = griddata(x, y, z2, xi, yi, interp="linear") # Plotting the 68%, 95% and 99.7% CL contours ax.contour(xi, yi, Z, [2.3, 5.99, 11.83], linewidths=[2.5, 2.5, 2.5], colors=["#B22222", "#FF8C00", "#FFD700"]) cax=ax.imshow(Z, vmin=0, vmax=15, origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], \ aspect=(theta_max-theta_min)/(m2_max-m2_min), cmap=plt.get_cmap("jet_r")) # Title, labels, color bar... plt.text(1.3 * pi / 8., 185, r"$m_{\widetilde{\tau}_1}=" + str(m1_fixed) + "$" r"$\rm{\ GeV}$, $\tan\beta=" + str(tb) + "$",
def contour_array(model, xname, yname, znames, cellsize=(5, 5), nrows=None, ncols=None, xticks=None, yticks=None, colors=None): # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # pylint: disable=too-many-statements """Arrar of contour plots for variables in a solved model Arguments --------- model: gpkit.Model xname, yname: strings znames: list of strings """ data = model.solution["variables"] n = len(znames) if nrows is None: nrows = (n + 1) / 2 if ncols is None: ncols = 2 if n >= 2 else 1 figsize = (cellsize[0] * ncols, cellsize[1] * nrows) x_sweep = model.substitutions[model[str(xname)].key][1] y_sweep = model.substitutions[model[str(yname)].key][1] if xticks is None: xticks = x_sweep if yticks is None: yticks = y_sweep def get_label(var): "Default axis label for var" var, = model.varkeys[var] label = var.name if "idx" in var.descr: idx = var.descr.pop("idx", None) var = VarKey(**var.descr) label += "_%s" % idx vals = data[var][:, idx] else: vals = data[var] if var.units: label += unitstr(var.units, " [%s] ") if "label" in var.descr: label += " %s" % var.descr["label"] return label, mag(vals) xlabel, x_sol = get_label(xname) ylabel, y_sol = get_label(yname) Z_lgs = [get_label(Z) for Z in znames] if colors is None: colors = LIGHT_COLORS[0], DARK_COLORS[0] fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True, sharey=True) if nrows > 1 and ncols > 1: xlabeledaxes = axes[-1, :] ylabeledaxes = axes[:, 0] elif ncols > 1: xlabeledaxes = axes ylabeledaxes = [axes[0]] else: xlabeledaxes = [axes[-1]] ylabeledaxes = axes for ax in xlabeledaxes: ax.set_xlabel(xlabel, color=NEUTRAL_DARK) ax.set_xlim((x_sol.min(), x_sol.max())) if isinstance(xticks, type(None)): ax.set_xticks(xticks, minor=True) m = len(xticks) major_xticks = [ xticks[i] for i in (0, 1 * m / 4, 2 * m / 4, 3 * m / 4, m - 1) ] major_ticklabels = ["%.3g" % x for x in major_xticks] ax.set_xticks(major_xticks) ax.set_xticklabels(major_ticklabels) for ax in ylabeledaxes: ax.set_ylabel(ylabel, color=NEUTRAL_DARK) ax.set_ylim((y_sol.min(), y_sol.max())) if isinstance(yticks, type(None)): ax.set_yticks(yticks, minor=True) m = len(yticks) major_yticks = [ yticks[i] for i in (0, 1 * m / 4, 2 * m / 4, 3 * m / 4, m - 1) ] major_ticklabels = ["%.3g" % y for y in major_yticks] ax.set_yticks(major_yticks) ax.set_yticklabels(major_ticklabels) fig.tight_layout(h_pad=3) for i, Z_lg in enumerate(Z_lgs): zlabel, z_sol = Z_lg row_idx = i / ncols # 0, 0, 1, 1, 2, 2 for ncols = 2 col_vector = axes[row_idx, :] if nrows > 1 else axes ax = (col_vector[(i - row_idx * ncols) % ncols] if ncols > 1 else col_vector[0]) lablevels = [np.percentile(z_sol, 100 * i / 7.0) for i in range(8)] shortlevels = [(lablevels[4] - lablevels[3]) / 6.0 * j + lablevels[3] for j in range(-32, 33)] Zgrid = griddata(x_sol, y_sol, z_sol, x_sweep, y_sweep, interp='linear') contour_plot(ax, x_sweep, y_sweep, Zgrid, zlabel, colors, shortlevels, lablevels) return fig, axes
lon.append(estacao.lon) lat.append(estacao.lat) lonfull.append(estacao.lon) latfull.append(estacao.lat) temp = np.array(temp) lon = np.array(lon) lat = np.array(lat) xg = np.linspace(lon.min(), lon.max(), 100) yg = np.linspace(lat.min(), lat.max(), 80) xg, yg = np.meshgrid(xg, yg) tg = griddata(lon, lat, temp, xg, yg) m = Basemap(projection='cyl', resolution='i', llcrnrlat=-30.6, llcrnrlon=-49.51, urcrnrlat=-18.16, urcrnrlon=-27.03) m.fillcontinents() # m.plot(lonfull, latfull, 'bo') m.contourf(xg, yg, tg, 40) cbar = plt.colorbar() cbar.set_label('$^\circ C$') plt.scatter(lon, lat, s=30, c=temp) plt.savefig("temp_media_primeiros_%sm.png" % (-prof))
def refine(lon, lat, sst, lims, res=0.02): xg = np.arange(lims[0]-1, lims[1]+1, res) yg = np.arange(lims[2]-1, lims[3]+1, res) xg, yg = np.meshgrid(xg, yg) sst = griddata(lon.ravel(), lat.ravel(), sst.ravel(), xg, yg) return xg, yg, sst
l_max = 0.15 m_min = -0.15 m_max = 0.15 numxout = num_grid_elements numyout = numxout xc = (l_max - l_min) / (numxout - 1) yc = (m_max - m_min) / (numyout - 1) print 'pixel seps ', xc, yc xo = -0.15 + xc * numpy.arange(0, numxout) yo = -0.15 + yc * numpy.arange(0, numxout) print 'gridding ...' result_real_co = griddata(l, m, real_data_co, xo, yo) result_imag_co = griddata(l, m, imag_data_co, xo, yo) result_real_cx = griddata(l, m, real_data_cx, xo, yo) result_imag_cx = griddata(l, m, imag_data_cx, xo, yo) result_theta = griddata(l, m, ampl_theta, xo, yo) result_phi = griddata(l, m, ampl_phi, xo, yo) # result_theta,result_phi,result_real_co,result_imag_co,result_real_cx,result_imag_cx,xc,l,m,xo,yo,poln print 'plotting ...' # plt.subplot(121) fig = plt.figure(1) # ax = plt.subplot(121) ax = Axes3D(fig) # contour the gridded data, plotting dots at the nonuniform data points. if poln:
minKE = min(branchesPts[:, 2]) maxKE = max(branchesPts[:, 2]) minRePt = branchesPts[0, :] x = branchesPts[:, 1] y = branchesPts[:, 2] z = branchesPts[:, 0] # define grid. fig = plt.figure() xi = np.linspace(minkx - 0.01, maxkx + 0.01, 500) yi = np.linspace(minKE - 0.01, maxKE + 0.01, 500) # grid the data. zi = griddata(x, y, z, xi, yi, interp='linear') # contour the gridded data, plotting dots at the nonuniform data points. #CS = plt.contour(xi,yi,zi) # Move numbers to an array (now that it is gridded) and plot using imshow print type(xi), type(yi), type(zi) print shape(xi), shape(yi), shape(zi) imArr = zeros((len(xi), len(yi)), dtype='d') for xIndx in range(len(xi)): for yIndx in range(len(yi)): imArr[xIndx, yIndx] = zi[xIndx, yIndx] ax1 = fig.add_subplot(111) ax1.set_ylim([0.4, 1])
# buffering velocity arrays: li, lj = lon.shape lk = np.size(z) u = np.zeros([lk, li, lj]) v = u.copy() temp = u.copy() salt = u.copy() # interpolating FM to new grid print ' ' print '======== GRIDDING NBUC-FM ========' print ' ' for k in range(0, lk - 1): print ' U: Z Level = ' + str(-1 * z[k]) + ' m' u[k, ...] = griddata(X.ravel(), Y.ravel(), U[z[k], ...].ravel(), lon, lat) print ' V: = ' v[k, ...] = griddata(X.ravel(), Y.ravel(), V[z[k], ...].ravel(), lon, lat) print ' TEMP: = ' temp[k, ...] = griddata(X.ravel(), Y.ravel(), TEMP[z[k], ...].ravel(), lon, lat) print ' SALT: = ' salt[k, ...] = griddata(X.ravel(), Y.ravel(), SALT[z[k], ...].ravel(), lon, lat) print ' ' print ' ' # removing nans u[np.isnan(u)] = 0 v[np.isnan(v)] = 0 for k in range(0, lk - 1):
ideal_states = np.arange(31.875, 0, -cc_lsb_db) i_word = [ cc_all_sign_i * cc_all_i for cc_all_sign_i, cc_all_i, cc_all_sign_q, cc_all_q in cc_all.keys() ] q_word = [ cc_all_sign_q * cc_all_q for cc_all_sign_i, cc_all_i, cc_all_sign_q, cc_all_q in cc_all.keys() ] z = [error for error in cc_all.values()] resX = 100 resY = 100 xi = np.linspace(min(i_word), max(i_word), resX) yi = np.linspace(min(q_word), max(q_word), resY) X, Y = np.meshgrid(xi, yi) Z = griddata(i_word, q_word, z, xi, yi, interp='linear') fig = plt.figure() fig.set_size_inches(17, 13) plt.interactive(False) ax = fig.gca(projection='3d') surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, rstride=1, cstride=1) fig.colorbar(surf, shrink=0.5, aspect=5) plt.xlabel('I Word (dB)') plt.ylabel('Q Word (dB)')
from numpy.random import uniform, seed from matplotlib.mlab import griddata import matplotlib.pyplot as plt import numpy as np # make up data. #npts = int(raw_input('enter # of random points to plot:')) seed(-1) npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) z = x*np.exp(-x**2-y**2) # define grid. xi = np.linspace(-2.1,2.1,100) yi = np.linspace(-2.1,2.1,100) # grid the data. zi = griddata(x,y,z,xi,yi) # contour the gridded data, plotting dots at the nonuniform data points. CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k') CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) plt.colorbar() # draw colorbar # plot data points. plt.scatter(x,y,marker='o',c='b',s=5) plt.xlim(-2,2) plt.ylim(-2,2) plt.title('griddata test (%d points)' % npts) plt.show() # test case that scikits.delaunay fails on, but natgrid passes.. #data = np.array([[-1, -1], [-1, 0], [-1, 1], # [ 0, -1], [ 0, 0], [ 0, 1], # [ 1, -1 - np.finfo(np.float_).eps], [ 1, 0], [ 1, 1],
def plotProfDist_in_BoundingBox(df, boundingBox=[], var='CTEMP', wd=7.48, ht=5, varmin=-2, varmax=5, levs=[], show=True, plotEcho=False, xlat=False, colorunit='$\\theta^{\circ}$C ', save=False, savename="Untitled.png", fontsize=8, levels=[], zmin=0.0, ticks=[], cline=[], legend_show=True, plotTimeHist=False): matplotlib.rcParams.update({'font.size': fontsize}) plt.close(1) fig = plt.figure(1, figsize=(wd, ht)) gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05]) ax = plt.subplot(gs[0, 0]) if not boundingBox: raise ValueError( 'provide arg boundingBox in fmt [[llcornerx, llcornery], [urcrnrx, urcrnry]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.' ) try: leftlonlim = boundingBox[0][0] rightlonlim = boundingBox[1][0] lowerlatlim = boundingBox[0][1] upperlatlim = boundingBox[1][1] except: raise ValueError( 'provide arg boundingBox in fmt [[x1,y1], [x2, y2], [x3, y3], [x4, y4]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.' ) selectProfiles = (df.LATITUDE >= lowerlatlim) & ( df.LATITUDE <= upperlatlim) & (df.LONGITUDE >= leftlonlim) & ( df.LONGITUDE <= rightlonlim) & (~df.CTEMP.isnull()) if xlat: dist = df.loc[selectProfiles, 'LATITUDE'] else: dist = df.loc[selectProfiles, 'DIST_GLINE'] depth = df.loc[selectProfiles, 'DEPTH'] gamman = df.loc[selectProfiles, 'gamman'] if xlat: ndist = int((np.max(dist) - np.min(dist)) / 0.01) else: ndist = int(df.loc[selectProfiles, 'DIST_GLINE'].max() / 10.) dist_grid = np.linspace(np.min(dist), np.max(dist), ndist) ndepth = int(np.abs(df.loc[selectProfiles, 'DEPTH'].min()) / 10.) depth_grid = np.linspace(df.loc[selectProfiles, 'DEPTH'].min(), 0, ndepth) gamman_interpolated = mlab.griddata(dist, depth, gamman, dist_grid, depth_grid, interp='linear') cs = ax.scatter(dist, df.loc[selectProfiles, 'DEPTH'], c=df.loc[selectProfiles, 'CTEMP']) if levels: cs_gamman = ax.contour(dist_grid, depth_grid, gamman_interpolated, levels, colors='0.5') else: cs_gamman = ax.contour(dist_grid, depth_grid, gamman_interpolated, colors='0.5') distSortedIndices = np.argsort(df.loc[selectProfiles, 'DIST_GLINE']) if plotEcho: depthMin = df.loc[selectProfiles].groupby( pd.cut(df.loc[selectProfiles].DIST_GLINE, dist_grid))[["DEPTH"]].min(axis=1).values echodepthMin = df.loc[selectProfiles].groupby( pd.cut(df.loc[selectProfiles].DIST_GLINE, dist_grid))[["ECHODEPTH"]].min(axis=1).values min_of_depth_echodepth = np.array(list(zip(depthMin, echodepthMin))).min(axis=1) ax.plot(dist_grid[:-1], min_of_depth_echodepth, linewidth=4, color='k') #ax.set_xlim(df.loc[selectProfiles, 'DIST_GLINE'].min()-1, df.loc[selectProfiles, 'DIST_GLINE'].max()+1) if not cline: cline = np.arange(27.8, 28.5, 0.1) ax.clabel(cs_gamman, colors='k', fontsize=14, fmt='%3.2f') colorax = plt.subplot(gs[1, 0]) cbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal') cbar1.ax.get_children()[0].set_linewidths(5) cbar1.set_label(colorunit) if plotTimeHist: plt.close(2) fig = plt.figure(2, figsize=(wd, ht)) uniqueProfs = df.loc[selectProfiles].groupby("PROFILE_NUMBER").head( 1).index df.loc[uniqueProfs, "JULD"].hist() plt.show() if save: plt.savefig(savename, dpi=300) if show: plt.show()
xcoords.append(x) ycoords.append(y) #zcoords.append(z) hbonds.append(hb) plt.figure() xlist = xcoords ylist = ycoords #np.linspace(-2., 1., 100) #zlist = zcoords #np.linspace(-1., 1., 100) hblist = hbonds xi = np.linspace(0., 12, 100) yi = np.linspace(0., 12, 100) hbi = griddata (xlist, ylist, hblist, xi, yi) CS = plt.contour(xi,yi,hbi,15,linewidths=0.5,colors='k') CS = plt.contourf(xi,yi,hbi,15,cmap=plt.cm.rainbow) plt.colorbar() plt.title('Number of hydrogen bonds per molecule wrt x and y axis') plt.xlabel('x-axis [Angstroms]') plt.ylabel('y-axis [Angstroms]') #plt.clabel(CS, inline=1, fontsize=10) plt.show()
def planarfit(indirpf, rawfile, outfile, pfmat='pfitmatrix.csv', pf0file='pfitdata0.csv', pf1file='pfitdata1.csv', pf2file='pfitdata2.csv', histsteps=50, plot=False): ''' Extracts raw wind speeds from the raw flux file of EddyFlux as input for EDDYPFit. When EDDYFit is finished, the script loads the results and do plots. If user is satisfied, results are saved. Definition ---------- planarfit(indirpf, rawfile, outfile, pfmat='pfitmatrix.csv', pf0file='pfitdata0.csv', pf1file='pfitdata1.csv', pf2file='pfitdata2.csv', histsteps=50): Input ----- indirpf str, path of the folder where results will be saved rawfile str, path of the file with raw wind speeds from EddyFlux outfile str, name of the output file Optional Input -------------- pfmat str, name of the pfitmatix file, default: 'pfitmatrix.csv' pf0file str, name of the original wind speed file of EDDYPFit, default: 'pfitdata0.csv' pf1file str, name of the one plane fit wind speed file of EDDYPFit, default: 'pfitdata1.csv' pf2file str, name of the sectorial fit wind speed file of EDDYPFit, default: 'pfitdata2.csv' histstep int, histogram steps for plotting (default=50) Output ------ X_pfit.pdf plot with planar fit X_uvw.csv file with raw wind speeds X_wd.pdf plot with wind rose X_wdis.pdf plot with wind speed distributions License ------- This file is part of the JAMS Python package, distributed under the MIT License. The JAMS Python package originates from the former UFZ Python library, Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany. Copyright (c) 2014 Arndt Piayda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. History ------- Written, AP, Aug 2014 ''' ############################################################################ # reading raw file uvw = np.array(fread('%s' %rawfile, skip=1, cskip=13, nc=3)) wdhor = np.array(fread('%s' %rawfile, skip=1, cskip=20, nc=1)) header = np.array(sread('%s' %rawfile, cskip=13, nc=3), dtype='|S5') ############################################################################ # coordinate transformation for u+v alpha = 120.*np.pi/180. #rotation angle in rad uvw_trans = np.copy(uvw) uvw_trans[:,0] = np.where((uvw[:,0]!=-9999) & (uvw[:,1]!=-9999), uvw[:,0]*np.cos(alpha)+uvw[:,1]*np.sin(alpha), -9999)# u uvw_trans[:,1] = np.where((uvw[:,0]!=-9999) & (uvw[:,1]!=-9999), -uvw[:,0]*np.sin(alpha)+uvw[:,1]*np.cos(alpha), -9999)# v ############################################################################ # writing uvw file with wind speed for EDDYPFit file1 = open('%s/%s_uvw.csv' %(indirpf,outfile[:-4]), 'w') output = csv.writer(file1) output.writerow(header[0]) for i in xrange(np.shape(uvw_trans)[0]): output.writerow(uvw_trans[i]) file1.close() ############################################################################ # user input to continue print("Do EddyPFit with the 'uvw.csv' file now!") ui1 = raw_input("Ready or quit (y/n)?: ").lower() if ui1 != "y": sys.exit() ############################################################################ # reading pfit files header0 = np.array(sread('%s/%s' %(indirpf,pf0file)) , dtype='|S1') uvw0 = np.array(fread('%s/%s' %(indirpf,pf0file), skip=1), dtype=np.float) uvw0_trans = np.copy(uvw0) uvw0_trans[:,0] = uvw0[:,0]*np.cos(alpha) - uvw0[:,1]*np.sin(alpha) uvw0_trans[:,1] = uvw0[:,0]*np.sin(alpha) + uvw0[:,1]*np.cos(alpha) header1 = np.array(sread('%s/%s' %(indirpf,pf1file)) , dtype='|S1') uvw1 = np.array(fread('%s/%s' %(indirpf,pf1file), skip=1), dtype=np.float) uvw1_trans = np.copy(uvw1) uvw1_trans[:,0] = uvw1[:,0]*np.cos(alpha) - uvw1[:,1]*np.sin(alpha) uvw1_trans[:,1] = uvw1[:,0]*np.sin(alpha) + uvw1[:,1]*np.cos(alpha) header2 = np.array(sread('%s/%s' %(indirpf,pf2file)) , dtype='|S1') uvw2 = np.array(fread('%s/%s' %(indirpf,pf2file), skip=1), dtype=np.float) uvw2_trans = np.copy(uvw2) uvw2_trans[:,0] = uvw2[:,0]*np.cos(alpha) - uvw2[:,1]*np.sin(alpha) uvw2_trans[:,1] = uvw2[:,0]*np.sin(alpha) + uvw2[:,1]*np.cos(alpha) ############################################################################ # plots # define grid if plot: import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.mlab import griddata import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.backends.backend_pdf as pdf x0 = np.linspace(np.min(np.minimum(uvw0_trans[:,0],uvw0_trans[:,1])), np.max(np.maximum(uvw0_trans[:,0],uvw0_trans[:,1])),500) y0 = np.linspace(np.min(np.minimum(uvw0_trans[:,0],uvw0_trans[:,1])), np.max(np.maximum(uvw0_trans[:,0],uvw0_trans[:,1])),500) x1 = np.linspace(np.min(np.minimum(uvw1_trans[:,0],uvw1_trans[:,1])), np.max(np.maximum(uvw1_trans[:,0],uvw1_trans[:,1])),500) y1 = np.linspace(np.min(np.minimum(uvw1_trans[:,0],uvw1_trans[:,1])), np.max(np.maximum(uvw1_trans[:,0],uvw1_trans[:,1])),500) x2 = np.linspace(np.min(np.minimum(uvw2_trans[:,0],uvw2_trans[:,1])), np.max(np.maximum(uvw2_trans[:,0],uvw2_trans[:,1])),500) y2 = np.linspace(np.min(np.minimum(uvw2_trans[:,0],uvw2_trans[:,1])), np.max(np.maximum(uvw2_trans[:,0],uvw2_trans[:,1])),500) # grid the data. z0 = griddata(uvw0_trans[:,0],uvw0_trans[:,1],uvw0_trans[:,2],x0,y0, interp='linear') z1 = griddata(uvw1_trans[:,0],uvw1_trans[:,1],uvw1_trans[:,2],x1,y1, interp='linear') z2 = griddata(uvw2_trans[:,0],uvw2_trans[:,1],uvw2_trans[:,2],x2,y2, interp='linear') # plotting contours fig1 = plt.figure(1, figsize=(6,13)) sub1 = fig1.add_subplot(311, aspect=1) fillings = sub1.contourf(x0,y0,z0,20,cmap=plt.cm.jet) scat = sub1.scatter(uvw0_trans[:,0],uvw0_trans[:,1],marker='o',c='b',s=0.2,zorder=10) cbar = fig1.colorbar(fillings, orientation='vertical') xlimits = sub1.get_xlim() sub1.plot(np.array([xlimits[0],xlimits[1]]),np.array([0,0]), c='k') ylimits = sub1.get_ylim() sub1.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='k') sub1.set_title('Original wind components\nwith point data') cbar.set_label('w [m/s]') plt.ylabel('v [m/s]') sub2 = fig1.add_subplot(312, aspect=1) fillings = sub2.contourf(x1,y1,z1,20,cmap=plt.cm.jet) cbar = fig1.colorbar(fillings, orientation='vertical') xlimits = sub2.get_xlim() sub2.plot(np.array([xlimits[0],xlimits[1]]),np.array([0,0]), c='k') ylimits = sub2.get_ylim() sub2.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='k') sub2.set_title('One plane') cbar.set_label('w [m/s]') plt.ylabel('v [m/s]') sub3 = fig1.add_subplot(313, aspect=1) fillings = sub3.contourf(x2,y2,z2,20,cmap=plt.cm.jet) cbar = fig1.colorbar(fillings, orientation='vertical') xlimits = sub3.get_xlim() sub3.plot(np.array([xlimits[0],xlimits[1]]),np.array([0,0]), c='k') ylimits = sub3.get_ylim() sub3.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='k') sub3.set_title('Sectorial') cbar.set_label('w [m/s]') plt.xlabel('u [m/s]') plt.ylabel('v [m/s]') # plotting histograms mi = np.min(np.array([np.min(uvw0_trans[:,2]),np.min(uvw1_trans[:,2]), np.min(uvw2_trans[:,2])])) ma = np.max(np.array([np.max(uvw0_trans[:,2]),np.max(uvw1_trans[:,2]), np.max(uvw2_trans[:,2])])) steps = np.abs((ma-mi)/histsteps) bins = np.arange(mi,ma+steps,steps) fig2 = plt.figure(2, figsize=(6,13)) fig2.subplots_adjust(hspace=0.3) sub4 = fig2.add_subplot(311) n0, bins0, patches0 = sub4.hist(uvw0_trans[:,2], bins, color= 'b', histtype='bar') ylimits = sub4.get_ylim() sub4.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='y', lw=3) plt.ylabel('count') plt.title('Original w-component:\navg(w)= %.2f, var(w)= %.4f, skew(w)= %.4f' %(np.mean(uvw0_trans[:,2]), np.var(uvw0_trans[:,2]), skew(uvw0_trans[:,2]))) sub5 = fig2.add_subplot(312) n1, bins1, patches1 = sub5.hist(uvw1_trans[:,2], bins, color= 'g', histtype='bar') ylimits = sub5.get_ylim() sub5.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='y', lw=3) plt.ylabel('count') plt.title('One plane w-component:\navg(w)= %.2f, var(w)= %.4f, skew(w)= %.4f' %(np.mean(uvw1_trans[:,2]), np.var(uvw1_trans[:,2]), skew(uvw1_trans[:,2]))) sub6 = fig2.add_subplot(313) n2, bins2, patches2 = sub6.hist(uvw2_trans[:,2], bins, color= 'r', histtype='bar') ylimits = sub6.get_ylim() sub6.plot(np.array([0,0]),np.array([ylimits[0],ylimits[1]]), c='y', lw=3) plt.xlabel('Classes [m/s]') plt.ylabel('count') plt.title('Sectorial w-component:\navg(w)= %.2f, var(w)= %.4f, skew(w)= %.4f' %(np.mean(uvw2_trans[:,2]), np.var(uvw2_trans[:,2]), skew(uvw2_trans[:,2]))) # wind rose fig3 = plt.figure(3, figsize=(6,6)) pol = fig3.add_subplot(111, polar=True) hist, bin_edges= np.histogram(wdhor, bins=36, range=(0,360)) x = 90-np.arange(5,365,10) x = [i*pi/180. for i in x] # convert to radians pol.bar(x, hist, width=10*pi/180) pol.set_xticklabels([r'$\sf{90\degree}$',r'$\sf{45\degree}$',r'$\sf{0\degree}$', r'$\sf{315\degree}$',r'$\sf{270\degree}$',r'$\sf{225\degree}$', r'$\sf{180\degree}$',r'$\sf{135\degree}$'], fontsize=15) plt.title('Horizontal wind direction frequency') plt.show() ############################################################################ # user input for saving results print("Satisfied with the fit?\ny will save the figures, n will exit without saving!") ui2 = raw_input("(y/n)?: ").lower() if ui2 != "y": sys.exit() ############################################################################ # save results if plot: pp1 = pdf.PdfPages('%s/%s_pfit.pdf'%(indirpf,outfile[:-4])) pp2 = pdf.PdfPages('%s/%s_wdis.pdf'%(indirpf,outfile[:-4])) pp3 = pdf.PdfPages('%s/%s_wd.pdf'%(indirpf,outfile[:-4])) fig1.savefig(pp1, format='pdf') fig2.savefig(pp2, format='pdf') fig3.savefig(pp3, format='pdf') pp1.close() pp2.close() pp3.close() print("Rename EddyPFit files?") ui3 = raw_input("(y/n)?: ").lower() if ui3 != "y": sys.exit() os.rename('%s/%s' %(indirpf,pf0file), '%s/%s_%s.csv' %(indirpf, outfile[:-4], pf0file[:-4])) os.rename('%s/%s' %(indirpf,pf1file), '%s/%s_%s.csv' %(indirpf, outfile[:-4], pf1file[:-4])) os.rename('%s/%s' %(indirpf,pf2file), '%s/%s_%s.csv' %(indirpf, outfile[:-4], pf2file[:-4])) os.rename('%s/%s' %(indirpf,pfmat), '%s/%s_%s.csv' %(indirpf, outfile[:-4], pfmat[:-4]))
####Gridding pressure########################### # Size of regular grid ny, nx = 100, 101 # Generate a regular grid to interpolate the data. ox = -40. oy = -25. dx = (20-ox)/nx dy = (20-oy)/ny xi = np.linspace(ox, 20., nx) yi = np.linspace(oy, 20., ny) xi, yi = np.meshgrid(xi, yi) # Interpolate using delaunay triangularization zi = mll.griddata(pressure2interp[:,0],pressure2interp[:,1],pressure2interp[:,2],xi,yi) fig = figure(1, figsize=(6, 5)) ax = plt.subplot(1,1,1) p = plt.pcolormesh(xi,yi,zi,cmap='RdBu_r') cbar=plt.colorbar(p) ax.set_xlabel('Impedance % difference') ax.set_ylabel('Vp/Vs ratio % difference') #ax.set_title('Saturation ') p = plt.axis([-20, 20, -20, 20]) cbar.set_label('Pore pressure change (MPa)') fig.savefig('pressureInt.png', bbox_inches='tight') n = zp_inversion.size
def averaged_asymptotic_density(mo_bound, Dipole, bs, Rmax, E): from PI import LebedevQuadrature k = np.sqrt(2*E) wavelength = 2.0 * np.pi/k r = np.linspace(Rmax, Rmax+wavelength, 30) n = 5810 #ths,phis,ws = np.array(LebedevQuadrature.LebedevGridPoints[n]).transpose() ths = [] phis = [] ws = [] for theta in np.linspace(0.0, np.pi, 30): for phi in np.linspace(0.0, 2.0*np.pi, 30): ths.append(theta) phis.append(phi) ws.append(1) ths = np.array(ths) phis = np.array(phis) ws = np.array(ws) # dipole between bound orbital and the continuum AO basis orbitals dipole_bf = np.tensordot(mo_bound, Dipole, axes=(0,0)) # average MF-PAD over all orientations of the laser polarization direction wfn2_angular_avg = np.zeros(ws.shape) # #weights, Rots = euler_average(10) weights, Rots = so3_quadrature(10) ez = np.array([0,0,1.0]) for i,(w,R) in enumerate(zip(weights, Rots)): print "i = %d of %d" % (i, len(weights)) # rotate laser polarization from lab frame into molecular frame, this is equivalent to # rotating the molecule from the molecular into the lab frame epol = np.dot(R, ez) # projection of dipoles onto polarization direction mo_scatt = np.zeros(Dipole.shape[1]) for xyz in [0,1,2]: mo_scatt += dipole_bf[:,xyz] * epol[xyz] # normalized coefficients nrm2 = np.dot(mo_scatt, mo_scatt) mo_scatt /= np.sqrt(nrm2) print "sigma = %s" % nrm2 print "mo_scatt = %s" % mo_scatt def wavefunction(grid, dV): # evaluate continuum orbital amp = Cube.orbital_amplitude(grid, bs.bfs, mo_scatt, cache=False) return amp # rotate continuum wavefunction from molecular frame into lab frame ths_rot, phis_rot = rotate_sphere(R, ths, phis) xs = LebedevQuadrature.outerN(r, np.sin(ths_rot)*np.cos(phis_rot)) ys = LebedevQuadrature.outerN(r, np.sin(ths_rot)*np.sin(phis_rot)) zs = LebedevQuadrature.outerN(r, np.cos(ths_rot)) wfn2 = abs(wavefunction((xs,ys,zs), 1.0))**2 wfn2_angular = np.sum(ws * wfn2, axis=0) """ ########## from matplotlib.mlab import griddata import matplotlib.pyplot as plt th_resampled,phi_resampled = np.mgrid[0.0: np.pi: 30j, 0.0: 2*np.pi: 30j] resampled = griddata(ths, phis, wfn2_angular, th_resampled, phi_resampled, interp="linear") # 2D PLOT plt.imshow(resampled.T, extent=(0.0, np.pi, 0.0, 2*np.pi)) plt.colorbar() #plt.plot(ths, phis, "r.") #plt.plot(xs, ys, "b.") plt.show() # SPHERICAL PLOT from mpl_toolkits.mplot3d import Axes3D x_resampled = resampled * np.sin(th_resampled) * np.cos(phi_resampled) y_resampled = resampled * np.sin(th_resampled) * np.sin(phi_resampled) z_resampled = resampled * np.cos(th_resampled) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x_resampled, y_resampled, z_resampled, rstride=1, cstride=1) ax.scatter(x_resampled, y_resampled, z_resampled, color="k", s=20) plt.show() ###### print "W = %s" % w """ # wfn2_angular_avg += w * wfn2_angular #### from matplotlib.mlab import griddata import matplotlib.pyplot as plt th_resampled,phi_resampled = np.mgrid[0.0: np.pi: 30j, 0.0: 2*np.pi: 30j] resampled = griddata(ths, phis, wfn2_angular_avg, th_resampled, phi_resampled, interp="linear") # 2D PLOT plt.imshow(resampled.T, extent=(0.0, np.pi, 0.0, 2*np.pi)) plt.colorbar() #plt.plot(ths, phis, "r.") #plt.plot(xs, ys, "b.") plt.show() # SPHERICAL PLOT from mpl_toolkits.mplot3d import Axes3D x_resampled = resampled * np.sin(th_resampled) * np.cos(phi_resampled) y_resampled = resampled * np.sin(th_resampled) * np.sin(phi_resampled) z_resampled = resampled * np.cos(th_resampled) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x_resampled, y_resampled, z_resampled, rstride=1, cstride=1) ax.scatter(x_resampled, y_resampled, z_resampled, color="k", s=20) plt.show()
for row in range(int(results.shape[0])): bias = bias_array[row] transmission = results[row] tmax = cutoff * np.max(transmission) transmission[transmission > tmax] = tmax grid_epsilon.extend(epsilon_array) grid_bias.extend(bias + epsilon_array * 0) grid_transmission.extend(transmission) mesh_transmission = griddata(grid_epsilon, grid_bias, grid_transmission, mesh_epsilon, mesh_bias, interp='linear') ###plot time fig, ax = plt.subplots(figsize=(25, 15), dpi=1080) plt.xticks(fontsize=30) plt.yticks(fontsize=30) color_levels = MaxNLocator(nbins=100).tick_values(0.00, np.max(grid_transmission)) cf = ax.contourf(mesh_epsilon, mesh_bias, mesh_transmission, cmap=cmap, levels=color_levels)
def map_haz(fig, plt, haz_map_file, sitelon, sitelat, **kwargs): ''' kwargs: shpfile: path to area source - is a list of files resolution: c (crude), l (low), i (intermediate), h (high), f (full) mbuffer: map buffer in degrees ''' from openquake.nrmllib.hazard.parsers import GMFScenarioParser from mpl_toolkits.basemap import Basemap from numpy import arange, array, log10, mean, mgrid, percentile from matplotlib.mlab import griddata from matplotlib import colors, colorbar, cm from os import path from mapping_tools import drawshapepoly, labelpolygon import shapefile # set kwargs drawshape = False res = 'c' mbuff = -0.3 keys = ['shapefile', 'resolution', 'mbuffer'] for key in keys: if key in kwargs: if key == 'shapefile': shpfile = kwargs[key] drawshape = True if key == 'resolution': res = kwargs[key] if key == 'mbuffer': mbuff = kwargs[key] gmfsp = GMFScenarioParser(haz_map_file).parse() metadata, values = parse_nrml_hazard_map(haz_map_file) hazvals = [] latlist = [] lonlist = [] for val in values: lonlist.append(val[0]) latlist.append(val[1]) hazvals.append(val[2]) # get map bounds llcrnrlat = min(latlist) - mbuff / 2. urcrnrlat = max(latlist) + mbuff / 2. llcrnrlon = min(lonlist) - mbuff urcrnrlon = max(lonlist) + mbuff lon_0 = mean([llcrnrlon, urcrnrlon]) lat_1 = percentile([llcrnrlat, urcrnrlat], 25) lat_2 = percentile([llcrnrlat, urcrnrlat], 75) m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \ urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat, projection='lcc',lat_1=lat_1,lat_2=lat_2,lon_0=lon_0, resolution=res,area_thresh=1000.) m.drawcoastlines(linewidth=0.5, color='k') m.drawcountries() # draw parallels and meridians. m.drawparallels(arange(-90., 90., 1.), labels=[1, 0, 0, 0], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) m.drawmeridians(arange(0., 360., 1.), labels=[0, 0, 0, 1], fontsize=10, dashes=[2, 2], color='0.5', linewidth=0.5) # make regular grid N = 150j extent = (min(lonlist), max(lonlist), min(latlist), max(latlist)) xs, ys = mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N] resampled = griddata(array(lonlist), array(latlist), log10(array(hazvals)), xs, ys) ############################################################################# # transform grid to basemap # get 1D lats and lons for map transform lons = ogrid[extent[0]:extent[1]:N] lats = ogrid[extent[2]:extent[3]:N] # transform to map projection if max(lonlist) - min(lonlist) < 1: transspace = 500 elif max(lonlist) - min(lonlist) < 5: transspace = 1000 elif max(lonlist) - min(lonlist) < 10: transspace = 2000 else: transspace = 5000 nx = int((m.xmax - m.xmin) / transspace) + 1 ny = int((m.ymax - m.ymin) / transspace) + 1 transhaz = m.transform_scalar(resampled.T, lons, lats, nx, ny) m.imshow(transhaz, cmap='Spectral_r', extent=extent, vmin=-2, vmax=log10(2.), zorder=0) # plot site xx, yy = m(sitelon, sitelat) plt.plot(xx, yy, '*', ms=20, mec='k', mew=2.0, mfc="None") # superimpose area source shapefile if drawshape == True: for shp in shpfile: sf = shapefile.Reader(shp) drawshapepoly(m, plt, sf, col='k', lw=1.5, polyline=True) labelpolygon(m, plt, sf, 'CODE', fsize=14) # set colourbar # set cb for final fig plt.gcf().subplots_adjust(bottom=0.1) cax = fig.add_axes([0.6, 0.05, 0.25, 0.02]) # setup colorbar axes. norm = colors.Normalize(vmin=-2, vmax=log10(2.)) cb = colorbar.ColorbarBase(cax, cmap=cm.Spectral_r, norm=norm, orientation='horizontal') # set cb labels #linticks = array([0.01, 0.03, 0.1, 0.3 ]) logticks = arange(-2, log10(2.), 0.25) cb.set_ticks(logticks) labels = [str('%0.2f' % 10**x) for x in logticks] cb.set_ticklabels(labels) # get map probabiltiy from filename mprob = path.split(haz_map_file)[-1].split('_')[-1].split('-')[0] probstr = str(int(float(mprob) * 100)) # set colourbar title if metadata['statistics'] == 'mean': titlestr = ''.join((metadata['imt'], ' ', metadata['sa_period'], ' s ', \ probstr,'% in ',metadata['investigation_time'][0:-2], \ ' Year Mean Hazard (g)')) #cb.set_ticklabels(labels) cb.set_label(titlestr, fontsize=12) return plt
print freq, c print parameters[parameter_name], (2*pi*freq/c) x = np.append(x, freq/frequnit) y = np.append(y, ynew) z = np.append(z, znew) #z2 = np.append(z2, znew2) ## XXX if not ylim: ylim=(min(y), max(y)) plt.ylabel(ylabel); plt.xlabel(u"Frequency (THz)"); xi = np.linspace(min(x), max(x), 500) yi = np.linspace(min(y), max(y), 300) # grid the data. from matplotlib.mlab import griddata zi = griddata(x, y*interp_anisotropy, z, xi, yi*interp_anisotropy, interp='linear') #zi2 = griddata(x, y*interp_anisotropy, z2, xi, yi*interp_anisotropy, interp='linear') # contour the gridded data, plotting dots at the nonuniform data points. if quantity=="Nim": Nim_data = zi if quantity in ('reflection', 'transmission'): cmap = cm.jet; levels = np.arange(0.,1.05,.03) elif quantity=='loss': cmap = cm.jet; levels = np.arange(-10.,0.01,.2) elif quantity=='Nim': cmap = cm.gist_earth_r; levels = np.arange(0, 3,.05) elif quantity=='Nim_log': cmap = cm.gist_earth_r; levels = np.arange(-4, 1,.05) elif quantity=='Nre': cmap = cm.gist_earth_r; levels = np.arange(0,5,.2) elif quantity=='absNre': cmap = cm.gist_earth_r; levels = np.arange(0.,.51,.03) elif quantity=='eps': cmap = cm.RdBu_r; levels = np.arange(-10.,10,.5) elif quantity=='epsangle': cmap = cm.jet; levels = np.arange(-np.pi,np.pi,.1) elif quantity=='mu': cmap = cm.RdBu_r; levels = np.arange(-10.,10,.5)
def __draw_plot(self): freqCentre = self.spinCentre.GetValue() freqBw = self.spinBw.GetValue() freqMin = (freqCentre - freqBw) / 1000. freqMax = (freqCentre + freqBw) / 1000. coords = {} for timeStamp in self.spectrum: spectrum = self.spectrum[timeStamp] sweep = [yv for xv, yv in spectrum.items() if freqMin <= xv <= freqMax] if len(sweep): peak = max(sweep) try: location = self.location[timeStamp] except KeyError: continue coord = tuple(location[0:2]) if coord not in coords: coords[coord] = peak else: coords[coord] = (coords[coord] + peak) / 2 x = [] y = [] z = [] for coord, peak in coords.iteritems(): x.append(coord[1]) y.append(coord[0]) z.append(peak) self.extent = (min(x), max(x), min(y), max(y)) self.xyz = (x, y, z) xi = numpy.linspace(min(x), max(x), self.IMAGE_SIZE) yi = numpy.linspace(min(y), max(y), self.IMAGE_SIZE) if self.plotMesh or self.plotCont: zi = mlab.griddata(x, y, z, xi, yi) if self.plotMesh: self.plot = self.axes.pcolormesh(xi, yi, zi, cmap=self.colourMap) self.plot.set_zorder(1) if self.plotCont: contours = self.axes.contour(xi, yi, zi, linewidths=0.5, colors='k') self.axes.clabel(contours, inline=1, fontsize='x-small', gid='clabel', zorder=3) if self.plotHeat: image = create_heatmap(x, y, self.IMAGE_SIZE, self.IMAGE_SIZE / 10, self.colourHeat) heatMap = self.axes.imshow(image, aspect='auto', extent=self.extent) heatMap.set_zorder(2) if self.plotPoint: self.axes.plot(x, y, 'wo') for posX, posY, posZ in zip(x, y, z): points = self.axes.annotate('{0:.2f}dB'.format(posZ), xy=(posX, posY), xytext=(-5, 5), ha='right', textcoords='offset points') points.set_zorder(3) if matplotlib.__version__ >= '1.3': effect = patheffects.withStroke(linewidth=2, foreground="w", alpha=0.75) for child in self.axes.get_children(): child.set_path_effects([effect]) if self.plotAxes: self.axes.set_axis_on() else: self.axes.set_axis_off() self.canvas.draw()
# plot contour and residual of sample model galaxies ----------------------------------------------- my_cm = mpl.colors.ListedColormap(np.loadtxt("colormap.dat") / 255) for i, ax in enumerate(np.ravel(axs)): ax.set_xlim(0.5, 2.5) ax.set_ylim(0.0, 1.25) ax.contour(xe[:-1], ye[:-1], H.T, levels=[0.1], colors=["#1A1A1A"], lw=2.5) sizes = std[:, i] * 100 if i == 0 or i == 3: colors = err(phy_sam[:, i], med[:, i]) else: colors = err(phy_sam[:, i], med[:, i], relative=False) xg = np.linspace(0.5, 2.5, 100) yg = np.linspace(0.0, 1.25, 100) zg = griddata(scolor_x, scolor_y, std[:, i], xg, yg, interp="linear") #cont = ax.contourf(xg, yg, zg, vmin = -1.0, vmax = +1.0, levels = np.linspace(-1., +1., 9), cmap = my_cm) cont = ax.contour(xg, yg, zg, 3) plt.colorbar(cont) #if i == 0 : #sc = ax.scatter(scolor_x, scolor_y, lw = 0, c = colors, s = sizes, vmin = -1.0, vmax = +1.0, cmap = my_cm) #cb = plt.colorbar(sc) #cb.set_label("residual") #cb.set_ticks(np.linspace(-1., +1., 9)) #else : ax.scatter(scolor_x, scolor_y, lw = 0, c = colors, s = sizes, vmin = -1.0, vmax = +1.0, cmap = my_cm) plt.tight_layout() plt.savefig("../../plots/photometric_fit/residual_maps.png", bbox_inches="tight")
def strain_plots(strain, avg_strain, strn_rng, descrip): # plot strain vs location for each column of data points for i_step in range(sample.n_load_step): plt.close('all') plt.figure(figsize=fig_size) plt.tick_params(labelsize=tick_size) plt.xlabel('y-coordinate', fontsize=label_size) plt.ylabel('strain', fontsize=label_size) plt.ylim(strn_rng) for i_col in range(len(strain[i_step])): plt.plot(z[i_step][i_col], strain[i_step][i_col], '-', label='x = '+'%6.1f'%x[0][i_col][0], lw=2) plt.grid(True) plt.legend(numpoints=1, fontsize=tick_size, bbox_to_anchor=legend_loc) plt.savefig(ring.strn_dir+orient+'/'+descrip+'_strain_line_'+sample.step_names[i_step]+'.png', bbox_inches='tight', pad_inches=0.1) # plot strains averaged across columns plt.close('all') plt.figure(figsize=fig_size) plt.tick_params(labelsize=tick_size) plt.xlabel('y-coordinate', fontsize=label_size) plt.ylabel('strain', fontsize=label_size) plt.ylim(strn_rng) for i_step in range(sample.n_load_step): plt.plot(np.unique(np.concatenate(z[i_step])), avg_strain[i_step], '-', label=sample.step_names[i_step]+' '*(10-len(sample.step_names[i_step])), lw=2) plt.grid(True) plt.legend(numpoints=1, fontsize=tick_size, bbox_to_anchor=legend_loc) plt.savefig(ring.strn_dir+orient+'/'+descrip+'_strain_line_averaged.png', bbox_inches='tight', pad_inches=0.1) # make 2d plots for i_step in range(sample.n_load_step): # contour and colorbar levels con_levels = np.linspace(strn_rng[0], strn_rng[1], num=n_levels) cb_levels = np.linspace(strn_rng[0], strn_rng[1], num=n_colorbar) # scatter plot plt.close('all') plt.figure(figsize=fig_size) plt.tick_params(labelsize=tick_size) plt.xlabel('x-coordinate', fontsize=label_size) plt.ylabel('y-coordinate', fontsize=label_size) for i_col in range(len(strain[i_step])): plt.scatter(x[i_step][i_col], z[i_step][i_col], s=scatter_size, c=strain[i_step][i_col], vmin=strn_rng[0], vmax=strn_rng[1], lw=0) cb = plt.colorbar(ticks=cb_levels, orientation='vertical') cb.ax.tick_params(labelsize=tick_size) plt.savefig(ring.strn_dir+orient+'/'+descrip+'_strain_scatter_'+sample.step_names[i_step]+'.png', bbox_inches='tight', pad_inches=0.1) # contour plot stepx, stepz, stepstrain = [], [], [] for i_col in range(len(strain[i_step])): for i_pt in range(len(strain[i_step][i_col])): stepx.append(x[i_step][i_col][i_pt]) stepz.append(z[i_step][i_col][i_pt]) stepstrain.append(strain[i_step][i_col][i_pt]) xa = np.linspace(np.min(stepx), np.max(stepx), num=n_contour, endpoint=True) za = np.linspace(np.min(stepz), np.max(stepz), num=n_contour, endpoint=True) var_array = griddata(stepx, stepz, stepstrain, xa, za, interp='linear') x_array, y_array = np.meshgrid(xa, za) plt.close('all') plt.figure(figsize=fig_size) plt.tick_params(labelsize=tick_size) plt.xlabel('x-coordinate', fontsize=label_size) plt.ylabel('y-coordinate', fontsize=label_size) plt.contourf(x_array, y_array, var_array, con_levels, linestyle = 'solid') cb = plt.colorbar(ticks=cb_levels, orientation='vertical') cb.ax.tick_params(labelsize=tick_size) plt.savefig(ring.strn_dir+orient+'/'+descrip+'_strain_contour_'+sample.step_names[i_step]+'.png', bbox_inches='tight', pad_inches=0.1) plt.close('all')
def __init__(self, args): import matplotlib.pyplot as plt import matplotlib.tri as tri from matplotlib.mlab import griddata """ Nx0,Ny0,Ix0,Iy0,typ0,finesse0 = probemapfile(args.inputs[0]) Nx1,Ny1,Ix1,Iy1,typ1,finesse1 = probemapfile(args.inputs[1]) print Ix0,Nx0,'...',Iy0,Ny0 print Ix1,Nx1,'...',Iy1,Ny1 Ix = min(Ix0,Ix1); Iy = min(Iy0,Iy1) Nx = max(Nx0,Nx1); Ny = max(Ny0,Ny1) if typ0 != typ1: print 'intrnl errrr',typ0,typ1 sys.exit(1) typ = typ0 print Ix0,Nx0,'...',Iy0,Ny0 print Ix1,Nx1,'...',Iy1,Ny1 """ Ix = +10000 Iy = +10000 Nx = -10000 Ny = -10000 for inpts in args.inputs: Nx0, Ny0, Ix0, Iy0, typ0, finesse0 = probemapfile(inpts) Ix = min(Ix0, Ix) Iy = min(Iy0, Iy) Nx = max(Nx0, Nx) Ny = max(Ny0, Ny) print 'Ix,Nx,Iy,Ny:', Ix, Nx, Iy, Ny ux = {} uy = {} uz = {} uu = {} # u[:,:] = vinit for inpts in args.inputs: f = open(inpts, 'r') for line in f.readlines(): line = line.split() if not line: continue # Skip empty lines if line[0][0] == '#': continue ii = int(float(line[1])) jj = int(float(line[0])) iii = ii - Ix0 jjj = jj - Iy0 if typ0 == 'scalar': uu[iii, jjj] = float(line[2]) elif typ0 == 'vector': ux[iii, jjj] = float(line[2]) uy[iii, jjj] = float(line[3]) uz[iii, jjj] = float(line[4]) uu[iii, jjj] = float(line[5]) f.close() xx = [] yy = [] for rr in uu.keys(): xx.append(rr[0]) yy.append(rr[1]) x = np.asarray(xx).flatten() y = np.asarray(yy).flatten() if typ0 == 'vector': Ux = np.asarray(ux.values()).flatten() Uy = np.asarray(uy.values()).flatten() Uz = np.asarray(uz.values()).flatten() U = np.asarray(uu.values()).flatten() # Create the Delaunay triangulation # triang = tri.Triangulation(x, y) triang = tri.Triangulation(y, x) # Mask off unwanted triangles. # xmid = x[triang.triangles].mean(axis=1) # ymid = y[triang.triangles].mean(axis=1) # mask = np.where(xmid*xmid + 2.*ymid*ymid < 100., 1, 0) # triang.set_mask(mask) # U = U / (U.max() - U.min()) low = U.min() upp = U.max() print 'low,upp:', low, upp, typ0 if typ0 == 'vector': upp = 224000 levels = np.arange(low, upp, 1.e-2 * (upp - low)) xi, yi = np.mgrid[0:Nx:complex(0, Nx), 0:Ny:complex(0, Ny)] if typ0 == 'vector': uxi = griddata(x, y, Ux, xi, yi, interp='linear') uyi = griddata(x, y, Uy, xi, yi, interp='linear') uzi = griddata(x, y, Uz, xi, yi, interp='linear') uui = griddata(x, y, U, xi, yi, interp='linear') # fig0, ax0 = plt.subplots() fig1, (ax1, ax2) = plt.subplots(ncols=2) if typ0 == 'vector': strm = ax1.streamplot(yi, xi, uxi, uzi, density=5.0, color=uui, linewidth=1) # plt.gca().set_aspect('equal') cset = plt.tricontourf(triang, U, levels=levels) plt.colorbar(cset) # plt.tricontour(triang, U, colors='k') # plt.title('Prottt') plt.show()
print "Computing average for AVG 1\n\n" umean1 = avg1.variables['u'][1800::10, -1, ...].mean(axis=0) vmean1 = avg1.variables['v'][1800::10, -1, ...].mean(axis=0) print "Computing average for AVG 2\n\n" umean2 = avg2.variables['u'][::10, -1, ...].mean(axis=0) vmean2 = avg2.variables['v'][::10, -1, ...].mean(axis=0) print "Computing average for AVG 3\n\n" umean3 = avg3.variables['u'][::10, -1, ...].mean(axis=0) vmean3 = avg3.variables['v'][::10, -1, ...].mean(axis=0) umean = (umean1 + umean2 + umean3) / 3 vmean = (vmean1 + vmean2 + vmean3) / 3 umean = griddata(lonu.ravel(), latu.ravel(), umean.ravel(), lon, lat) vmean = griddata(lonv.ravel(), latv.ravel(), vmean.ravel(), lon, lat) else: zu = get_depths(avg1, grd, 0, 'u') zv = get_depths(avg1, grd, 0, 'v') umean1 = np.zeros((km, im, jm - 1)) vmean1 = np.zeros((km, im - 1, jm)) umean2 = np.zeros((km, im, jm - 1)) vmean2 = np.zeros((km, im - 1, jm)) umean3 = np.zeros((km, im, jm - 1)) vmean3 = np.zeros((km, im - 1, jm)) umean = np.zeros((im, jm - 1)) vmean = np.zeros((im - 1, jm)) count = 0
#from matplotlib.collections import PatchCollection from matplotlib import cm from mpl_toolkits.mplot3d import axes3d data = np.loadtxt('result.txt', delimiter=',') fig = plt.figure(figsize=(24, 6)) #p=PatchCollection(mypatches,color='none', alpha=1.0,edgecolor="purple",linewidth=2.0) #levels=np.arange(data[:,2].min(),data[:,2].max(), 0.2) levels1=np.arange(data[:,2].min(),data[:,2].max(), 5) norm = cm.colors.Normalize(vmax=data[:,2].max(), vmin=data[:,2].min()) grid_x, grid_y = np.mgrid[data[:,0].min():data[:,0].max():250j, data[:,1].min():data[:,1].max():250j] #grid_z = griddata((data[:,0], data[:,1]), data[:,2], (grid_x, grid_y), method='cubic') grid_z = griddata(data[:,0], data[:,1], data[:,2], grid_x, grid_y, interp='linear') C = plt.contourf(grid_x, grid_y, grid_z, len(levels1)+8, cmap=plt.cm.Spectral, norm=norm,) C1 = plt.contour(grid_x, grid_y, grid_z, levels1, colors='k') plt.clabel(C1, inline=1, fontsize=10) for c in C1.collections: c.set_linestyle('solid') plt.colorbar(C) plt.subplots_adjust(left=0.04,right=1.1,wspace=0.25,hspace=0.25,bottom=0.1,top=0.94) plt.savefig('conrour.eps', format='eps',dpi = 1000)
def analyze(self, max_text_length=10000, max_patt_length=1000, progress=True, input_file_path=None): """ Analyzes given algorithm by varying both text and pattern length and plots it in 3D space :param max_text_length: Maximum length of text used in analysis. Should be greater than 5000 :param max_patt_length: Maximum length of pattern used in analysis. Should be greater than 500 :param progress: If True, Progress bar is shown :param input_file_path: Path to the sample file. Must be larger than 5000 char length. If None, analysis is done with in-built sample :return: 3D plot of running time vs text and pattern length """ # Analyzes the matching algorithm if max_text_length < self.__min_text_length: raise ValueError('Minimum text length is {}'.format(self.__min_text_length)) if max_patt_length < self.__min_patt_length: raise ValueError('Minimum text length is {}'.format(self.__min_patt_length)) if max_text_length < max_patt_length: raise ValueError( 'Pattern length {} is incompatible with Text Length {}'.format(max_patt_length, max_text_length)) if input_file_path is None: input_file_path = os.path.join(self.__sample_path, self.__samples_list[randrange(0, len(self.__samples_list))]) file = open(input_file_path, 'r') file_text = file.read() if max_text_length > len(file_text): raise ValueError('File length {} is smaller than {}'.format(len(file_text), max_text_length)) data_array = [] print('Please wait while analysing {} algorithm'.format(self.matcher.name)) if progress: import progressbar count = 0 max_count = (max_text_length - 1000) // 100 * (max_patt_length - 100) // 5 bar = progressbar.ProgressBar(max_value=max_count) for n in range(1000, max_text_length, 100): for m in range(100, max_patt_length, 5): if progress: bar.update(count) count += 1 pos = randint(0, len(file_text) - n) text = file_text[pos:pos + n] # Select a random text of size n pos = randint(0, len(text) - m) pattern = text[pos:pos + m] # Select a random pattern of size m from text, where m<n self.matcher.match(text, pattern) # Run the string matching algorithm with T and P as parameters data_array.append((n, m, self.matcher.count)) dat = np.array(data_array) fig = plt.figure() ax = fig.gca(projection='3d') x = dat[:, 0] y = dat[:, 1] z = dat[:, 2] xi = np.linspace(min(x), max(x)) yi = np.linspace(min(y), max(y)) X, Y = np.meshgrid(xi, yi) Z = griddata(x, y, z, xi, yi, interp='linear') surf = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap=plt.get_cmap('jet'), linewidth=1, antialiased=True) ax.set_xlabel('length of text $n$') ax.set_ylabel('length of pattern $m$') ax.set_zlabel('number of basic operations performed $c$') plt.suptitle('{0} Analysis\n Sample = {1}'.format(self.matcher.name, os.path.basename(input_file_path))) ax.set_zlim3d(np.min(Z), np.max(Z)) fig.colorbar(surf) plt.show()
def contour_array(model, X, Y, Zs, cellsize=(5, 5), nrows=None, ncols=None, xticks=None, yticks=None, colors=None): data = model.solution["variables"] n = len(Zs) if nrows is None: nrows = (n+1)/2 if ncols is None: ncols = 2 if n >= 2 else 1 figsize = (cellsize[0]*ncols, cellsize[1]*nrows) x_sweep = model.substitutions[model[str(X)].key][1] y_sweep = model.substitutions[model[str(Y)].key][1] if xticks is None: xticks = x_sweep if yticks is None: yticks = y_sweep def get_label(var): var = model[str(var)].key label = var.name if "idx" in var.descr: idx = var.descr.pop("idx", None) var = VarKey(**var.descr) label += "_%s" % idx vals = data[var][:, idx] else: vals = data[var] if var.units: label += unitstr(var.units, " [%s] ") if "label" in var.descr: label += " %s" % var.descr["label"] return label, vals xlabel, x_sol = get_label(X) ylabel, y_sol = get_label(Y) Z_lgs = [get_label(Z) for Z in Zs] if colors is None: colors = LIGHT_COLORS[0], DARK_COLORS[0] fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True, sharey=True) if nrows > 1 and ncols > 1: xlabeledaxes = axes[-1, :] ylabeledaxes = axes[:, 0] elif ncols > 1: xlabeledaxes = axes ylabeledaxes = [axes[0]] else: xlabeledaxes = [axes[-1]] ylabeledaxes = axes for ax in xlabeledaxes: ax.set_xlabel(xlabel, color=NEUTRAL_DARK) ax.set_xlim((x_sol.min(), x_sol.max())) if xticks is not None: ax.set_xticks(xticks, minor=True) m = len(xticks) major_xticks = [xticks[i] for i in (0, 1*m/4, 2*m/4, 3*m/4, m-1)] major_ticklabels = ["%.2g" % x for x in major_xticks] ax.set_xticks(major_xticks) ax.set_xticklabels(major_ticklabels) for ax in ylabeledaxes: ax.set_ylabel(ylabel, color=NEUTRAL_DARK) ax.set_ylim((y_sol.min(), y_sol.max())) if yticks is not None: ax.set_yticks(yticks, minor=True) m = len(yticks) major_yticks = [yticks[i] for i in (0, 1*m/4, 2*m/4, 3*m/4, m-1)] major_ticklabels = ["%.2g" % y for y in major_yticks] ax.set_yticks(major_yticks) ax.set_yticklabels(major_ticklabels) fig.tight_layout(h_pad=3) for i, Z_lg in enumerate(Z_lgs): zlabel, z_sol = Z_lg row_idx = i/ncols # 0, 0, 1, 1, 2, 2 for ncols = 2 col_vector = axes[row_idx, :] if nrows > 1 else axes ax = col_vector[(i-row_idx*ncols) % ncols] if ncols > 1 else row_vector[0] lablevels = [np.percentile(z_sol, 100*i/7.0) for i in range(8)] shortlevels = [(lablevels[4]-lablevels[3])/6.0 * j + lablevels[3] for j in range(-32, 33)] Zgrid = griddata(x_sol, y_sol, z_sol, x_sweep, y_sweep, interp='linear') contour_plot(ax, x_sweep, y_sweep, Zgrid, zlabel, colors, shortlevels, lablevels) return fig, axes
#!/usr/bin/env python import numpy as np from matplotlib.mlab import griddata import matplotlib.pyplot as plt data = np.genfromtxt("data/henon-lyapunov-ab-plane.tsv", dtype=float, delimiter='\t') a = data[:, 0] # The values of the a parameter for the henon map b = data[:, 1] # The values of the b parameter for the henon map l = data[:, 2] # The values of the lyapunov exponents lmax = max(np.absolute(l)) lmin = -lmax # Reshape l so it lies on the appropriate rectangular grid ai = np.unique(a) bi = np.unique(b) li = griddata(a, b, l, ai, bi) plt.pcolor(ai, bi, li, cmap='RdBu') plt.axis('tight') plt.xlabel("a value") plt.ylabel("b value") plt.colorbar() plt.savefig("henon-lyapunov-ab-plane.pdf")