0% found this document useful (0 votes)
243 views167 pages

GRADSmanual PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
243 views167 pages

GRADSmanual PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 167

GRADS

Table of Contents
General Topics 1
Starting and Quiting GrADS 1
Basic Concept of Operation 4
Gridded Data Sets 5
Gridded Data Descriptor File 5
Structure of a Gridded Binary Data File 6
Binary Data Formats 7
Creating Data Files 7
Elements of a GrADS Data Descriptor File 10
Creating a Data Descriptor File for GRIB Data 33
Reading NetCDF and HDF-SDS Files with GrADS (COARDS
Compliant) 41
Reading NetCDF and HDF-SDS Files with GrADS (Not COARDS
Compliant) 42
Reinitialization of GrADS 45
Command Line Editing and History 46
External Utilities 18
Using GrADS on a PC x
Using GrADS with a Graphical User Interface x

Analysis Topics 65

Dimension Environment 65
GrADS Variables 67
Variable Names 67
Defining New Variables 68
Undefining Variables 71
GrADS Expressions 72
Using Templates to Aggregate Data Files 73
About Station Data 75
Structure of a Station Data File 75
Creating a Station Data File 77
Station Data Descriptor File 79
The STNMAP Utility 81
Using Station Data 82
Operating on Station Data 82
Plotting Station Models 83
Drawing Arbitrary Cross Sections 84
User Defined Functions 87

ii
 Overview of User Defined Functions 87
 The user defined function table 88
 Format of the function data transfer file 89
 Format of the function result file 92
 Example: Linear Regression Function 93
 Using Pre-Projected Data in GrADS 96
 Polar Stereo Preprojected Data 97
 Lambert Conformal Preprojected Data 100
 NCEP ETA Model 103
 NCEP polar stereographic grid for SSMI data 107
 CSU RAMS oblique polar stereographic grid 109
 Pitfalls when using preprojected data 114
 GrADS Display Projections 115
 Summary and Plans 115
 Non-Standard Variable Formats and Data File Structures 116

Display Topics 119


 Displaying Data 119
 Drawing Plots 119
 Clearing the Display 119
 Graphics Output Types 120
 Graphics Options ?
 Drawing Basic Graphics Elements ?
 Animation 121
 Page Control 122
 Real and Virtual Pages 122
 Controlling the Plot Area 123
 Drawing Multi-Panel Plots 123
 Controlling Colors in GrADS 124
 Font File Format 129
 Producing Hardcopy and Image Output from GrADS 131

GrADS Scripting Language 134


 Introduction to GrADS scripts 134
 Elements of the Language: 136
 comment 137
 statement 137
 assignment 137
 say / prompt / pull 138
 if / else / endif 139

iii
 while / endwhile 140
 variables 141
 operators 143
 expressions 144
 concatenation 144
 Functions 145
 Intrinsic Functions 146
 Commands that complement the scripting language 147
 Widgets 150
 Dynamic Loading of Script Functions 155
 Script Library 158

iv
General Topics
Starting and Quitting GrADS
GrADS is started by entering the command:
 

Before initialising the graphics output environment, GrADS will prompt for landscape or
portrait mode. Landscape is 11 x 8.5 inches (usually what you want). Portrait is 8.5 x 11
inches, primarily used for producing vertically oriented hardcopy output. The actual size
of the window will not, of course, be 11 x 8.5 inches (or 8.5 x 11 inches), but instead will
be whatever size you chose by using your workstation's window manager. But GrADS
will treat the window as if it were one of the above sizes, so it is best to size the window
with approximately the proper aspect ratio. This can be done using the window manager
or from GrADS using the command:

 
 

which resizes the window to


 pixels.

After answering this prompt, a separate graphics output window will be opened (but not
on PCs). You may move or resize this window at any time.

You will enter GrADS commands in the text window from where you started GrADS.
Graphics output will appear in the graphics window in response to the commands you
enter. You will thus need to make the text window the "active" window; the window that
receives keyboard input.

Help
Typing 
 at the GrADS command prompt gives a summary list of operations
essential to do anything in GrADS. This is intended to jog memory rather than provide an
exhaustive help facility. If the GrADS manual is not available, you can obtain info on
most command parameters by typing the command on its own. Alternatively, we are
setting up comprehensive documentation intended to be used as a local Web facility.

1
Diagnostics at startup
When you start GrADS you get platform specific diagnostics, for example:
 "!#$&%#&')("*,+.- /0-#1-2# /0- 3 +465-2(87:99;=<?>
@@@@BA CDE - /8F.*GH I*KJ)HL#$M.-+(N( OQP - 3 +
'# R
@@@@ A CDE - /
The line E tells
-&'Syou
(&+)T0that
-#+ this version is (i.e., data are 32-bit) and it was
compiled for a machine (the Sun in this case). On the Cray you get...
@@@@VU WD F.*,X8YJQZ&[Q*HG\)G]5*,^H _`Z ] Ja5Qb

Startup options
'O# TP
You may specify the following options as arguments to the command when
GrADS is started:
DE
D 1 Run grads in batch mode. No graphics output window is opened.
Run grads in landscape mode. The Portrait vs. Landscape question is not
asked.
Dc
D $ Run grads in portrait mode.
Execute the supplied command as the 1 st GrADS command after GrADS is
started.

An example:
'O# TP D $edfOg+ c O030h-1(i<j'QPd

These options may be used in combinations. For example:


'O# TP DE 1$edfOg+ E # /0$M<j'QPd

Would run grads in batch mode, using landscape orientation (thus no questions are asked
at startup); and execute the command:
E # /0$M<j'QP
upon startup.

2
Leaving GrADS
To leave GrADS, enter the command:

kl m.n o
k

3
Basic Concept of Operation
When you have successfully installed and started GrADS, you'll be confronted with two
windows -- a terminal window with a prompt, much like the infamous C:> in MS-DOS,
and a resizable window (black background by default) where graphics are displayed.

GrADS commands are entered in the terminal window and the response from GrADS is
either graphics in the graphics window or text in the terminal window. The three
fundamental GrADS commands:

1. p qr&sopen or make available to GrADS a data file with either gridded or


station data
2. t display a GrADS "expression" (e.g., a slice of data)
3. u rv manipulate the "what" "where" and "how" of data display

The GrADS "expression," or what you want to look at, can be as simple as a variable in
the data file that was opened, e.g., twu xq or an arithmetic or GrADS function operation
on the data, e.g., twu xq0yz{{ or t}|~& where mag is a GrADS intrinsic
function.

The "where" of data display is called the "dimension environment" and defines which
part, chunk or "hyperslab" of the 4-D geophysical space (lon,lat,level,time) is displayed.
The dimension environment is manipulated through the set command and is controlled in
either grid coordinates (x,y,z,t or indices) or world coordinates ( x p s6x~ v=xr&
v0|Qr ).

The "what" and "how" of display is controlled by u rv" p||~s)tu and includes both
graphics methods (e.g., contours, streamlines) and data (e.g., t to a file).

GrADS graphics can be written to a file (i.e., r&s.~.xrqs)v filename and qs)v )
and then converted to postscript for printing and/or conversion to other image formats.

In addition, GrADS includes graphic primitives (e.g., lines and circles) and basic
labelling through the t ~ p||~s)t .

The or r  command is used to get information from GrADS such as which files
are opened and even statistics.

4
About GrADS Gridded Data Sets
This section describes GrADS gridded data sets -- their structure and format, how to
create them, and how to instruct GrADS to interpret them properly. Here are some quick
links for skipping through this section:

Introduction
The Data Descriptor File
Structure of a Gridded Binary Data File
Binary Formats
Creating Data Files

Introduction
In GrADS, the raw binary data and the meta data (information about the binary data) are
stored in separate files. The meta data file contains a complete description of the binary
data as well as instructions for GrADS on where to find the data and how to read it. The
binary data file is purely data with no space or time identifiers. The meta data file is the
one you open in GrADS -- it is called the data descriptor file. The data descriptor file
has a 0 extension and is therefore also referred to as a control file.

ga-> & filename.ctl

The Data Descriptor File


The data descriptor file contains a complete description of the binary data as well as
instructions for GrADS on where to find the data and how to read it. The descriptor file is
an ascii file that can be created easily with a text editor. The general contents of a gridded
data descriptor file are as follows:

Filename for the binary data


Missing or undefined data value
Mapping between grid coordinates and world coordinates
Description of variables in the binary data set

The individual components of data descriptor files are discussed in detail in the section
Elements of a Data Descriptor File.

The data descriptor file is free format, which means the components of each record (line

5
of text) are blank delimited. The only exceptions are comment records which must start
with an asterisk (*) in the first column and may not appear in the list of variable
descriptor records between the ) and  ) records. Individual records may not
be more than 255 characters long. Here is an example of a basic data descriptor file:
K?f?&Kf?
K` ``f?
` `?
ff `?K`KQ 
`ff K`K` 
ff ?`K?````B`V,?&
?ff K`K???``f`
K
? ` f?KfKf``
`f ` ffK
`f ` `fK?K
` ` K````
?`K

In this example, the binary data set is named  ,Q0 0K 0.i0 and is
located in the same directory as the descriptor file. This is specified by the caret (^) in
front of the data filename. The undefined or missing data value is -9.99e33, there are 180
grid points in the X direction, 90 grid points in the Y direction, 10 vertical levels, 4 time
steps, and 4 variables. The variable "slp" is a surface variable -- it has no vertical levels,
but is assigned a default vertical coordinate of Z=1. The variables "hgt" and "temp" have
10 vertical levels, and the variable "shum" has 6 vertical levels (the first six listed, 1000
to 300).

Structure of a Gridded Binary Data File


The binary data file is purely data with no space or time identifiers. The data descriptor
specifies the data's grid dimensions, but it is up to the user to make sure that the binary
data have been written to file in the proper order so GrADS will interpret them correctly.

GrADS views gridded data sets as 5-dimensional arrays varying in longitude, latitude,
vertical level, variable, and time. It is helpful to think of a gridded binary data file as a
sequence of "building blocks", where each building block is a horizonal grid of data
varying in the X and Y dimensions. The first dimension (X) always varies from west to
east; the second dimension (Y) varies from south to north (by default). One horizontal
grid represents a particular variable at a particular height and time.

Each horizontal grid in a GrADS binary data file must be the same size. If you have two
variables with different horizontal grids, you must create two separate data sets.

6
The structure of a 3-D, 4-D, or 5-D data set is determined by the order in which the
horizonal grids are written to file. The building blocks are stacked in a sequence
according to dimension. The sequence goes in the following order starting from the
fastest varying dimension to the slowest varying dimension: longitude (X), latitude (Y),
vertical level (Z), variable (VAR), time (T).

For example, suppose you want to create a 4-D binary data set containing four variables.
The horizonal grids would be written to the data set in the following order:
KQ,K`?Kf`?Kf
V
 



KQ,K`?  K  f `? Kf
V
 



KQ,K`?  K  f `? Kf
V
 



KQ,K`? }K  f `? Kf
V
 



K.,K`?Kf`?Kf
V
 



K .,K`?  K  f `? Kf
V
 



K .,K`?  K  f `? Kf
V
 



K .,K`? }K  f `? Kf

V
 





Binary Formats
GrADS can read binary data that are formatted with or without FORTRAN record length
headers. Files containing record length headers are called "sequential" and those without
embedded record length information are called "direct access" or "stream" files. Unless
otherwise specified, GrADS will assume the data file does not contain the record length
headers.

GrADS can also directly read GRIB formatted data -- one of GrADS most powerful and
unique features! See the section on Creating Data Descriptor Files for GRIB Data for
more information.

A third category of data formats that GrADS can read are "self-describing files" such as
NetCDF or HDF-SDS. For more information, see the references pages for sdfopen and
xdfopen.

Creating Data Files


The default format for GrADS gridded binary data files is "stream" or "direct access". If
you want to read FORTRAN "sequential" unformatted binary data files, you must include
the following additional record in the data descriptor file:

7
"! #%$&%'"$)(*,+.-./

Following are three examples of how to create gridded binary data files with simple
FORTRAN programs.

1. Suppose you have U and V wind components in 4-dimensions (X, Y, Z, and T)


and you want to write them out in so they can be viewed in GrADS. The
FORTRAN code might look something like this:
0213215476 8693;:=<7>? @A ACBD<7E?F@BD<G? HIBJ< 8 ? A%K
L >54769<7M >9N<O.:P<2>"BD<2E"BD<G%KBRQ,:=<7>BJ<2E"BD<G%KB L O94:=<7>BD<7E7K
L N< ?@BD<G
S1 TTT9N1 L :=OUBD<2>"BD<7EBJ< GUBD<UB L O94.K
V 32>86W:X@ Y)K L O94
6< LL N
L N< ?@BD<G
S1 TTT9N1 L :ZQ[BD<2>"BD<7EBJ< GUBD<UB L O94.K
V 32>86W:X@ Y)K L O94
6< LL N
M5O\ 3N9O8 ><6]TN 1 L :^1"BD<7>BJ<2E"BD<GCBJ<CB L O4K
L 5> 4769<7M >9N< 1):P<2>"BD<2E"BD<G%KB L O94:=<7>BJ<2EK
L N_>9?@BD<7>
L N_E? @IBJ<2E
L O94:^>"B`EK^?21):a>B`E"BD<WK
6< 
L L N
6< 
L L N
36 89O3 <

The data descriptor file would look something like:


b7cd e f 74 N L 6T"g L 198
e2hei d c 154 07T6kj2N L 6 T b 18 1
l m bdn YCgo@ Y YY Y d p @q
r b d n @ A AT><2613 Y_sIgXt
ub d n F@_T><2613v9F Y_sIgJY
w5b d n H_T 6Q76T Mx@ Y YYF YY]HYYyYYzt^YY|{5YY@ Y YztaY
eb d n AT><2613YY }Y@103 H)t~q93
2c s
O_HFF l S9N4 0 N<69< 8
QHFF S9N4 0 N<69< 8
d m b2c

2. This simple example write out one variable:


d92i w :^y s"BoAqIB@ q)K
gg gg
dm :HIB n h9id ?J 321 L Mg L 91 8 B n j2? l mn j e edb B
 9d2cc ?C bh de B d29i ? y s9Aq)K

8
9  29
_9o
2 ;Io92^%XDU`W ID J
9292 
_9 2 

3. Another simple sample might be:


92)
_9o
,^^2
_9 2 
;Xo Z5 o 9 9 2J 9  [ R77 9D792U
 )
2 ;Io29)



The associated descriptor file:


7 5 o 9
2 5 7x7  
 9 
292
 292]

5  ]

  ]  29 ]9

2
 79
2

Once created, you can use this data set to experiment with GrADS data functions,
such as:
,,7I. W ,[[

9
Components of a GrADS Data Descriptor File
DSET
DTYPE
INDEX
STNMAP
TITLE
UNDEF
UNPACK
FILEHEADER
THEADER
XYHEADER
XVAR
YVAR
ZVAR
STID
TVAR
TOFFVAR
OPTIONS
PDEF
XDEF
YDEF
ZDEF
TDEF
VARS
ENDVARS

10
back to top
DSET data_filename
This entry specifies the filename of the data file being described. If the data and the
descriptor file are not in the same directory, then data_filename must include a full path. If
a ^ character is placed in front of data_filename, then data_filename is assumed to be
relative to the path of the descriptor file. If data_filename does not include a full path or a
^, then GrADS assumes the data set and its descriptor file are in the same directory. If you
are using the ^ character in the DSET entry, then the descriptor file and the data file may
be moved to a new directory without changing any entries in the data descriptor file,
provided their relative paths remain the same. For example:

If the data descriptor file is:


/data/wx/grads/sa.ctl
and the binary data file is:
/data/wx/grads/sa.dat
then the data file name in the data descriptor file can be:
DSET ^sa.dat
instead of:
DSET /data/wx/grads/sa.dat
DTYPE keyword back to top

The DTYPE entry specifies the type of data being described. There are four options: grib,
hdfsds, netcdf, or station. If the data type is none of these, then the DTYPE entry is
omitted completely from the descriptor file and GrADS will assume the data type is
gridded binary.

11
bufr (GrADS version 1.9) Data file is a BUFR station data file. This data type must be
accompanied by the following special entries: XVAR, YVAR, TVAR, STID. Optional
special entries are: ZVAR, TOFFVAR.
grib Data file is an indexed GRIB file. This data type requires a secondary entry
in the descriptor file: INDEX. The INDEX entry provides the filename
(including the full path or a ^) for the grib index file. The index file is created
by the gribmap utility. You must run gribmap and create the index file before
you can display the grib data in GrADS.
hdfsds (GrADS version 1.9) Data file is an HDF Scientific Data Set (SDS). Although HDF-
SDS files are self-describing and may be read automatically using the
sdfopen/xdfopen commands, this DTYPE gives you the option of overriding the
file's own metadata and creating a descriptor file for some or all of the variables in
the file. This DTYPE may also be used if the metadata in the HDF-SDS file is
insufficient or is not coards-compliant. This data type requires a special entry in the
units field of the variable declaration. The undef and unpack entries contain special
options for this dtype.
netcdf (GrADS version 1.9) Data file is NetCDF. Although NetCDF files are self-
describing and may be read automatically using the sdfopen/xdfopen
commands, this DTYPE gives you the option of overriding the file's own
metadata and creating a descriptor file for some or all of the variables in the
file. This DTYPE may also be used if the metadata in the NetCDF file is
insufficient or is not coards-compliant. This data type requires a special entry
in the units field of the variable declaration. The undef and unpack entries
contain special options for this dtype.
station Data file is in GrADS station data format. This data type requires a secondary
entry in the descriptor file: STNMAP. The STNMAP entry provides the
filename (including the full path or a ^) for the station data map file. The map
file is created by the stnmap utility. You must run stnmap and create the map
file before you can display the station data in GrADS.
back to top
INDEX filename
This entry specifies the name of the grib map file. It is required when using the DTYPE
grib entry to read grib formatted data. The file is generated by running the external utility
gribmap. Filenaming conventions are the same as those described for the DSET entry.
back to top
STNMAP filename
This entry specifies the name of the station map file. It is required when using the DTYPE
station entry to read GrADS-formatted station data. The file is generated by running the
external utility stnmap. Filenaming conventions are the same as those described for the
DSET entry.
back to top
TITLE string

12
This entry gives brief description of the contents of the data set. String will be included in
the output from a query command and it will appear in the directory listing if you are
serving this data file with the GrADS-DODS Server (GDS), so it is helpful to put
meaningful information in the title field. For GDS use, do not use double quotation marks
(") in the title.
back to top
UNDEF value <undef_attribute_name>
This entry specifies the undefined or missing data value. UNDEF is a required entry even if there
are no undefined data. GrADS operations and graphics routines will ignore data with this value
from this data set.
(GrADS version 1.9) An optional second argument has been added for data sets of DTYPE netcdf
or hdfsds -- it is the name of the attribute that contains the undefined value. This is used when
individual variables in the data file have different missing values. Attribute names are case
sensitive, and it is assumed that the name is identical for all variables in the NetCDF or HDF-SDS
data file. After data I/O, the missing values in the grid are converted from the individual undef to
the file-wide undef (the numerical value in the first argument of the undef record). Then it appears
to GrADS that all variables have the same undef, even if they don't in the original data file. If the
name given does not match any attributes, or if no name is given, the file-wide undef value will be
used.
Example: UNDEF 1e+33 _FillValue
back to top
UNPACK scale_factor_attribute_name add_offset_attribute_name
(GrADS version 1.9) This entry is used with DTYPE netcdf or hdfsds for data variables
that are 'packed' -- i.e. non-float data that need to be converted to float by applying the
following formula:
y = x * scale_factor + add_offset
Two arguments are required, the first is the attribute name for the scale factor (e.g.
scale_factor, Slope), the second is the attribute nme for the offset (e.g. add_offset,
Intercept). Attribute names are case sensitive, and it is assumed that the names are
identical for all variables in the NetCDF or HDF-SDS data file. If the names given do not
match any attributes, the scale factor will be assigned a value of 1.0 and the offset will be
assigned a value of 0.0.
Example: UNPACK scale_factor add_offset
back to top
FILEHEADER length
This optional entry tells GrADS that your data file has a header record of length bytes that
precedes the data. GrADS will skip past this header, then treat the remaineder of the file as
though it were a normal GrADS binary file after that point. This optional descriptor file
entry is only valid for GrADS gridded data sets.
THEADER length back to top

This optional entry tells GrADS that the data file has a header record of length bytes
preceding each time block of binary data. This optional descriptor file entry is only valid
for GrADS gridded data sets. See the section on structure of a gridded binary data file for
more information.

13
back to top
XYHEADER length
This optional entry tells GrADS that the data file has a header record of length bytes
preceding each horizontal grid (XY block) of binary data. This optional descriptor file
entry is only valid for GrADS gridded data sets. See the section on structure of a gridded
binary data file for more information.
XVAR x,y back to top

(GrADS version 1.9) This entry provides the x,y pair for the station's longitude. This entry is
required for DTYPE bufr.
back to top
YVAR x,y
(GrADS version 1.9) This entry provides the x,y pair for the station's latitude. This entry is
required for DTYPE bufr.
back to top
ZVAR x,y
(GrADS version 1.9) This entry provides the x,y pair for the station data's vertical
coordinate (e.g., pressure). This is an optional entry for DTYPE bufr.
back to top
STID x,y
(GrADS version 1.9) This entry provides the x,y pair for the station ID. This entry is
required for DTYPE bufr.
back to top
TVAR yr x,y mo x,y dy x,y hr x,y mn x,y sc x,y
(GrADS version 1.9) This entry provides the x,y pairs for all the base time coordinate variables.
Each time unit (year=yr, month=mo, day=dy, hour=hr, minute=mn, second=sc) is presented as a
2-letter abbreviation followed by the x,y pair that goes with that time unit. The time for any
individual station report is the base time plus the offset time (see TOFFVAR). All six base time
units are not required to appear in the TVAR record, only those that are in the data file. This entry
is required for DTYPE bufr.
back to top
TOFFVAR yr x,y mo x,y dy x,y hr x,y mn x,y sc x,y
(GrADS version 1.9) This entry provides the x,y pairs for all the offset time coordinate variables.
The syntax is the same as TVAR. The time for any individual station report is the base time plus
the offset time. All six offset time units are not required to appear in the TOFFVAR record, only
those that are in the data file. This is an optional entry for DTYPE bufr.
back to top
OPTIONS keyword
This entry controls various aspects of the way GrADS interprets the raw data file. It
replaces the old FORMAT record. The keyword argument may be one or more of the
following:

14
yrev Indicates that the Y dimension (latitude) in the data file has been
written in the reverse order from what GrADS assumes. An important
thing to remember is that GrADS still presents the view that the data
goes from south to north. The YDEF statement does not change; it still
describes the transformation from a grid space going from south to
north. The reversal of the Y axis is done as the data is read from the
data file.
zrev Indicates that the Z dimension (pressure) in the data file has been
written from top to bottom, rather than from bottom to top as GrADS
assumes. The same considerations as noted above for yrev also apply.
template Indicates that a template for multiple data files is in use. For more
information, see the section on Using Templates.
sequential Indicates that the file was written in sequential unformatted I/O. This
keyword may be used with either station or gridded data. If your
gridded data is written in sequential format, then each record must be
an X-Y varying grid. If you have only one X and one Y dimension in
your file, then each record in the file will be one element long (it may
not be a good idea to write the file this way).
365_day_cale Indicates the data file was created with perpetual 365-day years, with
ndar no leap years. This is used for some types of model ouput.
byteswapped Indicates the binary data file is in reverse byte order from the normal
byte order of your machine. Putting this keyword in the OPTIONS
record of the descriptor file tells GrADS to swap the byte order as the
data is being read. May be used with gridded or station data.
The best way to ensure hardware independence for gridded data is to specify the data's
source platform. This facilitates moving data files and their descriptor files between
machines; the data may be used on any type of hardware without having to worry
about byte ordering. The following three OPTIONS keywords are used to describe the
byte ordering of a gridded or station data file:
big_endian Indicates the data file contains 32-bit IEEE floats created on a big
endian platform (e.g., sun, sgi)
little_endian Indicates the data file contains 32-bit IEEE floats created on a little
endian platform (e.g., iX86, and dec)
cray_32bit_ie
Indicates the data file contains 32-bit IEEE floats created on a cray.
ee

15
back to top
PDEF

Display Pre-Projected Data with PDEF

Gridded data that are mapped onto a particular map projection are called 'pre-projected.' An
example of pre-projected data is the output from a weather forecast model that is mapped onto a
north polar stereographic grid.

In order to display pre-projected data on a map in GrADS, the descriptor file must contain a
PDEF entry. A descriptor file that contains a PDEF record describes two different grids. The first
grid is described by the PDEF record itself and is the "native" grid for the pre-projected data in
the file. The PDEF record describes the size of this native grid, and then describes how to
convert from lat/lon to the i/j of the grid (this description takes the form of stating the projection of
the grid along with the projection constants or providing the mapping to the native grid in a
supplementary data file). The second grid described in the desctiptor file is a rectilinear lat/lon
grid, which is defined by the XDEF and YDEF records. The rectilinear grid is used by GrADS
internally and can be any size or resolution -- it is completely independent of the pre-projected or
native grid. GrADS uses the information about the two grids to interpolate from the PDEF-
described native grid to the XDEF/ YDEF-described rectilinear grid. All displays and analyses are
done using the interpolated data on the rectilinear grid. The virtue of this approach is that all built
in GrADS analytic functions (e.g., aave, hcurl...) will work even though the data were not
originally on a lon/lat grid. The downside is that you are looking at interpolated data.

It is possible to view the pre-projected data on its native grid. To do this, you omit the PDEF
entry from the descriptor file, and use the XDEF and YDEF entries to describe the shape of the
native grid. In this case, your displays must be drawn in i/j space without a map projection (set
mpdraw off).

When you do a display of a pre-projected vector field, you must know whether the original vector
components are defined relative to the data grid or relative to the Earth. If the data are grid-
relative, they must be rotated to Earth-relative coordinates in order for the interpolation to work
properly. See the "Notes" under each particular projection type for further information.

PDEF Syntax

PDEF isize jsize NPS ipole jpole lonref gridinc


PDEF isize jsize SPS ipole jpole lonref gridinc
Example:PDEF 53 45 nps 27 49 -105 190.5
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
ipole the i coordinate of the pole referenced from the lower left corner, assumed
to be at (1,1)
jpole the j coordinate of the pole referenced from the lower left corner, assumed
to be at (1,1)
lonref reference longitude
gridinc distance between gripoints in km

16
Notes: Polar stereographic projections (N and S) are defined as at NCEP. Wind rotation has
also been added so that vector data will be properly displayed.

PDEF isize jsize LCC latref lonref iref jref Struelat Ntruelat slon dx dy
Example:PDEF 103 69 lcc 30 -88 51.5 34.5 20 40 -88 90000 90000
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
latref reference latitude
lonref reference longitude (in degrees, E is positive, W is negative)
iref i of ref point
jref j of ref point
Struelat S true lat
Ntruelat N true lat
slon standard longitude
dx grid X increment in meters
dy grid Y increment in meters
Notes: The Lambert Conformal projection (lcc) was implemented for use with data from the
U.S. Navy's limited area model NORAPS.Wind rotation has not been implemented!!!
Use only for scalar fields.

PDEF isize jsize ETA.U lonref latref dlon dlat


Example:PDEF 181 136 eta.u -97.0 41.0 0.38888888 0.37
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
lonref reference longitude (in degrees, E is positive, W is negative)
latref reference latitude
dlon grid longitude increment in degrees
dlat grid latitude increment in degrees
Notes: The eta model native grid is awkward to work with because the variables are on
staggered and non-rectangular grids. NCEP created "unstaggered" eta model fields,
in which the variables are placed on a common rectangular grid. Wind rotation has
also been added so that vector data will be properly displayed.

PDEF isize jsize PSE slat slon ipole jpole dx dy sign


Example:

17
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
slat absolute value of the standard latitude
slon absolute value of the standard longitude
ipole the i coordinate of the pole referenced from the lower left corner, assumed
to be at (0,0)
jpole the j coordinate of the pole referenced from the lower left corner, assumed
to be at (0,0)
dx grid X increment in km
dy grid Y increment in km
sign 1 for NH; -1 for SH
Notes: The polar stereo projection used by the original NMC models is not very precise
because it assumes the earth is round (eccentricity = 0). While this approximation
was reasonable for coarse resolution NWP models, it is inadequate to work with
higher resolution data such as SSM/I. Wind rotation has not been implemented!!!
Use only for scalar fields.

PDEF isize jsize OPS latref lonref xoff yoff iref jref dx dy
Example:PDEF 26 16 ops 40.0 -100.0 90000.0 90000.0 14.0 9.0 180000.0 180000.0
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
latref reference latitude
lonref reference longitude (in degrees, E is positive, W is negative)
xoff lonref offset in meters
yoff latref offset in meters
iref the i coordinate of the reference point
jref the j coordinate of the reference point
dx grid X increment in km
dy grid Y increment in km
dy grid Y increment in km
Notes: The CSU RAMS model uses an oblique polar stereo projection. Wind rotation has
not been implemented!!! Use only for scalar fields.

PDEF isize jsize BILIN format byteorder fname


Example:PDEF 100 100 BILIN sequential binary-big ^mygrid.interp.values

18
Args: isize The size of the native grid in the x direction
jsize The size of the native grid in the y direction
Must be either STREAM (direct access) or SEQENTIAL (fortran
format
formatted)
byteorde If set to BINARY, byte odering is assumed to be same as local machine
r If set to BINARY-BIG, byte ordering is assumed to be big-endian
If set to BINARY-LITTLE, byte ordering is assumed to be little-endian
fname The name of the supplementary file
Notes:The supplementary file contains three lat-lon floating-point grids: i values, j values,
and wind rotation values. The size of these grids must match the XDEF and YDEF
entries in the descriptor file.

PDEF size 1 FILE num format byteorder fname


Example:PDEF 5000 1 file 4 sequential binary-big ^mygrid.interp.values
PDEF 15238 1 file 1 stream binary ^gtd.filepdef
Args: size of the native grid, expressed as a vector (eg, all gridpoints in an x-y
size
grid)
num number of sets of interpolation grids supplied
Must be either STREAM (direct access) or SEQENTIAL (fortran
format
formatted)
byteorde If set to BINARY, byte odering is assumed to be same as local machine
r If set to BINARY-BIG, byte ordering is assumed to be big-endian
If set to BINARY-LITTLE, byte ordering is assumed to be little-endian
fname The name of the supplementary file
Notes:See below
How PDEF Grid Interpolation Works
To illustrate how the data is interpolated from the native grid to the rectilinear grid, let's
consider an example. Here are a set of relevant records from a descriptor file:
PDEF 100 100 nps ...
XDEF 181 linear -180 1
YDEF 90 linear 0 1
These three entries describe data on a native 100x100 North Polar stereographic
projection and a rectilinear lat/lon grid that is 181 by 90 and has an interval of 1 degree in
both lat and lon. Consider one point within the rectilinear grid, the point -90,40. GrADS
calls an internal routine to calculate the i and j values in the native grid that correspond to
this lat/lon point. Let's say we get i,j values of 31.24 and 67.88. To do the interpolation to
the lat/lon point -90,40, GrADS uses the data values from the following four native grid
points: 31,67 - 31,68 - 32,67 - 32,68. Bi-linear interpolation is used within this grid box
to get down to the position 31.24,67.88. The interpolation is linear within the i,j grid.
When a descriptor file is opened that contains a PDEF record, GrADS calculates the i/j
values in the native grid that correspond to the lat/lon pair for each gridpoint in the
rectilinear grid.

19
How PDEF Wind Rotation Works
There is a third value calculated for every lat/lon point, and that is the wind rotation
value. With some "pre-projected" or native grids, the winds are given relative to the i/j
space and not the lat/lon space. To insure correct interpolation, the winds must be rotated
to lat/lon space. This is done by determining a rotation amount for each lat/lon point.
When u or v wind components are displayed, the values are not just interpolated but also
rotated.

To do the wind rotation properly, GrADS requires both the u and v components. Even if you are
just displaying u, GrADS has to retrieve (internally) both the u and v component in order to do
the rotation calculation. GrADS determines how to match u and v variables by checking the units
field of the variable record in the descriptor file. The u variable must have a units value of 33, and
the v variable must have a units value of 34. (This is the GRIB convention). If there are more
than one u/v pairs, secondary units values are used. For example:

u 18 33,100 U-Wind Components on Pressure Levels


v 18 34,100 V-Wind Components on Pressure Levels
u10 0 33,105 10 Meter U Wind
v10 0 34,105 10 Meter V Wind
might be some variable records in the descriptor file. If wind rotation is called for, u and v would
be paired, and u10 and v10 would be paired (since the secondary values would be checked, ie,
the 105,100 values).

The PDEF BILIN Option


When a descriptor file is opened that contains a PDEF record, we have explained that
GrADS internally generates three grids, each one the size of the rectilinear lat/lon grid.
The first two grids contain the i and j values (respectively) from the native grid that
correspond to each grid point in the rectilinear grid; the third grid contains wind rotation
values. But this only works for a small set of well-defined native grids. GrADS will
generate these three internal grids automatically for polar stereographic, lamber
conformal, and some eta grids. If the native grid for your data is not one of the predefined
projections, it is still possible for GrADS to handle the data. All you have to do is supply
these three grids to GrADS with a supplementary data file and use the bilin option in your
PDEF record.

The supplementary file will contains three lat-lon floating-point grids sized according to the XDEF
and YDEF records in the descriptor file.The three grids contain: i values, j values, and wind
rotation values. A value of -999 in the i-value grid indicates not to interpolate to that lat-lon point
(will end up missing on output) and a value of -999 in the wind-rotation grid indicates not to do
wind rotation for that point. If the wind-rotation grid is all -999 values, no rotation is ever done
and a flag is set not to even attempt rotation.

The PDEF FILE Option


All of the PDEF examples discussed so far involve the same method for grid
interpolation: a grid point value in the rectilinear grid is calculated by finding the four

20
neighboring grid points in the native grid and averaging them, with weights applied bi-
linearly according to their proximity to the to rectilinear grid point. The PDEF FILE
option generalizes this method so that an arbitrary number of native grid point values and
their weights are averaged to generate the interpolated rectilinear grid point values. The
index values for the native grid values that are to be used and their weights are specified
by the user in a supplementary data file (fname).

The num argument in the PDEF FILE entry specifies the number of native grid points that will be
used to calcuate each interpolated rectilinear grid point value. For each num, the supplementary
data file will contain two grids -- both will be the size of the rectilinear grid (as defined by XDEF
and YDEF). The first grid contains the index or offset values that point to the native grid value
that will be used in the interpolation; the second grid contains the weights for those native grid
values. The first grid contains integer values, the second grid contains floating-point values.
Finally, the supplementary data file must also contain one grid of floating-point wind rotation
values. Thus if num equals 1, there will be 3 grids in fname. If num equals 3, there will be 7 grids
in fname (3 sets of 2 grids plus the wind rotation grid).

To do the grid interpolation, GrADS will first read the data in the native grid (vector) along with
the values in the supplementary grids. To calculate the interpolated value for a particular lat-lon
point, GrADS will get num native grid point values, multiply each by their weight, sum over all the
weighted native grid points, and divide by the sum of the weights.

Native grid offset values of -999 indicate not to use an input point for that portion of the
calculation (thus you can apply less than the "num" number of interpolation points for some of
the points). So in theory this can be used for such things as thinned grids, staggered grids, etc.

An Example:

The original data are set up as a vector of land points only, taken from a 1-degree lat/lon grid.
There are 15238 land points in the native grid (vector). We use the PDEF FILE option to
repopulate a rectilinear lat/lon grid with the land values, leaving the ocean grid points as missing.
In this case, ther eis no interpolation done. The PDEF option is used simply to convert a vector
of land points into a 2D grid with ocean points missing. The descriptor file looks like this:

DSET ^gswp_vegetation_parameters.nc
DTYPE netcdf
TITLE Monthly Vegetation parameters at 1x1 degree
UNDEF 1.e+20
PDEF 15238 1 file 1 stream binary ^gswp.filepdef
XDEF 360 linear -179.5 1
YDEF 150 linear -59.5 1
ZDEF 1 linear 1 1
TDEF 204 linear 00Z01jan1982 1mo
VARS 1
NDVI=>ndvi 0 t,x Monthly vegetation index
ENDVARS

21
The supplementary file gtd.filepdef contains three grids -- the first contains the index values that
associate each location in the lat/lon grid with it's point in the vector. All of the ocean points will
have a missing value of -999. The second grid will contain the weights, which will be 1 for land
points, 0 for ocean points. The third grid will contain all missing values since wind rotation is not
a issue in this example. Here is a descriptor file for the supplementary data file (a useful strategy
for making sure you've got everything written out correctly):

DSET ^gswp.filepdef
TITLE PDEF file for GSWP Vegetation Parameters
UNDEF -999
XDEF 360 linear -179.5 1
YDEF 150 linear -59.5 1
ZDEF 1 linear 1 1
TDEF 1 linear 00z01jul1982 3hr
VARS 3
i 0 -1,40,4 Index Values
w 0 99 Weights
r 0 99 Wind Rotation Values
ENDVARS

22
back to top
XDEF xnum mapping <additional arguments>
This entry defines the grid point values for the X dimension, or longitude. The first
argument, xnum, specifies the number of grid points in the X direction. xnum must be an
integer >= 1. mapping defines the method by which longitudes are assigned to X grid
points. There are two options for mapping:

LINEAR Linear mapping


LEVELS Longitudes specified individually

The LINEAR mapping method requires two additional arguments: start and increment.
start is a floating point value that indicates the longitude at grid point X=1. Negative
values indicate western longitudes. increment is the spacing between grid point values,
given as a positive floating point value.

The LEVELS mapping method requires one additional argument, value-list, which
explicitly specifies the longitude value for each grid point. value-list should contain xnum
floating point values. It may continue into the next record in the descriptor file, but note
that records may not have more than 255 characters. There must be at least 2 levels in
value-list; otherwise use the LINEAR method.

Here are some examples:


XDEF 144 LINEAR 0.0 2.5
XDEF 72 LINEAR 0.0 5.0
XDEF 12 LEVELS 0 30 60 90 120 150 180 210 240 270 300 330
XDEF 12 LEVELS 15 45 75 105 135 165 195 225 255 285 315 345

23
back to top
YDEF ynum mapping <additional arguments>
This entry defines the grid point values for the Y dimension, or latitude. The first
argument, ynum, specifies the number of grid points in the Y direction. ynum must be an
integer >= 1. mapping defines the method by which latitudes are assigned to Y grid points.
There are several options for mapping:

LINEAR Linear mapping


LEVELS Latitudes specified individually
GAUST62 Gaussian T62 latitudes
GAUSR15 Gaussian R15 latitudes
GAUSR20 Gaussian R20 latitudes
GAUSR30 Gaussian R30 latitudes
GAUSR40 Gaussian R40 latitudes

The LINEAR mapping method requires two additional arguments: start and increment.
start is a floating point value that indicates the latitude at grid point Y=1. Negative values
indicate southern latitides. increment is the spacing between grid point values in the Y
direction. It is assumed that the Y dimension values go from south to north, so increment
is always positive.

The LEVELS mapping method requires one additional argument, value-list, which
explicitly specifies the latitude for each grid point, from south to north. value-list should
contain ynum floating point values. It may continue into the next record in the descriptor
file, but note that records may not have more than 255 characters. There must be at least 2
levels in value-list; otherwise use the LINEAR method.

The Gaussian mapping methods require one additional argument: start. This argument
indicates the first gaussian grid number. If the data span all latitudes, start would be 1,
indicating the southernmost gaussian grid latitude.

Here are some examples:


YDEF 73 LINEAR -90 2.5
YDEF 180 LINEAR -90 1.0
-85 -75 -65 -55 -45 -35 -25 -15 -5 5 15 25 35 45 55 65 75
YDEF 18 LEVELS
85
YDEF 94 GAUST62 1
YDEF 20 GAUSR40 15
The NCEP/NCAR Reanalysis surface variables are on the GAUST62 grid.

The final example shows that there are 20 Y dimension values which start at Gaussian
Latitude 15 (64.10 south) on the Gaussian R40 grid

24
back to top
ZDEF znum mapping <additional arguments>
This entry defines the grid point values for the Z dimension. The first argument, znum,
specifies the number of pressure levels. znum must be an integer >= 1. mapping defines
the method by which longitudes are assigned to Z grid points. There are two options for
mapping:

LINEAR Linear mapping


LEVELS Pressure levels specified individually

The LINEAR mapping method requires two additional arguments: start and increment.
start is a floating point value that indicates the longitude at grid point Z=1. increment is
the spacing between grid point values in the Z direction, or from lower to higher.
increment may be a negative value.

The LEVELS mapping method requires one additional argument, value-list, which
explicitly specifies the pressure level for each grid point in ascending order. value-list
should contain znum floating point values. It may continue into the next record in the
descriptor file, but note that records may not have more than 255 characters. There must
be at least 2 levels in value-list; otherwise use the LINEAR method.

Here are some examples:


ZDEF 10 LINEAR 1000 -100
ZDEF 7 LEVELS 1000 850 700 500 300 200 100
1000 925 850 700 600 500 400 300 250 200 150 100 70
ZDEF 17 LEVELS
50
back to top
TDEF tnum LINEAR start increment
This entry defines the grid point values for the T dimension. The first argument, tnum,
specifies the number of time steps. tnum must be an integer >= 1. The method by which
times are assigned to T grid points is always LINEAR.

start indicates the initial time value at grid point T=1. start must be specified in the
GrADS absolute date/time format:

hh:mmZddmmmyyyy

where:

25
hh = hour (two digit integer)
mm = minute (two digit integer)
dd = day (one or two digit integer)
mm = 3-character month
m
yyyy = year (may be a two or four digit integer; 2 digits implies a year between
1950 and 2049)
If not specified, hh defaults to 00, mm defaults to 00, and dd defaults to 1. The month and
year must be specified. No intervening blanks are allowed in the GrADS absolute
date/time format.

increment is the spacing between grid point values in the T direction. increment must be
specified in the GrADS absolute time increment format:

vvkk

where:
vv =an integer number, 1 or 2 digits
kk =mn (minute)
hr (hour)
dy (day)
mo (month)
yr (year)
Here are some examples:
TDEF 60 LINEAR00Z31dec1999 1mn
TDEF 73 LINEAR3jan1989 5dy
TDEF 730 LINEAR00z1jan1990 12hr
TDEF 12 LINEAR1jan2000 1mo
TDEF 365 LINEAR12Z1jan1959 1dy
TDEF 40 LINEAR1jan1950 1yr
back to top
VARS varnum
variable_record_1
variable_record_2
...
variable_record_varnum
ENDVARS

26
This ensemble of entries describes all the variables contained in the data set. varnum
indicates the number of variables in the data set and is therefore also equal to the number
of variable records that are listed between the VARS and ENDVARS entries. ENDVARS
must be the final line of the Grads data descriptor file. Any blank lines after the
ENDVARS statement may cause open to fail!

The format of the variable records is as follows:

varname levs units description

The syntax of varname and units is different depending on what kind of data format
(DTYPE) you are describing. Details provided below:

varname This is a 1-15 character "name" or abbreviation for the data variable.
varname may contain alphabetic and numeric characters but it must start
with an alphabetic character (a-z).
varname (GrADS version 1.9) For DTYPE netcdf or hdfsds, varname may have a
(DTYPE different syntax:
netcdf or
hdfsds) SDF_varname=>grads_varname

SDF_varname is the name the data variable was given when the SDF file
was originally created. For NetCDF files, this name appears in the output
from ncdump. It is important that SDF_varname exactly matches the
variable name in the data file. SDF_varname may contain uppercase
letters and non-alpha-numeric characters.

The classic varname syntax (i.e., when "SDF_varname =>" is omitted)


may be used if SDF_varname meets the criteria for GrADS variable
names: it must be less than 15 characters, start with an alphabetic
character, and cannot contain any upper case letters or non-alpha-numeric
characters.

27
levs This is an integer that specifies the number of vertical levels the variable
contains. levs may not exceed znum as specified in the ZDEF statement. If
levs is 0, the variable does not correspond to any vertical level. Surface
variables (e.g. sea level pressure) have a levs value of 0.

For DTYPE station or bufr, surface variables have a levs value of 0 and
upper air variables have a levs value of 1. (Exception to this rule for bufr
data: replicated surface variables are given a levs value of 2).
description This is text description or long name for the variable, max 40 characters.
The units component of the variable record is used for data with DTYPE bufr, grib,
netcdf, or hdfsds. It is also used for non-standard binary data files that require special
"unpacking" instructions, and special cases of pre-projected wind components. If the
data you are describing does not fall into any of these categories, put a value of 99 in the
units field.
units For flat binary files containing 4-byte floating-point data that are not pre-
projected, this field is ignored but must be included. Put in a value of 99.
units (GrADS version 1.9) For DTYPE bufr files, this field contains the x,y
(DTYPE pair for the named variable.
bufr)

28
units For DTYPE grib, the units field specifies the GRIB parameters of the
(DTYPE variable. This information is used by the gribmap utility for mapping the
grib) variables listed in the descriptor file to the data records in the GRIB files.
This parameter may contain up to four comma-delimited numbers:

VV,LTYPE,LEVEL,RI

where,
VV =The GRIB parameter number (Required)
LTYPE =The level type indicator (Required)
LEVEL =The value of the LTYPE (Optional)
The "range indicator" (for certain level types)
RI =
(Optional)
The external utilities gribscan and wgrib are quite useful in determining
what the values for the units field should be for a GRIB data file.
Examples:
u 39 33,100 U Winds [m/s]
t 39 11,100 Temperature [K]
ts 0 11,1 Surface Temperature [K]
11,116,60,
tb 0 Temperature, 30-60mb above surface [K]
30
17,100,100
dpt 0 Dew Point Temperature at 1000 mb [K]
0

29
units (GrADS version 1.9) For DTYPE netcdf or hdfsds, the units field is a comma-
(DTYPE delimited list of the varying dimensions of the variable. Dimensions expressed
as x, y, z, or t correspond to the four axes defined by XDEF, YDEF, ZDEF and
netcdf or TDEF. For example, a surface variable such as sea level pressure might look
hdfsds ) like this:

presSFC=>psfc 0 y,x Surface Pressure

A time-varying atmospheric variable such as geopotential height might


look like this:

Height=>hght 17 t,z,y,x Geopotential Height (m)

The order of the dimensions listed in the units field does matter. They must
describe the shape of the variable as it was written to the SDF data file. For
NetCDf files, this information appears in the output from ncdump next to the
variable name.

If your data file contains a variable that also varies in a non-world-coordinate


dimension (e.g. histogram interval, spectral band, ensemble number) then you
can put a non-negative integer in the list of varying dimensions that will become
the array index of the extra dimension. For example:

VAR=>hist0 0 0,y,x First historgram interval for VAR


VAR=>hist1 0 1,y,x Second historgram interval for VAR
VAR=>hist2 0 2,y,x Third histogram interval for VAR

Another option in this example would be to fill the unused Z axis with the
histogram intervals:

zdef 3 linear 1 1
...
VAR=>hist 0 z,y,x VAR Histogram

In this case, it would appear to GrADS that variable 'hist' varies in Z, but the
user would have to remember that the Z levels correspond to histogram
intervals. The latter technique makes it easier to slice through the data, but is
not the most accurate representation. And if you don't have an unsued world-
coordinate axis available, then you still have a way to access your data.

30
units For non-standard binary files, the units field is used to instruct GrADS
(non- how to read binary files that do not conform to the default structure or do
standard not contain 4-byte float data. GrADS assumes the data were written in the
binary) following order (starting from the fastest varying dimension to the
slowest): longitude (X), latitude (Y), vertical level (Z), variable (VAR),
time (T). If your binary data set was created or "packed" according to a
different dimension sequence, then you can use the units field to tell
GrADS exactly how to unpack the data.

For these non-standard binary files, the units field is a series of one or
more comma-delimited numbers, the first of which is always -1. The
syntax is as follows:

-1, structure <,arg>

There are four options for structure, outlined below. Some of these
options have additional attributes which are specified with arg.
-1,10,ar This option indicates that "VAR" and "Z" have been
g transposed in the dimension sequence. The order is: longitude
(X), latitude (Y), variable (VAR), vertical level (Z), time(T).
Thus, all variables are written out one level at a time.

This feature was designed to be used with NASA GCM data


in the "phoenix" format. The upper air prognostic variables
were transposed, but the diagnostic variables were not. Thus
an arg of 1 means the variable has been var-z transposed, and
an arg of 2 means the variable has not.
-1,20,ar This option indicates that "VAR" and "T" have been
g transposed in the dimension sequence. The order is: longitude
(X), latitude (Y), vertical level (Z), time(T), variable (VAR).
Thus, all times for one variable are written out in order
followed by all times for the next variable, etc.

If your data set is actually a collection of separate files that


are aggregated by using a template, then you must use arg to
tell GrADS how many time steps are contained in each
individual file. For example, here are the relevant records
from a descriptor file for 10 years of monthly wind and
temperature data packaged in 10 separate files (one for each
year) with "VAR" and "T" dimensions transposed:

DSET ^monthlydata_%y4.dat
OPTIONS template
31
TDEF 120 linear jan79 1mo
VARS 3
u 17 -1,20,12 U-Wind Component
v 17 -1,20,12 V-Wind Component
t 17 -1,20,12 Temperature
ENDVARS
-1,30 This option handles the cruel and unusual case where X and Y
dimensions are transposed and the horizontal grids are
(lat,lon) as opposed to (lon,lat) data. This option causes
GrADS to work very inefficiently. However, it is useful for
initial inspection and debugging.
-1,40,ar This option handles non-float data. Data are converted to
g floats internally after they are read from the binary file. The
dimension sequence is assumed to be the default. The
secondary arg tells GrADS what type of data values are in the
binary file:

units = -1,40,1 = 1-byte unsigned chars (0-255)


units = -1,40,2 = 2-byte unsigned integers
units = -1,40,-2 = 2-byte signed integers
units = -1,40,4 = 4-byte integers
units For pre-projected vector component data that require the use of PDEF and
(pre- rotation, GrADS has to retrieve both the u and v component in order to do
projected the rotation calculation. GrADS determines how to match u and v
wind variables by checking the units field of the variable record. The u variable
components) must have a units value of 33, and the v variable must have a units value
of 34. (This is the GRIB convention). If there are more than one u/v pairs,
secondary units values are used.

32
Doing GRIB in GrADS
Introduction
What is GRIB?
The Problem
Up-front Limitations
The Solution - Part 1
The Solution - Part 2
Conclusions

INTRODUCTION
One of the most powerful features of GrADS is its ability to work DIRECTLY
with GRIB data. Unfortunately, "doing GRIB in GrADS" is not simple; it requires
an understanding of GRIB and how GrADS works this type of data.

This note attempts to provide the required understanding to use GRIB data in
GrADS.

WHAT IS GRIB?
GRIB (GRIdded Binary) is an international, public, binary format for the efficient
storage of meteorological/oceanographic variables. Typically, GRIB data consists
of a sequence of 2-D ( W%a.W ) chunks of a (in most general sense) 4-D
variable (e.g., W,%%"C W%a.Wa)",7C ).
The sequence is commonly organized in files containing all variables at a
particular time (i.e., W W%a.Wa)"
;,
 ).

THE PROBLEM
The problem for the user is how to "interface" or "display" GRIB file(s) to
GrADS. The solution has two components. The first is to see what is in the GRIB
file, i.e., variables, grids, times, etc. and the second is to "map" the 2-D GRIB
fields to higher dimensional structures available in GrADS.

33
UP-FRONT LIMITATIONS
There are some limitations on the kinds of GRIB data that can be
interfaced/displayed in GrADS:

a) lon,lat grids (NOT lat,lon)


b) simple packing
c) grid point data
d) grids must be contiguous (no blocked or octet grids)

Thus, "thinned" grids (non rectangular) and spectral coefficients are not
supported. However, GRIB versions 1 AND 0 are supported (GRIB 0 data must
be filtered to GRIB 1 for wgrib (see wgrib) and version 1.7 of GrADS will
support such non-rectilinear grids. Further, it IS possible to display "preprojected"
GRIB data (e.g., polar stereo fields, see eta.ctl).

THE SOLUTION - PART 1


The first, and relatively straightforward, part of the solution is to find out what is
in the GRIB file. I use two utilities:

1. gribscan (comes with GrADS);


2. wgrib

The big virtue of wgrib is that the code is written in ANSI C and runs on all the
major platforms from PC's to Cray. Although wgrib was designed to support the
NCEP reanalysis project, it has been extended to handle other sources of GRIB
data (e.g., ECMWF) and is my tool of choice. If I can't read the data in wgrib then
I change the code and feed the changes to Wesley Ebisuzaki, NCEP.

Once you have wgrib running,



   "!$#
%& 


yields,
' *( )+(-,./$0
)')')
)+(213
456(78, 9 :;.<
<=(78, 9$>.')
)+(78, 9/$.?@:;)+(
A 4.'
' <=(BC'.
)+(BD.C>E( AFHGI 1C.' (-?@:;)
GCJ ("KLM("KN IO >PQR(S$TCN I .'D$U
DE(-'@:V?@:HDE(-,./$0
)')')
)+(213
456(78, 9 :;.<
<=(78, 9$>.')
)+(78, 9/$.W:
)
)+( A 4.'
' <=(BC'.
)+(BD.C>E( AFHGI 1C.' (X:;)
)
GCJ ("KLM("KN IO >PQR(S$TCN I .'D$U

34
Y Z[Y
Y\]
^ Z-_`a$b
\]\]\
\+Z2cd
ef6Zgh_ i j;`Y
Y=Zgh_ i$k`]\
\+Zgh_ ia$`Cl
=
\
\+Znme`]
] Y=ZoC]`
\+Zol`CkEZ2mpHqrcC`] Zsl\
\
qCtZ"uvwZ"ux ryCkz{RZ|$}Cx r`]l$~
~RZXjV]~b^ Z-_`a$b
\]\]\
\+Zd
ef6Zgh_ i j;`Y~RZgh_ i$k`]\
\+Zgh_ ia$`^
j;\+Znme`]
] Y=ZoC]`
\+Zol`CkEZ2mpHqrcC`] Z-^@j;\
qCtZ"uvwZ"ux ryCkz{RZ|$}Cx r`]l$~
jZsk
k\Y$kEZ-_`a$b
\]\]\
\+Zd
ef6Zgh_ i j;`Y~RZgh_ i$k`]\
\+Zgh_ ia$`Wj
\
\+Znme`]
] Y=ZoC]`
\+Zol`CkEZ2mpHqrcC`] ZXj;\
\
qCtZ"uvwZ"ux ryCkz{RZ|$}Cx r`]l$~
kEZ-^
]
^
^
^ Z-_`a$b
\]\]\
\+Zd
ef6Zgh_ i j;`Y~RZgh_ i$k`]\
\+Zgh_ ia$`Cl
\
\+Znme`]
] Y=ZoC]`
\+Zol`CkEZ2mpHqrcC`] Zsl\
\
qCtZ"uvwZ"ux ryCkz{RZ|$}Cx r`]l$~
aZ*b
b
\Wj~RZ-_`a$b
\]\]\
\+Zo
e
Zgh_ i j;`] Zgh_ i$k`]\ClEZgh_ ia$`
\+Z
me`]
] Y=ZoC]`
\+Zol`CkEZ2mpHqrcC`] ZRZ"uvwZ"ux ryCkz{RZ|$}Cx r`]l$~

So we see 7 fields in the file valid at


$ ( $

).

for,

 "$
CE


we find,
*+-$
C
+2
6 ;
= $
+ $@;+

=C
+CE H C -@;
C ""  R$C 

E-@V@HE-$
C
+2
6 ;
= $
+ $W

+ 
=C
+CE H C X;

C ""  R$C 

=[

-$
C
+2
6 ;
= $
+ $C

+ 
=C
+CE H C s

C ""  R$C 

X;
-$
C
+
6 ;  $
+ $
;+ 
=C
+CE H C -@;
C ""  R$C 

s 
E-$
C
+
6 ;  $
+ $W

+ 
=C
+CE H C X;

C ""  R$C 

E-W -$
C
+
6 ;  $
+ $C

+ 
=C
+CE H C s

C ""  R$C 

*C
E-$
C
+

 ;  $CE $


+

=C
+CE H C R""  R$C 


35
or the same fields as before, except they are valid at
CC$ .

To find out about the data grid use,



H "$
 


and for the first record you will find:


;VX   X
;;  V  ;;  "
  V   !"#%$X & ' s)(* +  ,V
-
. @
 &(H V +$;n  0/n1/ +
2 33+4  5)$ 6&Xn
+7
(
8'&,+98, Vn 0(&
&+$
X9 + , 7*HX9 + n ) X
 X  9 +@  X  ; : = <> : 
*
4?@:A "

+$ > : = <
@:A "  *
4?@:A " ;
B*332
 6#X, +  *;; $X &
(&+C9(, 2 X1 <X @:"   ;:D +7
(=*6&X;   E 5F86; G1<   
V 5  1 )E&,+5 

The grid is the NCEP #2 grid (see the Gospel According to John) which is a
global 2.5 deg grid. The grid has 144 points in x ( HJILK ) and 73 points in y ( MONJP ).
The (1,1) point is located at QORS and TU .

THE SOLUTION - PART 2


This is the hard part -- creating a relationship between the sequence of 2-D
( VJWLXZY[VO\J] ) GRIB fields in a file(s) and the GrADS, 4-D, external-to-the-data,
spatio-temporal data volume ( ^J_L`Za[^ObJcda[^e'fge!^haickjl;e ). In GrADS, the GRIB-
to-4-D volume relationship is defined by the mknJoknpm!qsrJt'ugvwsoOxJu or y[zJ{k| file.
The actual relationship is created using the GrADS utility }O~gJ> which
generates an "index" or "map" between GrADS variables in the [Jk file and the
GRIB data.

Before describing the details of OgJ> , first consider the unix shell script,
Og!Jkh
, originally written by Wesley which I have adapted to help me out.
This script uses sOg to first create a listing of fields in the GRIB data file and
then parses the listing for times, variables and levels for the [Jk file.

See,

http://wesley.wwb.noaa.gov/grib2ctl.html

In our example,

36
Og!Jkh@'Zs!@h@d[LO!dO

yields to standard output,


gL@'Zs!@h@d[LO!dO
OLOgOg
LskJL>!s'
s!'@'Zs!@h@d[LO!dOZLk
s!!LAO!@O
kJk@'Zs!@h@d[LO!dO
s!!pJOOg!'

s!!kpOg!'LO

!!p'g!k
 OJO
O!!pOg!'OsL!s@L@
@';
O g ikA ssO s
!OJ O iO p s Ag@>
sOJ  iOp s Ag@>

'sL@';

How did Og!Jkh do this? First, only ONE grid was found in the GRIB
data file (defined by g ) and the script had the grid geometry built in. Second,
variables with multiply levels (3-D or  
  
 ) where DEFINED to
have a "level indicator" of 100 (more below). Third, there was only ONE time in
the file and the script SET the time increment to 1mo.

These conditions will often not be present. Thus, the output from  !
will likely have to be "tweaked" by the good 'ol trial and error method. In some
cases the "
#$% file may have to built "by hand" using the output from &(' )*,+ , so
you'll probably have to know a lot about GRIB and how - ./,0132,4 works in
many situations.

The key ingredients in the 5


678 file are:

9;: <=>?:(@A,BC@D<E FHG(>@IJKE(>@ICL


MONPQRPS,TUVPS!WCXYQ,T(Z[PS!WCXYS,T]\R(X^WCXT(P _`P ZXaCb
c?d]efg e,h]ij(k?e,l(m npo l]gqknsr]efe!tCjqjf
u?v]wxy w,z]{|;}~ |Y^{|v|{Cx^ p|Cx !x w |3
p^

The units parameter specifies the GRIB parameters of the variable in the
 to

37
be used by ,3, for match GrADS variables to the fields in the GRIB files.
This parameter consists of up to four, comma-delimited numbers:
( ( H]]

where,

- (Required) The GRIB parameter number (33 = u comp of the wind,
table 2 in John:section 1 page 27, i.e., GRIB Edition 1 (FM 92))
(
- (Required) The level type indicator (100 = pressure level, in
Table 3 in John:section 1 Page 33)
(
- (optional) The value of the LTYPE (LTYPE 102 is mean sea
level so LEVEL is 0 for where level is located (1,102,0, 0 is AT mean sea
level)
]
- (optional) The "time range indicator" for special applications (Table
5 in John:section 1 Page 37).

Coming up with the units parameter, the grid geometry and the times is the trick.

Fortunately, ,3, can tell us how well the


 mapped the GRIB data to
the higher dimensional, GrADS data view. And, more importantly, the ,3,
process does NOT depend on how the data are actually ordered in the GRIB file,
in either level or variable.

Let's redirect output from ! to a


 file, e.g.,
![] (,]]
  V
] (,]]


and then run ,3, . To reiterate, the ,3, utility compares each field in
the GRIB file to each variable, at each level and for all times in the  file and
creates an index file telling GrADS WHERE the fields are (or are not) located in
the GRIB data.

With the verbose option on,



     !" #$%

we get,

38
&('*),+*+.-/+*0213-,+3),4(576*8.9,:<;*-(=(>@?A3BC
+3'D>FEGH4I>J),+3=GLK.MNGPOFQ(RJSGT0D4*1
U(U*U(U*UWV*XJY.Z/[ C\S S]^]`_ _ S R a(abS(R(R7^]cR21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ Cj_ a*aeRJS(^ _ S R a(abS(R(Rk]R(R21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ Cla ]`SDm*Q*^ _ S R a(abS(R(Rn_DR(R21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ Chm o*oDRpa,o _ S R aem7S(R(R7^]cR21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ Cq] ^*S(^*^(^ _ S R aem7S(R(Rk]R(R21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ C\o Q*Q(R@]cm _ S R aem7S(R(Rn_DR(R21IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
U(U*U(U*UWV*XJY.Z/[ CrOsS(S*o*_*_FR _ S R StS(RJ_sR 1IdJ-eKfC
SDQ.O/Q*R*S(R*S(R(RCHR*R7dJ)/gChR7i*dJ-eKfC\SDQ.O/Q*R*S(R*S(R(RCHR*R
8J>J)('/uI>(isv(wIx

We
yz{have
| succeeded!!!
{  y Each
z 2-D in the GRIB file has been mapped to a variable in
}~ }"$} . In the case of  , a 3-D ( @$
 )
variable which we can be sliced in the vertical with GrADS. However, failure to
match will NOT stop GrADS from "working." If the data was NOT there, GrADS
will return a grid with "undefined" values on display and this state can actually be
tested...

The "tweaking" is done by adjusting the  file until we get a b

for each GRIB field in the data file(s). I have added a number of options that
finely control the mapping process in 
 for NCEP. See the GrADS
document for details (ftp://sprite.llnl.gov/grads/doc/gadoc151.*).

Finally, let's adjust the  !"$ file to take advantage of the file
naming convention:

@  !"$"
pN
@


@@p
  !"$@
@
 !"$@$

D

@D

I I

@ @ 
N

   f
   


39
 p  

@N
I have changed the number of times to two and have used the template

option.
This
 tells
GrADS
  tolocate
 !data
"#in$!
TIME
% by the file name (
). Thus, I have two (or more) data files, but
only ONE &('*)+ file and I can now work with the 2-D GRIB data as if they were
4-D ( ,*-./(,!0*1/(,
23/41576"2 ) in GrADS. I also changed the name of the index
file to be reflective of the now 4-D data structure.

To summarize the process:

8 use 9:!;< = (or >!?@ ACB*D!E F ) to see if the data can be worked in GrADS;
G use H!I
JKL*MNPORQ7S or the output from TU!VW X to construct a Y(Z*[\ file;
] run ^!_` a*bCc d in verbose mode ( e f ) to relate the GRIB data to the 4-D
structure in the g(h*ij file, and to see how well the map worked; and
k repeat steps 2) and 3) until you get l!l!l!lnm!opqr from s!tu v*wCx y .

CONCLUSIONS
There's no doubt about it, "Doing GRIB in GrADS" is not very straightforward,
but the benefits are, in my opinion, immense for two reasons. First, we have
avoided conversion of the GRIB to a form which supports higher dimensional
data (e.g., z{
|} ~ ). We've saved disk space and have minimized potential
technical errors (every time you touch the data you have an opportunity to screw it
up). Second, from a GrADS performance standpoint, GRIB is nearly as fast as
other binary formats -- the cost in decompression on the fly is compensated by
reduced I/O.

In the end, GRIB-to-GrADS interface gives us the advantages of GRIB (efficient


storage, self description and an open, international format) while overcoming the
disadvantages of GRIB (2-D data and no means to organize to a higher
dimension) via the GrADS 4-D data model. We get the best of both worlds, but
only if we can make the (* file. Hopefully this document will help you do this.

40
sdfopen
*!!*"7C

Opens a NetCDF or HDF-SDS format file that conforms to the COARDS conventions.
The arguments and options are as follows:
!!
*The
" name of the COARDS-compliant NetCDF or HDF-SDS file.
This optional argument is used when you want to aggregate multiple data
files and handle them as if they were one individual file. The individual
data files must be identical in all dimensions except time. *" has
a similar structure to the substitution template in a GrADS data descriptor
7file.
CSee
Using Templates for details.
This C must be included whenever *" is invoked. The
7argument
is the sum of the timestep counts in all the files to be
examined, not the count in any one file.
"

1. Any particular data file in the group described by the *" is automatically
accessed as the "time" or "t" settings in GrADS are altered.

2. Use * to open a non-COARDS-compliant self-describing file.

3. For additional information, see The Self-Describing Files (SDF) Interface.


"

1. If you had daily U-Wind data in two files, *4



 and
*4 , you could access them both as one GrADS data set by
entering:

 
 
  
 !"# 
%$
&'(!"*)
+-,

41
xdfopen
./
0 123465789;:=<;>?9

GrADS requires a certain amount of metadata in order to understand how to read a


NetCDF/HDF-SDS data file, also called a self-describing file (SDF). The @A
B CDEF
GH
I JKLM assumes all the metadata is internal to the self-describing file, whereas the
command
command allows the user to supplement or replace any internal metadata via a
data descriptor file. In this way, NO
P QRST provides access to some self-describing files
that do not comply with the COARDS conventions.
UVWX;Y=Z;[?X
is the name of the data descriptor file that contains the supplemental
metadata. It has a syntax very similar to the regular data descriptor files that are used with
the \]^_ command. The few differences are noted below:

1. `bacd egfhjilkmno;p=q;r?o

This is the only required entry. sgtujvlwxyz;{=|;}?z may be either the name of a
netCDF or HDF-SDS file or a substitution template for a collection of netCDF or
HDF-SDS files.

than ~b , the only other data descriptor file entries that are supported are
Other
, b , 

, 

, 

, b ,  , and   .


Valid arguments
b
-=for  b entry are: 
  and

the
.

2. 

, 

, and 

Each of these entries requires an additional argument, gjg?; j-=;? ,


which comes before all the other arguments. The gjg?; j-=;? is
used to achieve dimension order independence, so it must be a real dimension in
the SDF. The gjg - 
; string may
be
 mixed case and should
appear exactly as it is listed in the output from .

If the coordinate variables in the SDF file exist and have the required metadata,
then !"# $ is the only argument needed for the corresonding
variable definition entry (%'&()+*-,.&()+*0/1&()+* and 24356 ) in the data
descriptor file.

3. The first argument (" 7894: 8;< ") of the variable definition lines that appear
between ='>?@ and A'BC4D'EFG has a slightly different syntax:

42
HIJKMLNO4P NQRS'TUVW'X4Y[ZM\WV4] W^_
` abcMdef4g ehi
j klmno . It may isbethe name of the variable as it appears in the output from
of mixed case and include blanks.

If everything up to and including the prq'stp is omitted, then uvw'x4y[zM{wv4| w}~


must be identical to M4  . This syntax (when " M4 ' " is
omitted) will only work properly in GrADS if M4  is less than 15
characters and does not contain any upper case letters.

As it was with the coordinate variables, if the data variables in the SDF file have
the required metadata, then M4 ''4[M4  is the only
argument needed for the corresonding variable definition entry in the data
descriptor file.

4. The order of the variable definition lines between VARS and ENDVARS is not
important. Unlike in data descriptor files for the  command, the variables
that do not vary in Z do not need to be listed first.
.

1. If ''   contains only the DSET entry, then  devolves into
working just like  .

2. ''  
does not need to be a full data descriptor file, it only needs to contain
whatever metadata the SDF file lacks. Anything not specified in ''   will
be looked for in the file's internal metadata.

3. The #  parameter in the XDEF, YDEF, TDEF, and ZDEF


entries and the first parameter of the VARIABLE definition lines are the only
parts of the data descriptor file that aren't converted to lower case before they are
interpreted.

4. For further information on the COARDS conventions, check out Conventions for
the standardization of NetCDF files.


1. This example shows the data descriptor file that would be required in order to
open a self-describing file that is missing much of the required metadata. Below is
the sample data descriptor file for the NetCDF file moisture.nc. Follow this link to
see output from ncdump for this file.

43

 
!"!##$ %&
'()!*****+-,
."")/$ 0011 2!2334(56,+-,879;:
<"")/$ 0011 7 =">?4(56,+-,879;:
1"")/$ 0011 @>!>A@:B4(56,C,2D45("2*=*E21<
F56G2
H 1IJ  !2!**KH ""1
(1F56

2. This second example comes from a real-world HDF-SDS file from the Data
Assimilation Office at NASA Goddard Space Flight Center. The data descriptor
file is shown below, and this link shows the output from running the HDF version
of ncdump on LNMPORQRSUT"VWMYX[Z]\P^ . (Note that the output has been annotated with
explanatory comments -- they are preceded with "//")
_`ab
c4_1dea"fhgjidlkm"no
bpbqabmrs!r"sKtuv4wyxGz{sz
e|bpe}`~a
}_ak-f1a@g
_"a"K_r U_1derniiqp4}ad1fkf8kg
~_"a"~"_r U_1dern !qp4}ad fkf8kf
_"a"Gb"_0p$@`]_d"e"1rn!q1a1"a"q`GfffE@gfffgjffiffy4ff8@gf
ffE@gjfE1fffgfy4fE1fg!!fki
b1_"a"Gbp$ai1_p 0`9_1der1n!iqp}a1df"1q"10"
d`8
ae|eba}bp dqap4b"m"z!"{ttz"{uz"rxvm{"rm"z
`|a"pp110p4_pb~s4m1
!
s {rorm0r1n"r1zw
ba1|ad"baz"{ "8!Ez"{ {x1z{
a}_1d`

44
Reinitialization of GrADS
Two commands are available for resetting or reinitializing the state of GrADS:

Reinit

The ]R@ command returns GrADS to its initial state. ]R@ closes all open files,
releases all defined variables, and resets all graphics settings to their defaults.

Reset

The ]]WN command returns GrADS to its initial state with the following exceptions:

1. No files are closed


2. No defined variables are released
3. The WNPP@ settings are not modified

If files are open, the default file is set to 1, and the dimension environment is set to X,Y
varying and Z and T set to 1 (as though file 1 were just opened).

The ]]WN command may be qualified so that only certain aspects of GrADS are
returned to their initial state. The qualifiers are as follows:
]]WN h 9h]9 resets the events buffer (e.g., mouse clicks)
]]WN 9@P resets the graphics, but not the widgets
]]WN  resets the display buffer when in double buffer mode
]]WN ]+WN resets the X events only

45
Command line editing and history
If the ]RP@9 library compiles on your system then the default prompt will be 9W
as opposed to 9W . This indicates that command line editing is active. The library
defaults to 0P mode but can be set up to run using  syntax.

Here's a list of the commands which may typically be used:


9 go to beginning of line
9  go to end of line
 
 go forward one char
   go backward one char
  delete the char
  recall previous line
! "#$ recall next line
%&' ()*' reverse search

You also get +,-.0/21435.7683:92-.;:,8</ using the =:>? key. If there is more than one
option, then @A<BC2DEGF:HC will list the available completions.

For example, suppose you are running grads on div40-2 at FNMOC and want to start
looking for files to open...

Type I<J K*LNMO and get,


P QR<S7T<U V*WNXY
_bac5hitdg two Z:[\^] and get:
_`_bac5d0_bac5defand

then type hi5jk and l:mnol:mn and get,


p qr<s7t<u v*wNxybtz5v{x
|b}}0~ tp^<2pw<ubt<u^wz^t ~ :tvb<v<:
|2 :*bv*7p q t *bt<wbfu2qv<N q
t q<y`y2q4z^t<wz5v*wb<y2qu2q*:f^
< t:qw`ybt<bfw2ybt::*t`:t<u^

then type  , : to go to GRIB dir, followed by , : to go to the dat dir and then ,
:o:
gives,
<7< *Nb52:b ^^

b ^^: b ^^:
b ^^: ^

46
b ^^: ^
b ^^:2 b ^^2:
b ^^:: b ^^2 ^
b ^^: b ^^:^::
b ^^: ^ b ^^:^::
b ^^::<2 b ^^::<:

and type :: to get


<7< *Nb5 :
b   

b   2 b    !#"

b   #"
 b    !
b    b    !%$^
b   %$^
b    !2

and finally open the & ' ( data with 12.c, )*+ , return to open the file
,.- /%01 234 53657489 8 4!3#: ;<
=?>A@CBEDFBHG

There is no guarantee that these I.J K LMNO%J routines will always work, so the PQ option
has been added to the invocation of GrADS to turn them off.

47
External Utilities
gribmap
gribscan
gxeps
gxps
gxtran
ncdump
ncgen
stnmap

gribmap
The GrADS data descriptor file defines a grid structure into which the data will fit -- it
gives "shape" to the data by identifying its spatial dimensions, the number of time steps,
and the number of variables.

If the data is in binary format, its structure has already been prescribed. If the data is in
GRIB format, no consistent relationship exists between the data and the grid structure
defined in the data descriptor file. Hence, the need for the RS%TU V WX utility which "maps"
between the GRIB data and the GrADS data description.

As YZ%[\ ] ^_ reads each field in the GRIB data file, the parameters for that field (e.g.
variable name, vertical level, time) are compared to the information in the data descriptor
file until a match is found. The process continues until all the GRIB elements have been
"mapped" to their location within the GrADS grid structure.

The syntax for the `a%bc d ef command is as follows:


gh%ij k lm npoirqsutwvyx%z|{p}~z|{p} yz|{p}yz|{p} |p|p


The options are as follows:


uwy
The name of the data descriptor file. If not specified, %  will
prompt the user.

Produces verbose output to make it easier to verify what is being mapped.

48

%  will only match those grib records whose base time is the same
as the initial time in the data descriptor file. This is used to pull out a
forecast sequence (0, 12, 24, ... , 72 hours) starting a specific time.


%  will ignore the forecast time when setting up a match. This is
useful for reanalysis data sets in which some diagnostic fields are "valid"
at slightly different forecast time even though the share the same starting
time.


%  will only match those grib records whose forecast time is
hours. This is used to isolate a sequence of forecasts. For example, if you
wanted to sample all the 120-hour forecasts from the MRF ensemble runs,
you would use %  .


%  will scan over no more than  bytes when searching for the
character string "GRIB" in each header. The default is 1000.


%  will skip over  bytes before starting the scan process. If
reading a special NMC format of GRIB data, use  .

#  feature was added to map by the GRIB "time-range-indicator" as specified in the


Another
file. This was put in for handling NMC reanalysis data where the time-range-
indicator distinguishes between monthly mean variances and means.

49
gribscan
The %  utility is used for extracting grid info from GRIB data files. Its features
include grid/product information, gridded output in ASCII, binary, and/or grib format,
plus automatic "scanning" for GRIB records so that you don't have to know the physical
layout of the data to scan it.

The command sytax is:


%  pr 
  !#"%$&')(+*+, - .
/0+1'24355 6748 1#/%9&6'1)7+5+: ; <'=>@?BADC'EFHG#A%I&>'G)J+?+K

Where:
LMNOPQ
This is the input grib file name. If RSHTUVWXY is omitted, Z[\]+^ _`a
will prompt the user for a file name.
bcdefg

This is the output file name WITHOUT an extension. If h ijklmno is


omitted, a default file name of prq@s t'uvxwzy{}|#~ is created where }#
@
is:
- ascii
4 - GRIB
@
- a stream of floats (GrADS format)

File Options:

+ 
will return output in GRIB format

@
+  will return output in ASCII format (%8g in C-language
syntax)

@
+ 
will return output as a stream of floats. This is machine
dependent and is 64-bit on Crays and 32-bit elsewhere.

50
Processing Options:

@}
Specifies the max number  of bytes between GRIB messages in the
file. The default is 500 and it is assumed that you want to ignore junk (e.g.,
comm stuff) between data.

@

Selects parameter #  (e.g.,@' for temperature)

@ r

Selects level #  (e.g., @& to get 500 mb fields)

@r 

Selects tau #  (e.g., @r to get t=12 forecasts)

B

Specifies a fixed file header of  bytes. If omitted, the default is to seek


the first GRIB message automatically, but if you know  , it is more
efficient to specify it.

Special note to NMC users: The once "standard" 81-byte header in an NMC GRIB
file contained the string "GRIB". Unfortunately, the same string is part of the
GRIB indicator section itself! Thus, an automatic scan for GRIB to demark the
start of the data will fail if the 81-byte header is present! When in doubt (or
failure) try using the ' option.

Note: These processing options can be used simultaneously to output a very


narrow set of fields.

Display options:

Quick output to extract stuff GrADS gribmap cares about


 One-line quick output
Comma delimited mode
 Verbose mode for diagnostics
' Binary data section info
r4 Uses the NMC GRIB variable table to output mnemonic, title, and units

51
r@ Output info from the grid defn sec
 Silent mode; NO standard output
x

1. A "quick" scan to get the info GrADS cares about:


+ 
4  
!

Gives the result:


"#$&%(')%("+*+,-%(" .#)%(" ../%0./%(" ../%0./%("12.3/%45%(" 33 $&%(#)%763/%("68%0./%(")%
$#)%0./%9&%(" . $&%:;49&%03 $.#63"6

Where:
<=>
? field # in the file
@+A+B field data
C DE param #
F GG level indicator
H level
I JJ l1 byte 1 of level
K l2 byte 2 of level
LMNOP time range indicator
Q decimal scale factor
R SS T time data follows
U year
VW month
XY day
Z hour
[ min
\] forecast time unit (hour)
^ t=48 h forecast
_ ` a grid param follows
bcde NMC grid #104
Base date-time-group (yymmddhh) follows

2. Comma delimited output:


fg+hikjlmnop oh q rmstuvwsxyg iz{| }~fgq !u|{

Gives the same results as the previous example but arranged differently:

52
(&( &(++-( )( /0/( /(  &()7/(80/())0
0/(

3. A full listing:
+k      ~


Gives the following results:


(&( &(++-( )( /0/( /(  &()7/(80/())
/0/(/k5+  
+ 8  k-(+( /
+/+-0/-0/+&/7 )
-0/+ 80/0/()0/(8
8(&( /k/7

Where:


grid id
++++ mconv,Horizontal moisture divergence,[kg/kg/s]

8( binary data section
k ref value 16170 - # of points
 starting byte of the data
length of the grib message

Note that eliminating the  option would result in a fixed-column type output.

4. Output a selected few fields in GRIB:


+k
   ! "#$
%  

&'( out all GRIB message containing the 135 parameter to the file
Writes
)%*+,-) ./0 . A subsequent execution of 123465789 on :;<=%>?@-= ABC
would return:
DFEHG E%DIJ-E%DKLFE%DKKMENKME%DKKMENKME%DOPKQME
R E%DQQSTE%LFEVUQME%DUWENKME%DFE SLFENKMEYX E%DKSTEYZ[ R XTE\QSKLUQDU]UWE
GFE%DIJ-E%DKLFEVUDL^KME%L_J-E%DKKMENKME%DOPKQME R
E%DQQSTE%LFEVUQME%DUWENKME%DFE SLFENKMEYX E%DKSTEYZ[ R XTE\QSKLUQDU

53
gxeps
`abdc6e fhg i jlk
mndoqpr]sutvdtwyxtnyz|{ sl}~v}  xtnyz|{ dyy|

Converts the GrADS metacode format file to a PostScript file. Where:

]_ identifies input GrADS metacode file


_ identifies output postscript file
 prints color plot
d prints on a black background
 appends CTRL-D to the file, useful if printing on a

HP1200C/PS color printer
use PostScript Level 1 (default)
 use PostScript Level 2
 Page size A4
 Page size US-Letter
d Ask for a label to be printed on the plot
 Ask for a note to include in PostScript file header

 Add a file and time stamp on the plot.
 Verbose mode.

Usage Notes

1. The default behaviour of d6 is to create a grayscale plot on a white


background. The GrADS default rainbow colors (color numbers 2 to 14) are
converted into appropriate grey shades. User-defined colors (numbers above 15)
are translated to greyscale intensity based on their green content only.
2. For more information, see the section in the User's Guide on Producing Image
Output from GrADS.

Examples

1. d6
Prompts user for the input and output file names and convert to greyscale on white
background with page size A4.
2. d6d]  dF6]  dF6
Converts GrADS metacode format file qdl66 to a color plot on black
background and outputs the result to PostScript file qdl6 .

54
gxps
6 hq6udyy| l~ y| ]

6 is a UNIX utility that converts the GrADS metacode format file to a PostScript
file. Command line arguments and switches are:

  

   identifies input GrADS metacode file

 identifies output postscript file

 prints color plot

  prints on a black background


appends CTRL-D to the file, useful if printing on a
HP1200C/PS color printer

Usage Notes

1. The default behaviour of  


is to create a grayscale plot on a white background.
The GrADS default rainbow colors (color numbers 2 to 14) are converted into
appropriate grey shades. User-defined colors (numbers above 15) are translated to
greyscale intensity based on their green content only.
2. For more information, see the section in the User's Guide on Producing Image
Output from GrADS.

Example
!"# $&%'()%*,+.-0/210$/435+ 6% 78+.-0/210$/439# $
Convert GrADS metacode format file :.;0<2=0><4?5: @ to a color plot on a black background
and outputs the result to PostScript file A.B0C2D0EC4F9G E .

55
gxtran
HI0J KMLN OQP0RTSU V WSXZYS[Z\^] _
This utility is used to display GrADS meta files containing single frames or animations
(multi frames).

The options are:

`abcde f
gh identifies input GrADS metacode file

ij
window
animates the frames without user hitting return in the command

kl&mon pq reverses background/foreground colors


sets the geometry of the X window as in any other X

ros tu
application.
has the form WWWxHHH+X+Y, giving a display
window
WWW pixels wide and HHH pixels tall starting at point X,Y
on the screen.

Usage Notes

Without any options, vw0x yMz{


prompts the user for the name of the GrADS meta file. To
quit gxtran, hit return in the command window.

Examples
|}0~ M| }M ,.0~20~45
.02045
This command would open a window of size 800x600 starting at the upper left corner of
the screen and animate all frames (plots) in the file .

56
ncdump
Z T . M TTM.4T 0^Z 0^Z
Where:


Show the values of coordinate variables (variables that are also
dimensions) as well as the declarations of all dimensions, variables, and
attribute values. Data values of non-coordinate variables are not included
in the output. This is the most suitable option to use for a brief look at the
structure and contents of a netCDF file.


Show only the header information in the output, that is the declarations of


dimensions, variables, and attributes but no data values for any variables.

 
The output is identical to using the option except that the values of
coordinate variables are not included. (At most one of or options
may be present.)

 T.MT
The output will include data values for the specified variables, in addition
to the declarations of all dimensions, variables, and attributes. One or more
variables must be specified by name in the comma-delimited list following
this option. The list must be a single argument to the command, hence
cannot contain blanks or other white space characters. The named
variables must be valid netCDF variables in the input-file. The default,
without this option and in the absence of the
 or   options, is to
include data values for all variables in the output.




A brief annotation in the form of a CDL comment (text beginning with the
characters ``//'') will be included in the data section of the output for each

  of data, to help identify data values for multidimensional variables. If
`row'
begins with  or  , then C language conventions will be used (zero-
based indices, last dimension varying fastest). If 
  begins with  or  ,
then Fortran language conventions will be used (one-based indices, first
dimension varying fastest). In either case, the data will be presented in the

57
same order; only the annotations will differ. This option is useful for
browsing through large volumes of multidimensional data.


!"

Full annotations in the form of trailing CDL comments (text beginning


with the characters ``//'') for every data value (except individual characters
in character arrays) will be included in the data section. If #
$ %& begins
with ' or ( , then C language conventions will be used (zero-based indices,
last dimension varying fastest). If )
* +, begins with - or . , then Fortran
language conventions will be used (one-based indices, first dimension
varying fastest). In either case, the data will be presented in the same
order; only the annotations will differ. This option may be useful for
piping data into other filters, since each data value appears on a separate
line, fully identified.

/013254

Changes the default maximum line length (80) used in formatting lists of
non-character data values.

678:95;=<

CDL requires a name for a netCDF data set, for use by >3?A@
BA>CD in
generating a default netCDF file name. By default, E3FHGJIHKML constructs
this name from the last component of the pathname of the input netCDF
file by stripping off any extension it has. Use the NO option to specify a
different name. Although the output file name used by P3QAR
SAPTU can be
specified, it may be wise to have V3WHXJYHZM[ change the default name to
\3]H^J_H`Minadvertantly
avoid a overwriting a valuable netCDF file when using
, editing the resulting CDL file, and using b3cAd
eAbfg to generate
a new netCDF file from the edited CDL file.

hHikjl
mnporqtsJuwvpuxozyt{}|~J3zp~MA}H}

Specifies default number of significant digits to use in displaying floating-


point or double precision data values for variables that don't have a

p
`C_format' z
attribute. Floating-point data will be displayed with
tJwp significant digits. If 
AH3tJwpxz is also
specified, double-precision values will be displayed with that many
significant digits. If a variable has a `C_format' attribute, that overrides
any specified floating-point default. In the absence of any H

58
specifications, floating-point and double- precision data are displayed with
7 and 15 significant digits respectively. CDL files can be made smaller if
less precision is required. If both floating-point and double-presision
precisions are specified, the two values must appear separated by a comma
(no blanks) as a single argument to the command. If you really want every
last bit of precision from the netCDF file represented in the CDL file for
all possible
M floating- point values, you will have to specify this with H
.

Usage Notes
3HJHM generates an ASCII representation of a specified netCDF file on standard
output. The ASCII representation is in a form called M (``network Common Data form
Language'') that can be viewed, edited, or serve as input to 3A
A . 3A
A is a
companion program that can generate a binary netCDF file from a M file. Hence
3A
A and 3HJHM can be used as inverses to transform the data representation
between binary and ASCII representations. See 3A
A for a description of CDL and
netCDF representations.
3HJHM defines a default format used for each type of netCDF data, but this can be
changed if a `C_format' attribute is defined for a netCDF variable. In this case, 3HJHM
will use the `C_format' attribute to format each value. For example, if floating-point data
for the netCDF variable is known to be accurate to only three significant digits, it
would be appropriate to use the variable attribute
z:HHJH w

3HJ M may also be used as a simple browser for netCDF data files, to display the
dimension names and sizes; variable names, types, and shapes; attribute names and
values; and optionally, the values of data for all variables or selected variables in a
netCDF file.

Examples

Look at the structure of the data in the netCDF file H3 :


3H 

3

 
1. Produce an annotated CDL version of the structure and data in the netCDF file
 , using C-style indexing for the annotations:
   "!#  $%

59
2. Output
23 3 45data
6 for only the variables &')(*,+ and -.)/0,1 from the netCDF file
, and show the floating-point data with only three significant digits of
precision:
789:;<=> :?)@7,9 A>?)@7,9B=9DCFEG G H78

3. Produce a fully-annotated (one data value per line) listing of the data for the
variable IJLKMON , using Fortran conventions for indices, and changing the netCDF
dataset name in the resulting CDL file to PQLRSOT :
UVWXYZ[\#]YL^_O` [ a a]bcbO`U[U#]YL^_O` a] ] dUV"e#fgd$VWh

60
ncgen
ijlk,mli npoqsrtnpo jurtnpo vurtnpoisrtnpowx,y,z|{}y,z$~ Ol},$ 

Where:


Create a (binary) netCDF file. If the  option is absent, a default file
name will be constructed from the netCDF name (specified after the netcdf
keyword in the input) by appending the  extension. If a file already
exists with the specified name, it will be overwritten.

Generate C source code that will create a netCDF file matching the
netCDF specification. The C source code is written to standard output.

Generate Fortran source code that will create a netCDF file matching the
netCDF specification. The Fortran source code is written to standard
output.

,,|}, 


Name for the netCDF file created. If this option is specified, it implies the
option. (This option is necessary because netCDF files cannot be
written directly to standard output, since standard output is not seekable.)

Like  option, except creates netCDF file with the obsolete $
extension instead of the  extension, in the absence of an output
filename specified by the  option. This option is only supported for
backward compatibility.

Examples

1. Check the syntax of the CDL file  $ :


l,l $

61
2. From the CDL file  $ , generate an equivalent binary netCDF file named
 :

l,l"  $

3. From the CDL file  $ , generate a C program containing the netCDF
 invocations necessary to create an equivalent binary netCDF file named
function
:
l,l "  $

62
stnmap
l) p O 


is an external GrADS utility that writes out a hash table and/or link list
information for station data that allows GrADS to access the data more efficiently. After

created, you must run the   


a station data set has been written and the accompanying data descriptor file has been
utility before you can look at the data in GrADS.

The    options are as follows:


!#"
The name of the station data descriptor file. If not specified,
prompt the user.
$%& ' () will

*+
Allows processing of certain templated station data sets without actually
reading the data.

The output from ,-. / 01


goes into a file that is named in the
descriptor file. (See Usage Note #2).
2354687:9 record of the data

Usage Notes

;<= > ?@


1. If you change the data file (perhaps by appending another time group), you will
also have to change the descriptor file to reflect the changes and then rerun the
utility.

2. Note the difference between required records in a station descriptor file and a grid
descriptor file:
A5B C:D8E
FG5HI8J:K
specifies a data type of: station

L8MONOPRQTS5MONOPRQVUWMONOP
gives the file name of the station mapping file

XZYO[O\ these records are not specified in a station data control file

describes the time grouping interval and the number of the time groups in
the file

63
]8^:_a`
surface variables are listed first, and show a "0" for the number-of-levels
field. Level-dependent variables are listed after the surface variables, and
show a "1" in the number-of-levels field.

Examples

Here's a sample descriptor file bcOd cRegf cOh for station data set ikjmlon:pq r :
sus5w t:vZw8v xykOzmz O{o|: }~ 
5wutw5 WsOw58vO8:v :xyk8}58zmz8{ {wkz~u}8~8~a}|z8| 
w8Z:sOvOat Z 8a}5z|58Z8:Zz:Z8O55|
a  ~88wat8}WO ~ 
y  88 ::aa
8a}5Z:a z
y 88wa}WO ~ : a
v8 sZ8:at 8W:a
Run the  
utility:
 8O Rg O
The station map file
list information.
km 
is a binary file, which includes the hash table and/or link

64
Analysis Topics
Dimension Environment
The data set is always viewed by GrADS as a generalized 4-D (5-D if you include
variables) array located in physical space (lon, lat, lev, time), even if it is in reality a
subset of a 4-D space.

The current dimension environment describes what part of the data set you want to work
with. Expressions are evaluated with respect to the dimension environment (which allows
for simplicity in the expression syntax), and the final display will be determined by the
dimension environment. Thus, the dimension environment is a GrADS concept that is
important to understand.

The dimension environment is manipulated by the user by entering one of the following
set commands:
Z8 o oZOu  OZ
This set command sets one dimension of the dimension environment using world
coordinates.

Alternatively:
Z  OZ
use whatever coordinates are convenient to you. Issuing
issuing
Z 
This sets one dimension of the dimension environment using grid coordinates. You may

Z is equivalent to
, both set the x dimension. The difference is only the units you wish to
enter the command in.

When you enter just one value, that dimension is said to be "fixed". When you enter two
values, that dimension is said to be "varying". The combination of fixed and varying
dimensions defines the dimension environment.

Examples:
Z   8Z sets longitude to vary from 180W to 0
sets latitude to vary from the equator to 90N

    sets the level to 500mb - a fixed dimension
    sets time to the first time in the data set--using grid

65
coordinates in this case. Time is now a fixed dimension

When all dimensions are fixed, you are referring to a single data point.

When one dimension is varying, you are referring to a 1-D "slice" through the data set.

When two dimensions are varying, you are referring to a 2-D "slice" through the data
set.

When three dimension vary, GrADS interprets this as a sequence of 2-D slices.

An important note: When you enter dimensions in grid coordinates, they are always
converted to world coordinates. This conversion requires some knowledge of what
scaling is in use for grid to world conversions. The scaling that is used in all cases (except
one) is the scaling of the default file. The exception is when you supply a dimension
expression within a variable specification, which will be covered later.

66
Grads Variables
Variable Names
Defining New Variables
Undefining Variables

Variable names
The complete specification for a variable name is:
!#"$%&('*)+$-,./0213)+$-,./02154 where:
67789: is the abbreviation for the variable as specified in the data
descriptor file
;<=>?
is the file number that contains this variable. The default initially
is 1. ( @ AB C+DEFA changes the default).
G+H-I.JKLM
is a dimension expression that locally modifies the current
dimension environment.

A dimension expression is used to locally modify the dimension environment for that
variable only. Only fixed dimensions can be thus modified.

An absolute dimension expression is:


NPORQSOUT2OWVXOZY[\]OZY ^+VXOZY_ `SOWV.acb_edgfihjkml

A relative dimension expression (relative to the current dimension environment):


nPoRpSoUq2oWrXoZstu]oZs v+rXoZsw xSoWr.yczwe{|}g~++ 

Examples of variable specifications are:


+
!3*+-. File 3, absolute dimension expression
Relative dimension expression
 Default file number is used
*+#+ Two dimension expressions
* This does have uses....

An important note: When you enter a dimension in grid units, GrADS always converts

67
it to world coordinates. This conversion is done using the scaling of the default file.
However, when a grid coordinate (x,y,z,t) is supplied within a dimension expression as
part of a variable specification, the scaling for that file (ie, the file that variable is to be
taken from) is used.

GrADS has a few "predefined" variable names. You can think of these as being variables
implicitly contained within any opened gridded file. The variable names are:




When used, they will contain the  ,  , and  at the respective grid points, using
the scaling of the appropriate file. You can specify:  for example, to get latitudes
on the grid of the 2nd opened data set.

Defining new variables


The m command allows you to interactively create a new variable. The syntax is:
mii-.g i c

The new variable can then be used in subsequent m and/or ++-i commands.
The new variable is stored in memory, not on disk, so avoid defining variables over large
dimension ranges.

Defined variables cover the dimension ranges in effect at the time the command is issued.
You may define a variable that has from 0 to 4 varying dimensions. The m
command is the only case within GrADS where four varying dimensions is valid.

When and/or are varying dimensions, the m command evaluates the
expression by stepping through  and  . In other words, the expression is evaluated
within a dimension environment that has fixed  and  . This will affect how you
compose the expression.

When you use a defined variable, data is taken from the variable in a way similar to data
taken from a GrADS data file. For example, say you define a four dimensional variable:

 
 

  

   

  

68
!!"#$%&!('*)+, -

After issuing the .!/!012%/ command, remember to change the dimension environment so
less than 4 dimensions are varying!
3
4 55 6
3
4 57 48 6:99
; 5!4(<*=

The display of the defined variable will display a 2-D slice taken at time 5 and level 500.

If you define a variable that has fixed dimensions, and then later access this variable, the
fixed dimensions are treated as "wild cards". The best way to show this is with an
example:
>
? @AB
CDEF GG
>
? @AH@GIG
>
? @A ?J K:GG
>
? @@E G
L ?!MNC%?O!HJ%?QPHJ%?SRTOVUW@ P!EXUW@ PZYG\[

The defined variable has two varying dimensions. If we now display this variable (or use
it in an expression), the fixed dimensions of the defined variable, namely ] and ^ , will
match ANY _ and ` dimension setting:
a
b ccd
a
b ce bfhgii
jk!l f%b

In the above display, the variable m!no%p would be displayed as it was defined, ie you
would get a time average of 500mb heights, even though the level is set to 850.

When the defined variable has varying dimensions, and you have a dimension
environment where that dimension is fixed, the proper dimension will be retrieved from
the variable:
q
r stu
vwxy zz
q
r st{sz|z
q
r st r} ~:zz
q
r ssx z
 r!v%rs!r(*
q
r st{sQ!z
 s!r(*

69
In the above example, the defined variable has a varying Y dimension. We then fix the Y
dimension to be 40N, and display a 1-D slice. The data from 40N in the defined grid will
be accessed. If you then did:

!
!(*

The data from 40S would be accessed from the defined variable. Since this is beyond the
dimensions originally used when the variable was defined, the data would be set to
missing.

You can also locally override the dimension environment:


!(* \:\

If that dimension is a varying dimension within the defined variable. If the dimension is a
fixed dimension for that variable, the local override will be ignored:
!(* !

In the above command, the defined variable temp has fixed T, so the t=15 would be
ignored.

N.B.: The !!% command currently supports only grids.

Once you have defined a grid variables, you may tell GrADS that the new variable is
climatological, ie that you wish to treat the time dimension of the new variable in a wild
card sense.

The command is:


Z* Z ZQZ !
(\

where Z Z is the name of a defined variable. If the grid is described as

!*
Z , then it is assumed that the defined variable contains monthly (or multi
month) means. Daily or multi-day means are not yet supported. If *! Z is specified,
it is assumed the defined variable contains means over some time period less than a day.

After describing the defined variable as climatological, then the date/times are treated
appropriately when data is accessed from the defined variable.

In the following example, the data set contains 10 years of monthly means:

70


 




  :

!
!%!%Q%STVW W !!W
!

This define will set up a variable called !% which contains 12 times, each time being
the 10 year mean for that month. We are making use here of the fact that the define
command loops through a varying time dimension when evaluating the expression, and
within the  function we are making use

 of
 the variable time offset of t+0, which uses
a start time that is whatever time the command is using as it loops.


 

 !!"#%$
&&'(

The final display will remove the 10 year monthly mean for December from the last
December in the data set.

Undefining variables
Each variable defined using the )*+
,-* command reserves some system resources. If
you no longer need a defined variable it is sensible to free these resources for other use.
This is accomplished with the .
/1023
4/2 command. For example:
5
61789
:68<;

would free the resources used by the defined variable = . Of course, the variable > would
no longer be available for GrADS processing.

71
Expressions
A GrADS expression consists of operators, operands, and parentheses. Parentheses are
used the same as in FORTRAN to control the order of operation.

Operators are:
? Addition
@ Subtraction
A
B Multiplication
Division

Operands are:
CDEF
DGH IJLKIM
F
N
F
M
D%OF%PQRJTSUNV
QM%OF%PQRJTSUDQ1WXM%PQRJODQ1OJ .

Operations are done on equivalent grid points in each grid. Missing data values in either
grid give a result of a missing data value at that grid point. Dividing by zero gives a result
of a missing data value at that grid point.

Operations cannot be done between grids that have different scaling in their varying
dimensions -- i.e., grids that have different rules for converting the varying dimensions
from grid space to world coordinate space. This can only be encountered when you are
attempting operations between grids from different files that have different scaling rules.

If one grid has more varying dimensions than the other, the grid with fewer varying
dimensions is 'expanded' and the operation is performed.

Some examples of expressions:


Y&Z(Y\[^]Z%_a` (Height change over time)
bdcfe ghikjml
lknpo%bdcfe ghiqajmlkn
(Temp change between 500 and
rst\uwvyx{z |}~x{z |k

850)
(Average of z over first 5 times in

\wy%
%%\
file)
(Remove zonal mean)
%
f
\~1 y~ 1R

(Time series of globally


averaged precip, on a 72x46 grid)

72
Using Templates
Grads allows you use a single data descriptor file to aggregate multiple data files and
handle them as if they were one individual file. The individual data files must be identical
in all dimensions except time and in a format GrADS can read. The time range of each
individual file must be indicated it its filename.

An example might be a timeseries spanning a single month, where each day's worth of
hourly data is contained in individual files:
mfm
mfm
^w
pfmf

In order to tell GrADS that there are multiple files in this time series, three records are
modified in the data descriptor (.ctl) file:
 

RLy{%
  p
%
X

& R1
(

First, the  entry has a substitution template instead of a filename. See below for a
description of all the possible components of the template. Second, the  p entry
contains the p
% keyword. Third, the  entry describes the time range for the
entire set of data files.

Templating works on the following GrADS data types: gridded binary, GRIB, and station
data. If you specify any additional 1%R keywords in the data descriptor file, make
sure the options apply equally to each file included in the template.

Valid components of the substitution template are as follows:



 2 digit year

 4 digit year

1 or 2 digit month
 2 digit month (leading zero if needed)
 3 character month abbreviation

1 or 2 digit day
 2 digit day (leading zero if needed)
 1 or 2 digit hour
 2 digit hour
3 digit hour (e.g., 120 or 012)

73

 2 or 3 digit forecast hour
!" 3 digit forecast hour
2 digit minute (leading zero if needed)

When specifying the initial time (e.g., NWP model output from NMC and FNMOC), use
these substitutions:
#$&%'
()&* + initial 2 digit year
,-/.0 initial 4 digit year
12/354 initial 1 or 2 digit month
67&89 initial 2 digit month (leading zero if needed)
:;/<= initial 2 minute (leading zero if needed)
>?A@B initial 3 character month abbreviation
CDAE F initial 1 or 2 digit day (leading zero if needed)
GH&IJ initial 2 digit day
KL&MN initial 1 or 2 digit hour
OP&QR initial 2 digit hour
initial 3 digit hour

74
About GrADS Station Data
This section describes the structure of station data files, how to create them, and how to
instruct GrADS to interpret them properly. Please refer to the companion section on
Using Station Data for information about the GrADS commands and functions that are
available for analyzing and displaying station data. Here are some quick links for
skipping through this section:

S Structure of a Station Data File


T Creating a Station Data File
U Station Data Descriptor File
V The STNMAP Utility

Structure of a Station Data File


Station data are written to a binary file one report at a time. Groups of station reports are
ordered within the file according to the time interval. The time interval for a set of upper
air soundings might be 12 hours, and the time interval for a set of surface observations
might be 1 hour.

Variables within each report are split into two categories: surface and level-dependent.
Surface variables are reported at most once per report, and level-dependent variable are
reported at multiple pressure levels within each report.

Each station report in a binary station data file has the following structure:

W A header which provides information about the location of the station


X Surface variables, if any
Y Level dependent variables, if any

The header is described by the following C language data structure:


Z\[^]`_/ab[c]ed\fhgb]h[biedkjblmd\]on
api/jp] qblrtsAuwv xey{zb[hjb[hqbg^|~}oybx
` gmj^[ j^[v xeyhj^[mq^[b_hlkdg zb[hjb[hqbg^|ybx
` gmj^[ g^|v xeykg^|keqb[^_mlmdg z^[mj^[mq^gb|~y\x
` gmj^[{[v xeyeq/dq\|^]/qblhp]ed jb[hqed_k|eq^[hZybx
qp|h[
| dpv xey`_^med\]g lmj^[mj`]mg^_`f/Z g k g\q\|k[^ihdiedkj^lkdb]
y\x
qp|h[ ` j\v xeymd\ed qp|hlkdbfhdb|mlmd\|h[/jp]oZ^d^[ k jby\x
v

75
A detailed description of each header entry follows:
A
The station ID uniquely identifies the station. It can be 1 to 7 characters
long and may be assigned arbitrarily; ie. the stations could be numbered in
some arbitrary order.
A~A

The location of the station, given in world coordinates (latitude and


longitude).

The time of this report, in grid-relative units. This refers to the way the
stations are grouped in time. For example, if you are working with surface
airways reports, you would probably have a time grouping interval of one
hour. If you wanted to treat the report times of each report as being exactly
on the hour, you would set t to 0.0. If the report was for 12:15pm, and you
were writing the time group for 12pm, you would set t to be 0.25. Thus, t
would typically have the range of - 0.5 to 0.5.
w

Number of data groups following the header. This is the count of the one
surface group, if present, plus the number of level dependent groups. Is set
to zero to mark the end of a time group in the file.
w

If set to , there are no surface variables following the header. If set to ,


then there are surface variables following the header.

The surface variable data (if present) are written to file following the header. Surface
variables are written out as floating point numbers in the order they are listed in the data
descriptor file. Each of the surface variables must be written -- missing variables should
contain the missing data value specified in the data descriptor file. The group of surface
variable data must be the same size for each report in the file.

The level-dependent variables are written to file following the surface variables as
follows:
w
-- a floating point value giving the Z dimension in world

76
w&for
coordinates this level.
-- The level-dependent variables for this level.

Each level dependent group must have all the level dependent variables present, even if
they are filled with the missing data value. The group of level dependent variable data
must be the same size for all levels and all reports in the file.

After all the reports for one time grouping have been written, a special header (with no
data groups -- w set to zero) is written to indicate the end of the time group. The next
time group may then start immediately after. A time group with no reports would still
contain the time group terminator header record (ie, two terminators in a row).

Creating a Station Data File


GrADS station data files must be written out in the structure outlined in the previous
section. Examples of C and FORTRAN programs to create station data sets are provided
below.

Let's say you have a data set with monthly rainfall:


/mp /bhb bhb h^ k^ e`\ek`k
^m^ k`  ^& ke
^m^ k` ` ^^ h
^m^ k` ` ^e km
^m^ k` ` ^k e
^m^ k`  ^& ^A
^m^ k` ` ^^ m^
^m^ k` ` ^e `e
^m^ k` ` ^k A

A sample DEC FORTRAN program to write this data set in GrADS format is given
below. Note that the OPEN statement is set to write a stream data set. This option may
not not available with every compiler. If your program writes out data in sequential
format, you must add an k 5 w5 entry to your GrADS data
descriptor file.
bbe\\kkeb\ep
m^k5^h 
  
m^k 5b m
  k!^k"#$k^k"`h`k^%``hbk^k&h` \k`b%
 'b
()*
#+, #.-
"+
  `bm 5/5``/0 1&m^h 1mk`ktp/'\h'^k 2k#'
/ ^k" `h " 355 476  8 86 e594 ` !0
  'b (:  ; !0 k``
" '\# ())

77
<>=?@A"B,CD<1=EF#?
<>G#H@A"B,CD<1G@HIJ
EHBK<"L
M <N.O#PQSRT1U PWVXYZ[:\]QX T"RP^R#T>UKPWVX#Y"Z[,RP"X"U_TO `"RY"X:a
M F0bbZ"U_TOV^OY)PU[#R cDR#T>UKPdVXYZ[Kbea
<Lgfh<1=#?@AB:aHE:a<1=EF#?a@?a<1GH@AB:aHE:a<1G@HIJjikIJEH
HAE"lDC*m
n#?<IEofpm0irq I<B:\?A F#I\!?A@H:\I <>Gs\HAEl%\HLA F#t
EHB <L
<>=?@A"B,CD<1=EF#?
<>G#H@A"B,CD<1G@HIJ
M n#XTRP^RuTbrX#P"[YXR
I <>GDC*mam
HAElDC)p
H#LA"Ft)C)p
n?#< IEofpmjirqI <1B%\?A FI:\?A@H\I<1G%\HAE"ls\H#LA"Ft
n?#< IEofpmjiv? lF#A
t@*I@,pm
M @ODP O#w*YN*NTxPrQX T"RP)x`b"R*RT1U PWVXYZ[,RP XUKT O`RYXa
y m M @HI< HzE
HAElDC*m
n?#< IEofpmjirqI <1B%\?A FI:\?A@H\I<1G%\HAE"ls\H#LA"Ft
q I@{
EHB

An equivalent C program might be:

| } ~#W }
#* ""#^*# } #^. #"#W#" S} ~S) "~S}
 "W
  }"0 #* }"~S1 "
, #d "#}""#^# #"#}"~
,"~ #d "~#}"^ }"~ "
* #. }>K*} ~) }"#"#}1 d~ }"
}~# ~% #. "## ,#* ^" K} ~ "
}~#   #d  *}~#"#"~ ~#d ",

K}~o"

  }} #}
  #90
}~#    ~ 1%#~ 1%}
d 
#. #"~S}#
}}WD"#"~o7}~: 0hj
}WD"#"~o7}~:!#"Kj
}7}}"  #}"  .
 }~#j ," ~ }~,} ~j
#"~:

78

#d#]#)S
 *)
  #05" _0.
#W"K," K"S
 #_K :j
 # #"d#d#0#":"" 
oh" "jk":e_^5"jj
#. >KW#",""_ "S ,
 j.
K,W:
K,d
 **

5Ks"  # s "#".
,*
#99 7  "Wj _

K,W:
K,d
##^r#",
,)
  *)
^*!
#5#": > "W#"#" K
#5K "#"0 K

,*
#5#": > W#"#" K

Station Data Descriptor File


After creating a binary file containing your station data, you must write a station data
descriptor file so GrADS knows how to interpret the binary data file. The format for the
data descriptor file for station data is similar to the format for a gridded data set, but there
are a few differences as well as additional entries that are unique to station data descriptor
files. These differences are outlined below. For further information on all the entries of a
descriptor file, consult the secion of the User's Guide on Elements of a GrADS Data
Descriptor File.

Here is an example of a station data descriptor file. Remember that the variables must be
listed in the same order as they were written to the binary file.
  "
" j 
 "
  "
S"
0  

79
!"#$% & ''')(*
+,+-$ . /0/1234#
0/05.06789
+#$% :;
* 81390=<>:?@:AB0=3:''?4:?C<
DEF.G::
7
H * ' ' .I<J0K9GL<9HH I<9
/H * ' ' .I<J0K9M+9=679<
0/I<9
N H * ' ' .I<J0K9O#9=P7213/G+9 679<0/I<9
I
H * ' ' .I<J0K9M!& Q 13 N
R H * ' ' .I<J0K9SD & Q 13 N
989 R * ' ' $
89 R 0/123>2J5./0/123
@ : ' ' T91UC/
/ : ' ' +9 679<
0/I<9
N : ' ' #
9 P7213/G+9 679<0/I<9
I : ' ' !
&Q 13 N
R : ' ' DV&Q 13 N
$"#DEF.

Note the following differences between this descriptor file and a gridded data descriptor
file:
WYX[Z]\_^a`cbed[bef[gih

This entry identifies the data file as station data.


jVkYlim_n]oqp_r_stuwvxyt

zc{i|[}entry
This ~V identifies the file name of the station map file created by the
utility.
_eeMYee
and ee

These entries are not included in a station data control file.


ee

This entry gives the number of the time groups in the file, the time stamp
for the first group, and the interval between time groups.
_]

The surface variables are listed first, and contain a "0" in the Yc field.
Level-dependent variables are listed after the surface variables, and
contain a "1" in the Yc field.

80

Once the station data set has been created and the descriptor file has been written, the
final step is to create the station map file by running the ci[V utility. This utility is
executed externally from the command line, not from within GrADs. ci[V writes out
information that allows GrADS to access the station report data more efficiently. The
output
VYi_]from
ci[V is called the station map file and its name is identified in the
entry of the data descriptor file. ci[V will prompt the user for the name of
the data descriptor file, or it can be specified as an input argument on the command line.
Station map files must be created on the machine where they are to be used. Consult the
reference page for more information.

If you change the station data file, perhaps by appending another time group, then you
ci[also
will V have to change the descriptor file to reflect the changes and then rerun the
utility.

81
Using GrADS Station Data
This section describes some of the GrADS commands and functions that are available for
analyzing and displaying station data. Please refer to the companion section About
Station Data for information on the structure of station data files, how to create them, and
how to instruct GrADS to interpret them properly.

Here are some quick links for skipping through this section:

Operating on Station Data


Plotting Station Models
Drawing Arbitrary Cross Sections

Operating on Station Data


Currently, station data operations and display are supported for three distinct dimension
environments:

X, Y varying (horizontal X, Y plot)


Z varying (vertical profile)
T varying (time series)

Operations may be done on station data as with gridded data. Operations between grids
and station data are not supported.

Operations between station data are defined as being the operation performed on data
points that have exactly the same varying dimension values.

For example, if T is the only varying dimension, the expression:


ee
_V[[

would result in a time series of station data reports being retrieved for two separate
variables. Then, for station reports having exactly the same time, the operation is
performed. Note that duplicates are ignored, with the operation being performed between
the first occurrences encountered.

When both X and Y are both fixed dimensions, the variable specification may include a
station identifier, which specifies a local override for both lat and lon.

82
The syntax for this would be:
c
)ce[][Yc]w

The station identifiers are case insensitive.

Some functions do not support station data types. These are:


]eVY VY V] i] V  
V  e 


When X and Y are varying, station data values are displayed as numbers centred at their
locations. If two expressions are supplied on the 
 command (ie, 

ts;ds) then two values are displayed, above and below the station location. The display is
controlled by the following  "! commands:
# $"%'&
& () ( * + , -.,/
0 1"243576"8
9 : ; <=><@?A
B C"D4EF7G>B F"H I J"K>L
M N"OPM7OQ R SUTWVXS Y
Y

The Z ["\PZ7\] ^ command controls whether the station identifier is displayed with each
value.

Plotting Station Models


GrADs will plot station models from station data. This is enabled by:
_ `"acb"d.e f.a model

The appropriate display command is:


ghijk
lm4nporqpotsuotguoXi kjpotgwvwk slxozy
k guo|{}porqhi

where:
~ and  are the wind components. A wind barb will be drawn using these values.
If either is missing, the station model will not be plotted at all.
uu  , and ww  are plotted numerically around the station model

is the value of the symbol desired at the center of the station model. Values
to are assumed to be the marker types (ie, circle, square, crosshair, etc). Values

83

to  are assumed to be cloudiness values:


" -clear
. -scattered
-broken
-overcast

 -obscured
-missing (M plotted)
 is the value of the  symbol (see 4 ) to be plotted in the 
location.
 is the visibility as a real number. It will be plotted as a whole number and a
fraction.

When any of these items are missing (other than and ), the model is plotted without
that element. To represent a globally missing value, enter a constant in the 

command. For example, if the ww  were always missing, use:

4prptutuX pz

The
7"station

models respond to the usual set commands such as "47> " , "
, "' 
7 , "'
 .

In addition, there is:


"P7 . .

which will cause the model to plot the number in the slp location as a three digit number,
with only the last three digits of the whole number plotted. This allows the standard 3
digit sea level pressure to be plotted by enabling dig3 and plotting slp*10.

Drawing Arbitrary Cross Sections


Drawing arbitrary vertical cross sections based on a collection of station data profiles
involves transforming station data (scattered observations) into gridded data so as to take
advantage of the GrADS grid display and analysis features.

The first step is to form a collection of 1-D data (Z or T varying). The collect command
saves station data profiles or time series in memory as a set. The 1-D data may be either
real station data or gridded data converted to station data using gr2stn.

84
The second stop is to convert the collection of station data into a grid for display or
analysis purposes. This is accomplished by the new function coll2gr.

coll2gr does not yet support time slices; currently, it will only work when the collection
of stations is a collection of vertical profiles.

coll2gr produces an output grid that varies in X and Z; the dimension environment used
when coll2gr is invoked must also be X and Z varying. The X axis of the output grid will
contain the equally spaced station profiles and will span the range of the current X
dimension environment. The Z axis of the output grid will span the range of the current Z
dimension environment and will have either the specified number of levels or a union of
the levels. Data points outside of the range of levels will be used for interpolating to
within the range if appropriate.

The X axis of the output grid from coll2gr is artificial in terms of the world coordinates --
it doesn't really represent longitudes. A way to completely control the labelling of the
display output is provided:

set xlabs lab1 | lab2 | lab3 ...


set ylabs lab1 | lab2 | lab3 ...

Each label string may include blanks. The labels will be plotted equally spaced along the
indicated axis. Spacing can be modified by adding blank strings:

set xlabs | | | | lab1 | ...

Here is a sample script written by M. Fiorino that uses these features:

*********************************************************************
* The following lines will display an arbitrary X section
* from one specified point to another.
*
* lon1 is the westernmost longitude point
* lon2 is the easternmost longitude point
* lat1 is the latitude that corresponds to lon1
* lat2 is the latitude that corresponds to lon2
*
* The loop is used to interpolate between points in
* the arbitrary cross section. This code will plot
* any cross section as long as you specify the points.
* My code plots cross sections of PV after I calculated
* PV on 11 pressure surfaces. I have another script
* that plots cross sections of potential temperature, and

85
* the code is very similar to this, except theta is substituted
* for PV.
*
* Many thanks to Brian Doty at COLA for his help with this code.
*
********************************************************************

'open pv.ctl'
'set grads off'
'set zlog on'
'set x 1'
'set y 1'
'set lev 1000 100'
lon1 = -95.0
lon2 = -90.0
lat1 = 55.0
lat2 = 15.0
lon = lon1
'collect 1 free'
while (lon <= lon2)
lat = lat1 + (lat2-lat1)*(lon-lon1) / (lon2-lon1)
'collect 1 gr2stn(pv,'lon','lat')'
lon = lon + 1
endwhile

'set x 14 16'
'set xaxis 'lon1' 'lon2
'set clab on'
'set gxout shaded'
'set clevs 0 .5 15'
'set ccols 0 0 7 0'
'd coll2gr(1,-u)'
'set gxout contour'
'set cint .5'
'd coll2gr(1,-u)'

86
User Defined Functions (UDFs)
Overview of User Defined Functions
The user defined function table
Format of the function data transfer file
Format of the function result file
Example: Linear Regression Function

Users may write their own GrADS functions in the computer language of their choice,
and have them available from the GrADS expression facility (via the 

command). Some possible user defined functions might be:

filtering functions
grid interpolation functions
thermodynamic functions

You may write a function that can be invoked via the GrADs expression facility. This
function may be written in any computer language, and may perform any desired I/O,
calculations, etc. Please read the following documentation carefully to understand the
restrictions to this capability.
   
 
      

The steps that GrADS uses to invoke a user defined function are:

1. When GrADS is first started, it reads a file that describes the user defined
functions. This file is called the 'user defined function table'.

2. When a user function is invoked via the display command expression, GrADS
parses the arguments to the functions, obtains the results of any expressions, and
writes the resultant data to a 'function data transfer file'.

!"$# note that in a user-defined function adding the double quote ("") around a
Please
argument passes the string directly without the usual conversion to lower
case and removal of blanks, e.g.,
%'&)(+*,)-/.1032/-!4657)89;: 5=<?>)*,@2',@2BAC*DFEG!HDI-J<5LK9;:NM)O

Here P)QR;S is passed as T/UV;W , but the second character string would not be

87
converted to XCYZ@[/Z@[$XCY\I])^!_\I] .

3. A user written program is then invoked. This program may read the function data
transfer file, do any desired processing, then write the result into a function result
file.

4. GrADS will read the function result file and generate the internal objects
necessary for this result to participate in the remainder of the expression
evaluation.
`abdc1e@bfhgbikjmlbJgnikclopjrqsltpvu1w1xyb

The user defined function table (UDFT) is a simple text file that contains information
about each user defined function. There are five records for each defined function, and
the file may contains descriptions for any number of functions. The 5 records are:

Record 1: This record contains several blank delimited fields:

Field 1: The name of the function, 1-8 characters, beginning with a letter.
The name should be in lower case. Note that function names are not case
dependent, and that GrADS converts all expression to lower case before
evaluation.

Field 2: An integer value, specifying the minimum number of arguments


that the function may have.

Field 3: An integer value, specifying the maximum number of arguments


that the function may have. This may not be more than 8.

Field 4 to N: A keyword describing the data type of each argument:


$z {)|I}~ The argument is an expression.
)! The argument is a data value.
!$ The argument is a character string.

Record 2: This record contains blank delimited option keywords. Current


keywords are:
C+C$@))
- GrADS will write data to the function data transfer file in
FORTRAN sequential unformatted records. This is typically appropriate if
the function is written in FORTRAN.
@$I/
- GrADS will write data to the function data transfer file without

88
any record descriptor words. This is typically appropriate if the function is
written in C.

Record 3: This record contains the file name of the function executable routine.
This routine will be invoked as its own separate process via the N$I call. Do
a N! N$I if you would like more information on the rules governing this
system feature.

Record 4: This record contains the file name of the function data transfer file. This
is the file that GrADS will write data to before invoking the user function
executable, and is typically the file the function will read to obtain the data to be
operated upon.

Record 5: This record contains the file name of the function result file. The
function writes the result of its operations into this file in a specified format, and
GrADS reads this file to obtain the result of the function calculation.

The user function definition table itself is pointed to by the environment variable
GAUDFT. If this variable is not set, the function table will not be read. An example of
setting this variable is:
C+I$)C@+C/NI/@))C+)/!/@/

User defined functions have precedence over GrADS intrinsic functions, thus a user
defined function can be set up to replace a GrADS function. Be sure you do not do this
inadvertently by choosing a function name already in use by GrADS.
Nk;;r1kI11kr

The function data transfer file contains a header record plus one or more records
representing each argument to the function. The user function routine will know what
data types to expect (since they will be specified in the UDFT), and can read the file in a
predictable way.

Header record: The header record always contains 20 floating point numbers. The
record will always be the same size. Values defined in this record are:

1st value: Number of arguments used when invoking the function.

2nd value: Set to zero, to indicate this particular transfer file format. The function
should test this value, and return an error if non-zero, in order to be compatible
with future enhancements to this file format.

89
Values 3 to 20: Reserved for future use.

Argument records: The argument records are written out in the order that the arguments
are presented. The contents of the argument records depends on the data type of the
argument: value, character string, or expression. Each of these data types will result in a
different argument record being written out:

')!
: If the argument data type is a value, then the argument record will
contain a single floating point value.

!$: If the argument data type is a character string, then the argument record
will an 80-byte character array that contains the argument string. If the argument
string is longer than 80 bytes, the trailing bytes will be lost. If the argument is
shorter, it will be padded with blanks. Note that the argument will already be
processed by the GrADS expression parser, which will convert all characters to
lower case and remove any blanks.

$)I : If the argument data type is a gridded expression, then GrADS will
evaluate the expression and write a series of records to the transfer file. Listed
below are the records that will be written to the transfer file for each argument
that is a gridded expression:

1st record: This record contains 20 values, all floating point, that make up
the header for the gridded expression. Note that some of the values are
essentially integer, but for convenience they are written as a floating point
array. Appropriate care should be taken in the function program when
converting these values back to integer.

1 -- Undefined value for the grid

2 -- An index to identify the i dimension (idim). Options for the


index are:

/ None

X dimension (lon)
Y dimension (lat)
Z dimension (lev)
T dimension (time)

3 -- An index to identify the j dimension (jdim). Options are the


same as for idim. If both idim and jdim are -1, the grid is a single
value.

90
4 -- number of elements in the i direction (isiz).

5 -- number of elements in the j direction (jsiz).

6 -- i dimension linear flag. If 0, the dimension has non-linear


scaling.

7 -- j dimension linear flag. If 0, the dimension has non-linear


scaling.

8 -- istrt. This is the world coordinate value of the first idim


element, ONLY if idim has linear scaling and idim is not time.

9 -- iincr. This is the increment of the world coordinate values for


idim, ONLY if idim has linear scaling.

10 -- jstrt. This is the world coordinate value of the first jdim


element, ONLY if jdim has linear scaling and jdim is not time.

11 -- jincr. This is the increment of the world coordinate values for


jdim, ONLY if jdim has linear scaling.

12 -- If one of the dimensions is time, values 12 to 16 define the


start time:

12: start year


13: start month
14: start day
15: start hour
16: start minute

17 -- If one of the dimensions is time, values 17 and 18 define the


time increment:

17: time increment in minutes


18: time increment in months
(GrADS handles all increments in terms of minutes and months.)

19,20 -- reserved for future use

2nd record: This record contains the actual grid of data. It contains
isiz*jsiz floating point elements.

91
3rd record: This record contains the world coordinate values for each grid
element in the i dimension. Thus, the record will contain isiz floating point
elements.

4th record: This record contains the world coordinate values for each grid
element in the j dimension. Thus, the record will contain jsiz floating point
elements.
Nk;;rN 1kr

The function result file returns the result of the user defined function to GrADS. It is the
responsibility of the function program to write this file in the proper format. A file written
out in an improper format may cause GrADS to crash, or to produce incorrect results.

The result of a function is always a grid. Thus, the format of the function result file is as
follows:

Header record: The header record should always contain 20 floating point numbers. The
record will always be the same size. Values defined in this record are:

1st value: This value contains the return code. Any non-zero return code causes
GrADS to assume the function detected an error, and GrADS does not read any
further output.

2nd value: Set to zero, to indicate this particular transfer file format. The function
should test this value, and return an error if non-zero, in order to be compatible
with future enhancements to this file format.

Values 3 to 20: Reserved for future use.

Grid records: The grid records should be written in the same order and format as the
 argument record in the data transfer file, with one important exception: the 3rd and
4th records containing the world coordinate values for each grid element in the i and j
dimensions are written out to the function result file only if the scaling is non-linear. Thus
the transfer file and the result file are not symmetric: GrADS writes a transfer file with
record #3 and #4 always included, but it does NOT like to see record #3 and #4 in the
result file if the dimensions are linear.

The linear/non-linear scaling of the grid dimensions is determined by examining the grid
header contents -- values 6 and 7 contain the idim and jdim linear flags. Note that the
time dimension is always linear.

92

 !"$#%&('$'$*),+-.(/1023)

This is a simple example of what a user defined function might look like in FORTRAN.
This is a simple linear regression function, which only handles a 1-D grid and takes one
argument, and expression.

First, the user defined function table (UDFT):


4658769;:=<?>@>?:8ACBC9
D :6E=F;:87HGI5CJ64
K8LH7IG6K6<69;JNM D KH4C5O7C9H:=<
K8LH7IG6K6<69;JNM D KH4C5O7C9H:=<PRQNFIG
K8LH7IG6K6<69;JNM D KH4C5O7C9H:=<PS587

The source code for the FORTRAN program linreg is:


THUIV6WYXZV6WI[]\2^=_a`cbed8XZV6WI[]\f^N_`
THUIV6WYgh\ji6_6_C_6_a`cblk\fiN_C_6_6_a`
m
d=n;U8op\fqbsr6tCWNUNu$vRw8xHoIy6w6zNT{V=|;[Ow;W6t8o6T;U=z}RdN~Iy$v6bsr=dNT=x;u$v~6o;rNd=TNxZVNy6yIUN|$vj`
d=n;U8op\fiN_bSrCt6W6U=uvw=xIoHyNw6z6T;VN|H[8wHWCtOoCTHUNz$}stOo(v6bsr=dNT=x;u$v~6o;rNd=TNxZVNy6yIUN|$vj`
m
THUIV=|\fq]`
THUIV=|\fq]`XZV6WI[
t=|Htx,uXZV6WI[]\2^Z`
|Htx,uXZV6WI[]\H`
m
m Cry={tC[tI[YoIdCyViIOzNT;tN|bHT;tNyCU@U=T6THd=TxZUI[C[NV=zIU?VOoH|?UOgZt=y
t6r\t=|Htx }eU6}s=i}ed=T(} |Itx}oHU}SNi]`yNHU=o
IT{t=yIU\j$bSZ`vlCT6THd=T8oNXZV6WCt=|@|HtxZU8oZ[NtNd=o,U=oNXZtOTIdNo=xZU8oHyv
X{VCWC[\ji`u?i
IT{t=yIU\ji6_`XZV6WI[
[8yCd=n
U8oH|ItCr
m
m Cry=;UzNT{t=|tI[y6dCd;t=z$bIT{t=yIU@U8TCTIdNTx{UH[6[6V8zHU?VOoH|@U8g{tNy
tC[6tNuXZV6WI[]\j`
t6r\tC[6tN}zIy}eiN_C_6_C_`y=;U8o
IT{t=yIU\j$bSZ`vlCT6THd=TrOTHdOxWCtOoCTHUNz$CT;tN|@y6dCd;t8zv
X{VCWC[\ji`u?i
IT{t=yIU\ji6_`XZV6WI[
[8yCd=n
U8oH|ItCr
m
m HUCVN|@y=;U|IVNyIV
THUIV=|\fq]`,\&k\t{`bSt=uCi$bStC[6tN]`
m
m HUCVN|oIdNo;CW6t8oHUIVOT[6m6VCW6t8oCz,t6ro;UCm6UI[C[NV8TNk
t6WCtOo?uXZV6WI[]\f]`
t6r\t6WCtOo(}eU6}R_`yNHU=o

93
HI=f],&{S=CsC6N]
CI=
6@66,=C$SIN6
{,
NC =NIHOCH
8HIC

;68HIO@;=6HH66=N
6C6@C=&(l(sC6NSa

H6C@OH=HY{CO;I
6@CN,=C$SIN6
{,==h2Z8
66 =NIHOCH

H;NCNI;NN6CO{=$
CH;CNC=OH@=;IN;6CO;C8NC6COI
8;NZC6;=;N{?CH;N6NC]HO;Zh
8Z6I]f]@
I{=Ij6={CC
I{=Ij6Z6I
I{=Ij6,&{S=CsC6N]
66CO(e6RH;NCafNa,h2Zcs8IsC6N]

8C=
8H

6C6C6C6C6C6C6C6C6C6C6C6C66C6C6C6C6C6C6C6C6C6C6C6C66
OCC66 ;86HO lN6IN

CNH?8II8{N=I
CNH6=NH

NHh&6NH=c&6NIN

@
,@
;@$
@$
I??6NH=
{
, ,h{
C 6{O

6 ?6 I&6NH=
;C H C
6,?6NH=
?{Y {6
; ;
h{
N 6{O
;
, 2 6

94
NC6IN
66

95
Using Map Projections in GrADS
It is important to understand the distinction between the two uses of map projections
when creating GrADS displays of your data:

projection of the data (preprojected grids);


projection of the display.

GrADS supports two types of data grids:

cahc grids (and not necessarily regular, e.g., gaussian);


preprojected grids.

Using Preprojected Grids


GrADS Display Projections
Summary and Plans

Using Preprojected Grids


Polar Stereo Preprojected Data
Lambert Conformal Preprojected Data
NMC Eta model
NMC high accuracy polar stereo for SSM/I data
CSU RAMS Oblique Polar Stereo Grids
Pitfalls when using preprojected data

Preprojected data are data already on a map projection. GrADS supports four
types of preprojected data:

1. N polar stereo (NMC model projection);


2. S polar stereo (NMC model projection) ;
3. Lambert Conformal (originally for Navy NORAPS model);
4. NMC eta model (unstaggered).
5. More precise N and S polar stereo (hi res SSM/I data)
6. Colorado State University RAMS model (oblique polar stereo; beta)

96
When preprojected grids are opened in GrADS, bilinear interpolation constants
are calculated and all date are displayed on an internal GrADS lat/lon grid defined
by the  and  card in the data description or c file (that's why it
takes longer to "open" a preprojected grid data set).

It is very important to point out that the internal GrADS grid can be any grid as it
is completely independent of the preprojected data grid. Thus, there is nothing
stopping you displaying preprojected data on a very high res lon/lat grid (again,
defined in the  by 
and 
   ). In fact, you could create and open
multiple .ctl files with different resolutions and/or regions which pointed to the
same preprojected data file.

When you do a  (i.e., get a grid of data), the preprojected data are
bilinearly interpolated to the GrADS internal lat/lon grid. For preprojected scalar
fields (e.g., 500 mb heights), the display is adequate and the precision of the
interpolation can be controlled by 
  and !
" # $ to define a higher spatial
resolution grid.

%%&(big
The ' virtue of this approach is that all built in GrADS analytic functions (e.g.,
, )*+ ,(- ...) continue to work even though the data were not originally on a
lon/lat grid. The downside is that you are not looking directly at your data on a
geographic map. However, one could always define a .ctl file which simply
opened the data file as i,j data and displayed without the map ( .0/21435
67(89 off).
So, in my opinion, this compromise is not that limiting even if as a modeller you
wanted to look at the grid--you just don't get the map background.
:;
<>= ;?
@< AB <2CED(< AB?;GFH2< IC(J
are a little trickier, depending on whether
the vector is defined relative to the data grid or relative to the Earth. For example,
NMC polar stereo grids use winds relative to the data grid and thus must be
rotated to the internal GrADS lat/lon grid (again defined in the KLMN file by the
O
P Q R and S
T U V cards).

The only potential problem with working with preprojected data (e.g., Lambert
Conformal model data) is defining the projection for GrADS. This is
accomplished using a W
X Y Z card in the data descriptor [\]^ file.

Polar Stereo Preprojected Data (coarse accuracy for NMC Models)

Preprojected data on a polar stereo projection (N and S) is defined as at NMC. For


the NCEP model GRIB data distributed via anon ftp from ftp.ncep.noaa.gov, the

97
_
` a b card is:
c
d e fhgig2jelk ig2jemc no
k0p0qc(ergc
os2elktc
os2erso0u n
e f
v n(gdguw
c
d e fyx>z|{}x~uciE m{ 2x2x

where,

2
and t
2 are the (i,j) of the pole referenced from the lower left
corner at (1,1) and ( is the dx in km.

The relevant GrADS source is:

void w3fb04 (float alat, float along, float xmeshl, float orient, float *xi, float *xj)
{
/*
C
C SUBPROGRAM: W3FB04 LATITUDE, LONGITUDE TO GRID
COORDINATES
C AUTHOR: MCDONELL,J. ORG: W345 DATE: 90-06-04
C
C ABSTRACT: CONVERTS THE COORDINATES OF A LOCATION ON
EARTH FROM THE
C NATURAL COORDINATE SYSTEM OF LATITUDE/LONGITUDE TO
THE GRID (I,J)
C COORDINATE SYSTEM OVERLAID ON A POLAR STEREOGRAPHIC
MAP PRO
C JECTION TRUE AT 60 DEGREES N OR S LATITUDE. W3FB04 IS THE
REVERSE
C OF W3FB05.
C
C PROGRAM HISTORY LOG:
C 77-05-01 J. MCDONELL
C 89-01-10 R.E.JONES CONVERT TO MICROSOFT FORTRAN 4.1
C 90-06-04 R.E.JONES CONVERT TO SUN FORTRAN 1.3
C 93-01-26 B. Doty converted to
C
C
C USAGE: CALL W3FB04 (ALAT, ALONG, XMESHL, ORIENT, XI, XJ)
C
C INPUT VARIABLES:
C NAMES INTERFACE DESCRIPTION OF VARIABLES AND TYPES
C ------ --------- -----------------------------------------------

98
C ALAT ARG LIST LATITUDE IN DEGREES (<0 IF SH)
C ALONG ARG LIST WEST LONGITUDE IN DEGREES
C XMESHL ARG LIST MESH LENGTH OF GRID IN KM AT 60 DEG
LAT(<0 IF SH)
C (190.5 LFM GRID, 381.0 NH PE GRID,-381.0 SH PE GRID)
C ORIENT ARG LIST ORIENTATION WEST LONGITUDE OF THE GRID
C (105.0 LFM GRID, 80.0 NH PE GRID, 260.0 SH PE GRID)
C
C OUTPUT VARIABLES:
C NAMES INTERFACE DESCRIPTION OF VARIABLES AND TYPES
C ------ --------- -----------------------------------------------
C XI ARG LIST I OF THE POINT RELATIVE TO NORTH OR SOUTH POLE
C XJ ARG LIST J OF THE POINT RELATIVE TO NORTH OR SOUTH POLE
C
C SUBPROGRAMS CALLED:
C NAMES LIBRARY
C ------------------------------------------------------- --------
C COS SIN SYSLIB
C
C REMARKS: ALL PARAMETERS IN THE CALLING STATEMENT MUST
BE
C REAL. THE RANGE OF ALLOWABLE LATITUDES IS FROM A POLE TO

C 30 DEGREES INTO THE OPPOSITE HEMISPHERE.


C THE GRID USED IN THIS SUBROUTINE HAS ITS ORIGIN (I=0,J=0)
C AT THE POLE IN EITHER HEMISPHERE, SO IF THE USER'S GRID HAS
ITS
C ORIGIN AT A POINT OTHER THAN THE POLE, A TRANSLATION IS
NEEDED
C TO GET I AND J. THE GRIDLINES OF I=CONSTANT ARE PARALLEL
TO A
C LONGITUDE DESIGNATED BY THE USER. THE EARTH'S RADIUS IS
TAKEN C TO BE 6371.2 KM.
C
C ATTRIBUTES:
C LANGUAGE: SUN FORTRAN 1.4 C MACHINE: SUN SPARCSTATION 1+
C*/
static float radpd = 0.01745329;
static float earthr = 6371.2;

float re,xlat,wlong,r;
re = (earthr * 1.86603) / xmeshl;
xlat = alat * radpd;

99
if (xmeshl>0.0) {
wlong = (along + 180.0 - orient) * radpd;
r = (re * cos(xlat)) / (1.0 + sin(xlat));
*xi = r * sin(wlong);
*xj = r * cos(wlong);

} else {
re = -re;
xlat = -xlat;
wlong = (along - orient) * radpd;
r = (re * cos(xlat)) / (1.0+ sin(xlat));
*xi = r * sin(wlong);
*xj = -r * cos(wlong);
}
}

Lambert Conformal Preprojected Data

The Lambert Conformal projection (lcc) was implemented for the U.S. Navy's
limited area model NORAPS. Thus, to work with your lcc data you must express
your grid in the context of the Navy lcc grid. NMC has been able to do this for
their AIWIPS grids and the Navy definition should be general enough for others.

A typical NORAPS Lambert-Conformal grid is described below, including the C


code which sets up the internal interpolation.

The  file is:


(02l t
2E2 0
(|2l (
 

2El mt 

2 >G2r
2 >G2r
r2>( m2h0  l
rr20 lr2
 l >r
2 2l >
>m
h r t
0>

100
where,
2
 = #pts in x
 = #pts in y
 = Lambert-Conformal
 = lat of ref point
= lon of ref point (E is positive, W is negative)
t = i of ref point
 = j of ref point
= S true lat
 = N true lat
 = standard lon
 = dx in M
= dy in M

Otherwise, it is the same as other GrADS files.

Note - the
0
apply to the 0
 grid GrADS internally
interpolates to and can be anything...

The GrADS source which maps   of the GrADS internal 
  grid
to  of the preprojected grid is:
!#"%$&('$)*,+.-$)&)/(0*1)2)$&3
/$245+,+)6!+%-879'%+)$!5:/(,+,1 ;<'%+)$!)>=)4!+,?;<'%+$>=%!4+$)&@;
'%+)$!)50=%!42 ;<',+$!)50=%!4A(BDC
 E:F,%$F!20&>%$5-)$&%/!5'0!$0G+%)!H,+$)&5%$>I!0#")$)&')$)*,+.2 ;JA K
L $0/*24!)4M%N#O,P,DQ($&,0NSR<-)$&%/!!)4.,$#"MT%,UWVX,Y%Z@K
- E:[,\,P%]%[,^_0O%`Sa<+%+%6,+,-
-
- L [!P L ]E0`@ab^$5-$0!c,F!!#2%H.:&45A%H,-$,$4!20&),1$!'.
1Ic,-,2%',2)%4
- =%2)4>=2:/&5d.+,2)F!4!#:&45+$)&,=2)F!4!
c!$2:&1 K
- ef+%+.+,2)F!4!!1>2:&5)d2!1g!$)F!2:&510:
- hf2)d3H0Y,i?Kjik.d510$)F!)d.c!$+)#0&!4
2:&(-:,!1
- &$d)h*0!4.,$>l%Y%i@Kmik).d&!$)!)d.c!$+)nK
^%d
- +)$&!=2)F4,1.10:!Dhf2)d#i?Kjik.)d
o %&hf2%-0d
- *0(242%0&3:&452:&-0!,1)>%$.)d.!,1n;p1$
d(
- Y,i?Kji>!')(1,$MY,i?Kji)`S;qU%r%i?Kjik2,1)d
2:&,H
- &(2$)&,+M4!),!+%2:&#:&4#6,si?Kjik2,1DY,i?Kji0tuK
-

101
v w:x!y)z,{M|%}~wI}!!)(
v
v (,,0% !%,?<%)!),#)M,%00(v)!0!
0! J:,*
v
v (,,0, !%)S<),)!!#M!)v%!:
0! J:,*
v
v (,,0! :, %,v,!0),D(,:>!D,%00(v)!0!
v
v (,,0( :, %,v,!0),D(,:>!D,%00(v)!0!
v
v (,,0% 0,!)%?p0:!0!5,,>)(
v
v (,,0W 0,!),np!v)!k!0!:!5,)!!>!%) ):
 %(:)
v %.)(>5n<%I!0#v)()f%*
v
v (,,0, 0,!)Sp0:!0!5)!)!!>!%) )!),
(
v !:,.D
v
v (,,0 ,!I )(k:,v%0,#!%)5:>*:,v)!)
v )30%)>#nnD)#?q!,:>!*0M
:M*)!0*
v )30%)>8q,!I>(M#05,))%
v
v (,,0, ,!I )(k:,v%0, 0M(%,((!%)5:>*
!0!v)
v )30%)>#nnD)#?q!,:>!*0M
:M*)!0*
v )30%)>8q,!I>(M#05,))%
v
v )!,?<%)!),>D!!0! )!m%!(
v
v )!)S<),)!!>!D!: %! j)!*
v
v )! %,v.)!:(! ((.)!g!)!:
,%00(!
v :()f)3
v
v )! %,v,!0), )).(,g!0 %,
!),
v :()f)3
v0

,M( b()b(0@q,@b)?b)!0( 0()?


,
v)Sj%v)S0:j!@v0!?v0nv0* v0,@(:S(0@(0@m%(:Sv0!v:S
,5,:( %:S,)@SS
(.?j : njW

102
()M>(0j?
(0.>(0,?j?
0#>(0!%%?m@
 #,)@m,)
( :*D#),,@m@
0()..?j:(0!%%%,?j?
I*.,%,%,%,%,%%,%f%
,%!g5!: 0 5 >:>5)I(#0
%X* :,W%k* :%,D
)#3%:XW( 0%I 
5
)# %9%:%%@m%* :,W,I %
%)0,,?m%* :%,I ,%
%!0,%@m%* :,W,I?I ,
%!0,,?m%* :%,I?I ,%

I*.,%,%,%,%,%%,%f%
))##nj%,)@
:Ikk,:*f9W* :,W,XX* :,W,
).,?j,%:*f9W( 0%%,I @
:>3)0 )W
:M> 0(%%:!)))@
). )?
:fg#!0 )W
).,?j,%:*f9I* ,I?I @
:!.#!0 )W
0#k:,0!0 %9:!%:fm)
).X* :,WI,W( 0,W%: 0(0)@
0#>0!)0 
0#k:(:(%)f )W:%0:
).,?j)  )!,:II?I @
:!.#!0 )W
%(:#k0!:: ,X0,,0*j)
:,0##%%?j%* :!f
, k* 0,WX:,0@
#.%  ),0!:S
!( X ),,?mg #k ),*:%?j?
!( X ),*:)@mg #k ):%?j?
).X ), (% :0) @
>%(:(,%: )W
k:,0,f I,:Iu
0% kW( :*9 099W( 0*%
0%  kW( :*9 099W( 0,W%

NMC Eta model (unstaggered grids)

The NMC eta model "native" grid is awkward to work with because the variables

103
are on staggered (e.g., the grid for winds is not the same as the grid for mass
points) and non rectangular (number of points in i is not constant with j) grids.
Because any contouring of irregularly gridded data involves interpolation at some
point, NMC creates "unstaggered" eta model fields for practical application
programs such as GrADS. In the unstaggered grids all variables are placed on a
common and rectangular grid (the mass points).

Wind rotation has also been added so that vector data will be properly displayed.

The pdef card for a typical eta model grid is:

         IW


  
 
I n n


 == #pts
 in x
 =#pts in y

 !  = etalon grid, unstaggered


of ref point (E is positive in GrADS, W is negative) [deg]
"$*$#&+&%(,.')-*/')',.- ==latdlonof [deg]
ref point [deg]

= dlat [deg]

The source code in GrADS for the lon,lat -> i,j mapping is:
02<:R2124I354768L5BT686:E 98;5<>=?3A@2BC3&DFEG3H@IB7J&DFEGK86512L5B7MA0NL868OE KP6:1IL:BQ<:R24I6:15@SEGKP6:1IL:B
KP6:1IL:B7MH<PRI4I3 EGKP6:1IL:B7MH<PRI42JEGK86512L5B7M8LP6AU8VWLYX[Z
\ M ]A^8_PR215^2BI3H@2;QBP17`:15@P0W;5RIB7KHRI1HDa6PL:BIb8651:@7BP1dc5eYfg;:B2Lg3EhJi
x 3:15RNj3AR2@21H1/0Yi 354I;:4d_Pkgl8RW38`nm81P<I;5RNOoc:eNf/pG`51:@:0N;HR2B8;:4gB81Cfrq \ 95s \ stu_:kQev3AwW;
`` ]Ay8z8mP{Py8|W}HcPlS~G6P6P9P;:<
`O&UW;8`83PK83:;P4 j yIm j {W]Hl~|217`51HDIU8^IBI;C3PbgLA@247JPb8`51815R24I3H@WL:B8;2On1IKgL
UI`` 123A@2B2Oi <PRW3:4Q<23A0W;5@7B5VW;g68L5B235B:^I4I;CLA@247651:@8<W35B:^I4I;
vv6P35B:6gV68bHL5s8B2T35B:i^Ir4I;IL5BgOQB53A@7VW;7B:VWOH1:3I^IOoB:VgRI1:^IUIB2123A6:@W;C;7LH@IOH4B2LAR2B
`3A@N`ARW;8LIO5;
|P`` VW; @215R2B5V:YLHRI4gB81QPsPirL:BgB5VW;n@I1:RIB:VgUI126:;/i
6:15@I<23:B5^248;2OgOHB2LARIB[v35B:VCTirL5BgB:V2;
` RW;P;5@5v3P`HV DY;HRN35423PLH@LA@2473A@W`HR2;IL8O:;QBP1gB:V2;g;IL8O5B/EO51
104
5 N5 8TQ2I:5N 8 8T:SPPTr8 :
A 5W 5 8dI: AW C8 Tr8[8TH
AI:8dPW2&II:N
8 HP I& : I2 52 5 nW8PHWHN:CPH 5g A
8 H8 85 :I : n2I:525WPC:5 Hg H
8 H I8 25 C:N HWH2 H A 5
8 HN
2
P
:
:
N
H
W
H
2
H
A
5

: I85 P: 52 [ H : P 2N
: I: S 5 8W :I [ A P : IY
I 525 : : P8 8 H : :W:g5 8o 52 H2ov 8
AN v5
I 525 : : I 8 8 H : :W:g5 8o 52 H2ov 8
AN v5
H
552255 N 8  : : S :I:gI& 2P&
8 PS&S P & P& P&  5T P& 2 h & h:HP hPA8 H A HhP
525n / S/NHP W5 8 8 : HS 2
H 5
NHY:Iv? P 
I:I :8NT PPIT ST
5 8 T
25 8 W 2 : I 8H A8 2 PW5 n 8 dS 5 d: 5 g 2 I
2P& PP AA8 vP 
H P AN P 
105
Wn:N5d2IHI7A27:5IIH72Q:2n:N5g5NHr5
Wg5::NH2gPdW:I8AYQH
88W gr:H2PIIIP::5IN:85I5HS 2g:5PW5IQnPQQS5Wd:N5W
H2A2I5:HI8W75::I5ICH
8Y >PII:5.&:85
88WW5 CC5I8&28882255IIHHSS
8WI >A:grYPIA8(gA5IHS
Wg5WQA2r:A5
:P2A8APPNNnnr5:WH)v88WWYY..
:P2A8APPNNHHggr:P2A)vPPNNHH..
:P2ANPPP&&IIIIW2:P2A(PP&&NNIIPP88WWIIvv..
W rr55WW&&PPNNPHW85 WWvN?P:H&YP88WP5&22I:.H P8W
rrP8:P2AP&88WW5828P2A 28:2vAPPN8HWW(8PA 8PN
W[WHW&vQ:5dYHId2P2525:PHPNgH
8I85HHWIW225W::22&8AAPWPNN8HPPW:I2P:PA:N58WP2&PIA8S P NHW8PA8PN
2W2:IH2.85F85
W[WH5(Q5:r85P2:55rhgH
NNHHPWPPN&rnrr5522AA)) ) ?5A5A2W.:T 8PAAW:T
::II&&rrrrvv::II
55::22II >>NNHH2:88WW5882:PPN&N????5522WW &&55TT..
55::22II >>55::II22HH AAHHAA

106

        ! " #%$
 & '()*+++-,.0/21'(3,.0/21'(3,.0/21'(3,.0/21'(,4
,4
,4
,4567*98
4&':!6;8<46&':6=8>4&': ?8>4&':@?8>A8<'"B&1:=8>! " A8>   7C$

D

NMC high accuracy polar stereo for SSM/I data

The polar stereo projection used by the original NMC models is not very precise
because it assumes the earth is round (eccentricity = 0). While this approximation
was reasonable for coarse resolution NWP models, it is inadequate to work with
higher resolution data such as SSM/I.

Wind rotation has not been implemented!!! Use only for scalar fields.
E?FGHJI=KJI0LME;N7GONCPQCRSNCPCT7IUE?TVP9GKJE?TVP9GVLWF7XOF7Y NBZ9I

I=K
= # points in x
[ \
0
= # points in y
]C^_C`
= absolute value of the standard latitude
aCbCc7d
= absolute value of the standard longitude
e;f7g
= polar stereo, "eccentric"
h?iVj9kl
= x index position of the pole (where (0,0) is the index of the
m?nVo9pV
first q
point vice the more typical (1,1) )
= y index position of the pole (where (0,0) is the index of the
r7s point vice the more typical (1,1) )
first
t7u = delta x in km
= delta y in km
vBw9x
= 1 for N polar stereo and -1 for S polar stereo

Source code in GrADS for the lon,lat -> i,j mapping:


yz{!|~}}6!6{'~{{~}6z'6~"yB}'V}6z'6~}!z6;}!z!~}!0
}!z!~!6'|{?}!z!~!6|'B-
6z66y~'z 'z|'6{}!{!6'|'|}6z!'{6!|z'z}
'6z6{
6{!|~6zz6'|'{6V z}}6z)B}}-60z'{'6{A

6z66y'{6z!{}|66 6}!~'|~}6-'BBz}
y}'
-
B{'"'6z!!z'}}6|6 !~"!

107
-'6!0!

!B'6'=
!B  
;6BV
!B~!!
#V<)6);
!! 6 6=!6;AA
!!0'06A
!! 6=6!6;6!06!0;'6'?'A

66))9
!6)9
'!7B''C
'!7B'C
')7"!0
'))"!0
6'7B''C
! '6
! '6
')





)>6=6!6;'6'?'6'? 7C>

6 6;6?
 6 ! ! ;
!6 6!' ! ;
 ~  =
!!C  B9
)!0
!6
6=
!6
6=
66;

'6~
;!'=
?06'60'66%!AC
);6!)=-
'~='666
?'V=A2=<'-'V=>6=<0B%!AC

'6~

666 ! ;
'0>A
?=>6'0'66C!AC
)6'90'"'66BC
''!3 66'

~' 7!6!6 ! C9

108
~''67!6!6!
!6 '


!

!6 
!
 )   
!#""!6$"%
&"&"'">("> )
*++,$
-
-

CSU RAMS Oblique Polar Stereo Grids

The CSU RAMS model uses an oblique polar stereo projection. This projection is
still being tested...
.(/101243#5461547.$8:91;=<>;@?6;#;=<>;BA#;#;#;#;=<>;BA#;#;#;#;=<>;C69D<>;
A=<>;C6#E;#;#;#;=<>;C6#E;#;#;#;=<>;

3#5
F1G = #pts in x
= #pts in y
HI$J
K1L=M>L = oblique polar stereo
= lat of ref point (14.0, 9.0)
N OP#P=Q>P
 = lon of ref point (14.0, 9.0 (E is positive in GrADS, W is
R#S#S#S#S S
negative)
T = xref offset [m]
U#V#V#V#V=W>V
XYDZ>[ = yref offset [m]
\=]>^ = i of ref point
_#`a#a#a#a=b>a = j of ref point
c#de#e#e#e=f>e = dx [m]
= dy [m]

Wind rotation has not been implemented!!! Use only for scalar fields.

Source code in GrADS for the lon,lat -> i,j mapping:

g h ijlkk+mhnporqsk+htulvg)tko(wxsk+ht+ulky)i(wxskh tulku i(wxskh tulvz+{ ji|wxsk+ht+u


vz{j })~


hypoulskh tu{t+ji)o)+mm$

109
+pl   +$
  +'+&||) |) (
 )%)$
 ++'+' 1$p |%&%)')(
) '++ '
)$+$) +$ +|
 +)
 +)r
 ) p
 )p 
p p
p p
l)r
l))
++'
)++#+r


l+) p  l++) l++

)


$
p++':
+l
p++ +':



l+) p  l++) l++

)


+)
> + +)+$+
p+ &
) +$) +p)+$


 l+) ++




110
) +
) > + 
l++

 +
) 
) > + 
l++



 l++++rll+|


> +)+
  +r
) + +'
)
+l
)  ++ (
)$

l++

)++$$ +$p+
) + (
+$
) +)
)$
+l
)$

l++



r+ +   +)p+ l
+)
   +p+


+p+&
+ +$+ +  
+ )+$


' ++  )  l+) 

111
 
 


 !
"#  $
%%&'(*)+, (,)-".  
%/*)10%32'%45&'0!   %&&
678)+%%:9;0%* 
%/*) 3<'%45&'!
6 =)->9?,
@%@ '(*)+% .
 
AB    %$
%%&C D)+AE  F) @@ .  
%/*)10%32'%45&'0!  
 %&HG
,#7=)->9I0, 
%/*) 3<'%45&' %&HG
, =)->9?,
  %%B&' F)+%%6.


 :JK L M GL N)-%O %P %'% 
6   


6Q+ %G%  $ 
RB  %G  $ 
%%&'(*)+ Q% (,) @@ 1SC F)-R*   F)+A*. 
%/*)10%32'%45&'0!  %&HG
,#7=)->9I0,  
%/*) 3<'%45&' %&HG
, =)->9?,
 % '% F)- .
 
%%&C D) @@  (,)-B   (*)T %,.
 
%/*)10%32'%45&'0!  %&HG
,#7=)->9I0,  
%/*) 3<'%45& ! %&HG
, =)->9?,
   '% F)- .


  M/(O%% 3(/LB LUHG  % H(  G% V)WG %X4
 E
  LM/(LYB%BO  U%&YB  CO%&B H% G


%%&C D)+AE  F)-R*=   
%/*)10%32'%45&'0!  %&HG
,#7=)->9I0,  
%/*) 3<'%45& ! %&HG
, =)->9?,
 UO' F)+%%6.


  LB %C  @@  GM % H%%B


%%&'(*)+ Q%   F)ZU%*.

112
[%\*]1^%_`3a'bc%deb4f5bcdeb&g'^_`!hKijObc%deb&gHkl,b#m`=]-bcdeb>nI^_`,f5ji
[%\*] _`3o'bc%deb4f5bcdeb&g _`!hKijObc%deb&gHkl,[p`=]-bcdeb>n?_`,f5ji
q%q g'b%_rs,]+bc%de%b6f.h
bc%de%b&gCs[pD]+_tEf+i s[pF]Zqq=f.h
[%\*]1^%_`3a'bc%deb4f5bcdeb&g'^_`!hKijObc%deb&gHkl,b#m`=]-bcdeb>nI^_`,f5ji
[%\*] _`3o'bc%deb4f5bcdeb&g _`!hKijObc%deb&gHkl,[p`=]-bcdeb>n?_`,f5ji
b%uv%wb&g'bs[pF]+bc%de%b6f.h
ij
_
_ dxy3duru[#lz^O[yM[s5pxs_:{|yrOyxsyM\rcMywxOxm [syxp _x3r\
sru}y[rp
_
ji
bc%d}e g'_rs,]+_e6fj_rs*]Tq%qEf1i~]W`{I^%s[pD]+_t*f#js[pF]Zqq=f#js[pF]-buvw b f%f.h
[%\*]1\%bq6s,]-bcd}e,f1a'_`f
duru[#l'gO{h
5xu%sxM
duru[#l'g'b_rs,]-bcd}e6f-iv [`%h

ij
_
_
l rk[\]+[%\5pxs_>{Wfywx&vup4sru}y[rp
_
ji
[%\*]O]1\%bq6s,]-bc%d}`*f1aOduru%[lH%4uy[&ogCsy%ku%byf%]1uy[&a
sy%ku%byfOf
v up`3g3v[`j`%{'^v up`h

ij
_
_ ywxMsru}y[rpC[%sOs#l%l xyc [_HsrOywx3k[cx%_y[rpLl} syLqxH[%\>;xk
_
ji
[%\*]-bcd}`3oO{Ef
v up`3g'^v up`h

ij
_
_ _rp xcyOywx&c bk[bp s&y%rOk%xdcxxs
_
ji
v uy3g3v uy%`iv[`%$h
v upHg3v up`iv[`%$h
ij
_
_ yrOrqyb[p'bcrybyxk&6bu}xV]-[xMsr&m ^bm [s3[pOvru:{Isy%x{vr[pys
x%bsy*f

113
%H%HM%

#%=Z%E.
%


 %5%#z L4 O &%&
%
%: 'M # 3OO%
%?%' % # HO%O6#%
M3%%#6OO %#6%5O6&O%M
&%M%LO

' 

 LM 


%&3 6 : %DT  %*% ,Z *8
%
M'%% *T  %E.
M'%% DT  %E

8T %% %ML >
8T %% %ML >
%

Pitfalls when using preprojected data

There are a few gotchas with using preprojected data:

1. the units in the variable definition for the and components must be F
and 6F (the GRIB standard) respectively, e.g.,
F
u component of the wind at 15 pressure levels
6
v component of the wind at 15 pressure levels

2. wind rotation is handled for polar stereo (N and S) preprojected data, but
not for Lambert Conformal, as the Navy rotates the winds relative to earth.
This will have to be added later......
3. the 8T and E projection are still experimental...

114
GrADS Display Projections
Now that you hopefully understand GrADS data grids, it is time to discuss display
projections. Graphics in GrADS are calculated relative to the internal GrADS data
grid space, transformed to the display device coordinates (e.g., the screen)
F=8then
and >=E displayed. That is, the i,j of the graphic element is converted to
and then to T on the screen via a map projection.

GrADS currently supports four F,D>=D==E :

lat/lon (or spherical);


N polar stereo (E
nps);
S polar stereo (  
 sps);
 the Robinson projection (set lon -180 180, set lat -90 90, set mproj
robinson).

As you can probably appreciate, the i,j-to-lon/lat-to-screen x,y for 



displays is very simple and is considerably more complicated for N and S 
!#"
$#%& " &  projections.

In principle, a Lambert Conformal display projection could be implemented. It


just takes work and a simple user interface for setting up that display projection.
Actually, the user interface (i.e., "set" calls) is the most difficult problem...

Summary and Plans


GrADS handles map projections in two different ways. The first is preprojected
data where the fields are already on a projection (e.g., Lambert Conformal). It is
fairly straightforward to implement other preprojected data projections and we
will be fully implementing the NMC eta grid both staggered and unstaggered,
"thinned" gaussian grids and the CSU RAMS oblique polar stereo projection. The
second is in how i,j graphics (calculated in "grid" space) are displayed on a map
background. Currently, only a few basic projections (lon/lat, polar stereo and
robinson) are supported, but perhaps the development group will tackle this
problem.

115
Variable Formats and Binary Data File Structure
This section describes how to refine the variable declarations in the data descriptor file to
accurately reflect the structure and format of each variable in a binary file. Before
continuing, it is recommended that you review the material in these other sections:

' About GrADS Gridded Data Sets


( Elements of a GrADS Data Descriptor File

In a GrADS data descriptor file each variable declaration record has the following syntax:
)*,+-.*0/21341)#5768-49;:,5=<15?>0+?9A@B:A9
CD-

The VARS section of Elements of a GrADS Data Descriptor File explains the general
syntax of the variable declaration record. This section goes into further detail on the use
of the E8F4G;H,I keyword to invoke some special features that allow GrADS to read binary
files that do not conform to the default structure.

The structure of a 3-D or 4-D data set is determined by the order in which the horizonal
grids are written to file. The default sequence goes in the following order starting from
the fastest varying dimension to the slowest varying dimension: longitude (X), latitude
(Y), vertical level (Z), variable (VAR), time (T).

If your binary data set was created or "packed" according to a different dimension
sequence, then you can use the J8K4L;M,N keyword to tell GrADS exactly how to unpack the
data. The O8P4Q;R,S keyword is actually a series of one or more comma-delimited numbers.
If T8U4V;W,X is set to YY then all the features for unpacking special data formats are ignored.
If Z8[4\;],^ is set to _` , then the features are invoked via additional parameters that follow
the ab and are separated by commas:
c8d4e;f,ghjikmlonqpsrutv
pt0r;wyx{z}|#~

There are four options for qsu


0; , outlined below. Some of these options have
additional attributes which are specified with , .

1. 84;,jm{

This option indicates that "VAR" and "Z" have been transposed in the dimension
sequence. The order is: longitude (X), latitude (Y), variable (VAR), vertical level
(Z), time(T). Thus, all variables are written out one level at a time.

This feature was designed to be used with NASA GCM data in the "phoenix"

116
format. The upper air prognostic variables were transposed, but the diagnostic
variables were not. Thus an , of means the variable has been var-z
transposed, and an , of means the variable has not.

2. 84;,jm

This option indicates that "VAR" and "T" have been transposed in the dimension
sequence. The order is: longitude (X), latitude (Y), vertical level (Z), time(T),
variable (VAR). Thus, all times for one variable are written out in order followed
by all times for the next variable, etc.

Suppose your data set is actually a collection of separate files that are aggregated
by using a template. Then you must use an additional argument to tell GrADS
how many time steps are contained in each individual file. Use , to tell GrADS
the size of the time dimension in each individual file. For example, here are the
relevant records from a descriptor file for 10 years of monthly wind component
and temperature data packaged with "VAR" and "T" dimensions transposed:
,Ds0sDAAA}08A0s
8 D 80,s8
8
s0008D8D,
DA
s4q0 0AD0
s4q0 0AD0
s4q080D, A
s8AD

3. 84;,jm

This option handles the cruel and unusual case where X and Y dimensions are
transposed and the horizontal grids are (lat,lon) as opposed to (lon,lat) data. This
option causes GrADS to work very inefficiently because it wasn't worth it to make
a big change to GrADS internal I/O to handle this type of pathological data.
However, it is useful for initial inspection and debugging and that's basically what
it is designed for.

4. 84;,jm

This option handles non-float data. Data are converted to floats internally after
they are read from the binary file. The dimension sequence is assumed to be the
default. The secondary  tells GrADS what type of data values are in the
binary file:

117
 
   = 1-byte unsigned chars (0-255)
  !"#$"&% = 2-byte unsigned integers
'( ) *+,-./01/2-43 = 2-byte signed integers
56 7 89:;<=>?=> = 4-byte integers

118
Display Topics
Drawing Data Plots
Clearing the Display
Graphics Output Types
Advanced Display Options

Drawing Data Plots


The @BABCD EGFIH command is how you actually display data (output expressions) plots via
the graphics output window. The command is:
JBKBLM NGOIP QSRUT V QXWGWY[Z]\

or
^ _S`Ua b _XcGcd[e]f

The simplest gShUi j gXkGkl[m]n is a variable abbreviation.

If you display when all dimensions are fixed, you get a single value which is typed out.

If you display when one dimension varies, you get a 1-D line graph by default.

If you display when two dimensions are varying, you get a 2-D contour plot by default.

A variety of plot types are available in addition to the above defaults.

Clearing the Display


GrADS will overlay the output from each display command. To clear the display, enter:
oGp4qrUs (or just t )

Issued without parameters, the uGv4wxUy command does pretty heavy duty clearing of
many of the GrADS internal settings. Parameters can be added to limit what is cleared
when using more advanced features, for example:

119
z|{U}~{U[~ flushes the events buffer (e.g., mouse clicks)
G~IG GB clears the graphics, but not the widgets
GG G
clears the display buffer when in double buffer mode

WARNING: If you make any error in the syntax of clear then GrADS does the full
clear...

Graphics Output Types


Before you can display a graph of your data, you will need to set the type of plot you
want and, probably, some other graphics parameters as well.

By default, when one dimension varies, you get a line graph, and when two dimensions
vary, you get a contour plot. These defaults can be changed by the command:
X44[X[ B~ U

Some examples of B~ U are X[GX 4G~ U


G or U[GI~ . For a complete list, see the reference page.

B~ are
There Umany

options that can be set to control how the data will be displayed for each
.

For the graphics output types ~GU[ and U4 , the plotting routines need
two result grids, where the first result grid is treated as the U component, and the second
result grid is treated as the V component. These two result grids are provided to the
display command by entering two expressions separated by a semicolon:
BB GI
BB GII~ I~

For the graphics output types  


  and   , you can specify a third result grid
that will be used to colorize the vectors or streamlines:
"!$# %'& %)(*+-,.#0/1&32
"!$# % &
' %'45"#6 7,.#0/1&32

For a graphics output type 89*:; < , each value at a station location is assumed to be a wx
symbol code number. To see a chart of all available wx symbols and their corresponding
code numbers, run the sample script =>*?@ ACBEDF? .

120
Animation
There are two different ways to animate images within GrADS.

1. Set
GHI the
JKdimension
L"M environment to have three varying dimensions and then
a variable. GrADS will return an animation sequence. By default, the
animation dimension is time, but you may specify a different dimension to
animate by using the following command:
NPOQSR TTPUVWX x|y|z|t

If you wish to animate a variable with fewer than three varying dimensions (i.e.,
animate a line graph), you can control animation by entering:
YPZ[S\ ]]P^_"`a on|off

Remember to bPcdSe ffPgh"ijSfkk when you are done animating, or you will
get a surprise when you display your next expression!

2. Use double buffering, which means you have two display windows, one of which
is always in the background. Double buffering is invoked with the following
command:
lPmn$oPpqrr sPt

When you issue a display command after turning on double buffering, the image
is drawn to the backgound buffer. Then you issue the uwv*x"y command, and
GrADS swaps the background and foreground buffers so you can see what you've
displayed. zw{*|"} works like ~ in that it resets many graphics options. Here
is a sample script demonstrating how to use double buffering:
ww
*
'
'wF
'

)wwww
F
..
.*
''
.w

121
You may also control the speed of the animation by inserting a  following
the w*" command -- then each click of the mouse would move to the next time
step.

Page Control in GrADS


7-7F*F

The "real" page is an 8.5x11 page in the landscape or portrait orientation. The orientation
is specified when you first startup grads. The graphics output window is a representation
of the real page on your computer screen. The graphics window can be any size at all.
You can set the dimensions explicitly (in pixel coordinates) using the set xsize command,
or you can simply resize the graphics window using your mouse. When it comes time to
print the contents of the graphics window to a real page, the screen coordinates (in pixels)
will be scaled so the graphics will fit in the real page in the same way they fit in the
graphics window.

The "virtual" page is a page-within-a-page that fits within the limits of the real page. By
default, the virtual page is the same as the real page, so that real page coordinates are
exactly the same as virtual page coordinates. All graphics are drawn on the virtual page.
The limits of the virtual page may be changed by using the following command:
P *"$ 7 *" 7

After entering a P command, GrADS will return the size of the virtual page
in inches. Any arguments to graphics commands that require page coordinates in inches
are to be given in virtual page coordinates. For example, to draw a plot in the lower left
quadrant of the real page, use the following command:
P *

GrADS will return the following virtual page dimensions:


*P  

If the virtual page has the same aspect ratio as the real page, Grads will give it the same
dimensions as the real page -- in this case the virtual page is a mini version of an
11"x8.5" page. Here's another example where the virtual page is a centered square:
 !"$#
#%"$#
GrADS will return the following virtual page dimensions:

122
&(')+*,-.0/-1234'5267 89:7 89
On the real page the plot will be within a 3" square, but on the virtual page in Grads the
plot will be within an 8.5" square. Remember that any arguments to graphics commands
that require page coordinates in inches are to be given in virtual page coordinates.

To return to the default state where the virtual page equals the real page, enter:
; <=>?@A<B+CC
DFEHG(IKJLEHMNMPOPGRQSIUTRVXWYMZEYI%[%JLV\[
It is possible to control the area within the virtual page where GrADS draws contour
plots, maps, or line graphs. The command is:
]^_`ab^ca d4e(fhg
d4ejikd lme(fhg lmejikd
This area does not include axis labels, titles, color bars, etc., so be sure to provide for
adequate margins in order to see these features. Note that the plot area is specified in
terms of virtual page units.

GrADS chooses an appropriate default plotting area depending on the type of graphics
output. To return to this default, enter:
nopqrsocr t+uu
Line graphs and contour plots that don't contain a map will be scaled to fill the entire plot
area. Any plot that contains a map projection will be scaled to fit within the plotting area
while maintaining a correct lat/lon aspect ratio. Thus, the map may not fill the entire
plotting area except under certain lat/lon ranges. This feature may be turned off by setting
the map projection to "scaled". See the reference page for set mproj for additional map
projection options.
vFwyxz|{~}R%Z{Z"x}R(Y
h\c+ $  $
For drawing multi-panel plots, use 
to define several virtual pages that fit
within the limits of the real page. Virtual pages may overlap. The sample script called
demonstrates how to set up virtual page coordinates for a multi-

called h\c+H$4
panel plot with a specified number of rows and columns. It uses a GrADS script function
.

If you want to place a label or some other graphic element in each panel, the position is

123
given in virtual page coordinates. These coordinates will be the same no matter which
panel you're in. This makes it easy to shift the labels in one direction or another to
accomodate the graphics.

Do not use c


to draw multiple plots on one page. That is not what
was designed for. It is far better (and easier!) to use the command as  c
described above.

Controlling Colors in GrADS


The GrADS Default Colors

GrADS is built with 16 default colors that are used in a variety of applications. Every
color in GrADS has a unique color number that is used as an index to identify it in
GrADS commands. Complete specifications of the default colors numbered 0 to 15 are
given below:
 kkm m
kmm kXmh
m h y mmmh
hU
k S
mXk S
k SS
mm k
km kS "
mm k
  S
kmk S "
mSk S
m m k
k S
124
m X   


   
Disclaimer: The color samples may not be displayed properly.

The GrADS Default Rainbow Sequence

GrADS creates a default rainbow palette using the following sequence of 13 built-in
colors:
9 14 4 11 5 13 3 10 7 12 8 2 6

When drawing contour plots, the default behaviour of GrADS is to color code the
contours and select an appropriate contour interval so that each contour is a different
color and the colors span the range of the default rainbow sequence. The same principle
is behind the selection of default contour intervals for filled contours and shaded grid
plots.

The scripts !#"$ and %&'()+*-,!.#/$% will draw a color key alongside a plot of
filled contours or shaded grid cells; the script uses the 021$324+5 678:9;3<6 command to get
information about the contour levels and their color shades.

Defining new colors

For some types of displays, the 16 GrADS default colors may not be suitable or adequate.
It is possible for the user to define new colors using the =2>+?A@CB+D command:
E2F+GAHCI+J K2L2M<LN<OQP RTS

For example, let's create a palette of colors for plotting anomalies. We need to define new
colors that will be shades of blue and red that range in intensity from fully saturated to
very light. White will be the color in the center of the new anomaly palette.
UWVXYZ Y\[^]Y`_XYWab cdeZ X[fYZ
ZY_g]hi jk l l mnn
ZY_g]hi jo nn nnpmnn
ZY_g]hi jqrjj l\jj l mnn
ZY_g]hi j s\jkntjknpmnn
ZY_g]hi ml mml mml mnn
UWVXYZ Y\[^]Y`_XYvud wxZ^X[ fYZ
ZY_g]hi m j\mnnpmml mm l
ZY_g]hi mmrmnntjkntjkn
ZY_g]hi myvmnntjj l\jjl
ZY_g]hi mz mnn nn nn

125
{|}g~ p

Overriding the Defaults

Now that we have a set of newly defined colors (numbered 16-25), we can override the
defaults and specify our anomaly palette with exact contour levels and the colors that go
with them. This is accomplished by using the following commands:
2+C+ ;;; CC;
2+C: 22: 22+ 22 CC22

Contour levels and the colors that go with them are reset with every execution of C+;
or C . Thus, it may be easier to use these commands in a script to avoid typing
them over and over again.

Filled Contours or Shaded Grids: If you are specifying the levels and colors for filled
contours ( 2+A+<2< :;+ ) or shaded grid cells ( 2+A+<2< C$CCC ), then
the number of colors specified with set ccols must be one larger than the number of
contour levels specified with set clevs. Continuing with our example of creating an
anomaly palette, the commands would have the following syntax:
2+A+<2< :;+

2+C+ #A+:
2+C: ;AC+:+C<Q2

Note the "0" contour level has been omitted, but color number "1" is still in the palette.
Drawing a plot with these specified C+ and C: and then running the "cbarn.gs"
script will result in the following color key:

Here is example using 6 colors and 5 contour levels that shows how the filled contours
(or shaded grids) relate to the data values:
# W^
  ^`gW^
 ^ggW^
 ^gW^
+ ^rgW^+
# ^+ g

126
Line Contours: If you are specifying the levels and colors for line contours (

 
  
 ), then the number of arguments to set clevs and set ccols should be
equal -- one color for each contour.

Plotting Contours of Constant Color

It is sometimes preferable to plot line contours without the rainbow coloring. An example
might be a plot with sea level pressure contours in one color (red) and 500 mb height
contours overlaid in another color (blue). For drawing all the contours in the same color,
use the     command:
 !  " # !$
"" % $ &
'  %)(
"" % $ *
' +-, %/.02143325

Omitting Colors

The default behavior of GrADS when plotting filled contours or shaded grid cells is to
colorize all areas. To omit a particular color (or contour level) from the plot, simply
assign the background color. For example:
6789: ;< 8 6>=@? A7A
678BC7/DE6 F GIF/JKFLFMNF OPONMQLIJ G
H
678BB ;C6 RNOSOTPOUM RPRMONMMPM LVMJNR

This example is similar to the one given above, but notice where some of the WW XYZ
have been set to "0" (the background color). The first, last, and middle colors have been
omitted. These commands set up a plot that will only shade areas where the anomalies are
between 1 and 5 and -1 and -5. The remaining areas will be black.

Plotting Non-Continuous Index Grids

Plotting grids with index values or non-continuous data (e.g. surface type classification)
is simplified by using the graphics output type [/\]_^ ` and the abcd/ef@gha command.
ijklm no k /p lq_r s
ijkp/lt@uvi Pw wyx{z x}|}w
s i p~ k_j

In this example, the variable /  _E has three values: represents land,

127
represents oceans, and represents sea ice. These commands would draw a plot with
land grid cells filled with color number 15 (gray), ocean grid cells filled with color
number 5 (light blue), and sea ice grid cells filled with color number 1 (white). If the first
two arguments to set fgvals were omitted, then the land grid cells would not be omitted
and only ocean and sea ice grid cells would be colored.

128
Font File Format
GrADS currently supports fonts numbered 0 to 9. Fonts 0 to 4 are provided with the
GrADS
 ydistribution.
 The files are named   ,   , etc. If you create a
file (or through ) and put it in the same place as the other font files, you
can use that font immediately, by   5, or via font escape sequences.

The font files are in an ASCII format. Each file is 95 records in length. Each record
represents a character in the font, and the records are ordered in the order of ASCII code
values, starting with the blank (code value 32 decimal). So the last record represents the
tilde, the 17th record the zero, etc. So when you are using the font the file represents, and
enter a zero character, the character in the 17th record is plotted, whatever it may be.

Each record starts with a 3 character number. This is the number of code pairs in the
record. This number is followed by the indicated number of code pairs. Each code pair is
two characters. Each character represents a value, which is determined as an offset from
the Capital R (decimal 82). So, if the character is Capital L, it represents a value of -6. If
the character is a lower case k, it represents a value of +25.

The first code pair represents the horizontal extent of the character. So the first character
of the code pair would be the minimum X, and the 2nd character the maximum X. If I
remember correctly, this extent should include white space. This is followed by code
pairs that represent drawing positions in X and Y, where the first character is X, and the
2nd Y. A "pen up" is indicated by the code pair " R" (blank, followed by capital R).

You can look at the existing font files for examples. If you look at   , the first
record represents the blank. It thus has one code pair, which just represents the width of
the blank in the font, thus allocating white space when a blank is encountered. If you look
at record (which represents Cap X), you see: /)@ Decoding this, you
see there are 6 code pairs. The first is the width extent,  , which is -10 to 10. The next
two pairs, ) , are points -7,-12 and 7,9. So a line would be drawn between those two
points (appropriate scaled). The next code pair indicates pen up, followed by @ ,
which are 7,-12 and -7,9.

You can see the horizontal extent does not match too well with the actual character. I am
not quite sure why this is, nor why the character is not centered. This is the way the fonts
came, so I assume there are some font design issues involved.

If you want to design your own font, you will need to review the code GraDS uses to
actually plot these fonts, which is @)@ . I determined scale factors and centering
issues by trial and error, and these values are contained in the code.

129
130
Producing Hardcopy and Image Output from GrADS
-E@yH-2

There are two different GrADS commands that will convert the contents of the graphics
window into an image file. The differences between them are the image formats they
support and the way they are implemented in GrADS. _) > is newer and will only
work with GrADS version 1.8.

wi

The command dumps an exact copy of the GrADS graphics window directly to an
image file. It supports a large variety of image formats: GIF, BMP, CGM, EPX, FAX,
ICO, JPEG, PCS, HDF, and many others.  requires an active connection to an X-server
-- it will not work in batch mode. Consult the reference page for details.

printim

The  
 command produces a PNG or GIF formatted image file based on the
current contents of the GrADS metabuffer, which is the stuff displayed in the graphics
window, minus any widgets.     will work in batch mode. Consult the reference
page for details.
!#"$&%'(*),+.-0/1  23"546&7

1. Set-up the GrADS metafile

The first step in creating hardcopy image output is to enter the command:
8:9!; <!=>8@?A B 9 C DFEFG!HJI&KJLH

This opens the output file MFNFO!PJQ&RJSP and enables GrADS to direct image information to
that file. Any existing contents of TFUFV!WJX&YJZW will be lost.

2. Display the image

The next step is to display the graphic that you want to print. When you have finished,
enter the command:
[\ ] ^ _

131
GrADS copies the vector instructions used to create the current display into the output
file in a GrADS metacode format.

3. Close the GrADS metafile

There are three way to close the output file:


` abdc e!f>g@hi a j k
i ga j!adk
lnm adk
oqpsr tvuwx#y$r&z'{(w*|~}u x 3y56u&,xppx w#yx

GrADS metacode files may be translated into postscript using the GrADS external
utilities >F and > : . Both utilities will prompt for input and output filenames,
unless they are provided on the command line. The input filename should be the file
created by the :! !>@ command. The output filename can be anything, but a
".ps" extension is conventional. Any existing file with this name will be overwritten.
Once the output file is created, you may print it using UNIX print commands. Please
consult the references pages for >F and > : to see all the command line arguments
and options.
>F
and > : are not GrADS commands. They must be executed from the UNIX
command line, or preceded by a and executed as a shell command from the GrADS
command line.
$&'(*~! 356&

GrADS metacode files may be displayed using the GrADS external utility > d . The
input filename should be the file created by the :! !>@ command. If the
GrADS metafile contains more than one image, > d will animate them. The
animation can be automatic or controlled by the user with carriage returns. Please consult
the gxtran reference page to see all the command line arguments and options.
$&'(*~! 356&,#,

The GrADS metafile Viewer (GV) allows you to view and manipulate GrADS graphics
output files using Windows 95/NT. There are two files to download:

 gv32.exe
 gv32.hlp

132
To open the metafile simply double click on a file listed in the File Manager or Explorer,
drag and drop the file onto GV, or use the standard Open dialog box. GV assumes that
default extension of GRADS metafiles is GMF. If your file includes more than one
picture you can browse through pages using the keyboard keys (PageDown and PageUp)
or the toolbar buttons.

Use the View commands and the View/Options dialog box to customize the image --
display it as black-and-white or color, change the line thickness, or clip and enlarge any
part of the image. Use the right mouse button to access the most commonly used features.

There are two ways to save separate pages of a GRADS metafile as Windows Metafile
(WMF): 1) use the File/Save Page As command, or 2) use the Edit/Copy command to
copy the current page to the Windows Clipboard and then Edit/Paste it in your favorite
Windows application that handles Windows Metafiles.

Use File/Print command to print a current document to any printer (you do not need a
Postscript printer). Use File/Print Preview to display the active metafile as it would
appear when printed.

133
GrADS Scripting Language
Introduction to GrADS scripts
Elements of the Language:
comment
statement
assignment
say / prompt / pull
if / else / endif
while / endwhile
variables
operators
expressions
Functions
Intrinsic Functions
Commands that complement the scripting language
Widgets
Script Library
Scripting Language Reference Card (Requires Adobe Acrobat Reader)

Introduction to GrADS Scripts


Scripts offer users the facility to program GrADS operations. Although it is relatively
easy for users to produce sophisticated GrADS graphics without ever writing a script,
there are occasions where the programming capability makes things even easier. This
section explains the general capabilities of scripts, how to run them, and suggests a
strategy for users who may wish to write their own.

What scripts can do

The GrADS scripting language, used via the GrADS


 command, provides a similar
capability to the 
 command, except that scripts also have flow control, defined
variables, and access to GrADS command output. Scripts may be written to perform a
variety of functions, such as allowing a user to interact with Grads via point and click
interface, animating any desired quantities, and annotating plots with information
obtained from GrADS query commands.

134
The scripting language is similar to REXX in implementation. All variables are of type
STRING. Mathematical
 operations

 are supported on script variables. Flow control is
achieved via and 
!"# constructs. Loop flow may be
modified by the $%&'(#&) * or + ,- .
/ commands. Strings contained in variables or
generated via an expression may be issued to GrADS as commands. The output from
those commands (i.e., the text that GrADS would have output to the terminal) is put into
a variable and made available to the script. The language includes support for functions.

Before writing your own scripts, it is recommended that you read the rest of this section
and then try to run some of the scripts in the library. Study these example scripts,
referring to this page for information on syntax etc., and you will soon be equipped to
write scripts of your own.

Running scripts

The command to execute a script is the 012 command:


345 6789;:=<;>?9A@ 8CBD<FEG?HI>?9;:JBFK#L

This command runs the script contained in the named file, which generally has a MONQPSR M
tag at the end. Optional TFUV?WIX?Y;ZJ[F\ are passed to the script as a string variable. You
may issue any GrADS command from a script, including the ]^_ command. When
calling scripts recursively, be sure that you can back out of the recursion and return to
your main script.

Automatic script execution

You may have a simple script automatically executed before every `abFcde#f command:
ghikjFlm nop q r;s tvuxwy{z=|;}?~

Fscript
This # would typically be used to set an option that by default gets reset after each
command, for example:
  off

You can issue any GrADS command from this script, but the interactions are not always
clear. For example, if you issued a F# command from this script, you could easily
enter an infinite recursion loop.

The argument to the script is the expression from the F# command.

135
Storing GrADS scripts

isDconvenient
It to put
 all
#your
#GrADS

#"utility"
scripts in one directory (e.g.,
).

To simplify running these scripts, GrADS first looks in the current directory for the script
and then, if it can't find it, appends the " QS " extension and tries again. For example,
suppose you are working on a test script called QS . You would run it in GrADS by,


If after the first two tries, the script still can't be located, then GrADS looks in the
directory defined by the environment variable  . In the ?;F , for example,

#S  ##

or in SF ,

 #S  ##

Note the if the is not added to the end of the directory name, it is automatically added
by UNIX. However, it'll still work if you type

 
S   

If the script cannot be found, then  is appended and GrADS tries yet again. Thus,
 "#
!
$%&(' ) *+,-'.$/  ' "01 ' 2 1 /3$&54.

simplifies to,
6 7 89
!
:;<>=?A@3:<

Elements of the Language


A script file is made up of records. The end of a script record is determined by either a
newline character or a semicolon (where the semicolon is not contained within a constant
string).

136
Each script record may be one of the following types:

B comment
C statement
D assignment
E say / prompt / pull
F if / else / endif
G while / endwhile / break / continue
H function header / return

Many of the above record types will contain expressions. Script expressions are
composed of operands and operators. Operands are strings constants, variables, or
function calls; operators are mathematical, logical, or concatenation operations. Further
discussion of these record types and the expressions they may contain is given below.

Comment

Comments in GrADS scripts must contain an asterisk (*) in the first column.

Statement

The statement record consists only of an expression:


IKJ3LAMNIOO P QSR

The expression is evaluated, and the resulting string is then submitted to GrADS as a
command for execution. The script variable TU will contain the return code from the
GrADS command (this will always be an integer value). In addition, any text output from
GrADS in response to the command is put in the variable V W XZYA[ \ for examination by
the script. A GrADS error resulting from an invalid command WILL NOT terminate
execution of the script.

The simplest type of expression is a string constant, which is just a character string
enclosed in single or double quotes. Here's an example of simple script containing a
comment plus statements comprised of string constants:
]_^`Aabcabcd(b dZefAghib j3kaf ^
lnm fh3ocepqrbb3^sqtd ^dbh^vuwj ^g l
l bh^(gd ^(xyz>yz l
l bh^(g m o({z>yzz l
l tabZfAgdp bb3^ l

Assignment

137
Assignment records are used to define variables and assign them values. The format of
the assignment record is:
|A}3~}Ac K3AN S

The expression is evaluated, and the result is assigned to be the value of the indicated
variable. The same example from above can be rewritten to include assignment
statements. Note the use of explicit and implied concatenation:
n 3cr3s vw 
A i
A A (
A (
A (>
( A A
(  A 5A 
nZA 3v

say / prompt

To present information or questions to the GrADS user via the terminal (standard output),
use the  or  commands:
 K3AN S
 K3AN S

The result of the K3AN S is written to the terminal. The  command works
the same way as the  command but does not append a carriage return. It is possible to
combine variables and string constants when writing to standard output:

For example:
c K 5 A(
>
   ( ( 

gives:
5 A 
    
  ( ( 5 A 
pull

138



To retrieve information provided by the GrADS user via the terminal (standard input),
use the command:

 
 
The script will pause for user input from the keyboard (ending with the carriage return),
and then the string entered by the user is assigned to the indicated variable name. To
elaborate on a previous example:
65 !7$#"%* $&9')8"(
*6(#*+!'-5:,$<.*;7"=.(!.7"*0,>/21$<*.734?= 3
.*;*@,6!(BAC

@65 73
$3D*$<;7" 983
".*>*6!$<5:.7$<? 3
;7"=.* .7",>$<.7?=3"6E;*@,6!(BAC

@F (!3
*3D$<3
;7." * 3G$<"%;7$<" .73
? .*73HI" CGH
$<.7? 3
.*
F,(!;*( 33
.7&" (
G$<(#*0;7"  3"JCG$<.7? 3"
if / else / endif

One way to control the flow of script execution is via the


The format is as follows:
K
LMN6OPNMN#QRK
L construct.

S
TVU#ZW
]#X6YYS7XU^%Z
ZYS[U6\][Y_
Z]#YS7X^%YU6][Y_
``
U6aZUZ]#YS7X^%YU6][Y_
``
U#\_S
T
The b6cdb block is optional, but the e#fgh
i record must be present. The script records
following j
kVl#m
n6olp
pjqr are executed if the expression evaluates to a string
s
t
block are not executed and the script continues with the u6vwu block (if it is present)
containing the character 1. If the expression evaluates to 0, then the script records in the

or the record following x#yz{


| . The }
~V#
6
} record must be separated from
the script records that follow it. For example, the following script record would be
invalid:

:>
139
The correct syntax requires three separate script records. This is achieved by putting each
record on one line:

:
#

Alternatively, the three records could be on the same line separated by a semicolon:

:  #

N.B. There is no 66


construct in GrADS.

while / endwhile

Another method for controlling the flow of script execution is the


construct. The format is as follows:

#7


C##7
6%6

#7%6

#7

The script records following 
C#
6
 are executed if the expression

script records in the 


 block are not executed and the script continues with the
evaluates to a string containing the character 1. If the expression evaluates to 0, then the

record following #7


 . The 
C#
6
 record must be separated
from the script records that follow it.

6
6additional
and
script commands may be used to modify the 
 loop execution:
+ . Inserting the 6  statement will immediately end execution
Two

of the loop and the script will move on to the records following  
 . The
   statement will immediately end execution of the loop, but the script will then
branch immediately back to the top of the loop, and the expression will be re-evaluated.

While loops are often used as counters. For example:


 !#"
$ % &'( ) !*#"+-,
.0/ ( 1 . 
.32 & /54 '6 798 .

140
:; <>=? @BA1C-D EGF=HIJ EKHLM :;
?NOLP!AQ?NOLP!R#S
HLM T U :VH

Variables

The contents of a script variable is always a character string. However, if the contents of
a variable represent a number in the correct format, certain operators may perform
numeric operations on that variable, giving a string result which will also be a number.

Variable names can have from 1 to 8 characters, beginning with an alphabetic character
and containing letters or numbers only. The name is case sensitive. If a variable has not
yet been assigned, its value is its name.

String variables or string constants are enclosed in either single or double quotes. An
example of an assignment statement that defines a string variable is as follows:
W X5Y[Z]\ `^ _ZaZb1_X Wdc
W X5Y[Z]\ ef_ZaZb1_X Wge

Numeric variables may be entered without quotes, but are still considered strings.
hij klm#nQopprqspp

Predefined script variables

Some variable names are predefined; it is a good idea to avoid assigning values to these
variables. The following are predefined script variables -- their values will change with
every execution of a GrADS command from the script:
tu
tvw5x yz
y{z}|~yd|~yvd| and 5[ are also used as predefined variables in GrADS.
Although using them within a script is okay, in order to avoid confusion it is not
recommended.

Global string variables

String variables are usually local to the functions they are contained in. Global string
variables are also available. They are specified via the variable name. Any variable name
starting with an underscore (_) will be assumed to be a global variable, and will keep its
value throughout an entire script file. An example of an assignment statement that defines

141
a global string variable is as follows:

  ! f   !
N.B. Global variables cannot be used in function headers. For example:
  Q ` 

wouldn't make sense, since   is a global variable, and would be invalid if it were the
only argument.

Compound string variables

Compound variables are used to construct arrays in scripts. A compound variable has a
variable name with segments separated by periods. For example:
 5[`

In this case, when the variable contents are accessed, and will be looked up to see if
they are also variables (non-compound). If they are, the and will be replaced by the
string values of and . For example:
#

 5[ [

In the above example, the assignment is equivalent to:


 5[3r0[

Note that the string values of and may be anything, but the variable name
specification in the script must follow the rules for variable names: letters or numbers,
with a leading letter. The variable name after substitution may be any string:
[ d
 5[[

The above is valid. However, we cannot refer to this variable name directly:
 5[[ [

would be invalid.

142
Variable names may not be longer than 16 characters, either before or after substitution.

Note that the GrADS scripting language is not particularly efficient in handling large
numbers of variables. Thus compound variables should not be used to create large arrays:
#

  
f #
 

Q #
Q
 

The above loop will create 10000 distinct variable names. Such a large number of
variables in the variable chain will slow the script down a lot.

Operators

The following operators are implemented in the scripting language:



 logical OR
 logical AND

 unary NOT
unary minus
  equal
 not equal
 greater than
 greater than or equal
 less than
less than or equal
! concatenation

"# addition
subtraction
$ multiplication
division

The following operators will perform a numeric operation if the operands are numeric:
%'&)(%'&+*'&+*%'&+,'&+,%'&+-'&/.0&213&+4
If any of the following operations are attempted with non-numeric operands, an error will
result:
5'6/7062836+9
143
:
Arithmetical operations are done in floating point. If the result is integral, the result string

;
will be an integer. Logical operations will give a character (zero) if the result is
FALSE, and a character (one) if the result is TRUE.

Expressions

Script expressions consist of any combination of operands, operators, and parentheses.


Operands may be string constants, variables, or function calls. The precedence of the
operators is:

I<0=) @
> B
? 
A
C
D 
E H
F G
KL =2=/<J
PRM Q =)> M =+N'=+N M =+O'=+O M
Within the same precedence level, operations are performed left to right. Parentheses
modify the order of operation according to standard convention.

All script expressions, including all function calls, etc. are evaluated and the resulting
string is what gets executed as a command. For example:
S bT c UWVYd S X[ \
Z V ^
]
S
T 
U
T UWVoqpefS rsuT tU_`l g) `
_ )
X 
V a
Vswa`vfxyhiv zS s T l UWVYT Uji as\Uk {|v}o
l n
T m W
s \
T
vw~ l vl Tnm o b s b l zrsisut|v)T l vYsut T\sprsut l sWT\swvfxyv zs l T Uv Y
v
s\v zU{| v}bc o
For the expression following  , both sides of the logical operation must be evaluated
before the entire expression can be simplified into a true or false result. In this case, the
subexpression on the left is true, but the subexpression on the left is not, so the whole
expressions resolves to 0 (zero) and the script will print:
\Wiu|)WuYu \u W\wfy |` Y\|
Concatenation

In some espressions, the concatenation operator may be implied. The operator may be
omitted whenever the two operands are a string constant and a variable name. With

144
implied concatentation, intervening blanks will be ignored.

For example, the following expressions have the same effect:


u\ n \nin \
u\ n \in \
uses the concatenation operator
%
concatenation is implied

Assuming two previous statements, n \Y[Wn and n \Yn , the


resulting expression would be:
u\Wnn'
Keep in mind the order of precedence when using the concatenation operator.

Functions

Function calls take the form of:


yH    
where the function name follows the same rules as for variable names, and the arguments
may be any expression. Functions may either be contained within the script file itself, or
the may be intrinsic functions. Functions contained within other script files are not
supported as yet (other script files may be executed via the GrADS run command).

In either case, functions are invoked as a script expression is being evaluated. Script
functions always have a single string result, but may have one or more string arguments.
Functions are invoked by:
yH    
If the function has no arguments, you must still provide the parentheses:
yH
n \may
You W\uprovide
your own functions from within your script file by using the
definition record:
n \W\ui yHB |n }^ |n }i
To return from a function, use the  command:

145

    

The !!"#$ is optional; if not provided, a NULL string will be returned. (A null
string is: '') The result of the function is the result of the expression specified on the return
command.

When a function is invoked, the arguments are evaluated, then flow of control is
transferred to the function. The variables contained in the list within the function
definition record are initialized to the values of the passed arguments. If too few
arguments where passed for the variables specified, the trailing variables are
uninitialized. If too many arguments are passed, the extra arguments are discarded.

You may modify the variables from the function definition record without modifying the
variables from the calling routine.

Scope of variables is normally local to the function, but can be global.

When a script file is first invoked (via the %&' command), execution starts at the
beginning of the file. A function definition record may optionally be provided at the
beginning. If it is, it should specify one variable name. This variable will be initialized to
any ()* command options. If no options were given, the variable will be initialized to
NULL.

Intrinsic Functions
+,-/.021 34576829:<;=9>
This function gets a single line from a string containing several lines. The result is
the ?A@CB line of DFEHGJILKM . If the string has too few lines, the result is NULL. N
must be an integer.
OPQRST UVW7XY2Z[<\=Z]
This functions gets a single word from a string. The result is the ^A_C` word of
aFbHcJdLef . If the string is too short, the result is NULL. g must be an integer.
hijFhLkl mno7pq2rs<tuno2vLpwoFtyxz{rs|o~}
This function gets part of a string. The sub-string of FHJL starting at location
F2{ for length C will be returned. If the string is too short, the result
will be short or NULL. F2{ and C must be integers.
 L{/{
This functions reads individual records from file | . Repeated calls must
be made to read consecutive records. The result is a string containing two lines:

146
the first line is the return code, the 2nd line is the record read from the file. The
record may be a maximum of 80 characters. Use the {L function to separate
the result. Return codes are:

ok
open error

end of file

file open for write


I/O error
Files are opened when the first call to read is made for a particular file name. Files
are closed when the execution of the script file terminates (note that files remain
open between function calls, etc).
L{/{|/2/
This functions writes records to output file {/
. On the first call to write
for a particular file, the file is opened in write mode. This will destroy an existing
file! If you use the optional append flag, the file will be opened in append mode,
and all writes will be appended to the end of the file. Return codes are:

- ok
- open error
- file open for read
L/2 /{
This function closes the named file. This must be done if you wish to read from a
file you have been writing to. This can also be used to rewind a file. Return codes
are:

- ok
- file not open

Commands that complement the scripting language


There are some GrADS commands that, although not designed exclusively for scripts, are
most useful in script applications. These include:
 
  or  
  

To see the list of available options, issue the  command by itself. A
description of the !" options that are most useful for script applications
follows.

147
# $&%')(
* % -- Lists all defined variables

+ ,&-.
/013245&687945&6 -- Gives defined grid value at ival, jval

To interactively modify grid point values for a : ; <&=?>;: variable, @ A B C?DFE&G


can be used in conjunction with HIJ3K I L?MFN&O . For example, the code shown
below queries the value of sst at gridpoint(i,j), then tests to see if the value is less
than -1.6, and if it is, sets the sst to a bad value.
PRQ3S T U?VFW&XZY&Y\[ P^]_P3Pa`
VFW&XcbdY e&fhgi)SkjliTY eFXh[nmpoq
]&U jrVFW&Xcsuthvnwyxzq
PpYT[3S T U?VFW&XZY&Y\[ P^]_P3Pa`{P3P|fFWhS
}VFW&X?eT
T\~S)]&U

 F -- Gives the current dimension environment

)&? -- Gives info on file number n

)&? -- Lists open files


F\ -- Gives the name of the file used for fwrite operations

\z
 -- Lists graphics settings

This option is handy when trying to find the plot area. The output from
F?Fh might look like this:
)\&?&F&c?
\&&&c&un
Z zhZ&3
u zh3^8&Z_^
?F))z?F)z&
) )Z

The first line indicates that the output is a line plot. The second line gives the page
dimensions -- in this case GrADS is in landscape mode. The third and fourth lines
give the x and y boundaries of the plot. In this case the plot has 1-inch margins in
the x direction and 0.75-inch margins in the y direction. The fifth line tells what
kind of axes you have, and the sixth line identifies the map projection:

Scaled (no preservation of aspect ratio)
Latlon (2-D horizontal fields)

148

Northern polar stereographic
Southern polar stereographic
Robinson (lon range must be -180 to 180 and lat range must be -90
to 90)
-- Waits for mouse click, returns position

)& -- Gives colors and levels of shaded contours

 ) - gives time range of current open file

F
?
h &&
F&&&
F -- Coordinate transformations

where zzh  is one of:


& XY coords to world coords
 XY coords to grid coords

  world coords to XY coords
  world coords to grid coords

grid coords to world coords
 grid coords to XY coords

XY coords are inches on the page (screen) where the page is 11x8.5 inches or
8.5x11 inches, depending on how GrADS was started.

World coords are lat, lon, lev, time or val, depending on what the dimension
environment is when the grid was displayed. Note that time is displayed (and must
be specified) in GrADS absolute date/time format. val is the value coordinate for a
1-D plot (linegraph).

Grid coordinates are the i,j indices the grid being displayed. For station data sets,
grid and world coordinates are equivalent except for the time dimension. Note that
if you display a grid from a 'wrapped' data set, the grid numbers may be out of
range of the actual file grid numbers. (A 'wrapped' data set is a data set that covers
the earth in the longitude direction. Wrapping takes place automatically). The
conversions are done consistently, but you may want to be sure you can handle
the wrapping case if your data set is global.

N.B. Coordinate transform queries are only valid after something has been
displayed, and the transformations apply only to the most recent item that has
been displayed.
!#"$&%('*)&+,!- .(,

149
When using the graphics output type /0214325671 findstn, three arguments must be
provided with the 8&9&:<;>=?.@ command. The first argument is a station data expression.
The 2nd and 3rd arguments are the X and Y screen coordinates of the of the desired
search location. GrADS will find the station closest to the specified X and Y position,
and print its stid, lon, and lat. This graphics output type should only be used when X and
Y are the varying dimensions and AFTER a regular display command (that results in
graphics output) is entered.
AB!CED2F2G>HHJI2KMLNIHH

This command sets double buffer mode OP or Q&RR . This allows animation to be
controlled from a script. The ST2U!VW command also sets double buffer mode X&YY .
Z\[](^

Swaps buffers, when double buffer mode is _` . If double buffer mode is a&bb , this
command has no effect.

The usual usage of these commands would be:


cd2egfhi>jj4kl
ce&mn&e*o(kkp>q.l!r
f&q&c<p>om.s t!uwvyxz|{>}.~2
\.
&(
2g>4&

Widgets
GrADS has the capability to implement a graphical user interface. This interface is used
to draw widgets (buttons and pull down menus) that allow a "point and click" interface
between the Grads user and the scripting language.

Here is a sample from a script illustrating how to draw a button:


|
|
|w||
|\|wwww
<w(ww|

150
The reference pages for 2J and (<* contain information on how
to specify the button characteristics and position.

A button's initial "state" is ! . If a user clicks on a button following a J command,


then the button state will switch from ! to  . A second J followed
by a mouse click on the button will return it to the ! state. The button state may also be
changed with the 2(<* command.

The output from the J command is what makes the button widgets so useful. Here
is a template of what J returns after a mouse click on a button:
&( 

    !"$#%&'() %*+$,
 --(. 

where:
/ 0 1243650 12 - coordinates of the mouse click in virtual page units
789 :;<9==8> - either 1, 2, or 3 for the left, center, or right mouse button
? @A$B%CDEFGHH - 1 is the widget class number for buttons
IJKKLMM%J*N+IO$P
- the number assigned to the button when it was originally
QRSSTU-V-SW.S X
drawn
- either 0 (meaning "off") or 1 (meaning "on")

If the user did not click on a button, then Y Z[$\%]^_`abb will be 0 and there will be no
output for cdeefgg%d*h+ci$j or klmmno-p-mq.m r .
sutwvyx{z}|~ 

As with button widgets, dropmenus provide a "point-and-click" interface between scripts


and the GrADS user. The reference pages for ).  and . 
contain information on how to specify the dropmenu characteristics and position.

The output from  after a click on a dropmenu is similar to that described above for
buttons. Here is a template of what is returned by  after a mouse click on a
dropmenu:
    $% %%*+$
%*

where:
46  - coordinates of the mouse click in the menu base in virtual

151
 units
page 
- either 1, 2, or 3 for the left, center, or right mouse button
$% - 3 is the widget class number for dropmenus
%%*+$ - the number assigned to the dropmenu when it was
%*
originally drawn
- the menu item number selected from the menu list

If no menu item is selected, then %%*+$ and %* will both be -1.

Here is a script sample illustrating how to use a dropmenu:


**
******.
***.
***$.
               "!$#%  &!
(' )  "!
** *   $ .
* * *  $  
* + &

 *   !,/-.

+  34 1 0    2

 w $*  *
$
   :// ))  5050   77696;8 22


 $$
 $$
<=<0>     :):/ /2 @? )  4/ A%   4/B#  ?  <

 *

$ *
<<  )):
 *
 * :
 //EC F
D ?? ))  44// AA%%    44/ / '*   + ??  <<
$
$
*
*
 -
$


 <   ):
*
 *
  / GH? ) 7  4/  A%    4/:!$#%-. &!(' ? )  <  "!
$ *
 $
-


$  
*  + &!, - . /

 *

)+  <

*

Here is another script sample illustrating how to use cascading dropmenus:


IKI9J QMLR4MN)OPOSI TVU WVXW WVXW WVXW WI
I9I9QQMMR4R4OOSSTV V
T UUX[X[W YZWV

W X[W YZWV 
W X[W YZWWII
I9I aQOMR4NbT \T\R RR]R ^]^X XU X 
X 
c _XX _WeXdfX YhU g\X iU RWI U[ X[`I
I9I aQOMRNbaOaO]j]k%jkMl^ M\

^ 
\ X XU X 
X f
d _YXn`_dfXYX [4U WX doY U Wp%UMl^ [ \X qUNX QM"UWr,Uslj[4N UJWM"Ur([ tmNlOI RuVvWwYxvyr,sl\^zr
pI a] O]^PNbI aO]jk M^\1YJ N QJNa MB{JM Nl^zr}|Nl^a&r$~ R)k ]Q)juMlOMBvXXvyr(qi]Q)juMlOM`I
I aONbaO]jk M^\X XJNQJ NaMsl^]lbr}N i)^zr$pi QR&r(]O^Na]@I
bu iLM1fX
152
) 4)V)   5 
l)= x) A%, le
It is left to the GrADS script writer (that means you!) to run the demo and interpret the
output of `
" when clicking on all the options in the cascade of dropmenus.
}PePAP
GrADS has a widget type called 7 for rubber banding. There are two 7
modes: and w `
. To set up the 7 widget, use the following command:
w&7 zF"`
where:

- widget number
w `
- may be either or
 - lowest X point where the widget will be active (in virtual page units)
` - lowest Y point where the widget will be active (in virtual page units)
- highest X point where the widget will be active (in virtual page units)
- highest Y point where the widget will be active (in virtual page units)

In w
mode, as the user clicks and drags the mouse in the active rband area a box is
drawn with one corner located at the initial click and the opposite corner located at the

release point. In  mode, a line is drawn between these two points.

For example, suppose you want to set up a 


rubber band widget in the plot region
only.

First, execute  to get the X and Y limits of the plot area. The result from 
 might look like this:
!#"%$'&(#)+*-,+.0/1,#23
465!387',:9'3%/8;+;%<:=?>A@CB
DE,GFH,:"I/EJK"'LK;+MA@NB
O?,GFH,:"I/1MP@RQHBS"'LEQ@TQ-B
D-VU-,!I/1'L:2 OGU-,!I/0WH'X
Y!)'&!LZ0/EJ

Second, set up the widget with [


\] ^_`ab using the dimensions grabbed from the
result of c defghi :

153
j-k'lnmpoIqroGs't(k'lVuwvyxzoGs-k6{A|~}(
-k'lnmpoIqroGs't(k'lVuwvyxzoGs-k6{A|

jKqroVs+t:!xvyj-k'lnmo|

j(%qroVs+t:!xvyj-k'lnmo|p
KqroVs+t:!xvy-k'lnmo|

(%qroVs+t:!xvy-k'lnmo|p
o:z:{%x't(#u!8+%t!#j j 1 ( 1 j( 1 -

Finally, use  to activate the widget.





This freezes the system until the user clicks, drags, and then releases the mouse
somewhere within the active rband area. Here is a template for the output you would get
from GrADS after a mouse click and drag in the rband area:

pp+pp
H( p
H
p6:p
+

where:
pp+p - coordinates of the initial mouse click in virtual page units
p
H( - either 1, 2, or 3 for the left, center, or right mouse button
p
H - 2 is the widget class number for rbands
p6: - the number assigned to the rband widget when it was set
p

up 

- coordinates of the mouse release point in virtual page


units

The page coordinates can be then be used to draw a box (or a line) where the user
specified, or parsed and used in the coordinate transform ' to recover the
lat/lon region selected by the user.

154
Dynamic Loading of Script Functions

Script variables are generally local to the functions (scripts) they are contained in; they
exist in memory only while the function is executing. If a variable name starts with an
underscore (_), then it becomes a global script variable and keeps its value throughout the
execution of the main script file. The drawback to global variables was that the functions
they are defined in had to be included in the main script file. With a new capability that
comes with GrADS version 1.8, that is no longer the case.

Dynamic loading of script functions means that when your main script calls a function
(subscript), all global variables from that function will be retained in memory and can
continue to be used by main script. Commonly used functions do not have to be copied
into every script that calls them.

The names of GrADS script functions may now have 16 characters and include the
underscore, although they still must begin with an alphabetic character. Grads script
function names are case sensitive.

Error messages will include the file name where the error ocurred -- in this case, the full
path name of the file that was actually opened.
A? 
  

The tricks to using GrADS script functions are (1) to enable dynamic loading and (2) to
teach GrADS how to find the script functions you call from your main script.

To enable the dynamic loading of script functions, put this at the top of your script:
 !#"$&% "'
To teach Grads how to find the script functions you call from your main script, you must
first know how Grads searches for main script file names.

How GrADS searches for main script file names

Let's assume the user wants to run a script called ()+*,-)/.10324 and gives the Grads
command:
5 67&8:9;+<=-;/>
Grads will search in the currently directory for the script name, as provided. If it doesn't
find the script, it appends .gs to the script name and tries again. If the script is still not
found, then the environment variable GASCRP is examined. GrADS attemps to open the

155
script file in all the directories listed in the GASCRP variable, first with the provided
name, then with the .gs appended.

If GASCRP contains " ?@A+BC?EDF/GHD&?-IB HJ ADKLM?@A+BC?NEFOPEA?#O/QNEFOP ", then


GrADS will search for the script RS+TU-S/V in the following order:

W:XY+Z[-Y/\
]:^_+`a-_/b1c3de
fhgij+kCgElm/nol&g-pk oq jlrs/gCqm+tu-m/v
whxyz+{CxE|}/~|&x-{  z|/xC}+-}/13z
h+CEE#/EC+-/
h+CEE#/EC+-/13
GrADS uses the first file it finds. Once found, the directory that contains the script file is
remembered as the "main function prefix".

How GrADS searches for script function file names

 /13with
Continuing our example, let's further assume that GrADS encounters a function in
 that is not included in the stuff already loaded from the main script file.
GrADS will look for a .gsf file to load, using the following search path:

h#/&CEC/E/&3
h#/&CEC/C CC&E/&
3
h-&-& &E/&3
The private path directory list is an optional list that is provided via the &
function:

 # 
If used, the declaration of the private path directory list should appear at the top of the
main script just underneath the statement enabling the dynamic script loading.

For example, if our main script "do_eof.gs" is executed with the command:
 !#"$%&"
'&(")*!($ +,$-

and this script file contains the following lines at the front:
./10324567789;:<8
=><?
./103245@6A
B :<DC6A
B#EF4A.G=!2#H<?

156
and the script calls a function IJKLMN#O
P which is not found in the main script, then the
search path would be:

1. /usr/local/gradslib/str_chop.gsf
2. /usr/local/gradslib/math1/str_chop.gsf
3. /usr/local/gradslib/string2/str_chop.gsf

157
GrADS Script Library

basemap.gs Overlays a land or ocean mask that exactly fits the coastal outlines.
Requires the following supplemental data files:
lpoly_lowres.asc and lpoly_mres.asc and lpoly_hires.asc
opoly_lowres.asc and opoly_mres.asc and opoly_hires.asc
See instructions in script header for using lpoly_US.asc to mask out
non-US areas.
cbar.gs and Scripts to draw a long rectangular color legend next to shaded plots.
cbarn.gs cbarn has more features -- e.g. it draws outlines and triangular
endpoints.
cbarc.gs Draws a small fan-shaped color legend in the corner of shaded plots.
cbar_l.gs and
Scripts to draw a legend for line graphs.
cbar_line.gs
cmap.gs Creates a color table. See additional documentation.
connect_the_d
Draws a line connecting user's mouse clicks.
ots.gs
define_colors.
Defines a variety of colors using the set rgb command.
gs
defval_demo.
Illustrates the use of q defval and set defval commands.
gs
font.gs Displays all the characters in a font set.
isen.gs Displays a field interpolated to a specified isentropic level.
lats4d.gs Writes NetCDF, HDF-SDS or GRIB files from GrADS. See additional
documentation.
makebg.gs Creates a background map image that shows topographic texture. It
requires a DODS-enabled version of GrADS and also uses the external
ImageMagick utility "combine".
map.gs Automates settings for a variety of useful map projections.
mconv.gs Calculates moisture convergence.

158
meteogram_et
a.gs
These scrips draw meteograms based on NCEP forecast data, which is
meteogram_gf
accessed through the GrADS-DODS Server. You must use a DODS-
s.gs
enabled version of GrADS for these scripts to work.
meteogram_gf
sb.gs
panels.gsf and Scripts to create global variables that contain the 'set vpage' commands
panels_demo. for a multi-panel plot. These also illustrate the dynamic loading of
gs script functions.
script_math_d
Illustrates the use of the scripting language math funcitons.
emo.gs
pinterp.gs Displays a field interpolated to a specified pressure level.
plotskew.gs Draws a SkewT/LogP Diagram.
stack.gs Delays display while command sequence is entered by user, then
executes all at once.
string.gs Draws a string located at position of user's mouse click.
sweat_index.g Calculates the SWEAT Index given relative humidity, temperature, and
s wind components.
traj.gs Draws forward and backward trajectories in the horizontal plane.
use.gs Similar to open except it checks the list of current files to see if the
specified file has already been opened. If it has been opened, it changes
the default file number to the previously opened file instead of opening
the same data file again.
wxsym.gs Displays available weather symbols.
xanim.gs Controls an animated display.
zinterp.gs Displays a field interpolated to a specified height level.
zoom.gs A simple way to zoom into a plot.

159
A set clskip set display gr2stn()
aave() set cmark displaying data grads
abs() set cmax displaying metafiles set grads
acos() set cmin draw button grib data
aggregate data filescollect draw dropmenu gribmap
amean() coll2gr() draw line gribscan
animation default colors draw map gridded data sets
set annot controlling colors draw mark set grid
set arrlab command line editing draw polyf set gridln
set arrowhead commands: attribute draw rec gsfallow()
set arrscl const() draw recf gsfpath()
asin() control file draw string gxeps
asum() correlation, spatial draw title set gxout
asumg() correlation, temporal draw wxsym gxps
atan2() cos() draw xlab gxtran
athena widgets cross sections draw ylab
ave() set csmooth draw dropmenu
set cstyle set dropmenu H
set cterp hardcopy output
set cthick hcurl()
B
E hdivg()
set background
set barbase enable print help
D exec set hempref
set bargap
set baropts data descriptor files: exp()
basic operation elements of expressions
binary data sets gridded data external utilites I
set black self-describing data image output
draw button station data set imprun
redraw button data sets (gridded) F
set button data sets (station) set fgvals
set datawarn fndlvl() J
set dbuff font file format
define set font
C K
set defval set frame
cascading dropmenus set dfile
set ccolor disable fwrite
q dialog q fwrite L
set ccols set dialog set fwrite set lat
cdiff() set dignum functions: alpha set lev
set cint set digsiz functions: attribute set lfcols
set clab dimension math functions script library
clear environment draw line
set clevs disable fwrite set line
set clip disable print G log()
set clopts display log10()
close gint()
set lon P scorr() set gridln
set loopdim page control script functions set gxout
set loopincr set parea script library set hempref
set looping PC GrADS scripting language set imprun
PDEF sdfopen set lat
plot area set annot set lev
M set poli set arrlab set lfcols
mag() draw polyf set arrowhead set line
map projections q pos set arrscl set lon
draw map pow() set background set loopdim
set map print set barbase set loopincr
draw mark disable print set bargap set looping
maskout() enable print set baropts set map
math functions printim set black set mdlopts
max() set prnopts set button set missconn
maxloc() set ccolor set mpdraw
set mdlopts set ccols set mpdset
mean() set cint set mproj
Q
metafiles set clab set mpt
q (query)
min() set clevs set mpvals
q dialog
minloc() set clip set parea
q fwrite
set missconn set clopts set poli
q pos
modify set clskip set prnopts
quick: commands
set mpdraw set cmark set rband
quick: scripts
set mpdset set cmax set rbcols
quit
set mproj set cmin set rbrange
set mpt set csmooth set rgb
set mpvals set cstyle set stat
R set cterp set stid
multi-panel plots
set rband set cthick set stnprint
set rbcols set datawarn set string
set rbrange set dbuff set strmden
N
real page set defval set strsiz
ncdump draw rec set dfile set t
ncgen draw recf set dialog set time
redraw button set dignum set timelab
reset set digsiz set tlsupp
O reinit set display set vpage
oabin() reinitialization set dropmenu set vrange
oacres() set rgb set fgvals set vrange2
open run set font set warn
outxwd set frame set wxcols
set fwrite set wxopt
S set grads set x
set grid set xaxis
set xflip T set x
set xlab set t set xaxis
set xlabs tan() xdfopen
set xlevs tcorr() set xflip
set xlint templates draw xlab
set xlopts set time set xlab
set xlpos set timelab set xlabs
set xsize draw title set xlevs
set xyrev tloop() set xlint
set y set tlsupp set xlopts
set yaxis tmave() set xlpos
set yflip tregr() set xsize
set ylab Tutorial set xyrev
set ylabs tvrh2q()
set ylevs tvrh2t()
set ylint Y
set ylopts set y
set ylpos set yaxis
U
set z set yflip
undefine
set zlog
user defined functions draw ylab
!shell set ylab
user's guide
sin() set ylabs
external utilites
skip() set ylevs
smth9() set ylint
sqrt() set ylopts
sregr() V
set ylpos
starting GrADS variables
set stat vint()
about station data virtual page
Z
using station data set vpage
set vrange set z
set stid
set vrange2 set zlog
stnave()
stnmin()
stnmap
stnmax() W
set stnprint set warn
draw string wi
set string widgets
set strmden set wxcols
set strsiz set wxopt
sum() draw wxsym
sumg()
swap
X

You might also like