Converting Grib To Binary And Transpose Problems

This was a problem I faced some time ago. I wanted to convert some grib files into plain binary files.

Here's how I tried to do it, starting from one single grib file:

grib2ctl.pl -verf input.grib > input.ctl
gribmap -e -i input.ctl
wgrib -verf -nh -o output.bin input.grib
cat input.ctl|grep -v -e index -e dtype|sed "s/grib/bin/">output.ctl

Line1. Creating a ctl from the original gribbed data

Line2. Creating the map, so that we can access grib data with GrADS. In my case I had ECWMF grib files (junk bytes) so I need to use '-e' flag.

Line3. Using wgrib to read in grib and output binary

Line4. Modifying the 'input.ctl' to open the output binary file

The problem is that most of the times the order of x/y/z/var/time in your binary file will messed up and you'll not be able to use it. For instance, while I was trying to overcome this problem I tried to convert a very simple file, which had only 2 variables, 2 levels and a single time step and I found that:

 displaying variable 1, for level 1, show variable 1 level 1
 displaying variable 1, for level 2, show variable 2 level 1
 displaying variable 2, for level 1, show variable 1 level 2
 displaying variable 2, for level 2, show variable 2 level 2

This meant that wgrib was writing to the binary file in the "wrong" order:

x, y, Variable, Z, time    (variables change faster than levels)

While the "correct" order should be:

x, y, Z, Variable, time (levels change faster than variables)

The issue is that grib data can come in any order and wgrib writes in order of appearence. However, IEEE grads binary files have a very specific order and someone should never assume/expect the order of data in the GRIB file is correct for an IEEE file.

To solve the problem to first thing you need to do is check the order of your data:

wgrib -s input.grb | more

In my case, Z and Var are transposed. Now the second step, we must tell GrADS about this. For that we need to change the ctl:

vars
  variable  level  -1,xx,yy  description
endvars

About the variable line in your ctl, you should look it up in your GrADS document, the link is copied below. In my case I used:

hgeo  20  -1,10,1  geopotentical height

Pages you should read:

CTL: defining variables
wgrib page
Doing GRIB in GrADS
grib2ctl page
About gribmap

Page last modified on May 26, 2015, at 05:40 PM
Powered by PmWiki