MetPy Documentation

repository·main·Indexed 23 days ago

https://github.com/unidata/metpy

A Python library for meteorological data analysis, providing tools for reading, calculating, and visualizing weather data. It integrates with the scientific Python stack, including numpy, scipy, matplotlib, pandas, pint, and xarray. The library includes the metpy.calc module for dry and moist thermodynamics, sounding and stability indices, dynamic and kinematic calculations, and boundary layer turbulence, as well as plotting utilities via metpy.plots.ctables and xarray integration through custom accessors.

Tokens
35.9K
Snippets
19
Records
195
Agent score
81%

What's inside MetPy

  1. Overview of MetPy

    main

    MetPy is a collection of Python tools designed for reading, visualizing, and performing calculations with weather data. It is designed to integrate seamlessly with the scientific Python ecosystem, specifically numpy, scipy, and matplotlib.

    MetPy follows semantic versioning, meaning 1.x releases are backwards compatible with previous 1.y releases. It supports Python version 3.11 and above.

  2. MetPy's core goals and philosophy

    main

    MetPy aims to provide domain-specific tools for building meteorological and atmospheric science applications in Python. Its primary objectives include:

    • Supporting scripted workflows: Replicating the capabilities of legacy tools like GEMPAK and NCL.
    • Calculation Core: Serving as the computational engine for graphical applications, not just for static views.
    • Upstream Integration: Moving general-purpose functionality to established libraries like matplotlib and xarray whenever possible to maintain a focused, domain-specific toolset.
  3. Explore the MetPy API Reference

    main

    The MetPy API is organized into several functional modules. You can access core functionality through the following submodules:

    • constants: Physical constants used in meteorological calculations.
    • units: Tools for handling quantities with physical units (integration with Pint).
    • io: Input/Output utilities for reading and writing meteorological data.
    • remote: Tools for accessing data from remote sources.
    • calc: A collection of meteorological calculation routines.
    • plots: Functions for creating meteorological plots.
    • plots.ctables: Color table definitions for plotting.
    • interpolate: Interpolation routines for meteorological data.
    • xarray: Integration and utilities for working with xarray datasets.
  4. Use MetPy accessors with Xarray objects

    main

    MetPy provides integration with xarray through custom accessors. Once MetPy is installed and your Xarray objects are loaded, you can access MetPy-specific functionality directly on DataArray and Dataset objects using the .metpy attribute.

    • MetPyDataArrayAccessor: Provides meteorological calculations and utilities specifically for xarray.DataArray objects.
    • MetPyDatasetAccessor: Provides meteorological calculations and utilities specifically for xarray.Dataset objects.

    These accessors allow you to perform complex meteorological operations while preserving the metadata and coordinate structures inherent to Xarray.

  5. Understand MetPy versioning and compatibility

    main

    MetPy follows semantic versioning. For the 1.x release series, any 1.x release is guaranteed to be backwards compatible with an earlier 1.y release.

    Backward compatibility definition: Correct code that works on a 1.y version will work on a future 1.x version. Note that bug fixes may change behavior or cause previously incorrect code to stop working.

    Version numbering convention:

    • 1.x.y where x is incremented for new features.
    • 1.x.y where y is incremented for bug fixes only.
    • Backwards-incompatible changes are reserved for major version updates (e.g., moving to 2.0).

    When breaking changes are planned for the 1.x series, they will be preceded by MetpyDeprecationWarning or FutureWarning to allow users to migrate.

  6. Xarray support for function input/output in MetPy 1.0

    main
    In MetPy 1.0, many functions in the metpy.calc module have been updated to support xarray.DataArray for both inputs and outputs. Previously, these functions often returned pint.Quantity objects even when an xarray.DataArray was provided as input. Now, MetPy will attempt to return an xarray.DataArray when provided one, preserving xarray metadata and structure where possible. For detailed usage, refer to the MetPy xarray tutorial.
  7. Declarative Plotting in MetPy

    main

    MetPy is developing a simplified, declarative plotting interface inspired by the simplicity of GEMPAK. Instead of complex matplotlib configurations, the goal is to allow users to create meteorological plots by setting variables.

    Planned and existing support includes:

    • Plot Types: Image plots, contour plots, vector plots, streamlines, filled contours, Polar Radar Data, cross-sections, and Skew-T diagrams.
    • Decorations: Logos, timestamps, colorbars, contour labeling, and figure titles.

    Note: This interface is intended for common meteorological use cases and does not aim to replicate the full feature set of matplotlib.

  8. Understand the MetPy Contributor License Agreement (CLA) requirements

    main

    The MetPy CLA is a license agreement, not a copyright assignment. Key points for contributors include:

    • Copyright Ownership: You retain full copyright for your contributions. You are only granting MetPy a license to distribute your code without further restrictions.
    • Irrevocability: Once a contribution is made, you cannot withdraw permission for its use at a later date. This ensures stability for the community of users.
    • License Flexibility: The CLA allows the MetPy project to change its distribution license in the future, provided the new license is approved by the Open Source Initiative (OSI).
    • Corporate Contributions: If your work is created as part of your employment, your employer may need to sign a corporate version of the CLA. You should still sign an individual CLA, but ensure you have the legal right to license the specific code you are submitting.
  9. Xarray integration and unit handling

    main

    MetPy relies on xarray for gridded data models and pint for robust unit handling. A key architectural goal is to move toward native xarray support to enable coordinate-aware calculations (e.g., vorticity, isentropic interpolation).

    Key Integration Patterns:

    • Native Xarray: Calculations are moving toward using xarray natively, pulling unit information from metadata.
    • Hybrid Input: MetPy continues to accept numpy arrays with pint units but converts them to xarray internally.
    • Coordinate Awareness: By using xarray as the primary interface, calculations can leverage coordinate information directly from the dataset.
  10. Use the MetPy Xarray accessor

    main

    MetPy extends xarray via an accessor that allows you to quickly parse Climate and Forecasting (CF) metadata, handle projections, and extract unit-aware arrays from multi-dimensional datasets.

    Key capabilities include:

    • ds.metpy.parse_cf(): Parses CF metadata.
    • ds.variable.metpy.unit_array: Returns dimensions (like lat/lon) as unit-aware arrays.
    • ds.variable.metpy.time: Accesses time information.
    • ds.variable.metpy.sel(...): Allows selecting data using unit-aware coordinates (e.g., selecting a specific pressure level).
    import xarray as xr
    import metpy
    from metpy.cbook import get_test_data
    from metpy.units import units
    
    ds = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj = False))
    ds = ds.metpy.parse_cf()
    
    # Grab lat/lon values from file as unit arrays
    lats = ds.lat.metpy.unit_array
    lons = ds.lon.metpy.unit_array
    
    # Get the valid time
    vtime = ds.Temperature_isobaric.metpy.time[0]
    
    # Get the 700-hPa heights without manually identifying the vertical coordinate
    hght_700 = ds.Geopotential_height_isobaric.metpy.sel(vertical=700 * units.hPa,
                                                     time=vtime)
  11. How MetPy performance benchmarking works

    main
    MetPy uses asv (airspeed velocity) to manage performance benchmarking. It builds environments based on historical and current software iterations, runs benchmark functions, and compiles results into HTML pages. This process is integrated into the CI/CD workflow via GitHub Actions and Jenkins to identify bottlenecks and track performance changes in pull requests.