CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygrib

Python module for reading/writing GRIB files using ECMWF ECCODES library

Pending
Overview
Eval results
Files

message-access.mddocs/

Message Access and Selection

Methods for accessing individual messages, iterating through files, and selecting messages based on criteria. Supports flexible filtering with scalars, sequences, and functions.

Capabilities

Direct Message Access

Access specific messages by position or through indexing.

class open:
    def message(self, N: int):
        """
        Get specific message by number (1-based).
        Positions iterator at this message.
        
        Parameters:
        - N: int, message number (1-based indexing)
        
        Returns:
        gribmessage object
        """
        
    def __getitem__(self, key):
        """
        Index-based message access.
        Does not change iterator position.
        
        Parameters:
        - key: int or slice, message index (0-based) or slice object
        
        Returns:
        gribmessage object or list of gribmessage objects
        """

Usage example:

grbs = pygrib.open('weather.grb')

# Get 3rd message (1-based) - moves iterator
grb = grbs.message(3)

# Get 2nd message (0-based) - preserves iterator position  
grb = grbs[1]

# Get multiple messages via slicing
first_five = grbs[0:5]
every_other = grbs[::2]
last_three = grbs[-3:]

Message Selection and Filtering

Select messages based on GRIB key criteria with support for scalars, sequences, and functions.

class open:
    def select(self, **kwargs):
        """
        Select messages matching specified key/value criteria.
        
        Parameters:
        - **kwargs: GRIB key/value pairs for filtering
          Values can be:
          - Scalar: exact match
          - Sequence: match any value in sequence  
          - Callable: function that returns True for matches
        
        Returns:
        List of gribmessage objects matching criteria
        """
        
    def __call__(self, **kwargs):
        """Alias for select() method"""

Usage example:

grbs = pygrib.open('weather.grb')

# Select by single criteria
temp_500 = grbs.select(shortName='t', level=500)

# Select by multiple values
temp_levels = grbs.select(shortName='t', level=(850, 700, 500))

# Select using function criteria  
low_levels = grbs.select(shortName='t', level=lambda l: l > 850)

# Select by date/time
from datetime import datetime
today_data = grbs.select(validDate=datetime(2023, 12, 1, 0))

# Using __call__ method (equivalent to select)
wind_data = grbs(shortName=['u', 'v'], level=250)

Creating Messages from Strings

Create GRIB message objects from binary GRIB data.

def fromstring(gribstring: bytes):
    """
    Create gribmessage object from binary GRIB string.
    
    Parameters:
    - gribstring: bytes, binary GRIB message data
    
    Returns:
    gribmessage object
    """

Usage example:

# Get binary representation of a message
grbs = pygrib.open('weather.grb')
grb = grbs.readline()
binary_data = grb.tostring()

# Recreate message from binary data
new_grb = pygrib.fromstring(binary_data)
print(new_grb)  # Same as original message

Message Reloading

Reload message data from the source file to refresh any cached information.

def reload(grb):
    """
    Reload gribmessage from file to refresh data.
    
    Parameters:
    - grb: gribmessage, message to reload
    
    Returns:
    New gribmessage object with refreshed data
    """

Usage example:

grbs = pygrib.open('weather.grb')
grb = grbs.readline()

# Modify message (example)
grb['forecastTime'] = 120

# Reload original data from file
original_grb = pygrib.reload(grb)
print(f"Modified: {grb['forecastTime']}")
print(f"Original: {original_grb['forecastTime']}")

Advanced Selection Examples

Complex filtering scenarios using multiple criteria types.

grbs = pygrib.open('weather.grb')

# Temperature at specific levels  
temps = grbs.select(
    shortName='t',
    level=(1000, 850, 700, 500, 250),
    typeOfLevel='isobaricInhPa'
)

# Surface variables
surface_vars = grbs.select(
    shortName=['sp', 'msl', '2t', '10u', '10v'],
    typeOfLevel='surface'
)

# Forecast data for specific time range
from datetime import datetime
forecast_range = grbs.select(
    validDate=lambda d: datetime(2023, 12, 1) <= d <= datetime(2023, 12, 2),
    level=lambda l: l <= 100  # Upper atmosphere
)

# Select by parameter ID
geopotential = grbs.select(paramId=129)

# Multi-criteria complex selection
upper_air_winds = grbs.select(
    shortName=['u', 'v'],
    level=lambda l: 100 <= l <= 1000,
    typeOfLevel='isobaricInhPa', 
    step=lambda s: s % 6 == 0  # Every 6 hours
)

Selection Performance Notes

  • Use select() for flexible criteria matching with moderate performance
  • For large files with frequent searches, consider using index class for better performance
  • Function-based criteria (lambdas) are evaluated for each message and may be slower
  • Sequence matching is efficient for small-to-medium lists of values
  • Multi-field messages require special handling - see documentation warnings

Install with Tessl CLI

npx tessl i tessl/pypi-pygrib

docs

data-extraction.md

file-operations.md

index-operations.md

index.md

message-access.md

message-modification.md

utility-functions.md

tile.json