def Contour(files, Variable, COSMOind, RealCoord = True, pollon = -165., pollat = 35.): """ Draws contour plot of Variable """ dt = 5. * 60 dx = 0.025 #Get field if Variable == "TOT_PREC_S": field1 = pwg.getfield(files[COSMOind - 1], "TOT_PREC_S", invfile = False) field2 = pwg.getfield(files[COSMOind + 1], "TOT_PREC_S", invfile = False) field = (field2 - field1)/(dt*2)*3600 else: field = pwg.getfield(files[COSMOind], Variable, invfile = False) # Set up grid ny, nx = field.shape x = np.linspace(-dx * (nx -1) / 2, dx * (nx -1) / 2, nx) #y = np.linspace(-dx * (ny -1) / 2, dx * (ny -1) / 2, ny) Domain is slightly off center y = np.linspace(-22, 21, ny) if RealCoord: roteqlon = 180 + pollon roteqlat = 90 - pollat x += roteqlon y += roteqlat X, Y = np.meshgrid(x, y) if Variable == "FI": field = SmoothField(field, 8) levels = list(np.arange(400,600,8)) # Needs smoothing? plt.contour(X, Y, field/100, levels = levels, colors = "k", linewidths = 2) elif Variable == "T": field = SmoothField(field, 8) plt.contourf(X, Y, field, alpha = 0.5) plt.colorbar() #plt.contour(X, Y, field, levels = list(np.arange(150, 350, 4)), colors = "grey", linewidths = 2) elif Variable == "TOT_PREC_S": cmPrec =( (0 , 0.627 , 1 ), (0.137, 0.235 , 0.98 ), (0.1 , 0.1 , 0.784), (0.392, 0 , 0.627), (0.784, 0 , 0.627), (1 , 0.3 , 0.9 ) ) # Tobi's colormap levels = [0.1, 0.3, 1, 3, 10, 100] plt.contourf(X, Y, field, levels, colors=cmPrec, extend='max', alpha = 0.8, zorder = 10) plt.colorbar(shrink = 0.7) elif Variable == "PMSL": field = SmoothField(field, 8)/100 levels = list(np.arange(900, 1100, 5)) CS = plt.contour(X, Y, field, levels = levels, colors = 'k', linewidths = 1, zorder = 9, alpha = 0.5) plt.clabel(CS, fontsize = 7, inline = 1, fmt = "%.0f") else: plt.contour(X, Y, field) #plt.colorbar() del field
def _get_level(obj, filename, varname, level, leveltype = 'PS'): """ TODO NOTE: For now only pressure, not height! """ # Get pressure field try: levmat = pwg.getfield(filename, leveltype) / 100. # hPa except: print leveltype, 'not found. Try "PP"!' ppmat = pwg.getfield(filename, 'PP') / 100. # hPa HHhl = pwg.getfield(obj.cfile, 'HH') print HHhl.shape HHfl = cu.derive.hl_to_fl(HHhl) print HHfl.shape P0 = cosmo_ref_p(HHfl) / 100. # hPa del HH levmat = P0 + ppmat del P0, ppmat #except: #print 'ERROR! Not possible to get pressure data!' # Get variable array varmat = pwg.getfield(filename, varname) # Get indices minmat = levmat - level posinf = np.copy(minmat) neginf = np.copy(minmat) del minmat posinf[posinf >= 0] = np.inf neginf[neginf < 0] = np.inf negind = np.argmin(np.abs(posinf), axis = 0) posind = np.argmin(np.abs(neginf), axis = 0) negval = np.min(np.abs(posinf), axis = 0) posval = np.min(np.abs(neginf), axis = 0) # Create new array and loop over all entries array = np.zeros((varmat.shape[1:])) for i in range(array.shape[0]): for j in range(array.shape[1]): diff = negval[i, j] + posval[i, j] negweight = posval[i, j] / diff posweight = negval[i, j] / diff array[i, j] = (varmat[negind[i, j], i, j] * negweight + varmat[posind[i, j], i, j] * posweight) return array
def basemap(cfile, xlim, ylim): """ Draws Land-Sea Map Parameters ---------- cfile : string COSMO constants file location xlim : tuple Dimensions in x-direction in rotated coordinates ylim : tuple Dimensions in y-direction in rotated coordinates """ dx = 0.025 # Assumes COSMO 2.2 resolution field = pwg.getfield(cfile, "FR_LAND_S", invfile = False) # Setting up grid ny, nx = field.shape x = np.linspace(xlim[0], xlim[1], nx) y = np.linspace(ylim[0], ylim[1], ny) X, Y = np.meshgrid(x, y) # Plot and filter field field[field != 0] = 1. plt.contourf(X, Y, field, levels = [0.5, 2], colors = ["0.85"], zorder=0.4) #plt.contour(X, Y, field, 2, colors = "0.5") del field
def BaseMap(cfile, RealCoord = True, pollon = -165., pollat = 35.): """ Draws Land-Sea Map """ dx = 0.025 # Assumes COSMO 2.2 resolution field = pwg.getfield(cfile, "FR_LAND_S", invfile = False) # Setting up grid ny, nx = field.shape x = np.linspace(-dx * (nx -1) / 2, dx * (nx -1) / 2, nx) #y = np.linspace(-dx * (ny -1) / 2, dx * (ny -1) / 2, ny) Domain is slightly off center y = np.linspace(-22, 21, ny) if RealCoord: roteqlon = 180 + pollon roteqlat = 90 - pollat x += roteqlon y += roteqlat X, Y = np.meshgrid(x, y) # Plot and filter field field[field != 0] = 1. plt.contourf(X, Y, field, levels = [0.5, 2], colors = ["0.85"]) #plt.contour(X, Y, field, 2, colors = "0.5") del field
def _interpolate_3d(obj, varname, outint = 60): """ TODO """ # Get rotated lon/lat and height fields for interpolation hhobj = pwg.getfobj(obj.cfile, 'HH') clons = hhobj.rlons[0, :] clats = hhobj.rlats[:, 0] chhfield = hhobj.data hlevhh = [] # Use cu.derive.hl_to_fl for lev in range(chhfield.shape[0]-1): hlevhh.append((chhfield[lev] + chhfield[lev+1]) / 2) hlevhh = np.array(hlevhh) # Create new filelist newlist = [] for trjfn in obj.trjfiles: newfn = trjfn.rstrip('.nc') + '_' + varname + '.nc' newlist.append(newfn) os.system('cp ' + trjfn + ' ' + newfn) # Iterate over trajectory files for fn in newlist: print 'Opening file:', fn # Open Trajectory file rootgrp = nc.Dataset(fn, 'a') # Read position matrices lon = rootgrp.variables['longitude'][:, :] lat = rootgrp.variables['latitude'][:, :] z = rootgrp.variables['z'][:, :] # Allocate new netCDF array newvar = rootgrp.createVariable(varname, 'f4', ('time', 'id')) # Retrieve trajectory start time trjstart = rootgrp.variables['time'][0] / 60 # In mins # Iterate over trj times for itrj in range(lon.shape[0]): # Only interpolate if outint if (rootgrp.variables['time'][itrj] / 60) % outint == 0: # Get cosmo index icosmo = int((itrj * obj.dtrj + trjstart) / obj.dacosmo) print icosmo, itrj, rootgrp.variables['time'][itrj] / 60,obj.afiles[icosmo] field = pwg.getfield(obj.afiles[icosmo], varname) # Iterate over individual trajectories for trjid in range(lon.shape[1]): # NOTE: Nearest Neighbor method! ilon = lon[itrj, trjid] ilat = lat[itrj, trjid] iz = z[itrj, trjid] # Get nearest lat, lon lonid = np.abs(clons - ilon).argmin() latid = np.abs(clats - ilat).argmin() # Get closest vertical coordinate zid = np.abs(hlevhh[:, latid, lonid] - iz).argmin() # Get nearest neighbor newvar[itrj, trjid] = field[zid, latid, lonid] else: newvar[itrj, :] = np.nan # Clean up rootgrp.close() return newlist
def contour(filelist, variable, cosmoind, xlim, ylim, zlevel = None): """ Draws contour plot of one variable. Parameters ---------- filelist : list List of COSMO output files variable : string COSMO identifier of variable cosmoind : int index in filelist xlim : tuple Dimensions in x-direction in rotated coordinates ylim : tuple Dimensions in y-direction in rotated coordinates """ print 'Plotting:', variable dt = 5. * 60 dx = 0.025 # Retrieve or evaluate fields # NOTE: 'CUM_PREC' note implemented right now! #if variable == 'CUM_PREC': #field1 = pwg.getfield(filelist[trjstart/5], "TOT_PREC_S", #invfile = False) #field2 = pwg.getfield(filelist[-1], "TOT_PREC_S", #invfile = False) #diff = len(filelist)-1 - trjstart/5 #field = (field2 - field1)/(dt*diff)*3600 # Get precipitation difference if variable == "TOT_PREC_S": try: field1 = pwg.getfield(filelist[cosmoind - 1], "TOT_PREC_S", invfile = False) field2 = pwg.getfield(filelist[cosmoind + 1], "TOT_PREC_S", invfile = False) field = (field2 - field1)/(dt*2)*3600 except IndexError: # Reached end of array, use precip from previous time step field1 = pwg.getfield(filelist[cosmoind - 2], "TOT_PREC_S", invfile = False) field2 = pwg.getfield(filelist[cosmoind], "TOT_PREC_S", invfile = False) field = (field2 - field1)/(dt*2)*3600 # Retrieve regular fields elif zlevel != None: print zlevel field = pwg.getfield(filelist[cosmoind], variable, levs = zlevel) else: field = pwg.getfield(filelist[cosmoind], variable) # Setting up grid ny, nx = field.shape x = np.linspace(xlim[0], xlim[1], nx) y = np.linspace(ylim[0], ylim[1], ny) X, Y = np.meshgrid(x, y) # Plot fields with special format if variable == "FI": # Geopotential field field = smoothfield(field, 8) levels = list(np.arange(400,600,8)) plt.contour(X, Y, field/100, levels = levels, colors = "k", linewidths = 2) elif variable == "T": # Temperature field field = smoothfield(field, 8) #plt.contourf(X, Y, field, alpha = 0.5, zorder = 0.45) #plt.colorbar(shrink = 0.7) plt.contour(X, Y, field, levels = list(np.arange(150, 350, 4)), colors = "r", linewidths = 0.5, zorder = 0.45) elif variable in ["TOT_PREC_S", 'CUM_PREC']: # Precipitation fields cmPrec =( (0 , 0.627 , 1 ), (0.137, 0.235 , 0.98 ), (0.1 , 0.1 , 0.784), (0.392, 0 , 0.627), (0.784, 0 , 0.627), (1 , 0.3 , 0.9 ) ) # Tobi's colormap levels = [0.1, 0.3, 1, 3, 10, 100] plt.contourf(X, Y, field, levels, colors=cmPrec, extend='max', alpha = 0.8, zorder = 1) cbar = plt.colorbar(shrink = 0.7, pad = 0) cbar.set_label('Precipitation [cm/h]', rotation = 90) elif variable == "PMSL": # Surface pressure field = smoothfield(field, 8)/100 levels = list(np.arange(900, 1100, 5)) CS = plt.contour(X, Y, field, levels = levels, colors = 'k', linewidths = 1, zorder = 0.5, alpha = 0.5) plt.clabel(CS, fontsize = 7, inline = 1, fmt = "%.0f") elif variable == 'var145_S': # CAPE field = smoothfield(field, 8) levels = list(np.arange(100, 3000, 100)) plt.contourf(X, Y, field, cmap = plt.get_cmap('hot_r'), extend = 'max', levels = levels, alpha = 0.8, zorder = 0.45) cbar = plt.colorbar(shrink = 0.7) cbar.set_label('CAPE [J/kg]', rotation = 90) elif variable == 'var4': # PV #field = smoothfield(field, 2) field = field * 1.e6 # PVU levels = list(np.arange(-3, 8, 1)) plt.contourf(X, Y, field, cmap = plt.get_cmap('coolwarm'), extend = 'both', levels = levels, alpha = 0.5, zorder = 0.45) cbar = plt.colorbar(shrink = 0.7, pad = 0) cbar.set_label('PV [PVU]', rotation = 90) plt.contour(X, Y, field, color = 'black', levels = [2.], zorder = 0.5, linewidth = 4.) else: # All other fields, unformatted plt.contourf(X, Y, field) #plt.colorbar() del field
cmPrec = ((1, 1, 1), (0, 0.627, 1), (0.137, 0.235, 0.98), (0.392, 0, 0.627), (0.784, 0, 0.627)) #(0.1 , 0.1 , 0.784), levelsPrec = [0, 0.3, 1, 3, 10, 30] lev_max = 30 # Create box ie1, ie2, je1, je2 = args.box_coo # first indices (ie*) are N-S mask = np.zeros((461, 421)) mask[ie1:ie2, je1:je2] = 1 # Load HH hhfn = datadir + args.expid[ 0] + '/' + args.date + '/det/' + gribpref + ddhhmmss( timedelta(hours=0)) + 'c' + tsuf hhfield = getfield(hhfn, fieldn='HH') hhfield = (hhfield[1:] + hhfield[:-1]) / 2. meanhh = np.mean(np.mean(hhfield[:, ie1:ie2, je1:je2], axis=2), axis=1) del hhfield ############################## ncols = len(args.expid) fig1, axmat1 = plt.subplots(3, ncols, figsize=(4.5 * ncols, 14)) if ncols == 1: axmat1 = [axmat1] fig2, axmat2 = plt.subplots(3, ncols, figsize=(4.5 * ncols, 14)) cdict = { 'radar': 'k', 'REF': 'navy',
""" plot testing cosmo output """ import cosmo_utils.pywgrib as pwg import matplotlib.pyplot as plt lff0 = "/home/scratch/users/stephan.rasp/cosmo_test/lfff00000000_5m" # read file lff15 = "/home/scratch/users/stephan.rasp/cosmo_test/lfff00001000_5m" pwg.print_grib(lff0) # print content T = pwg.getfield(lff0, "var145_S") # extract field T as matrix w0 = pwg.getfield(lff0, "W") #print w0.shape w15= pwg.getfield(lff15, "W") ## Plotting ## plt.subplot(2,1,1) plt.contourf(T) #plt.subplot(2,1,2) #plt.contourf(w15) plt.show()