Comprehensive Python library for meteorological data analysis and weather visualization.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
MetPy provides robust I/O support for major meteorological file formats including GEMPAK surface/sounding/grid data, NEXRAD radar data, GINI satellite imagery, and METAR observations. All readers provide automatic format detection, metadata preservation, and seamless integration with the scientific Python ecosystem.
Complete support for GEMPAK surface, upper-air, and grid data formats used widely in meteorological operations and research.
class GempakSurface:
"""
Read GEMPAK surface data files.
Provides access to surface meteorological observations stored in GEMPAK format
including station metadata, parameter definitions, and observation data.
"""
def __init__(self, file):
"""
Initialize GEMPAK surface data reader.
Parameters:
- file: path to GEMPAK surface file
"""
@property
def parameters(self):
"""Available parameters in the file."""
@property
def stations(self):
"""Station information and metadata."""
def gdxarray(self, parameter=None, station_id=None, date_time=None):
"""
Read data as xarray Dataset.
Parameters:
- parameter: parameter name to read
- station_id: specific station ID
- date_time: specific date/time
Returns:
xarray Dataset with observation data
"""
class GempakSounding:
"""
Read GEMPAK upper-air sounding data files.
Provides access to atmospheric profile data including mandatory and significant
levels, with support for multiple sounding types and station locations.
"""
def __init__(self, file):
"""
Initialize GEMPAK sounding data reader.
Parameters:
- file: path to GEMPAK sounding file
"""
@property
def parameters(self):
"""Available parameters in sounding data."""
@property
def stations(self):
"""Sounding station information."""
def gdxarray(self, station_id=None, date_time=None):
"""
Read sounding data as xarray Dataset.
Parameters:
- station_id: specific station ID
- date_time: specific date/time
Returns:
xarray Dataset with sounding profile data
"""
class GempakGrid:
"""
Read GEMPAK gridded data files.
Provides access to gridded meteorological analysis and forecast data
with full coordinate system and metadata support.
"""
def __init__(self, file):
"""
Initialize GEMPAK grid data reader.
Parameters:
- file: path to GEMPAK grid file
"""
@property
def parameters(self):
"""Available grid parameters."""
@property
def grid_info(self):
"""Grid coordinate system information."""
def gdxarray(self, parameter=None, date_time=None, level=None):
"""
Read grid data as xarray DataArray.
Parameters:
- parameter: parameter name to read
- date_time: specific date/time
- level: specific vertical level
Returns:
xarray DataArray with gridded data and coordinates
"""Support for NEXRAD Level 2 (base data) and Level 3 (derived products) radar data formats.
class Level2File:
"""
Read NEXRAD Level 2 radar data files.
Provides access to base radar moments including reflectivity, velocity,
and spectrum width with full sweep and radial structure preservation.
"""
def __init__(self, file):
"""
Initialize Level 2 radar file reader.
Parameters:
- file: path to Level 2 radar file
"""
@property
def sweeps(self):
"""Available radar sweeps and their parameters."""
@property
def site_info(self):
"""Radar site location and configuration."""
def get_data(self, moment, sweep=0):
"""
Get radar moment data for specific sweep.
Parameters:
- moment: radar moment ('REF', 'VEL', 'SW', etc.)
- sweep: sweep number
Returns:
Radar data array with range/azimuth coordinates
"""
class Level3File:
"""
Read NEXRAD Level 3 radar product files.
Provides access to derived radar products including composite reflectivity,
precipitation estimates, and storm-relative products.
"""
def __init__(self, file):
"""
Initialize Level 3 radar file reader.
Parameters:
- file: path to Level 3 product file
"""
@property
def product_info(self):
"""Product metadata and specifications."""
@property
def site_info(self):
"""Radar site information."""
def get_data(self):
"""
Get product data.
Returns:
Product data array with appropriate coordinates
"""Support for GINI (GOES Ingest and NOAAPORT Interface) satellite data format.
class GiniFile:
"""
Read GINI satellite data files.
Provides access to GOES satellite imagery and derived products with
full coordinate system and calibration information.
"""
def __init__(self, file):
"""
Initialize GINI file reader.
Parameters:
- file: path to GINI file
"""
@property
def metadata(self):
"""Satellite and product metadata."""
@property
def proj_info(self):
"""Map projection information."""
def get_data(self):
"""
Get satellite data.
Returns:
Satellite data array with geographic coordinates
"""Parsing and processing of METAR (Meteorological Aerodrome Report) surface observations.
def parse_metar_file(filename, year=None, month=None):
"""
Parse a file containing METAR observations.
Parameters:
- filename: path to METAR file
- year: year for date parsing (if not in METAR)
- month: month for date parsing (if not in METAR)
Returns:
List of parsed METAR observation dictionaries
"""
def parse_metar_to_dataframe(filename, year=None, month=None):
"""
Parse METAR file and return as pandas DataFrame.
Parameters:
- filename: path to METAR file
- year: year for date parsing
- month: month for date parsing
Returns:
pandas DataFrame with METAR observations and metadata
"""from metpy.io import GempakSurface
# Open GEMPAK surface file
sf = GempakSurface('surface_data.gem')
# Examine available parameters and stations
print("Parameters:", sf.parameters)
print("Stations:", sf.stations[:5]) # First 5 stations
# Read specific parameter as xarray Dataset
temp_data = sf.gdxarray(parameter='TMPF')
print(temp_data)
# Read data for specific station and time
denver_data = sf.gdxarray(station_id='KDEN', date_time='2023-01-15/12:00')
print(denver_data)from metpy.io import Level2File
import matplotlib.pyplot as plt
# Open Level 2 radar file
radar = Level2File('KFTG20230115_120000_V06')
# Get radar site information
print("Site:", radar.site_info)
print("Available sweeps:", radar.sweeps)
# Read reflectivity data for first sweep
ref_data = radar.get_data('REF', sweep=0)
print("Reflectivity shape:", ref_data.shape)
# Basic radar plot
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.pcolormesh(ref_data.azimuth, ref_data.range, ref_data)
ax.set_title('Radar Reflectivity')
plt.show()from metpy.io import parse_metar_to_dataframe
import pandas as pd
# Parse METAR file to DataFrame
df = parse_metar_to_dataframe('metar_data.txt', year=2023, month=1)
# Examine the data structure
print(df.columns)
print(df.head())
# Filter and analyze
denver_obs = df[df['station_id'] == 'KDEN']
print(f"Denver observations: {len(denver_obs)}")
# Basic statistics
print("Temperature statistics:")
print(denver_obs['air_temperature'].describe())from metpy.io import GiniFile
import matplotlib.pyplot as plt
# Open GINI satellite file
gini = GiniFile('goes_visible.gini')
# Get metadata and projection information
print("Metadata:", gini.metadata)
print("Projection:", gini.proj_info)
# Read satellite data
sat_data = gini.get_data()
print("Data shape:", sat_data.shape)
# Display satellite image
plt.figure(figsize=(10, 8))
plt.imshow(sat_data, origin='upper', cmap='gray')
plt.title('GOES Visible Imagery')
plt.colorbar(label='Digital Counts')
plt.show()from metpy.io import GempakGrid
import metpy.calc as mpcalc
# Open GEMPAK grid file
grid = GempakGrid('nam_analysis.gem')
# Check available parameters
print("Available parameters:", grid.parameters)
# Read 500 hPa geopotential height
hght_500 = grid.gdxarray(parameter='HGHT', level=500)
print(hght_500)
# Read temperature and calculate potential temperature
temp_500 = grid.gdxarray(parameter='TMPK', level=500)
theta = mpcalc.potential_temperature(500 * units.hPa, temp_500)
print("Potential temperature calculated")All MetPy I/O classes provide native xarray output with proper coordinate systems and metadata.
# GEMPAK data as xarray Dataset
sf = GempakSurface('surface.gem')
ds = sf.gdxarray()
# Automatic coordinate parsing with MetPy
ds = ds.metpy.parse_cf()
print("CRS:", ds.metpy.crs)
# Access coordinates by type
print("Time coordinate:", ds.metpy.time)
print("Spatial coordinates:", ds.metpy.x, ds.metpy.y)Data readers automatically apply appropriate units to meteorological variables.
# Temperature data with units
temp_data = sf.gdxarray(parameter='TMPF')
print("Temperature units:", temp_data.metpy.units)
# Unit conversion
temp_celsius = temp_data.metpy.convert_units('celsius')
print("Converted to Celsius:", temp_celsius.metpy.units)try:
sf = GempakSurface('nonexistent.gem')
except FileNotFoundError:
print("GEMPAK file not found")
except Exception as e:
print(f"Error reading GEMPAK file: {e}")
# Check for valid radar moments
radar = Level2File('radar.dat')
try:
ref_data = radar.get_data('REF', sweep=0)
except ValueError as e:
print(f"Reflectivity not available: {e}")from typing import Dict, List, Optional, Union
import xarray as xr
import pandas as pd
import numpy as np
# File path types
FilePath = Union[str, Path]
# Data return types
GempakData = xr.Dataset
RadarData = np.ndarray
SatelliteData = np.ndarray
MetarData = Union[List[Dict], pd.DataFrame]
# Metadata types
StationInfo = Dict[str, Union[str, float]]
ProductInfo = Dict[str, Union[str, int, float]]