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 (N.B. The Cairo graphics display inteface in version 2.1+ does not support widgets)
Script Library
Scripting Language Reference Card (Requires Adobe Acrobat Reader)
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 run command, provides a similar capability to the exec 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.
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 if/else/endif and while/endwhile constructs. Loop flow may be modified by the continue or break 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 run command:
run filename <arguments>
This command runs the script contained in the named file, which generally has a ".gs" tag at the end. Optional arguments are passed to the script as a string variable. You may issue any GrADS command from a script, including the run 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 display command:
set imprun script-name
This script would typically be used to set an option that by default gets reset after each display command, for example:
set grads off
You can issue any GrADS command from this script, but the interactions are not always clear. For example, if you issued a display command from this script, you could easily enter an infinite recursion loop.
The argument to the script is the expression from the display command.
It is convenient to put all your GrADS "utility" scripts in one directory (e.g., /usr/local/grads/lib/scripts).
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 ".gs" extension and tries again. For example, suppose you are working on a test script called t.gs. You would run it in GrADS by,
run t
If after the first two tries, the script still can't be located, then GrADS looks in the directory defined by the environment variable GASCRP. In the t(csh), for example,
setenv GASCRP /home1/grads/lib
or in ksh,
export GASCRP=/home1/grads/lib
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
setenv GASCRP /home1/grads/lib/
If the script cannot be found, then .gs is appended and GrADS tries yet again. Thus,
d slp
run /home1/grads/lib/cbarn.gs
simplifies to,
d slp
run cbarn
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).
Each script record may be one of the following types:
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.
Comments in GrADS scripts must contain an asterisk (*) in the first column.
The statement record consists only of an expression:
expression
The expression is evaluated, and the resulting string is then submitted to GrADS as a command for execution. The script variable rc 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 result 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:
* this is a sample script
'open my_sst_dataset.ctl'
'set lat -30 30'
'set lon 90 300'
'display sst'
Assignment records are used to define variables and assign them values. The format of the assignment record is:
variable = expression
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:
'open my_sst_dataset.ctl'
minlat = -30
maxlat = minlat + 60
minlon = 90
maxlon = 300
'set lat 'minlat%' '%maxlat
'set lon 'minlon' 'maxlon
'display sst'
To present information or questions to the GrADS user via the terminal (standard output), use the say or prompt commands:
say expression
prompt expression
The result of the expression is written to the terminal. The prompt command works the same way as the say command but does not append a carriage return. It is possible to combine variables and string constants when writing to standard output:
For example:
line = "Peter Pan, the flying one"
say line
say `She said it is `line
gives:
Peter Pan, the flying one
She said it is Peter Pan, the flying one
pull
To retrieve information provided by the GrADS user via the terminal (standard input), use the pull command:
pull variable
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:
'open my_sst_dataset.ctl'
prompt 'Enter min and max latitudes: '
pull minlat maxlat
prompt 'Enter min and max longitudes: '
pull minlon maxlon
'set lat 'minlat%' '%maxlat
'set lon 'minlon' 'maxlon
'display sst'
One way to control the flow of script execution is via the if/else/endif construct. The format is as follows:
if expression
script record
script record
.
.
else
script record
.
.
endif
The else block is optional, but the endif record must be present. The script records following if expression are executed if the expression evaluates to a string containing the character 1. If the expression evaluates to 0, then the script records in the if block are not executed and the script continues with the else block (if it is present) or the record following endif. The if expression record must be separated from the script records that follow it. For example, the following script record would be invalid:
if (i = 10) j = 20
The correct syntax requires three separate script records. This is achieved by putting each record on one line:
if (i = 10)
j = 20
endif
Alternatively, the three records could be on the same line separated by a semicolon:
if (i = 10) ; j = 20 ; endif
N.B. There is no elseif construct in GrADS.
Another method for controlling the flow of script execution is the while/endwhile construct. The format is as follows:
while expression
script record
script record
.
.
endwhile
The script records following while expression are executed if the expression evaluates to a string containing the character 1. If the expression evaluates to 0, then the script records in the while block are not executed and the script continues with the record following endwhile. The while expression record must be separated from the script records that follow it.
Two additional script commands may be used to modify the while loop execution: break and continue. Inserting the break statement will immediately end execution of the loop and the script will move on to the records following endwhile. The continue 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:
count = 1
while (count < 10)
'set t 'count
'display z'
if (rc != 0) ; break ; endif
count = count + 1
endwhile
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:
name = `Peter Pan'
name = "Peter Pan"
Numeric variables may be entered without quotes, but are still considered strings.
number = -99.99
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:
rc
result
lat, lon, and lev are also used as predefined internal 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 a global string variable is as follows:
_var1 = "global variable 1"
N.B. Global variables cannot be used in function headers. For example:
function dostuff(_var)
wouldn't make sense, since _var 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:
varname.i.j
In this case, when the variable contents are accessed, i and j will be looked up to see if they are also variables (non-compound). If they are, the i and j will be replaced by the string values of i and j. For example:
i = 10
j = 3
varname.i.j = 343
In the above example, the assignment is equivalent to:
varname.10.3 = 343
Note that the string values of i and j 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:
i = 'a#$xx'
varname.i = 343
The above is valid. However, we cannot refer to this variable name directly:
varname.a#$xx = 343
would be invalid.
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:
i = 1
while (i < 10000)
var.i = i
i = i + 1
endwhile
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.
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/ divisionThe following operators will perform a numeric operation if the operands are numeric:
=, !=, >, >=, <, <=, +, -, *, /
If any of the following operations are attempted with non-numeric operands, an error will result:
+, -, *, /
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 0 (zero) if the result is FALSE, and a character 1 (one) if the result is TRUE.
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:
-, ! (Unary)
/, *
+, -
%
=, !=, >, >=, <, <=
&
|
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:
var1 = -1 ; var2 = 10
if (var1*var2 < 10 & var1 > 0)
say 'both statements are true'
else
say 'it is not the case that both statements are true'
endif
For the expression following if, 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:
it is not the case that both statements are true
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 implied concatentation, intervening blanks will be ignored.
For example, the following expressions have the same effect:
'set lat 'minlat%' '%maxlat uses the concatenation operator %'set lat 'minlat' 'maxlat concatenation is impliedAssuming two previous statements, minlat = -30 and maxlat = 30, the resulting expression would be:
'set lat -30 30'
Keep in mind the order of precedence when using the concatenation operator.
Function calls take the form of:
name(arg,arg,arg,...)
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:
name(arg,arg,arg...)
If the function has no arguments, you must still provide the parentheses:
name()
You may provide your own functions from within your script file by using the function definition record:
function name(variable, variable, ...)
To return from a function, use the return command:
return expression
The expression 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 run 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 run command options. If no options were given, the variable will be initialized to NULL.
strlen (string)string.
sublin (string, n)
This function gets a single line from a string containing several lines. The result is the nth line of string. If the string has too few lines, the result is NULL. n must be an integer.
subwrd (string, n)
This functions gets a single word from a string. The result is the nth word of string. If the string is too short, the result is NULL. n must be an integer.
substr (string, start, length)
This function gets part of a string. The sub-string of string starting at location start for length length will be returned. If the string is too short, the result will be short or NULL. start and length must be integers.
read (filename)
This functions reads individual records from file filename. Repeated calls must be made to read consecutive records. The result is a string containing two lines: 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 sublin function to separate the result. Return codes are:
0 -ok1 -open error2 -end of file8 -file open for write9 -I/O errorwrite (filename, record <, append>)
This functions writes records to output file filename. 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:
0- ok1- open error8- file open for read
close (name)
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:
0- ok1- file not open
sys (command)
This function was added in version 2.1.1.b0. It submits the specified command to the shell and returns the resulting text stream that gets sent to standard output (stdout). The command is passed to /bin/sh. There is no way to check if the command succeeded; the return code is not captured, and an empty result could mean that the command has no output or that the command failed. Any error notifications or text streams sent to standard error (stderr) will appear in the console window and not the returned text unless you explicitly include a capture of stderr in your command string.
Consider the following script test_sys.gs:
cmd1="ls ./foo"
cmd2="ls ./foo 2>&1"
cmd3='echo Hello, world!'
res1=sys(cmd1); say 'cmd1 returned ->'res1'<-'
res2=sys(cmd2); say 'cmd2 returned ->'res2'<-'
res3=sys(cmd3); say 'cmd3 returned ->'res3'<-'
ga-> test_sys
ls: ./foo: No such file or directory
cmd1 returned -><-
cmd2 returned ->ls: ./foo: No such file or directory
<-
cmd3 returned ->Hello, world!
<-
ga->
There are some GrADS commands that, although not designed exclusively for scripts, are most useful in script applications. These include:
To see the list of available options, issue the query command by itself. A description of the query options that are most useful for script applications follows.
q define -- Lists all defined variables
q define varname -- (Added in version 2.1.1b0) Lists information about a specific defined variable: grid dimensions, coordinate axis definitions, calendar type, and whether it has been modified to be a climatological variable.
q defval ival jval -- Gives defined grid value at ival, jval
To interactively modify grid point values for a defined variable, q defval can be used in conjunction with set defval. 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.
'q defval sst 'i' 'j
val = subwrd(result,3)
if (val < -1.6)
'set defval sst 'i' 'j' 'bad_value
endif
q dims -- Gives the current dimension environment
q file n -- Gives info on file number n
q files -- Lists open files
q fwrite -- Gives the name of the file used for fwrite operations
q gxinfo -- Lists graphics settings
This option is handy when trying to find the plot area. The output from q gxinfo might look like this:
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:
1 Scaled (no preservation of aspect ratio)2 Latlon (2-D horizontal fields)3 Northern polar stereographic4 Southern polar stereographic5 Robinson (lon range must be -180 to 180 and lat range must be -90 to 90)q pos -- Waits for mouse click, returns position
q shades -- Gives colors and levels of shaded contours
q time - gives time range of current open file
q transform coord1 coord2 -- Coordinate transformations
where transform is one of:
xy2w XY coords to world coords
xy2gr XY coords to grid coords
w2xy world coords to XY coords
w2gr world coords to grid coords
gr2w grid coords to world coords
gr2xy 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.
When using the graphics output type set gxout findstn, three arguments must be provided with the display 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.
set dbuff on|off
This command sets double buffer mode on or off. This allows animation to be controlled from a script. The clear command also sets double buffer mode off.
swap
Swaps buffers, when double buffer mode is on. If double buffer mode is off, this command has no effect.
The usual usage of these commands would be:
set dbuff on
start looping
display something
swap
endloop
set dbuff off
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. (N.B. The Cairo graphics display inteface in version 2.1+ does not support widgets.)
Here is a sample from a script illustrating how to draw a button:
set rgb 90 100 100 100 set rgb 91 50 50 50 set rgb 92 200 200 200 set button 2 90 91 92 3 90 92 91 6 draw button 1 5.5 1 2 0.5 This is a Button
The reference pages for set button and draw button contain information on how to specify the button characteristics and position.
A button's initial "state" is ON. If a user clicks on a button following a q pos command, then the button state will switch from ON (1) to OFF (0). A second q pos followed by a mouse click on the button will return it to the ON state. The button state may also be changed with the redraw button command.
The output from the q pos command is what makes the button widgets so useful. Here is a template of what q pos returns after a mouse click on a button:
Position = xpos ypos mousebutton widgetclass buttonnumber buttonstate
where:
xpos, ypos - coordinates of the mouse click in virtual page unitsmousebutton - either 1, 2, or 3 for the left, center, or right mouse buttonwidgetclass - 1 is the widget class number for buttonsbuttonnumber - the number assigned to the button when it was originally drawnbuttonstate - either 0 (meaning "off") or 1 (meaning "on")
If the user did not click on a button, then widgetclass will be 0 and there will be no output for buttonnumber or buttonstate.
As with button widgets, dropmenus provide a "point-and-click" interface between scripts and the GrADS user. The reference pages for set dropmenu and draw dropmenu contain information on how to specify the dropmenu characteristics and position.
The output from q pos after a click on a dropmenu is similar to that described above for buttons. Here is a template of what is returned by q pos after a mouse click on a dropmenu:
Position = xpos ypos mousebutton widgetclass menunumber inum
where:
xpos, ypos - coordinates of the mouse click in the menu base in virtual page unitsmousebutton - either 1, 2, or 3 for the left, center, or right mouse buttonwidgetclass - 3 is the widget class number for dropmenusmenunumber - the number assigned to the dropmenu when it was originally drawninum - the menu item number selected from the menu list
If no menu item is selected, then menunumber and inum will both be -1.
Here is a script sample illustrating how to use a dropmenu:
'reset events'
'set rgb 90 100 100 100'
'set rgb 91 150 150 150'
'set rgb 92 200 200 200'
'set dropmenu 1 91 90 92 0 91 90 92 1 91 90 92 90 92 6'
'draw dropmenu 1 1 8 1.5 0.5 Select a Variable | Wind | Temperature | Height | SLP '
noselect = 1
while (noselect)
'q pos'
menunum = subwrd(result,7)
menuitem = subwrd(result,8)
if (menunum = 1)
if menuitem = 1 ; newbase = 'Variable = Wind' ; endif
if menuitem = 2 ; newbase = 'Variable = Temp' ; endif
if menuitem = 3 ; newbase = 'Variable = Height' ; endif
if menuitem = 4 ; newbase = 'Variable = SLP' ; endif
'draw dropmenu 1 1 8 1.5 0.5 'newbase' | Wind | Temperature | Height | SLP '
noselect = 0
endif
endwhile
Here is another script sample illustrating how to use cascading dropmenus:
'clear' 'set rgb 90 100 100 100' 'set rgb 91 150 150 150' 'set rgb 92 200 200 200' 'set button 1 91 -1 -1 1 91 90 92 12' 'draw button 1 1 8 1 0.5 quit' 'set dropmenu 1 91 -1 -1 1 91 90 92 1 91 90 92 90 92 6' 'draw dropmenu 1 1.5 7.5 2 0.5 Menu Base | Space | Earth >05> | Sun | Moon' 'draw dropmenu 5 cascade Ocean | Land | Atmosphere >11> | Biosphere' 'draw dropmenu 11 cascade Snow | Rain | Mist | Tornado ' while (1) 'q pos' say result ev = subwrd(result,6) if (ev!=3); break; endif; endwhile
It is left to the GrADS script writer (that means you!) to run the demo and interpret the output of q pos when clicking on all the options in the cascade of dropmenus.
GrADS has a widget type called rband for rubber banding. There are two rband modes: box and line. To set up the rband widget, use the following command:
set rband num mode x1 y1 x2 y2
where:
num - widget numbermode - may be either boxor linex1 - lowest X point where the widget will be active (in virtual page units)y1 - lowest Y point where the widget will be active (in virtual page units)x2 - highest X point where the widget will be active (in virtual page units)y2 - highest Y point where the widget will be active (in virtual page units)In box 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 line mode, a line is drawn between these two points.
For example, suppose you want to set up a box rubber band widget in the plot region only.
First, execute q gxinfo to get the X and Y limits of the plot area. The result from q gxinfo might look like this:
Last Graphic = Line Page Size = 11 by 8.5 X Limits = 2 to 10.5 Y Limits = 0.75 to 7.75 Xaxis = Lon Yaxis = Val Mproj = 2
Second, set up the widget with set rband using the dimensions grabbed from the result of q gxinfo:
xlims = sublin(result,3) ylims = sublin(result,4) x1 = subwrd(xlims,4) x2 = subwrd(xlims,6) y1 = subwrd(ylims,4) y2 = subwrd(ylims,6) 'set rband 21 box 'x1' 'y1' 'x2' 'y2
Finally, use q pos to activate the widget.
ga-> q pos
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:
Position = xpos1 ypos1 mousebutton widgetclass widgetnumber xpos2 ypos2
where:
xpos1, ypos1 - coordinates of the initial mouse click in virtual page unitsmousebutton - either 1, 2, or 3 for the left, center, or right mouse buttonwidgetclass - 2 is the widget class number for rbandswidgetnumber - the number assigned to the rband widget when it was set upxpos2, ypos2 - coordinates of the mouse release point in virtual page unitsThe 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 q xy2w to recover the lat/lon region selected by the user.