def save_ps_map(self, title, data, labels_on=True): """ Directly create a PS file of data with filename=title. Assumes normalized data between 0 and 1. INPUT: title a string describing the dataset data a numpy array containing the map to be drawn """ # Change the levels of contouring resources = self.resources resources.cnLevelSelectionMode = "ExplicitLevels" # Define own levels. resources.cnLevels = np.arange(0., 1., 0.05) wks_type = "ps" wks = Ngl.open_wks(wks_type, title, resources) if labels_on: resources.lbTitleString = title # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def save_ps_map(self, title, data, labels_on=True): """ Directly create a PS file of data with filename=title. Assumes normalized data between 0 and 1. INPUT: title a string describing the dataset data a numpy array containing the map to be drawn """ # Change the levels of contouring resources = self.resources resources.cnLevelSelectionMode = "ExplicitLevels" # Define own levels. resources.cnLevels = np.arange(0., 1., 0.05) wks_type = "ps" wks = Ngl.open_wks(wks_type, title, resources) if labels_on: resources.lbTitleString = title # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def save(self,filename = 'plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps',filename,self.WorkstationResources) Ngl.change_workstation(self.plot,weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot,self.workstation) Ngl.destroy(weps)
def save(self, filename='plot'): #'eps' workstation doesn't work reliably, but 'ps' is OK weps = Ngl.open_wks('ps', filename, self.WorkstationResources) Ngl.change_workstation(self.plot, weps) Ngl.draw(self.plot) Ngl.change_workstation(self.plot, self.workstation) Ngl.destroy(weps)
def generate_multiple_map_plots_npy(self, map_names, map_scales, title_on=True, labels_on=True): """ Method for very large datasets (RAM issues) and useful for PARALLEL code. Generates map plots from the datasets stored in the npy files and the list of titles. The data is sorted as parallel computation mixes it up. Stores the plots in the file indicated by filename in the current directory. """ # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title for k in range(len(self.map_mult_data)): # Open a workstation for every map, only wks_type = "ps" allows # multiple workstation # Sort dataset, as parallel code will mix it self.map_mult_data[k].sort() # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for ititle in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = ititle data = np.load(str(k) + "_" + ititle + ".npy") # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up for file_name in glob.glob('*.npy'): os.remove(file_name) del resources Ngl.end()
def generate_multiple_map_plots_npy(self, map_names, map_scales, title_on=True, labels_on=True): """ Method for very large datasets (RAM issues) and useful for PARALLEL code. Generates map plots from the datasets stored in the npy files and the list of titles. The data is sorted as parallel computation mixes it up. Stores the plots in the file indicated by filename in the current directory. """ # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title for k in range(len(self.map_mult_data)): # Open a workstation for every map, only wks_type = "ps" allows # multiple workstation # Sort dataset, as parallel code will mix it self.map_mult_data[k].sort() # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for ititle in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = ititle data = np.load(str(k) + "_" + ititle + ".npy") # Reshape for visualization on the sphere data.shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, data, resources) # Clear map del cmap Ngl.destroy(wks) # Clean up for file_name in glob.glob('*.npy'): os.remove(file_name) del resources Ngl.end()
def plot(filename, outputend): # set up parameters f = Nio.open_file(filename) q = f.variables['q'][:, 0, :] r2d = 57.2957795 lat = f.variables['lat'][:, :]*r2d lon = f.variables['lon'][:, :]*r2d vertx = f.variables['vertx'][:, :, :]*r2d verty = f.variables['verty'][:, :, :]*r2d ncols = f.variables['nCols'][:] ae = 6.371229e6 # Open a workstation. wks_type = "pdf" rlist = Ngl.Resources() rlist.wkColorMap = "WhBlReWh" # Create contour and map resource lists. for it in range(13): wks = Ngl.open_wks(wks_type,"Moving_"+str(it)+outputend, rlist) cnres = Ngl.Resources() cnres.nglFrame = False # cnres.nglDraw = False cnres.mpGridAndLimbOn = False cnres.mpOutlineOn = False cnres.mpPerimOn = False# ; turn off box around plot cnres.nglMaximize = True cnres.mpProjection = "Orthographic" # Change the map projection. # x_c, y_c = 0, 90.#qmoving(it*24.*3600., 12.*24.*3600., 0.25*np.pi, ae) cnres.mpCenterLonF = x_c*r2d # Rotate the projection. cnres.mpCenterLatF = y_c*r2d # Rotate the projection. cnres.mpOutlineOn = False cnres.sfXArray = lon[it, 0:ncols[it]] cnres.sfYArray = lat[it, 0:ncols[it]] cnres.cnLinesOn = False cnres.cnFillOn = True cnres.cnLineLabelsOn = False cnres.cnInfoLabelOn = False cnres.lbLabelBarOn = True cnres.cnLevelSelectionMode = "ManualLevels" cnres.cnMinLevelValF = 0.4 cnres.cnMaxLevelValF = 1.6 cnres.cnLevelSpacingF = 0.05 cnres.pmTickMarkDisplayMode = "Never" contour1 = Ngl.contour_map(wks,q[it, 0:ncols[it]],cnres) gsres = Ngl.Resources() gsres.gsLineColor = "Gray25" gsres.gsLineThicknessF = 3.0 # print(vertx[0, :, 0],verty[0, :, 0]) for nc in range(ncols[it]): Ngl.polyline(wks,contour1,vertx[it, :, nc],verty[it, :, nc],gsres) # Ngl.draw(contour1) Ngl.frame(wks) Ngl.destroy(wks) Ngl.end()
def generate_multiple_map_plots(self, map_names, map_scales, title_on=True, labels_on=True): """ Generate map plots from the datasets stored in the :attr:`map_data` list of dictionaries. Stores the plots in the file indicated by filename in the current directory. """ for k in range(len(self.map_mult_data)): # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title # Open a workstation for every map, only wks_type = "ps" allows # multiple workstations # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for dataset in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = dataset["title"] # Reshape for visualization on the sphere dataset["data"].shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, dataset["data"], resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def generate_multiple_map_plots(self, map_names, map_scales, title_on=True, labels_on=True): """ Generate map plots from the datasets stored in the :attr:`map_data` list of dictionaries. Stores the plots in the file indicated by filename in the current directory. """ for k in xrange(len(self.map_mult_data)): # Set resources resources = self.resources # Set plot title if title_on: resources.tiMainString = self.title # Open a workstation for every map, only wks_type = "ps" allows # multiple workstations # Define own levels resources.cnLevelSelectionMode = "ExplicitLevels" resources.cnLevels = map_scales[k] wks_type = "pdf" wks = Ngl.open_wks(wks_type, map_names[k], resources) # # Generate map plots # for dataset in self.map_mult_data[k]: # Set title if labels_on: resources.lbTitleString = dataset["title"] # Reshape for visualization on the sphere dataset["data"].shape = (self.grid.grid_size()["lat"], self.grid.grid_size()["lon"]) # Generate map plot cmap = Ngl.contour_map(wks, dataset["data"], resources) # Clear map del cmap Ngl.destroy(wks) # Clean up del resources Ngl.end()
def clubb_skw_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "C6rt_Skw_fnc", "C11_Skw_fnc", "C1_Skw_fnc", "C7_Skw_fnc", "Lscale", "Richardson_num", "Kh_zm", "tau_zm", "Skw_velocity" ] varisobs = [ "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U", "CIWC_ISBL", "T" ] nvaris = len(varis) cunits = [ "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s", "K", "m" ] cscale = [ 1, 1, 1, 1, 1., 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] obsdataset = [ "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI" ] plotskw = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotskw[ire] = 'CLUBB_skewfunc_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 # res.tmXBLabelAngleF = 45 res.xyMarkLineMode = "Lines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkWidth = 2500 pres.wkHeight = 2500 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = False else: res.pmLegendDisplayMode = "NEVER" # if(obsdataset[iv] =="CCCM"): # if(cseason == "ANN"): # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc" # else: # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc" # inptrobs = Dataset(fileobs,'r') # B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])] # else: # if (varisobs[iv] =="PRECT"): # fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' # else: # fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' # inptrobs = Dataset(fileobs,'r') # if (varisobs[iv] =="THETA"): # B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])] # pre1 = inptrobs.variables['lev'][:] # for il1 in range (0, len(pre1)): # B[il1] = B[il1]*(1000/pre1[il1])**0.286 # else: # pre1 = inptrobs.variables['lev'][:] # B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])] # # B[:]=B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['ilev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] else: tmp = inptrs.variables[varis[iv]][0, :, npoint] theunits = str( cscale[iv]) + inptrs.variables[varis[iv]].units A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiMainString = varis[iv] + " " + theunits # res.trXMinF = min(np.min(A_field[0, :])) # res.trXMaxF = max(np.max(A_field[0, :])) res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) # res.trYReverse = False # res.xyLineColors = ["black"] # pt = Ngl.xy(wks,B,pre1,res) # Ngl.overlay(p,pt) plot.append(p) pres.txString = "Skewness Functions at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc( wks, "Skewness Functions at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres) Common_functions.create_legend(wks, casenames, 0.02, np.arange(3, 20, 2), 0.1, 0.89 + ncases * 0.01) Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres) Ngl.frame(wks) Ngl.destroy(wks) return plotskw
res2.tiMainString = str(sinefreq2)+"-Hz Sine Wave"+ \ "~C~~B~"+leftname res3.trYMinF = -10.0 # Limits for Y axis res3.trYMaxF = 10.0 res3.xyLineColors = ["navy"] res3.tiMainString = "Simulated Signal of Mixed Sine Waves With White Noise, "+ \ "~C~SNR = {} dB".format(SNR) plot = [] plot.append(Ngl.xy(wks,t,sig1,res)) plot.append(Ngl.xy(wks,t,sig2,res2)) plot.append(Ngl.xy(wks,t,data,res3)) panelres = Ngl.Resources() Ngl.panel(wks,plot[0:3+1],[3,1],panelres) Ngl.destroy(wks); del res, panelres, plot """ Plot 2-1 """ image_name = "FFT_ex3_2" resf = Ngl.Resources() (wks,resf,dummy) = wks_setting(resf,image_name) resf.xyLineColors = ["navy"] resf.xyLineThicknesses = [25] resf.vpWidthF = 0.74; resf.vpHeightF = 0.54 resf.tiMainFontHeightF = 0.025 resf.tiXAxisString = "~F25~Frequency (Hz)" resf.tiYAxisString = "~F25~Power Spectrum (dB)" leftname = "~F25~Period from ~F34~%~F25~ to {} seconds".format(1./faxis[-1]) resf.tiMainString = "Spectral Analysis (FFT)"+ \ "~C~~B~"+leftname resf.trYMinF = -100 # Limits for Y axis
def draw_clubb_bgt(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plotbgt = ["" for x in range(nsite * ncases)] alphas = [ 'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) ' ] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason plotbgt[im + ncases * ire] = pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.nglScale = False # res.vpWidthF = 0.40 # set width and height # res.vpHeightF = 0.40 # res.vpXF = 0.04 # res.vpYF = 0.30 res.nglMaximize = False if (lats[ire] > 0 and lons[ire] < 230): res.trYMinF = 400. res.trYMaxF = 1000. else: res.trYMinF = 700. res.trYMaxF = 1000. res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.02 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2, 2 ] res.xyLineColors = np.arange(1, 16, 4) res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(1, 16, 4) res.pmLegendDisplayMode = "NEVER" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.75 # move units right res.pmLegendOrthogonalPosF = -0.65 # more neg = down res.pmLegendWidthF = 0.05 # Change width and res.pmLegendHeightF = 0.06 # height of legend. res.lgLabelFontHeightF = 0.03 # change font height res.lgLabelFontThicknessF = 1. # res.lgBoxMinorExtentF = 0.5 res.lgPerimOn = False res.tiYAxisString = "Pressure [hPa]" res.tmYLLabelFontHeightF = 0.02 res.trYReverse = True res1 = Ngl.Resources() res1 = res pres = Ngl.Resources() # pres.gsnPaperOrientation= "Landscape" # pres.wkPaperWidthF = 20 # in inches # pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = False # pres.vpWidthF = 0.40 # set width and height # pres.vpHeightF = 0.40 pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 3 pres.nglPanelTop = .9 # pres.nglPanelBottom=0.3 # pres.nglPanelLeft= 0.2 # pres.nglPanelRight= 0.95 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range(0, nvaris): if (varis[iv] == "rtp2" or varis[iv] == "thlp2"): budget_ends = ["_ta", "_tp", "_dp1"] budget_name = [ '~F10~turb adv', '~F10~turb prod', '~F10~dissipation' ] nterms = len(budget_ends) if (varis[iv] == "wprtp"): budget_ends = [ "_bt", "_ma", "_ta", "_tp", "_ac", "_bp", "_pr1", "_pr2", "_pr3", "_dp1", "_mfl", "_cl", "_sicl", "_pd", "_forcing" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wpthlp"): budget_ends = ["_tp", "_bp", "_pr1"] budget_name = [ '~F10~turb prod', '~F10~buoy+pres', '~F10~ret to iso' ] nterms = len(budget_ends) if (varis[iv] == "rtpthlp"): budget_ends = [ "_bt", "_ma", "_ta", "_tp1", "_tp2", "_dp1", "_dp2", "_cl", "_sf", "_forcing" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wp2"): budget_ends = ["_ta", "_bp", "_pr1", "_dp1", "_dp2"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "wp3"): budget_ends = [ "_ta", "_tp", "_bp1", "_bp2", "_pr1", "_pr2", "_dp1" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "up2" or varis[iv] == "vp2"): budget_ends = [ "_bt", "_ma", "_ta", "_tp", "_dp1", "_dp2", "_pr1", "_pr2", "_cl", "_pd", "_sf" ] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "um" or varis[iv] == "vm"): budget_ends = ["_bt", "_ma", "_ta", "_gf", "_f"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == "thlm" or varis[iv] == "rtm"): budget_ends = ["_bt", "_ma", "_ta", "_cl", "_mc"] budget_name = budget_ends nterms = len(budget_ends) if (varis[iv] == 'tau_no_N2_zm'): budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear'] budget_name = [ '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bkgnd~N~', '~F8~t~N~~F25~~B~shear~N~', '~F8~t~N~~F25~~B~shear~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_xp2_zm'): budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm'] budget_name = [ '~F8~t~N~~F25~~B~x`~S~2~N~~N~', '~F8~t~N~~F25~~B~noN2~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp2_zm'): budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos'] budget_name = [ '~F8~t~N~~F25~~B~w`~S~2~N~~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wpxp_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ '~F8~t~N~~F25~~B~w`x`~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~', '~F8~t~N~~F25~~B~clr~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp3_zm'): budget_ends = [ 'tau_wp3_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ '~F8~t~N~~F25~~B~w`~S~3~N~~N~', '~F8~t~N~~F25~~B~noN2~N~', '~F8~t~N~~F25~~B~bv~N~', '~F8~t~N~~F25~~B~clr~N~' ] nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['ilev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) for it in range(0, nterms): for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 varis_bgt = varis[iv] + budget_ends[it] tmp0 = inptrs.variables[varis[iv]][0, :, npoint] theunits0 = "~F25~" + inptrs.variables[varis[iv]].units if (varis[iv] == 'wpthlp' and budget_ends[it] == '_bp'): tmp = inptrs.variables[varis_bgt][ 0, :, npoint] + inptrs.variables['wpthlp_pr3'][ 0, :, npoint] else: tmp = inptrs.variables[varis_bgt][0, :, npoint] theunits = str( chscale[iv]) + "~F25~" + inptrs.variables[ varis[iv] + '_bt'].units if (varis[iv] == "wprtp" or varis[iv] == "thlp2"): tmp[0:10] = 0.0 tmp0[0:10] = 0.0 txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font tmp = tmp * cscale[iv] A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.tiXAxisString = vname[iv] + ' Unit= ' + theunits if (varis[iv] == "wpthlp" or varis[iv] == "thlp2" or varis[iv] == "wp3" or varis[iv] == "wp2"): res1.tiXAxisString = vname[iv] + ' Unit= ' + theunits0 p0 = Ngl.xy(wks, tmp0, ilev, res1) plot.append(p0) if (varis[iv] == 'wpthlp'): if (lons[ire] < 230): res.trXMinF = -1. res.trXMaxF = 1. Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) else: res.trXMinF = -0.4 res.trXMaxF = 0.4 Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) if (varis[iv] == 'thlp2'): if (lons[ire] < 230): res.trXMinF = -2.8 res.trXMaxF = 2.8 Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) else: res.trXMinF = -1. res.trXMaxF = 1. Common_functions.create_legend(wks, budget_name, 0.013, np.arange(1, 16, 4), 0.77, 0.85 - iv * 0.45) res.tiXAxisString = vname[iv] + ' Unit= ' + theunits p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) del (res.trXMaxF) del (res.trXMinF) xp = np.mod(iv, 2) yp = int(iv / 2) Ngl.panel(wks, plot[:], [nvaris, 2], pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.02 Ngl.text_ndc( wks, casenames[im] + " BUDGET at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.91, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plotbgt)
# use colormap and type information to setup output background wks_type = "pdf" wks = Ngl.open_wks(wks_type,"HighRes"+str(it), rlist) # resources for the contour res = Ngl.Resources() res.lbLabelBarOn = False # Filled contour/labels/labelinfos res.cnLinesOn = False res.cnFillOn = True res.cnLineLabelsOn = False res.cnInfoLabelOn = False res.mpGridAndLimbOn = False #Level selection res.cnLevelSelectionMode = "ExplicitLevels" # Set explicit contour levels res.cnLevels = np.arange(1e-5,8.e-4, 4e-5) # 0,5,10,...,70 # maximize the plot contour = [] res.nglMaximize = True res.nglFrame = False # coordinate settings NewTracerPlot, LonPlot = Ngl.add_cyclic(NewTracer_AI_High[it, lev, :, :], lon_high) res.sfXArray = LonPlot res.sfYArray = lat_high[:] res.vpWidthF = 1 res.vpHeightF = 0.5 Ngl.contour_map(wks,NewTracerPlot,res) Ngl.frame(wks) Ngl.destroy(wks) Ngl.end()
def plot_statistical_value_around_point(path, run, data_tmax_24h, point, stat_processing): if stat_processing['method'] == 'max': data_processed = data_tmax_24h.max(axis=0) elif stat_processing['method'] == 'min': data_processed = data_tmax_24h.min(axis=0) elif stat_processing['method'] == 'median': data_processed = np.percentile(data_tmax_24h, 50, axis=0) elif stat_processing['method'] == 'spread': data_processed = data_tmax_24h.std(axis=0) elif stat_processing['method'] == 'member_extract': data_processed = data_tmax_24h[stat_processing['member'] - 1, :] ######################################################################## mpi_file = nc.Dataset( path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = mpi_file.variables['clat_vertices'][:].data * 180. / np.pi vlon = mpi_file.variables['clon_vertices'][:].data * 180. / np.pi clat = mpi_file.variables['clat'][:].data * 180. / np.pi clon = mpi_file.variables['clon'][:].data * 180. / np.pi mpi_file.close() ######################################################################## if stat_processing['method'] == 'max'\ or stat_processing['method'] == 'min'\ or stat_processing['method'] == 'spread'\ or stat_processing['method'] == 'median': member_text_filename = stat_processing['method'] elif stat_processing['method'] == 'member_extract': member_text_filename = 'm{:02d}'.format(stat_processing['member']) plot_name = 'iconeueps_tmax_24h_{}_run_{:02d}.{:02d}._{}'.format(\ member_text_filename, run['day'], run['month'], point['name']) ######################################################################## x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources() resources.mpProjection = 'Hammer' resources.mpCenterLonF = point['lon'] resources.mpCenterLatF = point['lat'] radius = 700 # image radius in km around centered point cutout_plot = dict( lat_min=point['lat'] - radius / 111.2, lat_max=point['lat'] + radius / 111.2, lon_min=point['lon'] - radius / (111.2 * np.cos(point['lat'] * np.pi / 180)), lon_max=point['lon'] + radius / (111.2 * np.cos(point['lat'] * np.pi / 180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.95 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ######################################################################## # Turn on filled map areas: resources.mpFillOn = True # Set colors for [FillValue, Ocean, Land , InlandWater]: resources.mpFillColors = ['pink', 'blue', 'white', 'blue'] resources.mpDataBaseVersion = 'MediumRes' resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 resources.tmXBOn = False resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed resources.sfXArray = clon resources.sfYArray = clat resources.sfXCellBounds = vlon resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 resources.cnFillOn = True resources.cnFillMode = 'CellFill' #resources.cnCellFillEdgeColor = 'black' resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'GMT_wysiwygcont' resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 maxlevel = 45.0 numberoflevels = 45 resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels if stat_processing['method'] == 'spread': resources.cnFillPalette = 'WhiteYellowOrangeRed' minlevel = 0.0 maxlevel = 4.0 # Turn off contour lines and labels: resources.cnLinesOn = False resources.cnLineLabelsOn = False # Set resources for a nice label bar resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 5 #25 resources.lbLabelFontHeightF = 0.02 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'K' resources.lbTitleFontHeightF = 0.02 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' #resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = 0.0 resources.nglFrame = False plot = Ngl.contour_map(wks, data_processed, resources) ######################################################################## '''polymarker_res_1 = Ngl.Resources() polymarker_res_1.gsMarkerColor = 'black' polymarker_res_1.gsMarkerIndex = 16 polymarker_res_1.gsMarkerSizeF = 0.012 polymarker_res_1.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_1) ######################################################################## polymarker_res_2 = Ngl.Resources() polymarker_res_2.gsMarkerColor = 'white' polymarker_res_2.gsMarkerIndex = 16 polymarker_res_2.gsMarkerSizeF = 0.008 polymarker_res_2.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_2)''' ######################################################################## if stat_processing['method'] == 'max'\ or stat_processing['method'] == 'min'\ or stat_processing['method'] == 'spread'\ or stat_processing['method'] == 'median': member_text = '{} of members'.format(stat_processing['method']) elif stat_processing['method'] == 'member_extract': member_text = 'member {:d}'.format(stat_processing['member']) text = 'tmax 00Z-00Z for 25.07.19, icon-eu-eps run {:02d}.{:02d}.19, {}'.format(\ run['day'], run['month'], member_text) x = 0.1 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.018 text_res_1.txJust = 'BottomLeft' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) return
def large_scale_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = 'Red' mkres.gsMarkerSizeF = 15. infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] nregions = nsite localnames=np.append('ERAI',casenames) varis = [ 'CLOUD' , 'CLDLIQ', 'THETA','RELHUM'] varisobs = ['CC_ISBL', 'CLWC_ISBL', 'THETA','RELHUM' ] alphas = ['a) ','b) ','c) ','d) ','e) ','f) ','g) ','h) ','i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) '] nvaris = len(varis) cunits = ['%','g/kg','K', '%' ] cscale = [100, 1000 , 1., 1 ] cscaleobs = [100, 1000 , 1., 1, 1, 1000, 1,1,1,1,1,1,1] obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI'] plotlgs=['' for x in range(nsite)] for ire in range (0, nsite): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason plotlgs[ire] = 'Largescale_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,'GMT_paired') plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.tiYAxisString = "Pressure [hPa]" if (lats[ire] > 0 and lons[ire]<230 ): res.trYMinF = 400. res.trYMaxF = 1000. else: res.trYMinF = 700. res.trYMaxF = 1000. res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'Lines' res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3] res.xyDashPatterns = np.arange(0,24,1) pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 # pres.nglPanelTop = 0.88 pres.wkPaperWidthF = 17 # in inches pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = True pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range (0, nvaris): if(iv == nvaris-1): res.pmLegendDisplayMode = 'NEVER' res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = 'top' res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = 'NEVER' if(obsdataset[iv] =='CCCM'): if(cseason == 'ANN'): fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-'+cseason+'.nc' else: fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-'+cseason+'.nc' inptrobs = Dataset(fileobs,'r') latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B=inptrobs.variables[varisobs[iv]][:,latobs_idx,lonobs_idx] else: if (varisobs[iv] =='PRECT'): fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' else: fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs,'r') if (varisobs[iv] =='THETA'): latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables['T'][0,:,latobs_idx,lonobs_idx] pre1 = inptrobs.variables['lev'][:] for il1 in range (0, len(pre1)): B[il1] = B[il1]*(1000/pre1[il1])**0.286 else: pre1 = inptrobs.variables['lev'][:] latobs=inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs=inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][0,:,latobs_idx,lonobs_idx] B[:]=B[:] * cscaleobs[iv] for im in range (0,ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) lev=inptrs.variables['lev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() if (im ==0 ): A_field = np.zeros((ncases,nlev),np.float32) for subc in range( 0, n[ire]): npoint=idx_cols[ire,n[subc]-1]-1 if (varis[iv] == 'THETA'): tmp = inptrs.variables['T'][0,:,npoint] hyam =inptrs.variables['hyam'][:] hybm =inptrs.variables['hybm'][:] ps=inptrs.variables['PS'][0,npoint] ps=ps p0=inptrs.variables['P0'] pre = np.zeros((nlev),np.float32) for il in range (0, nlev): pre[il] = hyam[il]*p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000/pre[il])**0.286 theunits=str(cscale[iv])+inptrs.variables['T'].units else: tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(cscale[iv])+inptrs.variables[varis[iv]].units A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 ) A_field[im,:] = A_field[im,:] *cscale[iv] inptrs.close() textres = Ngl.Resources() textres.txFontHeightF = 0.02 textres.txFont = _Font textres.txFontHeightF = 0.015 res.tiXAxisString = varis[iv]+ " Unit= " + cunits[iv] res.trXMinF = min(np.min(A_field[0, :]),np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]),np.max(B)) if(varis[iv] == 'CLOUD') : if (lats[ire] >= 0 and lons[ire]<230): res.trXMinF = 0. res.trXMaxF = 50. else: res.trXMinF = 0. res.trXMaxF = 100. if(varis[iv] =='CLDLIQ') : if (lats[ire] >= 0): res.trXMinF = 0. res.trXMaxF = 0.1 else: res.trXMinF = 0. res.trXMaxF = 0.1 if(varis[iv] =='RELHUM') : res.trXMinF = 0. res.trXMaxF = 100. if(varis[iv] == 'THETA') : if (lats[ire] >= 0 and lons[ire]<230 ): res.trXMinF = 290. res.trXMaxF = 340. else: res.trXMinF = 280 res.trXMaxF = 320 if(varis[iv] == 'T') : res.trXMinF = 180 res.trXMaxF = 300 if(varis[iv] == 'U') : res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(3,20,2) res.xyMarkerColors = np.arange(2,20,2) p = Ngl.xy(wks,A_field,lev,res) res.trYReverse = False res.xyLineColors = ['black'] pt = Ngl.xy(wks,B,pre1,res) Ngl.overlay(p,pt) plot.append(p) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc(wks,'Large-scale VAR at '+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.93,txres) Common_functions.create_legend(wks,localnames,0.02,np.append('black',np.arange(3,20,2)),0.25,0.85) Ngl.frame(wks) Ngl.destroy(wks) return plotlgs
def rain_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,varis,cscale,chscale,pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = 'Red' mkres.gsMarkerSizeF = 15. infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] nregions = nsite varisobs = ['CC_ISBL', 'OMEGA','SHUM','CLWC_ISBL', 'THETA','RELHUM','U','CIWC_ISBL','T' ] nvaris = len(varis) cunits = ['%','mba/day','g/kg','g/kg','K', '%', 'm/s', 'g/kg', 'm/s', 'm/s','K','m' ] cscaleobs = [100, 1, 1, 1000 , 1., 1, 1, 1000, 1,1,1,1,1,1,1] obsdataset =['ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI', 'ERAI','ERAI','ERAI'] plotrain=['' for x in range(nsite)] for ire in range (0, nsite): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/'+pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason plotrain[ire] = pname+'_'+str(lons[ire])+'E_'+str(lats[ire])+'N_'+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,'GMT_paired') plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .02 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiMainFont = _Font res.tmXBLabelFontHeightF = 0.015 res.tmXBLabelFontThicknessF = 1.0 # res.tmXBLabelAngleF = 45 res.xyMarkLineMode = 'Lines' res.xyLineThicknesses = [3.0, 3.0, 3.0, 3.0, 3.0, 3.0,3.,3.,3.,3.,3,3,3,3,3,3,3] res.xyDashPatterns = np.arange(0,24,1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkWidth = 2500 pres.wkHeight = 2500 for iv in range (0, nvaris): if(iv == nvaris-1): res.pmLegendDisplayMode = 'Never' res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = 'top' res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = False else: res.pmLegendDisplayMode = 'NEVER' for im in range (0,ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) lev=inptrs.variables['lev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() if (im ==0): A_field = np.zeros((ncases,nlev),np.float32) for subc in range( 0, n[ire]): npoint=idx_cols[ire,n[subc]-1]-1 tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(chscale[iv])+'x'+inptrs.variables[varis[iv]].units A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 ) A_field[im,:] = A_field[im,:] *cscale[iv] inptrs.close() res.tiMainString = varis[iv]+' '+theunits # res.trXMinF = min(np.min(A_field[0, :])) # res.trXMaxF = max(np.max(A_field[0, :])) res.trYReverse = True res.xyLineColors = np.arange(3,20,2) res.xyMarkerColors = np.arange(2,20,2) p = Ngl.xy(wks,A_field,lev,res) # res.trYReverse = False # res.xyLineColors = ['black'] # pt = Ngl.xy(wks,B,pre1,res) # Ngl.overlay(p,pt) plot.append(p) pres.txString = pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N' txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc(wks,pname+' at'+ str(lons[ire])+'E,'+str(lats[ire])+'N',0.5,0.92+ncases*0.01,txres) Common_functions.create_legend(wks,casenames,np.arange(3,20,2),0.1,0.89+ncases*0.01) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) Ngl.frame(wks) Ngl.destroy(wks) return plotrain
def draw_e3sm_bgt (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,dpsc): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "DCQ","DCCLDLIQ","DCCLDICE","PTEQ","PTTEND","DTCOND"] nvaris = len(varis) cscale = [1E8, 1E8, 1E8, 1E8, 1E4, 1E4] chscale = ['1E-8', '1E-8', '1E-8', '1E-8', '1E-4', '1E-4'] plote3smbgt=["" for x in range(nsite*ncases)] for ire in range (0, nsite): for im in range (0,ncases): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason plote3smbgt[im+ncases*ire] = 'E3SM_Budgets_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,"radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # res.txFontHeightF = .01 # res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = 12 res.tmXBLabelFont = 12 res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2] res.xyLineColors = np.arange(2,16,2) res.xyDashPatterns = np.arange(0,24,1) res.xyMarkers = np.arange(16,40,1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(2,16,2) res.pmLegendDisplayMode = "ALWAYS" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.6 # move units right res.pmLegendOrthogonalPosF = -0.55 # more neg = down res.pmLegendWidthF = 0.2 # Decrease width res.pmLegendHeightF = 0.1 # Decrease height res.lgBoxMinorExtentF = 0.1 # Shorten the legend lines res.lgLabelFontHeightF = 0.015 # Change the font size res.lgPerimOn = True res.tiYAxisString = "PRESSURE" res.trYReverse = True pres = Ngl.Resources() pres.nglMaximize = True pres.wkWidth = 2000 pres.wkHeight = 2000 pres.nglFrame = False pres.txFont = 12 pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 for iv in range (0, nvaris): if (varis[iv] == "DCQ" ): if (dpsc[im] == "zm" ): budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len (budget_ends) if (varis[iv] == "DTCOND" ): if (dpsc[im] == "zm" ): budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT","ZMDT", "EVAPTZM", "ZMMTT"] else: budget_ends = ["STEND_CLUBB", "MPDT", "DPDLFT"] nterms = len (budget_ends) if (varis[iv] == "PTTEND") : budget_ends = ["DTCOND", "QRS", "QRL", "TTGW"] nterms = len (budget_ends) if (varis[iv] == "PTEQ") : if (dpsc[im] == "zm" ): budget_ends = ["MPDQ", "RVMTEND_CLUBB","ZMDQ", "EVAPQZM"] else: budget_ends = ["MPDQ", "RVMTEND_CLUBB"] nterms = len (budget_ends) if (varis[iv] == "DCCLDLIQ") : if (dpsc[im] == "zm" ): budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ","ZMDLIQ"] else: budget_ends = ["MPDLIQ", "RCMTEND_CLUBB", "DPDLFLIQ"] nterms = len (budget_ends) if (varis[iv] == "DCCLDICE") : if (dpsc[im] == "zm" ): budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE","ZMDICE"] else: budget_ends = ["MPDICE", "RIMTEND_CLUBB", "DPDLFICE"] nterms = len (budget_ends) ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) ilev=inptrs.variables['lev'][:] nilev=len(ilev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() A_field = np.zeros((nterms,nilev),np.float32) theunits=str(chscale[iv])+"x"+inptrs.variables[varis[iv]].units res.tiMainString = varis[iv]+" "+theunits for it in range(0, nterms): for subc in range( 0, n[ire]): varis_bgt= budget_ends[it] npoint=idx_cols[ire,n[subc]-1]-1 tmp=inptrs.variables[varis_bgt][0,:,npoint] #/n[ire] tmp=tmp*cscale[iv] if (varis_bgt == "MPDT" or varis_bgt == "STEND_CLUBB" ): tmp=tmp/1004 A_field[it,:] = (A_field[it,:]+tmp[:]/n[ire]).astype(np.float32 ) inptrs.close() res.xyExplicitLegendLabels = budget_ends[:] p = Ngl.xy(wks,A_field,ilev,res) plot.append(p) xp=np.mod(iv,2) yp=int(iv/2) Ngl.panel(wks,plot[:],[nvaris/2,2],pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc(wks,casenames[im]+" BUDGET at" +str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.95,txres) Ngl.frame(wks) Ngl.destroy(wks) return (plote3smbgt)
def grid_order_contourplot(model, grid, first_varying_var, cut_domain): # define paths # path = dict(base='/', plots='data/plots/experimental/gridpoint_order/') print('plotting model: {}'.format(model)) # load icosahedral grid information # if grid == 'icosahedral': clat, clon, vlat, vlon = read_grid_coordinates(model, grid) data_array1 = np.arange(clat.shape[0], dtype='float32') else: clat, clon = read_grid_coordinates(model, grid) clon = clon - 180 if first_varying_var == 'lon': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clat.shape[0], clon.shape[0])) elif first_varying_var == 'lat': data_array1 = np.arange(clat.shape[0] * clon.shape[0], dtype='float32').reshape( (clon.shape[0], clat.shape[0])).T print('data_array1:', data_array1.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1 min,max:', data_array1.min(), data_array1.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) print('------------------------------------------') if cut_domain['name'] == 'uncut': data_array1_cut = data_array1 else: margin_deg = 0 if grid == 'icosahedral': data_array1_cut, clat, clon, vlat, vlon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, vlat, vlon, margin_deg) else: data_array1_cut, clat, clon \ = cut_by_domain(cut_domain, grid, data_array1, clat, clon, None, None, margin_deg) print('data_array1:', data_array1_cut.shape, 'clat:', clat.shape, 'clon:', clon.shape) if grid == 'icosahedral': print('vlat:', vlat.shape, 'vlon:', vlon.shape) print('data_array1_cut min,max:', data_array1_cut.min(), data_array1_cut.max()) print('clat min,max:', clat.min(), clat.max()) print('clon min,max:', clon.min(), clon.max()) if grid == 'icosahedral': print('vlat min,max:', vlat.min(), vlat.max()) print('vlon min,max:', vlon.min(), vlon.max()) if grid == 'icosahedral': plot_name = 'gridpoint_order_{}_{}_global_{}'.format( model, grid, cut_domain['name']) else: plot_name = 'gridpoint_order_{}_{}_{}-varying-first_global_{}'.format( model, grid, first_varying_var, cut_domain['name']) # plot basic map with borders # wks_res = Ngl.Resources() x_resolution = 800 y_resolution = 800 wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_res.wkColorMap = 'BkBlAqGrYeOrReViWh200' levels1 = np.linspace(data_array1.min(), data_array1.max(), 200) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) mpres = Ngl.Resources() mpres.mpProjection = 'CylindricalEquidistant' mpres.mpLimitMode = 'LatLon' mpres.mpCenterLonF = 0.0 mpres.mpCenterLatF = 0.0 mpres.mpMinLonF = -180. mpres.mpMaxLonF = 180. mpres.mpMinLatF = -90. mpres.mpMaxLatF = 90. mpres.nglMaximize = False mpres.vpXF = 0.003 mpres.vpYF = 1.00 mpres.vpWidthF = 0.86 mpres.vpHeightF = 1.00 mpres.mpMonoFillColor = 'True' mpres.mpFillColor = -1 #Ngl.set_values(wks,mpres) mpres.mpFillOn = True #resources.cnFillDrawOrder = 'Predraw' # draw contours first mpres.mpGridAndLimbOn = False mpres.mpGreatCircleLinesOn = False #mpres.mpOutlineDrawOrder = 'PreDraw' mpres.mpDataBaseVersion = 'LowRes' mpres.mpDataSetName = 'Earth..4' mpres.mpOutlineBoundarySets = 'national' mpres.mpGeophysicalLineColor = 'black' mpres.mpNationalLineColor = 'black' mpres.mpGeophysicalLineThicknessF = 2. * x_resolution / 1000 mpres.mpNationalLineThicknessF = 2. * x_resolution / 1000 mpres.mpPerimOn = True mpres.mpPerimLineColor = 'black' mpres.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 mpres.tmXBOn = False mpres.tmXTOn = False mpres.tmYLOn = False mpres.tmYROn = False mpres.nglDraw = False #-- don't draw plot mpres.nglFrame = False #-- don't advance frame basic_map = Ngl.map(wks, mpres) # plot variable1 in shading/contours # v1res = Ngl.Resources() v1res.sfDataArray = data_array1_cut v1res.sfXArray = clon v1res.sfYArray = clat if grid == 'icosahedral': v1res.cnFillMode = 'CellFill' v1res.sfXCellBounds = vlon v1res.sfYCellBounds = vlat else: v1res.cnFillMode = 'RasterFill' v1res.sfMissingValueV = 9999 v1res.cnLinesOn = False # Turn off contour lines. v1res.cnFillOn = True #v1res.cnFillOpacityF = 0.5 #v1res.cnFillDrawOrder = 'Predraw' v1res.cnLineLabelsOn = False v1res.cnLevelSelectionMode = 'ExplicitLevels' v1res.cnLevels = levels1 # set resources for a nice label bar # v1res.lbLabelBarOn = True v1res.lbAutoManage = False v1res.lbOrientation = 'vertical' v1res.lbLabelOffsetF = 0.04 # minor axis fraction: the distance between colorbar and numbers v1res.lbBoxMinorExtentF = 0.20 # minor axis fraction: width of the color boxes when labelbar down v1res.lbTopMarginF = 0.05 # make a little more space at top for the unit label v1res.lbRightMarginF = 0.0 v1res.lbBottomMarginF = 0.0 v1res.lbLeftMarginF = -0.35 v1res.cnLabelBarEndStyle = 'ExcludeOuterBoxes' #v1res.cnLabelBarEndStyle = 'IncludeOuterBoxes' #v1res.cnExplicitLabelBarLabelsOn = True #v1res.pmLabelBarDisplayMode = 'Always' v1res.pmLabelBarWidthF = 0.10 #v1res.lbLabelStrings = label_str_list v1res.lbLabelFontHeightF = 0.010 #v1res.lbBoxCount = 40 v1res.lbBoxSeparatorLinesOn = False v1res.lbBoxLineThicknessF = 4 #v1res.lbBoxEndCapStyle = 'TriangleBothEnds' v1res.lbLabelAlignment = 'InteriorEdges' v1res.lbLabelStride = 1 v1res.nglFrame = False v1res.nglDraw = False v1plot = Ngl.contour(wks, data_array1_cut, v1res) # plot label bar unit # text_str = 'Index' text_res_1 = Ngl.Resources() text_res_1.txFontColor = 'black' text_x = 0.975 text_y = 0.72 text_res_1.txFontHeightF = 0.012 Ngl.overlay(basic_map, v1plot) Ngl.draw(basic_map) Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) #Ngl.end() # cut top and bottom whitespace of plot # im = Image.open(path['base'] + path['plots'] + plot_name + '.png') image_array = np.asarray(im.convert('L')) image_array = np.where(image_array < 255, 1, 0) image_filter = np.amax(image_array, axis=1) vmargins = [ np.nonzero(image_filter)[0][0], np.nonzero(image_filter[::-1])[0][0] ] #print(vmargins) #print(im.size) im_cropped = Image.new( 'RGB', (im.size[0], im.size[1] - vmargins[0] - vmargins[1]), (255, 255, 255)) im_cropped.paste( im.crop((0, vmargins[0], im.size[0], im.size[1] - vmargins[1])), (0, 0)) #print(im_cropped.size) im.close() im_cropped.save(path['base'] + path['plots'] + plot_name + '.png', 'png') im_cropped.close() del data_array1, data_array1_cut, clat, clon if grid == 'icosahedral': del vlat, vlon return
def large_scale_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "CLOUD", "OMEGA", "Q", "CLDLIQ", "THETA", "RELHUM", "U", "CLDICE", "T" ] varisobs = [ "CC_ISBL", "OMEGA", "SHUM", "CLWC_ISBL", "THETA", "RELHUM", "U", "CIWC_ISBL", "T" ] nvaris = len(varis) cunits = [ "%", "mba/day", "g/kg", "g/kg", "K", "%", "m/s", "g/kg", "m/s", "m/s", "K", "m" ] cscale = [100, 864, 1000, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] cscaleobs = [100, 1, 1, 1000, 1., 1, 1, 1000, 1, 1, 1, 1, 1, 1, 1] obsdataset = [ "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI" ] plotlgs = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotlgs[ire] = 'Largescale_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.tiYAxisString = "Pressure [hPa]" res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'Lines' # res.tmXBLabelAngleF = 45 res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) pres = Ngl.Resources() pres.nglFrame = False pres.txString = "Large-scale VAR at" + str(lons[ire]) + "E," + str( lats[ire]) + "N" pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.88 pres.wkPaperWidthF = 17 # in inches pres.wkPaperHeightF = 28 # in inches pres.nglMaximize = True pres.wkWidth = 10000 pres.wkHeight = 10000 for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = "NEVER" if (obsdataset[iv] == "CCCM"): if (cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc" inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][:, latobs_idx, lonobs_idx] else: if (varisobs[iv] == "PRECT"): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' inptrobs = Dataset(fileobs, 'r') if (varisobs[iv] == "THETA"): latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables['T'][0, :, latobs_idx, lonobs_idx] pre1 = inptrobs.variables['lev'][:] for il1 in range(0, len(pre1)): B[il1] = B[il1] * (1000 / pre1[il1])**0.286 else: pre1 = inptrobs.variables['lev'][:] latobs = inptrobs.variables['lat'][:] latobs_idx = np.abs(latobs - lats[ire]).argmin() lonobs = inptrobs.variables['lon'][:] lonobs_idx = np.abs(lonobs - lons[ire]).argmin() B = inptrobs.variables[varisobs[iv]][0, :, latobs_idx, lonobs_idx] B[:] = B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['lev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() theunits = "[units]" if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (varis[iv] == 'THETA'): if (dofv): tmp = inptrs.variables['T'][0, :, npointlat, npointlon] else: tmp = inptrs.variables['T'][0, :, npoint] hyam = inptrs.variables['hyam'][:] hybm = inptrs.variables['hybm'][:] if (dofv): ps = inptrs.variables['PS'][0, npointlat, npointlon] else: ps = inptrs.variables['PS'][0, npoint] ps = ps p0 = 100000.0 #CAM uses a hard-coded p0 pre = np.zeros((nlev), np.float32) for il in range(0, nlev): pre[il] = hyam[il] * p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000 / pre[il])**0.286 theunits = str( cscale[iv]) + "x" + inptrs.variables['T'].units else: if (dofv): tmp = inptrs.variables[varis[iv]][0, :, npointlat, npointlon] else: tmp = inptrs.variables[varis[iv]][0, :, npoint] theunits = str(cscale[iv]) + "x" + inptrs.variables[ varis[iv]].units ##import pdb; pdb.set_trace() A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiMainString = varis[iv] + " " + theunits res.trXMinF = min(np.min(A_field[0, :]), np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]), np.max(B)) if (varis[iv] == "THETA"): res.trXMinF = 270. res.trXMaxF = 400. if (varis[iv] == "CLOUD" or varis[iv] == "RELHUM"): res.trXMinF = 0. res.trXMaxF = 100. if (varis[iv] == "T"): res.trXMinF = 180 res.trXMaxF = 300 if (varis[iv] == "U"): res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) res.trYReverse = False res.xyLineColors = ["black"] pt = Ngl.xy(wks, B, pre1, res) Ngl.overlay(p, pt) plot.append(p) Ngl.panel(wks, plot[:], [nvaris / 3, 3], pres) txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "Large-scale VAR at" + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.92 + ncases * 0.01, txres) Common_functions.create_legend(wks, casenames, 0.02, np.arange(3, 20, 2), 0.1, 0.89 + ncases * 0.01) Ngl.frame(wks) Ngl.destroy(wks) return plotlgs
def draw_2D_plot(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) if not os.path.exists(casedir + '/2D'): os.mkdir(casedir + '/2D') _Font = 25 interp = 2 extrap = False infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] alpha = ['A', 'B', 'C', 'D', 'E', 'F'] cunits = [''] varis = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'TMQ', 'PS', 'TS', 'U10', 'CLDTOT', 'CLDLOW', 'CLDHGH', 'TGCLDLWP' ] varisobs = [ 'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'PREH2O', 'PS', 'TS', 'U10', 'CLDTOT_CAL', 'CLDTOT_CAL', 'CLDTOT_CAL', 'TGCLDLWP_OCEAN' ] nvaris = len(varis) cscale = [1, 1, 86400000, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1000, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # cntrs = [[0 for col in range(11)] for row in range(nvaris)] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = [ 'CERES-EBAF', 'CERES-EBAF', 'GPCP', 'ERAI', 'NCEP', 'ERAI', 'NCEP', 'ERAI', 'ERAI', 'CALIPSOCOSP', 'CALIPSOCOSP', 'CALIPSOCOSP', 'NVAP' ] plot2d = ['' for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field if (varis[iv] == 'CLDTOT' or varis[iv] == 'CLDLOW' or varis[iv] == 'CLDHGH'): cntrs[iv, :] = [2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90] if (varis[iv] == 'LWCF'): cntrs[iv, :] = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45] if (varis[iv] == 'SWCF' or varis[iv] == 'FLUT'): cntrs[iv, :] = [ -40, -50, -60, -70, -80, -90, -100, -110, -120, -130, -140 ] if (varis[iv] == 'PRECT' or varis[iv] == 'QFLX'): cntrs[iv, :] = [0.5, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15] if (varis[iv] == 'LHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'SHFLX'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] if (varis[iv] == 'U10'): cntrs[iv, :] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] if (varis[iv] == 'TMQ'): cntrs[iv, :] = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] if (varis[iv] == 'TGCLDLWP'): cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] # Observational data if (obsdataset[iv] == 'CCCM'): if (cseason == 'ANN'): fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-' + cseason + '.nc' else: fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-' + cseason + '.nc' else: if (varisobs[iv] == 'PRECT'): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' # infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] if (varisobs[iv] == 'U10'): B0 = inptrobs.variables[varisobs[iv]][0, :, :] B1 = inptrobs.variables['V10'][0, :, :] B = (B0 * B0 + B1 * B1) B = B * cscaleobs[iv] B = np.sqrt(B) else: B = inptrobs.variables[varisobs[iv]][0, :, :] B = B * cscaleobs[iv] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[iv] + '_' + cseason plot2d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, 'cmocean_thermal') # Ngl.define_colormap(wks,'MPL_coolwarm') # ngl_define_colormap(wks,'prcp_1') plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres) pres = Ngl.Resources() pres.nglMaximize = True pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.20 pres.nglPanelTop = 0.9 pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = 'helvetica-bold' # Labelbar font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = 'BottomRight' res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = 'RasterFill' res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = '' res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = '' res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font res.vpWidthF = 0.80 # set width and height res.vpHeightF = 0.40 res.vpXF = 0.04 res.vpYF = 0.30 res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False # res.vcRefMagnitudeF = 5. # res.vcMinMagnitudeF = 1. # res.vcRefLengthF = 0.04 # res.vcRefAnnoOn = True#False # res.vcRefAnnoZone = 3 # res.vcRefAnnoFontHeightF = 0.02 # res.vcRefAnnoString2 ='' # res.vcRefAnnoOrthogonalPosF = -1.0 # res.vcRefAnnoArrowLineColor = 'blue' # change ref vector color # res.vcRefAnnoArrowUseVecColor = False # res.vcMinDistanceF = .05 # res.vcMinFracLengthF = . # res.vcRefAnnoParallelPosF = 0.997 # res.vcFillArrowsOn = True # res.vcLineArrowThicknessF = 3.0 # res.vcLineArrowHeadMinSizeF = 0.01 # res.vcLineArrowHeadMaxSizeF = 0.03 # res.vcGlyphStyle = 'CurlyVector' # turn on curley vectors # res@vcGlyphStyle ='Fillarrow' # res.vcMonoFillArrowFillColor = True # res.vcMonoLineArrowColor = True # res.vcLineArrowColor = 'green' # change vector color # res.vcFillArrowEdgeColor ='white' # res.vcPositionMode ='ArrowTail' # res.vcFillArrowHeadInteriorXF =0.1 # res.vcFillArrowWidthF =0.05 #default # res.vcFillArrowMinFracWidthF =.5 # res.vcFillArrowHeadMinFracXF =.5 # res.vcFillArrowHeadMinFracYF =.5 # res.vcFillArrowEdgeThicknessF = 2.0 res.mpFillOn = False res.cnLevelSelectionMode = 'ExplicitLevels' res.cnLevels = cntrs[iv][:] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) area = inptrs.variables['area'][:] area_wgt = np.zeros(nlat) sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] if (varis[iv] == 'PRECT'): A = inptrs.variables['PRECC'][ 0, :] + inptrs.variables['PRECL'][0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'FLUT'): A = inptrs.variables['FLUT'][0, :] - inptrs.variables['FLNS'][ 0, :] else: A = inptrs.variables[varis[iv]][0, :] if (varis[iv] == 'U10'): A = inptrs.variables['U10'][0, :] * inptrs.variables['U10'][ 0, :] A = np.sqrt(A) else: A = inptrs.variables[varis[iv]][0, :] A_xy = A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0: dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if (np.mod(im, 2) == 0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) res.tiMainString = 'GLB=' + str( np.sum(A_xy[:] * area[:] / np.sum(area))) textres.txFontHeightF = 0.015 Ngl.text_ndc(wks, alpha[im] + ' ' + casenames[im], 0.3, .135 - im * 0.03, textres) p = Ngl.contour_map(wks, A_xy, res) plot.append(p) # observation # res.nglLeftString = obsdataset[iv] # res@lbLabelBarOn = True # res@lbOrientation = 'vertical' # vertical label bars res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0 * np.arctan(1.0) / 180.0 re = 6371220.0 rr = re * rad dlon = abs(lonobs[2] - lonobs[1]) * rr dx = dlon * np.cos(latobs * rad) jlat = len(latobs) dy = np.zeros(jlat, dtype=float) # close enough dy[0] = abs(lat[2] - lat[1]) * rr dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5 dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr area_wgt = dx * dy # is_SE = False sum1 = 0 sum2 = 0 for j in range(0, jlat - 1): for i in range(0, len(lonobs) - 1): if (np.isnan(B[j][i]) != '--'): sum1 = sum1 + area_wgt[j] * B[j][i] sum2 = sum2 + area_wgt[j] glb = sum1 / sum2 res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = 'LatLon' res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = 'GLB=' + str(glb) p = Ngl.contour_map(wks, B, res) if (iv == 0): poly_res = Ngl.Resources() poly_res.gsMarkerIndex = 16 poly_res.gsMarkerSizeF = 0.005 poly_res.gsMarkerColor = 'green' dum = Ngl.add_polymarker(wks, p, lons, lats, poly_res) plot.append(p) if (np.mod(ncases + 1, 2) == 1): Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) # Ngl.end() return plot2d
def draw_clm_plot (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) if not os.path.exists(casedir+"/2D"): os.mkdir(casedir+"/2D") _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] varis = ["SOILWATER_10CM", "QBOT"] varisobs = ["PRECT" ,"PRECT"] alpha = ["A","B","C","D","E","F"] nvaris = len(varis) cunits = [""] cscale = [1,1,1,86400000, 1, 1,1,100,100,1,1,1000,1,1,1,1] cscaleobs = [1,1,1,1,1,1,1,1,1,1,1,1,1,1] # cntrs = [[0 for col in range(11)] for row in range(nvaris)] cntrs = np.zeros((nvaris,11),np.float32) obsdataset= ["GPCP","GPCP", "NCEP", "ERAI", "CALIPSOCOSP","CALIPSOCOSP","NCEP","NCEP","NVAP"] plotclm=["" for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field if(varis[iv] == "SOILWATER_10CM" or varis[iv] == "QBOT" ): cntrs[iv,:] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Observational data if(obsdataset[iv] =="CCCM"): if(cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc" else: if (varisobs[iv] =="PRECT"): fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' else: fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' # infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc' inptrobs = Dataset(fileobs,'r') latobs=inptrobs.variables['lat'][:] lonobs=inptrobs.variables['lon'][:] if (varisobs[iv] =="U10"): B0=inptrobs.variables[varisobs[iv]][0,:,:] B1=inptrobs.variables["V10"][0,:,:] B=(B0*B0+B1*B1) B=B * cscaleobs[iv] B=np.sqrt(B) else: B=inptrobs.variables[varisobs[iv]][0,:,:] B=B * cscaleobs[iv] #************************************************ # create plot #************************************************ plotname = casedir+'/2D/Land_'+varis[iv]+'_'+cseason plotclm[iv] = 'Land_'+varis[iv]+'_'+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,"cmocean_thermal") # ngl_define_colormap(wks,"prcp_1") plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks,varis[iv],0.1,.97,textres) pres = Ngl.Resources() pres.nglMaximize = True pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.20 pres.nglPanelTop = 0.9 pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = "helvetica-bold" # Labelbar font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = "BottomRight" res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = "RasterFill" res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = "" res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = "" res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font res.vpWidthF = 0.80 # set width and height res.vpHeightF = 0.40 res.vpXF = 0.04 res.vpYF = 0.30 res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False res.mpFillOn = False res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = cntrs[iv][:] for im in range(0, ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_clm.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) area=inptrs.variables['area'][:] area_wgt = np.zeros(nlat) sits=np.linspace(0,nsite-1,nsite) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:] if (varis[iv] == 'PRECT'): A = inptrs.variables['PRECC'][0,:]+inptrs.variables['PRECL'][0,:] else: A = inptrs.variables[varis[iv]][0,:] if (varis[iv] == 'FLUT'): A = inptrs.variables['FLUT'][0,:]-inptrs.variables['FLNS'][0,:] else: A = inptrs.variables[varis[iv]][0,:] if (varis[iv] == 'U10'): A = inptrs.variables['U10'][0,:]*inptrs.variables['U10'][0,:] A = np.sqrt(A) else: A = inptrs.variables[varis[iv]][0,:] A_xy=A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0 : dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if(np.mod(im,2)==0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) res.tiMainString = "GLB="+str(np.sum(A_xy[:]*area[:]/np.sum(area))) textres.txFontHeightF = 0.015 Ngl.text_ndc(wks,alpha[im]+" "+ casenames[im],0.3,.135-im*0.03,textres) # varM = A_xy # for ix in range(0, nlon-1): # if ( np.isnan(A_xy[ix]) or not np.isfinite(A_xy[ix])): # varM[ix]=0.0 p = Ngl.contour_map(wks,A_xy,res) plot.append(p) res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0*np.arctan(1.0)/180.0 re = 6371220.0 rr = re*rad dlon = abs(lonobs[2]-lonobs[1])*rr dx = dlon* np.cos(latobs*rad) jlat = len(latobs ) dy = np.zeros(jlat,dtype=float) # close enough dy[0] = abs(lat[2]-lat[1])*rr dy[1:jlat-2] = abs(lat[2:jlat-1]-lat[0:jlat-3])*rr*0.5 dy[jlat-1] = abs(lat[jlat-1]-lat[jlat-2])*rr area_wgt = dx*dy # is_SE= False sum1 = 0 sum2 = 0 for j in range(0, jlat-1): for i in range(0, len(lonobs)-1): if (np.isnan(B[j][i]) != "--"): sum1= sum1+area_wgt[j]*B[j][i] sum2= sum2+area_wgt[j] glb=sum1/sum2 res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = "GLB="+str(glb) p =Ngl.contour_map(wks,B,res) plot.append(p) if(np.mod(ncases+1,2)==1): Ngl.panel(wks,plot[:],[(ncases+1)/2+1,2],pres) else: Ngl.panel(wks,plot[:],[(ncases+1)/2,2],pres) Ngl.frame(wks) Ngl.destroy(wks) # Ngl.end() return plotclm
res2.trXMinF = faxis[0] # Limits for X axis res2.trXMaxF = faxis[-1] res2.tiXAxisString = "~F25~Frequency (Hz)" res2.tiYAxisString = "~F25~Power Spectrum" leftname = "Period from ~F34~%~F25~ to {} seconds".format(1./faxis[-1]) res2.tiMainString = "Spectral Analysis (FFT)"+ \ "~C~~B~"+leftname plot = [] plot.append(Ngl.xy(wks,t,sig,res)) plot.append(Ngl.xy(wks,faxis,PS,res2)) #wrf_tools.ngl_Strings(wks, plot[0], left=leftname, center="", right="") panelres = Ngl.Resources() Ngl.panel(wks,plot[0:1+1],[2,1],panelres) #Ngl.draw(plot[0]) #Ngl.frame(wks) Ngl.destroy(wks); del res, plot Ngl.end() end_time = cpu_time(); end_time = (end_time - start_time)/60.0 print(os.path.basename(__file__)+" has done!\nTime elapsed: {:.2f}".format(end_time), "mins.")
def draw_clubb_tau(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plottau = ["" for x in range(nsite * ncases)] alphas = [ 'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) ' ] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason plottau[im + ncases * ire] = pname + '_' + casenames[im] + "_" + str( lons[ire]) + "E_" + str(lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "radar") plot = [] res = Ngl.Resources() res.nglMaximize = False res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # if (lats[ire] > 0 and lons[ire]!=240 ): # res.trYMinF = 400. # res.trYMaxF = 1000. # else: res.trYMinF = 100. res.trYMaxF = 1000. res.tiMainFont = _Font res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 2., 2., 2., 2, 2, 2, 2, 2, 2, 2 ] res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.pmLegendDisplayMode = "Never" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.75 # move units right res.pmLegendOrthogonalPosF = -0.65 # more neg = down res.pmLegendWidthF = 0.1 # Change width and res.pmLegendHeightF = 0.15 # height of legend. res.lgLabelFontHeightF = .02 # change font height res.lgLabelFontThicknessF = 1. # res.lgBoxMinorExtentF = 0.2 res.lgPerimOn = True res.tiYAxisString = "Pressure [hPa]" res.trYReverse = True pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 pres.txFont = _Font pres.nglMaximize = False pres.txFont = _Font pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topright' pres.nglPanelFigureStringsFontHeightF = 0.015 for iv in range(0, nvaris): if (varis[iv] == 'tau_no_N2_zm'): budget_ends = ['tau_no_N2_zm', 'bkgnd', 'sfc', 'shear'] budget_name = [ '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bkgnd~N~', '1/~F8~t~N~~F10~~B~surf~N~', '1/~F8~t~N~~F10~~B~shear~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_xp2_zm'): budget_ends = ['tau_xp2_zm', 'tau_no_N2_zm'] budget_name = [ "1/~F8~t~N~~F10~~B~x'~S~2~N~~N~", '1/~F8~t~N~~F10~~B~noN2~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp2_zm'): budget_ends = ['tau_wp2_zm', 'tau_no_N2_zm', 'bvpos'] budget_name = [ "1/~F8~t~N~~F10~~B~w'~S~2~N~~N~", '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wpxp_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ "1/~F8~t~N~~F10~~B~w'x'~N~", "1/~F8~t~N~~F10~~B~noN2~N~", '1/~F8~t~N~~F10~~B~bv~N~', '1/~F8~t~N~~F10~~B~clr~N~' ] nterms = len(budget_ends) if (varis[iv] == 'tau_wp3_zm'): budget_ends = [ 'tau_wpxp_zm', 'tau_no_N2_zm', 'bvpos', 'clear' ] budget_name = [ "1/~F8~t~N~~F10~~B~w'x'~N~", '1/~F8~t~N~~F10~~B~noN2~N~', '1/~F8~t~N~~F10~~B~bv~N~', '1/~F8~t~N~~F10~~B~clr~N~' ] nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['ilev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) if (varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wp2_zm' or varis[iv] == 'tau_xp2_zm' or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_wpxp_zm'): theunits = str(chscale[iv]) + '~F10~' + inptrs.variables[ varis[iv]].units + '~S~-1~N~' else: theunits = str( chscale[iv]) + '~F10~' + inptrs.variables[varis[iv] + '_bt'].units res.tiXAxisString = '1/~F8~t~N~~F25~~B~' + vname[ iv] + "~N~ " + ' Unit= ' + theunits res1 = Ngl.Resources() res1 = res for it in range(0, nterms): for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (varis[iv] == 'tau_wp2_zm' or varis[iv] == 'tau_xp2_zm' or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_wpxp_zm' or varis[iv] == 'tau_no_N2_zm'): varis_tau = budget_ends[it] if ( varis_tau == 'bkgnd' or varis_tau == 'shear' \ or varis_tau == 'sfc' ): tmp = inptrs.variables['invrs_tau_' + varis_tau][0, :, npoint] if (varis_tau == 'tau_no_N2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis[iv] == 'tau_wp2_zm'): if (varis_tau == 'tau_wp2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis[iv] == 'tau_zm'): if (varis_tau == 'tau_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_zm'][0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis[iv] == 'tau_xp2_zm'): if (varis_tau == 'tau_xp2_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'Rich'): tmp0 = inptrs.variables['tau_xp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 / (1 / tmp1) / 1000 if (varis[iv] == 'tau_wp3_zm'): if (varis_tau == 'tau_wp3_zm' or varis_tau == 'tau_wpxp_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp tmp[0:10] = 0 if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 if (varis_tau == 'clear'): tmp0 = inptrs.variables['tau_wp3_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_wp2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 - 1 / tmp1 tmp[0:10] = 0 if (varis[iv] == 'tau_wpxp_zm'): if (varis_tau == 'tau_wpxp_zm' or varis_tau == 'tau_zm'): tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = 1 / tmp if (varis_tau == 'bvpos'): tmp0 = inptrs.variables['tau_zm'][0, :, npoint] tmp1 = inptrs.variables['tau_no_N2_zm'][ 0, :, npoint] tmp = tmp0 tmp = 2 / tmp0 - 1 / tmp1 if (varis_tau == 'clear'): tmp0 = inptrs.variables['tau_wpxp_zm'][ 0, :, npoint] tmp1 = inptrs.variables['tau_zm'][0, :, npoint] tmp = tmp0 tmp = 1 / tmp0 / 5 - 2 / tmp1 else: varis_tau = varis[iv] + budget_ends[it] tmp0 = inptrs.variables[varis[iv]][0, :, npoint] tmp = inptrs.variables[varis_tau][0, :, npoint] tmp = tmp * cscale[iv] A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.pmLegendDisplayMode = "Never" if (varis[iv] == 'tau_wp3_zm'): res.trXMinF = 0 res.trXMaxF = 450 res.xyMarkerColors = [ 'black', 'orange', 'purple', 'firebrick' ] res.xyLineColors = [ 'black', 'orange', 'purple', 'firebrick' ] if (varis[iv] == 'tau_no_N2_zm'): res.trXMinF = 0 res.trXMaxF = 20 res.xyMarkerColors = ['black', 'red', 'green', 'blue'] res.xyLineColors = ['black', 'red', 'green', 'blue'] if (varis[iv] == 'tau_wp2_zm'): res.trXMinF = 0 res.trXMaxF = 12 res.xyMarkerColors = ['black', 'orange', 'purple'] res.xyLineColors = ['black', 'orange', 'purple'] if (varis[iv] == 'tau_xp2_zm'): res.trXMinF = 0 res.trXMaxF = 35 res.xyMarkerColors = ['black', 'orange'] res.xyLineColors = ['black', 'orange'] p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) xp = np.mod(iv, 2) yp = int(iv / 2) if (varis[iv] == 'tau_wp3_zm'): res.trXMinF = 0 res.trXMaxF = 450 res.xyMarkerColors = [ 'black', 'orange', 'purple', 'firebrick' ] res.xyLineColors = [ 'black', 'orange', 'purple', 'firebrick' ] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'orange', 'purple', 'firebrick'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_no_N2_zm'): res.trXMinF = 0 res.trXMaxF = 20 res.xyMarkerColors = ['black', 'red', 'green', 'blue'] res.xyLineColors = ['black', 'red', 'green', 'blue'] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'red', 'green', 'blue'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_wp2_zm'): res.trXMinF = 0 res.trXMaxF = 12 res.xyMarkerColors = ['black', 'orange', 'purple'] res.xyLineColors = ['black', 'orange', 'purple'] Common_functions.create_legend( wks, budget_name[:], 0.02, ['black', 'orange', 'purple'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) if (varis[iv] == 'tau_xp2_zm'): res.trXMinF = 0 res.trXMaxF = 35 res.xyMarkerColors = ['black', 'orange'] res.xyLineColors = ['black', 'orange'] Common_functions.create_legend(wks, budget_name[:], 0.02, ['black', 'orange'], 0.3 + xp * 0.5, 0.8 - yp * 0.5) Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc( wks, casenames[im] + " BUDGET at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.95, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plottau)
def plot_rain_around_point(path, data_rain_tot_sum, hour_start, hour_end, point, stat_processing, member): if stat_processing == 'max': data_processed = (data_rain_tot_sum[hour_end, :, :] - data_rain_tot_sum[hour_start, :, :]).max(axis=0) elif stat_processing == 'member_extract': data_processed = data_rain_tot_sum[hour_end, member-1, :] - data_rain_tot_sum[hour_start, member-1, :] ######################################################################## if stat_processing == 'max': member_text_filename = 'max' elif stat_processing == 'member_extract': member_text_filename = 'm{:02d}'.format(member) plot_name = 'iconeueps_rain_{}_{:02d}Z-{:02d}Z_{}'.format(\ point['name'], hour_start+12, hour_end+12, member_text_filename) mpi_file = nc.Dataset(path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = mpi_file.variables['clat_vertices'][:].data * 180./np.pi vlon = mpi_file.variables['clon_vertices'][:].data * 180./np.pi clat = mpi_file.variables['clat'][:].data * 180./np.pi clon = mpi_file.variables['clon'][:].data * 180./np.pi mpi_file.close() ######################################################################## x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources() resources.mpProjection = 'Hammer' resources.mpCenterLonF = point['lon'] resources.mpCenterLatF = point['lat'] radius = 500 # image radius in km around centered point cutout_plot = dict( lat_min = point['lat'] - radius / 111.2, lat_max = point['lat'] + radius / 111.2, lon_min = point['lon'] - radius / (111.2 * np.cos(point['lat']*np.pi/180)), lon_max = point['lon'] + radius / (111.2 * np.cos(point['lat']*np.pi/180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.95 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ######################################################################## # Turn on filled map areas: resources.mpFillOn = True # Set colors for [FillValue, Ocean, Land , InlandWater]: resources.mpFillColors = ['pink','blue','white','blue'] resources.mpDataBaseVersion = 'MediumRes' resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 resources.tmXBOn = False resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed resources.sfXArray = clon resources.sfYArray = clat resources.sfXCellBounds = vlon resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 resources.cnFillOn = True resources.cnFillMode = 'CellFill' resources.cnCellFillEdgeColor = 'black' resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 maxlevel = 50.0 numberoflevels = 250 resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels # Turn off contour lines and labels: resources.cnLinesOn = False resources.cnLineLabelsOn = False # Set resources for a nice label bar resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 resources.lbLabelFontHeightF = 0.02 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.02 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = 0.0 resources.nglFrame = False plot = Ngl.contour_map(wks, data_processed, resources) ######################################################################## polymarker_res_1 = Ngl.Resources() polymarker_res_1.gsMarkerColor = 'black' polymarker_res_1.gsMarkerIndex = 16 polymarker_res_1.gsMarkerSizeF = 0.012 polymarker_res_1.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_1) ######################################################################## polymarker_res_2 = Ngl.Resources() polymarker_res_2.gsMarkerColor = 'white' polymarker_res_2.gsMarkerIndex = 16 polymarker_res_2.gsMarkerSizeF = 0.008 polymarker_res_2.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_2) ######################################################################## if stat_processing == 'max': member_text = 'max member of each cell' elif stat_processing == 'member_extract': member_text = 'member {:d}'.format(member) text = 'rain_gsp + rain_con, 07.08.19 {}Z-{}Z, {}'.format(hour_start+12, hour_end+12, member_text) x = 0.1 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.02 text_res_1.txJust = 'BottomLeft' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) return
res.cnLevelSelectionMode = "ManualLevels" res.cnMinLevelValF = 1000.0 res.cnMaxLevelValF = 6000.0 res.cnLevelSpacingF = 250.0 res.cnLineThicknessF = 2.5 # create PWAT plot for analysis data MD_plot = ngl.contour_map(wks,MD,res) ngl.maximize_plot(wks, MD_plot) ngl.draw(MD_plot) ngl.frame(wks) ngl.destroy(wks) del res del MD #del CIN ################################################################################################### # open forecast file f_fili = "GFS_forecast_%s_%s.nc" % (init_dt[:8], init_dt[8:10]) forecast = nio.open_file(diri+f_fili) # loop through forecast times for i in range(0, len(fore)):
def delete(self): Ngl.destroy(self.workstation)
def draw_micro_bgt(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname, dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = 'Red' mkres.gsMarkerSizeF = 15. infiles = ['' for x in range(ncases)] ncdfs = ['' for x in range(ncases)] nregions = nsite nvaris = len(varis) plotmicrobgt = ['' for x in range(nsite * ncases)] for ire in range(0, nsite): for im in range(0, ncases): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + casenames[im] + '_' + str( lons[ire]) + 'E_' + str(lats[ire]) + 'N_' + cseason plotmicrobgt[ im + ncases * ire] = pname + '_' + casenames[im] + '_' + str( lons[ire]) + 'E_' + str(lats[ire]) + 'N_' + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, 'radar') plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # res.txFontHeightF = .01 # res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = 12 res.tmXBLabelFont = 12 res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = 'MarkLines' res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyLineColors = np.arange(2, 16, 1) res.xyDashPatterns = np.arange(0, 24, 1) res.xyMarkers = np.arange(16, 40, 1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(2, 16, 1) res.pmLegendDisplayMode = 'ALWAYS' res.pmLegendSide = 'top' # Change location of res.pmLegendParallelPosF = 0.6 # move units right res.pmLegendOrthogonalPosF = -0.55 # more neg = down res.pmLegendWidthF = 0.2 # Decrease width res.pmLegendHeightF = 0.1 # Decrease height res.lgBoxMinorExtentF = 0.1 # Shorten the legend lines res.lgLabelFontHeightF = 0.015 # Change the font size res.lgPerimOn = True res.tiYAxisString = 'PRESSURE' # res.nglLeftString = varis[iv] # res.nglRightString = cunits[iv] res.trYReverse = True pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = 12 pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 txres = Ngl.Resources() # txres.txFontHeightF = 0.01 for iv in range(0, nvaris): if (varis[iv] == 'MPDLIQ'): # LIQ budget_ends = [ 'PRCO', 'PRAO', 'MNUCCCO', 'MNUCCTO', 'MSACWIO', 'PSACWSO', 'BERGSO', 'BERGO' ] # in fortran prc*cld, pra*cld,mnuccc*cld,mnucct*cld,msacwi*cld,psacws*cld,bergs*cld, berg # (-pra-prc-mnuccc-mnucct-msacwi- psacws-bergs)*lcldm-berg nterms = len(budget_ends) if (varis[iv] == 'MPDICE'): # ICE budget_ends = [ 'PRCIO', 'PRAIO', 'MSACWIO', 'MNUCCCO', 'MNUCCTO', 'mnudepo', 'BERGO', 'CMEIOUT', 'mnuccrio' ] # in fortran prci*cld,prai*cld,msacwi*cld,mnuccc*cld, mnucct*cld, berg, vap_dep + ice_sublim + mnuccd # (mnuccc+mnucct+mnudep+msacwi)*lcldm+(-prci-prai)*icldm+(vap_dep+ice_sublim+mnuccd)+berg+mnuccri*precip_frac nterms = len(budget_ends) if (varis[iv] == 'QRSEDTEN'): # RAIN budget_ends = [ 'PRAO', 'PRCO', 'PRACSO', 'EVAPPREC', 'MNUCCRO', 'mnuccrio' ] # pra*cld,prc*cld, psacs*prf, -pre*prf(nevapr),mnuccr*prf # (pra+prc)*lcldm+(pre-pracs- mnuccr-mnuccri)*precip_frac nterms = len(budget_ends) if (varis[iv] == 'QSSEDTEN'): # SNOW budget_ends = [ 'PRAIO', 'PRCIO', 'PSACWSO', 'PRACSO', 'EVAPSNOW', 'MNUCCRO', 'BERGSO' ] # prai*cld,prci*cld,psacws*cld,psacs*prf, -prds*prc, mnuccr*prf,bergs*cld # (prai+prci)*icldm+(psacws+bergs)*lcldm+(prds+ pracs+mnuccr)*precip_frac nterms = len(budget_ends) if (varis[iv] == 'QISEVAP'): # Vapor budget_ends = [ 'EVAPPREC', 'EVAPSNOW', 'CMEIOUT', 'mnudepo' ] # -pre*prf(nevapr),-prds*prc ,vap_dep + ice_sublim + mnuccd # -(pre+prds)*precip_frac-vap_dep-ice_sublim-mnuccd-mnudep*lcldm nterms = len(budget_ends) if (varis[iv] == 'nnuccco'): # NUM of LIQ budget_ends = [ 'nnuccco', 'nnuccto', 'npsacwso', 'nsubco', 'nprao', 'nprc1o' ] # nnuccc*cld,nnucct*cld,npsacws*cld,nsubc*cld,npra*cld,nprc1*cld # (-nnuccc-nnucct-npsacws+nsubc-npra-nprc1)*lcldm nterms = len(budget_ends) if (varis[iv] == 'nnuccdo'): # NUM of ICE budget_ends = [ 'nnuccdo', 'nnuccto', 'tmpfrzo', 'nnudepo', 'nsacwio', 'nsubio', 'nprcio', 'npraio', 'nnuccrio', 'DETNICETND' ] # nnuccd ,nnucct*lcld,tmpfrz*lcld,nnudep*lcld,nsacwi*lcld,nsubi*icld,nprci*icld,nprai*icld,nnuccri*prf # nnuccd+ (nnucct+tmpfrz+nnudep+nsacwi)*lcldm+(nsubi-nprci- nprai)*icldm+nnuccri*precip_frac nterms = len(budget_ends) ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) ilev = inptrs.variables['lev'][:] nilev = len(ilev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] if (dofv): idx_lats = ncdf.variables['idx_coord_lat'][:, :] idx_lons = ncdf.variables['idx_coord_lon'][:, :] ncdf.close() A_field = np.zeros((nterms, nilev), np.float32) theunits = str( chscale[iv]) + 'x' + inptrs.variables[varis[iv]].units res.tiMainString = vname[iv] + ' ' + theunits for it in range(0, nterms): for subc in range(0, n[ire]): varis_bgt = budget_ends[it] npoint = idx_cols[ire, n[subc] - 1] - 1 if (dofv): npointlat = idx_lats[ire, 0] npointlon = idx_lons[ire, 0] if (dofv): tmp = inptrs.variables[varis_bgt][ 0, :, npointlat, npointlon] #/n[ire] else: tmp = inptrs.variables[varis_bgt][0, :, npoint] #/n[ire] tmp = tmp * cscale[iv] if (dofv): lcldm = inptrs.variables['CLOUD'][0, :, npointlat, npointlon] else: lcldm = inptrs.variables['CLOUD'][0, :, npoint] icldm = lcldm if (dofv): precip_frac = inptrs.variables['FREQR'][0, :, npointlat, npointlon] else: precip_frac = inptrs.variables['FREQR'][0, :, npoint] if (varis_bgt == 'MPDT' or varis_bgt == 'STEND_CLUBB'): tmp = tmp / 1004 if (varis[iv] == 'MPDLIQ'): # LIQ if (varis_bgt == 'PRCO' or varis_bgt == 'PRCIO' or varis_bgt == 'PRAO' or varis_bgt == 'PRAICSO' or varis_bgt == 'PRAIO' \ or varis_bgt == 'MNUCCCO' or varis_bgt == 'MNUCCTO' or varis_bgt == 'MSACWIO' or varis_bgt == 'PSACWSO' or varis_bgt == 'BERGSO' or varis_bgt == 'BERGO'): tmp = tmp * (-1) if (varis[iv] == 'MPDICE'): # ICE if (varis_bgt == 'PRCIO' or varis_bgt == 'PRAIO'): tmp = tmp * (-1) if (varis[iv] == 'QRSEDTEN'): # RAIN if (varis_bgt == 'MNUCCRO' or varis_bgt == 'PRACSO' or varis_bgt == 'EVAPPREC' or varis_bgt == 'mnuccrio'): tmp = tmp * (-1) if (varis[iv] == 'QSSEDTEN'): # SNOW if (varis_bgt == 'EVAPSNOW'): tmp = tmp * (-1) if (varis[iv] == 'QISEVAP'): # Vapor if (varis_bgt == 'CMEIOUT' or varis_bgt == 'mnudepo'): tmp = -1 * tmp if (varis[iv] == 'nnuccco'): # NUM of LIQ if (varis_bgt == 'nnuccco' or varis_bgt == 'nnuccto' or varis_bgt == 'npsacwso' or varis_bgt == 'nprao' or varis_bgt == 'nprc1o'): tmp = -1 * tmp if (varis[iv] == 'nnuccdo'): # NUM of ICE if (varis_bgt == 'nprcio' or varis_bgt == 'npraio'): tmp = -1 * tmp A_field[it, :] = (A_field[it, :] + tmp[:] / n[ire]).astype(np.float32) inptrs.close() res.xyExplicitLegendLabels = budget_ends[:] p = Ngl.xy(wks, A_field, ilev, res) plot.append(p) xp = np.mod(iv, 2) yp = int(iv / 2) pres.txFontHeightF = 0.02 pres.txFont = _Font pres.txString = casenames[im] + ' Microphy BUDGET at' + str( lons[ire]) + 'E,' + str(lats[ire]) + 'N' if (np.mod(nvaris, 2) == 1): Ngl.panel(wks, plot[:], [(nvaris) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(nvaris) / 2, 2], pres) txres = Ngl.Resources() txres.txFontHeightF = 0.020 txres.txFont = _Font Ngl.text_ndc( wks, casenames[im] + ' Microphy BUDGET at' + str(lons[ire]) + 'E,' + str(lats[ire]) + 'N', 0.5, 0.95, txres) Ngl.frame(wks) Ngl.destroy(wks) return (plotmicrobgt)
def plot_prob_of_exceedance_around_point(path, run, data_tmax_24h, domain, threshold): data_processed = np.where(data_tmax_24h >= threshold, 1, 0).sum(axis=0) / 40 * 100 data_processed += 0.1 ######################################################################## mpi_file = nc.Dataset( path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = mpi_file.variables['clat_vertices'][:].data * 180. / np.pi vlon = mpi_file.variables['clon_vertices'][:].data * 180. / np.pi clat = mpi_file.variables['clat'][:].data * 180. / np.pi clon = mpi_file.variables['clon'][:].data * 180. / np.pi mpi_file.close() ######################################################################## color = 'heat' plot_name = 'iconeueps_tmax_24h_prob_over_{:.0f}C_run_{:02d}.{:02d}._{}_{}'.format(\ threshold, run['day'], run['month'], domain['name'], color) subfolder = 'prob_of_exceedance/{}'.format(domain['name']) if not os.path.isdir(path['base'] + path['plots'] + subfolder): os.mkdir(path['base'] + path['plots'] + subfolder) path['plots_subfolder'] = subfolder + '/' ######################################################################## colorpalette_source = 'hclwizard' if colorpalette_source == 'tristenca': filename = 'colorscale_tristenca_tot_prec_monohue_blues.txt' with open(path['base'] + path['colorpalette'] + filename, 'r') as f: line = f.read() hex_colors = [] for i in range(40): start = i * 8 + 1 end = start + 6 hex_colors.append(line[start:end]) custom_palette_list = [[255, 255, 255]] for hex_color in hex_colors[:]: rgb_color = [ int(hex_str, 16) for hex_str in [hex_color[:2], hex_color[2:4], hex_color[4:]] ] custom_palette_list.append(rgb_color) custom_palette = np.array(custom_palette_list) / 255 elif colorpalette_source == 'hclwizard': filename = 'colorscale_hclwizard_t2m_prob_{}.txt'.format(color) with open(path['base'] + path['colorpalette'] + filename, 'r') as f: lines = f.readlines() hex_colors = [] for line in lines: hex_colors.append(line[2:8]) custom_palette_list = [[0, 255, 0]] # extra color for correct LabelBar view custom_palette_list.append([255, 255, 255]) # color for 1% category for hex_color in hex_colors[:]: rgb_color = [ int(hex_str, 16) for hex_str in [hex_color[:2], hex_color[2:4], hex_color[4:]] ] custom_palette_list.append(rgb_color) custom_palette_list.append([255, 0, 0 ]) # extra color for correct LabelBar view custom_palette = np.array(custom_palette_list) '''custom_palette = np.array([[255, 255, 255],\ [255, 255, 0],\ [250, 0, 0],\ [ 0, 250, 0],\ [ 0, 0, 250],\ [100, 0, 0],\ [ 0, 100, 0],\ [ 0, 0, 100],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [100, 100, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [ 0, 0, 0],\ [250, 100, 100],\ [100, 250, 100],\ [100, 100, 250]])''' custom_palette = custom_palette / 255 #print(custom_palette.shape) ######################################################################## x_resolution = 1200 y_resolution = 1200 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution wks_res.wkColorMap = custom_palette wks_type = 'png' wks = Ngl.open_wks( wks_type, path['base'] + path['plots'] + path['plots_subfolder'] + plot_name, wks_res) resources = Ngl.Resources() if domain['method'] == 'centerpoint': resources.mpProjection = 'Hammer' resources.mpCenterLonF = domain['lon'] resources.mpCenterLatF = domain['lat'] cutout_plot = dict( lat_min=domain['lat'] - domain['radius'] / 111.2, lat_max=domain['lat'] + domain['radius'] / 111.2, lon_min=domain['lon'] - domain['radius'] / (111.2 * np.cos(domain['lat'] * np.pi / 180)), lon_max=domain['lon'] + domain['radius'] / (111.2 * np.cos(domain['lat'] * np.pi / 180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] elif domain['method'] == 'deltalatlon': resources.mpProjection = 'Hammer' resources.mpCenterLonF = domain['lon'] resources.mpCenterLatF = domain['lat'] cutout_plot = dict( lat_min=domain['lat'] - domain['deltalat'] / 111.2, lat_max=domain['lat'] + domain['deltalat'] / 111.2, lon_min=domain['lon'] - domain['deltalon'] / (111.2 * np.cos(domain['lat'] * np.pi / 180)), lon_max=domain['lon'] + domain['deltalon'] / (111.2 * np.cos(domain['lat'] * np.pi / 180)), ) resources.mpLimitMode = 'latlon' resources.mpMinLonF = cutout_plot['lon_min'] resources.mpMaxLonF = cutout_plot['lon_max'] resources.mpMinLatF = cutout_plot['lat_min'] resources.mpMaxLatF = cutout_plot['lat_max'] else: print('domain method "{}" not implemented!'.format(domain['method'])) exit() resources.nglMaximize = False resources.vpXF = 0.02 resources.vpYF = 0.92 resources.vpWidthF = 0.82 resources.vpHeightF = 0.70 ######################################################################## # Turn on filled map areas: resources.mpFillOn = True # Set colors for [FillValue, Ocean, Land , InlandWater]: resources.mpFillColors = ['pink', 'blue', 'white', 'blue'] resources.mpDataBaseVersion = 'MediumRes' resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' resources.mpGeophysicalLineThicknessF = 3.0 * x_resolution / 1000 resources.mpNationalLineThicknessF = 3.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 resources.tmXBOn = False resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed resources.sfXArray = clon resources.sfYArray = clat resources.sfXCellBounds = vlon resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 resources.cnFillOn = True resources.cnFillMode = 'CellFill' #resources.cnCellFillEdgeColor = 'black' resources.cnMissingValFillColor = 'black' resources.cnFillPalette = custom_palette resources.cnLevelSelectionMode = 'ExplicitLevels' resources.cnLevels = np.arange(0, 103, 2.5) minlevel = 0.0 maxlevel = 100.0 numberoflevels = 40 resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels # Turn off contour lines and labels: resources.cnLinesOn = False resources.cnLineLabelsOn = False # Set resources for a nice label bar resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 #label_str_list = ['{:d}'.format(int(x)) for x in list(range(0, 101, 10))] resources.cnLabelBarEndStyle = 'ExcludeOuterBoxes' #resources.cnExplicitLabelBarLabelsOn = True #resources.pmLabelBarDisplayMode = 'Always' resources.pmLabelBarWidthF = 0.10 #resources.lbLabelStrings = label_str_list resources.lbLabelStride = 4 resources.lbLabelFontHeightF = 0.018 #resources.lbBoxCount = 40 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = '%' resources.lbTitleFontHeightF = 0.018 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' #resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = 0.0 resources.nglFrame = False plot = Ngl.contour_map(wks, data_processed, resources) ######################################################################## '''polymarker_res_1 = Ngl.Resources() polymarker_res_1.gsMarkerColor = 'black' polymarker_res_1.gsMarkerIndex = 16 polymarker_res_1.gsMarkerSizeF = 0.012 polymarker_res_1.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_1) ######################################################################## polymarker_res_2 = Ngl.Resources() polymarker_res_2.gsMarkerColor = 'white' polymarker_res_2.gsMarkerIndex = 16 polymarker_res_2.gsMarkerSizeF = 0.008 polymarker_res_2.gsMarkerThicknessF = 1 Ngl.polymarker(wks, plot, point['lon'], point['lat'], polymarker_res_2)''' ######################################################################## run_time = datetime.datetime(run['year'], run['month'], run['day'], run['hour']) timeshift = 2 if timeshift == 1: time_code = 'CET' # UTC+1 elif timeshift == 2: time_code = 'CEST' # UTC+2 run_time = run_time + datetime.timedelta(0, 3600 * int(timeshift)) valid_time = run_time + datetime.timedelta(0, 3600 * int(4 * 24 + 12)) text1 = '4-Tages-Vorhersage der Maximaltemperatur vom 21.07.19: \ Wahrscheinlichkeit, dass am 25.07.19 Temperaturen von \ 36 ~S~o~N~C, 38 ~S~o~N~C, 40 ~S~o~N~C u~H-13V2F35~H~FV-2H3~berschritten werden' text1 = 'Vorhersage der Hitzewelle ' text1 = 'Modell: ICON-EU-EPS, Bildautor: Marco Wurth, IMK-TRO (KIT)' #text2 = 'Wahrscheinlichkeit fu~H-13V2F35~H~FV-2H3~r u~H-13V2F35~H~FV-2H3~ber {:d} ~S~o~N~C'.format(int(threshold)) text_res_1 = Ngl.Resources() text_res_1.txJust = 'BottomLeft' text_res_1.txFontHeightF = 0.009 x = 0.01 y = 0.01 Ngl.text_ndc(wks, text1, x, y, text_res_1) text_res_1.txFontHeightF = 0.018 x = 0.25 y = 0.94 #Ngl.text_ndc(wks, text2, x, y, text_res_1) text_res_1.txFontHeightF = 0.014 x = 0.575 y = 0.93 #Ngl.text_ndc(wks, text3, x, y, text_res_1) text_res_1.txFontHeightF = 0.014 x = 0.025 y = 0.192 #Ngl.text_ndc(wks, text4, x, y, text_res_1) Ngl.frame(wks) Ngl.destroy(wks) return
def clubb_std_prf(ptype, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir, varis, vname, cscale, chscale, pname): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. alphas = [ 'a) ', 'b) ', 'c) ', 'd) ', 'e) ', 'f) ', 'g) ', 'h) ', 'i) ', 'j) ', 'k) ', 'l) ', 'm) ', 'n) ', 'o) ', 'p) ', 'q) ', 'r) ', 's) ', 't) ', 'u) ', 'v) ', 'w) ', 'x) ', 'y) ', 'z) ' ] infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite nvaris = len(varis) plotstd = ["" for x in range(nsite)] for ire in range(0, nsite): if not os.path.exists(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N'): os.mkdir(casedir + '/' + str(lons[ire]) + 'E_' + str(lats[ire]) + 'N') plotname = casedir + '/' + str(lons[ire]) + 'E_' + str( lats[ire]) + 'N/' + pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason plotstd[ire] = pname + '_' + str(lons[ire]) + "E_" + str( lats[ire]) + "N_" + cseason wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "GMT_paired") plot = [] res = Ngl.Resources() res.nglMaximize = False if (lats[ire] > 0 and lons[ire] < 230): res.trYMinF = 400. res.trYMaxF = 1000. else: res.trYMinF = 700. res.trYMaxF = 1000. res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .02 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.vpXF = 0.04 res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tiYAxisFont = _Font res.tiXAxisFont = _Font res.tmXBLabelFontHeightF = 0.01 res.tmXBLabelFontThicknessF = 2.0 res.xyMarkLineMode = "Lines" res.xyLineThicknesses = [ 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3., 3., 3., 3., 3, 3, 3, 3, 3, 3, 3 ] res.xyDashPatterns = np.arange(0, 24, 1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 res.tiYAxisString = "Pressure [hPa]" for iv in range(0, nvaris): if (iv == nvaris - 1): res.pmLegendDisplayMode = "NEVER" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = True else: res.pmLegendDisplayMode = "NEVER" # if(obsdataset[iv] =="CCCM"): # if(cseason == "ANN"): # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-"+cseason+".nc" # else: # fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-"+cseason+".nc" # inptrobs = Dataset(fileobs,'r') # B=inptrobs.variables[varisobs[iv]][:,(lats[ire]),(lons[ire])] # else: # if (varisobs[iv] =="PRECT"): # fileobs = filepathobs+'/GPCP_'+cseason+'_climo.nc' # else: # fileobs = filepathobs + obsdataset[iv]+'_'+cseason+'_climo.nc' # inptrobs = Dataset(fileobs,'r') # if (varisobs[iv] =="THETA"): # B = inptrobs.variables['T'][0,:,(lats[ire]),(lons[ire])] # pre1 = inptrobs.variables['lev'][:] # for il1 in range (0, len(pre1)): # B[il1] = B[il1]*(1000/pre1[il1])**0.286 # else: # pre1 = inptrobs.variables['lev'][:] # B = inptrobs.variables[varisobs[iv]][0,:,(lats[ire]),(lons[ire])] # # B[:]=B[:] * cscaleobs[iv] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + cases[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) lev = inptrs.variables['ilev'][:] nlev = len(lev) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:, :] ncdf.close() if (im == 0): A_field = np.zeros((ncases, nlev), np.float32) for subc in range(0, n[ire]): npoint = idx_cols[ire, n[subc] - 1] - 1 if (varis[iv] == 'THETA'): tmp = inptrs.variables['T'][0, :, npoint] hyam = inptrs.variables['hyam'][:] hybm = inptrs.variables['hybm'][:] ps = inptrs.variables['PS'][0, npoint] ps = ps p0 = inptrs.variables['P0'] pre = np.zeros((nlev), np.float32) for il in range(0, nlev): pre[il] = hyam[il] * p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000 / pre[il])**0.286 theunits = str( chscale[iv]) + inptrs.variables['T'].units else: tmp = inptrs.variables[varis[iv]][0, :, npoint] # tmp2=inptrs.variables['C6rt_Skw_fnc'][0,:,npoint] # tmp3=inptrs.variables['tau_zm'][0,:,npoint] # tmp4=inptrs.variables['tau_wpxp_zm'][0,:,npoint] theunits = str( chscale[iv]) + inptrs.variables[varis[iv]].units if (varis[iv] == 'tau_zm' or varis[iv] == 'tau_wp2_zm' \ or varis[iv] == 'tau_wp3_zm' or varis[iv] == 'tau_xp2_zm' \ or varis[iv] == 'tau_no_N2_zm' or varis[iv] == 'tau_wpxp_zm'): tmp = 1 / tmp tmp[0:10] = 0.0 theunits = str(chscale[iv]) + inptrs.variables[ varis[iv]].units + '^-1' A_field[im, :] = (A_field[im, :] + tmp[:] / n[ire]).astype( np.float32) A_field[im, :] = A_field[im, :] * cscale[iv] inptrs.close() res.tiXAxisString = vname[iv] + " Unit= " + theunits res.trYReverse = True res.xyLineColors = np.arange(3, 20, 2) res.xyMarkerColors = np.arange(2, 20, 2) p = Ngl.xy(wks, A_field, lev, res) plot.append(p) pres = Ngl.Resources() pres.nglFrame = False pres.txFont = _Font pres.nglMaximize = False pres.txFont = _Font # pres.nglPanelYWhiteSpacePercent = 5 # pres.nglPanelXWhiteSpacePercent = 5 # pres.wkPaperWidthF = 17 # in inches # pres.wkPaperHeightF = 28 # in inches pres.nglPanelTop = 0.935 pres.nglPanelFigureStrings = alphas pres.nglPanelFigureStringsJust = 'Topleft' pres.nglPanelFigureStringsFontHeightF = 0.015 pres.gsnPaperOrientation = "Landscape" txres = Ngl.Resources() txres.txFontHeightF = 0.02 txres.txFont = _Font Ngl.text_ndc( wks, "CLUBB VAR at " + str(lons[ire]) + "E," + str(lats[ire]) + "N", 0.5, 0.75, txres) Common_functions.create_legend(wks, casenames, 0.015, np.arange(3, 20, 2), 0.3, 0.59 + ncases * 0.01) Ngl.panel(wks, plot[:], [nvaris / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) return plotstd
def delete(self): Ngl.destroy(self.workstation)
def draw_3D_plot(ptype, clevel, cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs, casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) if not os.path.exists(casedir + "/2D"): os.mkdir(casedir + "/2D") _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] varis = ["T", "OMEGA", "Z3"] varisobs = ["T", "OMEGA", "Z3"] alpha = ["A", "B", "C", "D", "E", "F"] nvaris = len(varis) cunits = [""] cscale = [1, 864, 1, 1, 1, 1] cscaleobs = [1, 1, 1, 1, 0.04] cntrs = np.zeros((nvaris, 11), np.float32) obsdataset = ["ERAI", "ERAI", "ERAI", "ERAI", "ERAI"] level = [ 1000., 925., 850., 700., 600., 500., 400., 300., 250., 200., 150., 100. ] plot3d = ["" for x in range(nvaris)] for iv in range(0, nvaris): # make plot for each field # Observational data if (obsdataset[iv] == "CCCM"): if (cseason == "ANN"): fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-" + cseason + ".nc" else: fileobs = "/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-" + cseason + ".nc" else: if (varisobs[iv] == "PRECT"): fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc' else: fileobs = filepathobs + obsdataset[ iv] + '_' + cseason + '_climo.nc' inptrobs = Dataset(fileobs, 'r') latobs = inptrobs.variables['lat'][:] lonobs = inptrobs.variables['lon'][:] levobs = inptrobs.variables['lev'][:] levobs_idx = np.abs(levobs - clevel).argmin() B = inptrobs.variables[varisobs[iv]][0, levobs_idx, :, :] B = B * cscaleobs[iv] # cntrs= np.arange(np.min(B),np.max(B),12) if (varis[iv] == "OMEGA"): cntrs[iv, :] = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50] if (varis[iv] == "Z3"): if (clevel == 500): cntrs[iv, :] = [ 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100, 6200, 6300 ] else: cntrs[iv, :] = [ 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300 ] if (varis[iv] == "T"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] if (varis[iv] == "Q"): if (clevel == 500): cntrs[iv, :] = [ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310 ] else: cntrs[iv, :] = [ 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312 ] #************************************************ # create plot #************************************************ plotname = casedir + '/2D/Horizontal_' + varis[ iv] + '_' + cseason + str(clevel) plot3d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason + str(clevel) wks = Ngl.open_wks(ptype, plotname) Ngl.define_colormap(wks, "amwg256") plot = [] textres = Ngl.Resources() textres.txFontHeightF = 0.02 # Size of title. textres.txFont = _Font Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres) pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelBottom = 0.2 pres.nglPanelTop = 0.9 pres.nglPanelLabelBar = True pres.pmLabelBarWidthF = 0.8 pres.nglFrame = False pres.nglPanelLabelBar = True # Turn on panel labelbar pres.nglPanelLabelBarLabelFontHeightF = 0.015 # Labelbar font height pres.nglPanelLabelBarHeightF = 0.0750 # Height of labelbar pres.nglPanelLabelBarWidthF = 0.700 # Width of labelbar pres.lbLabelFont = "helvetica-bold" # Labelbar font pres.nglPanelTop = 0.93 pres.nglPanelFigureStrings = alpha pres.nglPanelFigureStringsJust = "BottomRight" res = Ngl.Resources() res.nglDraw = False #-- don't draw plots res.nglFrame = False res.cnFillOn = True res.cnFillMode = "RasterFill" res.cnLinesOn = False res.nglMaximize = True res.mpFillOn = True res.mpCenterLonF = 180 res.tiMainFont = _Font res.tiMainFontHeightF = 0.025 res.tiXAxisString = "" res.tiXAxisFont = _Font res.tiXAxisFontHeightF = 0.025 res.tiYAxisString = "" res.tiYAxisFont = _Font res.tiYAxisOffsetXF = 0.0 res.tiYAxisFontHeightF = 0.025 res.tmXBLabelFont = _Font res.tmYLLabelFont = _Font res.tiYAxisFont = _Font # res.nglStringFont = _Font # res.nglStringFontHeightF = 0.04 # res.nglRightString = ""#"Cloud Fraction" # res.nglScalarContour = True res.cnInfoLabelOn = False res.cnFillOn = True res.cnLinesOn = False res.cnLineLabelsOn = False res.lbLabelBarOn = False # res.vcRefMagnitudeF = 5. # res.vcMinMagnitudeF = 1. # res.vcRefLengthF = 0.04 # res.vcRefAnnoOn = True#False # res.vcRefAnnoZone = 3 # res.vcRefAnnoFontHeightF = 0.02 # res.vcRefAnnoString2 ="" # res.vcRefAnnoOrthogonalPosF = -1.0 # res.vcRefAnnoArrowLineColor = "blue" # change ref vector color # res.vcRefAnnoArrowUseVecColor = False # res.vcMinDistanceF = .05 # res.vcMinFracLengthF = . # res.vcRefAnnoParallelPosF = 0.997 # res.vcFillArrowsOn = True # res.vcLineArrowThicknessF = 3.0 # res.vcLineArrowHeadMinSizeF = 0.01 # res.vcLineArrowHeadMaxSizeF = 0.03 # res.vcGlyphStyle = "CurlyVector" # turn on curley vectors # res@vcGlyphStyle ="Fillarrow" # res.vcMonoFillArrowFillColor = True # res.vcMonoLineArrowColor = True # res.vcLineArrowColor = "green" # change vector color # res.vcFillArrowEdgeColor ="white" # res.vcPositionMode ="ArrowTail" # res.vcFillArrowHeadInteriorXF =0.1 # res.vcFillArrowWidthF =0.05 #default # res.vcFillArrowMinFracWidthF =.5 # res.vcFillArrowHeadMinFracXF =.5 # res.vcFillArrowHeadMinFracYF =.5 # res.vcFillArrowEdgeThicknessF = 2.0 res.mpFillOn = False res.cnLevelSelectionMode = "ExplicitLevels" res.cnLevels = cntrs[iv, :] for im in range(0, ncases): ncdfs[im] = './data/' + cases[im] + '_site_location.nc' infiles[im] = filepath[im] + '/' + cases[ im] + '_' + cseason + '_climo.nc' inptrs = Dataset(infiles[im], 'r') # pointer to file1 lat = inptrs.variables['lat'][:] nlat = len(lat) lon = inptrs.variables['lon'][:] nlon = len(lon) #area=inptrs.variables['area'][:] lev = inptrs.variables['lev'][:] lev_idx = np.abs(lev - clevel).argmin() area_wgt = np.zeros(nlat) # area_wgt[:] = gw[:] sits = np.linspace(0, nsite - 1, nsite) ncdf = Dataset(ncdfs[im], 'r') n = ncdf.variables['n'][:] idx_cols = ncdf.variables['idx_cols'][:] A = inptrs.variables[varis[iv]][0, lev_idx, :] A_xy = A A_xy = A_xy * cscale[iv] ncdf.close() inptrs.close() if im == 0: dsizes = len(A_xy) field_xy = [[0 for col in range(dsizes)] for row in range(ncases)] field_xy[im][:] = A_xy res.lbLabelBarOn = False if (np.mod(im, 2) == 0): res.tiYAxisOn = True else: res.tiYAxisOn = False res.tiXAxisOn = False res.sfXArray = lon res.sfYArray = lat res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lon) res.mpMinLonF = min(lon) res.mpMinLatF = min(lat) res.mpMaxLatF = max(lat) #res.tiMainString = "GLB="+str(np.sum(A_xy[:]*area[:]/np.sum(area))) res.tiMainString = "GLB=" textres.txFontHeightF = 0.015 Ngl.text_ndc(wks, alpha[im] + " " + casenames[im], 0.3, .135 - im * 0.03, textres) p = Ngl.contour_map(wks, A_xy, res) plot.append(p) # observation # res.nglLeftString = obsdataset[iv] # res@lbLabelBarOn = True # res@lbOrientation = "vertical" # vertical label bars res.lbLabelFont = _Font res.tiYAxisOn = True res.tiXAxisOn = True res.tiXAxisFont = _Font rad = 4.0 * np.arctan(1.0) / 180.0 re = 6371220.0 rr = re * rad dlon = abs(lonobs[2] - lonobs[1]) * rr dx = dlon * np.cos(latobs * rad) jlat = len(latobs) dy = np.zeros(jlat, dtype=float) # close enough dy[0] = abs(lat[2] - lat[1]) * rr dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5 dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr area_wgt = dx * dy # is_SE = False sum1 = 0 sum2 = 0 for j in range(0, jlat - 1): for i in range(0, len(lonobs) - 1): if (np.isnan(B[j][i]) != "--"): sum1 = sum1 + area_wgt[j] * B[j][i] sum2 = sum2 + area_wgt[j] res.sfXArray = lonobs res.sfYArray = latobs res.mpLimitMode = "LatLon" res.mpMaxLonF = max(lonobs) res.mpMinLonF = min(lonobs) res.mpMinLatF = min(latobs) res.mpMaxLatF = max(latobs) res.tiMainString = "GLB=" + str( sum1 / sum2) #Common_functions.area_avg(B, area_wgt,is_SE)) p = Ngl.contour_map(wks, B, res) plot.append(p) if (np.mod(ncases + 1, 2) == 1): Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres) else: Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres) Ngl.frame(wks) Ngl.destroy(wks) return plot3d
def draw_clubb_bgt (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir,varis,cscale,chscale,pname,dofv): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varisobs = [ "CLOUD", "OMEGA","SHUM","CLWC_ISBL", "THATA","RELHUM"] nvaris = len(varis) cunits = ["%", "mba/day","g/kg","g/kg","K", "%", "mba/day", "K", "g/kg", "m/s", "m/s","K","m"] cscaleobs = [100., 100/86400., 1., 1000, 1., 1., 1, 1,1,1] obsdataset =["CCCM", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI", "ERAI","ERAI","ERAI"] plotbgt=["" for x in range(nsite*ncases)] for ire in range (0, nsite): for im in range (0,ncases): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/'+pname+'_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason plotbgt[im+ncases*ire] = pname+'_'+casenames[im]+"_"+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,"radar") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 # res.txFontHeightF = .01 # res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tmXBLabelFontHeightF = 0.005 res.tmXBLabelFontThicknessF = 1.0 res.xyMarkLineMode = "MarkLines" res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2] res.xyLineColors = np.arange(2,16,1) res.xyDashPatterns = np.arange(0,24,1) res.xyMarkers = np.arange(16,40,1) res.xyMarkerSizeF = 0.005 res.xyMarkerColors = np.arange(2,16,1) res.pmLegendDisplayMode = "ALWAYS" res.pmLegendSide = "top" # Change location of res.pmLegendParallelPosF = 0.75 # move units right res.pmLegendOrthogonalPosF = -0.65 # more neg = down res.pmLegendWidthF = 0.10 # Change width and res.pmLegendHeightF = 0.15 # height of legend. res.lgLabelFontHeightF = .01 # change font height res.lgLabelFontThicknessF = 1. res.lgBoxMinorExtentF = 0.1 res.lgPerimOn = True res.tiYAxisString = "PRESSURE" res.tiYAxisString = "Pressure [hPa]" res.tmYLLabelFontHeightF = 0.02 res.trYReverse = True pres = Ngl.Resources() # pres.nglMaximize = True pres.nglFrame = False pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 for iv in range (0, nvaris): if (varis[iv] == "rtp2" or varis[iv] == "thlp2"): budget_ends = ["_bt", "_ma", "_ta", "_tp", "_dp1", "_dp2", "_cl", "_pd", "_sf", "_forcing"] nterms = len (budget_ends) if (varis[iv] == "wprtp") : budget_ends = ["_bt", "_ma", "_ta", "_tp", "_ac","_bp","_pr1","_pr2", "_pr3","_dp1","_mfl", "_cl", "_sicl","_pd", "_forcing"] nterms = len (budget_ends) if (varis[iv] == "wpthlp") : budget_ends = ["_bt", "_ma", "_ta", "_tp", "_ac","_bp","_pr1","_pr2", "_pr3","_dp1","_mfl", "_cl", "_sicl", "_forcing"] nterms = len (budget_ends) if (varis[iv] == "rtpthlp") : budget_ends = ["_bt", "_ma", "_ta", "_tp1","_tp2","_dp1","_dp2", "_cl", "_sf", "_forcing"] nterms = len (budget_ends) if (varis[iv] == "wp2") : budget_ends = ["_bt", "_ma", "_ta", "_ac","_bp","_pr1","_pr2", "_pr3","_dp1","_dp2", "_cl", "_pd", "_sf"] nterms = len (budget_ends) if (varis[iv] == "wp3") : budget_ends = ["_bt", "_ma", "_ta", "_tp", "_ac","_bp1","_bp2","_pr1","_pr2","_dp1", "_cl"] nterms = len (budget_ends) if (varis[iv] == "up2" or varis[iv] == "vp2") : budget_ends = ["_bt", "_ma", "_ta", "_tp", "_dp1", "_dp2","_pr1","_pr2" ,"_cl", "_pd", "_sf"] nterms = len (budget_ends) if (varis[iv] == "um" or varis[iv] == "vm") : budget_ends = ["_bt", "_ma","_ta","_gf", "_f"] nterms = len (budget_ends) if (varis[iv] == "thlm" or varis[iv] == "rtm") : budget_ends = ["_bt", "_ma","_ta","_cl", "_mc"] nterms = len (budget_ends) ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) ilev=inptrs.variables['ilev'][:] nilev=len(ilev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] if (dofv): idx_lats=ncdf.variables['idx_coord_lat'][:,:] idx_lons=ncdf.variables['idx_coord_lon'][:,:] ncdf.close() A_field = np.zeros((nterms,nilev),np.float32) theunits=str(chscale[iv])+"x"+inptrs.variables[varis[iv]+'_bt'].units res.tiMainString = varis[iv]+" "+theunits for it in range(0, nterms): for subc in range( 0, n[ire]): varis_bgt= varis[iv]+budget_ends[it] npoint=idx_cols[ire,n[subc]-1]-1 if(dofv): npointlat=idx_lats[ire,0] npointlon=idx_lons[ire,0] if (dofv): tmp=inptrs.variables[varis_bgt][0,:,npointlat,npointlon] else: tmp=inptrs.variables[varis_bgt][0,:,npoint] #/n[ire] if (varis[iv] == "wprtp" ) : tmp [0:10] = 0.0 tmp=tmp*cscale[iv] A_field[it,:] = (A_field[it,:]+tmp[:]/n[ire]).astype(np.float32 ) inptrs.close() res.xyExplicitLegendLabels = budget_ends[:] p = Ngl.xy(wks,A_field,ilev,res) plot.append(p) xp=np.mod(iv,2) yp=int(iv/2) # pres.txFontHeightF = 0.02 # pres.txString = casenames[im]+" BUDGET at" +str(lons[ire])+"E,"+str(lats[ire])+"N" Ngl.panel(wks,plot[:],[nvaris/2,2],pres) txres = Ngl.Resources() txres.txFont = _Font txres.txFontHeightF = 0.020 Ngl.text_ndc(wks,casenames[im]+" BUDGET at" +str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.95,txres) Ngl.frame(wks) Ngl.destroy(wks) return (plotbgt)
def plot_contourmap(path, date, fcst_hours, variable, stat_processing_methods): ##### generate subpath and filename ##### subpath = 'run_{}{:02}{:02}{:02}/{}/'.format(\ date['year'], date['month'], date['day'], date['hour'], variable) filename1 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[0], variable) filename2 = 'icon-eu-eps_europe_icosahedral_single-level_{}{:02}{:02}{:02}_{:03}_{}.grib2'.format(\ date['year'], date['month'], date['day'], date['hour'], fcst_hours[1], variable) ######################################################################## ### read data ### ######################################################################## ##### create empty numpy arrays ##### ##### 2 fcst_hours, 40 members, 75948 eu gridpoints ##### data_raw = np.empty((2, 40, 75948)) data_members = np.empty((40, 75948)) ##### every time in loop open next grib msg from grib file ##### ##### grib messages in dwd file are sorted by increasing member number ##### with open(path['base'] + path['data'] + subpath + filename1, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[0, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) with open(path['base'] + path['data'] + subpath + filename2, 'rb') as file: for member in range(1, 41): print('read data from member {}'.format(member)) grib_msg_id = eccodes.codes_grib_new_from_file(file) data_raw[1, member - 1, :] = eccodes.codes_get_array( grib_msg_id, 'values') eccodes.codes_release(grib_msg_id) ##### take the difference of the two accumulated total precipitation arrays ##### data_members = data_raw[1, :, :] - data_raw[0, :, :] del data_raw ##### open icon-eps grid file ##### icongrid_file = nc.Dataset( path['base'] + path['grid'] + 'icon_grid_0028_R02B07_N02.nc', 'r') vlat = icongrid_file.variables['clat_vertices'][:].data * 180. / np.pi vlon = icongrid_file.variables['clon_vertices'][:].data * 180. / np.pi clat = icongrid_file.variables['clat'][:].data * 180. / np.pi clon = icongrid_file.variables['clon'][:].data * 180. / np.pi icongrid_file.close() for stat_processing in stat_processing_methods: ######################################################################## ### statistically process data ### ######################################################################## if stat_processing == 'mean': data_processed = data_members.mean(axis=0) elif stat_processing == 'max': data_processed = data_members.max(axis=0) elif stat_processing == 'min': data_processed = data_members.min(axis=0) elif stat_processing == '90p': data_processed = np.percentile(data_members, 90, axis=0) elif stat_processing == '75p': data_processed = np.percentile(data_members, 75, axis=0) elif stat_processing == '50p': data_processed = np.percentile(data_members, 50, axis=0) elif stat_processing == '25p': data_processed = np.percentile(data_members, 25, axis=0) elif stat_processing == '10p': data_processed = np.percentile(data_members, 10, axis=0) #print('shape of data_members: {}'.format(np.shape(data_members))) #print('shape of data_processed: {}'.format(np.shape(data_processed))) ######################################################################## ### plot data on world map ### ######################################################################## ##### set domain due to center point and radius ##### center_point = dict(lat=48.5, lon=9.0) radius = 1800 # domain radius in km around center_point domain = dict( lat_min=center_point['lat'] - radius / 111.2, lat_max=center_point['lat'] + radius / 111.2, lon_min=center_point['lon'] - radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), lon_max=center_point['lon'] + radius / (111.2 * np.cos(center_point['lat'] * np.pi / 180)), ) ##### or set domain manually in deg N/E ##### '''domain = dict( lat_min = 0.0, lat_max = 20.0, lon_min = 0.0, lon_max = 20.0, )''' ##### set image size (should be squared) ##### ##### plotting area in pyngl can not exceed squared area even if plotting on rectangular images ##### ##### for obtaining rectangular plots on has to cut manually afterwards e.g. with pillow package ##### x_resolution = 800 y_resolution = 800 wks_res = Ngl.Resources() wks_res.wkWidth = x_resolution wks_res.wkHeight = y_resolution plot_name = 'contourplot_icon-eu-eps_tot_prec_{:02d}-{:02d}h_{}'.format(\ fcst_hours[0], fcst_hours[1], stat_processing) wks_type = 'png' wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name, wks_res) resources = Ngl.Resources( ) # create resources object containing all the plot settings resources.mpProjection = 'Hammer' # projection type resources.mpCenterLonF = (domain['lon_max'] + domain['lon_min'] ) / 2 # projection center point resources.mpCenterLatF = (domain['lat_max'] + domain['lat_min']) / 2 resources.mpLimitMode = 'latlon' resources.mpMinLonF = domain['lon_min'] resources.mpMaxLonF = domain['lon_max'] resources.mpMinLatF = domain['lat_min'] resources.mpMaxLatF = domain['lat_max'] ##### set plot area ##### resources.nglMaximize = False resources.vpXF = 0.05 resources.vpYF = 0.9 resources.vpWidthF = 0.7 resources.vpHeightF = 0.7 ##### set all map plot settings ##### resources.mpFillOn = True # turn on filled map areas resources.mpFillColors = [ 'pink', 'blue', 'white', 'white' ] # set colors for [FillValue, Ocean, Land , InlandWater] resources.mpDataBaseVersion = 'MediumRes' # quality of national borders resources.mpDataSetName = 'Earth..4' resources.mpOutlineBoundarySets = 'national' #resources.mpDataBaseVersion = 'HighRes' #resources.mpDataResolution = 'Fine' resources.mpGeophysicalLineThicknessF = 7.0 * x_resolution / 1000 # keep borders thickness resolution-independent resources.mpNationalLineThicknessF = 7.0 * x_resolution / 1000 #resources.mpGridAndLimbDrawOrder = 'postdraw' resources.mpGridAndLimbOn = False # turn off geographic coordinates grid #resources.mpLimbLineColor = 'black' #resources.mpLimbLineThicknessF = 10 #resources.mpGridLineColor = 'black' #resources.mpGridLineThicknessF = 1.0 #resources.mpGridSpacingF = 1 resources.mpPerimOn = True # turn on perimeter around plot resources.mpPerimLineColor = 'black' resources.mpPerimLineThicknessF = 8.0 * x_resolution / 1000 # keep perimeter thickness resolution-independent resources.tmXBOn = False # turn off location ticks around plot resources.tmXTOn = False resources.tmYLOn = False resources.tmYROn = False resources.sfDataArray = data_processed # data input file to plot resources.sfXArray = clon # array with cell center locations resources.sfYArray = clat resources.sfXCellBounds = vlon # array with cell vertices locations resources.sfYCellBounds = vlat resources.sfMissingValueV = 9999 # in case you want to mask values resources.cnFillOn = True resources.cnFillMode = 'CellFill' #resources.cnCellFillEdgeColor = 'black' # uncomment this for plotting the cell edges resources.cnMissingValFillColor = 'black' resources.cnFillPalette = 'WhiteBlueGreenYellowRed' # color palette resources.cnLevelSelectionMode = 'ManualLevels' minlevel = 0.0 # min level of colorbar maxlevel = 50.0 # max level of colorbar numberoflevels = 250 # number of levels of colorbar, max. 250 with this color palette resources.cnMinLevelValF = minlevel resources.cnMaxLevelValF = maxlevel resources.cnLevelSpacingF = (maxlevel - minlevel) / numberoflevels resources.cnLinesOn = False # turn off contour lines resources.cnLineLabelsOn = False # turn off contour labels ##### set resources for a nice colorbar ##### resources.lbLabelBarOn = True resources.lbAutoManage = False resources.lbOrientation = 'vertical' resources.lbLabelOffsetF = 0.05 #resources.lbBoxMinorExtentF = 0.2 resources.lbLabelStride = 25 # print a tick every 25 levels resources.lbLabelFontHeightF = 0.016 resources.lbBoxSeparatorLinesOn = False resources.lbBoxLineThicknessF = 4.0 #resources.lbBoxEndCapStyle = 'TriangleBothEnds' resources.lbLabelAlignment = 'BoxCenters' resources.lbTitleString = 'mm' resources.lbTitleFontHeightF = 0.016 resources.lbTitlePosition = 'Right' resources.lbTitleDirection = 'Across' resources.lbTitleAngleF = 90.0 resources.lbTitleExtentF = 0.1 resources.lbTitleOffsetF = -0.15 resources.nglFrame = False # hold on frame because will plot text afterwards on same plot Ngl.contour_map(wks, data_processed, resources) # plot the actual plot ##### plot title text ##### text = '{:02d}-{:02d}h Total Precipitation {}, ICON-EPS run {:02}.{:02}.{} {:02}Z'.format(\ fcst_hours[0], fcst_hours[1], stat_processing,\ date['day'], date['month'], date['year'], date['hour']) x = 0.5 y = 0.95 text_res_1 = Ngl.Resources() text_res_1.txFontHeightF = 0.018 text_res_1.txJust = 'TopCenter' Ngl.text_ndc(wks, text, x, y, text_res_1) Ngl.frame(wks) # advance frame Ngl.destroy( wks ) # delete workspace to free memory, relevant if plotting various plots in one script print('plotted "{}.png"'.format(plot_name)) return
def silhs_prf (ptype,cseason, ncases, cases, casenames, nsite, lats, lons, filepath, filepathobs,casedir): # ncases, the number of models # cases, the name of models # casename, the name of cases # filepath, model output filepath # filepathobs, filepath for observational data # inptrs = [ncases] if not os.path.exists(casedir): os.mkdir(casedir) _Font = 25 interp = 2 extrap = False mkres = Ngl.Resources() mkres.gsMarkerIndex = 2 mkres.gsMarkerColor = "Red" mkres.gsMarkerSizeF = 15. infiles = ["" for x in range(ncases)] ncdfs = ["" for x in range(ncases)] nregions = nsite varis = [ "SILHS_CLUBB_PRECIP_FRAC","SILHS_CLUBB_ICE_SS_FRAC","HR","AWNC","AWNI","ADSNOW","ANSNOW","AQSNOW","RHW","QRS","QRL","AQRAIN" ] nvaris = len(varis) cunits = ["%","mba/day","g/kg","g/kg","K", "%", "m/s", "g/kg", "m/s", "m/s","K","m" ] cscale = [1, 1, 1, 1, 1., 1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ] plotsilhs=["" for x in range(nsite)] for ire in range (0, nsite): if not os.path.exists(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N'): os.mkdir(casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N') plotname = casedir+'/'+str(lons[ire])+'E_'+str(lats[ire])+'N/silhs_'+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason plotsilhs[ire] = 'CLUBB_standard_'+str(lons[ire])+"E_"+str(lats[ire])+"N_"+cseason wks= Ngl.open_wks(ptype,plotname) Ngl.define_colormap(wks,"GMT_paired") plot = [] res = Ngl.Resources() res.nglDraw = False res.nglFrame = False res.lgLabelFontHeightF = .012 # change font height res.lgPerimOn = False # no box around res.vpWidthF = 0.30 # set width and height res.vpHeightF = 0.30 res.txFontHeightF = .01 #res.vpXF = 0.04 # res.vpYF = 0.30 res.tmYLLabelFont = _Font res.tmXBLabelFont = _Font res.tmXBLabelFontHeightF = 0.005 res.tmXBLabelFontThicknessF = 1.0 res.tmXBLabelAngleF = 45 res.xyMarkLineMode = "Lines" res.xyLineThicknesses = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,2.,2.,2.,2.,2,2,2,2,2,2,2] res.xyDashPatterns = np.arange(0,24,1) # res.xyMarkers = np.arange(16,40,1) # res.xyMarkerSizeF = 0.005 pres = Ngl.Resources() pres.nglMaximize = True pres.txString = str(lons[ire])+"E,"+str(lats[ire])+"N" pres.txFont = _Font pres.nglPanelYWhiteSpacePercent = 5 pres.nglPanelXWhiteSpacePercent = 5 pres.nglPanelTop = 0.93 txres = Ngl.Resources() txres.txFontHeightF = 0.01 for iv in range (0, nvaris): if(iv == nvaris-1): res.pmLegendDisplayMode = "ALWAYS" res.xyExplicitLegendLabels = casenames[:] res.pmLegendSide = "top" res.pmLegendParallelPosF = 0.6 res.pmLegendOrthogonalPosF = -0.5 res.pmLegendWidthF = 0.10 res.pmLegendHeightF = 0.10 res.lgLabelFontHeightF = .02 res.lgLabelFontThicknessF = 1.5 res.lgPerimOn = False else: res.pmLegendDisplayMode = "NEVER" for im in range (0,ncases): ncdfs[im] = './data/'+cases[im]+'_site_location.nc' infiles[im]= filepath[im]+cases[im]+'/'+cases[im]+'_'+cseason+'_climo.nc' inptrs = Dataset(infiles[im],'r') # pointer to file1 lat=inptrs.variables['lat'][:] nlat=len(lat) lon=inptrs.variables['lon'][:] nlon=len(lon) lev=inptrs.variables['ilev'][:] nlev=len(lev) ncdf= Dataset(ncdfs[im],'r') n =ncdf.variables['n'][:] idx_cols=ncdf.variables['idx_cols'][:,:] ncdf.close() if (im ==0): A_field = np.zeros((ncases,nlev),np.float32) for subc in range( 0, n[ire]): npoint=idx_cols[ire,n[subc]-1]-1 if (varis[iv] == 'THETA'): tmp = inptrs.variables['T'][0,:,npoint] hyam =inptrs.variables['hyam'][:] hybm =inptrs.variables['hybm'][:] ps=inptrs.variables['PS'][0,npoint] ps=ps p0=inptrs.variables['P0'] pre = np.zeros((nlev),np.float32) for il in range (0, nlev): pre[il] = hyam[il]*p0 + hybm[il] * ps tmp[il] = tmp[il] * (100000/pre[il])**0.286 theunits=str(cscale[iv])+inptrs.variables['T'].units else: tmp=inptrs.variables[varis[iv]][0,:,npoint] theunits=str(cscale[iv])+inptrs.variables[varis[iv]].units A_field[im,:] = (A_field[im,:]+tmp[:]/n[ire]).astype(np.float32 ) A_field[im,:] = A_field[im,:] *cscale[iv] inptrs.close() res.tiMainString = varis[iv]+" x"+theunits res.trXMinF = min(np.min(A_field[0, :]))#,np.min(B)) res.trXMaxF = max(np.max(A_field[0, :]))#,np.max(B)) if(varis[iv] == "THETA"): res.trXMinF = 280. res.trXMaxF = 400. if(varis[iv] == "CLOUD" or varis[iv] =="RELHUM") : res.trXMinF = 0. res.trXMaxF = 100. if(varis[iv] == "T") : res.trXMinF = 180 res.trXMaxF = 300 if(varis[iv] == "U") : res.trXMinF = -40 res.trXMaxF = 40 res.trYReverse = True res.xyLineColors = np.arange(2,20,1) res.xyMarkerColors = np.arange(2,20,2) p = Ngl.xy(wks,A_field,lev,res) plot.append(p) Ngl.panel(wks,plot[:],[nvaris/3,3],pres) txres = Ngl.Resources() txres.txFontHeightF = 0.020 Ngl.text_ndc(wks,"SILHS VAR at"+ str(lons[ire])+"E,"+str(lats[ire])+"N",0.5,0.05,txres) Ngl.frame(wks) Ngl.destroy(wks) return plotsilhs