def readdiag(nvar): var = getvar(ncfile, nvar) smooth_var = smooth2d(var, 3) lats, lons = latlon_coords(smooth_var) lons = to_np(lons) lats = to_np(lats) cart_proj = get_cartopy(var) return lons,lats
def get_plot_element(infile): rootgroup = Dataset(infile, 'r') p = wrf.getvar(rootgroup, 'RAINNC') #lats, lons = wrf.latlon_coords(p) cart_proj = wrf.get_cartopy(p) xlim = wrf.cartopy_xlim(p) ylim = wrf.cartopy_ylim(p) rootgroup.close() return cart_proj, xlim, ylim
def prepare_figure(smooth_slp): fig = plt.figure() ax = plt.axes(projection=get_cartopy(smooth_slp)) states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('10m', linewidth=0.8) ax.set_xlim(cartopy_xlim(smooth_slp)) ax.set_ylim(cartopy_ylim(smooth_slp)) # box containing San Francisco Bay, Monterey Bay ax.set_extent((-123.0, -121.0, 36.2, 38.0)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") return (fig, ax)
def filter_available_stations_inside_wrf_domain(nc, time_range, aod_level): """ Return list of stations within the domain and time interval Take into account map distortion and first transform coordinates to PlateCarree and then test if the stations are inside domain :param domain: :param time_range: :param aod_level: :return: """ # list of stations, that have the temporal coverage prelim_stations = get_available_stations(time_range, aod_level) import wrf as wrf # wrf-python library https://wrf-python.readthedocs.io/en/latest/ import cartopy.crs as crs from shapely.geometry.polygon import Polygon wrf_proj = wrf.get_cartopy(wrfin=nc) proj = crs.PlateCarree() geo_bounds = wrf.geo_bounds(wrfin=nc) domain_points = [(geo_bounds.bottom_left.lon, geo_bounds.bottom_left.lat), (geo_bounds.bottom_left.lon, geo_bounds.top_right.lat), (geo_bounds.top_right.lon, geo_bounds.top_right.lat), (geo_bounds.top_right.lon, geo_bounds.bottom_left.lat)] pc_points = [ proj.transform_point(point[0], point[1], wrf_proj) for point in domain_points ] domain = Polygon(pc_points) # domain in the transoformed coordinates # filter stations within the domain stations_inside_domain = pd.DataFrame(columns=prelim_stations.columns) for index, station in prelim_stations.iterrows(): # point = Point(station['Longitude(decimal_degrees)'], station['Latitude(decimal_degrees)']) point = [ station['Longitude(decimal_degrees)'], station['Latitude(decimal_degrees)'] ] point = Point(proj.transform_point(point[0], point[1], wrf_proj)) if domain.contains(point): stations_inside_domain = stations_inside_domain.append( station, ignore_index=True) return stations_inside_domain
def get_plot_element(infile): """get_plot_element .. description: get boxes from geo_em files to draw on plot .. args: infile (str): filename (e.g. geo_em.d01.nc) .. returns: cart_proj xlim ylim """ rootgroup = nc.Dataset(infile, 'r') p = getvar(rootgroup, 'HGT_M') cart_proj = get_cartopy(p) xlim = cartopy_xlim(p) ylim = cartopy_ylim(p) rootgroup.close() return cart_proj, xlim, ylim
def plot_domain(nc): """ quick way to plot the WRF simulation domain :param nc: :return: """ # import to work with WRF output import wrf as wrf # wrf-python library https://wrf-python.readthedocs.io/en/latest/ fig = plt.figure(figsize=(12, 6)) # Set the GeoAxes to the projection used by WRF cart_proj = wrf.get_cartopy(wrfin=nc) ax = plt.axes(projection=cart_proj) ax.coastlines('50m', linewidth=0.8) # Set the map bounds ax.set_xlim(wrf.cartopy_xlim(wrfin=nc)) ax.set_ylim(wrf.cartopy_ylim(wrfin=nc)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") return fig, ax
for j in range(theta_cross_filled.shape[-1]): column_vals_th = theta_cross_filled[:,j] first_idx_th = int(np.transpose((column_vals_th > -200).nonzero())[0]) theta_cross_filled[0:first_idx_th, j] = theta_cross_filled[first_idx_th,j] # Get the terrain heights along the cross section line ter_line = interpline(ter, wrfin=wrf_file, start_point=cross_start, end_point=cross_end) road_line = interpline(ter, wrfin=wrf_file,start_point=road1,end_point=road2) # Get the lat/lon points lats, lons = latlon_coords(wind) # Get the cartopy projection object cart_proj = get_cartopy(wind) # Create the figure fig = pyplot.figure(figsize=(8,6)) ax_cross = pyplot.axes() wind_levels = np.arange(2., 26., 2.) # Create the color table found on NWS pages. #wind_rgb = np.array([[4,233,231], # [1,159,244], [3,0,244], # [2,253,2], [1,197,1], # [0,142,0], [253,248,2], # [229,188,0], [253,149,0], # [253,0,0], [212,0,0], # [188,0,0]], np.float32) / 255.0
wspd = getvar(ncfiles, "uvmet_wspd_wdir", timeidx=i, method="cat", units="m s-1", meta=True)[0, :, :] # Interpolate geopotential height, u, and v winds to 60 hPa levels = np.asarray([100]) u_60 = interplevel(ua, ht, levels) v_60 = interplevel(va, ht, levels) wspd_60 = interplevel(wspd, ht, levels) #get the latlon coordinates lats, lons = latlon_coords(wspd_60) cart_proj = get_cartopy(wspd_60) # Create the figure fig = plt.figure(figsize=(20, 17)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines fname = 'Rizal.shp' fname1 = 'gadm36_PHL_2.shp' shape_feature = ShapelyFeature(Reader(fname).geometries(), crs.PlateCarree(), facecolor='none') shape_feature1 = ShapelyFeature(Reader(fname1).geometries(), crs.PlateCarree(), facecolor='none')
# Open the NetCDF file ncfile = Dataset( "/Users/zhenkunli/Dropbox/share/results/wrfout_d01_2014-07-01_00:00:00") # Get the sea level pressure T2 = getvar(ncfile, "T2", timeidx=ALL_TIMES) print T2 # Smooth the sea level pressure since it tends to be noisy near the mountains T2 = smooth2d(T2, 3) # Get the latitude and longitude points lats, lons = latlon_coords(T2) # Get the cartopy mapping object cart_proj = get_cartopy(T2) print cart_proj # Create a figure fig = plt.figure(figsize=(8, 6)) # Set the GeoAxes to the projection used by WRF ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8)
time_index = 32 nc1 = Dataset(root_dir + file_dir1 + 'wrfout_d01_2015-11-27_00:00:00') qnifa1 = wrf.getvar(nc1, 'QNIFA', timeidx=time_index) nc2 = Dataset(root_dir + file_dir2 + 'wrfout_d01_2015-11-27_00:00:00') qnifa2 = wrf.getvar(nc2, 'QNIFA', timeidx=time_index) ## Quick Plot to check all is well # qnifa.plot() ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(qnifa1) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(qnifa1) ################################### ################################### ## WRF data processing ################################### ################################### ################################### ##### FILE #1 ################################### theta1 = wrf.getvar(nc1, 'T', timeidx=time_index) + 300 # potential temperature in K theta1.name = 'Potential temperature, K' pressure1 = wrf.getvar(nc1, 'P', timeidx=time_index) + wrf.getvar(
first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) var_cross_filled[0:first_idx, i] = var_cross_filled[first_idx, i] for i in range(w_cross_filled.shape[-1]): column_vals = w_cross_filled[:,i] first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) w_cross_filled[0:first_idx, i] = w_cross_filled[first_idx, i] # Para sacar las alturas del terreno del corte ter_line = interpline(ter, wrfin=wrf_file, start_point=cross_start, end_point=cross_end) # Sacar las lat/lon lats, lons = latlon_coords(var) # Sacar la projeccion de cartopy cart_proj = get_cartopy(var) ############# GRAFICADO ############# # Figura fig = plt.figure(figsize=(8,6)) ax_cross = plt.axes() ## si se quiere tener un intervalo para los datos #var_levels = np.arange(5, 100., 10.) # Se hace el grafico de la variable xs = np.arange(0, var_cross.shape[-1], 1) ys = to_np(var_cross.coords["vertical"]) tita_contours = ax_cross.contour(xs, ys, to_np(var_cross_filled),
def main(folder, wrffolder, append, sourceid, plotmap, plotcurves, plotcontour, plotcontourf, plotbarbs, resol): #z_unit = 'km' z_unit = 'dm' z_unitStr = 'dam' #u_unit = 'm s-1' u_unit = 'kt' w_unit = u_unit w_unitStr = 'm/s' w_unitStr = 'kt' p_unit = 'hPa' df_obs = pd.read_csv(folder + sourceid + '_json.txt', delimiter='\t') df_obs['time'] = pd.to_datetime(df_obs['CurrentTime'], unit='s') df_obs['air_temperature'] = df_obs['Temperature'] df_obs['pressure'] = df_obs['Barometric Pressure'] df_obs['wind_speed'] = df_obs[ 'Wind Speed'] * 1.852 / 3.6 # Convert from knots to m/s if z_unit == "km": feetScale = 0.3048 / 1000 elif z_unit == "m": feetScale = 0.3048 elif z_unit == "dm": feetScale = 0.3048 / 10 df_obs['z'] = df_obs['Alt'].to_numpy( ) * feetScale # Convert from feet to decameters (dam) # Get data from WRF file i_domain = 10 isOutside = True while isOutside: if i_domain < 0: print('Parts of the flightpath for ' + str(sourceid) + ' is not inside the solution domain') break i_domain -= 1 try: ncfile = Dataset(wrffolder + '/wrfout_d0' + str(i_domain) + '.nc') except: continue fields = ['T', 'wind_speed', 'wind_from_direction'] lat_e = df_obs['Latitude'].to_numpy() lon_e = df_obs['Longitude'].to_numpy() z_e = df_obs['z'].to_numpy() time_e = df_obs['time'].to_numpy() dummy = pd.DataFrame( {'time': wrf.getvar(ncfile, 'Times', wrf.ALL_TIMES)}) time = dummy['time'].to_numpy() indices = (time[0] <= time_e) & (time_e <= time[-1]) if not np.any(indices): raise OutOfRange('The mode-S data is out of range') lat_e = lat_e[indices] lon_e = lon_e[indices] z_e = z_e[indices] time_e = time_e[indices] x = np.zeros((lat_e.shape[0], 4)) xy = wrf.ll_to_xy(ncfile, lat_e, lon_e, as_int=False, meta=False) if ncfile.MAP_PROJ_CHAR == 'Cylindrical Equidistant' and i_domain == 1: xy[0] += 360 / 0.25 x[:, 0] = xy[0] x[:, 1] = xy[1] e_we = ncfile.dimensions['west_east'].size e_sn = ncfile.dimensions['south_north'].size if np.any(xy < 0) or np.any(xy[0] > e_we - 1) or np.any( xy[1] > e_sn - 1): print('Flight path is outside domain d0' + str(i_domain)) continue else: print('Extracting WRF-data from domain d0' + str(i_domain)) if plotcurves: xy2 = np.zeros(xy.T.shape) xy2[:, :] = xy[:, :].T #zgrid = wrf.interp2dxy(wrf.getvar(ncfile,'z',units=z_unit),xy2,meta=False) zgrid = wrf.interp2dxy(wrf.g_geoht.get_height(ncfile, units=z_unit), xy2, meta=False) # Get geopotential height for i in range(0, len(z_e)): f_time = interp1d(zgrid[:, i], range(0, zgrid.shape[0]), kind='linear') x[i, 2] = f_time(z_e[i]) f_time = interp1d(time.astype('int'), range(0, len(time)), kind='linear') x[:, 3] = f_time(time_e.astype('int')) df_wrf = pd.DataFrame() df_wrf['time'] = time_e df_wrf['air_temperature'] = linInterp( wrf.getvar(ncfile, 'tc', wrf.ALL_TIMES, meta=False), x) df_wrf['pressure'] = linInterp( wrf.g_pressure.get_pressure(ncfile, wrf.ALL_TIMES, meta=False, units=p_unit), x) df_wrf['wind_speed'] = linInterp( wrf.g_wind.get_destag_wspd(ncfile, wrf.ALL_TIMES, meta=False), x) df_wrf['wind_from_direction'] = linInterp( wrf.g_wind.get_destag_wdir(ncfile, wrf.ALL_TIMES, meta=False), x) if df_wrf.isnull().values.any(): print('Some points are outside the domain ' + str(i_domain)) continue else: isOutside = False else: isOutside = False if plotcurves: # Plot data sharex = True #fields = np.array([['air_temperature','wind_speed','pressure'], # ['windDirX', 'windDirY','z']]) #ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]', 'Pressure ['+p_unit+']'], # ['Wind direction - X','Wind direction - Y', 'Altitude ['+z_unitStr+']']]) fields = np.array([['air_temperature', 'wind_speed'], ['windDirX', 'windDirY']]) ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]'], ['Wind direction - X', 'Wind direction - Y']]) df_obs['windDirX'] = np.cos(np.radians(df_obs['Wind Direction'])) df_obs['windDirY'] = np.sin(np.radians(df_obs['Wind Direction'])) df_wrf['windDirX'] = np.cos(np.radians(df_wrf['wind_from_direction'])) df_wrf['windDirY'] = np.sin(np.radians(df_wrf['wind_from_direction'])) df_wrf['z'] = z_e fig, axs = plt.subplots(fields.shape[0], fields.shape[1], sharex=sharex) mng = plt.get_current_fig_manager() #mng.resize(*mng.window.maxsize()) #mng.frame.Maximize(True) mng.window.showMaximized() title = 'Comparison between Mode-S data and WRF simulations for flight ' + sourceid if plotcurves: title += '. WRF data from domain d0' + str( i_domain) + ' with grid resolution {:.1f} km'.format( max(ncfile.DX, ncfile.DY) / 1000) fig.suptitle(title) for i in range(0, fields.shape[0]): for j in range(0, fields.shape[1]): axs[i, j].plot(df_wrf.time.to_numpy(), df_wrf[fields[i, j]].to_numpy(), 'b', label='WRF forecast') axs[i, j].plot(df_obs.time.to_numpy(), df_obs[fields[i, j]].to_numpy(), 'r', label='Observation data') axs[i, j].legend() axs[i, j].set(xlabel='Time', ylabel=ylabels[i, j]) axs[i, j].set_xlim(time_e[0], time_e[-1]) axs[1, 0].set_ylim(-1, 1) axs[1, 1].set_ylim(-1, 1) plt.show() fig.savefig(folder + '/' + sourceid + '_curves.png', dpi=400) if plotmap: # Extract the pressure, geopotential height, and wind variables ncfile = Dataset(wrffolder + '/wrfout_d01.nc') p = wrf.g_pressure.get_pressure(ncfile, units=p_unit) #p = getvar(ncfile, "pressure",units=p_unit) z = getvar(ncfile, "z", units=z_unit) ua = getvar(ncfile, "ua", units=u_unit) va = getvar(ncfile, "va", units=u_unit) wspd = getvar(ncfile, "wspd_wdir", units=w_unit)[0, :] # Interpolate geopotential height, u, and v winds to 500 hPa ht_500 = interplevel(z, p, 500) u_500 = interplevel(ua, p, 500) v_500 = interplevel(va, p, 500) wspd_500 = interplevel(wspd, p, 500) # Get the lat/lon coordinates lats, lons = latlon_coords(ht_500) # Get the map projection information cart_proj = get_cartopy(ht_500) # Create the figure fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines name = 'admin_0_boundary_lines_land' #name = 'admin_1_states_provinces_lines' #name = "admin_1_states_provinces_shp" bodr = cfeature.NaturalEarthFeature(category='cultural', name=name, scale=resol, facecolor='none') land = cfeature.NaturalEarthFeature('physical', 'land', \ scale=resol, edgecolor='k', facecolor=cfeature.COLORS['land']) ocean = cfeature.NaturalEarthFeature('physical', 'ocean', \ scale=resol, edgecolor='none', facecolor=cfeature.COLORS['water']) lakes = cfeature.NaturalEarthFeature('physical', 'lakes', \ scale=resol, edgecolor='b', facecolor=cfeature.COLORS['water']) rivers = cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', \ scale=resol, edgecolor='b', facecolor='none') ax.add_feature(land, facecolor='beige', zorder=0) ax.add_feature(ocean, linewidth=0.2, zorder=0) ax.add_feature(lakes, linewidth=0.2, zorder=1) ax.add_feature(bodr, edgecolor='k', zorder=1, linewidth=0.5) #ax.add_feature(rivers, linewidth=0.5,zorder=1) if plotcontour: # Add the 500 hPa geopotential height contour levels = np.arange(100., 2000., 10.) contours = plt.contour(to_np(lons), to_np(lats), to_np(ht_500), levels=levels, colors="forestgreen", linewidths=1, transform=ccrs.PlateCarree(), zorder=3) plt.clabel(contours, inline=1, fontsize=10, fmt="%i") if plotcontourf: try: with open(home + '/kode/colormaps/SINTEF1.json') as f: json_data = json.load(f) SINTEF1 = np.reshape(json_data[0]['RGBPoints'], (-1, 4)) cmap = ListedColormap(fill_colormap(SINTEF1)) except: print( 'SINTEF1 colormap not found (can be found at https://github.com/Zetison/colormaps.git)' ) cmap = get_cmap("rainbow") # Add the wind speed contours levels = np.linspace(20, 120, 101) wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(wspd_500), levels=levels, cmap=cmap, alpha=0.7, antialiased=True, transform=ccrs.PlateCarree(), zorder=2) cbar_wspd = plt.colorbar(wspd_contours, ax=ax, orientation="horizontal", pad=.05, shrink=0.5, aspect=30, ticks=range(10, 110, 10)) cbar_wspd.ax.set_xlabel('Wind speeds [' + w_unitStr + '] at 500 mbar height') # Add the 500 hPa wind barbs, only plotting every nthb data point. nthb = 10 if plotbarbs: plt.barbs(to_np(lons[::nthb, ::nthb]), to_np(lats[::nthb, ::nthb]), to_np(u_500[::nthb, ::nthb]), to_np(v_500[::nthb, ::nthb]), transform=ccrs.PlateCarree(), length=6, zorder=3) track = sgeom.LineString( zip(df_obs['Longitude'].to_numpy(), df_obs['Latitude'].to_numpy())) fullFlightPath = ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', zorder=4, edgecolor='red', linewidth=2, label='Flight path') track = sgeom.LineString(zip(lon_e, lat_e)) flightPath = ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', zorder=4, linestyle=':', edgecolor='green', linewidth=2, label='Extracted flight path') #plt.legend(handles=[fullFlightPath]) #blue_line = mlines.Line2D([], [], color='red',linestyle='--', label='Flight path',linewidth=2) #plt.legend(handles=[blue_line]) # Set the map bounds ax.set_xlim(cartopy_xlim(ht_500)) ax.set_ylim(cartopy_ylim(ht_500)) #ax.gridlines(draw_labels=True) ax.gridlines() startdate = pd.to_datetime(str( time_e[0])).strftime("%Y-%m-%d %H:%M:%S") plt.title('Flight ' + sourceid + ', with visualization of WRF simulation (' + startdate + ') at 500 mbar Height (' + z_unitStr + '), Wind Speed (' + w_unitStr + '), Barbs (' + w_unitStr + ')') # Plot domain boundaries infile_d01 = wrffolder + '/wrfout_d01.nc' cart_proj, xlim_d01, ylim_d01 = get_plot_element(infile_d01) infile_d02 = wrffolder + '/wrfout_d02.nc' _, xlim_d02, ylim_d02 = get_plot_element(infile_d02) infile_d03 = wrffolder + '/wrfout_d03.nc' _, xlim_d03, ylim_d03 = get_plot_element(infile_d03) infile_d04 = wrffolder + '/wrfout_d04.nc' _, xlim_d04, ylim_d04 = get_plot_element(infile_d04) # d01 ax.set_xlim([ xlim_d01[0] - (xlim_d01[1] - xlim_d01[0]) / 15, xlim_d01[1] + (xlim_d01[1] - xlim_d01[0]) / 15 ]) ax.set_ylim([ ylim_d01[0] - (ylim_d01[1] - ylim_d01[0]) / 15, ylim_d01[1] + (ylim_d01[1] - ylim_d01[0]) / 15 ]) # d01 box textSize = 10 colors = ['blue', 'orange', 'brown', 'deepskyblue'] linewidth = 1 txtscale = 0.003 ax.add_patch( mpl.patches.Rectangle((xlim_d01[0], ylim_d01[0]), xlim_d01[1] - xlim_d01[0], ylim_d01[1] - ylim_d01[0], fill=None, lw=linewidth, edgecolor=colors[0], zorder=10)) ax.text(xlim_d01[0], ylim_d01[0] + (ylim_d01[1] - ylim_d01[0]) * (1 + txtscale), 'd01', size=textSize, color=colors[0], zorder=10) # d02 box ax.add_patch( mpl.patches.Rectangle((xlim_d02[0], ylim_d02[0]), xlim_d02[1] - xlim_d02[0], ylim_d02[1] - ylim_d02[0], fill=None, lw=linewidth, edgecolor=colors[1], zorder=10)) ax.text(xlim_d02[0], ylim_d02[0] + (ylim_d02[1] - ylim_d02[0]) * (1 + txtscale * 3), 'd02', size=textSize, color=colors[1], zorder=10) # d03 box ax.add_patch( mpl.patches.Rectangle((xlim_d03[0], ylim_d03[0]), xlim_d03[1] - xlim_d03[0], ylim_d03[1] - ylim_d03[0], fill=None, lw=linewidth, edgecolor=colors[2], zorder=10)) ax.text(xlim_d03[0], ylim_d03[0] + (ylim_d03[1] - ylim_d03[0]) * (1 + txtscale * 3**2), 'd03', size=textSize, color=colors[2], zorder=10) # d04 box ax.add_patch( mpl.patches.Rectangle((xlim_d04[0], ylim_d04[0]), xlim_d04[1] - xlim_d04[0], ylim_d04[1] - ylim_d04[0], fill=None, lw=linewidth, edgecolor=colors[3], zorder=10)) ax.text(xlim_d04[0], ylim_d04[0] + (ylim_d04[1] - ylim_d04[0]) * (1 + txtscale * 3**3), 'd04', size=textSize, color=colors[3], zorder=10) plt.show() fig.savefig(folder + '/' + sourceid + '_map.png', dpi=400)
# Open the NetCDF file ncfile = Dataset("/Users/zhenkunli/Dropbox/share/results/wrfout_d01_2014-07-01_00:00:00") # Get the sea level pressure LH = getvar(ncfile, "LH", timeidx=ALL_TIMES) print LH # Smooth the sea level pressure since it tends to be noisy near the mountains LH = smooth2d(LH, 3) # Get the latitude and longitude points lats, lons = latlon_coords(LH) # Get the cartopy mapping object cart_proj = get_cartopy(LH) print cart_proj # Create a figure fig = plt.figure(figsize=(8,6)) # Set the GeoAxes to the projection used by WRF ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8) # Make the contour outlines and filled contours for the smoothed sea level pressure. plt.contour(to_np(lons), to_np(lats), to_np(LH[160,:,:]), 10, colors="black",
def plotmap(data1, data2, data3, time_index, z_index): import matplotlib import matplotlib.cm as mpl_cm import matplotlib.pyplot as plt import cartopy.crs as crs import cartopy.feature as cfe ################################### ################################### ## Plot map (with cartopy) ################################### ################################### ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(data1) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(data1) data1 = wrf.to_np(data1[z_index,:,:]) data2 = wrf.to_np(data2[z_index,:,:]) data3 = wrf.to_np(data3[z_index,:,:]) # Create a figure fig = plt.figure(figsize=(8,4)) # Set the GeoAxes to the projection used by WRF ax = fig.add_axes([0.1,0.1,0.4,0.8], projection=cart_proj) # left, bottom, width, height # ax = plt.axes(projection=cart_proj) # Add coastlines ax.coastlines('50m', linewidth=0.8) ax.add_feature(cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none') ) # Plot contours plt.contourf(wrf.to_np(lons), wrf.to_np(lats), data1, 10, transform=crs.PlateCarree(), cmap = mpl_cm.Reds) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.62) cbar.set_label(data1.name[-5:]) # Set the map limits. Not really necessary, but used for demonstration. # ax.set_xlim(wrf.cartopy_xlim(qnwfa1)) # ax.set_ylim(wrf.cartopy_ylim(qnwfa1)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(data1.name+'\n'+str(data1.Time.values)) # Set the GeoAxes to the projection used by WRF ax = fig.add_axes([0.55,0.1,0.4,0.8], projection=cart_proj) # left, bottom, width, height # ax = plt.axes(projection=cart_proj) # Add coastlines ax.coastlines('50m', linewidth=0.8) ax.add_feature(cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none') ) # Plot contours plt.contourf(wrf.to_np(lons), wrf.to_np(lats), data2, 10, transform=crs.PlateCarree(), cmap = mpl_cm.Reds) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.62) cbar.set_label(data2.name[-5:]) # Set the map limits. Not really necessary, but used for demonstration. # ax.set_xlim(wrf.cartopy_xlim(qnwfa2)) # ax.set_ylim(wrf.cartopy_ylim(qnwfa2)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(data2.name+'\n'+str(data2.Time.values)) plt.show()
ua = getvar(wrf_file, "ua", tidx, units="kt") # viento zonal va = getvar(wrf_file, "va", tidx, units="kt") # viento meridional wspd = getvar(wrf_file, "wspd_wdir", tidx, units="kts")[0, :] # viento magnitud # Se interpolan las variables al campo de presion correspondiente para podee graficarlas ht = interplevel(z, p, nivel) u = interplevel(ua, p, nivel) v = interplevel(va, p, nivel) wspd = interplevel(wspd, p, nivel) # Se extraen lat-lon lats, lons = latlon_coords(ht) # Se extrae info de la proyeccion cart_proj = get_cartopy(ht) ############################################## GRAFICADO ############################################## fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Aniadiendo los contornos levels = np.arange(5200., 5800., 25.) contours = plt.contour(to_np(lons), to_np(lats), to_np(ht), levels=levels, colors="black", transform=crs.PlateCarree()) plt.clabel(contours, inline=1, fontsize=10,
filelist = [ncfile1, ncfile2, ncfile3] fig = plt.figure(figsize=(12, 8)) # Assign format baed on domain width gs = gridspec.GridSpec(5, 6, height_ratios=[0.1, 1, 1, 0.2, 0.2], width_ratios=[1, 1, 1, 1, 1, 1]) # for each file plot the topography for i, f in enumerate(filelist): # Get the sea level pressure HGT = getvar(f, "HGT_M") # Get the latitude and longitude points lats, lons = latlon_coords(HGT) # Get the cartopy mapping object cart_proj = get_cartopy(HGT) # Set the GeoAxes to the projection used by WRF if i == 0: ax = plt.subplot(gs[0:4, 0:3], projection=cart_proj) elif i == 1: ax = plt.subplot(gs[0:4, 3:5], projection=cart_proj) elif i == 2: ax = plt.subplot(gs[0:4, 5:6], projection=cart_proj) lat3, lons3 = lats, lons gl = ax.gridlines(draw_labels=True, alpha=0.2) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER if i == 0: gl.xlabel_style = {'weight': 'bold', 'fontsize': '16'} gl.ylabel_style = {'weight': 'bold', 'fontsize': '16'}
bj = str(int(ti[11:13]) + 8) bjt = ti.replace(ti[11:13], bj) BJT = bjt[0:19] #get dbz from wrf_out file dbz = getvar(f, 'dbz', timeidx=3) #get dbz in the specified height z = getvar(f, 'z') dbz_ht = interplevel(dbz, z, 2065.2) #get the latitude and longitude points lats, lons = latlon_coords(dbz_ht) #get the cartopy mapping object cart_proj = get_cartopy(dbz_ht) #creat a figure fig = plt.figure(figsize=(10, 7.5)) #set the geoaxes to the projection used by wrf ax = plt.axes(projection=cart_proj) #####################add background map############################### #define a function def add_shape(source, projection): return cfeature.ShapelyFeature(Reader(source).geometries(), projection, facecolor='none')
y_end = int(dims[0]-1) x_start = int(0) x_end = int(dims[1]/2) td2_zoom = td2[y_start:y_end, x_start:x_end] # Define the latitude and longitude coordinates lats, lons = latlon_coords(td2_zoom) ############################################################################### # Plot the data # The `get_cartopy` wrf function will automatically find and use the # intended map projection for this dataset cart_proj = get_cartopy(td2_zoom) fig = plt.figure(figsize=(12,12)) ax = plt.axes(projection=cart_proj) # Add features to the projection states = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=0.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) # Add filled dew point temperature contours plt.contourf(to_np(lons),
## Load in WRF data ################################### root_dir = '/data/mac/giyoung/MAC_WRFThompson/' nc = Dataset(root_dir + '2_Nisg80_ThompsonDefault/wrfout_d01_2015-11-27_00:00:00') t2 = wrf.getvar(nc, 'T2', timeidx=2) ## Quick Plot to check all is well # t2.plot() ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(t2) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(t2) # Create a figure fig = plt.figure(figsize=(6, 5)) # Set the GeoAxes to the projection used by WRF ax = plt.axes(projection=cart_proj) # Add coastlines ax.coastlines('50m', linewidth=0.8) ax.add_feature( cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none'))
# definindo o membro do qual se obterá as previsões dirArq = dataDir + '/membro' + str(membro + 1).zfill( 2) + '/' # zfill preenche esquerda com zeros, 2 dígitos if membro == 0: #print( '\t acessando membro 1' ) arq = nc.Dataset(dirArq + arqPrev) chuvac = wrf.getvar(arq, 'RAINC', wrf.ALL_TIMES) chuvanc = wrf.getvar(arq, 'RAINNC', wrf.ALL_TIMES) varMet = chuvac + chuvanc varMet = varMet.rename('chuva') if deltaDia == 0: projecaoWRF = wrf.get_cartopy( wrfin=arq) # projeção dos dados -> para plotagem dominioLimsX = wrf.cartopy_xlim(wrfin=arq) dominioLimsY = wrf.cartopy_ylim(wrfin=arq) arq.close() else: #print( '\t acessando membro '+str( membro+1 ) ) arq = nc.Dataset(dirArq + arqPrev) chuvac = wrf.getvar(arq, 'RAINC', wrf.ALL_TIMES) chuvanc = wrf.getvar(arq, 'RAINNC', wrf.ALL_TIMES) d2 = chuvac + chuvanc del chuvac, chuvanc
# Read bestTrck Data CMA dateparse = lambda x: datetime.datetime.strptime(x, '%Y%m%d%H') df_cma_obv=pd.read_csv(cma_path,parse_dates=True,index_col='time', sep='\s+', date_parser=dateparse) print('Plot...') # Create the figure # ----------seperate land/sea--------- # Get the map projection information fig = plt.figure(figsize=(12,8), frameon=True) proj = get_cartopy(lsmask) ax = fig.add_axes([0.08, 0.05, 0.8, 0.94], projection=proj) # Download and add the states and coastlines ax.coastlines(MAP_RES, linewidth=0.8) # plot province/city shp boundaries #ax.add_geometries(county_shp, ccrs.PlateCarree(),facecolor='none', edgecolor='gray',linewidth=0.5, zorder = 0) ax.add_geometries(province_shp, ccrs.PlateCarree(),facecolor='none', edgecolor='black',linewidth=1., zorder = 1) # Add ocean, land, rivers and lakes ax.add_feature(cfeature.OCEAN.with_scale(MAP_RES)) ax.add_feature(cfeature.LAND.with_scale(MAP_RES))
# Open the NetCDF file ncfile = Dataset( '/Users/sunt05/Documents/20180813WRF-SUEWS-London/wrfout_d03_2014-07-01_00:00:00' ) # Get the sea level pressure slp = getvar(ncfile, "T2", 10) # Smooth the sea level pressure since it tends to be noisy near the mountains smooth_slp = smooth2d(slp, 3) # Get the latitude and longitude points lats, lons = latlon_coords(slp) # Get the cartopy mapping object cart_proj = get_cartopy(slp) # Create a figure fig = plt.figure(figsize=(12, 9)) # Set the GeoAxes to the projection used by WRF ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8) # Make the contour outlines and filled contours for the smoothed sea level pressure.
# Extract the pressure and wind variables p = getvar(ncfile, "pressure") # Note: This is m/s. ua = getvar(ncfile, "ua") va = getvar(ncfile, "va") # Interpolate u, and v winds to 950 hPa u_950 = interplevel(ua, p, 950) v_950 = interplevel(va, p, 950) # Get the lat/lon coordinates lats, lons = latlon_coords(u_950) # Get the map projection information cart_proj = get_cartopy(u_950) # Create the figure fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=0.5) ax.coastlines('50m', linewidth=0.8) # Add the 950 hPa wind barbs, only plotting every 'thin'ed barb. Adjust thin # as needed. Also, no scaling is done for the arrows, so you might need to
time_index = 32 nc1 = Dataset(root_dir+file_dir1+'wrfout_d02_2015-11-27_00:00:00') olr1 = wrf.getvar(nc1, 'OLR', timeidx=time_index) nc2 = Dataset(root_dir+file_dir2+'wrfout_d02_2015-11-27_00:00:00') olr2 = wrf.getvar(nc2, 'OLR', timeidx=time_index) ## Quick Plot to check all is well # olr.plot() ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(olr1) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(olr1) ################################### ################################### ## WRF data processing ################################### ################################### ################################### ##### FILE #1 ################################### theta1 = wrf.getvar(nc1, 'T', timeidx=time_index) + 300 # potential temperature in K theta1.name = 'Potential temperature, K' pressure1 = wrf.getvar(nc1, 'P', timeidx=time_index) + wrf.getvar(nc1, 'PB', timeidx=time_index) # pressure in Pa pressure1.name = 'Air pressure, Pa'
z = getvar(ncfile, "z", units="dm") ua = getvar(ncfile, "ua", units="kt") va = getvar(ncfile, "va", units="kt") wspd = getvar(ncfile, "wspd_wdir", units="kts")[0, :] # Interpolate geopotential height, u, and v winds to 500 hPa ht_500 = interplevel(z, p, 1000) u_500 = interplevel(ua, p, 1000) v_500 = interplevel(va, p, 1000) wspd_500 = interplevel(wspd, p, 1000) # Get the lat/lon coordinates lats, lons = latlon_coords(ht_500) # Get the map projection information cart_proj = get_cartopy(ht_500) # Create the figure fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines ##states = NaturalEarthFeature(category="cultural", scale="50m", # facecolor="none", # name="admin_1_states_provinces_shp") #ax.add_feature(states, linewidth=0.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) # Add the 500 hPa geopotential height contours levels = np.arange(520., 580., 6.) contours = plt.contour(to_np(lons),
#proj = ccrs.LambertConformal() proj = ccrs.PlateCarree() prow = 1 pcol = 2 nc8 = Dataset(mp8 + filename) nc55 = Dataset(mp55 + filename) shape_feature = ShapelyFeature(Reader(shppath + shpname).geometries(), proj, facecolor='none') prec8 = nc8.variables['RAINNC'][7, :, :] #降水 prec55 = nc55.variables['RAINNC'][7, :, :] ctt8 = getvar(nc8, "ctt") ctt55 = getvar(nc55, "ctt") lats, lons = latlon_coords(ctt8) cart_proj = get_cartopy(ctt8) ax1 = fig.add_subplot(prow, pcol, 1, projection=cart_proj) cf1 = ax1.contourf(to_np(lons), to_np(lats), to_np(ctt8), cmap=cmaps.WhBlGrYeRe, transform=proj) plotdetails(ax1, ctt8, u'Cloud Top Temperature_mp8/$degC$') color_bar(fig, ax2, cf1) ax2 = fig.add_subplot(prow, pcol, 2, projection=cart_proj) cf2 = ax2.contourf(to_np(lons), to_np(lats), to_np(ctt55), cmap=cmaps.WhBlGrYeRe, transform=proj)
# Get the data. slp = getvar(ncfile, "slp", timeidx=78) uvmet10 = getvar(ncfile, "uvmet10", units="km h-1", timeidx=78) u10 = uvmet10[1,:,:] v10 = uvmet10[0,:,:] lh = getvar(ncfile, "LH", timeidx=78) # Smooth the sea level pressure since it tends to be noisy near the mountains. smooth_slp = smooth2d(slp, 5) # Get the latitude and longitude points. lats, lons = latlon_coords(slp) # Get the cartopy mapping object. cart_proj = get_cartopy(slp) # Create a figure. fig = plt.figure(figsize=(12,9)) # Set the GeoAxes to the projection used by WRF. ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines. states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',name='admin_0_countries') ax.coastlines('50m', linewidth=1.7) ax.add_feature(cfeature.BORDERS,linewidth=1.7) # Make the contour outlines and filled contours for the smoothed Sea Level Pressure. clevs1 = np.arange(980,1040.,2.) c1 = ax.contour(lons, lats, to_np(smooth_slp), levels=clevs1, colors="white",transform=crs.PlateCarree(), linewidths=1.3)
# SE HACE UN CICLO PARA TODOS LOS TIEMPOS DEL WRF_FILE for tidx in range(0, tpos) : # len(tpos) p = getvar(wrf_file, "pressure", tidx) # presion z = getvar(wrf_file, "z", tidx, units = 'm') # geopotencial w = getvar(wrf_file, "wa", tidx, units="m s-1") # vel vertical ter = getvar(wrf_file, "ter", tidx) # terreno alturas # Se interpolan las variables al campo de presion correspondiente para podee graficarlas w = interplevel(w, p, nivel) # Se extraen lat-lon lats, lons = latlon_coords(p) # Se extrae info de la proyeccion cart_proj = get_cartopy(p) ############################################## GRAFICADO ############################################## fig = plt.figure(figsize=(12,9)) ax = plt.axes(projection=cart_proj) # Aniadiendo los sombreados #levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120] levels = np.arange(-1.5, 1.5, 0.25) wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(w), levels=levels, cmap="bwr", transform=crs.PlateCarree()) plt.colorbar(wspd_contours, ax=ax)
time_index = 32 nc1 = Dataset(root_dir+file_dir1+'wrfout_d02_2015-11-27_00:00:00') qncloud1 = wrf.getvar(nc1, 'QNCLOUD', timeidx=time_index) nc2 = Dataset(root_dir+file_dir2+'wrfout_d02_2015-11-27_00:00:00') qncloud2 = wrf.getvar(nc2, 'QNCLOUD', timeidx=time_index) ## Quick Plot to check all is well # qncloud.plot() ## Get the latitude and longitude points lats, lons = wrf.latlon_coords(qncloud1) ## Get the cartopy mapping object cart_proj = wrf.get_cartopy(qncloud1) #### Define near-aircraft cloud box xlon = wrf.getvar(nc2, 'XLONG', timeidx=time_index) box = np.where(np.logical_and(xlon >=-29.5, xlon<=-26.5)) ################################### ################################### ## WRF data processing ################################### ################################### ################################### ##### FILE #1 ################################### theta1 = wrf.getvar(nc1, 'T', timeidx=time_index) + 300 # potential temperature in K
from cartopy.feature import NaturalEarthFeature from wrf import (getvar, interplevel, to_np, latlon_coords, get_cartopy, cartopy_xlim, cartopy_ylim, ALL_TIMES) ncfile = Dataset("wrfout_d01_2019-03-22_00:00:00") # Extract the pressure, geopotential height, and wind variables p = getvar(ncfile, "pressure", timeidx=ALL_TIMES) z = getvar(ncfile, "z", timeidx=ALL_TIMES, units="dm") u10 = getvar(ncfile, "U10", timeidx=ALL_TIMES) v10 = getvar(ncfile, "V10", timeidx=ALL_TIMES) wspd = getvar(ncfile, "wspd_wdir", timeidx=ALL_TIMES, units="kts")[0, :] # Get the lat/lon coordinates lats, lons = latlon_coords(u10) # Get the map projection information cart_proj = get_cartopy(u10) # Create the figure fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category="cultural", scale="50m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=0.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) lat = lats[:, :].squeeze() lon = lons[:, :].squeeze()
if len(pnmm.shape) < 4: nmembros, nlat, nlon = pnmm.shape else: nmembros, nt, nlat, nlon = pnmm.shape # campos médios e de dispersão pnmm_media = pnmm.mean(dim='membro') pnmm_dp = pnmm.std(dim='membro') # criando strings de tempo (p/ gráficos) strTempoPrev = np.datetime_as_string(tempoPrev, unit='h') # obtendo informações de projeção e coordenadas dos dados # devem ser usadas antes de qualquer conversão de unidades ou operação # aritmética projecaoWRF = wrf.get_cartopy(pnmm) lats, lons = wrf.latlon_coords(pnmm) # estados do Brasil estados = cfeature.NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') # definindo mapa de cores para desvio padrão # cores = ['white', 'green', 'yellow', 'orange', 'red' ] # mapa_cores = matplotlib.colors.ListedColormap( cores ) # mapa_cores.set_over( 'purple' ) # mapa_cores_norma = matplotlib.colors.Normalize( vmin=0, vmax=10 ) # cores = ['lawngreen','limegreen','forestgreen','green','white','plum','mediumorchid','fuchsia','magenta','orchid']