wrf-python

repository·develop·Indexed 19 days ago

https://github.com/ncar/wrf-python

A Python library providing diagnostic and interpolation routines specifically for Weather Research and Forecasting (WRF-ARW) model output. It offers over 30 diagnostic calculations, several interpolation routines, and utilities to assist with plotting using cartopy, basemap, or PyNGL, providing functionality similar to the NCL WRF package.

Tokens
27.1K
Snippets
80
Records
128
Agent score
67%

What's inside wrf-python

  1. What is WRF-Python?

    develop

    WRF-Python is a collection of diagnostic and interpolation routines designed for use with output from the Weather Research and Forecasting (WRF-ARW) Model. It provides over 30 diagnostic calculations, several interpolation routines, and utilities to assist with plotting via cartopy, basemap, or PyNGL. Its functionality is intended to be similar to the NCL WRF package.

    Important Note: WRF-Python is NOT a tool for running the WRF-ARW model using Python; it is for analyzing and visualizing model output.

  2. Overview of wrf-python functionality

    develop

    wrf-python is a collection of diagnostic and interpolation routines designed for use with output from the Weather Research and Forecasting (WRF-ARW) Model.

    Key features include:

    • Over 30 diagnostic calculations.
    • Several interpolation routines.
    • Utilities to assist with plotting using cartopy, basemap, or PyNGL.

    The functionality is intended to be similar to the NCL WRF package.

  3. Plotting with wrf-python using Matplotlib and PyNGL

    develop

    To create visualizations from WRF data, wrf-python is designed to work with matplotlib (using either basemap or cartopy) and PyNGL.

    Note: These examples do not use xarray's built-in plotting functions, as xarray requires additional extension work to work correctly with WRF data structures. This support is planned for a future release.

  4. How WRF-Python wraps Fortran routines with decorators

    develop

    WRF-Python uses a layered decorator pattern to bridge the gap between high-level Python/xarray objects and low-level Fortran routines. When a diagnostic is called, the decorators are executed from top to bottom (outermost to innermost) to prepare data, and then from bottom to top to clean up the result.

    A typical decorator chain for a compiled routine includes:

    1. check_args: Verifies input array shapes to provide clear error messages.
    2. left_iteration: Handles multidimensional arrays by iterating over 'leftmost' dimensions and passing slices to the Fortran routine.
    3. cast_type: Converts input arrays to the precision required by Fortran (e.g., REAL(KIND=8)) and casts the result back to the original type.
    4. extract_and_transpose: Converts xarray.DataArray or C-ordered numpy.ndarray into Fortran-ordered arrays and handles the final transposition back to C-order for the user.
  5. Use raw diagnostic routines for non-WRF data

    develop

    If you are working with variables that are not contained in a WRF-ARW NetCDF file, or with non-WRF data, you can use the raw diagnostic routines.

    Warning: Most of these routines do not allow for missing values in any of the input arrays; ensure missing values are removed before calling them. While designed for WRF-ARW, their behavior with non-WRF data may vary.

    import wrf
    # Examples of raw routines:
    # wrf.slp(p, t)
    # wrf.tk(t)
    # wrf.td(t)
    # wrf.rh(t, q)
    # wrf.uvmet(u, v, ...)
    # wrf.cape_2d(...)
    # wrf.cloudfrac(...)
    # wrf.dbz(...)
  6. Important considerations when using Cartopy with WRF data

    develop

    While Cartopy is the standard for base mapping with Matplotlib, there are two specific behaviors to manage when working with WRF data:

    1. Rotated Pole Projection: The built-in coordinate transformations in Matplotlib's contouring functions do not work correctly with the rotated pole projection. You must manually call the transform_points method on your latitude and longitude arrays.
    2. Axis Limits: The rotated pole projection requires you to set the x and y limits manually using set_xlim and set_ylim (it is recommended to use wrf.cartopy_xlim and wrf.cartopy_ylim for this).
  7. Manage memory usage and xarray caching in wrf.getvar

    develop

    When xarray is enabled, wrf.getvar uses an internal thread-local cache to store XLAT and XLONG coordinate variables and moving nest metadata. This prevents repeated extraction when processing sequences of WRF files.

    By default, the cache holds up to 20 items, keyed by the object ID of the file or sequence. If you are creating new file objects in a loop (e.g., using netCDF4.Dataset), the cache will fill up, leading to higher memory usage until it reaches the limit. This is not a memory leak; memory usage will eventually stabilize.

    You can manage this behavior using:

    • wrf.disable_xarray(): Disables xarray functionality entirely.
    • wrf.set_cache_size(size): Adjusts the number of items held in the cache. Setting the size to 0 disables the cache completely.
    from netCDF4 import Dataset
    import wrf
    
    # To disable xarray functionality and reduce memory overhead:
    wrf.disable_xarray()
    
    for i in range(150):
        f = Dataset('wrfout_d01_2005-07-17_12_00_00.nc')
        p = wrf.getvar(f, 'pressure')
        f.close()
  8. Understanding compiled computational routines

    develop

    WRF-Python utilizes compiled Fortran 90 routines for high-performance computations. These are exposed to Python via f2py.

    The Extension Layer

    Raw Fortran routines are compiled into the wrf._wrffortran extension module. However, users should not interact with wrf._wrffortran directly. Instead, these routines are wrapped in the extension.py module to provide a user-friendly interface.

    How the wrapper handles data

    When you call a routine exported via extension.py, the following logic is applied to ensure compatibility and performance:

    1. Argument Validation: The wrapper verifies argument shapes to provide clearer error messages than standard f2py errors.
    2. Output Allocation: It allocates an output array based on the algorithm's requirements and the input data dimensions.
    3. Dimension Iteration: It iterates over the "leftmost" dimensions. For example, if a 2D Fortran algorithm receives a 5D array, the wrapper iterates over the 3 leftmost dimensions to process slices.
    4. Type Casting: It casts input arrays to the required dtype (typically converting 4-byte floats to 8-byte doubles for WRF data).
    5. Memory Efficiency: It extracts arrays from xarray into numpy arrays and transposes them into Fortran ordering. This reorders the shape tuple and sets the Fortran ordering flag without copying data, allowing the Fortran routine to work directly on the data pointers.
  9. Compute vertical cross-sections with vertcross()

    develop

    The vertcross function computes a vertical cross-section interpolation between two points.

    Key Parameters:

    • variable: The 3D field to interpolate.
    • vertical_coord: The vertical coordinate field (e.g., geopotential height z).
    • wrfin: The original NetCDF file object.
    • start_point: A CoordPair object defining the starting latitude and longitude.
    • end_point: A CoordPair object defining the ending latitude and longitude.
    • latlon=True: If set, includes latitude/longitude points in the metadata.
    • meta=True: If set, includes metadata in the returned object.

    Usage Pattern:

    1. Define points using CoordPair(lat=..., lon=...).
    2. Call vertcross for each variable of interest.
    3. Use the resulting object's coordinates (e.g., coords['xy_loc'] or coords['vertical']) to set axis ticks for plotting.
    from wrf import vertcross, CoordPair
    
    # 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
    z_cross = vertcross(Z, z, wrfin=ncfile, start_point=start_point, 
                        end_point=end_point, latlon=True, meta=True)
  10. Prerequisites for using WRF-Python

    develop

    To effectively use WRF-Python, users should have the following background:

    Python Proficiency

    Users should be comfortable with Python programming, including:

    • Using the Python interpreter and import statements.
    • Basic types: str, list, tuple, dict, bool, float, int, None.
    • Data structure syntax: [ ] for lists, ( ) for tuples, { } for dicts.
    • Accessing items via x[ ] syntax and slicing via : syntax.
    • Using object methods and attributes via x.y syntax.
    • Calling functions.
    • Familiarity with numpy and matplotlib is highly recommended.

    Terminal Skills

    Basic command-line proficiency is required, specifically directory navigation and manipulation commands such as:

    • cd (change directory)
    • mkdir (make directory)
    • cp (copy)
    • mv (move)
  11. How wrf.getvar diagnostic computations work

    develop

    When you call wrf.getvar, the library performs a multi-step process to transform raw NetCDF data into a usable diagnostic:

    1. Getter Selection: The routine identifies and calls the appropriate 'getter' function based on your specified diagnostic label (these functions are prefixed with g_ in the source, e.g., g_something).
    2. Data Extraction: It extracts the necessary raw variables from the NetCDF files.
    3. Computation: It executes the diagnostic using a wrapped routine (written in Fortran, C, or Python).
    4. Unit Conversion: It converts the result to the requested units (handled via a wrapt decorator in decorators.py).
    5. Metadata & Return: It attaches metadata and returns the result. The return type is an xarray.DataArray if metadata is requested, or a numpy.ndarray if no metadata is required.
  12. Coordinate name handling with xarray

    develop
    In version 1.3.2, wrf-python updated its logic to search for coordinate name index positions rather than assuming them. This change ensures compatibility with users who use xarray to rewrite WRF output files, as xarray may reorder coordinate name positions.