GMTB Workflow Documentation
subset_grib.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Input:
4 # Environment variables BIG_GRIB (path to original grib file)
5 # and LITTLE_GRIB (path to new grib file)
6 # Description:
7 # Script copies prescribed fields listed in *_vars variables
8 # from BIG_GRIB and stores them in LITTLE_GRIB. Levels are specified
9 # for multilevel variables. All available listed variables will be grabbed
10 # from all available listed levels.
11 #
12 # Utilizes the wgrib2, grep, and cat functions.
13 # Matching is done by both the wgrib2 -match option, and the grep tool.
14 
15 import os
16 
17 
18 in_grib=os.environ.get('BIG_GRIB')
19 out_grib=os.environ.get('LITTLE_GRIB')
20 
21 single_lev_vars = ['APCP','ACPCP','PWAT']
22 multi_lev_vars = ['UGRD', 'VGRD', 'RH', 'TMP']
23 levels = "'1000 mb|850 mb|700 mb|600 mb|500 mb|400 mb|300 mb|10 m|2 m'"
24 
25 # Make sure output directory exists
26 if not os.path.isdir(os.path.dirname(out_grib)):
27  os.makedirs(os.path.dirname(out_grib))
28 
29 # Do single level vars first:
30 wg_args = ' '.join(['-match', ''.join(["'",'|'.join(single_lev_vars),"'"])])
31 newgrib_args = ' '.join(['-grib', out_grib])
32 cmd = ' '.join(['wgrib2', in_grib, wg_args, newgrib_args])
33 
34 print cmd
35 os.system(cmd)
36 
37 
38 # Add the multi-level variables
39 wg_args = ' '.join(['-match', ''.join(["'",'|'.join(multi_lev_vars),"'"])])
40 # grep_args need -Ew for matching any item in the list (E) exactly (w).
41 grep_arg = ' '.join(['|', 'grep','-Ew', levels, '|'])
42 tempgrid_args= ' '.join(['wgrib2', '-i', in_grib, '-grib tmp.grib2'])
43 cat_args = ' '.join(['cat tmp.grib2 >>', out_grib])
44 cmd = ' '.join(['wgrib2', in_grib, wg_args, grep_arg, tempgrid_args])
45 
46 print cmd
47 os.system(cmd)
48 
49 print cat_args
50 os.system(cat_args)
51 
52 os.system('rm tmp.grid2')
53 
54 #How do I extract records 10,12,19 from a grib file
55 #
56 # wgrib2 old_grib -match '^(1|12|19):' -grib new_grib
57 #
58 # The ^ is a special regular-expression character that matches the
59 # start of the line. The () denotes an expression and the vertical bar
60 # is the OR operator. See you book on regular expressions for details.
61 
62