grib2io.tables API documentation

# grib2io.tables

Functions for retreiving data from NCEP GRIB2 Tables.

View Source

      1"""
      2Functions for retreiving data from NCEP GRIB2 Tables.
      3"""
      4
      5from .section0 import *
      6from .section1 import *
      7from .section3 import *
      8from .section4 import *
      9from .section5 import *
     10from .section6 import *
     11from .originating_centers import *
     12
     13
     14def get_table(table, expand=False):
     15    """
     16    Return GRIB2 code table as a dictionary.
     17
     18    Parameters
     19    ----------
     20
     21    **`table`**: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value
     22    representing the product discipline (e.g. '4.1.0').
     23
     24    **`expand`**: If `True`, expand output dictionary where keys are a range.
     25
     26    Returns
     27    -------
     28
     29    **`dict`**
     30    """
     31    if len(table) == 3 and table == '4.1':
     32        raise Exception('GRIB2 Code Table 4.1 requires a 3rd value representing the discipline.')
     33    if len(table) == 3 and table.startswith('4.2'):
     34        raise Exception('Use function get_varinfo_from_table() for GRIB2 Code Table 4.2')
     35    try:
     36        tbl = globals()['table_'+table.replace('.','_')]
     37        if expand:
     38            _tbl = {}
     39            for k,v in tbl.items():
     40                if '-' in k:
     41                    irng = [int(i) for i in k.split('-')]
     42                    for i in range(irng[0],irng[1]+1):
     43                        _tbl[str(i)] = v
     44                else:
     45                    _tbl[k] = v
     46            tbl = _tbl
     47        return tbl
     48    except(KeyError):
     49        return {}
     50
     51
     52def get_value_from_table(value, table, expand=False):
     53    """
     54    Return the definition given a GRIB2 code table.
     55
     56    Parameters
     57    ----------
     58
     59    **`value`**: `int` or `str` code table value.
     60
     61    **`table`**: `str` code table number.
     62
     63    **`expand`**: If `True`, expand output dictionary where keys are a range.
     64    Returns
     65    -------
     66
     67    Table value or `None` if not found.
     68    """
     69    try:
     70        tbl = get_table(table,expand=expand)
     71        value = str(value)
     72        return tbl[value]
     73    except(KeyError):
     74        for k in tbl.keys():
     75            if '-' in k:
     76                bounds = k.split('-')
     77                if value >= bounds[0] and value <= bounds[1]:
     78                    return tbl[k]
     79        return None
     80
     81
     82def get_varinfo_from_table(discipline,parmcat,parmnum,isNDFD=False):
     83    """
     84    Return the GRIB2 variable information given values of `discipline`,
     85    `parmcat`, and `parmnum`. NOTE: This functions allows for all arguments
     86    to be converted to a string type if arguments are integer.
     87
     88    Parameters
     89    ----------
     90
     91    **`discipline`**: `int` or `str` of Discipline code value of a GRIB2 message.
     92
     93    **`parmcat`**: `int` or `str` of Parameter Category value of a GRIB2 message.
     94
     95    **`parmnum`**: `int` or `str` of Parameter Number value of a GRIB2 message.
     96
     97    **`isNDFD`**: If `True`, signals function to try to get variable information
     98    from the supplemental NDFD tables.
     99
    100    Returns
    101    -------
    102
    103    **`list`**: containing variable information. "Unknown" is given for item of
    104    information if variable is not found.
    105    - list[0] = full name
    106    - list[1] = units
    107    - list[2] = short name (abbreviated name)
    108    """
    109    if isNDFD:
    110        try:
    111            tblname = f'table_4_2_{discipline}_{parmcat}_ndfd'
    112            modname = f'.section4_discipline{discipline}'
    113            exec('from '+modname+' import *')
    114            return locals()[tblname][str(parmnum)]
    115        except(ImportError,KeyError):
    116            pass
    117            #return ['Unknown','Unknown','Unknown']
    118    try:
    119        tblname = f'table_4_2_{discipline}_{parmcat}'
    120        modname = f'.section4_discipline{discipline}'
    121        exec('from '+modname+' import *')
    122        return locals()[tblname][str(parmnum)]
    123    except(ImportError,KeyError):
    124        return ['Unknown','Unknown','Unknown']
    125
    126
    127def get_wgrib2_level_string(pdtn,pdt):
    128    """
    129    Return a string that describes the level or layer of the GRIB2 message. The
    130    format and language of the string is an exact replica of how wgrib2 produces
    131    the level/layer string in its inventory output.
    132
    133    Contents of wgrib2 source, [Level.c](https://github.com/NOAA-EMC/NCEPLIBS-wgrib2/blob/develop/wgrib2/Level.c),
    134    were converted into a Python dictionary and stored in grib2io as table
    135    'wgrib2_level_string'.
    136
    137    Parameters
    138    ----------
    139
    140    **`pdtn`**: GRIB2 Product Definition Template Number
    141
    142    **`pdt`**: sequence containing GRIB2 Product Definition Template (Section 4).
    143
    144    Returns
    145    -------
    146
    147    **`str`**: wgrib2-formatted level/layer string.
    148    """
    149    if pdtn == 48:
    150        idxs = slice(20,26)
    151    else:
    152        idxs = slice(9,15)
    153    type1, sfac1, sval1, type2, sfac2, sval2 = map(int,pdt[idxs])
    154    lvlstr = ''
    155    val1 = sval1/10**sfac1
    156    if type1 in [100,108]: val1 *= 0.01
    157    if type2 != 255:
    158        # Layer
    159        #assert type2 == type1, "Surface types are not equal: %g - %g" % (type1,type2)
    160        val2 = sval2/10**sfac2
    161        if type2 in [100,108]: val2 *= 0.01
    162        lvlstr = get_value_from_table(type1,table='wgrib2_level_string')[1]
    163        vals = (val1,val2)
    164    else:
    165        # Level
    166        lvlstr = get_value_from_table(type1,table='wgrib2_level_string')[0]
    167        vals = (val1)
    168    if '%g' in lvlstr: lvlstr %= vals
    169    return lvlstr

def get_table(table, expand=False): View Source

    15def get_table(table, expand=False):
    16    """
    17    Return GRIB2 code table as a dictionary.
    18
    19    Parameters
    20    ----------
    21
    22    **`table`**: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value
    23    representing the product discipline (e.g. '4.1.0').
    24
    25    **`expand`**: If `True`, expand output dictionary where keys are a range.
    26
    27    Returns
    28    -------
    29
    30    **`dict`**
    31    """
    32    if len(table) == 3 and table == '4.1':
    33        raise Exception('GRIB2 Code Table 4.1 requires a 3rd value representing the discipline.')
    34    if len(table) == 3 and table.startswith('4.2'):
    35        raise Exception('Use function get_varinfo_from_table() for GRIB2 Code Table 4.2')
    36    try:
    37        tbl = globals()['table_'+table.replace('.','_')]
    38        if expand:
    39            _tbl = {}
    40            for k,v in tbl.items():
    41                if '-' in k:
    42                    irng = [int(i) for i in k.split('-')]
    43                    for i in range(irng[0],irng[1]+1):
    44                        _tbl[str(i)] = v
    45                else:
    46                    _tbl[k] = v
    47            tbl = _tbl
    48        return tbl
    49    except(KeyError):
    50        return {}

Return GRIB2 code table as a dictionary.

## Parameters

`table`: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value representing the product discipline (e.g. '4.1.0').

`expand`: If `True`, expand output dictionary where keys are a range.

## Returns

`dict`

def get_value_from_table(value, table, expand=False): View Source

    53def get_value_from_table(value, table, expand=False):
    54    """
    55    Return the definition given a GRIB2 code table.
    56
    57    Parameters
    58    ----------
    59
    60    **`value`**: `int` or `str` code table value.
    61
    62    **`table`**: `str` code table number.
    63
    64    **`expand`**: If `True`, expand output dictionary where keys are a range.
    65    Returns
    66    -------
    67
    68    Table value or `None` if not found.
    69    """
    70    try:
    71        tbl = get_table(table,expand=expand)
    72        value = str(value)
    73        return tbl[value]
    74    except(KeyError):
    75        for k in tbl.keys():
    76            if '-' in k:
    77                bounds = k.split('-')
    78                if value >= bounds[0] and value <= bounds[1]:
    79                    return tbl[k]
    80        return None

Return the definition given a GRIB2 code table.

## Parameters

`value`: `int` or `str` code table value.

`table`: `str` code table number.

`expand`: If `True`, expand output dictionary where keys are a range.

## Returns

Table value or `None` if not found.

def get_varinfo_from_table(discipline, parmcat, parmnum, isNDFD=False): View Source

     83def get_varinfo_from_table(discipline,parmcat,parmnum,isNDFD=False):
     84    """
     85    Return the GRIB2 variable information given values of `discipline`,
     86    `parmcat`, and `parmnum`. NOTE: This functions allows for all arguments
     87    to be converted to a string type if arguments are integer.
     88
     89    Parameters
     90    ----------
     91
     92    **`discipline`**: `int` or `str` of Discipline code value of a GRIB2 message.
     93
     94    **`parmcat`**: `int` or `str` of Parameter Category value of a GRIB2 message.
     95
     96    **`parmnum`**: `int` or `str` of Parameter Number value of a GRIB2 message.
     97
     98    **`isNDFD`**: If `True`, signals function to try to get variable information
     99    from the supplemental NDFD tables.
    100
    101    Returns
    102    -------
    103
    104    **`list`**: containing variable information. "Unknown" is given for item of
    105    information if variable is not found.
    106    - list[0] = full name
    107    - list[1] = units
    108    - list[2] = short name (abbreviated name)
    109    """
    110    if isNDFD:
    111        try:
    112            tblname = f'table_4_2_{discipline}_{parmcat}_ndfd'
    113            modname = f'.section4_discipline{discipline}'
    114            exec('from '+modname+' import *')
    115            return locals()[tblname][str(parmnum)]
    116        except(ImportError,KeyError):
    117            pass
    118            #return ['Unknown','Unknown','Unknown']
    119    try:
    120        tblname = f'table_4_2_{discipline}_{parmcat}'
    121        modname = f'.section4_discipline{discipline}'
    122        exec('from '+modname+' import *')
    123        return locals()[tblname][str(parmnum)]
    124    except(ImportError,KeyError):
    125        return ['Unknown','Unknown','Unknown']

Return the GRIB2 variable information given values of `discipline`, `parmcat`, and `parmnum`. NOTE: This functions allows for all arguments to be converted to a string type if arguments are integer.

## Parameters

`discipline`: `int` or `str` of Discipline code value of a GRIB2 message.

`parmcat`: `int` or `str` of Parameter Category value of a GRIB2 message.

`parmnum`: `int` or `str` of Parameter Number value of a GRIB2 message.

`isNDFD`: If `True`, signals function to try to get variable information from the supplemental NDFD tables.

## Returns

`list`: containing variable information. "Unknown" is given for item of information if variable is not found.

- list[0] = full name
- list[1] = units
- list[2] = short name (abbreviated name)

def get_wgrib2_level_string(pdtn, pdt): View Source

    128def get_wgrib2_level_string(pdtn,pdt):
    129    """
    130    Return a string that describes the level or layer of the GRIB2 message. The
    131    format and language of the string is an exact replica of how wgrib2 produces
    132    the level/layer string in its inventory output.
    133
    134    Contents of wgrib2 source, [Level.c](https://github.com/NOAA-EMC/NCEPLIBS-wgrib2/blob/develop/wgrib2/Level.c),
    135    were converted into a Python dictionary and stored in grib2io as table
    136    'wgrib2_level_string'.
    137
    138    Parameters
    139    ----------
    140
    141    **`pdtn`**: GRIB2 Product Definition Template Number
    142
    143    **`pdt`**: sequence containing GRIB2 Product Definition Template (Section 4).
    144
    145    Returns
    146    -------
    147
    148    **`str`**: wgrib2-formatted level/layer string.
    149    """
    150    if pdtn == 48:
    151        idxs = slice(20,26)
    152    else:
    153        idxs = slice(9,15)
    154    type1, sfac1, sval1, type2, sfac2, sval2 = map(int,pdt[idxs])
    155    lvlstr = ''
    156    val1 = sval1/10**sfac1
    157    if type1 in [100,108]: val1 *= 0.01
    158    if type2 != 255:
    159        # Layer
    160        #assert type2 == type1, "Surface types are not equal: %g - %g" % (type1,type2)
    161        val2 = sval2/10**sfac2
    162        if type2 in [100,108]: val2 *= 0.01
    163        lvlstr = get_value_from_table(type1,table='wgrib2_level_string')[1]
    164        vals = (val1,val2)
    165    else:
    166        # Level
    167        lvlstr = get_value_from_table(type1,table='wgrib2_level_string')[0]
    168        vals = (val1)
    169    if '%g' in lvlstr: lvlstr %= vals
    170    return lvlstr

Return a string that describes the level or layer of the GRIB2 message. The format and language of the string is an exact replica of how wgrib2 produces the level/layer string in its inventory output.

Contents of wgrib2 source, Level.c, were converted into a Python dictionary and stored in grib2io as table 'wgrib2_level_string'.

## Parameters

`pdtn`: GRIB2 Product Definition Template Number

`pdt`: sequence containing GRIB2 Product Definition Template (Section 4).

## Returns

`str`: wgrib2-formatted level/layer string.