### Getting Variable Example Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/WRF_python_demo.ipynb A minimal example showing the import of the getvar function. ```python from wrf import getvar ``` -------------------------------- ### Build and Install WRF-Python (Windows) Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/contrib.rst Builds and installs WRF-Python on Windows systems. ```bash ./win_msvc_mingw_omp.bat ``` -------------------------------- ### Install via Source Code Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/installation.rst Instructions for installing wrf-python from its source code using pip. ```bash $ pip install . ``` -------------------------------- ### Get Number of OpenMP Processes Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of getting the number of available OpenMP processes. ```python from __future__ import print_function from wrf import omp_get_num_procs print(omp_get_num_procs()) ``` -------------------------------- ### Set and Get OpenMP Schedule Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of setting and getting the OpenMP schedule and its modifier. ```python from __future__ import print_function from wrf import omp_set_schedule, omp_get_schedule, OMP_SCHED_GUIDED omp_set_schedule(OMP_SCHED_GUIDED, 0) sched, modifier = omp_get_schedule() print(sched, modifier) ``` -------------------------------- ### Set and Get Number of OpenMP Threads Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of setting and getting the maximum number of OpenMP threads. ```python from __future__ import print_function from wrf import omp_set_num_threads, omp_get_max_threads omp_set_num_threads(4) print(omp_get_max_threads()) ``` -------------------------------- ### Build and Install WRF-Python (OSX/Linux) Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/contrib.rst Builds and installs WRF-Python on OSX and Linux systems. ```bash sh gnu_omp.sh ``` -------------------------------- ### Loop and Fill Technique Example Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example demonstrating the loop and fill technique for processing multiple WRF files. ```python from __future__ import print_function, division import numpy as np from netCDF4 import Dataset from wrf import getvar, ALL_TIMES filename_list = ["/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-28_00:00:00", "/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-28_12:00:00", "/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-29_00:00:00"] # Result shape (hardcoded for this example, modify as necessary) result_shape = (9, 29, 96, 96) # Only need 4-byte floats z_final = np.empty(result_shape, np.float32) # Modify this number if using more than 1 time per file times_per_file = 4 for timeidx in xrange(result_shape[0]): # Compute the file index and the time index inside the file fileidx = timeidx // times_per_file file_timeidx = timeidx % times_per_file f = Dataset(filename_list[fileidx]) z = getvar(f, "z", file_timeidx) z_final[timeidx,:] = z[:] f.close() ``` -------------------------------- ### Determining the Number of Available Processors Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst The example below shows how you can get the maximum number of processors that are available on your system. ```python from __future__ import print_function from wrf import omp_get_num_procs print(omp_get_num_procs()) ``` ```none 8 ``` -------------------------------- ### Using the cache Argument Example Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example demonstrating the use of the 'cache' argument in getvar for performance improvement. ```python from __future__ import print_function import time from netCDF4 import Dataset from wrf import getvar, ALL_TIMES, extract_vars wrf_filenames = ["/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-28_00:00:00", "/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-28_12:00:00", "/Users/ladwig/Documents/wrf_files/wrf_vortex_multi/wrfout_d02_2005-08-29_00:00:00"] wrfin = [Dataset(x) for x in wrf_filenames] start = time.time() my_cache = extract_vars(wrfin, ALL_TIMES, ("P", "PSFC", "PB", "PH", "PHB", "T", "QVAPOR", "HGT", "U", "V", "W")) end = time.time() print ("Time taken to build cache: ", (end-start), "s") vars = ("avo", "eth", "cape_2d", "cape_3d", "ctt", "dbz", "mdbz", "geopt", "helicity", "lat", "lon", "omg", "p", "pressure", "pvo", "pw", "rh2", "rh", "slp", "ter", "td2", "td", "tc", "theta", "tk", "tv", "twb", "updraft_helicity", "ua", "va", "wa", "uvmet10", "uvmet", "z", "cfrac", "zstag", "geopt_stag") start = time.time() for var in vars: v = getvar(wrfin, var, ALL_TIMES) end = time.time() no_cache_time = (end-start) print ("Time taken without variable cache: ", no_cache_time, "s") start = time.time() for var in vars: v = getvar(wrfin, var, ALL_TIMES, cache=my_cache) end = time.time() cache_time = (end-start) print ("Time taken with variable cache: ", cache_time, "s") improvement = ((no_cache_time-cache_time)/no_cache_time) * 100 print ("The cache decreased computation time by: ", improvement, "%") ``` -------------------------------- ### Install via Conda Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/installation.rst The recommended method for installing wrf-python is using Conda. ```bash conda install conda-forge::wrf-python ``` -------------------------------- ### Get SLP and Geo Bounds Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of getting sea level pressure (slp) and geographic boundaries from a NetCDF file. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import getvar, get_pyngl, latlon_coords, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") slp = getvar(ncfile, "slp") # Get the pyngl mapping object pyngl_resources = get_pyngl(slp) print (pyngl_resources) # Get the latitude and longitude coordinate. This is needed for plotting. lats, lons = latlon_coords(slp) # Get the geobounds for the full domain bounds = geo_bounds(slp) print(bounds) # Get the geographic boundaries for a subset of the domain slp_subset = slp[150:250, 150:250] slp_subset_bounds = geo_bounds(slp_subset) print (slp_subset_bounds) ``` -------------------------------- ### Build Script Example (GCC with OpenMP) Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/internals.rst Commands to uninstall the current wrf-python package, navigate to the build scripts directory, and execute the gnu_omp.sh script to build and install the Fortran code with OpenMP support. ```bash pip uninstall wrf-python cd build_scripts sh ./gnu_omp.sh ``` -------------------------------- ### Dbus Installation Message Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/boise_2018.rst Example message posted by the command terminal after dbus installation, indicating how to set it up to automatically load on login. ```none If this is your first install of dbus, automatically load on login with: mkdir -p ~/Library/LaunchAgents cp /path/to/miniconda3/envs/tutorial_test/org.freedesktop.dbus-session.plist ~/Library/LaunchAgents/ launchctl load -w ~/Library/LaunchAgents/org.freedesktop.dbus-session.plist ``` -------------------------------- ### Optional dbus setup Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/wrf_workshop_2017.rst Optional commands to automatically load the dbus package on login, as suggested by the miniconda installer. ```none mkdir -p ~/Library/LaunchAgents cp /path/to/miniconda2/envs/tutorial_test/org.freedesktop.dbus-session.plist ~/Library/LaunchAgents/ launchctl load -w ~/Library/LaunchAgents/org.freedesktop.dbus-session.plist ``` -------------------------------- ### Panel Plots Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/plot.rst This example shows how to make the panel plots on the first page of the documentation. ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs import cartopy.feature as cfeature from netCDF4 import Dataset from wrf import ( getvar, to_np, vertcross, smooth2d, CoordPair, GeoBounds, get_cartopy, latlon_coords, cartopy_xlim, cartopy_ylim ) # Open the NetCDF file ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the WRF variables slp = getvar(ncfile, "slp") smooth_slp = smooth2d(slp, 3) ctt = getvar(ncfile, "ctt") z = getvar(ncfile, "z") dbz = getvar(ncfile, "dbz") Z = 10**(dbz/10.) wspd = getvar(ncfile, "wspd_wdir", units="kt")[0,:] # Set the start point and end point for the cross section start_point = CoordPair(lat=26.76, lon=-80.0) end_point = CoordPair(lat=26.76, lon=-77.8) # Compute the vertical cross-section interpolation. Also, include the # lat/lon points along the cross-section in the metadata by setting latlon # to True. z_cross = vertcross(Z, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) dbz_cross = 10.0 * np.log10(z_cross) # Get the lat/lon points lats, lons = latlon_coords(slp) # Get the cartopy projection object cart_proj = get_cartopy(slp) # Create a figure that will have 3 subplots fig = plt.figure(figsize=(12,9)) ax_ctt = fig.add_subplot(1,2,1,projection=cart_proj) ax_wspd = fig.add_subplot(2,2,2) ax_dbz = fig.add_subplot(2,2,4) # Download and create the states, land, and oceans using cartopy features states = cfeature.NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') land = cfeature.NaturalEarthFeature(category='physical', name='land', scale='50m', facecolor=cfeature.COLORS['land']) ocean = cfeature.NaturalEarthFeature(category='physical', name='ocean', scale='50m', facecolor=cfeature.COLORS['water']) # Make the pressure contours contour_levels = [960, 965, 970, 975, 980, 990] c1 = ax_ctt.contour(lons, lats, to_np(smooth_slp), levels=contour_levels, colors="white", transform=crs.PlateCarree(), zorder=3, linewidths=1.0) # Create the filled cloud top temperature contours contour_levels = [-80.0, -70.0, -60, -50, -40, -30, -20, -10, 0, 10] ctt_contours = ax_ctt.contourf(to_np(lons), to_np(lats), to_np(ctt), contour_levels, cmap=get_cmap("Greys"), transform=crs.PlateCarree(), zorder=2) ax_ctt.plot([start_point.lon, end_point.lon], [start_point.lat, end_point.lat], color="yellow", marker="o", ``` -------------------------------- ### Basemap Plot Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This example shows how to create a plot using the Basemap library. ```python from __future__ import (absolute_import, division, print_function, unicode_literals) from netCDF4 import Dataset import matplotlib.pyplot as plt from matplotlib.cm import get_cmap from mpl_toolkits.basemap import Basemap from wrf import to_np, getvar, smooth2d, get_basemap, latlon_coords # Open the NetCDF file ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") # Get the sea level pressure slp = getvar(ncfile, "slp") # Smooth the sea level pressure since it tends to be noisy near the mountains smooth_slp = smooth2d(slp, 3, cenweight=4) # Get the latitude and longitude points lats, lons = latlon_coords(slp) ``` -------------------------------- ### Cartopy Plot Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This example shows how to create a plot using the Cartopy library. ```python from __future__ import (absolute_import, division, print_function, unicode_literals) from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from wrf import getvar, interplevel, to_np, latlon_coords, get_cartopy, cartopy_xlim, cartopy_ylim # Open the NetCDF file ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") # Extract the pressure, geopotential height, and wind variables p = getvar(ncfile, "pressure") 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, 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 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), to_np(lats), to_np(ht_500), levels=levels, colors="black", transform=crs.PlateCarree()) plt.clabel(contours, inline=1, fontsize=10, fmt="%i") # Add the wind speed contours levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120] wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(wspd_500), levels=levels, cmap=get_cmap("rainbow"), transform=crs.PlateCarree()) plt.colorbar(wspd_contours, ax=ax, orientation="horizontal", pad=".05") # Add the 500 hPa wind barbs, only plotting every 125th data point. plt.barbs(to_np(lons[::125,::125]), to_np(lats[::125,::125]), to_np(u_500[::125, ::125]), to_np(v_500[::125, ::125]), transform=crs.PlateCarree(), length=6) # Set the map bounds ax.set_xlim(cartopy_xlim(ht_500)) ax.set_ylim(cartopy_ylim(ht_500)) ax.gridlines() plt.title("500 MB Height (dm), Wind Speed (kt), Barbs (kt)") plt.savefig("/Users/ladwig/Documents/workspace/wrf_python/doc/source/_static/images/cartopy_500.png", transparent=True, bbox_inches="tight") plt.show() ``` -------------------------------- ### PyNGL Example Using WRF Output Files Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst This example shows how to extract the basemap mapping object and geographic boundaries directly from a netcdf file. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import get_pyngl, geo_bounds ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the pyngl resources from the netcdf file pyngl_resources = get_pyngl(wrfin=ncfile) print (pyngl_resources) # Get the geographic boundaries from the netcdf file bounds = geo_bounds(wrfin=ncfile) print (bounds) ``` -------------------------------- ### setup.py Extension Configuration Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/internals.rst An example of how to update the numpy.distutils.core.Extension section in setup.py to include a new Fortran source file. ```python ext1 = numpy.distutils.core.Extension( name="wrf._wrffortran", sources=["fortran/wrf_constants.f90", "fortran/wrf_testfunc.f90", "fortran/wrf_user.f90", "fortran/rip_cape.f90", "fortran/wrf_cloud_fracf.f90", "fortran/wrf_fctt.f90", "fortran/wrf_user_dbz.f90", "fortran/wrf_relhl.f90", "fortran/calc_uh.f90", "fortran/wrf_user_latlon_routines.f90", "fortran/wrf_pvo.f90", "fortran/eqthecalc.f90", "fortran/wrf_rip_phys_routines.f90", "fortran/wrf_pw.f90", "fortran/wrf_vinterp.f90", "fortran/wrf_wind.f90", "fortran/omp.f90", "fortran/example.f90 # New file added here ] ) ``` -------------------------------- ### Creating Tutorial Conda Environment Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/boise_2018.rst Command to create a conda environment named 'tutorial_backup' with specified packages. ```bash conda create -n tutorial_backup python=3.6 matplotlib cartopy netcdf4 jupyter git ffmpeg wrf-python ``` -------------------------------- ### Example Usage with Dask Source: https://github.com/ncar/wrf-python/wiki/How-to-add-dask-support This snippet demonstrates how to open multiple WRF output files in parallel using dask and compute a variable. ```python ds = xarray.open_mfdataset("/path/to/wrf_vortex_multi/moving_nest/wrfout_d02*", parallel=True) tv = tv_getter(ds, omp_threads=2) # Now actually compute tv (note: result is a numpy array) # Let's use 4 workers with 2 OpenMP threads for a total of 8 CPUs tv_result = tv.compute(num_workers=4) ``` -------------------------------- ### Update Tutorial Repository Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/wrf_workshop_2018.rst Commands to activate the tutorial environment, navigate to the tutorial directory, and pull the latest changes for the repository on Linux/Mac and Windows. ```bash source activate tutorial_2018 cd ~/wrf_python_tutorial/wrf_workshop_2018 git pull ``` ```batch activate tutorial_2018 cd %HOMEPATH%\wrf_python_tutorial\wrf_workshop_2018 git pull ``` -------------------------------- ### Check if OpenMP is Enabled Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of checking if OpenMP is enabled in the wrf-python installation. ```python from __future__ import print_function from wrf import omp_enabled print(omp_enabled()) ``` -------------------------------- ### Loop and Fill Example Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/loop_and_fill.ipynb This code snippet shows how to loop through WRF output files, extract temperature data (T2), and populate a numpy array while preserving metadata using xarray. ```python from __future__ import print_function, division import os import numpy as np from netCDF4 import Dataset from wrf import getvar, ALL_TIMES, to_np import xarray path = '/scratch/mawagner/2015_GRELL3D/TESTFILES/TestTime' filename_list = os.listdir(path) filename_list.sort() #filename_list = ["/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_00:00:00", # "/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_03:00:00", # "/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_06:00:00", # "/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_09:00:00"] # Result shape result_shape = (6, 1, 290, 265) #result_shape = (4, 1, 96, 96) # Let's get the first time so we can copy the metadata later f = Dataset(filename_list[0]) # By setting squeeze to False, you'll get all the dimension names. z1 = getvar(f, "T2", 0, squeeze=False) xlat = getvar(f, "XLAT", 0) xlong = getvar(f, "XLONG", 0) z_final = np.empty(result_shape, np.float32) # Modify this number if using more than 1 time per file times_per_file = 1 #times_per_file = 4 data_times = [] xtimes = [] for timeidx in range(result_shape[0]): # Compute the file index and the time index inside the file fileidx = timeidx // times_per_file file_timeidx = timeidx % times_per_file f = Dataset(filename_list[fileidx]) z = getvar(f, "T2", file_timeidx) t = getvar(f, "Times", file_timeidx) xt = getvar(f, "xtimes", file_timeidx) data_times.append(to_np(t)) xtimes.append(to_np(xt)) z_final[timeidx,:] = z[:] f.close() # Let's make the metadata. Dimension names should copy easily if you set sqeeze to False, # otherwise you can just set them yourself is a tuple of dimension names. Since you wanted # to keep the bottom_top dimension for this 2D variable (which is normally removed), # I'm doing this manually. z_dims = ["Time", "bottom_top", "south_north", "west_east"] # Xarray doesn't copy coordinates easily (it always complains about shape mismatches), so do this # manually z_coords = {} z_coords["Time"] = data_times z_coords["XTIME"] = ("Time",), xtimes z_coords["XLAT"] = ("south_north", "west_east"), xlat z_coords["XLONG"] = ("south_north", "west_east"), xlong z_name = "T2" # Attributes copy nicely z_attrs = {} z_attrs.update(z1.attrs) z_with_meta = xarray.DataArray(z_final, coords=z_coords, dims=z_dims, attrs=z_attrs, name=z_name) print(z_with_meta) ``` -------------------------------- ### Geo Bounds Plot Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This example shows how to get the geographic bounds of a WRF variable. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import getvar, get_cartopy, latlon_coords, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") slp = getvar(ncfile, "slp") # Get the cartopy mapping object cart_proj = get_cartopy(slp) print (cart_proj) # Get the latitude and longitude coordinate. This is needed for plotting. lats, lons = latlon_coords(slp) # Get the geobounds for the full domain bounds = geo_bounds(slp) print (bounds) # Get the geographic boundaries for a subset of the domain slp_subset = slp[150:250, 150:250] slp_subset_bounds = geo_bounds(slp_subset) print (slp_subset_bounds) ``` -------------------------------- ### Geo Bounds Plot (wrfin) Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This example shows how to get the geographic bounds of a WRF variable using the wrfin argument. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import get_cartopy, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") cart_proj = get_cartopy(wrfin=ncfile) print (cart_proj) bounds = geo_bounds(wrfin=ncfile) print (bounds) ``` -------------------------------- ### Create tutorial conda environment Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/wrf_workshop_2017.rst Command to create the conda environment for the tutorial, including specified packages. ```bash conda create -n tutorial_2017 python=2.7 matplotlib=1.5.3 cartopy netcdf4 jupyter git ffmpeg wrf-python ``` -------------------------------- ### Example PATH export line Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/wrf_workshop_2017.rst An example of how a PATH export line might look in .bash_profile or .bashrc, which can be commented out to undo Miniconda installation. ```bash # added by Miniconda2 4.1.11 installer export PATH="/path/to/miniconda2/bin:$PATH" ``` -------------------------------- ### Panel Plots from the Front Page Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/plot.rst This example demonstrates how to create panel plots, similar to those on the front page of the documentation, by combining different types of WRF data visualizations. ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap from netCDF4 import Dataset from wrf import ( getvar, to_np, vertcross, smooth2d, CoordPair, get_basemap, latlon_coords) # Open the NetCDF file ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the WRF variables slp = getvar(ncfile, "slp") smooth_slp = smooth2d(slp, 3) ctt = getvar(ncfile, "ctt") z = getvar(ncfile, "z") dbz = getvar(ncfile, "dbz") Z = 10**(dbz/10.) wspd = getvar(ncfile, "wspd_wdir", units="kt")[0,:] # Set the start point and end point for the cross section start_point = CoordPair(lat=26.76, lon=-80.0) end_point = CoordPair(lat=26.76, lon=-77.8) # Compute the vertical cross-section interpolation. Also, include the # lat/lon points along the cross-section in the metadata by setting latlon # to True. z_cross = vertcross(Z, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) dbz_cross = 10.0 * np.log10(z_cross) # Get the latitude and longitude points lats, lons = latlon_coords(slp) # Create the figure that will have 3 subplots fig = plt.figure(figsize=(12,9)) ax_ctt = fig.add_subplot(1,2,1) ax_wspd = fig.add_subplot(2,2,2) ax_dbz = fig.add_subplot(2,2,4) # Get the basemap object bm = get_basemap(slp) # Convert the lat/lon points in to x/y points in the projection space x, y = bm(to_np(lons), to_np(lats)) # Make the pressure contours contour_levels = [960, 965, 970, 975, 980, 990] c1 = bm.contour(x, y, to_np(smooth_slp), levels=contour_levels, colors="white", zorder=3, linewidths=1.0, ax=ax_ctt) # Create the filled cloud top temperature contours contour_levels = [-80.0, -70.0, -60, -50, -40, -30, -20, -10, 0, 10] ctt_contours = bm.contourf(x, y, to_np(ctt), contour_levels, cmap=get_cmap("Greys"), zorder=2, ax=ax_ctt) point_x, point_y = bm([start_point.lon, end_point.lon], [start_point.lat, end_point.lat]) bm.plot([point_x[0], point_x[1]], [point_y[0], point_y[1]], color="yellow", marker="o", zorder=3, ax=ax_ctt) # Create the color bar for cloud top temperature cb_ctt = fig.colorbar(ctt_contours, ax=ax_ctt, shrink=".60") cb_ctt.ax.tick_params(labelsize=5) # Draw the oceans, land, and states ``` -------------------------------- ### Get PyNGL Resources and Geo Bounds from WRF Input Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb Example of retrieving PyNGL resources and geographic boundaries directly from a WRF input file. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import get_pyngl, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") pyngl_resources = get_pyngl(wrfin=ncfile) print (pyngl_resources) bounds = geo_bounds(wrfin=ncfile) print (bounds) ``` -------------------------------- ### Get the sea level pressure Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This code snippet shows how to retrieve sea level pressure (SLP) from a NetCDF file and get the map projection resources using PyNGL. ```python # SLP from __future__ import (absolute_import, division, print_function, unicode_literals) import Ngl import Nio import numpy as np from wrf import to_np, getvar, smooth2d, get_pyngl, latlon_coords ncfile = Nio.open_file(b"/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00.nc") # Get the sea level pressure ctt = getvar(ncfile, "ctt") wks = Ngl.open_wks(b"png", b"test") # Get the map projection resources = get_pyngl(ctt) ``` -------------------------------- ### Example With Multiple Coordinates Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst Demonstrates converting multiple XY coordinate pairs to latitude/longitude and vice versa. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import getvar, interpline, CoordPair, xy_to_ll, ll_to_xy ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") lat_lon = xy_to_ll(ncfile, [400,105], [200,205]) print(lat_lon) x_y = ll_to_xy(ncfile, lat_lon[0,:], lat_lon[1,:]) print (x_y) ``` -------------------------------- ### Optional dbus Setup Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/tutorials/wrf_workshop_2019.rst Optional commands to set up dbus to automatically load on login. ```bash mkdir -p ~/Library/LaunchAgents cp /path/to/miniconda3/envs/tutorial_test/org.freedesktop.dbus-session.plist ~/Library/LaunchAgents/ launchctl load -w ~/Library/LaunchAgents/org.freedesktop.dbus-session.plist ``` -------------------------------- ### Plotting with Cartopy - Setup Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/WRF_python_demo.ipynb Initializes matplotlib for inline plotting and imports necessary libraries for Cartopy plotting. ```python %matplotlib inline ``` -------------------------------- ### Vertical Cross Section Example Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/plot.rst This code snippet shows how to compute and plot a vertical cross-section of wind speed. It includes extracting data, defining start and end points for the cross-section, computing the cross-section, and then plotting it with appropriate labels and color bars. ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from netCDF4 import Dataset from wrf import to_np, getvar, CoordPair, vertcross # Open the NetCDF file filename = "wrfout_d01_2016-10-07_00_00_00" ncfile = Dataset(filename) # Extract the model height and wind speed z = getvar(ncfile, "z") wspd = getvar(ncfile, "uvmet_wspd_wdir", units="kt")[0,:] # Create the start point and end point for the cross section start_point = CoordPair(lat=26.76, lon=-80.0) end_point = CoordPair(lat=26.76, lon=-77.8) # Compute the vertical cross-section interpolation. Also, include the # lat/lon points along the cross-section. wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) # Create the figure fig = plt.figure(figsize=(12,6)) ax = plt.axes() # Make the contour plot wspd_contours = ax.contourf(to_np(wspd_cross), cmap=get_cmap("jet")) # Add the color bar plt.colorbar(wspd_contours, ax=ax) # Set the x-ticks to use latitude and longitude labels. coord_pairs = to_np(wspd_cross.coords["xy_loc"]) x_ticks = np.arange(coord_pairs.shape[0]) x_labels = [pair.latlon_str(fmt="{:.2f}, {:.2f}") for pair in to_np(coord_pairs)] ax.set_xticks(x_ticks[::20]) ax.set_xticklabels(x_labels[::20], rotation=45, fontsize=8) # Set the y-ticks to be height. vert_vals = to_np(wspd_cross.coords["vertical"]) v_ticks = np.arange(vert_vals.shape[0]) ax.set_yticks(v_ticks[::20]) ax.set_yticklabels(vert_vals[::20], fontsize=8) # Set the x-axis and y-axis labels ``` -------------------------------- ### Get the cartesian projection Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This code snippet demonstrates how to obtain the cartesian projection and geographic boundaries from a NetCDF file using wrf-python. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import get_basemap, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") cart_proj = get_basemap(wrfin=ncfile) print (cart_proj) bounds = geo_bounds(wrfin=ncfile) print (bounds) ``` -------------------------------- ### Example Using Start Point and End Point Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst This code snippet demonstrates how to create a vertical cross section using a start and end point in grid coordinates. It retrieves geopotential height and pressure, defines the start and end points, and then calculates the vertical cross section. The `latlon=True` argument is used to also calculate and add latitude and longitude coordinates to the metadata for plotting purposes. ```python from __future__ import print_function, division from netCDF4 import Dataset from wrf import getvar, vertcross, CoordPair ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the geopotential height (m) and pressure (hPa). z = getvar(ncfile, "z") p = getvar(ncfile, "pressure") # Define a start point and end point in grid coordinates start_point = CoordPair(x=0, y=(z.shape[-2]-1)//2) end_point = CoordPair(x=-1, y=(z.shape[-2]-1)//2) # Calculate the vertical cross section. By setting latlon to True, this # also calculates the latitude and longitude coordinates along the cross # section line and adds them to the 'xy_loc' metadata to help with plotting. p_vert = vertcross(p, z, start_point=start_point, end_point=end_point, latlon=True) print(p_vert) ``` -------------------------------- ### Example Using Pivot Point and Angle Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst Demonstrates how to use `interpline` with a pivot point and angle to create a vertical cross-section. ```python from __future__ import print_function, division from netCDF4 import Dataset from wrf import getvar, interpline, CoordPair ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the 2m temperature t2 = getvar(ncfile, "T2") # Create a south-north line using pivot point and angle pivot_point = CoordPair((t2.shape[-1]-1)//2, (t2.shape[-2]-1)//2) angle = 0.0 # Calculate the vertical cross section. By setting latlon to True, this # also calculates the latitude and longitude coordinates along the line # and adds them to the metadata to help with plotting labels. t2_line = interpline(t2, pivot_point=pivot_point, angle=angle, latlon=True) print(t2_line, "\n") ``` -------------------------------- ### Navigate to WRF-Python Directory Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/contrib.rst Navigates to the cloned WRF-Python directory. ```bash cd wrf-python ``` -------------------------------- ### Example Using Start Point and End Point Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/basic_usage.rst This code snippet demonstrates how to interpolate a two-dimensional field (2m temperature in this case) along a line defined by a start and end point. It retrieves the 2m temperature, defines the start and end points for the line using grid coordinates, and then uses the `interpline` function to perform the interpolation. Setting `latlon=True` also calculates and adds latitude and longitude coordinates along the line. ```python from __future__ import print_function, division from netCDF4 import Dataset from wrf import getvar, interpline, CoordPair ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00") # Get the 2m temperature t2 = getvar(ncfile, "T2") # Create a south-north line in the center of the domain using # start point and end point start_point = CoordPair(x=(t2.shape[-1]-1)//2, y=0) end_point = CoordPair(x=(t2.shape[-1]-1)//2, y=-1) # Calculate the vertical cross section. By setting latlon to True, this # also calculates the latitude and longitude coordinates along the line # and adds them to the metadata to help with plotting labels. t2_line = interpline(t2, start_point=start_point, end_point=end_point, latlon=True) print(t2_line, "\n") ``` -------------------------------- ### Basic Variable Extraction Setup Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/WRF_python_demo.ipynb Imports necessary libraries and opens a NetCDF file for WRF data. ```python from __future__ import (absolute_import, division, print_function, unicode_literals) from wrf import getvar from netCDF4 import Dataset as nc #ncfile = nc("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-02-25_18_00_00") ncfile = nc("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") ``` -------------------------------- ### Get the basemap mapping object Source: https://github.com/ncar/wrf-python/blob/develop/test/ipynb/Doc_Examples.ipynb This code snippet shows how to retrieve the basemap mapping object, latitude and longitude coordinates, and geographic boundaries for the full domain and a subset of the domain. ```python from __future__ import print_function from netCDF4 import Dataset from wrf import getvar, get_basemap, latlon_coords, geo_bounds ncfile = Dataset("/Users/ladwig/Documents/wrf_files/wrfout_d01_2016-10-07_00_00_00") slp = getvar(ncfile, "slp") # Get the basemap mapping object basemap_proj = get_basemap(slp) print (basemap_proj) # Get the latitude and longitude coordinate. This is needed for plotting. lats, lons = latlon_coords(slp) # Get the geobounds for the full domain bounds = geo_bounds(slp) print(bounds) # Get the geographic boundaries for a subset of the domain slp_subset = slp[150:250, 150:250] slp_subset_bounds = geo_bounds(slp_subset) print (slp_subset_bounds) ``` -------------------------------- ### Horizontal Interpolation to a Pressure Level Source: https://github.com/ncar/wrf-python/blob/develop/doc/source/plot.rst This code snippet is a starting point for interpolating a variable to a specific pressure level. It shows how to open a NetCDF file and use the `getvar` and `interplevel` functions from wrf-python. ```python from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap from wrf import getvar, interplevel, to_np, get_basemap, latlon_coords # Open the NetCDF file ```