def spaghetti(self, t, lv, va, contour, wrfouts, outpath, da=0, dom=0): """ wrfouts : list of wrfout files Only change dom if there are multiple domains. """ m, x, y = self.basemap_setup() time_idx = self.W.get_time_idx(t) colours = utils.generate_colours(M, len(wrfouts)) # import pdb; pdb.set_trace() if lv == 2000: lv_idx = None else: print("Only support surface right now") raise Exception lat_sl, lon_sl = self.get_limited_domain(da) slices = {'t': time_idx, 'lv': lv_idx, 'la': lat_sl, 'lo': lon_sl} # self.ax.set_color_cycle(colours) ctlist = [] for n, wrfout in enumerate(wrfouts): self.W = WRFOut(wrfout) data = self.W.get(va, slices)[0, ...] # m.contour(x,y,data,levels=[contour,]) ct = m.contour(x, y, data, colors=[ colours[n], ], levels=[ contour, ], label=wrfout.split('/')[-2]) print( ("Plotting contour level {0} for {1} from file \n {2}".format( contour, va, wrfout))) # ctlist.append(ct) # self.ax.legend() # labels = [w.split('/')[-2] for w in wrfouts] # print labels # self.fig.legend(handles=ctlist) # plt.legend(handles=ctlist,labels=labels) #labels,ncol=3, loc=3, # bbox_to_anchor=[0.5,1.5]) datestr = utils.string_from_time('output', t, tupleformat=0) lv_na = utils.get_level_naming(va, lv) naming = ['spaghetti', va, lv_na, datestr] if dom: naming.append(dom) fname = self.create_fname(*naming) self.save(outpath, fname)
def spaghetti(self,t,lv,va,contour,wrfouts,outpath,da=0,dom=0): """ wrfouts : list of wrfout files Only change dom if there are multiple domains. """ m,x,y = self.basemap_setup() time_idx = self.W.get_time_idx(t) colours = utils.generate_colours(M,len(wrfouts)) # import pdb; pdb.set_trace() if lv==2000: lv_idx = None else: print("Only support surface right now") raise Exception lat_sl, lon_sl = self.get_limited_domain(da) slices = {'t': time_idx, 'lv': lv_idx, 'la': lat_sl, 'lo': lon_sl} # self.ax.set_color_cycle(colours) ctlist = [] for n,wrfout in enumerate(wrfouts): self.W = WRFOut(wrfout) data = self.W.get(va,slices)[0,...] # m.contour(x,y,data,levels=[contour,]) ct = m.contour(x,y,data,colors=[colours[n],],levels=[contour,],label=wrfout.split('/')[-2]) print("Plotting contour level {0} for {1} from file \n {2}".format( contour,va,wrfout)) # ctlist.append(ct) # self.ax.legend() # labels = [w.split('/')[-2] for w in wrfouts] # print labels # self.fig.legend(handles=ctlist) # plt.legend(handles=ctlist,labels=labels) #labels,ncol=3, loc=3, # bbox_to_anchor=[0.5,1.5]) datestr = utils.string_from_time('output',t,tupleformat=0) lv_na = utils.get_level_naming(va,lv) naming = ['spaghetti',va,lv_na,datestr] if dom: naming.append(dom) fname = self.create_fname(*naming) self.save(outpath,fname)
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 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_error_growth(self, ofname, folder, pfname, sensitivity=0, ylimits=0, **kwargs): """Plots line graphs of DKE/DTE error growth varying by a sensitivity - e.g. error growth involving all members that use a certain parameterisation. ofname : output filename prefix pfname : pickle filename plotlist : list of folder names to loop over ylim : tuple of min/max for y axis range """ DATA = self.load_data(folder, pfname, format='pickle') for perm in DATA: times = DATA[perm]['times'] break times_tup = [time.gmtime(t) for t in times] time_str = ["{2:02d}/{3:02d}".format(*t) for t in times_tup] if sensitivity: # Plot multiple line charts for each sensitivity # Then a final chart with all the averages # If data is 2D, sum over x/y to get one number # Dictionary with average AVE = {} for sens in sensitivity: ave_stack = 0 n_sens = len(sensitivity) - 1 colourlist = utils.generate_colours(M, n_sens) M.rcParams['axes.color_cycle'] = colourlist fig = plt.figure() labels = [] #SENS['sens'] = {} for perm in DATA: f1 = DATA[perm]['file1'] f2 = DATA[perm]['file2'] if sens in f1: f = f2 elif sens in f2: f = f1 else: f = 0 if f: subdirs = f.split('/') labels.append(subdirs[-2]) data = self.make_1D(DATA[perm]['values']) plt.plot(times, data) # pdb.set_trace() ave_stack = utils.vstack_loop(N.asarray(data), ave_stack) else: pass # pdb.set_trace() n_sens += 1 colourlist = utils.generate_colours(M, n_sens) M.rcParams['axes.color_cycle'] = colourlist AVE[sens] = N.average(ave_stack, axis=0) labels.append('Average') plt.plot(times, AVE[sens], 'k') plt.legend(labels, loc=2, fontsize=9) if ylimits: plt.ylim(ylimits) plt.gca().set_xticks(times[::2]) plt.gca().set_xticklabels(time_str[::2]) outdir = self.C.output_root fname = '{0}_Growth_{1}.png'.format(ofname, sens) fpath = os.path.join(outdir, fname) fig.savefig(fpath) plt.close() print("Saved {0}.".format(fpath)) # Averages for each sensitivity labels = [] fig = plt.figure() ave_of_ave_stack = 0 for sens in AVE.keys(): plt.plot(times, AVE[sens]) labels.append(sens) ave_of_ave_stack = utils.vstack_loop(AVE[sens], ave_of_ave_stack) labels.append('Average') ave_of_ave = N.average(ave_of_ave_stack, axis=0) plt.plot(times, ave_of_ave, 'k') plt.legend(labels, loc=2, fontsize=9) if ylimits: plt.ylim(ylimits) plt.gca().set_xticks(times[::2]) plt.gca().set_xticklabels(time_str[::2]) outdir = self.C.output_root fname = '{0}_Growth_Averages.png'.format(ofname) fpath = os.path.join(outdir, fname) fig.savefig(fpath) plt.close() print("Saved {0}.".format(fpath)) #pdb.set_trace() else: fig = plt.figure() ave_stack = 0 for perm in DATA: data = self.make_1D(DATA[perm]['values']) plt.plot(times, data, 'blue') ave_stack = utils.vstack_loop(N.asarray(data), ave_stack) total_ave = N.average(ave_stack, axis=0) plt.plot(times, total_ave, 'black') if ylimits: plt.ylim(ylimits) plt.gca().set_xticks(times[::2]) plt.gca().set_xticklabels(time_str[::2]) outdir = self.C.output_root fname = '{0}_Growth_allmembers.png'.format(ofname) fpath = os.path.join(outdir, fname) fig.savefig(fpath) plt.close() print("Saved {0}.".format(fpath))