def get_xy_from_latlon(self,lat,lon): """ Return x and y coordinates for given lat/lon. exactlat, exactlon : exact coordinates of closest x/y """ y,x,exactlat,exactlon = utils.getXY(self.W.lats1D,self.W.lons1D,lat,lon) return x,y
def get_xy_from_latlon(self, lat, lon): """ Return x and y coordinates for given lat/lon. exactlat, exactlon : exact coordinates of closest x/y """ y, x, exactlat, exactlon = utils.getXY(self.W.lats1D, self.W.lons1D, lat, lon) return x, y
def composite_profile(self, va, plot_time, plot_latlon, wrfouts, outpath, dom=1, mean=True, std=True, xlim=False, ylim=False, fig=False, ax=False, locname=0, ml=-2): """ Loop over wrfout files. Get profile of variable Plot all members Optional standard deviation Optional mean If ax, save image to that axis ml : member level. negative number that corresponds to the folder in absolute string for naming purposes. """ # Set up figure if isinstance(fig, M.figure.Figure): self.fig = fig self.ax = ax else: self.fig, self.ax = plt.subplots() # Plot settings if xlim: xmin, xmax, xint = xlim if ylim: if ylim[1] > ylim[0]: # top to bottom P_top, P_bot, dp = [y * 100.0 for y in ylim] else: P_bot, P_top, dp = [y * 100.0 for y in ylim] else: P_bot = 100000.0 P_top = 20000.0 dp = 10000.0 # plevs = N.arange(P_bot,P_top,dp) # Get wrfout prototype for information W = WRFOut(wrfouts[0]) lat, lon = plot_latlon datestr = utils.string_from_time('output', plot_time) t_idx = W.get_time_idx(plot_time, ) y, x, exact_lat, exact_lon = utils.getXY(W.lats1D, W.lons1D, lat, lon) slices = {'t': t_idx, 'la': y, 'lo': x} #var_slices = {'t': t_idx, 'lv':0, 'la':y, 'lo':x} # Initialise array # Number of levels and ensembles: nPlevs = W.z_dim data = W.get(va, slices) nvarlevs = data.shape[1] nens = len(wrfouts) # 2D: (profile,member) profile_arr = N.zeros((nvarlevs, nens)) composite_P = N.zeros((nPlevs, nens)) # Set up legend labels = [] colourlist = utils.generate_colours(M, nens) # M.rcParams['axes.color_cycle'] = colourlist # Collect profiles for n, wrfout in enumerate(wrfouts): W = WRFOut(wrfout) # Get pressure levels composite_P[:, n] = W.get('pressure', slices)[0, :, 0, 0] #elev = self.W.get('HGT',H_slices) #pdb.set_trace() # Grab variable profile_arr[:, n] = W.get(va, slices)[0, :, 0, 0] # Plot variable on graph self.ax.plot(profile_arr[:, n], composite_P[:, n], color=colourlist[n]) member = wrfout.split('/')[ml] labels.append(member) # if locname=='KOAX': pdb.set_trace() # Compute mean, std etc if mean: profile_mean = N.mean(profile_arr, axis=1) profile_mean_P = N.mean(composite_P, axis=1) self.ax.plot(profile_mean, profile_mean_P, color='black') if std: # Assume mean P across ensemble is correct level # to plot standard deviation profile_std = N.std(profile_arr, axis=1) std_upper = profile_mean + profile_std std_lower = profile_mean - profile_std self.ax.plot(std_upper, profile_mean_P, 'k--') self.ax.plot(std_lower, profile_mean_P, 'k--') if not locname: fname = '_'.join(('profile_comp', va, datestr, '{0:03d}'.format(x), '{0:03d}'.format(y))) + '.png' else: fname = '_'.join(('profile_comp', va, datestr, locname)) + '.png' # Set semi-log graph self.ax.set_yscale('log') # Plot limits, ticks yticks = N.arange(P_bot, P_top + dp * 100.0, -100 * 100.0) # yticks = N.arange(P_bot,P_top+dp,-dp*100) # self.ax.set_yticks(yticks) ylabels = ["%4u" % (p / 100.0) for p in yticks] self.ax.set_yticks(yticks) self.ax.set_yticklabels(ylabels) # import pdb; pdb.set_trace() # self.ax.yaxis.tick_right() #plt.axis([-20,50,105000.0,20000.0]) #plt.xlabel(r'Temperature ($^{\circ}$C) at 1000 hPa') #plt.xticks(xticks,['' if tick%10!=0 else str(tick) for tick in xticks]) self.ax.set_ylabel('Pressure (hPa)') #yticks = N.arange(self.P_bot,P_t-1,-10**4) #plt.yticks(yticks,yticks/100) if xlim: self.ax.set_xlim([xmin, xmax]) xticks = N.arange(xmin, xmax + xint, xint) self.ax.set_xticks(xticks) # Flip y axis # Limits are already set self.ax.set_ylim([P_bot, P_top]) # plt.tight_layout(self.fig) #plt.autoscale(enable=1,axis='x') #ax = plt.gca() #ax.relim() #ax.autoscale_view() #plt.draw() self.ax.legend(labels, loc=2, fontsize=6) self.save(outpath, fname) plt.close(self.fig)
def plot_skewT(self, plot_time, plot_latlon, dom, outpath, save_output=0, save_plot=1): # Defines the ranges of the plot, do not confuse with self.P_bot and self.P_top self.barb_increments = {'half': 2.5, 'full': 5.0, 'flag': 25.0} self.skewness = 37.5 self.P_bot = 100000. self.P_top = 10000. self.dp = 100. self.plevs = N.arange(self.P_bot, self.P_top - 1, -self.dp) # pdb.set_trace() prof_lat, prof_lon = plot_latlon datestr = utils.string_from_time('output', plot_time) t_idx = self.W.get_time_idx(plot_time) y, x, exact_lat, exact_lon = utils.getXY(self.W.lats1D, self.W.lons1D, prof_lat, prof_lon) # Create figure if save_plot: # height, width = (10,10) # fig = plt.figure(figsize=(width,height)) self.isotherms() self.isobars() self.dry_adiabats() self.moist_adiabats() # P_slices = {'t': t_idx, 'la': y, 'lo': x} # H_slices = {'t':t_idx, 'lv':0, 'la':y, 'lo':x} # pdb.set_trace() P = self.W.get('pressure', utc=t_idx, lats=y, lons=x)[0, :, 0, 0] elev = self.W.get('HGT', utc=t_idx, level=0, lats=y, lons=x) thin_locs = utils.thinned_barbs(P) self.windbarbs(self.W.nc, t_idx, y, x, P, thin_locs, n=45, color='blue') self.temperature(self.W.nc, t_idx, y, x, P, linestyle='solid', color='blue') self.dewpoint(self.W.nc, t_idx, y, x, P, linestyle='dashed', color='blue') xticks = N.arange(-20, 51, 5) yticks = N.arange(100000.0, self.P_top - 1, -10**4) ytix = ["%4u" % (p / 100.0) for p in yticks] self.ax.set_xticks( xticks, ['' if tick % 10 != 0 else str(tick) for tick in xticks]) self.ax.set_yticks(yticks, ytix) self.ax.axis([-20, 50, 105000.0, 20000.0]) self.ax.set_xlabel(r'Temperature ($^{\circ}$C) at 1000 hPa') self.ax.set_xticks( xticks, ['' if tick % 10 != 0 else str(tick) for tick in xticks]) self.ax.set_ylabel('Pressure (hPa)') self.ax.set_yticks(yticks, ytix) #yticks = N.arange(self.P_bot,P_t-1,-10**4) #plt.yticks(yticks,yticks/100) fname = '_'.join(('skewT', datestr, '{0:03d}'.format(x), '{0:03d}'.format(y))) + '.png' # utils.trycreate(self.path_to_output) # fpath = os.path.join(self.path_to_output,fname) # plt.savefig(fpath) self.save(outpath, fname) plt.close() # For saving Skew T data if save_output: # Pickle files are saved here: pickle_fname = '_'.join( ('WRFsounding', datestr, '{0:03d}'.format(x), '{0:03d}'.format(y) + '.p')) pickle_path = os.path.join(self.C.pickledir, pickle_fname) u, v = self.return_data('wind', self.W.nc, t_idx, y, x, thin_locs) T = self.return_data('temp', self.W.nc, t_idx, y, x, thin_locs, P=P) Td = self.return_data('dwpt', self.W.nc, t_idx, y, x, thin_locs, P=P) data_dict = {'u': u, 'v': v, 'T': T, 'Td': Td, 'P': P} with open(pickle_path, 'wb') as p: pickle.dump(data_dict, p) print(("Saving data to {0}".format(pickle_path))) return else: return
def composite_profile(self,va,plot_time,plot_latlon,wrfouts,outpath, dom=1,mean=1,std=1,xlim=0,ylim=0,fig=0,ax=0, locname=0,ml=-2): """ Loop over wrfout files. Get profile of variable Plot all members Optional standard deviation Optional mean If ax, save image to that axis ml : member level. negative number that corresponds to the folder in absolute string for naming purposes. """ # Set up figure if isinstance(fig,M.figure.Figure): self.fig = fig self.ax = ax else: self.fig, self.ax = plt.subplots() # Plot settings if xlim: xmin, xmax, xint = xlim if ylim: if ylim[1] > ylim[0]: # top to bottom P_top, P_bot, dp = [y*100.0 for y in ylim] else: P_bot, P_top, dp = [y*100.0 for y in ylim] else: P_bot = 100000.0 P_top = 20000.0 dp = 10000.0 # plevs = N.arange(P_bot,P_top,dp) # Get wrfout prototype for information W = WRFOut(wrfouts[0]) lat, lon = plot_latlon datestr = utils.string_from_time('output',plot_time) t_idx = W.get_time_idx(plot_time,) y, x, exact_lat, exact_lon = utils.getXY(W.lats1D,W.lons1D,lat,lon) slices = {'t': t_idx, 'la': y, 'lo': x} #var_slices = {'t': t_idx, 'lv':0, 'la':y, 'lo':x} # Initialise array # Number of levels and ensembles: nPlevs = W.z_dim data = W.get(va,slices) nvarlevs = data.shape[1] nens = len(wrfouts) # 2D: (profile,member) profile_arr = N.zeros((nvarlevs,nens)) composite_P = N.zeros((nPlevs,nens)) # Set up legend labels = [] colourlist = utils.generate_colours(M,nens) # M.rcParams['axes.color_cycle'] = colourlist # Collect profiles for n,wrfout in enumerate(wrfouts): W = WRFOut(wrfout) # Get pressure levels composite_P[:,n] = W.get('pressure',slices)[0,:,0,0] #elev = self.W.get('HGT',H_slices) #pdb.set_trace() # Grab variable profile_arr[:,n] = W.get(va,slices)[0,:,0,0] # Plot variable on graph self.ax.plot(profile_arr[:,n],composite_P[:,n],color=colourlist[n]) member = wrfout.split('/')[ml] labels.append(member) # if locname=='KOAX': pdb.set_trace() # Compute mean, std etc if mean: profile_mean = N.mean(profile_arr,axis=1) profile_mean_P = N.mean(composite_P,axis=1) self.ax.plot(profile_mean,profile_mean_P,color='black') if std: # Assume mean P across ensemble is correct level # to plot standard deviation profile_std = N.std(profile_arr,axis=1) std_upper = profile_mean + profile_std std_lower = profile_mean - profile_std self.ax.plot(std_upper,profile_mean_P,'k--') self.ax.plot(std_lower,profile_mean_P,'k--') if not locname: fname = '_'.join(('profile_comp',va,datestr,'{0:03d}'.format(x),'{0:03d}'.format(y))) + '.png' else: fname = '_'.join(('profile_comp',va,datestr,locname)) + '.png' # Set semi-log graph self.ax.set_yscale('log') # Plot limits, ticks yticks = N.arange(P_bot,P_top+dp*100.0,-100*100.0) # yticks = N.arange(P_bot,P_top+dp,-dp*100) # self.ax.set_yticks(yticks) ylabels = ["%4u" %(p/100.0) for p in yticks] self.ax.set_yticks(yticks) self.ax.set_yticklabels(ylabels) # import pdb; pdb.set_trace() # self.ax.yaxis.tick_right() #plt.axis([-20,50,105000.0,20000.0]) #plt.xlabel(r'Temperature ($^{\circ}$C) at 1000 hPa') #plt.xticks(xticks,['' if tick%10!=0 else str(tick) for tick in xticks]) self.ax.set_ylabel('Pressure (hPa)') #yticks = N.arange(self.P_bot,P_t-1,-10**4) #plt.yticks(yticks,yticks/100) if xlim: self.ax.set_xlim([xmin,xmax]) xticks = N.arange(xmin,xmax+xint,xint) self.ax.set_xticks(xticks) # Flip y axis # Limits are already set self.ax.set_ylim([P_bot,P_top]) # plt.tight_layout(self.fig) #plt.autoscale(enable=1,axis='x') #ax = plt.gca() #ax.relim() #ax.autoscale_view() #plt.draw() self.ax.legend(labels,loc=2,fontsize=6) self.save(outpath,fname) plt.close(self.fig)
def plot_skewT(self,plot_time,plot_latlon,dom,outpath,save_output=0,save_plot=1): # Defines the ranges of the plot, do not confuse with self.P_bot and self.P_top self.barb_increments = {'half': 2.5,'full':5.0,'flag':25.0} self.skewness = 37.5 self.P_bot = 100000. self.P_top = 10000. self.dp = 100. self.plevs = N.arange(self.P_bot,self.P_top-1,-self.dp) # pdb.set_trace() prof_lat, prof_lon = plot_latlon datestr = utils.string_from_time('output',plot_time) t_idx = self.W.get_time_idx(plot_time) y,x, exact_lat, exact_lon = utils.getXY(self.W.lats1D,self.W.lons1D,prof_lat,prof_lon) # Create figure if save_plot: # height, width = (10,10) # fig = plt.figure(figsize=(width,height)) self.isotherms() self.isobars() self.dry_adiabats() self.moist_adiabats() P_slices = {'t': t_idx, 'la': y, 'lo': x} H_slices = {'t':t_idx, 'lv':0, 'la':y, 'lo':x} # pdb.set_trace() P = self.W.get('pressure',P_slices)[0,:,0,0] elev = self.W.get('HGT',H_slices) thin_locs = utils.thinned_barbs(P) self.windbarbs(self.W.nc,t_idx,y,x,P,thin_locs,n=45,color='blue') self.temperature(self.W.nc,t_idx,y,x,P,linestyle='solid',color='blue') self.dewpoint(self.W.nc,t_idx,y,x,P,linestyle='dashed',color='blue') xticks = N.arange(-20,51,5) yticks = N.arange(100000.0,self.P_top-1,-10**4) ytix = ["%4u" %(p/100.0) for p in yticks] self.ax.set_xticks(xticks,['' if tick%10!=0 else str(tick) for tick in xticks]) self.ax.set_yticks(yticks,ytix) self.ax.axis([-20,50,105000.0,20000.0]) self.ax.set_xlabel(r'Temperature ($^{\circ}$C) at 1000 hPa') self.ax.set_xticks(xticks,['' if tick%10!=0 else str(tick) for tick in xticks]) self.ax.set_ylabel('Pressure (hPa)') self.ax.set_yticks(yticks,ytix) #yticks = N.arange(self.P_bot,P_t-1,-10**4) #plt.yticks(yticks,yticks/100) fname = '_'.join(('skewT',datestr,'{0:03d}'.format(x),'{0:03d}'.format(y))) + '.png' # utils.trycreate(self.path_to_output) # fpath = os.path.join(self.path_to_output,fname) # plt.savefig(fpath) self.save(outpath,fname) plt.close() # For saving Skew T data if save_output: # Pickle files are saved here: pickle_fname = '_'.join(('WRFsounding',datestr,'{0:03d}'.format(x), '{0:03d}'.format(y)+'.p')) pickle_path = os.path.join(self.C.pickledir,pickle_fname) u,v = self.return_data('wind',self.W.nc,t_idx,y,x,thin_locs) T = self.return_data('temp',self.W.nc,t_idx,y,x,thin_locs,P=P) Td = self.return_data('dwpt',self.W.nc,t_idx,y,x,thin_locs,P=P) data_dict = {'u':u,'v':v,'T':T,'Td':Td,'P':P} with open(pickle_path,'wb') as p: pickle.dump(data_dict,p) print("Saving data to {0}".format(pickle_path)) return else: return
def cold_pool_strength(self, time, wrf_sd=0, wrf_nc=0, out_sd=0, swath_width=100, dom=1, twoplot=0, fig=0, axes=0, dz=0): """ Pick A, B points on sim ref overlay This sets the angle between north and line AB Also sets the length in along-line direction For every gridpt along line AB: Locate gust front via shear Starting at front, do 3-grid-pt-average in line-normal direction time : time (tuple or datenum) to plot wrf_sd : string - subdirectory of wrfout file wrf_nc : filename of wrf file requested. If no wrfout file is explicitly specified, the netCDF file in that folder is chosen if unambiguous. out_sd : subdirectory of output .png. swath_width : length in gridpoints in cross-section-normal direction dom : domain number return2 : return two figures. cold pool strength and cref/cross-section. axes : if two-length tuple, this is the first and second axes for cross-section/cref and cold pool strength, respectively dz : plot height of cold pool only. """ # Initialise self.W = self.get_wrfout(wrf_sd, wrf_nc, dom=dom) outpath = self.get_outpath(out_sd) # keyword arguments for plots line_kwargs = {} cps_kwargs = {} # Create two-panel figure if twoplot: P2 = Figure(self.C, self.W, plotn=(1, 2)) line_kwargs['ax'] = P2.ax.flat[0] line_kwargs['fig'] = P2.fig P2.ax.flat[0].set_size_inches(3, 3) cps_kwargs['ax'] = P2.ax.flat[1] cps_kwargs['fig'] = P2.fig P2.ax.flat[1].set_size_inches(6, 6) elif isinstance(axes, tuple) and len(axes) == 2: line_kwargs['ax'] = axes[0] line_kwargs['fig'] = fig cps_kwargs['ax'] = axes[1] cps_kwargs['fig'] = fig return_ax = 1 # Plot sim ref, send basemap axis to clicker function F = BirdsEye(self.C, self.W) self.data = F.plot2D('cref', time, 2000, dom, outpath, save=0, return_data=1) C = Clicker(self.C, self.W, data=self.data, **line_kwargs) # C.fig.tight_layout() # Line from front to back of system C.draw_line() # C.draw_box() lon0, lat0 = C.bmap(C.x0, C.y0, inverse=True) lon1, lat1 = C.bmap(C.x1, C.y1, inverse=True) # Pick location for environmental dpt # C.click_x_y() # Here, it is the end of the cross-section lon_env, lat_env = C.bmap(C.x1, C.y1, inverse=True) y_env, x_env, exactlat, exactlon = utils.getXY(self.W.lats1D, self.W.lons1D, lat_env, lon_env) # Create the cross-section object X = CrossSection(self.C, self.W, lat0, lon0, lat1, lon1) # Ask user the line-normal box width (self.km) #C.set_box_width(X) # Compute the grid (DX x DY) cps = self.W.cold_pool_strength(X, time, swath_width=swath_width, env=(x_env, y_env), dz=dz) # import pdb; pdb.set_trace() # Plot this array CPfig = BirdsEye(self.C, self.W, **cps_kwargs) tstr = utils.string_from_time('output', time) if dz: fprefix = 'ColdPoolDepth_' else: fprefix = 'ColdPoolStrength_' fname = fprefix + tstr pdb.set_trace() # imfig,imax = plt.subplots(1) # imax.imshow(cps) # plt.show(imfig) # CPfig.plot_data(cps,'contourf',outpath,fname,time,V=N.arange(5,105,5)) mplcommand = 'contour' plotkwargs = {} if dz: clvs = N.arange(100, 5100, 100) else: clvs = N.arange(10, 85, 2.5) if mplcommand[:7] == 'contour': plotkwargs['levels'] = clvs plotkwargs['cmap'] = plt.cm.ocean_r cf2 = CPfig.plot_data(cps, mplcommand, outpath, fname, time, **plotkwargs) # CPfig.fig.tight_layout() plt.close(fig) if twoplot: P2.save(outpath, fname + "_twopanel") if return_ax: return C.cf, cf2