def draw_force_field(x_list, y_list, width, height): from pprint import pprint '''docstring for draw_force_field''' log.info("draw_force_field is working..." ) X = [] Y = [] for row in range(0,height): one_row_x = [] one_row_y = [] for col in range(0, width): i = row * width + col one_row_x.append(x_list[i]) one_row_y.append(y_list[i]) X.append(one_row_x) Y.append(one_row_y) #X.insert(0, one_row_x) #Y.insert(0, one_row_y) Q = plt.quiver( X, Y) plt.quiverkey(Q, 0.5, 0.92, 2, r'') #l,r,b,t = plt.axis() #dx, dy = r-l, t-b ##axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy]) #plt.xticks(range(0,width +3)) #plt.yticks(range(0,height + 3)) plt.title('Attraction Force field') plt.savefig("pixel.jpg") plt.show() return 0
def plot_meancontquiv(turbine="turbine2", save=False): mean_u = load_vel_map(turbine=turbine, component="u") mean_v = load_vel_map(turbine=turbine, component="v") mean_w = load_vel_map(turbine=turbine, component="w") y_R = np.round(np.asarray(mean_u.columns.values, dtype=float), decimals=4) z_R = np.asarray(mean_u.index.values, dtype=float) plt.figure(figsize=(7.5, 4.1)) # Add contours of mean velocity cs = plt.contourf(y_R, z_R, mean_u / U, 20, cmap=plt.cm.coolwarm) cb = plt.colorbar(cs, orientation="vertical") cb.set_label(r"$U/U_{\infty}$") # Make quiver plot of v and w velocities Q = plt.quiver(y_R, z_R, mean_v / U, mean_w / U, angles="xy", width=0.0022, edgecolor="none", scale=3.0) plt.xlabel(r"$y/R$") plt.ylabel(r"$z/R$") plt.quiverkey( Q, 0.65, 0.045, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"} ) ax = plt.axes() ax.set_aspect(1) # Plot circle to represent turbine frontal area circ = plt.Circle((0, 0), radius=1, facecolor="none", edgecolor="gray", linewidth=3.0) ax.add_patch(circ) plt.tight_layout() if save: plt.savefig("figures/" + turbine + "-meancontquiv.pdf")
def main(): plot_utils.apply_plot_params(width_cm=20, height_cm=20, font_size=10) high_hles_years = [1993, 1995, 1998] low_hles_years = [1997, 2001, 2006] data_path = "/BIG1/skynet1_rech1/diro/sample_obsdata/eraint/eraint_uvslp_years_198111_201102_NDJmean_ts.nc" with xr.open_dataset(data_path) as ds: print(ds) u = get_composit_for_name(ds, "u10", high_years_list=high_hles_years, low_years_list=low_hles_years) v = get_composit_for_name(ds, "v10", high_years_list=high_hles_years, low_years_list=low_hles_years) msl = get_composit_for_name(ds, "msl", high_years_list=high_hles_years, low_years_list=low_hles_years) lons = ds["longitude"].values lats = ds["latitude"].values print(lats) print(msl.shape) print(lons.shape, lats.shape) lons2d, lats2d = np.meshgrid(lons, lats) fig = plt.figure() map = Basemap(llcrnrlon=-130, llcrnrlat=22, urcrnrlon=-28, urcrnrlat=65, projection='lcc', lat_1=33, lat_2=45, lon_0=-95, resolution='i', area_thresh=10000) clevs = np.arange(-11.5, 12, 1) cmap = cm.get_cmap("bwr", len(clevs) - 1) bn = BoundaryNorm(clevs, len(clevs) - 1) x, y = map(lons2d, lats2d) im = map.contourf(x, y, msl / 100, levels=clevs, norm=bn, cmap=cmap) # convert to mb (i.e hpa) map.colorbar(im) stride = 2 ux, vy = map.rotate_vector(u, v, lons2d, lats2d) qk = map.quiver(x[::stride, ::stride], y[::stride, ::stride], ux[::stride, ::stride], vy[::stride, ::stride], scale=10, width=0.01, units="inches") plt.quiverkey(qk, 0.5, -0.1, 2, "2 m/s", coordinates="axes") map.drawcoastlines(linewidth=0.5) map.drawcountries() map.drawstates() #plt.show() fig.savefig("hles_wind_compoosits.png", bbox_inches="tight", dpi=300)
def add_std_vector_to_12months_cycle_figure(plt, fig, CF, parameter): std_length = parameter[0] scale = parameter[1] qkeyx = parameter[2] qkeyy = parameter[3] plt.quiverkey(CF, qkeyx, qkeyy, std_length, str(std_length)) return plt
def PLOT_E(v1,v2,v3,v4,scale,title="",flag_out=0,name_out="output.png",flag_show=0): if not len(v1) == len (v2): print("v1 and v2 have different length") return if not len(v1) == len (v3): print("v1 and v3 have different length") return if not len(v1) == len (v4): print("v1 and v4 have different length") return E1 = [] E2 = [] for i in range(len(v1)): E=math.hypot(v3[i],v4[i]) T=math.atan2(v4[i],v3[i]) E1.append( E*math.cos(0.5*T)) E2.append( E*math.sin(0.5*T)) plt.title(title) A=plt.quiver(v1,v2,E1,E2,scale=(float)(scale),width=0.005,headwidth=0,pivot='middle') plt.quiverkey(A,0.95,0.95,0.1,"0.1") plt.axis('scaled') if flag_out == 1: plt.savefig(name_out) if flag_show == 1: plt.show() plt.close()
def plot_meancontquiv(): data = calcwake(t1=0.4) y_R = data["y/R"] z_R = data["z/R"] u = data["meanu"] v = data["meanv"] w = data["meanw"] plt.figure(figsize=(7, 9)) # Add contours of mean velocity cs = plt.contourf(y_R, z_R, u/U, 20, cmap=plt.cm.coolwarm) cb = plt.colorbar(cs, shrink=1, extend="both", orientation="horizontal", pad=0.1) #ticks=np.round(np.linspace(0.44, 1.12, 10), decimals=2)) cb.set_label(r"$U/U_{\infty}$") # Make quiver plot of v and w velocities Q = plt.quiver(y_R, z_R, v/U, w/U, angles="xy", width=0.0022, edgecolor="none", scale=3.0) plt.xlabel(r"$y/R$") plt.ylabel(r"$z/R$") plt.quiverkey(Q, 0.8, 0.21, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"}) ax = plt.axes() ax.set_aspect(1) # Plot circle to represent turbine frontal area circ = plt.Circle((0, 0), radius=1, facecolor="none", edgecolor="gray", linewidth=3.0) ax.add_patch(circ) plt.tight_layout()
def whiskerplot(cat,col,fig): if col == 'psf': key = r'e_{PSF}' if col == 'e': key = r'e' if col == 'dpsf': key = r'\Delta e_{PSF}' scale=0.02 y,x,mw,e1,e2,e=field.field.whisker_calc(cat,col=col) pos0=0.5*np.arctan2(e2/mw,e1/mw) e/=mw for i in range(len(x)): y[i,:,:],x[i,:,:]=field.field_methods.ccd_to_field(i,y[i,:,:]-2048,x[i,:,:]-1024) print 'y,x',y[i,:,:],x[i,:,:] plt.figure(fig) print np.shape(x),np.shape(y),np.shape(np.sin(pos0)*e),np.shape(np.cos(pos0)*e) Q = plt.quiver(np.ravel(y),np.ravel(x),np.ravel(np.sin(pos0)*e),np.ravel(np.cos(pos0)*e),units='width',pivot='middle',headwidth=0,width=.0005) plt.quiverkey(Q,0.2,0.2,scale,str(scale)+' '+key,labelpos='E',coordinates='figure',fontproperties={'weight': 'bold'}) plt.savefig('plots/y1/whisker_'+col+'.pdf', dpi=500, bbox_inches='tight') plt.close(fig) return
def plot_grid(EIC_grid,sat_track,sat_krig,title): ''' This function plots a scatter map of the EICS grid and its horizontal components, and the krigged value for the satellite. :param EIC_grid: The EICS grid :param satPos: The position of the satellite :param ptz_u: The krigged u component of the satellite :param ptz_v: The krigged v component of the satllite :param title: Timestamp of the satellite :return: The figure ''' # Define the size of the figure in inches plt.figure(figsize=(18,18)) # The horizontal components of the Ionospheric current from the EICS grid u = EIC_grid[:,2] v = EIC_grid[:,3] ''' The m variable defines the basemap of area that is going to be displayed. 1) width and height is the area in pixels of the area to be displayed. 2) resolution is the resolution of the boundary dataset being used 'c' for crude and 'l' for low 3) projection is type of projection of the basemape, in this case it is a Lambert Azimuthal Equal Area projection 4) lat_ts is the latitude of true scale, 5) lat_0 and lon_0 is the latitude and longitude of the central point of the basemap ''' m = Basemap(width=8000000, height=8000000, resolution='l', projection='lcc',\ lat_0=60,lon_0=-100.) m.drawcoastlines() #draw the coastlines on the basemap # draw parallels and meridians and label them m.drawparallels(np.arange(-80.,81.,20.),labels=[1,0,0,0],fontsize=10) m.drawmeridians(np.arange(-180.,181.,20.),labels=[0,0,0,1],fontsize=10) # Project the inputted grid into x,y values defined of the projected basemap parameters x,y =m(EIC_grid[:,1],EIC_grid[:,0]) satx,saty = m(sat_track[::10,7],sat_track[::10,6]) satkrigx,satkrigy = m(sat_krig[1],sat_krig[0]) ''' Plot the inputted grid as a quiver plot on the basemap, 1) x,y are the projected latitude and longitude coordinates of the grid 2) u and v are the horizontal components of the current 3) the EICS grid values are plotted in blue color where as the satellite krigged values are in red ''' eic = m.quiver(x,y,u,v,width = 0.004, scale=10000,color='#0000FF') satkrig = m.quiver(satkrigx,satkrigy,sat_krig[2],sat_krig[3],color='#FF0000',width=0.004, scale = 10000) satpos = m.scatter(satx,saty,s=100,marker='.',c='#009933',edgecolors='none',label='Satellite Track') sat_halo = m.scatter(satkrigx,satkrigy,s=400,facecolors='none',edgecolors='#66FF66',linewidth='5') plt.title(title) plt.legend([satpos],['Satellite Track'],loc='upper right',scatterpoints=1) plt.quiverkey(satkrig,0.891,0.948,520,u'\u00B1' +'520 mA/m',labelpos='E') plt.savefig('EICS_20110311_002400.png',bbox_inches='tight',pad_inches=0.2)
def water_quiver1(current_data): u = water_u1(current_data) v = water_v1(current_data) plt.hold(True) Q = plt.quiver(current_data.x[::2, ::2], current_data.y[::2, ::2], u[::2, ::2], v[::2, ::2]) max_speed = np.max(np.sqrt(u ** 2 + v ** 2)) label = r"%s m/s" % str(np.ceil(0.5 * max_speed)) plt.quiverkey(Q, 0.15, 0.95, 0.5 * max_speed, label, labelpos="W") plt.hold(False)
def animate(n): # the function of the animation ax.cla() plt.title('Drifter: {0} {1}'.format(drifter_ID,point['time'][n].strftime("%F %H:%M"))) draw_basemap(ax, points) ax.plot(drifter_points['lon'],drifter_points['lat'],'bo-',markersize=6,label='Drifter') ax.annotate(an2,xy=(dr_points['lon'][-1],dr_points['lat'][-1]),xytext=(dr_points['lon'][-1]+0.01*track_days, dr_points['lat'][-1]+0.01*track_days),fontsize=6,arrowprops=dict(arrowstyle="fancy")) ax.plot(model_points['lon'][:n+1],model_points['lat'][:n+1],'ro-',markersize=6,label=MODEL) #M = np.hypot(U[n], V[n]) Q = ax.quiver(X,Y,U[n],V[n],color='black',pivot='tail',units='xy') plt.quiverkey(Q, 0.5, 0.92, 1, r'$1 \frac{m}{s}$', labelpos='E',fontproperties={'weight': 'bold','size':18})
def plotResPosArrow2D(ccdSet, iexp, matchVec, sourceVec, outputDir): import matplotlib.pyplot as plt _xm = [] _ym = [] _dxm = [] _dym = [] for m in matchVec: if (m.good == True and m.iexp == iexp): _xm.append(m.u) _ym.append(m.v) _dxm.append((m.xi_fit - m.xi)*3600) _dym.append((m.eta_fit - m.eta)*3600) _xs = [] _ys = [] _dxs = [] _dys = [] if (len(sourceVec) != 0): for s in sourceVec: if (s.good == True and s.iexp == iexp): _xs.append(s.u) _ys.append(s.v) _dxs.append((s.xi_fit - s.xi)*3600) _dys.append((s.eta_fit - s.eta)*3600) xm = numpy.array(_xm) ym = numpy.array(_ym) dxm = numpy.array(_dxm) dym = numpy.array(_dym) xs = numpy.array(_xs) ys = numpy.array(_ys) dxs = numpy.array(_dxs) dys = numpy.array(_dys) plt.clf() plt.rc("text", usetex=USETEX) plt.rc('xtick', labelsize=10) plt.rc('ytick', labelsize=10) plotCcd(ccdSet) q = plt.quiver(xm, ym, dxm, dym, units="inches", angles="xy", scale=1, color="green", label="external") if len(xm) != 0 and len(ym) != 0: xPos = round(xm.min() + (xm.max() - xm.min())*0.002, -2) yPos = round(ym.max() + (ym.max() - ym.min())*0.025, -2) plt.quiverkey(q, xPos, yPos, 0.1, "0.1 arcsec", coordinates="data", color="blue", labelcolor="blue", labelpos='E', fontproperties={'size': 10}) plt.quiver(xs, ys, dxs, dys, units="inches", angles="xy", scale=1, color="red", label="internal") plt.axes().set_aspect("equal") plt.legend(fontsize=8) plt.title("LSST: %d" % (iexp)) plt.savefig(os.path.join(outputDir, "ResPosArrow2D_%d.png" % (iexp)), format="png")
def plot_whisker(x,y,e1,e2,name='',label='',scale=.01,key='',chip=False): plt.figure() Q = plt.quiver(x,y,e1,e2,units='width',pivot='middle',headwidth=0,width=.0005) if chip: plt.quiverkey(Q,0.2,0.125,scale,str(scale)+' '+key,labelpos='E',coordinates='figure',fontproperties={'weight': 'bold'}) plt.xlim((-250,4250)) plt.ylim((-200,2100)) else: plt.quiverkey(Q,0.2,0.2,scale,str(scale)+' '+key,labelpos='E',coordinates='figure',fontproperties={'weight': 'bold'}) plt.savefig('plots/footprint/whisker_'+name+'_'+label+'.png', dpi=500,bbox_inches='tight') plt.close() return
def plot_flow(binpath, pngpath, title, value): data = np.fromfile(binpath, dtype=float) # reading additional info NX = int(data[0]) NY = int(data[1]) data = data[2:] # hack a = NX NX = NY NY = a U = data[0:len(data):2] V = data[1:len(data):2] # get max and min vector UV = np.vstack((U, V)) UV_max = np.amax(UV, axis=1) UV_min = np.amin(UV, axis=1) # get sqrt(x^x + y^y) UV_max = np.square(UV_max) UV_max = np.sum(UV_max) UV_max = np.sqrt(UV_max) UV_min = np.square(UV_min) UV_min = np.sum(UV_min) UV_min = np.sqrt(UV_min) UV_average = (UV_max + UV_min) / 2 U = U.reshape(NX, NY) V = V.reshape(NX, NY) # create figure plt.figure(figsize=(6 * NY / NX, 6)) # title plt.title(title) Q = plt.quiver(U, V, color='r', pivot='mid', units='xy') plt.quiverkey(Q, 0.5, 0.95, UV_average, '{0:.3e} {1}'.format(UV_average, value), labelpos='W') l,r,b,t = plt.axis() l,r,b,t = 0.0, NY, 0.0, NX dx, dy = r-l, t-b plt.axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy]) plt.savefig(pngpath, dpi=150) plt.close() return 0
def quick_static(gflist,datapath,run_name,run_num,c): ''' Make quick quiver plot of static fields IN: gflist: Tod ecide which stations to plot datapath: Where are the data files ''' import matplotlib.pyplot as plt from numpy import genfromtxt,where,zeros,meshgrid,linspace GF=genfromtxt(gflist,usecols=3) sta=genfromtxt(gflist,usecols=0,dtype='S') lon=genfromtxt(gflist,usecols=1,dtype='f') lat=genfromtxt(gflist,usecols=2,dtype='f') #Read coseismcis i=where(GF!=0)[0] lon=lon[i] lat=lat[i] n=zeros(len(i)) e=zeros(len(i)) u=zeros(len(i)) #Get data if run_name!='' or run_num!='': run_name=run_name+'.' run_num=run_num+'.' for k in range(len(i)): neu=genfromtxt(datapath+run_name+run_num+sta[i[k]]+'.static.neu') n[k]=neu[0]#/((neu[0]**2+neu[1]**2)**0.5) e[k]=neu[1]#/((neu[0]**2+neu[1]**2)**0.5) u[k]=neu[2]#/(2*abs(neu[2])) #Plot plt.figure() xi = linspace(min(lon), max(lon), 500) yi = linspace(min(lat), max(lat), 500) X, Y = meshgrid(xi, yi) #c=Colormap('bwr') #plt.contourf(X,Y,Z,100) #plt.colorbar() Q=plt.quiver(lon,lat,e,n,width=0.001,color=c) plt.scatter(lon,lat,color='b') plt.grid() plt.title(datapath+run_name+run_num) plt.show() qscale_en=1 plt.quiverkey(Q,X=0.1,Y=0.9,U=qscale_en,label=str(qscale_en)+'m')
def overdraw_vec_with_axis(plt, datax, datay, xgrid, ygrid, std_length=0.1, scale=1, intvl=3, qkeyx=0.8, qkeyy=0.8, lw = 2): import matplotlib.pyplot as plt if datax.shape!=datay.shape: raise Exception('datax and datay don\'t have same shape!') if datax.shape[0] != ygrid.size: raise Exception('data size x does not match ygrid size!') if datay.shape[1] != xgrid.size: raise Exception('data size y does not match xgrid size!') X, Y=np.meshgrid(xgrid, ygrid) Q=plt.quiver(X[::intvl, ::intvl], Y[::intvl, ::intvl], datax[::intvl, ::intvl], datay[::intvl, ::intvl], angles='xy', scale=scale, lw = lw) plt.quiverkey(Q, qkeyx, qkeyy, std_length, str(std_length)) return plt
def plotmap(self, domain = [0., 360., -90., 90.], res='c', stepp=2, scale=20): latitudes = self.windspeed.latitudes.data longitudes = self.windspeed.longitudes.data m = bm(projection='cyl',llcrnrlat=latitudes.min(),urcrnrlat=latitudes.max(),\ llcrnrlon=longitudes.min(),urcrnrlon=longitudes.max(),\ lat_ts=0, resolution=res) lons, lats = np.meshgrid(longitudes, latitudes) cmap = palettable.colorbrewer.sequential.Oranges_9.mpl_colormap f, ax = plt.subplots(figsize=(10,6)) m.ax = ax x, y = m(lons, lats) im = m.pcolormesh(lons, lats, self.windspeed.data, cmap=cmap) cb = m.colorbar(im) cb.set_label('wind speed (m/s)', fontsize=14) Q = m.quiver(x[::stepp,::stepp], y[::stepp,::stepp], \ self.uanoms.data[::stepp,::stepp], self.vanoms.data[::stepp,::stepp], \ pivot='middle', scale=scale) l,b,w,h = ax.get_position().bounds qk = plt.quiverkey(Q, l+w-0.1, b-0.03, 5, "5 m/s", labelpos='E', fontproperties={'size':14}, coordinates='figure') m.drawcoastlines() return f
def my_plot(u,v,t,daystr,levels): #boston light swim ax= [-71.10, -70.10, 41.70, 42.70] # region to plot vel_arrow = 0.2 # velocity arrow scale subsample = 8 # subsampling of velocity vectors # find velocity points in bounding box ind = np.argwhere((lonc >= ax[0]) & (lonc <= ax[1]) & (latc >= ax[2]) & (latc <= ax[3])) np.random.shuffle(ind) Nvec = int(len(ind) / subsample) idv = ind[:Nvec] # tricontourf plot of water depth with vectors on top plt.figure(figsize=(20,10)) plt.subplot(111,aspect=(1.0/np.cos(lat[:].mean()*np.pi/180.0))) #tricontourf(tri, t,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.tricontourf(tri, t,levels=levels,shading='faceted') plt.axis(ax) plt.gca().patch.set_facecolor('0.5') cbar=plt.colorbar() cbar.set_label('Forecast Surface Temperature (C)', rotation=-90) plt.tricontour(tri, t,levels=[0]) Q = plt.quiver(lonc[idv],latc[idv],u[idv],v[idv],scale=10) maxstr='%3.1f m/s' % vel_arrow qk = plt.quiverkey(Q,0.92,0.08,vel_arrow,maxstr,labelpos='W') plt.title('NECOFS Surface Velocity, Layer %d, %s UTC' % (ilayer, daystr)) plt.plot(lon_track,lat_track,'m-o') plt.plot(lon_buoy,lat_buoy,'y-o')
def velocidadlimpio(self): #sino no llega al 2, asi funciona v = np.arange(-3, 3,1) [x,y] = np.meshgrid(v,v) z=np.multiply(x,np.exp( -np.power(x,2) - np.power(y,2) )) #Matplotlib t invierte el orden de las matrices a diferenciade matlab [py,px] = np.gradient(z,1,1) print 'x '+str(x) print 'y '+str(y) print 'z '+str(z) print 'px '+str(px) print 'py '+str(py) #q = plt.quiver(X, Y, u, v, angles='xy', scale=40, color=['r']) #p = plt.quiverkey(q,1,16.5,50,"50 m/s",coordinates='data',color='r') #primero los rangos, despues los valores q contiene q = plt.quiver(x,y, px, py) p = plt.quiverkey(q,1,16.5,50,"50 m/s",coordinates='data',color='r') plt.title('Velocidad') plt.show() print 'Fourth plot loaded...'
def plot_meancontquiv(t1_fraction=0.5, cb_orientation="vertical", save=False): """Plot contours of normalized mean streamwise velocity and vectors of cross-stream and vertical mean velocity. """ data = load_probe_data(t1_fraction=t1_fraction) y_R = data["y_R"] z_H = data["z_H"] mean_u = data["mean_u"] mean_v = data["mean_v"] mean_w = data["mean_w"] scale = 7.5/10.0 plt.figure(figsize=(10*scale, 3*scale)) # Add contours of mean velocity cs = plt.contourf(y_R, z_H, mean_u, 20, cmap=plt.cm.coolwarm) if cb_orientation == "horizontal": cb = plt.colorbar(cs, shrink=1, extend="both", orientation="horizontal", pad=0.14) elif cb_orientation == "vertical": cb = plt.colorbar(cs, shrink=0.88, extend="both", orientation="vertical", pad=0.02) cb.set_label(r"$U/U_{\infty}$") # Make quiver plot of v and w velocities Q = plt.quiver(y_R, z_H, mean_v, mean_w, width=0.0022, edgecolor="none", scale=3) plt.xlabel(r"$y/R$") plt.ylabel(r"$z/H$") plt.ylim(-0.15, 0.85) plt.xlim(-1.68/R, 1.68/R) if cb_orientation == "horizontal": plt.quiverkey(Q, 0.65, 0.26, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"}) elif cb_orientation == "vertical": plt.quiverkey(Q, 0.65, 0.09, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"}) plot_turb_lines() ax = plt.axes() ax.set_aspect(H/R) plt.yticks([0, 0.13, 0.25, 0.38, 0.5, 0.63, 0.75]) plt.grid(True) plt.tight_layout() if save: plt.savefig("figures/meancontquiv.pdf") plt.savefig("figures/meancontquiv.png", dpi=300)
def plot_meancontquiv(save=False, show=False, savetype=".pdf", cb_orientation="vertical"): """Plot mean contours/quivers of velocity.""" mean_u = load_vel_map("u") mean_v = load_vel_map("v") mean_w = load_vel_map("w") y_R = np.round(np.asarray(mean_u.columns.values, dtype=float), decimals=4) z_H = np.asarray(mean_u.index.values, dtype=float) plt.figure(figsize=(7.5, 4.8)) # Add contours of mean velocity cs = plt.contourf(y_R, z_H, mean_u, np.arange(0.15, 1.25, 0.05), cmap=plt.cm.coolwarm) if cb_orientation == "horizontal": cb = plt.colorbar(cs, shrink=1, extend="both", orientation="horizontal", pad=0.14) elif cb_orientation == "vertical": cb = plt.colorbar(cs, shrink=1, extend="both", orientation="vertical", pad=0.02) cb.set_label(r"$U/U_{\infty}$") plt.hold(True) # Make quiver plot of v and w velocities Q = plt.quiver(y_R, z_H, mean_v, mean_w, width=0.0022, edgecolor="none", scale=3.0) plt.xlabel(r"$y/R$") plt.ylabel(r"$z/H$") # plt.ylim(-0.2, 0.78) # plt.xlim(-3.2, 3.2) if cb_orientation == "horizontal": plt.quiverkey(Q, 0.65, 0.26, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"}) elif cb_orientation == "vertical": plt.quiverkey(Q, 0.65, 0.055, 0.1, r"$0.1 U_\infty$", labelpos="E", coordinates="figure", fontproperties={"size": "small"}) plot_turb_lines() plot_exp_lines() ax = plt.axes() ax.set_aspect(2.0) plt.yticks(np.around(np.arange(-1.125, 1.126, 0.125), decimals=2)) plt.tight_layout() if show: plt.show() if save: plt.savefig("figures/meancontquiv"+savetype)
def Vector(plt, X, Y, data, parameter, label_flg = 0): # std_length,scaleの目安として、 # 流速の場合、1, 10.0 # 風応力の場合、0.1, 1.0 std_length = parameter[0] scale = parameter[1] intvl = parameter[2] qkeyx = parameter[3] qkeyy = parameter[4] data[np.where(abs(data)==np.inf)]=np.nan datax = data[0, :, :] datay = data[1, :, :] Q=plt.quiver(X[::intvl,::intvl],Y[::intvl,::intvl],datax[::intvl,::intvl],datay[::intvl,::intvl],angles='xy',scale=scale) if label_flg == 0: plt.quiverkey(Q, qkeyx, qkeyy, std_length, str(std_length)) return plt, Q
def DrawUV(self, m, micapsfile, clipborder, patch): if m is plt: if self.stream: plot = m.streamplot(self.X, self.Y, self.U, self.V, density=self.density, linewidth=self.linewidth, color=self.color, cmap=self.cmap ) if self.barbs: barbs = m.barbs(self.X, self.Y, self.U, self.V, length=self.length, barb_increments=dict(half=2, full=4, flag=20), sizes=dict(emptybarb=0)) pass else: # transform vectors to projection grid. uproj, vproj, xx, yy = \ m.transform_vector(self.U, self.V, self.x, self.y, self.barbsgrid[0], self.barbsgrid[1], returnxy=True, masked=True) if isinstance(self.color, np.ndarray): self.color = self.colorlist if self.stream: # plot = m.streamplot(xx, yy, uproj, vproj # , latlon=True # # density=self.density, # # linewidth=self.linewidth, # # color=self.color # # cmap=self.cmap # ) # now plot. Q = m.quiver(xx, yy, uproj, vproj, color=self.color, scale=self.scale) # make quiver key. speed = micapsfile.uv.markscalelength qk = plt.quiverkey(Q, 0.1, 0.1, speed, '%.0f m/s' % speed, labelpos='W') if self.barbs: barbs = m.barbs(xx, yy, uproj, vproj, length=self.length, barb_increments=dict(half=2, full=4, flag=20), sizes=dict(emptybarb=0), barbcolor='k', flagcolor='r', linewidth=0.5) if clipborder.path is not None and clipborder.using: from matplotlib.patches import FancyArrowPatch from matplotlib.collections import PolyCollection from matplotlib.lines import Line2D for artist in plt.gca().get_children(): if self.wholeclip: # from matplotlib.patches import Polygon if not isinstance(artist, Line2D): artist.set_clip_path(patch) else: from matplotlib.collections import LineCollection if isinstance(artist, FancyArrowPatch) or isinstance(artist, PolyCollection) or \ isinstance(artist, LineCollection): artist.set_clip_path(patch)
def _show_currentloop_field(): '''http://www.netdenizen.com/emagnettest/offaxis/?offaxisloop ''' from numpy import sqrt r = numpy.linspace(0.0, 3.0, 51) z = numpy.linspace(-1.0, 1.0, 51) R, Z = numpy.meshgrid(r, z) a = 1.0 V = 230 * sqrt(2.0) rho = 1.535356e-08 II = V/rho mu0 = pi * 4e-7 alpha = R / a beta = Z / a gamma = Z / R Q = (1+alpha)**2 + beta**2 k = sqrt(4*alpha / Q) from scipy.special import ellipk from scipy.special import ellipe Kk = ellipk(k**2) Ek = ellipe(k**2) B0 = mu0*II / (2*a) V = B0 / (pi*sqrt(Q)) \ * (Ek * (1.0 - alpha**2 - beta**2)/(Q - 4*alpha) + Kk) U = B0 * gamma / (pi*sqrt(Q)) \ * (Ek * (1.0 + alpha**2 + beta**2)/(Q - 4*alpha) - Kk) Q = plt.quiver(R, Z, U, V) plt.quiverkey( Q, 0.7, 0.92, 1e4, '$1e4$', labelpos='W', fontproperties={'weight': 'bold'}, color='r' ) plt.show() return
def quiver_3d(x,y,vx,vy,vz, ax=None, sep=1): import matplotlib.pyplot as plt if ax==None: ax = plt.figure().add_subplot(111) Q = ax.quiver(vy[::sep,::sep], vx[::sep,::sep], \ vz[::sep,::sep], pivot='mid') qk = plt.quiverkey(Q, 0.9, 0.95, 5, r'$5 \frac{m}{s}$', labelpos='E', coordinates='figure', fontproperties={'weight': 'bold'}) return ax
def plotVectorField(X,Y): plt.figure() Q = plt.quiver(X,Y) qk = plt.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) l,r,b,t = plt.axis() dx, dy = r-l, t-b plt.axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy]) plt.title('Minimal arguments, no kwargs') plt.show()
def add_quiver(self, vname, t, k, cff, step, scale): """ ベクトルの ax を返す関数 2015-11-08 作成 """ X, Y = self.get_xy('quiver', step) if 'u_eastward' in self.nc.variables.keys(): u = self.nc.variables['u_eastward'][t,k-1,::step,::step] v = self.nc.variables['v_northward'][t,k-1,::step,::step] else: u = self.nc.variables['u'][t,k-1,::step,::step] v = self.nc.variables['v'][t,k-1,::step,::step] ax = plt.gca() print X.shape, Y.shape, u.shape, v.shape if 'u_eastward' in self.nc.variables.keys(): Q = ax.quiver(X, Y, u, v, units='width', angles='xy', scale=scale) else: Q = ax.quiver(X[:-1,:], Y[:-1,:], u[:-1,:], v, units='width', angles='xy', scale=scale) plt.quiverkey(Q, 0.9, 0.1, 1.0/scale, '1 m/s') return Q
def plot_meancontquiv(): data = calcwake(t1=3.0) y_R = data["y/R"] z_H = data["z/H"] u = data["meanu"] v = data["meanv"] w = data["meanw"] xvorticity = data["xvorticity"] plt.figure(figsize=(7, 6.8)) # Add contours of mean velocity cs = plt.contourf(y_R, z_H, u, 20, cmap=plt.cm.coolwarm) cb = plt.colorbar(cs, shrink=1, extend='both', orientation='horizontal', pad=0.12) #ticks=np.round(np.linspace(0.44, 1.12, 10), decimals=2)) cb.set_label(r'$U/U_{\infty}$') plt.hold(True) # Make quiver plot of v and w velocities Q = plt.quiver(y_R, z_H, v, w, angles='xy', width=0.0022, edgecolor="none", scale=3.0) plt.xlabel(r'$y/R$') plt.ylabel(r'$z/H$') #plt.ylim(-0.2, 0.78) #plt.xlim(-3.2, 3.2) plt.xlim(-3.66, 3.66) plt.ylim(-1.22, 1.22) plt.quiverkey(Q, 0.8, 0.22, 0.1, r'$0.1 U_\infty$', labelpos='E', coordinates='figure', fontproperties={'size': 'small'}) plt.hlines(0.5, -1, 1, linestyles='solid', colors='gray', linewidth=3) plt.hlines(-0.5, -1, 1, linestyles='solid', colors='gray', linewidth=3) plt.vlines(-1, -0.5, 0.5, linestyles='solid', colors='gray', linewidth=3) plt.vlines(1, -0.5, 0.5, linestyles='solid', colors='gray', linewidth=3) ax = plt.axes() ax.set_aspect(2.0)
def reload_and_postprocess(int_u = None): # Creates a pretty picture =) if int_u is None: f = open('data/disk_compression/int_u_disk.pkl', 'rb') int_u = cPickle.load(f) x_pts = 20 y_pts = 22 x = np.linspace(-0.95, 0.95, x_pts) y = np.linspace(-0.95, 0.95, y_pts) X, Y = np.meshgrid(x, y) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) quiver_plot = plt.quiver(X, Y, int_u[0, :, :], int_u[1, :, :]) plt.quiverkey(quiver_plot, 0.60, 0.95, 0.05, r'0.05', labelpos='W') plt.xlabel('X') plt.ylabel('Y') plt.ylim([-1.1, 1.2]) plt.xlim([-1.1, 1.1]) circ = plt.Circle((0, 0), radius = 1.0, color = 'g', fill = False) ax.add_patch(circ) plt.title(r'Displacement vectors for a disk compressed in plane strain') plt.show()
def single_ax(ax, title, df): states = df.index num_sts = len(states) y = np.linspace(0, num_sts-1, num_sts) if case == 'vec': assert len(df.columns) == 1 x = [0] x_num_sts = 1 else: assert len(df.columns) == num_sts x = y x_num_sts = num_sts xx, yy = np.meshgrid(x, y) # print(xx) # print(yy) ax.set_xlim(-1, x_num_sts) ax.set_xticks(np.arange(0, x_num_sts)) ax.xaxis.tick_top() ax.set_ylim(-1, num_sts) ax.set_yticks(np.arange(0, num_sts)) ax.invert_yaxis() ax.set_aspect('equal', adjustable='box') ax.set_title(title, y=1.2) for st, nom in enumerate(states): ax.annotate(nom, xy=(x_num_sts+.25, st), annotation_clip=False) max_mag = np.max(np.absolute(df.values)) q = ax.quiver(xx, yy, df.values.real, df.values.imag, scale=max_mag, units='x') plt.quiverkey(q, 0, -2, max_mag, '= {:.2e}'.format(max_mag), labelpos='E', coordinates='data')
def PlotCurrentField(self,t,**kwargs): ''' PlotNewRiskmapFig - Produces a pretty picture from the RiskMapArray which is useful for providing a context within which to plot simulation results. Requires 'matplotlib<http://matplotlib.sourceforge.net>' pyplot functionality Args: t * t (int) : time index for the current data file that was loaded last. ''' if kwargs.has_key('max_depth'): max_depth = kwargs['max_depth'] else: max_depth = self.MaxDepth if kwargs.has_key('min_depth'): min_depth = kwargs['min_depth'] else: min_depth = self.MinDepth if kwargs.has_key('arrow_color'): arrow_color = kwargs['arrow_color'] else: arrow_color = 'k' d0,d1 = FindLowAndHighIndices(min_depth,self.depth) d1,d2 = FindLowAndHighIndices(max_depth,self.depth) print 'Averaging depths between indices %d and %d.'%(d0,d2) import matplotlib.pyplot as plt mapResX, mapResY = 20, 20 width,height = self.Width, self.Height #import pdb; pdb.set_trace() u2,v2 = self.u[:,d0:d2,:,:],self.v[:,d0:d2,:,:] u2ma,v2ma = np.ma.masked_array(u2,np.isnan(u2)),np.ma.masked_array(v2,np.isnan(v2)) u_mean, v_mean = u2ma.mean(axis=1).filled(np.nan),v2ma.mean(axis=1).filled(np.nan) #u_mean, v_mean = self.u.mean(axis=1),self.v.mean(axis=1) X,Y = np.linspace(0, width-0.5, mapResX), np.linspace(0, height-0.5, mapResY) aX,aY = np.meshgrid(X,Y) U,V = np.zeros((mapResX,mapResY)),np.zeros((mapResX,mapResY)) for j in range(0,mapResY): for i in range(0,mapResX): myLat,myLon = self.GetLatLonfromXY(X[i],Y[j]) if self.GetRisk(myLat, myLon, False )<0.9: U[j,i], V[j,i] = BilinearInterpolate(myLat,myLon,self.lat,self.lon,u_mean[int(t)]), \ BilinearInterpolate(myLat,myLon,self.lat,self.lon,v_mean[int(t)]) q = plt.quiver(aX,aY,U,V,scale=self.gVel*10,color=arrow_color) p = plt.quiverkey(q,1,height-0.5,self.gVel,"%.3f m/s"%(self.gVel),coordinates='data',color='k')
def plot_image(self, wavelength0, overplot=False, inclination=None, cmap=None, ax=None, axes_units='AU', polarization=False, polfrac=False, psf_fwhm=None, vmin=None, vmax=None, dynamic_range=1e6, colorbar=False): """ Show one image from an MCFOST model Parameters ---------- wavelength : string note this is a string!! in microns. TBD make it take strings or floats inclination : float Which inclination to plot, in the case where there are multiple images? If not specified, defaults to the median inclination of whichever RT mode inclinations were computed. overplot : bool Should we overplot on current axes (True) or display a new figure? Default is False cmap : matplotlib Colormap instance Color map to use for display. ax : matplotlib Axes instance Axis to display into. vmin, vmax : scalars Min and max values for image display. Always shows in log stretch dynamic_range : float default vmin is vmax/dynamic range. Default dynamic range is 1e6. axes_units : str Units to label the axes in. May be 'AU', 'arcsec', 'deg', or 'pixels' psf_fwhm : float or None convolve with PSF of this FWHM? Default is None for no convolution colorbar : bool Also draw a colorbar To Do: * Add convolution with PSFs * Add coronagraphic occulters """ wavelength = self._standardize_wavelength(wavelength0) if inclination is None: inclination = self.parameters.inclinations[len( self.parameters.inclinations) / 2] if not overplot: if ax is None: plt.clf() else: plt.cla() if ax is None: ax = plt.gca() # Read in the data and select the image of imHDU = self.images[wavelength] inclin_index = utils.find_closest(self.parameters.inclinations, inclination) image = imHDU.data[0, 0, inclin_index, :, :] # Set up color mapping if cmap is None: from copy import deepcopy #cmap = plt.cm.gist_heat cmap = deepcopy(plt.cm.gist_gray) cmap.set_over('white') cmap.set_under('black') cmap.set_bad('black') if vmax is None: vmax = image.max() if vmin is None: vmin = vmax / dynamic_range norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax, clip=True) # calculate the display extent of the image # check if the image header has CDELT keywords, if so use those in preference to # the plate scale specified in the parameter file. # This will gracefully handle the case of the user overriding the default pixel # scale on the command line to MCFOST. cd1 = imHDU.header['CDELT1'] cd2 = imHDU.header['CDELT2'] pixelscale = np.asarray([cd1, cd2]) # in degrees if axes_units.lower() == 'deg': pass elif axes_units.lower() == 'arcsec': pixelscale *= 3600 elif axes_units.lower() == 'au': pixelscale *= 3600 * self.parameters.distance elif axes_units.lower() == 'pixels' or axes_units.lower() == 'pixel': pixelscale = np.ones(2) else: raise ValueError("Unknown unit for axes_units: " + axes_units) halfsize = (np.asarray(image.shape)) / 2 * pixelscale extent = [-halfsize[0], halfsize[0], -halfsize[1], halfsize[1]] # Optional: convolve with PSF if psf_fwhm is not None: raise NotImplementedError("This code not yet implemented") import optics #psf = optics.airy_2d(aperture=10.0, wavelength=1.6e-6, pixelscale=0.020, shape=(99,99)) psf = pyfits.getdata( '/Users/mperrin/Dropbox/AAS2013/models_pds144n/manual/keck_psf_tmp4.fits' ) from astropy.nddata import convolve convolved = convolve(image, psf, normalize_kernel=True) image = convolved if polfrac: ax = plt.subplot(121) # Display the image! ax = utils.imshow_with_mouseover(ax, image, norm=norm, cmap=cmap, extent=extent, origin='lower') ax.set_xlabel("Offset [{unit}]".format(unit=axes_units)) ax.set_ylabel("Offset [{unit}]".format(unit=axes_units)) ax.set_title("Image for " + wavelength + " $\mu$m") if polarization == True: # overplot polarization vectors # don't show every pixel's vectors: showevery = 5 imQ = imHDU.data[ 1, 0, inclin_index, :, :] * -1 #MCFOST sign convention requires flip for +Q = up imU = imHDU.data[ 2, 0, inclin_index, :, :] * -1 #MCFOST sign convention, ditto imQn = imQ / image imUn = imU / image polfrac_ar = np.sqrt(imQn**2 + imUn**2) theta = 0.5 * np.arctan2(imUn, imQn) + np.pi / 2 vecX = polfrac_ar * np.cos(theta) * -1 vecY = polfrac_ar * np.sin(theta) Y, X = np.indices(image.shape) Q = plt.quiver(X[::showevery, ::showevery], Y[::showevery, ::showevery], vecX[::showevery, ::showevery], vecY[::showevery, ::showevery], headwidth=0, headlength=0, headaxislength=0.0, pivot='middle', color='white') plt.quiverkey(Q, 0.85, 0.95, 0.5, "50% pol.", coordinates='axes', labelcolor='white', labelpos='E', fontproperties={'size': 'small'}) #, width=0.003) # ax = plt.subplot(152) # ax.imshow(imQn, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('Q') # ax = plt.subplot(153) # ax.imshow(imUn, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('U') # ax = plt.subplot(154) # ax.imshow(vecX, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('vecX') # ax = plt.subplot(155) # ax.imshow(vecY, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('vecY') # ax.colorbar() #plt.colorbar() if polfrac: # Display a 2nd panel showing the polarization fraction ax2 = plt.subplot(122) cmap2 = plt.cm.gist_heat cmap2 = plt.cm.jet cmap2.set_over('red') cmap2.set_under('black') cmap2.set_bad('black') ax2 = utils.imshow_with_mouseover(ax2, polfrac_ar, vmin=0, vmax=1, cmap=cmap2) ax2.set_title("Polarization fraction") cax = plt.axes([0.92, 0.25, 0.02, 0.5]) plt.colorbar(ax2.images[0], cax=cax, orientation='vertical') if colorbar == True: cb = plt.colorbar(mappable=ax.images[0]) cb.set_label("Intensity [$W/m^2/pixel$]")
pivot='mid', color='blue', #cmap = plt.cm.seismic ) # Main tweaks # Radius limits ax1.set_ylim(0, 4) # Radius Ticks ax1.set_yticks(np.linspace(0, 4, 5)) # Radius tick position in degrees ax1.set_rlabel_position(135) # Angle ticks ax1.set_xticks(np.linspace(0, 2.0 * np.pi, 17)[:-1]) # Additional tweaks plt.grid(True) plt.quiverkey(Quiver, 1.01, 1.01, 3, label='3 m/s', labelcolor='blue', labelpos='N', coordinates='axes') # plt.colorbar(Quiver) # plt.legend() - no label option, hence no legend plt.title('Polar Quiver Plots') plt.show()
def plot2dxy_vector(ufilename, vfilename, ttest=True, lvl=850): f, ax = plt.subplots(1, figsize=(16, 10)) #llon = 130; rlon = 230; blat = -25; tlat = 25 llon = 130 rlon = 230 blat = -55 tlat = 30 #draw map m = Basemap(ax=ax, llcrnrlon=85 + (llon - 180), llcrnrlat=18.5 + blat, urcrnrlon=85 + (rlon - 180), urcrnrlat=18.5 + tlat, resolution='c', projection='merc', lat_0=18.5, lon_0=85) m.drawcoastlines() parallels = np.arange(-90, 90, 15.) m.drawparallels(parallels, labels=[1, 0, 0, 0]) meridians = np.arange(0., 360., 15.) m.drawmeridians(meridians, labels=[0, 0, 0, 1]) #quiver on top if ttest: u_da_raw = xr.open_dataarray(ufilename + '.nc') v_da_raw = xr.open_dataarray(vfilename + '.nc') u_da_sig = xr.open_dataarray(ufilename + '_ttest.nc') v_da_sig = xr.open_dataarray(vfilename + '_ttest.nc') Uraw = u_da_raw.values Vraw = v_da_raw.values Usig = u_da_sig.values Vsig = v_da_sig.values Usig[np.where(Vsig != 0.0)] = Uraw[np.where(Vsig != 0.0)] Vsig[np.where(Usig != 0.0)] = Vraw[np.where(Usig != 0.0)] u_da = u_da_raw v_da = v_da_raw u_da.values = Usig v_da.values = Vsig else: u_da = xr.open_dataarray(ufilename + '.nc') v_da = xr.open_dataarray(vfilename + '.nc') u_comp = u_da.sel({ 'lv_ISBL0': lvl }, method='nearest').sel({ 'g4_lat_1': slice(tlat, blat), 'g4_lon_2': slice(llon, rlon) }) v_comp = v_da.sel({ 'lv_ISBL0': lvl }, method='nearest').sel({ 'g4_lat_1': slice(tlat, blat), 'g4_lon_2': slice(llon, rlon) }) x = u_comp.coords['g4_lon_2'].values - 180 + 85 y = u_comp.coords['g4_lat_1'].values + 18.5 x, dummy = m(x, x) dummy, y = m(y, y) U = u_comp.values V = v_comp.values #Q = m.quiver(x, y, U, V) Q = m.quiver(x[::3], y[::3], U[::3, ::3], V[::3, ::3], pivot='mid', units='inches', scale=75, scale_units='width', headwidth=5, headlength=2, headaxislength=5) qk = plt.quiverkey(Q, 0.9, 0.9, 2, '2 m/s', labelpos='E', coordinates='figure') #bounding box and center x, y = m([75, 95, 95, 75, 75], [10, 10, 27, 27, 10]) m.plot(x, y, 'r-', lw=2.5) x, y = m([85], [18.5]) m.plot(x, y, 'ro', ms=5) if ttest: ax.set_title('{}: {} mb, ttest'.format(ufilename, lvl)) else: ax.set_title('{}: {} mb'.format(ufilename, lvl)) plt.tight_layout(pad=4)
def plot(self, timedata=None, udata=None, vdata=None, ylabel=None, **kwargs): if kwargs['rotate'] != 0.0: print "rotating vectors" angle_offset_rad = np.deg2rad(kwargs['rotate']) udata = udata * np.cos(angle_offset_rad) + vdata * np.sin( angle_offset_rad) vdata = -1 * udata * np.sin(angle_offset_rad) + vdata * np.cos( angle_offset_rad) magnitude = np.sqrt(udata**2 + vdata**2) fig = plt.figure(1) ax2 = plt.subplot2grid((2, 1), (0, 0), colspan=1, rowspan=1) ax1 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1) # Plot u and v components # Plot quiver ax1.set_ylim(-1 * np.nanmax(magnitude), np.nanmax(magnitude)) fill1 = ax1.fill_between(timedata, magnitude, 0, color='k', alpha=0.1) # Fake 'box' to be able to insert a legend for 'Magnitude' p = ax1.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1)) leg1 = ax1.legend([p], ["Current magnitude [cm/s]"], loc='lower right') leg1._drawFrame = False # 1D Quiver plot q = ax1.quiver(timedata, 0, udata, vdata, color='r', units='y', scale_units='y', scale=1, headlength=1, headaxislength=1, width=0.04, alpha=.95) qk = plt.quiverkey(q, 0.2, 0.05, 25, r'$25 \frac{cm}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) # Plot u and v components ax1.set_xticklabels(ax1.get_xticklabels(), visible=True) ax2.set_xticklabels(ax2.get_xticklabels(), visible=True) ax1.axes.get_xaxis().set_visible(True) ax1.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5) ax1.set_ylabel("Velocity (cm/s)") ax2.plot(kwargs['timedata2'], kwargs['data2'][:, 0, 0, 0], 'k-', linewidth=1) ax2.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5) ax2.set_xlabel("Date (UTC)") ax2.set_ylabel("Salinity (PSU)") ax2.xaxis.set_major_locator(MonthLocator()) ax2.xaxis.set_minor_locator( MonthLocator(bymonth=range(1, 13), bymonthday=15)) ax2.xaxis.set_major_formatter(ticker.NullFormatter()) ax2.xaxis.set_minor_formatter(ticker.NullFormatter()) ax1.xaxis.set_major_locator(MonthLocator()) ax1.xaxis.set_minor_locator( MonthLocator(bymonth=range(1, 13), bymonthday=15)) ax1.xaxis.set_major_formatter(ticker.NullFormatter()) ax1.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax2.spines['bottom'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.xaxis.set_ticks_position('top') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('both') ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize) ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize) return plt, fig
var, lons_cyclic = addcyclic(var, lons) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) u, lons_cyclic = addcyclic(u, lons) u, lons_cyclic = shiftgrid(180., u, lons_cyclic, start=False) v, lons_cyclic = addcyclic(v, lons) v, lons_cyclic = shiftgrid(180., v, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lats) x, y = m(lon2d, lat2d) cs = m.contourf(x, y, var[:, :], values, extend='both') #cs1 = m.contour(x,y,var[:,:], # values,linewidths=0.2,colors='k', # linestyles='-') cs2 = m.quiver(x, y, u, v, scale=150, color='k') qk = plt.quiverkey(cs2, 1, 0.03, 10, r'10 m/s', labelpos='W') cmap = ncm.cmap('testcmap') cs.set_cmap(cmap) cbar = m.colorbar(cs, location='right', pad='10%', drawedges=True) cbar.set_ticks(barlim) cbar.set_ticklabels(map(str, barlim)) cbar.ax.tick_params(axis='x', size=.1) cbar.set_label(r'\textbf{925mb wind anomalies [m/s]}') fig.suptitle(r'\textbf{JAS 2007}') plt.savefig(directoryfigure + 'testwind.png', dpi=300) 'Completed: Script done!'
def main(dataDir, visit, title="", outputTxtFileName=None, showFwhm=False, minFwhm=None, maxFwhm=None, correctDistortion=False, showEllipticity=False, ellipticityDirection=False, showNdataFwhm=False, showNdataEll=False, minNdata=None, maxNdata=None, gridPoints=30, verbose=False): butler = dafPersist.ButlerFactory(mapper=hscSim.HscSimMapper( root=dataDir)).create() camera = butler.get("camera") if not (showFwhm or showEllipticity or showNdataFwhm or showNdataEll or outputTxtFileName): showFwhm = True # # Get a dict of cameraGeom::Ccd indexed by serial number # ccds = {} for raft in camera: for ccd in raft: ccd.setTrimmed(True) ccds[ccd.getId().getSerial()] = ccd # # Read all the tableSeeingMap files, converting their (x, y) to focal plane coordinates # xArr = [] yArr = [] ellArr = [] fwhmArr = [] paArr = [] aArr = [] bArr = [] e1Arr = [] e2Arr = [] elle1e2Arr = [] for tab in butler.subset("tableSeeingMap", visit=visit): # we could use tab.datasetExists() but it prints a rude message fileName = butler.get("tableSeeingMap_filename", **tab.dataId)[0] if not os.path.exists(fileName): continue with open(fileName) as fd: ccd = None for line in fd.readlines(): if re.search(r"^\s*#", line): continue fields = [float(_) for _ in line.split()] if ccd is None: ccd = ccds[int(fields[0])] x, y, fwhm, ell, pa, a, b = fields[1:8] x, y = ccd.getPositionFromPixel(geom.PointD(x, y)).getMm() xArr.append(x) yArr.append(y) ellArr.append(ell) fwhmArr.append(fwhm) paArr.append(pa) aArr.append(a) bArr.append(b) if len(fields) == 11: e1 = fields[8] e2 = fields[9] elle1e2 = fields[10] else: e1 = -9999. e2 = -9999. elle1e2 = -9999. e1Arr.append(e1) e2Arr.append(e2) elle1e2Arr.append(elle1e2) xArr = np.array(xArr) yArr = np.array(yArr) ellArr = np.array(ellArr) fwhmArr = np.array(fwhmArr) * 0.168 # arcseconds paArr = np.radians(np.array(paArr)) aArr = np.array(aArr) bArr = np.array(bArr) e1Arr = np.array(e1Arr) e2Arr = np.array(e2Arr) elle1e2Arr = np.array(elle1e2Arr) if correctDistortion: import lsst.afw.geom.ellipses as afwEllipses dist = camera.getDistortion() for i in range(len(aArr)): axes = afwEllipses.Axes(aArr[i], bArr[i], paArr[i]) if False: # testing only! axes = afwEllipses.Axes(1.0, 1.0, np.arctan2(yArr[i], xArr[i])) quad = afwGeom.Quadrupole(axes) quad = quad.transform( dist.computeQuadrupoleTransform(geom.PointD(xArr[i], yArr[i]), False)) axes = afwEllipses.Axes(quad) aArr[i], bArr[i], paArr[i] = axes.getA(), axes.getB( ), axes.getTheta() ellArr = 1 - bArr / aArr if len(xArr) == 0: gridPoints = 0 xs, ys = [], [] else: N = gridPoints * 1j extent = [min(xArr), max(xArr), min(yArr), max(yArr)] xs, ys = np.mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N] title = [ title, ] title.append("\n#") if outputTxtFileName: f = open(outputTxtFileName, 'w') f.write("# %s visit %s\n" % (" ".join(title), visit)) for x, y, ell, fwhm, pa, a, b, e1, e2, elle1e2 \ in zip(xArr, yArr, ellArr, fwhmArr, paArr, aArr, bArr, e1Arr, e2Arr, elle1e2Arr): f.write('%f %f %f %f %f %f %f %f %f %f\n' % (x, y, ell, fwhm, pa, a, b, e1, e2, elle1e2)) if showFwhm: title.append("FWHM (arcsec)") if len(xs) > 0: fwhmResampled = griddata(xArr, yArr, fwhmArr, xs, ys) plt.imshow(fwhmResampled.T, extent=extent, vmin=minFwhm, vmax=maxFwhm, origin='lower') plt.colorbar() if outputTxtFileName: ndataGrids = getNumDataGrids(xArr, yArr, fwhmArr, xs, ys) f = open(outputTxtFileName + '-fwhm-grid.txt', 'w') f.write("# %s visit %s\n" % (" ".join(title), visit)) for xline, yline, fwhmline, ndataline \ in zip(xs.tolist(), ys.tolist(), fwhmResampled.tolist(), ndataGrids): for xx, yy, fwhm, ndata in zip(xline, yline, fwhmline, ndataline): if fwhm is None: fwhm = -9999 f.write('%f %f %f %d\n' % (xx, yy, fwhm, ndata)) elif showEllipticity: title.append("Ellipticity") scale = 4 if ellipticityDirection: # we don't care about the magnitude ellArr = 0.1 u = -ellArr * np.cos(paArr) v = -ellArr * np.sin(paArr) if gridPoints > 0: u = griddata(xArr, yArr, u, xs, ys) v = griddata(xArr, yArr, v, xs, ys) x, y = xs, ys else: x, y = xArr, yArr Q = plt.quiver( x, y, u, v, scale=scale, pivot="middle", headwidth=0, headlength=0, headaxislength=0, ) keyLen = 0.10 if not ellipticityDirection: # we care about the magnitude plt.quiverkey(Q, 0.20, 0.95, keyLen, "e=%g" % keyLen, labelpos='W') if outputTxtFileName: ndataGrids = getNumDataGrids(xArr, yArr, ellArr, xs, ys) f = open(outputTxtFileName + '-ell-grid.txt', 'w') f.write("# %s visit %s\n" % (" ".join(title), visit)) # f.write('# %f %f %f %f %f %f %f\n' % (x, y, ell, fwhm, pa, a, b)) for xline, yline, uline, vline, ndataline \ in zip(x.tolist(), y.tolist(), u.tolist(), v.tolist(), ndataGrids): for xx, yy, uu, vv, ndata in zip(xline, yline, uline, vline, ndataline): if uu is None: uu = -9999 if vv is None: vv = -9999 f.write('%f %f %f %f %d\n' % (xx, yy, uu, vv, ndata)) elif showNdataFwhm: title.append("N per fwhm grid") if len(xs) > 0: ndataGrids = getNumDataGrids(xArr, yArr, fwhmArr, xs, ys) plt.imshow(ndataGrids, interpolation='nearest', extent=extent, vmin=minNdata, vmax=maxNdata, origin='lower') plt.colorbar() else: pass elif showNdataEll: title.append("N per ell grid") if len(xs) > 0: ndataGrids = getNumDataGrids(xArr, yArr, ellArr, xs, ys) plt.imshow(ndataGrids, interpolation='nearest', extent=extent, vmin=minNdata, vmax=maxNdata, origin='lower') plt.colorbar() else: pass # plt.plot(xArr, yArr, "r.") # plt.plot(xs, ys, "b.") plt.axes().set_aspect('equal') plt.axis([-20000, 20000, -20000, 20000]) def frameInfoFrom(filepath): with fits.open(filepath) as hdul: h = hdul[0].header 'object=ABELL2163 filter=HSC-I exptime=360.0 alt=62.11143274 azm=202.32265181 ' 'hst=(23:40:08.363-23:40:48.546)' return 'object=%s filter=%s exptime=%.1f azm=%.2f hst=%s' % \ (h['OBJECT'], h['FILTER01'], h['EXPTIME'], h['AZIMUTH'], h['HST']) title.insert( 0, frameInfoFrom( butler.get('raw_filename', { 'visit': visit, 'ccd': 0 })[0])) title.append(r'$\langle$FWHM$\rangle %4.2f$"' % np.median(fwhmArr)) plt.title("%s visit=%s" % (" ".join(title), visit), fontsize=9) return plt
def geoplot(data=None, lon=None, lat=None, **kw): '''Show 2D data in a lon-lat plane. Parameters ----------- data: array of shape (n_lat, n_lon), or [u_array, v_array]-like for (u,v) data or None(default) when only plotting the basemap. lon: n_lon length vector or None(default). lat: n_lat length vector or None(default). kw: dict parameters related to basemap or plot functions. Basemap related parameters: ---------------------------- basemap_kw: dict parameter in the initialization of a Basemap. proj or projection: map projection name (default='moll') popular projections: 'ortho', 'np'(='nplaea'), 'sp'(='splaea') and other projections given from basemap. lon_0: map center longitude (None as default). lat_0: map center latitude (None as default). lonlatcorner: (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat). boundinglat: latitude at the map out boundary (None as default). basemap_round or round: True(default) or False. fill_continents: bool value (False as default). continents_kw: dict parameter used in the Basemap.fillcontinents method. continents_color: color of continents ('0.33' as default). lake_color: color of lakes ('none' as default). ocean_color: color of ocean (None as default). coastlines_kw: dict parameter used in the Basemap.drawcoastlines method. coastlines_color: color of coast lines ('0.33' as default). gridOn: bool value (True as default). gridLabelOn: bool value (False as default). parallels_kw: dict parameters used in the Basemap.drawparallels method. parallels: parallels to be drawn (None as default). parallels_color: color of parallels ('0.5' as default). parallels_labels:[0,0,0,0] or [1,0,0,0]. meridians_kw: dict parameters used in the Basemap.drawmeridians method. meridians: meridians to be drawn (None as default). meridians_color: color of meridians (parallels_color as default). meridians_labels: [0,0,0,0] or [0,0,0,1]. lonlatbox: None or (lon_start, lon_end, lat_start, lat_end). lonlatbox_kw: dict parameters in the plot of lon-lat box. lonlatbox_color: General plot parameters: ------------------------- ax: axis object, default is plt.gca() plot_type: a string of plot type from ('pcolor', 'pcolormesh', 'imshow', 'contourf', 'contour', 'quiver', 'scatter') or None(default). cmap: pyplot colormap. clim: a tuple of colormap limit. levels: sequence, int or None (default=None) plot_kw: dict parameters used in the plot functions. Pcolor/Pcolormesh related parameters: ------------------------------- rasterized: bool (default is True). Imshow related parameters --------------------------- origin: 'lower' or 'upper'. extent: horizontal range. interpolation: 'nearest' (default) or 'bilinear' or 'cubic'. Contourf related parameters: ------------------------------- extend: 'both'(default). Contour related parameters: ---------------------------- label_contour: False(default) or True. Whether to label contours or not. colors: contour color (default is 'gray'). Quiver plot related parameters: -------------------------------- stride: stride along lon and lat. stride_lon: stride along lon. stride_lat: stride along lat. quiver_scale: quiver scale. quiver_color: quiver color. sparse_polar_grids: bool, default is True. quiver_kw: dict parameters used in the plt.quiver function. hide_qkey: bool value, whether to show the quiverkey plot. qkey_X: X parameter in the plt.quiverkey function (default is 0.85). qkey_Y: Y parameter in the plt.quiverkey function (default is 1.02). qkey_U: U parameter in the plt.quiverkey function (default is 2). qkey_label: label parameter in the plt.quiverkey function. qkey_labelpos: labelpos parameter in the plt.quiverkey function. qkey_kw: dict parameters used in the plt.quiverkey function. Scatter related parameters: ------------------------------ scatter_data: None(default) or (lonvec, latvec). Hatch plot related parameters: ---------------------------------- hatches: ['///'] is default. Colorbar related parameters: ------------------------------- hide_cbar: bool value, whether to show the colorbar. cbar_type: 'vertical'(shorten as 'v') or 'horizontal' (shorten as 'h'). cbar_extend: extend parameter in the plt.colorbar function. 'neither' as default here. cbar_size: default '2.5%' for vertical colorbar, '5%' for horizontal colorbar. cbar_pad: default 0.1 for vertical colorbar, 0.4 for horizontal colorbar. cbar_kw: dict parameters used in the plt.colorbar function. units: str long_name: str Returns -------- basemap object if only basemap is plotted. plot object if data is shown. ''' # target axis ax = kw.pop('ax', None) if ax is not None: plt.sca(ax) if isinstance(data, xr.DataArray): data_array = data.copy() data = data_array.values if np.any(np.isnan(data)): data = ma.masked_invalid(data) if lon is None: try: lonname = [ s for s in data_array.dims if s in ('lon', 'longitude', 'X') ][0] except IndexError: lonname = [s for s in data_array.dims if 'lon' in s][0] lon = data_array[lonname] if lat is None: try: latname = [ s for s in data_array.dims if s in ('lat', 'latitude', 'Y') ][0] except IndexError: latname = [s for s in data_array.dims if 'lat' in s][0] lat = data_array[latname] # guess data name try: data_name = data_array.attrs['long_name'] except KeyError: try: data_name = data_array.name except AttributeError: data_name = '' # guess data units try: data_units = data_array.attrs['units'] except KeyError: data_units = '' # copy the original data elif data is not None: try: data = data.copy() except: try: # data has two components(u,v) data = (data[0].copy(), data[1].copy()) except: pass if lon is not None: lon = lon.copy() if lat is not None: lat = lat.copy() # #### basemap parameters # basemap kw parameter basemap_kw = kw.pop('basemap_kw', {}) # projection # proj = kw.pop('proj', 'cyl') # proj = kw.pop('proj', 'moll') proj = kw.pop('proj', 'hammer') proj = kw.pop('projection', proj) # projection overrides the proj parameter # short names for nplaea and splaea projections if proj in ('npolar', 'polar', 'np'): proj = 'nplaea' elif proj in ('spolar', 'sp'): proj = 'splaea' # lon_0 lon_0 = kw.pop('lon_0', None) if lon_0 is None: if lon is not None: if np.isclose(np.abs(lon[-1] - lon[0]), 360): lon_0 = (lon[0] + lon[-2]) / 2.0 else: lon_0 = (lon[0] + lon[-1]) / 2.0 else: # dummy = np.linspace(0, 360, data.shape[1]+1)[0:-1] # lon_0 = ( dummy[0] + dummy[-1] )/2.0 lon_0 = 180 # elif proj in ('moll', 'cyl', 'hammer', 'robin'): # lon_0 = 180 # elif proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): # lon_0 = 0 else: # lon_0 is specified if lon is not None and proj in ('moll', 'cyl', 'hammer'): # correct the lon_0 so that it is at the edge of a grid box lon_0_data = (lon[0] + lon[-1]) / 2.0 d_lon = lon[1] - lon[0] d_lon_0 = lon_0 - lon_0_data lon_0 = float(int(d_lon_0 / d_lon)) * d_lon + lon_0_data # lat_0 lat_0 = kw.pop('lat_0', None) if lat_0 is None: if lat is not None: lat_0 = (lat[0] + lat[-1]) / 2.0 elif proj in ('ortho', ): lat_0 = 45 # lonlatcorner = (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat) lonlatcorner = kw.pop('lonlatcorner', None) if lonlatcorner is not None: llcrnrlon = lonlatcorner[0] urcrnrlon = lonlatcorner[1] llcrnrlat = lonlatcorner[2] urcrnrlat = lonlatcorner[3] else: llcrnrlon = None urcrnrlon = None llcrnrlat = None urcrnrlat = None llcrnrlon = basemap_kw.pop('llcrnrlon', llcrnrlon) urcrnrlon = basemap_kw.pop('urcrnrlon', urcrnrlon) llcrnrlat = basemap_kw.pop('llcrnrlat', llcrnrlat) urcrnrlat = basemap_kw.pop('urcrnrlat', urcrnrlat) if llcrnrlon is None and urcrnrlon is None and llcrnrlat is None and urcrnrlat is None: lonlatcorner = None else: lonlatcorner = (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat) # boundinglat boundinglat = kw.pop('boundinglat', None) if boundinglat is None: if proj in ('npstere', 'nplaea', 'npaeqd'): boundinglat = 30 elif proj in ('spstere', 'splaea', 'spaeqd'): boundinglat = -30 # basemap round: True or False if proj in ('npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): basemap_round = kw.pop('basemap_round', True) else: basemap_round = kw.pop('basemap_round', False) basemap_round = kw.pop('round', basemap_round) # base map proj = basemap_kw.pop('projection', proj) lon_0 = basemap_kw.pop('lon_0', lon_0) lat_0 = basemap_kw.pop('lat_0', lat_0) boundinglat = basemap_kw.pop('boundinglat', boundinglat) basemap_round = basemap_kw.pop('round', basemap_round) m = Basemap(projection=proj, lon_0=lon_0, lat_0=lat_0, boundinglat=boundinglat, round=basemap_round, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, **basemap_kw) # fill continents or plot coast lines fill_continents = kw.pop('fill_continents', False) if fill_continents: # use Basemap.fillcontinents method continents_kw = kw.pop('continents_kw', {}) continents_color = kw.pop('continents_color', '0.33') continents_color = continents_kw.pop('color', continents_color) lake_color = kw.pop('lake_color', 'none') lake_color = continents_kw.pop('lake_color', lake_color) m.fillcontinents(color=continents_color, lake_color=lake_color, **continents_kw) # else: draw_coastlines = kw.pop('draw_coastlines', not fill_continents) if draw_coastlines: # use Basemap.drawcoastlines method coastlines_kw = kw.pop('coastlines_kw', {}) coastlines_color = kw.pop('coastlines_color', '0.33') coastlines_color = coastlines_kw.pop('color', coastlines_color) coastlines_lw = kw.pop('coastlines_lw', 0.5) coastlines_lw = coastlines_kw.pop('lw', coastlines_lw) m.drawcoastlines(color=coastlines_color, linewidth=coastlines_lw, **coastlines_kw) ocean_color = kw.pop('ocean_color', None) if ocean_color is not None: m.drawmapboundary(fill_color=ocean_color) # parallels gridOn = kw.pop('gridOn', True) gridLabelOn = kw.pop('gridLabelOn', False) parallels_kw = kw.pop('parallels_kw', {}) # parallels = kw.pop('parallels', np.arange(-90,91,30)) parallels = kw.pop('parallels', None) parallels = parallels_kw.pop('parallels', parallels) parallels_color = kw.pop('parallels_color', '0.5') parallels_color = parallels_kw.pop('color', parallels_color) parallels_lw = kw.pop('parallels_lw', 0.5) parallels_lw = parallels_kw.pop('lw', parallels_lw) parallels_labels = kw.pop('parallels_labels', None) parallels_labels = parallels_kw.pop('labels', parallels_labels) if parallels_labels is None: if gridLabelOn: parallels_labels = [1, 0, 0, 0] else: parallels_labels = [0, 0, 0, 0] if parallels is not None: m.drawparallels(parallels, color=parallels_color, labels=parallels_labels, linewidth=parallels_lw, **parallels_kw) elif gridOn: m.drawparallels(np.arange(-90, 91, 30), color=parallels_color, linewidth=parallels_lw, labels=parallels_labels, **parallels_kw) # meridians meridians_kw = kw.pop('meridians_kw', {}) # meridians = kw.pop('meridians', np.arange(-180, 360, 30)) meridians = kw.pop('meridians', None) meridians = meridians_kw.pop('meridians', meridians) meridians_color = kw.pop('meridians_color', parallels_color) meridians_color = meridians_kw.pop('color', meridians_color) meridians_lw = kw.pop('meridians_lw', parallels_lw) meridians_lw = meridians_kw.pop('lw', meridians_lw) meridians_labels = kw.pop('meridians_labels', None) meridians_labels = meridians_kw.pop('labels', meridians_labels) if meridians_labels is None: if gridLabelOn: if proj in ('npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): meridians_labels = [1, 1, 0, 0] elif proj in ('cyl', ): meridians_labels = [0, 0, 0, 1] else: meridians_labels = [0, 0, 0, 0] print('Meridian are not labeled.') else: meridians_labels = [0, 0, 0, 0] if meridians is not None: m.drawmeridians(meridians, color=meridians_color, labels=meridians_labels, linewidth=meridians_lw, **meridians_kw) elif gridOn: m.drawmeridians(np.arange(0, 360, 30), color=meridians_color, labels=meridians_labels, linewidth=meridians_lw, **meridians_kw) # lonlatbox lonlatbox = kw.pop('lonlatbox', None) if lonlatbox is not None: lonlon = np.array([ np.linspace(lonlatbox[0], lonlatbox[1], 100), lonlatbox[1] * np.ones(100), np.linspace(lonlatbox[1], lonlatbox[0], 100), lonlatbox[0] * np.ones(100) ]).ravel() latlat = np.array([ lonlatbox[2] * np.ones(100), np.linspace(lonlatbox[2], lonlatbox[3], 100), lonlatbox[3] * np.ones(100), np.linspace(lonlatbox[3], lonlatbox[2], 100) ]).ravel() lonlatbox_kw = kw.pop('lonlatbox_kw', {}) lonlatbox_color = kw.pop('lonlatbox_color', 'k') lonlatbox_color = lonlatbox_kw.pop('color', lonlatbox_color) m.plot(lonlon, latlat, latlon=True, color=lonlatbox_color, **lonlatbox_kw) # scatter scatter_data = kw.pop('scatter_data', None) if scatter_data is not None: # L = data.astype('bool') # marker_color = kw.pop('marker_color', 'k') # plot_obj = m.scatter(X[L], Y[L], color=marker_color, **kw) lonvec, latvec = scatter_data plot_obj = m.scatter(lonvec, latvec, **kw) # #### stop here and return the map object if data is None if data is None: return m # data prepare input_data_have_two_components = isinstance(data, tuple) \ or isinstance(data, list) if input_data_have_two_components: # input data is (u,v) or [u, v] where u, v are ndarray and two components of a vector assert len( data) == 2, 'quiver data must contain only two componets u and v' u = data[0].squeeze() v = data[1].squeeze() assert u.ndim == 2, 'u component data must be two dimensional' assert v.ndim == 2, 'v component data must be two dimensional' data = np.sqrt(u**2 + v**2) # calculate wind speed else: # input data is a ndarray data = data.squeeze() assert data.ndim == 2, 'Input data must be two dimensional!' # lon if lon is None: # lon = np.linspace(0, 360, data.shape[1]+1)[0:-1] # lon_edge = np.hstack(( # lon[0]*2 - lon[1], # lon, # lon[-1]*2 - lon[-2])) # lon_edge = ( lon_edge[:-1] + lon_edge[1:] )/2.0 lon_edge = np.linspace(lon_0 - 180, lon_0 + 180, data.shape[1] + 1) lon = (lon_edge[:-1] + lon_edge[1:]) / 2.0 else: # lon is specified if np.isclose(np.abs(lon[-1] - lon[0]), 360): # first and last longitude point to the same location: remove the last longitude lon = lon[:-1] data = data[:, :-1] if input_data_have_two_components: u = u[:, :-1] v = v[:, :-1] if (not np.isclose(lon_0, (lon[0] + lon[-1]) / 2.0) and proj in ('moll', 'cyl', 'hammer', 'robin')): # lon_0 not at the center of lon, need to shift grid lon_west_end = lon_0 - 180 + ( lon[1] - lon[0]) / 2.0 # longitude of west end # make sure the longitude of west end within the lon if lon_west_end < lon[0]: lon_west_end += 360 elif lon_west_end > lon[-1]: lon_west_end -= 360 data, lon_shift = shiftgrid(lon_west_end, data, lon, start=True) if input_data_have_two_components: u, lon_shift = shiftgrid(lon_west_end, u, lon, start=True) v, lon_shift = shiftgrid(lon_west_end, v, lon, start=True) lon = lon_shift if lon[0] < -180: lon += 360 elif lon[-1] >= 540: lon -= 360 lon_hstack = np.hstack( (2 * lon[0] - lon[1], lon, 2 * lon[-1] - lon[-2])) lon_edge = (lon_hstack[:-1] + lon_hstack[1:]) / 2.0 # lat if lat is None: lat_edge = np.linspace(-90, 90, data.shape[0] + 1) lat = (lat_edge[:-1] + lat_edge[1:]) / 2.0 else: lat_hstack = np.hstack( (2 * lat[0] - lat[1], lat, 2 * lat[-1] - lat[-2])) lat_edge = (lat_hstack[:-1] + lat_hstack[1:]) / 2.0 lat_edge[lat_edge > 90] = 90 lat_edge[lat_edge < -90] = -90 Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) Lon_edge, Lat_edge = np.meshgrid(lon_edge, lat_edge) X_edge, Y_edge = m(Lon_edge, Lat_edge) # ###### plot parameters # plot_type plot_type = kw.pop('plot_type', None) if plot_type is None: if input_data_have_two_components: plot_type = 'quiver' # elif ( proj in ('cyl',) # and lonlatcorner is None # ): # plot_type = 'imshow' # print('plot_type **** imshow **** is used.') elif proj in ('nplaea', 'splaea', 'ortho'): # pcolormesh has a problem for these projections plot_type = 'pcolor' print('plot_type **** pcolor **** is used.') else: plot_type = 'pcolormesh' print('plot_type **** pcolormesh **** is used.') # cmap cmap = kw.pop('cmap', None) if cmap is None: zz_max = data.max() zz_min = data.min() if zz_min >= 0: try: cmap = plt.get_cmap('viridis') except: cmap = plt.get_cmap('OrRd') elif zz_max <= 0: try: cmap = plt.get_cmap('viridis') except: cmap = plt.get_cmap('Blues_r') else: cmap = plt.get_cmap('RdBu_r') elif isinstance(cmap, str): cmap = plt.get_cmap(cmap) # clim parameters clim = kw.pop('clim', None) robust = kw.pop('robust', False) if clim is None: if isinstance(data, np.ma.core.MaskedArray): data1d = data.compressed() else: data1d = data.ravel() notNaNs = np.logical_not(np.isnan(data1d)) data1d = data1d[notNaNs] if robust: a = np.percentile(data1d, 2) b = np.percentile(data1d, 98) else: a = data1d.min() b = data1d.max() if a * b < 0: b = max(abs(a), abs(b)) a = -b clim = a, b # levels levels = kw.pop('levels', None) if levels is None: if plot_type in ('contour', 'contourf', 'contourf+'): a, b = clim levels = np.linspace(a, b, 11) elif isinstance(levels, int): if plot_type in ('contour', 'contourf', 'contourf+'): a, b = clim levels = np.linspace(a, b, levels) elif plot_type in ('pcolor', 'pcolormesh', 'imshow'): cmap = plt.get_cmap(cmap.name, levels - 1) else: # levels is a sequence if plot_type in ('pcolor', 'pcolormesh', 'imshow'): cmap = plt.get_cmap(cmap.name, len(levels) - 1) clim = min(levels), max(levels) # colorbar parameters if plot_type in ('pcolor', 'pcolormesh', 'contourf', 'contourf+', 'imshow'): cbar_type = kw.pop('cbar_type', 'vertical') cbar_kw = kw.pop('cbar_kw', {}) cbar_extend = kw.pop('cbar_extend', 'neither') cbar_extend = cbar_kw.pop('extend', cbar_extend) hide_cbar = kw.pop('hide_cbar', False) if cbar_type in ('v', 'vertical'): cbar_size = kw.pop('cbar_size', '2.5%') cbar_size = cbar_kw.pop('size', cbar_size) cbar_pad = kw.pop('cbar_pad', 0.1) cbar_pad = cbar_kw.pop('pad', cbar_pad) cbar_position = 'right' cbar_orientation = 'vertical' elif cbar_type in ('h', 'horizontal'): # cbar = hcolorbar(units=units) cbar_size = kw.pop('cbar_size', '5%') cbar_size = cbar_kw.pop('size', cbar_size) cbar_pad = kw.pop('cbar_pad', 0.4) cbar_pad = cbar_kw.pop('pad', cbar_pad) cbar_position = 'bottom' cbar_orientation = 'horizontal' # units in colorbar units = kw.pop('units', None) if units is None: try: units = data_units # input data is a DataArray except: units = '' # long_name in colorbar long_name = kw.pop('long_name', None) if long_name is None: try: long_name = data_name # if input data is a DataArray if long_name is None: long_name = '' except: long_name = '' # ###### plot # pcolor if plot_type in ('pcolor', ): rasterized = kw.pop('rasterized', True) plot_obj = m.pcolor(X_edge, Y_edge, data, cmap=cmap, rasterized=rasterized, **kw) # pcolormesh elif plot_type in ('pcolormesh', ): rasterized = kw.pop('rasterized', True) plot_obj = m.pcolormesh(X_edge, Y_edge, data, cmap=cmap, rasterized=rasterized, **kw) # imshow elif plot_type in ('imshow', ): if Y_edge[-1, 0] > Y_edge[0, 0]: origin = kw.pop('origin', 'lower') else: origin = kw.pop('origin', 'upper') extent = kw.pop( 'extent', [X_edge[0, 0], X_edge[0, -1], Y_edge[0, 0], Y_edge[-1, 0]]) interpolation = kw.pop('interpolation', 'nearest') plot_obj = m.imshow(data, origin=origin, cmap=cmap, extent=extent, interpolation=interpolation, **kw) # contourf elif plot_type in ('contourf', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) extend = kw.pop('extend', 'both') plot_obj = m.contourf(X, Y, data, extend=extend, cmap=cmap, levels=levels, **kw) # contour elif plot_type in ('contour', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) colors = kw.pop('colors', 'k') if colors is not None: cmap = None alpha = kw.pop('alpha', 0.5) plot_obj = m.contour(X, Y, data, cmap=cmap, colors=colors, levels=levels, alpha=alpha, **kw) label_contour = kw.pop('label_contour', False) if label_contour: plt.clabel(plot_obj, plot_obj.levels[::2], fmt='%.2G') # contourf + contour elif plot_type in ('contourf+', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) extend = kw.pop('extend', 'both') linewidths = kw.pop('linewidths', 1) plot_obj = m.contourf(X, Y, data, extend=extend, cmap=cmap, levels=levels, **kw) colors = kw.pop('colors', 'k') if colors is not None: cmap = None alpha = kw.pop('alpha', 0.5) m.contour(X, Y, data, cmap=cmap, colors=colors, alpha=alpha, levels=levels, linewidths=linewidths, **kw) # quiverplot elif plot_type in ('quiver', ): nGrids = kw.pop('nGrids', 50) nx = kw.pop('nx', nGrids) ny = kw.pop('ny', nGrids) stride = kw.pop('stride', 1) stride_lon = kw.pop('stride_lon', stride) stride_lat = kw.pop('stride_lat', stride) print(stride, stride_lon, stride_lat) if (stride != 1) or (stride_lon != 1) or ( stride_lat != 1 ): # compatible with old api, with stride, stride_lon, stride_lat controling quiver grids. To be obsolete. Use nGrids, nx, ny instead print('stride used') lon_ = lon[::stride_lon] # subset of lon lat_ = lat[::stride_lat] u_ = u[::stride_lat, ::stride_lon] v_ = v[::stride_lat, ::stride_lon] # sparse polar area sparse_polar_grids = kw.pop('sparse_polar_grids', True) if sparse_polar_grids: msk = np.empty(u_.shape) * np.nan for i in range(lat_.size): step = int(1. / np.cos(lat_[i] * np.pi / 180)) msk[i, 0::step] = 0 u_ += msk v_ += msk Lon_, Lat_ = np.meshgrid(lon_, lat_) u_rot, v_rot, X_, Y_ = m.rotate_vector(u_, v_, Lon_, Lat_, returnxy=True) else: # use nGrids, nx, ny to control the quiver grids if lon.max() > 180: u_, lon_ = shiftgrid(180., u, lon, start=False) v_, lon_ = shiftgrid(180., v, lon, start=False) else: u_ = u v_ = v lon_ = lon u_rot, v_rot, X_, Y_ = m.transform_vector(u_, v_, lon_, lat, nx, ny, returnxy=True) quiver_color = kw.pop('quiver_color', 'g') quiver_scale = kw.pop('quiver_scale', None) hide_qkey = kw.pop('hide_qkey', False) qkey_kw = kw.pop('qkey_kw', {}) qkey_X = kw.pop('qkey_X', 0.85) qkey_X = qkey_kw.pop('X', qkey_X) qkey_Y = kw.pop('qkey_Y', 1.02) qkey_Y = qkey_kw.pop('Y', qkey_Y) qkey_U = kw.pop('qkey_U', 2) qkey_U = qkey_kw.pop('U', qkey_U) qkey_label = kw.pop('qkey_label', '{:g} '.format(qkey_U) + units) qkey_label = qkey_kw.pop('label', qkey_label) qkey_labelpos = kw.pop('qkey_labelpos', 'W') qkey_labelpos = qkey_kw.pop('labelpos', qkey_labelpos) plot_obj = m.quiver(X_, Y_, u_rot, v_rot, color=quiver_color, scale=quiver_scale, **kw) if not hide_qkey: # quiverkey plot plt.quiverkey(plot_obj, qkey_X, qkey_Y, qkey_U, label=qkey_label, labelpos=qkey_labelpos, **qkey_kw) # hatch plot elif plot_type in ('hatch', 'hatches'): hatches = kw.pop('hatches', ['///']) plot_obj = m.contourf(X, Y, data, colors='none', hatches=hatches, extend='both', **kw) else: print( 'Please choose a right plot_type from ("pcolor", "contourf", "contour")!' ) # set clim if plot_type in ('pcolor', 'pcolormesh', 'imshow'): plt.clim(clim) # plot colorbar if plot_type in ('pcolor', 'pcolormesh', 'contourf', 'contourf+', 'imshow'): ax_current = plt.gca() divider = make_axes_locatable(ax_current) cax = divider.append_axes(cbar_position, size=cbar_size, pad=cbar_pad) cbar = plt.colorbar(plot_obj, cax=cax, extend=cbar_extend, orientation=cbar_orientation, **cbar_kw) if cbar_type in ('v', 'vertical'): # put the units on the top of the vertical colorbar cbar.ax.xaxis.set_label_position('top') cbar.ax.set_xlabel(units) cbar.ax.set_ylabel(long_name) elif cbar_type in ('h', 'horizontal'): # cbar.ax.yaxis.set_label_position('right') # cbar.ax.set_ylabel(units, rotation=0, ha='left', va='center') if long_name == '' or units == '': cbar.ax.set_xlabel('{}{}'.format(long_name, units)) else: cbar.ax.set_xlabel('{} [{}]'.format(long_name, units)) # remove the colorbar to avoid repeated colorbars if hide_cbar: cbar.remove() # set back the main axes as the current axes plt.sca(ax_current) return plot_obj
def draw_wind(m, lons, lats, model, dsize, background, location, lat, lon, RUNDATE, VALIDDATE, fxx, alpha, half_box, barb_thin, level='10 m', Fill=False, Shade=False, Barbs=False, Quiver=False, p95=False, Convergence=False, Vorticity=False): """ wind speed, wind barbs, wind quiver, Convergence, Divergence, shade high wind area, wind speed 95th percentile exceedance """ LEVEL = level.replace(' ', '') H_UV = get_hrrr_variable(RUNDATE, 'UVGRD:%s' % level, model=model, fxx=fxx, outDIR='/uufs/chpc.utah.edu/common/home/u0553130/temp/', verbose=False, value_only=False) if Fill: m.pcolormesh(lons, lats, H_UV['SPEED'], latlon=True, cmap=cm_wind(), vmin=0, vmax=60, zorder=2, alpha=alpha) cb = plt.colorbar(orientation='horizontal', pad=pad, shrink=shrink, extend='max') cb.set_label(r'%s Wind Speed (m s$\mathregular{^{-1}}$)' % level) if Shade: m.contourf(lons, lats, H_UV['SPEED'], levels=[10, 15, 20, 25], colors=('yellow', 'orange', 'red'), alpha=alpha, extend='max', zorder=3, latlon=True) cb = plt.colorbar(orientation='horizontal', shrink=shrink, pad=pad) cb.set_label(r'%s Wind Speed (ms$\mathregular{^{-1}}$)' % level) if Barbs or Quiver: if level == '10 m': color = 'k' elif level == '80 m': color = 'darkred' elif level == '500 mb': color = 'navy' else: color='k' # For small domain plots, trimming the edges significantly reduces barb plotting time if barb_thin < 20: subset = hrrr_subset(H_UV, half_box=half_box, lat=lat, lon=lon, verbose=False) else: subset = H_UV # Need to rotate vectors for map projection subset['UGRD'], subset['VGRD'] = m.rotate_vector(subset['UGRD'], subset['VGRD'], subset['lon'], subset['lat']) thin = barb_thin # Add to plot if Barbs: m.barbs(subset['lon'][::thin,::thin], subset['lat'][::thin,::thin], subset['UGRD'][::thin,::thin], subset['VGRD'][::thin,::thin], zorder=10, length=5.5, color=color, barb_increments={'half':2.5, 'full':5,'flag':25}, latlon=True) if Quiver: Q = m.quiver(subset['lon'][::thin,::thin], subset['lat'][::thin,::thin], subset['UGRD'][::thin,::thin], subset['VGRD'][::thin,::thin], zorder=10, units='inches', scale=40, color=color, latlon=True) qk = plt.quiverkey(Q, .92, 0.07, 10, r'10 s$^{-1}$', labelpos='S', coordinates='axes', color='magenta') qk.text.set_backgroundcolor('w') if p95: DIR = '/uufs/chpc.utah.edu/common/home/horel-group8/blaylock/HRRR_OSG/hourly30/UVGRD_%s/' % level.replace(' ', '_') FILE = 'OSG_HRRR_%s_m%02d_d%02d_h%02d_f00.h5' % (('UVGRD_%s' % level.replace(' ', '_'), VALIDDATE.month, VALIDDATE.day, VALIDDATE.hour)) with h5py.File(DIR+FILE, 'r') as f: spd_p95 = f["p95"][:] masked = H_UV['SPEED']-spd_p95 masked = np.ma.array(masked) masked[masked < 0] = np.ma.masked m.pcolormesh(lons, lats, masked, vmax=10, vmin=0, latlon=True, zorder=9, cmap='viridis', alpha=alpha) cb = plt.colorbar(orientation='horizontal', pad=pad, shrink=shrink) cb.set_label(r'%s Wind Speed exceeding 95th Percentile (m s$\mathregular{^{-1}}$)' % level) if Convergence or Vorticity: dudx, dudy = np.gradient(H_UV['UGRD'], 3, 3) dvdx, dvdy = np.gradient(H_UV['VGRD'], 3, 3) if Vorticity: vorticity = dvdx - dudy # Mask values vort = vorticity vort = np.ma.array(vort) vort[np.logical_and(vort < .05, vort > -.05) ] = np.ma.masked m.pcolormesh(lons, lats, vort, latlon=True, cmap='bwr', zorder=8, vmax=np.max(vort), vmin=-np.max(vort)) cb = plt.colorbar(orientation='horizontal', pad=pad, shrink=shrink) cb.set_label(r'%s Vorticity (s$\mathregular{^{-1}}$)' % level) if Convergence: convergence = dudx + dvdy # Mask values conv = convergence conv = np.ma.array(conv) conv[np.logical_and(conv < .05, conv > -.05) ] = np.ma.masked m.pcolormesh(lons, lats, conv, latlon=True, cmap='bwr', zorder=8, vmax=np.max(conv), vmin=-np.max(conv)) cb = plt.colorbar(orientation='horizontal', pad=pad, shrink=shrink) cb.set_label(r'%s Convergence (s$\mathregular{^{-1}}$)' % level)
v = np.ma.masked_where(np.abs(v) >= 999, v) x = f.variables['lon'][:] y = f.variables['lat'][:] vel = np.sqrt(u * u + v * v, where=(np.ma.getmaskarray(u) == False)) f.close() # - # ## Using colormap plt.figure() q = plt.quiver(x, y, u, v, vel, cmap=plt.cm.get_cmap('hsv'), scale=1000) q.set_clim(0, 50) cb = plt.colorbar(q) cb.set_label('Wind speed (m/s)') plt.show() # ## Using reference arrow # # Adding a reference arrow is done by using the [quiverkey](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.quiverkey.html) function plt.figure() q = plt.quiver(x, y, u, v, scale=1000) keys = plt.quiverkey(q, -131, 21, 70, 'Wind speed\n(50 m/s)', coordinates='data') plt.show()
def main(): source_all = [ 'f4\\W3Main', 'f5\\W3OH', 'f6\\L1448I', 'f7\\L1448N', 'f8\\L1448C', 'f9\\L1445', 'f10\\IRAS2A', 'f11\\SVS13', 'f12\\IRAS4A', 'f13\\IRAS4B', 'f14\\HH211', 'f15\\DGTau', 'f16\\L1551', 'f17\\L1527', 'f18\\CB26', 'f19\\OrionKL', 'f20\\MMS5', 'f20\\MMS6', 'f21\\FIR4', 'f23\\VLA1623', 'f24\\SerEmb17', 'f26\\SerEmb8', 'f27\\SerEmb6', 'f31\\B335', 'f32\\DR21OH', 'f33\\L1157', 'f34\\CB230' ] for ii in range(len(source_all)): try: tapol, scuba, hertz, sharp, Idust, xx, yy = take_data( source_all[ii]) Imax = max((Idust[0].data[0, 0, :, :]).flatten()) center = numpy.where(Idust[0].data[0, 0, :, :] == Imax) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(60, 20)) tap = range(len(tapol[0])) for i in range(len(tapol[0])): tap[i] = numpy.sqrt((tapol[0][i] - xx[center[0]])**2.0 + (tapol[1][i] - yy[center[1]])**2.0) ax1.scatter(tap, tapol[4], color='b', label='tapol') if scuba != []: scu = range(len(scuba[0])) for i in range(len(scuba[0])): scu[i] = numpy.sqrt((scuba[0][i] - xx[center[0]])**2.0 + (scuba[1][i] - yy[center[1]])**2.0) ax1.scatter(scu, scuba[3], color='r', label='scuba') if hertz != []: her = range(len(hertz[0])) for j in range(len(hertz[0])): her[j] = numpy.sqrt((hertz[0][j] - xx[center[0]])**2.0 + (hertz[1][j] - yy[center[1]])**2.0) ax1.scatter(her, hertz[3], color='y', label='hertz') if sharp != []: sha = range(len(sharp[0])) for k in range(len(sharp[0])): sha[k] = numpy.sqrt((sharp[0][k] - xx[center[0]])**2.0 + (sharp[1][k] - yy[center[1]])**2.0) ax1.scatter(sha, sharp[3], color='g', label='sharp') ax1.legend() xx_dust, yy_dust = a.sky_coor(Idust) ax2.contourf(Idust[0].data[0, 0, :, ::-1], extent=[ max(xx_dust), min(xx_dust), min(yy_dust), max(yy_dust) ], origin='lower', aspect='auto') # qv1 = ax2.quiver(-tapol[0],tapol[1],-tapol[4]*numpy.sin(tapol[6]*numpy.pi/180.0),tapol[4]*numpy.cos(tapol[6]*numpy.pi/180.0),headwidth=0,width=0.001,scale=100,color='w',pivot='middle') qv1 = ax2.quiver(-tapol[0], tapol[1], -tapol[2] * numpy.sin(tapol[6] * numpy.pi / 180.0), tapol[2] * numpy.cos(tapol[6] * numpy.pi / 180.0), headwidth=0, width=0.001, scale=100, color='w', pivot='middle') plt.quiverkey(qv1, 0.2, 0.2, 4, '4% Tapol') if scuba != []: qv2 = ax2.quiver( -scuba[0], scuba[1], -scuba[3] * numpy.sin(scuba[5] * numpy.pi / 180.0), scuba[3] * numpy.cos(scuba[5] * numpy.pi / 180.0), headwidth=0, width=0.001, color='r', scale=100, pivot='middle') plt.quiverkey(qv2, 0.2, 0.15, 4, '4% Scuba') if hertz != []: qv3 = ax2.quiver( -hertz[0], hertz[1], -hertz[3] * numpy.sin(hertz[5] * numpy.pi / 180.0), hertz[3] * numpy.cos(hertz[5] * numpy.pi / 180.0), headwidth=0, width=0.001, color='y', scale=100, pivot='middle') plt.quiverkey(qv3, 0.2, 0.1, 4, '4% Hertz') if sharp != []: qv4 = ax2.quiver( -sharp[0], sharp[1], -sharp[3] * numpy.sin(sharp[5] * numpy.pi / 180.0), sharp[3] * numpy.cos(sharp[5] * numpy.pi / 180.0), headwidth=0, width=0.001, color='g', scale=100, pivot='middle') plt.quiverkey(qv4, 0.2, 0.05, 4, '4% Sharp') if ii > 4: plt.savefig(source_all[ii][4:] + '_vector.png') plt.clf() else: plt.savefig(source_all[ii][3:] + '_vector.png') plt.clf() except: print 'except', source_all[ii]
def trend_all(): srfc = cnst.ERA_MONTHLY_SRFC_SYNOP pl = cnst.ERA_MONTHLY_PL_SYNOP storm_mean = 'aggs/gridsat_WA_-65_monthly_count_-40base_15-21UTC_1000km2.nc' storm_extreme = 'aggs/gridsat_WA_-70_monthly_count_5000km2.nc' mcs = cnst.GRIDSAT + storm_extreme fpath = cnst.network_data + 'figs/CLOVER/months/' box = [5, 55, -36, 0] # [-18,40,0,25] # da = xr.open_dataset(pl) da = u_darrays.flip_lat(da) da = da.sel(longitude=slice(box[0], box[1]), latitude=slice(box[2], box[3])) da2 = xr.open_dataset(srfc) da2 = u_darrays.flip_lat(da2) da2 = da2.sel(longitude=slice(box[0], box[1]), latitude=slice(box[2], box[3])) da3 = xr.open_dataset(mcs) da3 = da3.sel(lon=slice(box[0], box[1]), lat=slice(box[2], box[3])) lons = da.longitude lats = da.latitude press = da2['sp'] press = press[press['time.hour'] == 12] press.values = press.values * 1000 low_press = 850 up_press = 550 q = da['q'].sel(level=slice(low_press - 100, low_press)).mean('level') q = q[q['time.hour'] == 12] t2d = da2['t2m'] #['t2m'] #t2d = da['t'].sel(level=slice(800, 850)).mean('level') t2d = t2d[t2d['time.hour'] == 12] u600 = da['u'].sel(level=slice(up_press - 100, up_press)).mean('level') u600 = u600[u600['time.hour'] == 12] v600 = da['v'].sel(level=slice(up_press - 100, up_press)).mean('level') v600 = v600[v600['time.hour'] == 12] ws600 = u_met.u_v_to_ws_wd(u600, v600) u800 = da['u'].sel(level=slice(low_press - 100, low_press)).mean('level') u800 = u800[u800['time.hour'] == 12] v800 = da['v'].sel(level=slice(low_press - 100, low_press)).mean('level') v800 = v800[v800['time.hour'] == 12] shear_u = u600 - u800 #u600- shear_v = v600 - v800 # v600- ws_shear = u_met.u_v_to_ws_wd(shear_u.values, shear_v.values) ws_600 = t2d.copy(deep=True) ws_600.name = 'ws' ws_600.values = ws600[0] shear = t2d.copy(deep=True) shear.name = 'shear' shear.values = ws_shear[0] u6 = u800 v6 = v800 # wind vectors q.values = q.values * 1000 grid = t2d.salem.grid.regrid(factor=0.25) t2 = t2d # grid.lookup_transform(t2d) tir = grid.lookup_transform(da3['tir']) grid = grid.to_dataset() tir = xr.DataArray(tir, coords=[da3['time'], grid['y'], grid['x']], dims=['time', 'latitude', 'longitude']) months = [ (11, 1), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] #, 2,3,10]#[(12,2)]#[1,2,3,4,5,6,7,8,9,10,11,12]# #,2,3,11,12]#[(12,2)]#[1,2,3,4,5,6,7,8,9,10,11,12]# #,2,3,11,12] dicm = {} dicmean = {} for m in months: method = 'mk' if type(m) == int: m = [m] sig = True t2trend, t2mean = calc_trend(t2, m, method=method, sig=sig, hour=12, wilks=False) #hour=12, t2_mean = t2mean.mean(axis=0) tirtrend, tirmean = calc_trend(tir, m, method=method, sig=sig, wilks=False) tirm_mean = tirmean.mean(axis=0) qtrend, qmean = calc_trend(q, m, method=method, sig=sig, hour=12, wilks=False) #hour=12, q_mean = qmean.mean(axis=0) sheartrend, shearmean = calc_trend(shear, m, method=method, sig=sig, hour=12, wilks=False) #hour=12, shear_mean = shearmean.mean(axis=0) u6trend, u6mean = calc_trend(u6, m, method=method, sig=sig, hour=12, wilks=False) #hour=12, u6_mean = u6mean.mean(axis=0) v6trend, v6mean = calc_trend(v6, m, method=method, sig=sig, hour=12, wilks=False) #hour=12, v6_mean = v6mean.mean(axis=0) t2trend_unstacked = t2trend * 10. # warming over decade qtrend_unstacked = qtrend * 10. # warming over decade sheartrend_unstacked = sheartrend * 10. # warming over decade u6trend_unstacked = u6trend * 10 v6trend_unstacked = v6trend * 10 tirtrend_unstacked = ( (tirtrend.values) * 10. / tirm_mean.values) * 100. tirtrend_out = xr.DataArray(tirtrend_unstacked, coords=[grid['y'], grid['x']], dims=['latitude', 'longitude']) tirmean_out = xr.DataArray(tirm_mean, coords=[grid['y'], grid['x']], dims=['latitude', 'longitude']) dicm[m[0]] = tirtrend_out dicmean[m[0]] = tirmean_out t_da = t2trend_unstacked q_da = qtrend_unstacked s_da = sheartrend_unstacked ti_da = tirtrend_unstacked if len(m) == 1: fp = fpath + 'trend_synop_-70C5000_trend_' + str( m[0]).zfill(2) + '.png' else: fp = fpath + 'trend_synop_-70C5000_trend_' + str( m[0]).zfill(2) + '-' + str(m[1]).zfill(2) + '.png' map = t2d.salem.get_map() f = plt.figure(figsize=(15, 8), dpi=300) # transform their coordinates to the map reference system and plot the arrows xx, yy = map.grid.transform(shear.longitude.values, shear.latitude.values, crs=shear.salem.grid.proj) xx, yy = np.meshgrid(xx, yy) #Quiver only every 7th grid point u = u6trend_unstacked.values[1::2, 1::2] v = v6trend_unstacked.values[1::2, 1::2] #Quiver only every 7th grid pointtr uu = u6_mean.values[1::2, 1::2] vv = v6_mean.values[1::2, 1::2] xx = xx[1::2, 1::2] yy = yy[1::2, 1::2] ax1 = f.add_subplot(221) map.set_data(t_da.values, interp='linear') # interp='linear' map.set_contour((t2_mean.values - 273.15).astype(np.float64), interp='linear', colors='k', linewidths=0.5, levels=[20, 23, 26, 29, 32, 35]) map.set_plot_params(levels=[ -0.5, -0.4, -0.3, -0.2, -0.1, -0.05, -0.02, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5 ], cmap='RdBu_r', extend='both') # levels=np.arange(-0.5,0.51,0.1), #map.set_contour((t2_mean.values).astype(np.float64), interp='linear', colors='k', linewidths=0.5, levels=np.linspace(800,925,8)) #map.set_plot_params(levels=[-0.5,-0.4,-0.3,-0.2,-0.1,-0.05,-0.02, 0.02,0.05,0.1,0.2,0.3,0.4,0.5], cmap='RdBu_r', extend='both') # levels=np.arange(-0.5,0.51,0.1), dic = map.visualize(ax=ax1, title='2m temperature trend | contours: mean T', cbar_title='K decade-1') qu = ax1.quiver(xx, yy, uu, vv, scale=40, width=0.002) # 80 qk = plt.quiverkey(qu, 0.4, 0.03, 4, '4 m s$^{-1}$', labelpos='E', coordinates='figure') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') ax2 = f.add_subplot(222) map.set_data(q_da.values, interp='linear') # interp='linear' map.set_contour((q_mean.values).astype(np.float64), interp='linear', colors='k', levels=[6, 8, 10, 12, 14, 16], linewidths=0.5) map.set_plot_params(levels=[ -0.4, -0.3, -0.2, -0.1, -0.05, -0.02, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4 ], cmap='RdBu', extend='both') # levels=np.arange(-0.5,0.51,0.1), dic = map.visualize( ax=ax2, title='800hPa Spec. humidity trend | contours: mean q', cbar_title='g kg-1 decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') ax3 = f.add_subplot(223) map.set_data(s_da.values, interp='linear') # interp='linear' map.set_contour(s_da.values, interp='linear', levels=np.arange(-7, 7, 8), cmap='Blues') map.set_plot_params(levels=[ -0.5, -0.4, -0.3, -0.2, -0.1, -0.05, -0.02, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5 ], cmap='RdBu_r', extend='both') # levels=np.arange(-0.5,0.51,0.1) map.visualize( ax=ax3, title='800-500hPa wind shear trend, mean 850hPa wind vector trends', cbar_title='m s-1 decade-1') qu = ax3.quiver(xx, yy, u, v, scale=40, width=0.002) # 80 qk = plt.quiverkey(qu, 0.4, 0.03, 4, '4 m s$^{-1}$', labelpos='E', coordinates='figure') ax4 = f.add_subplot(224) map.set_contour((tirm_mean.values).astype(np.float64), interp='linear', levels=[0.1, 0.5, 1, 2.5], colors='k', linewidths=0.5) ti_da[ti_da == 0] = np.nan map.set_data(ti_da) # coord = [18, 25, -28, -20] geom = shpg.box(coord[0], coord[2], coord[1], coord[3]) #map.set_geometry(geom, zorder=99, color='darkorange', linewidth=3, linestyle='--', alpha=0.3) map.set_plot_params( cmap='viridis', extend='both', levels=np.arange( 10, 41, 10)) # levels=np.arange(20,101,20) #np.arange(20,101,20) dic = map.visualize(ax=ax4, title='-65C cloud cover change | >1000km2 -40C', cbar_title='$\%$ decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') plt.tight_layout() plt.savefig(fp) plt.close('all') pkl.dump( dicm, open( cnst.network_data + 'data/CLOVER/saves/storm_frac_synop12UTC_SA.p', 'wb')) pkl.dump( dicmean, open( cnst.network_data + 'data/CLOVER/saves/storm_frac_mean_synop12UTC_SA.p', 'wb'))
pijd0 = 1 X, Y = np.meshgrid(np.arange(0, 5.2, step), np.arange(0, 4, step)) # others = [[1, 1], [1, 2], [2.732, 1], [2.732, 2]] # others = [[1, 1], [1+1.732/2, 1.5], [2.732, 1]] others = [[2, 2], [3, 2]] U = 0 V = 0 for robot in others: pijx = X - robot[0] pijy = Y - robot[1] pij0 = (pijx**2 + pijy**2)**0.5 # the norm of pij pij0 = np.where(pij0 < 1e-4, 1, pij0) tauij0 = 2 * (pij0**4 - pijd0**4) / pij0**3 U += tauij0 * pijx / pij0 V += tauij0 * pijy / pij0 U, V = saturate(U * K3, V * K3, 0.7) plt.figure() plt.title('Vector field') Q = plt.quiver(X, Y, U, V, units='width') qk = plt.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure') plt.axes().set_aspect('equal', 'datalim')
def show_image(wavelength, parfilename=None, par=None, dir="./", overplot=False, inclination=80, cmap=None, ax=None, polarization=False, polfrac=False, psf_fwhm=None, vmin=None, vmax=None): """ Show one image from an MCFOST model Parameters ---------- wavelength : string note this is a string!! in microns. TBD make it take strings or floats inclination : float Which inclination to plot, in the case where there are multiple images? For RT computations with just one, then this parameter is essentially ignored overplot : bool Should we overplot on current axes (True) or display a new figure? Default is False cmap : matplotlib Colormap instance Color map to use for display. ax : matplotlib Axes instance Axis to display into. vmin, vmax : scalars Min and max values for image display. Always shows in log stretch psf_fwhm : float or None convolve with PSF of this FWHM? Default is None for no convolution parfilename : string, optional par : dict, optional dir : string """ if not overplot: if ax is None: plt.clf() else: plt.cla() if ax is None: ax = plt.gca() if par is None: par = paramfiles.Paramfile(parfilename, dir) if cmap is None: cmap = plt.cm.gist_heat cmap = plt.cm.gist_gray cmap.set_over('white') cmap.set_under('black') cmap.set_bad('black') rt_im = fits.getdata(dir + os.sep + "data_" + wavelength + os.sep + "RT.fits.gz") inclin_index = _find_closest(par.im_inclinations, inclination) #print "using image %s, inc=%f" % ( str(inclin_index), par['im:inclinations'][inclin_index] ) #ax = plt.subplot(151) image = rt_im[0, 0, inclin_index, :, :] if vmax is None: #image.shape = image.shape[2:] # drop leading zero-length dimensions... vmax = image.max() if vmin is None: vmin = vmax / 1e8 norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax, clip=True) if psf_fwhm is not None: raise NotImplementedError("This code not yet implemented") import optics #psf = optics.airy_2d(aperture=10.0, wavelength=1.6e-6, pixelscale=0.020, shape=(99,99)) psf = pyfits.getdata( '/Users/mperrin/Dropbox/AAS2013/models_pds144n/manual/keck_psf_tmp4.fits' ) from astropy.nddata import convolve convolved = convolve(image, psf, normalize_kernel=True) image = convolved if polfrac: ax = plt.subplot(121) ax = utils.imshow_with_mouseover(ax, image, norm=norm, cmap=cmap) ax.set_xlabel("Offset [pix]") ax.set_ylabel("Offset [pix]") ax.set_title(wavelength + " $\mu$m") if polarization == True: # dont' show every pixel's vectors: showevery = 5 imQ = rt_im[ 1, 0, inclin_index, :, :] * -1 #MCFOST sign convention requires flip for +Q = up imU = rt_im[2, 0, inclin_index, :, :] * -1 #MCFOST sign convention imQn = imQ / image imUn = imU / image polfrac_ar = np.sqrt(imQn**2 + imUn**2) theta = 0.5 * np.arctan2(imUn, imQn) + np.pi / 2 vecX = polfrac_ar * np.cos(theta) * -1 vecY = polfrac_ar * np.sin(theta) Y, X = np.indices(image.shape) Q = plt.quiver(X[::showevery, ::showevery], Y[::showevery, ::showevery], vecX[::showevery, ::showevery], vecY[::showevery, ::showevery], headwidth=0, headlength=0, headaxislength=0.0, pivot='middle', color='white') plt.quiverkey(Q, 0.85, 0.95, 0.5, "50% pol.", coordinates='axes', labelcolor='white', labelpos='E', fontproperties={'size': 'small'}) #, width=0.003) # ax = plt.subplot(152) # ax.imshow(imQn, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('Q') # ax = plt.subplot(153) # ax.imshow(imUn, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('U') # ax = plt.subplot(154) # ax.imshow(vecX, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('vecX') # ax = plt.subplot(155) # ax.imshow(vecY, vmin=-1, vmax=1, cmap=matplotlib.cm.RdBu) # ax.set_title('vecY') # ax.colorbar() #plt.colorbar() if polfrac: ax2 = plt.subplot(122) cmap2 = plt.cm.gist_heat cmap2 = plt.cm.jet cmap2.set_over('red') cmap2.set_under('black') cmap2.set_bad('black') ax2 = imshow_with_mouseover(ax2, polfrac_ar, vmin=0, vmax=1, cmap=cmap2) ax2.set_title("Polarization fraction") cax = plt.axes([0.92, 0.25, 0.02, 0.5]) plt.colorbar(ax2.images[0], cax=cax, orientation='vertical')
bounds = np.linspace(np.min(anom_NDEFM_speed), np.max(anom_NDEFM_speed), 20) bounds = np.around(bounds, decimals=2) CF = map.contourf(x, y, anom_NDEFM_speed[:, :], 20, norm=MidpointNormalize(midpoint=0), cmap=plt.cm.RdYlBu_r) #plt.cm.rainbow cb = plt.colorbar(CF, orientation='horizontal', pad=0.05, shrink=0.8, boundaries=bounds) cb.set_label('m/s') Q = map.quiver(x[::2, ::2], y[::2, ::2], anom_NDEFM_u[::2, ::2], anom_NDEFM_v[::2, ::2], scale=150) plt.quiverkey(Q, 0.93, 0.05, 10, '10 m/s') ax.set_title('$Wind$ $Field$ $-$ $Winter$ $Anomalies$', size='15') #map.plot(P_TT_lon, P_TT_lat, marker='D', color='w') #map.plot(P_PP_lon, P_PP_lat, marker='D', color='w') #map.plot(P_PN_lon, P_PN_lat, marker='D', color='w') map.plot(TT_lon, TT_lat, marker=None, color='k') map.plot(PP_lon, PP_lat, marker=None, color='k') map.plot(PN_lon, PN_lat, marker=None, color='k') map.fillcontinents(color='white') plt.show()
def main(): # Plot diagnostics, model and pressure levels etc. to plot on for looping through plot_type='mean' plot_diags=['temp', 'sp_hum'] plot_levels = [925, 850, 700, 500] #plot_levels = [925] #experiment_ids = ['djznq', 'djzns', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] experiment_ids = ['dkjxq'] #experiment_id = 'djzny' p_levels = [1000, 950, 925, 850, 700, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10] ###### Unrotate global model data ############################## ######### Regrid to global, and difference ####### ############################################################################ ## Load global wind and orography fw_global = '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/djzn/djzny/30201_mean.pp' fo_global = '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/djzn/djzny/33.pp' u_global,v_global = iris.load(fw_global) oro_global = iris.load_cube(fo_global) # Unrotate global coordinates cs_glob = u_global.coord_system('CoordSystem') cs_glob_v = v_global.coord_system('CoordSystem') cs_glob_oro = oro_global.coord_system('CoordSystem') lat_g = u_global.coord('grid_latitude').points lon_g = u_global.coord('grid_longitude').points lat_g_oro = oro_global.coord('grid_latitude').points lon_g_oro = oro_global.coord('grid_longitude').points if cs_glob!=cs_glob_v: print 'Global model u and v winds have different poles of rotation' # Unrotate global winds if isinstance(cs_glob, iris.coord_systems.RotatedGeogCS): print ' Global Model - Winds - djzny - Unrotate pole %s' % cs_glob lons_g, lats_g = np.meshgrid(lon_g, lat_g) lons_g,lats_g = iris.analysis.cartography.unrotate_pole(lons_g,lats_g, cs_glob.grid_north_pole_longitude, cs_glob.grid_north_pole_latitude) lon_g=lons_g[0] lat_g=lats_g[:,0] for i, coord in enumerate (u_global.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_uglobal = i if coord.standard_name=='grid_longitude': lon_dim_coord_uglobal = i csur_glob=cs_glob.ellipsoid u_global.remove_coord('grid_latitude') u_global.remove_coord('grid_longitude') u_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob), lat_dim_coord_uglobal) u_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob), lon_dim_coord_uglobal) #print u_global v_global.remove_coord('grid_latitude') v_global.remove_coord('grid_longitude') v_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob), lat_dim_coord_uglobal) v_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob), lon_dim_coord_uglobal) #print v_global # Unrotate global model if isinstance(cs_glob_oro, iris.coord_systems.RotatedGeogCS): print ' Global Model - Orography - djzny - Unrotate pole %s - Winds and other diagnostics may have different number of grid points' % cs_glob_oro lons_go, lats_go = np.meshgrid(lon_g_oro, lat_g_oro) lons_go,lats_go = iris.analysis.cartography.unrotate_pole(lons_go,lats_go, cs_glob_oro.grid_north_pole_longitude, cs_glob_oro.grid_north_pole_latitude) lon_g_oro=lons_go[0] lat_g_oro=lats_go[:,0] for i, coord in enumerate (oro_global.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_og = i if coord.standard_name=='grid_longitude': lon_dim_coord_og = i csur_glob_oro=cs_glob_oro.ellipsoid oro_global.remove_coord('grid_latitude') oro_global.remove_coord('grid_longitude') oro_global.add_dim_coord(iris.coords.DimCoord(points=lat_g_oro, standard_name='grid_latitude', units='degrees', coord_system=csur_glob_oro), lat_dim_coord_og) oro_global.add_dim_coord(iris.coords.DimCoord(points=lon_g_oro, standard_name='grid_longitude', units='degrees', coord_system=csur_glob_oro), lon_dim_coord_og) ############################################################################### #################### Load global heights and temp/sp_hum ##################### f_glob_h = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/408_pressure_levels_interp_pressure_djzny_%s' % (plot_type) ###################################################################################### with h5py.File(f_glob_h, 'r') as i: mh = i['%s' % plot_type] mean_heights_global = mh[. . .] ###################################################################################### ## Loop through experiment id's ###################################################### for pl in plot_diags: plot_diag=pl f_glob_d = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/%s_pressure_levels_interp_djzny_%s' % (plot_diag, plot_type) with h5py.File(f_glob_d, 'r') as i: mg = i['%s' % plot_type] mean_var_global = mg[. . .] for experiment_id in experiment_ids: expmin1 = experiment_id[:-1] ############################################################################### #################### Load global heights and temp/sp_hum ##################### fname_h = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/408_pressure_levels_interp_pressure_%s_%s' % (experiment_id, plot_type) fname_d = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/%s_pressure_levels_interp_%s_%s' % (plot_diag, experiment_id, plot_type) # print fname_h # print fname_d # Height data file with h5py.File(fname_h, 'r') as i: mh = i['%s' % plot_type] mean_heights = mh[. . .] # print mean_heights.shape with h5py.File(fname_d, 'r') as i: mh = i['%s' % plot_type] mean_var = mh[. . .] # print mean_var.shape f_oro = '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/%s/%s/409.pp' % (expmin1, experiment_id) oro = iris.load_cube(f_oro) #print oro for i, coord in enumerate (oro.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_oro = i if coord.standard_name=='grid_longitude': lon_dim_coord_oro = i fu = '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/%s/%s/30201_mean.pp' % (expmin1, experiment_id) u_wind,v_wind = iris.load(fu) # Wind may have different number of grid points so need to do unrotate again for wind grid points lat_w = u_wind.coord('grid_latitude').points lon_w = u_wind.coord('grid_longitude').points p_levs = u_wind.coord('pressure').points lat = oro.coord('grid_latitude').points lon = oro.coord('grid_longitude').points cs_w = u_wind.coord_system('CoordSystem') cs = oro.coord_system('CoordSystem') if isinstance(cs_w, iris.coord_systems.RotatedGeogCS): print ' Wind - %s - Unrotate pole %s' % (experiment_id, cs_w) lons_w, lats_w = np.meshgrid(lon_w, lat_w) lons_w,lats_w = iris.analysis.cartography.unrotate_pole(lons_w,lats_w, cs_w.grid_north_pole_longitude, cs_w.grid_north_pole_latitude) lon_w=lons_w[0] lat_w=lats_w[:,0] csur_w=cs_w.ellipsoid for i, coord in enumerate (u_wind.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_uwind = i if coord.standard_name=='grid_longitude': lon_dim_coord_uwind = i u_wind.remove_coord('grid_latitude') u_wind.remove_coord('grid_longitude') u_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w),lat_dim_coord_uwind ) u_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w), lon_dim_coord_uwind) v_wind.remove_coord('grid_latitude') v_wind.remove_coord('grid_longitude') v_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w), lat_dim_coord_uwind) v_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w),lon_dim_coord_uwind ) if isinstance(cs, iris.coord_systems.RotatedGeogCS): print ' 409.pp - %s - Unrotate pole %s' % (experiment_id, cs) lons, lats = np.meshgrid(lon, lat) lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high)) lons,lats = iris.analysis.cartography.unrotate_pole(lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon_corner_u,lat_corner_u = iris.analysis.cartography.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) #lon_highu,lat_highu = iris.analysis.cartography.unrotate_pole(lon_high, lat_high, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon=lons[0] lat=lats[:,0] lon_low = lon_corner_u[0,0] lon_high = lon_corner_u[0,1] lat_low = lat_corner_u[0,0] lat_high = lat_corner_u[1,0] for i, coord in enumerate (oro.coords()): if coord.standard_name=='grid_latitude': lat_dim_coord_oro = i if coord.standard_name=='grid_longitude': lon_dim_coord_oro = i csur=cs.ellipsoid oro.remove_coord('grid_latitude') oro.remove_coord('grid_longitude') oro.add_dim_coord(iris.coords.DimCoord(points=lat, standard_name='grid_latitude', units='degrees', coord_system=csur), lat_dim_coord_oro) oro.add_dim_coord(iris.coords.DimCoord(points=lon, standard_name='grid_longitude', units='degrees', coord_system=csur), lon_dim_coord_oro) else: lons, lats = np.meshgrid(lon, lat) lons_w, lats_w = np.meshgrid(lon_w, lat_w) lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) ############## Regrid and Difference ################################# # Regrid Height and Temp/Specific humidity to global grid h_regrid = np.empty((len(lat_g_oro), len(lon_g_oro))) v_regrid = np.empty((len(lat_g_oro), len(lon_g_oro))) for p in plot_levels: ### Search for pressure level match s = np.searchsorted(p_levels[::-1], p) h_regrid = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_heights[:,:,-(s+1)].flatten() , (lats_go,lons_go),method='linear') v_regrid = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_var[:,:,-(s+1)].flatten() , (lats_go,lons_go),method='linear') # Difference heights plt_h = np.where(np.isnan(h_regrid), np.nan, h_regrid - mean_heights_global[:,:,-(s+1)]) #Difference temperature/specific humidity plt_v = np.where(np.isnan(v_regrid), np.nan, v_regrid - mean_var_global[:,:,-(s+1)]) # Set u,v for winds, linear interpolate to approx. 2 degree grid sc = np.searchsorted(p_levs, p) ##### Does not work on iris1.0 as on Leeds computers. Does work on later versions #u_interp = u_wind[sc,:,:] #v_interp = v_wind[sc,:,:]. #sample_points = [('grid_latitude', np.arange(lat_low,lat_high,2)), ('grid_longitude', np.arange(lon_low,lon_high,2))] #u = iris.analysis.interpolate.linear(u_interp, sample_points, extrapolation_mode='linear') #v = iris.analysis.interpolate.linear(v_interp, sample_points).data ##### Does work on Iris 1.0 # 2 degree lats lon lists for wind regridding on plot lat_wind_1deg = np.arange(lat_low,lat_high, 2) lon_wind_1deg = np.arange(lon_low,lon_high, 2) ### Regrid winds to global, difference, and then regrid to 2 degree spacing fl_la_lo = (lats_w.flatten(),lons_w.flatten()) # print u_wind[sc,:,:].data.flatten().shape u_wind_rg_to_glob = scipy.interpolate.griddata(fl_la_lo, u_wind[sc,:,:].data.flatten(), (lats_g, lons_g), method='linear') v_wind_rg_to_glob = scipy.interpolate.griddata(fl_la_lo, v_wind[sc,:,:].data.flatten(), (lats_g, lons_g), method='linear') u_w=u_wind_rg_to_glob-u_global[sc,:,:].data v_w=v_wind_rg_to_glob-v_global[sc,:,:].data #u_interp = u_wind[sc,:,:].data #v_interp = v_wind[sc,:,:].data lons_wi, lats_wi = np.meshgrid(lon_wind_1deg, lat_wind_1deg) fl_la_lo = (lats_g.flatten(),lons_g.flatten()) u = scipy.interpolate.griddata(fl_la_lo, u_w.flatten(), (lats_wi, lons_wi), method='linear') v = scipy.interpolate.griddata(fl_la_lo, v_w.flatten(), (lats_wi, lons_wi), method='linear') ####################################################################################### ### Plotting ######################################################################### #m_title = 'Height of %s-hPa level (m)' % (p) # Set pressure height contour min/max if p == 925: clev_min = -24. clev_max = 24. elif p == 850: clev_min = -24. clev_max = 24. elif p == 700: clev_min = -24. clev_max = 24. elif p == 500: clev_min = -24. clev_max = 24. else: print 'Contour min/max not set for this pressure level' # Set potential temperature min/max if p == 925: clevpt_min = -10. clevpt_max = 10. elif p == 850: clevpt_min = -3. clevpt_max = 3. elif p == 700: clevpt_min = -3. clevpt_max = 3. elif p == 500: clevpt_min = -3. clevpt_max = 3. else: print 'Potential temperature min/max not set for this pressure level' # Set specific humidity min/max if p == 925: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 850: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 700: clevsh_min = -0.0025 clevsh_max = 0.0025 elif p == 500: clevsh_min = -0.0025 clevsh_max = 0.0025 else: print 'Specific humidity min/max not set for this pressure level' #clevs_col = np.arange(clev_min, clev_max) clevs_lin = np.linspace(clev_min, clev_max, num=24) m =\ Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229) #x, y = m(lons, lats) x,y = m(lons_go,lats_go) print x.shape x_w,y_w = m(lons_wi, lats_wi) fig=plt.figure(figsize=(8,8)) ax = fig.add_axes([0.05,0.05,0.9,0.85], axisbg='#262626') m.drawcoastlines(color='#262626') m.drawcountries(color='#262626') m.drawcoastlines(linewidth=0.5) #m.fillcontinents(color='#CCFF99') m.drawparallels(np.arange(-80,81,10),labels=[1,1,0,0]) m.drawmeridians(np.arange(0,360,10),labels=[0,0,0,1]) cs_lin = m.contour(x,y, plt_h, clevs_lin,colors='#262626',linewidths=0.5) cmap=plt.cm.RdBu_r #cmap.set_bad('#262626', 1.) #cmap.set_over('#262626') #cmap.set_under('#262626') if plot_diag=='temp': plt_v = np.ma.masked_outside(plt_v, clevpt_max+20, clevpt_min-20) cs_col = m.contourf(x,y, plt_v, np.linspace(clevpt_min, clevpt_max), cmap=cmap, extend='both') cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%d') cbar.set_ticks(np.arange(clevpt_min,clevpt_max+2,2.)) cbar.set_ticklabels(np.arange(clevpt_min,clevpt_max+2,2.)) cbar.set_label('K') plt.suptitle('Difference from global model (Model - global ) of Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10) elif plot_diag=='sp_hum': plt_v = np.ma.masked_outside(plt_v, clevsh_max+20, clevsh_min-20) cs_col = m.contourf(x,y, plt_v, np.linspace(clevsh_min, clevsh_max), cmap=cmap, extend='both') cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') cbar.set_label('kg/kg') plt.suptitle('Difference from global model (Model - Global Model ) of Height, Specific Humidity and Wind Vectors at %s hPa'% (p), fontsize=10) wind = m.quiver(x_w,y_w, u, v, scale=150,color='#262626' ) qk = plt.quiverkey(wind, 0.1, 0.1, 5, '5 m/s', labelpos='W') plt.clabel(cs_lin, fontsize=10, fmt='%d', color='black') #plt.title('%s\n%s' % (m_title, model_name_convert_title.main(experiment_id)), fontsize=10) plt.title('\n'.join(wrap('%s' % (model_name_convert_title.main(experiment_id)), 80)), fontsize=10) #plt.show() if not os.path.exists('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s' % (experiment_id, plot_diag)): os.makedirs('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s' % (experiment_id, plot_diag)) plt.savefig('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s/geop_height_difference_120LAM_%shPa_%s_%s.png' % (experiment_id, plot_diag, p, experiment_id, plot_diag), format='png', bbox_inches='tight')
def plot_timeseries(dat, met, float): f, ax = plt.subplots(6, 1, sharex=True) if float != '7782b': met = met.sel(floatid=float) met['tau'] = np.sqrt(met.tx**2 + met.ty**2) met.tx.plot(ax=ax[0], label=r'$\tau_x$') met.ty.plot(ax=ax[0], label=r'$\tau_y$') met.tau.plot(ax=ax[0], label=r'$\tau$') ax[0].legend() ax[0].set_xlabel(None) ax[0].set_ylabel(r'wind stress [Nm$-2$]') met = met.resample(time='9h', skipna=True).mean() quiveropts = dict(headlength=0, headwidth=1, scale_units='y', scale=1, color='k') qv = ax[1].quiver(met.time.values, np.zeros(met.time.shape), met.tx, met.ty,met.tau, **quiveropts) plt.quiverkey(qv, 0.9, 0.8, 0.5, '0.5 Nm$^{-2}$', coordinates='axes') ax[1].set_xlabel(None) ax[1].set_ylabel(r'wind stress vectors') ax[1].set_ylim(-1,1) dat.mld.plot(ax=ax[2], label=r'mld (0.03kgm$^{-3}$ from $\rho_{10m}$)') ax[2].legend() ax[2].set_xlabel(None) ax[2].set_ylabel('Mixed layer depth [m]') dat.hke.plot(ax=ax[3],marker='.',lw=0, label='total hke') dat.hke_lowpass.plot(ax=ax[3],marker='.',lw=0, label='lowpass hke') dat.hke_resid.plot(ax=ax[3], label='resid hke') dat.hke_ni.plot(ax=ax[3], label='ni hke') ax[3].legend() ax[3].set_xlabel(None) ax[3].set_ylabel('HKE [m$^2$s$^2$]') dat.dHKEdt_total.pipe(np.abs).pipe(np.log10).plot(ax=ax[4], lw=0, marker='.', label='total dhke/dt') dat.dHKEdt_lowpass.pipe(np.abs).pipe(np.log10).plot(ax=ax[4], lw=0, marker='.', label='lowpass dhke/dt') dat.dHKEdt_resid.pipe(np.abs).pipe(np.log10).plot(ax=ax[4], marker='.', label='resid dhke/dt') dat.dHKEdt_ni.pipe(np.abs).pipe(np.log10).plot(ax=ax[4], marker='.', label='ni dhke/dt') ax[4].legend() ax[4].set_xlabel(None) ax[4].set_ylabel(r'$\frac{\partial HKE}{\partial t}$ [m$^2$s$^3$]') dat.eps.pipe(np.abs).pipe(np.log10).plot(ax=ax[5], marker='.', lw=0.1, label=r'$log_{10}(\epsilon)$') # ax[7].set_ylim(-8,0) ax[5].legend() ax[5].set_xlabel(None) ax[5].set_ylabel(r'$\epsilon$ [m$^2$s$^3$]') ax[-1].set_xlim(dat.mld.time.values.min(), dat.mld.time.values.max()) plt.tight_layout() plt.subplots_adjust(hspace=0.1) plt.savefig(f'figures/storms/nov152017/{float:s}.pdf') plt.close()
def plot_uv(ds, grd, block=2): # Radius of the Earth in metres r = 6.371e6 # Degrees to radians conversion factor deg2rad = np.pi / 180 # Side length of blocks to average vectors over (can't plot vector at every # single point or the plot will be way too crowded) lon = grd.lon_rho.values lat = grd.lat_rho.values u = ds.ubar.values v = ds.vbar.values angle = np.zeros(np.shape(lon)) u_rho, v_rho = rotate_vector_roms(u, v, angle) speed = np.sqrt(np.square(u_rho) + np.square(v_rho)) #print('initialize and fill up the arrays') numy = np.size(lon, 0) #530 numx = np.size(lon, 1) #630 x = np.arange(numx) y = np.arange(numy) xmesh, ymesh = np.meshgrid(x, y) #print(numx,numy,x,y) # Average x, y, u_circ, and v_circ over block x block intervals # Calculate number of blocks size0 = int(np.ceil(numy / float(block))) size1 = int(np.ceil(numx / float(block))) # Set up arrays for averaged fields x_block = np.ma.empty([size0, size1]) y_block = np.ma.empty([size0, size1]) u_block = np.ma.empty([size0, size1]) v_block = np.ma.empty([size0, size1]) # Set up arrays containing boundary indices posn0 = list(np.arange(0, numy, block)) posn0.append(numy) posn1 = list(np.arange(0, numx, block)) posn1.append(numx) #print(posn0,posn1) # Double loop to average each block (can't find a more efficient way to do # this) for j in np.arange(size0): for i in np.arange(size1): start0 = posn0[j] end0 = posn0[j + 1] start1 = posn1[i] end1 = posn1[i + 1] x_block[j, i] = np.mean(xmesh[start0:end0, start1:end1]) y_block[j, i] = np.mean(ymesh[start0:end0, start1:end1]) u_block[j, i] = np.mean(u_rho[start0:end0, start1:end1]) v_block[j, i] = np.mean(v_rho[start0:end0, start1:end1]) # Make the plot fig, ax0 = plt.subplots(1, figsize=(15, 10)) speedP = ax0.pcolormesh(xmesh, ymesh, speed * 100, vmin=0, vmax=10, cmap=cmo.speed) plt.colorbar(speedP, ax=ax0) # Add vectors for each block quiverP = ax0.quiver(x_block, y_block, u_block, v_block, pivot="mid", color='black', scale_units='xy', scale=0.01) plt.quiverkey(quiverP, 0.75, 0.99, 0.1, r'$10 \frac{cm}{s}$', labelpos='E', coordinates='figure') ax0.set_title('Mean barotropic velocity (cm/s)', fontsize=16) ax0.set_aspect('equal') ax0.axis('off') print('test') return fig
def plotear(lllat, urlat, lllon, urlon, dist_lat, dist_lon, Lon, Lat, mapa, bar_min, bar_max, unds, titulo, path, C_T='k', wind=False, mapa_u=None, mapa_v=None): # lllat (low-left-lat) : float con la latitud de la esquina inferior izquierda # urlat (uper-right-lat) : float con la latitud de la esquina superior derecha # lllon (low-left-lon) : float con la longitud de la esquina inferior izquierda en coordenas negativas este # urlon (uper-right-lon) : float con la longitud de la esquina superior derecha en coordenas negativas este # dist_lat : entero que indica cada cuanto dibujar las lineas de los paralelos # dist_lon : entero que indica cada cuanto dibujar las lineas de los meridianos # Lon : array de numpy con las longitudes del mapa a plotearse en coordenadas negativas este # Lat : array de numpy con las longitudes del mapa a plotearse # mapa : array de numpy 2D a plotearse con contourf # bar_min : mínimo valor del mapa a plotearse # bar_max : máximo valor del mapa a plotearse # unds : string de las unidades de la variable que se va a plotear # titulo : string del titulo que llevará el mapa # path : 'string de la dirección y el nombre del archivo que contendrá la figura a generarse' # wind : boolean que diga si se quiere pintar flechas de viento (corrientes), donde True es que sí se va a hacer # mapa_u : array de numpay 2D con la componente en x de la velocidad y que será utilizado para pintar las flechas. Este tomara algun valor siempre y cuando wind=True # mapa_v : array de numpay 2D con la componente en y de la velocidad y que será utilizado para pintar las flechas. Este tomara algun valor siempre y cuando wind=True # return : gráfica o mapa fig = plt.figure(figsize=(8, 8), edgecolor='W', facecolor='W') ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) map = Basemap(projection='merc', llcrnrlat=lllat, urcrnrlat=urlat, llcrnrlon=lllon, urcrnrlon=urlon, resolution='i') map.drawcoastlines(linewidth=0.8) map.drawcountries(linewidth=0.8) map.drawparallels(np.arange(lllat, urlat, dist_lat), labels=[1, 0, 0, 1]) map.drawmeridians(np.arange(lllon, urlon, dist_lon), labels=[1, 0, 0, 1]) lons, lats = np.meshgrid(Lon, Lat) x, y = map(lons, lats) bounds = np.linspace(bar_min, bar_max, 20) bounds = np.around(bounds, decimals=2) if wind == False: CF1 = map.contourf(x, y, mapa, 20, norm=MidpointNormalize(midpoint=0), cmap=plt.cm.viridis, levels=bounds, extend='max') #plt.cm.rainbow , plt.cm.RdYlBu_r CF2 = map.contourf(x, y, mapa, 20, norm=MidpointNormalize(midpoint=0), cmap=plt.cm.viridis, levels=bounds, extend='min') #plt.cm.rainbow, plt.cm.RdYlBu_r else: CF1 = map.contourf(x, y, mapa, 20, cmap=plt.cm.rainbow, levels=bounds, extend='max') #plt.cm.rainbow , plt.cm.RdYlBu_r CF2 = map.contourf(x, y, mapa, 20, cmap=plt.cm.rainbow, levels=bounds, extend='min') #plt.cm.rainbow, plt.cm.RdYlBu_r cb1 = plt.colorbar(CF1, orientation='horizontal', pad=0.05, shrink=0.8, boundaries=bounds) cb1.set_label(unds) ax.set_title(titulo, size='15', color=C_T) if wind == True: Q = map.quiver(x[::2, ::2], y[::2, ::2], mapa_u[::2, ::2], mapa_v[::2, ::2], scale=20) plt.quiverkey(Q, 0.93, 0.05, 2, '2 m/s') #map.fillcontinents(color='white') plt.savefig(path + '.png', bbox_inches='tight', dpi=300) plt.close('all')
def corr_box(): srfc = cnst.ERA_MONTHLY_SRFC_SYNOP pl = cnst.ERA_MONTHLY_PL_SYNOP mcs = cnst.GRIDSAT + 'aggs/gridsat_WA_-65_monthly_count_-40base_15-21UTC_1000km2.nc' # -70count fpath = cnst.network_data + 'figs/CLOVER/months/' dicm = pkl.load( open( cnst.network_data + 'data/CLOVER/saves/storm_frac_synop12UTC_SA.p', 'rb')) dicmean = pkl.load( open( cnst.network_data + 'data/CLOVER/saves/storm_frac_mean_synop12UTC_SA.p', 'rb')) # mcsbox = cnst.GRIDSAT + 'aggs/SAboxWest_meanT-40_1000km2.nc' # box_13W-13E-4-8N_meanT-50_from5000km2.nc' # mcs_temp = xr.open_dataset(mcsbox) # mcs_temp = mcs_temp['tir'] box = [5, 55, -36, 0] #[-18,55,-35,35]#[-10,55,-35,0] da = xr.open_dataset(pl) da = u_darrays.flip_lat(da) da = da.sel(longitude=slice(box[0], box[1]), latitude=slice(box[2], box[3])) # latitude=slice(36, -37)) da2 = xr.open_dataset(srfc) da2 = u_darrays.flip_lat(da2) da2 = da2.sel(longitude=slice(box[0], box[1]), latitude=slice(box[2], box[3])) # latitude=slice(36, -37)) da3 = xr.open_dataset(mcs) da3 = da3.sel(lon=slice(box[0], box[1]), lat=slice(box[2], box[3])) lons = da.longitude lats = da.latitude press = da2['sp'] press = press[press['time.hour'] == 12] press.values = press.values * 1000 low_press = 850 up_press = 550 q = da['q'].sel(level=slice(low_press - 50, low_press)).mean('level') q = q[q['time.hour'] == 12] t2d = da2['t2m'] #['t2m'] #t2d = da['t'].sel(level=slice(800, 850)).mean('level') t2d = t2d[t2d['time.hour'] == 12] u600 = da['u'].sel(level=slice(up_press - 50, up_press)).mean('level') u600 = u600[u600['time.hour'] == 12] v600 = da['v'].sel(level=slice(up_press - 50, up_press)).mean('level') v600 = v600[v600['time.hour'] == 12] ws600 = u_met.u_v_to_ws_wd(u600, v600) u800 = da['u'].sel(level=slice(low_press - 50, low_press)).mean('level') u800 = u800[u800['time.hour'] == 12] v800 = da['v'].sel(level=slice(low_press - 50, low_press)).mean('level') v800 = v800[v800['time.hour'] == 12] shear_u = u600 - u800 #u600- shear_v = v600 - v800 # v600- ws_shear = u_met.u_v_to_ws_wd(shear_u.values, shear_v.values) ws_600 = t2d.copy(deep=True) ws_600.name = 'ws' ws_600.values = ws600[0] shear = t2d.copy(deep=True) shear.name = 'shear' shear.values = ws_shear[0] q.values = q.values * 1000 tir = da3['tir'] tir = t2d.salem.lookup_transform(tir) def array_juggling(data, month, hour=None): m = month if hour is not None: if len(month) > 1: data = data[((data['time.month'] >= month[0]) | (data['time.month'] <= month[1])) & (data['time.hour'] == hour) & (data['time.year'] >= 1983) & (data['time.year'] <= 2017)] else: data = data[(data['time.month'] == month[0]) & (data['time.hour'] == hour) & (data['time.year'] >= 1983) & (data['time.year'] <= 2017)] else: if len(month) > 1: data = data[((data['time.month'] >= month[0]) | (data['time.month'] <= month[1])) & (data['time.year'] >= 1983) & (data['time.year'] <= 2017)] else: data = data[(data['time.month'] == month[0]) & (data['time.year'] >= 1983) & (data['time.year'] <= 2017)] data_years = data.groupby('time.year').mean(axis=0) data_mean = data.mean(axis=0) # diff = xr.DataArray(data_years.values[1::, :, :] - data_years.values[0:-1, :, :], # coords=[data_years.year[1::], data.latitude, data.longitude], dims=['year','latitude', 'longitude'] ) diff = xr.DataArray( data_years.values, coords=[data_years.year, data.latitude, data.longitude], dims=['year', 'latitude', 'longitude']) # unstack back to lat lon coordinates return diff, data_mean def corr(a, b, bsingle=None, c_box=None): ds = xr.Dataset() ds['pval'] = a.copy(deep=True).sum('year') * np.nan ds['r'] = a.copy(deep=True).sum('year') * np.nan ds['slope'] = a.copy(deep=True).sum('year') * np.nan corr_box = c_box if bsingle: bb = b else: bb = b.sel(latitude=slice(corr_box[2], corr_box[3]), longitude=slice( corr_box[0], corr_box[1])).mean(dim=['latitude', 'longitude']) for lat in a.latitude.values: for lon in a.longitude.values: aa = a.sel(latitude=lat, longitude=lon) if bsingle: r, p = stats.pearsonr(aa.values, bb) pf = np.polyfit(aa.values, bb, 1) else: r, p = stats.pearsonr(aa.values, bb.values) pf = np.polyfit(aa.values, bb.values, 1) slope = pf[0] if (np.nansum(aa.values == 0) >= 10): p = np.nan r = np.nan ds['r'].loc[{'latitude': lat, 'longitude': lon}] = r ds['pval'].loc[{'latitude': lat, 'longitude': lon}] = p ds['slope'].loc[{'latitude': lat, 'longitude': lon}] = slope return ds box_dic = { 1: [16, 30, -25, -20], 2: [12, 28, -10, 3], 3: [16, 25, -23, -18], 4: [16, 25, -23, -18], 10: [14, 28, -15, -5], 11: [16, 30, -20, -10], 12: [16, 30, -22, -12], (11, 1): [18, 30, -23, -18] } months = [(11, 1), 2, 3, 10] for m in months: c_box = box_dic[m] if type(m) == int: m = [m] t2diff, t2year = array_juggling(t2d, m) # qdiff, qyear = array_juggling(q, m) #, hour=12 shdiff, sheyear = array_juggling(shear, m) #, hour=12 vdiff, vyear = array_juggling(v800, m) # , hour=12 udiff, uyear = array_juggling(u800, m) # , hour=12 tirdiff, tiryear = array_juggling(tir, m) # average frequency change #mcs_month = mcs_temp[mcs_temp['time.month'] == m] # meanT box average change #tirdiff = mcs_month.values[1::]-mcs_month.values[0:-1] bs = False try: qcorr = corr(qdiff, tirdiff, bsingle=bs, c_box=c_box) except: continue shearcorr = corr(shdiff, tirdiff, bsingle=bs, c_box=c_box) tcorr = corr(t2diff, tirdiff, bsingle=bs, c_box=c_box) dicm[m[0]].values[dicm[m[0]].values == 0] = np.nan print('plot') if len(m) == 1: fp = fpath + 'corr_mid_-70C_synop_-50base_linear_850T' + str( m[0]).zfill(2) + '.png' else: fp = fpath + 'corr_mid_-70C_synop_-50base_linear_850T' + str( m[0]).zfill(2) + '-' + str(m[1]).zfill(2) + '.png' map = shear.salem.get_map() xx, yy = map.grid.transform(shear.longitude.values, shear.latitude.values, crs=shear.salem.grid.proj) xx, yy = np.meshgrid(xx, yy) # Quiver only every 7th grid point u = uyear.values[1::2, 1::2] v = vyear.values[1::2, 1::2] xx = xx[1::2, 1::2] yy = yy[1::2, 1::2] #ipdb.set_trace() f = plt.figure(figsize=(15, 8), dpi=350) ax1 = f.add_subplot(221) map.set_data(tcorr['r'], interp='linear') # interp='linear' map.set_contour(t2year - 273.15, interp='linear', levels=np.arange(24, 37, 4), colors='k', linewidths=0.5) map.set_plot_params( cmap='RdBu_r', extend='both', levels=[-0.7, -0.6, -0.5, -0.4, -0.3, 0.3, 0.4, 0.5, 0.6, 0.7]) # levels=np.arange(-0.5,0.51,0.1), dic = map.visualize(ax=ax1, title='2m temperature corr. | contours: mean T', cbar_title='K decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') ax2 = f.add_subplot(222) map.set_data(qcorr['r'], interp='linear') # interp='linear' map.set_contour(qyear, interp='linear', levels=np.arange(5, 19, 3), colors='k', linewidths=0.5) map.set_plot_params( cmap='RdBu_r', extend='both', levels=[-0.7, -0.6, -0.5, -0.4, -0.3, 0.3, 0.4, 0.5, 0.6, 0.7]) # levels=np.arange(-0.5,0.51,0.1), dic = map.visualize( ax=ax2, title='800hPa Spec. humidity corr. | contours: mean q', cbar_title='g kg-1 decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') ax3 = f.add_subplot(223) # map.set_data(shearcorr['r'], interp='linear') # interp='linear' # map.set_plot_params(cmap='RdBu_r', extend='both', levels=[-0.7,-0.6,-0.5,-0.4, -0.3,0.3,0.4,0.5,0.6,0.7]) #map.set_contour(sheyear, interp='linear', levels=np.arange(-10,1,6), colors='k', linewidths=0.5) map.set_data(tcorr['r'], interp='linear') # interp='linear' map.set_plot_params( cmap='RdBu_r', extend='both', levels=[-0.7, -0.6, -0.5, -0.4, -0.3, 0.3, 0.4, 0.5, 0.6, 0.7]) qu = ax3.quiver(xx, yy, u, v, scale=50, width=0.002) qk = plt.quiverkey(qu, 0.4, 0.03, 4, '4 m s$^{-1}$', labelpos='E', coordinates='figure') # levels=np.arange(-0.5,0.51,0.1) dic = map.visualize( ax=ax3, title='800-500hPa wind shear corr., mean 500hPa wind vectors', cbar_title='m s-1 decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') ax4 = f.add_subplot(224) map.set_contour(dicmean[m[0]], interp='linear', levels=[0.1, 0.5, 1, 2.5], colors='k', linewidths=0.5) map.set_data(dicm[m[0]]) # #ax4.axhspan(-26,18) #[15,25,-26,-18] coord = c_box #[17, 25, -28, -22] geom = shpg.box(coord[0], coord[2], coord[1], coord[3]) map.set_geometry(geom, zorder=99, color='darkorange', linewidth=3, linestyle='--', alpha=0.3) # ax4.axvline(x=25, ymin=-26, ymax=-18) # ax4.axhline(y=-26, xmin=15, xmax=25) # ax4.axhline(y=-18, xmin=15, xmax=25) map.set_plot_params( cmap='viridis', extend='both', levels=np.arange( 10, 41, 10)) # levels=np.arange(20,101,20) #np.arange(20,101,20) dic = map.visualize(ax=ax4, title='-65C cloud cover change | >1000km2 -40C', cbar_title='$\%$ decade-1') contours = dic['contour'][0] plt.clabel(contours, inline=True, fontsize=7, fmt='%1.1f') plt.tight_layout() plt.savefig(fp) plt.close('all')
def plot(self): if self.filetype == 'geotiff': f, fname = tempfile.mkstemp() os.close(f) driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create(fname, self.latitude.shape[1], self.longitude.shape[0], 1, gdal.GDT_Float64) x = [self.longitude[0, 0], self.longitude[-1, -1]] y = [self.latitude[0, 0], self.latitude[-1, -1]] outRasterSRS = osr.SpatialReference() x, y = self.basemap(x, y) outRasterSRS.ImportFromProj4(self.basemap.proj4string) pixelWidth = (x[-1] - x[0]) / self.longitude.shape[0] pixelHeight = (y[-1] - y[0]) / self.latitude.shape[0] outRaster.SetGeoTransform( (x[0], pixelWidth, 0, y[0], 0, pixelHeight)) outband = outRaster.GetRasterBand(1) d = self.data.astype("Float64") ndv = d.fill_value outband.WriteArray(d.filled(ndv)) outband.SetNoDataValue(ndv) outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache() outRaster = None with open(fname, 'r', encoding="latin-1") as f: buf = f.read() os.remove(fname) return (buf, self.mime, self.filename.replace(".geotiff", ".tif")) # Figure size figuresize = list(map(float, self.size.split("x"))) fig = plt.figure(figsize=figuresize, dpi=self.dpi) ax = plt.gca() if self.scale: vmin = self.scale[0] vmax = self.scale[1] else: vmin = np.amin(self.data) vmax = np.amax(self.data) if self.compare: vmax = max(abs(vmax), abs(vmin)) vmin = -vmax c = self.basemap.imshow(self.data, vmin=vmin, vmax=vmax, cmap=self.cmap) if len(self.quiver_data) == 2: qx, qy = self.quiver_data qx, qy, x, y = self.basemap.rotate_vector(qx, qy, self.quiver_longitude, self.quiver_latitude, returnxy=True) quiver_mag = np.sqrt(qx**2 + qy**2) if self.quiver['magnitude'] != 'length': qx = qx / quiver_mag qy = qy / quiver_mag qscale = 50 else: qscale = None if self.quiver['magnitude'] == 'color': if self.quiver['colormap'] is None or \ self.quiver['colormap'] == 'default': qcmap = colormap.colormaps.get('speed') else: qcmap = colormap.colormaps.get(self.quiver['colormap']) q = self.basemap.quiver( x, y, qx, qy, quiver_mag, width=0.0035, headaxislength=4, headlength=4, scale=qscale, pivot='mid', cmap=qcmap, ) else: q = self.basemap.quiver( x, y, qx, qy, width=0.0025, headaxislength=4, headlength=4, scale=qscale, pivot='mid', ) if self.quiver['magnitude'] == 'length': unit_length = np.mean(quiver_mag) * 2 unit_length = np.round(unit_length, -int(np.floor(np.log10(unit_length)))) if unit_length >= 1: unit_length = int(unit_length) plt.quiverkey(q, .65, .01, unit_length, self.quiver_name.title() + " " + str(unit_length) + " " + utils.mathtext(self.quiver_unit), coordinates='figure', labelpos='E') if self.show_bathymetry: # Plot bathymetry on top cs = self.basemap.contour( self.longitude, self.latitude, self.bathymetry, latlon=True, linewidths=0.5, norm=LogNorm(vmin=1, vmax=6000), cmap=mcolors.LinearSegmentedColormap.from_list( 'transparent_gray', [(0, 0, 0, 0.5), (0, 0, 0, 0.1)]), levels=[100, 200, 500, 1000, 2000, 3000, 4000, 5000, 6000]) plt.clabel(cs, fontsize='xx-small', fmt='%1.0fm') if self.area and self.show_area: for a in self.area: polys = [] for co in a['polygons'] + a['innerrings']: coords = np.array(co).transpose() mx, my = self.basemap(coords[1], coords[0]) map_coords = list(zip(mx, my)) polys.append(Polygon(map_coords)) paths = [] for poly in polys: paths.append(poly.get_path()) path = concatenate_paths(paths) poly = PathPatch(path, fill=None, edgecolor='#ffffff', linewidth=5) plt.gca().add_patch(poly) poly = PathPatch(path, fill=None, edgecolor='k', linewidth=2) plt.gca().add_patch(poly) if self.names is not None and len(self.names) > 1: for idx, name in enumerate(self.names): x, y = self.basemap(self.centroids[idx].y, self.centroids[idx].x) plt.annotate( xy=(x, y), s=name, ha='center', va='center', size=12, # weight='bold' ) if len(self.contour_data) > 0: if (self.contour_data[0].min() != self.contour_data[0].max()): cmin, cmax = utils.normalize_scale(self.contour_data[0], self.contour_name, self.contour_unit) levels = None if self.contour.get('levels') is not None and \ self.contour['levels'] != 'auto' and \ self.contour['levels'] != '': try: levels = list( set([ float(xx) for xx in self.contour['levels'].split(",") if xx.strip() ])) levels.sort() except ValueError: pass if levels is None: levels = np.linspace(cmin, cmax, 5) cmap = self.contour['colormap'] if cmap is not None: cmap = colormap.colormaps.get(cmap) if cmap is None: cmap = colormap.find_colormap(self.contour_name) if not self.contour.get('hatch'): contours = self.basemap.contour(self.longitude, self.latitude, self.contour_data[0], latlon=True, linewidths=2, levels=levels, cmap=cmap) else: hatches = [ '//', 'xx', '\\\\', '--', '||', '..', 'oo', '**' ] if len(levels) + 1 < len(hatches): hatches = hatches[0:len(levels) + 2] self.basemap.contour(self.longitude, self.latitude, self.contour_data[0], latlon=True, linewidths=1, levels=levels, colors='k') contours = self.basemap.contourf(self.longitude, self.latitude, self.contour_data[0], latlon=True, colors=['none'], levels=levels, hatches=hatches, vmin=cmin, vmax=cmax, extend='both') if self.contour['legend']: handles, l = contours.legend_elements() labels = [] for i, lab in enumerate(l): if self.contour.get('hatch'): if self.contour_unit == 'fraction': if i == 0: labels.append( "$x \\leq {0: .0f}\\%$".format( levels[i] * 100)) elif i == len(levels): labels.append("$x > {0: .0f}\\%$".format( levels[i - 1] * 100)) else: labels.append( "${0:.0f}\\% < x \\leq {1:.0f}\\%$". format(levels[i - 1] * 100, levels[i] * 100)) else: if i == 0: labels.append("$x \\leq %.3g$" % levels[i]) elif i == len(levels): labels.append("$x > %.3g$" % levels[i - 1]) else: labels.append("$%.3g < x \\leq %.3g$" % (levels[i - 1], levels[i])) else: if self.contour_unit == 'fraction': labels.append("{0:.0%}".format(levels[i])) else: labels.append( "%.3g %s" % (levels[i], utils.mathtext(self.contour_unit))) ax = plt.gca() if self.contour_unit != 'fraction' and not \ self.contour.get('hatch'): contour_title = "%s (%s)" % (self.contour_name, utils.mathtext( self.contour_unit)) else: contour_title = self.contour_name leg = ax.legend(handles[::-1], labels[::-1], loc='lower left', fontsize='medium', frameon=True, framealpha=0.75, title=contour_title) leg.get_title().set_fontsize('medium') if not self.contour.get('hatch'): for legobj in leg.legendHandles: legobj.set_linewidth(3) # Map Info self.basemap.drawmapboundary(fill_color=(0.3, 0.3, 0.3), zorder=-1) self.basemap.drawcoastlines(linewidth=0.5) self.basemap.fillcontinents(color='grey', lake_color='dimgrey') def find_lines(values): if np.amax(values) - np.amin(values) < 1: return [values.mean()] elif np.amax(values) - np.amin(values) < 25: return np.round( np.arange(np.amin(values), np.amax(values), round(np.amax(values) - np.amin(values)) / 5)) else: return np.arange(round(np.amin(values), -1), round(np.amax(values), -1), 5) parallels = find_lines(self.latitude) meridians = find_lines(self.longitude) self.basemap.drawparallels(parallels, labels=[1, 0, 0, 0], color=(0, 0, 0, 0.5)) self.basemap.drawmeridians(meridians, labels=[0, 0, 0, 1], color=(0, 0, 0, 0.5), latmax=85) title = self.plotTitle if self.plotTitle is None or self.plotTitle == "": area_title = "\n".join(wrap(", ".join(self.names), 60)) + "\n" title = "%s %s %s, %s" % (area_title, self.variable_name.title(), self.depth_label, self.date_formatter(self.timestamp)) plt.title(title.strip()) ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) bar = plt.colorbar(c, cax=cax) bar.set_label( "%s (%s)" % (self.variable_name.title(), utils.mathtext(self.variable_unit)), fontsize=14) if self.quiver is not None and \ self.quiver['variable'] != '' and \ self.quiver['variable'] != 'none' and \ self.quiver['magnitude'] == 'color': bax = divider.append_axes("bottom", size="5%", pad=0.35) qbar = plt.colorbar(q, orientation='horizontal', cax=bax) qbar.set_label(self.quiver_name.title() + " " + utils.mathtext(self.quiver_unit), fontsize=14) fig.tight_layout(pad=3, w_pad=4) return super(MapPlotter, self).plot(fig)
index.append(i) #November index uc = u[index[yr]][0][:] #surface layer 0 eastward flow vc = v[index[yr]][0][:] #surface layer 0 northward flow uwse = uws[index[yr]][:] #eastward windstress vwsn = vws[index[yr]][:] #northward windstress xi = np.arange(gbox[0], gbox[1], gridscale) #region of interest yi = np.arange(gbox[2], gbox[3], gridscale) xb, yb, ub_mean, ub_median, ub_std, ub_num = sh_bindata(lonc, latc, uc, xi, yi) xb, yb, vb_mean, vb_median, vb_std, vb_num = sh_bindata(lonc, latc, vc, xi, yi) xxb, yyb = np.meshgrid(xb, yb) fig = plt.figure() ax1 = fig.add_subplot(211, aspect=1.3) Q = plt.quiver(xxb, yyb, ub_mean.T, vb_mean.T, scale=3.) #current vectors qk = plt.quiverkey(Q, 0.7, 0.12, .1, r'$.1m/s$', fontproperties={'weight': 'bold'}) ax1.plot(CL['lon'], CL['lat']) ax1.set_xlim([gbox[0], gbox[1]]) ax1.set_ylim([gbox[2], gbox[3]]) ax1.set_title(str(2014 + yr) + ' mean surface current') ax1.set_xticklabels('', visible=False) # shut off xticklabels xb, yb, uw_mean, uw_median, uw_std, uw_num = sh_bindata( lonc, latc, uwse, xi, yi) xb, yb, vw_mean, vw_median, vw_std, vw_num = sh_bindata( lonc, latc, vwsn, xi, yi) ax2 = fig.add_subplot(212, aspect=1.3) Q = plt.quiver(xxb, yyb, uw_mean.T, vw_mean.T, scale=3.) # wind stress vectors qk = plt.quiverkey(Q, 0.7,
df.tail() Let's take a look at our fake data. %matplotlib inline import matplotlib.pyplot as plt from oceans.plotting import stick_plot q = stick_plot([t.to_pydatetime() for t in df["time"]], df["u"], df["v"]) ref = 1 qk = plt.quiverkey( q, 0.1, 0.85, ref, f"{ref} m s$^{-1}$", labelpos="N", coordinates="axes" ) plt.xticks(rotation=70) `pocean.dsg` is relatively simple to use. The user must provide a DataFrame, like the one above, and a dictionary of attributes that maps to the data and adhere to the DSG conventions desired. Because we want the file to work seamlessly with ERDDAP we also added some ERDDAP specific attributes like `cdm_timeseries_variables`, and `subsetVariables`. attributes = { "global": { "title": "Fake mooring", "summary": "Vector current meter ADCP @ 10 m", "institution": "Restaurant at the end of the universe", "cdm_timeseries_variables": "station", "subsetVariables": "depth",
# create a figure, add an axes. fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.1, 0.7, 0.7]) # rotate wind vectors to map projection coordinates. # (also compute native map projections coordinates of lat/lon grid) # only do Northern Hemisphere. urot, vrot, x, y = m.rotate_vector(u[36:, :], v[36:, :], lons[36:, :], lats[36:, :], returnxy=True) # plot filled contours over map. cs = m.contourf(x, y, p[36:, :], 15, cmap=plt.cm.jet) # plot wind vectors over map. Q = m.quiver(x, y, urot, vrot) #or specify, e.g., width=0.003, scale=400) qk = plt.quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W') cax = plt.axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes. plt.colorbar(cax=cax) # draw colorbar plt.axes(ax) # make the original axes current again m.drawcoastlines() m.drawcountries() # draw parallels delat = 20. circles = np.arange(0.,90.+delat,delat).tolist()+\ np.arange(-delat,-90.-delat,-delat).tolist() m.drawparallels(circles, labels=[1, 1, 1, 1]) # draw meridians delon = 45. meridians = np.arange(-180, 180, delon) m.drawmeridians(meridians, labels=[1, 1, 1, 1]) plt.title('Surface Winds Winds and Pressure (lat-lon grid)', y=1.075)
'20170118.015_lp_2min-fitcal_2dVEF_001001', '20170118.017_lp_2min-fitcal_2dVEF_001001', '20170118.019_lp_2min-fitcal_2dVEF_001001', '20170118.021_lp_2min-fitcal_2dVEF_001001'] for runname in runnames: print runname d=io_utils.read_whole_h5file(runname+'.h5') plt.rcParams['figure.figsize']=10,10 plt.rcParams['font.size']=16 for r in range(d['/Fit2D']['DivE'].shape[0]): fig=plt.figure() div_clrs=plt.pcolormesh(d['/Grid']['x'][0,:],d['/Grid']['y'][0,:],d['/Fit2D']['DivE'][r,:,:],vmin=-1e-5,vmax=1e-5,cmap='RdBu_r') qv=plt.quiver(d['/Grid']['x'][0,:],d['/Grid']['y'][0,:],d['/Fit2D']['Ex'][r,:,:],d['/Fit2D']['Ey'][r,:,:],d['/Fit2D']['Emag'][r,:,:],scale=2500,cmap='bone_r') qk = plt.quiverkey(qv, 0.5, 0.875, 100, '100 mV/m', labelpos='E', coordinates='figure', fontproperties={'weight': 'bold'}) plt.title(datetime.datetime(1970,1,1)+datetime.timedelta(seconds=int(d['/Time']['UnixTime'][r,0]))) plt.xlabel('Mag Longitude') plt.ylabel('Mag Latitude') hc=plt.colorbar(div_clrs) hc.set_label('DivE') plt.savefig('./figtmp/fig_'+runname+'_'+str(r)+'.png',format='png',dpi=100) plt.close(fig) os.system('ffmpeg -r 4 -i figtmp/fig_'+runname+'_%d.png -c:v libx264 -pix_fmt yuv420p ' + runname + '_divE.mp4')
def test(err=0, mknewcat=True, pattern_error=100, dev_pat=True, distort=True, debug_plots=False, order_pattern_error=False, trim_cam=False, fix_trans=False, fit=True, npos=3, rot_ang_l=[0, 90, 180, 270], step_size=250, Niter=5, plot_in=False, order=4, correct_ref=False, lab_offsets=False, plot_dist=True, Nmissing=None, pattern_from_distortion=True, order_pattern=1): ''' Test function for disotriotn fitting routine that includes altering the refernece positions The fit_all.simul_wref() takes a list of xpositoins, ypositions and offsets, compares them to a perfect square reference and then fits for both the distortion and the pattern deviation err is the size of measurment error in pixels pattern error is the size of the (random) deviations applied ot each pinhole correct_ref(bool): If True, the reference coordinates used in the fit are chaged to the correct deviated values. This validates that the fit works if you give it the right answer To simulate: -First create a perfect square reference -For each mask position: -Apply a pattern deviation (function of reference pixel location as a single second order polynomial) TEST:redo using arbitrary deviations -Apply a translation offset (~1000 pixels) -Apply a distortion map (function of translated pixels) -Add noise if desired Note:Deviations (distortion and pattern) must be smaller than 30 pixels in total, as that is the matching radius in the code. To match measured data the distortion should be ~0.3 pixels and the pattern deviation should be ~ 0.016 pixels. Do the tests in terms of the coeffiicients not just the residuals. Walk up distoriton solutions from fits order in separate functions ''' colors = ['black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray','black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray','black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray','black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray','black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray','black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray', 'black', 'blue', 'green', 'purple', 'brown', 'magenta', 'teal', 'yellow', 'gray'] wd = os.getcwd() if not 'tmp' in wd: os.mkdir('tmp') os.chdir('./tmp') if mknewcat: #make the reference catalog that the fitting code will use fit_all.mkrefcat(ang=0) #make a starting reference catalog that we will deviate and use to create simulated measurements. #fit_all.mkrefcat(outf='ref_test.txt', ang=0) ref = Table.read('reference.txt', format='ascii.basic') #need to declare a pattern deviation t = transforms.PolyTransform(np.ones(10), np.ones(10), np.ones(10), np.ones(10), 4) #change this to directly call the astropy.models directly #now we can declare the polynomial coefficients #translation = 0 t.px.c0_0 = 0 #x scale t.px.c1_0 = 0 #-0.00002 #linear cross term t.px.c0_1 = 0 #0.00004 #quadratic terms t.px.c2_0 = 2 * 10**-8 t.px.c0_2 = 0 #-4 * 10**-9 t.px.c1_1 = 0# 5 * 10**-10 t.px.c3_0 = 0 #10**-12 t.px.c2_1 = 0 t.px.c1_2 = 0 t.px.c0_3 = 0 t.px.c4_0 = 0 #10**-14 t.px.c3_1 = 0 t.px.c2_2 = 0 t.px.c1_3 = 0 t.px.c0_4 = 0 t.py.c0_0 = 0 t.py.c1_0 = 0 # 0.00009 t.py.c0_1 = 0 #-0.00005 t.py.c2_0 = 0 # 7 * 10**-10 t.py.c1_1 = 0 #6 * 10**-9 t.py.c0_2 = 0 #2* * 10**-9 t.py.c3_0 = 0 #10**-12 t.py.c2_1 = 0 t.py.c1_2 = 0 t.py.c0_3 = 0 t.py.c4_0 = 0# 10**-14 t.py.c3_1 = 0 t.py.c2_2 = 0 t.py.c1_3 = 0 t.py.c0_4 = 0 #now apply this as a function of reference position xmin = 1000 xmax = 6000 ymin = 1000 ymax = 5500 cb = (ref['x'] < xmax) * (ref['x'] > xmin) * (ref['y'] < ymax) * (ref['y'] > ymin) inco = Table.read('best_fit.txt', format='ascii.basic') #only keep the linear terms if order_pattern == 2: #only keep the quadratic trerms from the distortion as pattern deviation inco[-9:] = 0.0 inco[-21:-12] = 0.0 if order_pattern == 3: #4th order Y terms inco[-5:] = 0 #2nd order Y terms inco[-12:-10] = 0 #4th order x terms inco[-17:-12] = 0 #2nd order x terms inco[-24:-21] = 0 if order_pattern == 4: #3rd order Y terms inco[-9:-5] = 0 #2nd order Y terms inco[-12:-9] = 0 #3rd order x terms inco[-21:-18] = 0 #2nd order x terms inco[-24:-21] = 0 #chop out the linear parameters at the begining of this array inco = inco[-30:] xmin = 0 xmax = np.inf ymin = 0 ymax = np.inf xmin = 965.148 xmax = 7263.57 ymin = 490.87 ymax = 5218.0615 rb = (ref['x'] > xmin) * (ref['x'] < xmax) * (ref['y'] < ymax) * (ref['y'] > ymin) print('input RMS deviations') #import pdb;pdb.set_trace() dx_pd, dy_pd = fit_all.com_mod(inco['col0'], [ref['x']], [ref['y']], [ref['x']], [ref['y']], order=4, evaluate=True, ret_dist=True) print(np.std(dx_pd[0][rb])*6000, np.std(dy_pd[0][rb])*6000) #rb2 = np.invert(rb) #dx_pd[0][rb2] = 0 #dy_pd[0][rb2] = 0 if not pattern_from_distortion: dx_pd = 0 dy_pd = 0 if order_pattern_error: dx, dy = t.evaluate(ref['x']-np.median(ref['x']), ref['y']-np.median(ref['y'])) else: dx = np.zeros(len(ref['x'])) dy = np.zeros(len(ref['y'])) # import pdb;pdb.set_trace() print(np.std(dx[cb])*6000.0,np.std(dy[cb])*6000.0) print(np.min(dx[cb])*6000.0, np.max(dx[cb])*6000.0, np.min(dy[cb])*6000.0, np.max(dy[cb])*6000.0) _norm_pattern = scipy.stats.norm(loc=0, scale=pattern_error/6000.0) _xerr = _norm_pattern.rvs(len(ref['x'])) _yerr = _norm_pattern.rvs(len(ref['x'])) xpin = ref['x'] + _xerr + dx + dx_pd ypin = ref['y'] + _yerr + dy +dy_pd xpin = np.array(xpin)[0] ypin = np.array(ypin)[0] plt.close('all') if correct_ref: _out = ref _out['x'] = xpin _out['y'] = ypin _out.write('reference.txt', format='ascii.basic') if debug_plots: mkplots_1(ref, dx, dy, _xerr, _yerr, xpin, ypin) #now we need to apply translation offsets and create the "average stacked catalogs" #these are the offsets from s8, used in paper #offsets = [[753, 333],[356,336],[7388-7096,5705-7015],[6203-7096,5707-7015],[6173-7055,300--40.6],[1192-40.6,5758-7055.0], [ 1500, 330], [1500, -1300], [0,0]] rot_ang = [] if lab_offsets: offsets_s = [[447-40.6, 5894-7055], [770-40.6, 5895-7055], [945-40.6, 5888-7055], [944-40.6, 5644-7055], [697-40.6, 5620-7055], [488-40.6, 5619-7055], [486-40.6, 5376-7055], [745-40.6, 5381-7055], [982-40.6, 5371-7055]] #create a square gird (npos x npos) of obsevations at each rot_ang note these are now input keyword arguements offsets = [] #rot_ang_l = [0, 90, 180, 270] #import pdb;pdb.set_trace() for _ang in rot_ang_l: if not lab_offsets: for i in range(npos): for j in range(npos): offsets.append([i * step_size, j * step_size]) rot_ang.append(_ang) else: for k in range(len(offsets_s)): offsets.append(offsets_s[k]) rot_ang.append(_ang) xlis = [] ylis = [] plt.figure(2) plt.clf() offsets_in = [] _norm = scipy.stats.norm(loc=0 , scale=err) for _iii, _off in enumerate(offsets): _ang = -1.0*np.deg2rad(rot_ang[_iii]) _xtmp = (xpin-4000)*np.cos(_ang) - (ypin-3000)*np.sin(_ang) _ytmp = (ypin-3000)*np.cos(_ang) + (xpin-4000)*np.sin(_ang) #now we need to move the measured coordiantes such that the lowest value points (lower left) is at offsets[i][0,1] #import pdb;pdb.set_trace() _dx = _off[0] + 4000 _dy = _off[1] + 3000 xlis.append(np.array(_xtmp + _dx)) ylis.append(np.array(_ytmp + _dy)) offsets_in.append(((xlis[-1][0]),ylis[-1][0]) ) #if _ang != 0: # import pdb;pdb.set_trace() print(offsets_in[-1]) if debug_plots: plt.figure(2) plt.scatter(xlis[-1], ylis[-1], label='catalog '+str(_iii)) plt.title('Measured Position with no distortion') plt.legend(loc='upper right') #this is a 4th order Legendre Polynomial -- measured for single stack s6/pos_1/ td = mkdist() #look in def mkdist for details of the current distortion applied xmax = 8000 xmin = -1 ymax = 8000 ymin = -1 xln = [] yln = [] xrn = [] yrn = [] xrnC = [] yrnC = [] plt.figure(100) plt.clf() #import pdb;pdb.set_trace() for i in range(len(xlis)): cbool = (xlis[i] < xmax) * (xlis[i] > xmin) * (ylis[i] < ymax) * (ylis[i] > ymin) cbool = np.ones(len(xlis[i]), dtype='bool') dxd, dyd = td.evaluate(xlis[i][cbool]-4000.0, ylis[i][cbool]-3000.0) print('RMS size of distortion', np.std(dxd)*6000, np.std(dyd)*6000.0, np.median(dxd)*6000, np.median(dyd)*6000) #import pdb;pdb.set_trace() if not distort: dxd = np.zeros(np.sum(cbool)) dyd = np.zeros(np.sum(cbool)) if plot_dist: plt.figure(2200) q = plt.quiver(xlis[i][cbool], ylis[i][cbool],dxd, dyd, scale =10, color=colors[i]) plt.quiverkey(q, -50, -50, 1, '6000 nm', coordinates='data', color='red') #add the distortion term to the measurments xln.append(xlis[i][cbool]+dxd+ _norm.rvs(np.sum(cbool))) yln.append(ylis[i][cbool]+dyd+ _norm.rvs(np.sum(cbool))) #create the array of reference positions that is matched to the measurements xrnC.append(xpin[cbool]) yrnC.append(ypin[cbool]) #create transformstion for the debugging plots tl = transforms.PolyTransform(ref['x'], ref['y'], xln[-1], yln[-1], 1) __xn, __yn = tl.evaluate(ref['x'], ref['y']) xrn.append(__xn) yrn.append(__yn) if debug_plots: #need mk_debug_plots(ref, xln, yln) #import pdb;pdb.set_trace() #now we are ready to run the fitting routine #we iterate to allow the reference positions to converge #fit_all.simul_wref(xln,yln,offsets) if not fit: import pdb;pdb.set_trace() init_guess = fit_all.guess_co(xln, yln, xrnC, yrnC, order=order) res = leastsq(fit_all.com_mod, init_guess, args=(xln, yln, xrnC, yrnC, fix_trans, init_guess, order)) outres = fit_all.com_mod(res[0], xln, yln, xrnC, yrnC,fix_trans=fix_trans, order=order, evaluate=False, init_guess=init_guess) return outres, res if Nmissing is None: Nmissing = len(xln)+1 res = fit_all.simul_wref(xln, yln, offsets_in, order=order, rot_ang=rot_ang, Niter=Niter, dev_pat=dev_pat, Nmissing=len(xln)+1, sig_clip=False, fourp=False, trim_cam=trim_cam, fix_trans=fix_trans, debug=True, plot_ind=plot_in, trim_pin=False) #import pdb;pdb.set_trace() #return #if the fitting procedure has updated reference.txt with fixed coordiantes -> these should match xpin and ypin refn = Table.read('reference_new.txt', format='ascii.basic') cb = (refn['x'] - refn['xorig']) != 0.0 __dx = (refn['x'] - xpin) #this is the input deviation __dy = (refn['y'] - ypin) #make scatter plots of the recovered pinhole deviation errors plt.figure(2000) mkplots_2(refn, xpin, ypin, cb, __dx, __dy) #now we compare coefficients to the fit fit_all.mksamp(outf='dist_test.txt', order=order) _dist = Table.read('dist_test.txt', format='ascii.basic') if distort: _dxin, _dyin = td.evaluate(_dist['x']-4000, _dist['y']-3000) else: _dxin = np.zeros(len(_dist['x'])) _dyin = np.zeros(len(_dist['y'])) #to do this comparrison you need to eliminate the linear terms in the input distortion plt.figure(2005) #_tl = transforms.PolyTransform(_dist['x']+_dxin, _dist['y']+_dyin, _dist['dx']+_dist['x'], _dist['dy']+_dist['y'], 1) _tl = transforms.PolyTransform(_dist['x'], _dist['y'],_dist['dx']+_dxin,_dist['dy']+ _dyin, 1) _xmd, _ymd = _tl.evaluate(_dist['x'], _dist['y']) #_tl1 = transforms.PolyTransform(_dist['x'], _dist['y'],_dist['dx'], _dist['dy'], 1) #_xmd1, _ymd1 = _tl.evaluate(_dist['x'], _dist['y']) diffx = _dist['dx'] + _dxin - _xmd diffy = _dist['dy'] + _dyin - _ymd import pdb;pdb.set_trace() #diffx = _dist['dx']+_dxin #diffx = diffx - np.mean(diffx) #diffy = _dist['dy']+_dyin #diffy = diffy - np.mean(diffy) plt.figure(2005) plt.scatter(_dist['x'], _dist['y'], c=diffx*6000.0) plt.title('X Camera Distortion Meaurement Mistake (model - input)') plt.xlabel("X reference (pix)") plt.ylabel("Y reference (pix)") plt.colorbar() plt.tight_layout() plt.figure(2006) plt.scatter(_dist['x'], _dist['y'], c=diffy*6000.0) plt.title('Y Camera Distortion Measurement Mistake (model - input)') plt.xlabel("X reference (pix)") plt.ylabel("Y reference (pix)") plt.colorbar() plt.tight_layout() plt.figure(2007) plt.hist((diffx)*6000.0, histtype='step', label='x', lw=3) plt.hist((diffy)*6000.0, histtype='step', label='y', lw=3) plt.xlabel("Camera Distortion Meaurement Mistake (model - input)") plt.ylabel("N") plt.legend(loc='upper left') co = Table.read('fit.txt', format='ascii.basic')
#Q1 = plt.quiver(x[::dec,::dec],y[::dec,::dec],Gx[::dec,::dec],Gy[::dec,::dec], # scale=500,width=0.006) plot_fig_label(ax, xc=0.95, yc=.05, label="b") else: plt.contour(x, y, qpsi / (Ue * ke), cq0[2:], colors='k') plt.contour(x, y, qpsi / (Ue * ke), cq0[:2], colors='k') Q = plt.quiver(x[::dec, ::dec], y[::dec, ::dec], Fwx[::dec, ::dec], Fwy[::dec, ::dec], scale=5e-2, width=0.006) qk = plt.quiverkey(Q, 0.175, .8285, 5e-3, r'$5\times10^{-3}\times\,\,{\mathcal{{\bf F}}}/F$', labelpos='E', coordinates='figure') plot_fig_label(ax, xc=0.95, yc=.05, label="a") plt.xlim(xlim) plt.ylim(xlim) ax.set_xlabel(r"$x\times k_e/2\pi$") ax.set_xticks([-1., 0, 1]) if i == 0: ax.set_ylabel(r"$y\times k_e/2\pi$") ax.set_yticks([-1., 0, 1]) elif i == 1 or i == 2: ax.set_yticks([]) else:
def bin_by_fov(ccd, x, y, dT, de1, de2, bands): import numpy as np import matplotlib.pyplot as plt from toFocal import toFocal all_x = np.array([]) all_y = np.array([]) all_e1 = np.array([]) all_e2 = np.array([]) all_T = np.array([]) nwhisk = 5 x_bins = np.linspace(0, 2048, nwhisk + 1) y_bins = np.linspace(0, 4096, 2 * nwhisk + 1) ccdnums = np.unique(ccd) for ccdnum in ccdnums: mask = np.where(ccd == ccdnum)[0] print('ccdnum = ', ccdnum, ', nstar = ', mask.sum()) if mask.sum() < 100: continue x_index = np.digitize(x[mask], x_bins) y_index = np.digitize(y[mask], y_bins) bin_de1 = np.array([ de1[mask][(x_index == i) & (y_index == j)].mean() for i in range(1, len(x_bins)) for j in range(1, len(y_bins)) ]) print('bin_de1 = ', bin_de1) bin_de2 = np.array([ de2[mask][(x_index == i) & (y_index == j)].mean() for i in range(1, len(x_bins)) for j in range(1, len(y_bins)) ]) print('bin_de2 = ', bin_de2) bin_dT = np.array([ dT[mask][(x_index == i) & (y_index == j)].mean() for i in range(1, len(x_bins)) for j in range(1, len(y_bins)) ]) print('bin_dT = ', bin_dT) bin_x = np.array([ x[mask][(x_index == i) & (y_index == j)].mean() for i in range(1, len(x_bins)) for j in range(1, len(y_bins)) ]) print('bin_x = ', bin_x) bin_y = np.array([ y[mask][(x_index == i) & (y_index == j)].mean() for i in range(1, len(x_bins)) for j in range(1, len(y_bins)) ]) print('bin_y = ', bin_y) bin_count = np.array([((x_index == i) & (y_index == j)).sum() for i in range(1, len(x_bins)) for j in range(1, len(y_bins))]) print('bin_count = ', bin_count) focal_x, focal_y = toFocal(ccdnum, bin_x, bin_y) mask2 = np.where(bin_count > 0)[0] print('num with count > 0 = ', mask2.sum()) all_x = np.append(all_x, focal_x[mask2]) all_y = np.append(all_y, focal_y[mask2]) all_e1 = np.append(all_e1, bin_de1[mask2]) all_e2 = np.append(all_e2, bin_de2[mask2]) all_T = np.append(all_T, bin_dT[mask2]) plt.clf() #plt.title('PSF Ellipticity residuals in DES focal plane') theta = np.arctan2(all_e2, all_e1) / 2. r = np.sqrt(all_e1**2 + all_e2**2) u = r * np.cos(theta) v = r * np.sin(theta) plt.xlim(-250, 250) plt.ylim(-250, 250) print('all_x = ', all_x) print('len(all_x) = ', len(all_x)) qv = plt.quiver(all_x, all_y, u, v, pivot='middle', scale_units='xy', headwidth=0., headlength=0., headaxislength=0., width=0.001, scale=1.e-3, color='blue') ref_scale = 0.01 if 'raw' in bands: ref_label = 'e = ' + str(ref_scale) else: ref_label = 'de = ' + str(ref_scale) plt.quiverkey(qv, 0.10, 0.08, ref_scale, ref_label, coordinates='axes', color='darkred', labelcolor='darkred', labelpos='E', fontproperties={'size': 'x-small'}) plt.axis('off') plt.savefig('de_fov_' + bands + '.png') plt.savefig('de_fov_' + bands + '.pdf') plt.savefig('de_fov_' + bands + '.eps')
def plot(self, timedata=None, udata=None, vdata=None, ylabel=None, **kwargs): if kwargs['rotate'] != 0.0: #when rotating vectors - positive(+) rotation is equal to cw of the axis (ccw of vector) # - negative(+) rotation is equal to ccw of the axis (cw of the vector) print "rotating vectors" angle_offset_rad = np.deg2rad(kwargs['rotate']) udata = udata * np.cos(angle_offset_rad) + vdata * np.sin( angle_offset_rad) vdata = -1. * udata * np.sin(angle_offset_rad) + vdata * np.cos( angle_offset_rad) magnitude = np.sqrt(udata**2 + vdata**2) fig = plt.figure(1) ax1 = plt.subplot2grid((2, 1), (0, 0), colspan=1, rowspan=1) ax2 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1) # Plot u and v components # Plot quiver ax1.set_ylim(-1 * np.nanmax(magnitude), np.nanmax(magnitude)) fill1 = ax1.fill_between(timedata, magnitude, 0, color='k', alpha=0.1) # Fake 'box' to be able to insert a legend for 'Magnitude' p = ax1.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1)) leg1 = ax1.legend([p], ["Current magnitude [cm/s]"], loc='lower right') leg1._drawFrame = False # 1D Quiver plot q = ax1.quiver(timedata, 0, udata, vdata, color='r', units='y', scale_units='y', scale=1, headlength=1, headaxislength=1, width=0.04, alpha=.95) qk = plt.quiverkey(q, 0.2, 0.05, 5, r'$5 \frac{cm}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) # Plot u and v components ax1.set_xticklabels(ax1.get_xticklabels(), visible=False) ax2.set_xticklabels(ax2.get_xticklabels(), visible=True) ax1.axes.get_xaxis().set_visible(False) ax1.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5) ax1.set_ylabel("Velocity (cm/s)") ax2.plot(timedata, vdata, 'b-', linewidth=0.25) ax2.plot(timedata, udata, 'g-', linewidth=0.25) ax2.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5) ax2.set_xlabel("Date (UTC)") ax2.set_ylabel("Velocity (cm/s)") ax2.xaxis.set_major_locator(MonthLocator()) ax2.xaxis.set_minor_locator( MonthLocator(bymonth=range(1, 13), bymonthday=15)) ax2.xaxis.set_major_formatter(ticker.NullFormatter()) ax2.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax1.spines['bottom'].set_visible(False) ax2.spines['top'].set_visible(False) ax1.xaxis.set_ticks_position('top') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('both') ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize) ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize) #manual time limit sets #ax1.set_xlim([datetime.datetime(2016,2,1),datetime.datetime(2016,9,15)]) #ax2.set_xlim([datetime.datetime(2016,2,1),datetime.datetime(2016,9,15)]) # Set legend location - See: http://matplotlib.org/Volumes/WDC_internal/users/legend_guide.html#legend-location leg2 = plt.legend(['v', 'u'], loc='upper left') leg2._drawFrame = False return plt, fig
ax.set_xticks(np.arange(40,80,10)) ax.set_xticklabels((r'$40^o$E', r'$50^o$E', r'$60^o$E', r'$70^o$E')) ax.set_yticks(np.arange(-20,10,10)) ax.set_yticklabels((r'$20^o$S', r'$10^o$S', r'$0^o$S')) ax.text(0.03, 0.88, 'h)', transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.5), color='k', fontsize=14) #plt.axis([51.63, 58.36, -8.9, -1.06]) plt.axis([42, 65, -18, 3]) # fig.suptitle('ssh clim 1993-2009') fig.subplots_adjust(left=0.07, right=0.9, hspace=0.03, wspace=0.01) cbar_ax = fig.add_axes([0.91, 0.15, 0.02, 0.7]) cbar = fig.colorbar(ctop, cax=cbar_ax, extend='both', ticks=np.arange(-10,12,2)) cbar.set_label('[cm]') qk = plt.quiverkey(Q, 0.90, 0.08, 10, r'$10 \frac{cm}{s}$', labelpos='E', coordinates='figure') plt.savefig('aviso_pop_comp_seas_large.pdf', bbox_inches='tight') # Calculate the monthly average - the 19 year average uavg_sat = u_sat.mean(0) vavg_sat = v_sat.mean(0) sshavg_sat = ssh_sat.mean(0) uavg_pop = u_pop.mean(0) vavg_pop = v_pop.mean(0) sshavg_pop = ssh_pop.mean(0) colori = cmocean.cm.balance colori = cm.bwr li = 4
q = ax1.quiver(xdate, 0, ucomp, vcomp, color='r', units='y', scale_units='y', scale=1, headlength=2, headaxislength=2, width=0.1, alpha=.95) qk = plt.quiverkey(q, 0.2, 0.05, 5, r'$5 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) ax1.set_ylim(vcomp.min(), vcomp.max()) ax1.set_ylabel("(m/s)") ax1.set_xlim( datetime.datetime(2010 + i - 1, 8, 01).toordinal(), datetime.datetime(2011 + i - 1, 10, 31).toordinal()) ax1.xaxis.set_major_locator(MonthLocator()) ax1.xaxis.set_minor_locator( MonthLocator(bymonth=range(1, 13), bymonthday=15)) ax1.xaxis.set_major_formatter(ticker.NullFormatter()) ax1.xaxis.set_minor_formatter(DateFormatter('%b %y')) ax1.tick_params(axis='both', which='minor', labelsize=12)