Session 1 - Getting started


What is NCL?

You can execute the NCAR Command Language interactively from the command line or as a batch script.

NCL is a powerful interpreted language for reading, writing, and manipulating scientific data. It uses an internal netCDF data model, but handles input data in a variety of formats. The command language provides many functions for manipulating data (including sorting) as well as arithmetic and trigonometric functions. As part of an integrated package, the NCAR Command Language can create any visualization supported by the High Level Utility interface, including X-Y plots and contour plots with maps, legends, label bars, and other annotations. You can use the command language's looping constructs to create series of images that can be animated using the NCAR Graphics Interactive Display Tool (idt); you can also subscript arrays directly with latitude and longitude values.

What can one do with NCL?

Some of its many uses include:

Starting and terminating NCL

On a system in which NCAR Graphics Version 4.0 or newer has been installed: (ncargversion is a command that will give you the version number)

How about a simple interactive NCL session? In your command window type:

ncl

You will get the NCL prompt:

ncl>

Type:

record "piscript.ncl"
pi = 3.1415926
a = cos(pi/4.)
print (a)

You should get the following:


Variable: a
Type: float
Total Size: 4 bytes
	    1 values
Number of Dimensions: 1
Dimensions and sizes:   [1]
Coordinates:
(0)     0.707107

Now type:

stop record
quit

Now list the script called piscript.ncl. You should get:

pi=3.1415926
a=cos(pi/4.)
print(a)

Simple huh? You can do some experimental interactive NCL and save it as a script. Remember that you may have to edit this script because all statements get logged, even erroneous ones.

The basic structure of an NCL program

NCL is a flexible programming language. It can be used to read data, write data in netCDF format, process the data in various ways, and visualize the data. A very simple NCL script might be:
begin
a = 2.
b = 3.5
c = a * b
print (c)
end
Every NCL script begins with "begin" and ends with "end". Between these statements go NCL statements that read or create data, manipulate data, and visualize data. In this script we defined two numbers, multiplied them, and printed the result.

To visualize data, NCL uses the NCAR Graphics object-oriented High Level Utilities (HLUs). The HLU paradigm is to create and connect objects. These objects are of various types including the most commonly used:

Creating and connecting objects

The function for creating and connecting objects is:
objectname = create "object_character_name" class_name parent_object
end create
where:

objectname is the name assigned to this object by the create function. We will use this name when we make subsequent references to this object. For example, if the object we create is a graphical object, we may later issue a command such as draw (objectname) to cause the graphic to be "drawn" on a designated workstation.

object_character_name is a string identifier of the object that is used by resource files to describe the object hierarchy. The option switches for objects are called object resources. They can be set in either a resource file, or in NCL code. For now we will set resources directly in NCL code.

class_name tells NCL what type of object to create. These names are given in the NCAR Graphics Reference Manual, but we do not need to be concerned about them now. The objects we create in this tutorial will already have their appropriate class names.

parent_object is the parent object for this new object. This is how objects are connected. For example, the graphical objects such as TextItem, XyPlot, or ContourPlot need as their parent object a workstation "objectname". This tells where the graphics are to be sent.

Let's look at the creation of a couple of typical objects:

x11 = create "x11" xWorkstationClass defaultapp
end create
We create an X11 window as our workstation. Its parent object is a default application automatically created by NCL. Graphical objects for which we designate x11 as the parent will be sent to this workstation. For example:
text = create "text" textItemClass x11
end create
would be a text string that we would create with x11 as the parent object. If we then say draw(text) the text will be drawn into an X window on our monitor.

OK, we have some basic understanding of how to create and connect objects. Let's build and execute some NCL scripts.

A minimal visualization with NCL

The minimum NCL program to do visualization would require two objects, a Workstation object and a View object. For example, if we start with "begin", add the two objects we previously defined, an X11 workstation and a TextItem, then ended with "end", we would have"
begin
x11 = create "x11" xWorkstationClass defaultapp
end create
text = create "text" textItemClass x11
end create
end
If we execute this script, however, nothing will happen. We need a couple more NCL statements. We need to draw the TextItem object (text) on the workstation, which is simply "draw(text)", and we must tell the workstation when this is the end of a "frame", in this case "frame(x11)". The frame statement causes a frame advance when a metafile is selected as the output workstation, and a frame pause when an X11 window is selected as the output workstation. Let's review our NCL script now:
begin
x11 = create "x11" xWorkstationClass defaultapp
end create
text = create "text" textItemClass x11
end create
draw(text)
frame(x11)
end
Let's name this minimal example tx_template0.ncl. To execute tx_template0.ncl, you can copy it into your working directory using your web browser. Click on the linked name above to bring the example script into your browser window. Copy it into your working directory by using the save as option under the file menu on your browser. If you use the name tx_template0.ncl when you copy the file into your working directory, then in your command window type the command:

ncl < tx_template0.ncl

A window should appear on your monitor with some partial characters in the upper left corner of the window. The default performance of the TextItem object is to write the word "text" centered at the viewport NDC location of (0,1). Thus, only the right bottom half of the word is visible.

So we need to change the behavior of the TextItem object. Let's change two things: where we place the text, and what the text is. Let's write "Hello World" in the middle of the window. We do this by specifying object resources. This is analogous to setting parameters in a Fortran subroutine.

tx_template1.ncl just draws the string "Hello World" in the middle of an X11 window and waits for a mouse click to clear the window.

Notice in this simple example that the way objects are manipulated in NCL is through
"Resource name" : value
statements that are sandwiched between the create line and the end create of an object. There can be any number of these resource assignment statements. The resource name on the left of the colon must be enclosed in quotes. The value on the right side needs be put in quotes only if it is of type character. Almost all objects have associated resources. Some objects like TickMark and ContourPlot have almost 200 resources. This may seem like overkill when you first learn to use the HLU objects, but later when you are trying to create a very detailed specific plot for publication, you may appreciate the flexibility.

Don't spend a lot of time now studying resources. You will have time to do that after we start writing some programs. However, you may want to take a quick look at the TextItem resources.

To execute tx_template1.ncl, once again use the save as option under the file menu on your browser. Use the name tx_template1.ncl to copy the file into your working directory. Read this script. It is commented with respect to the creation of an X11 Workstation object and a TextItem View object. In your command window type:

ncl < tx_template1.ncl

A plot that looks like the following should appear in a window on your monitor:



Sample NCL visualization scripts

Visualizing text

Now let's create a more sophisticated TextItem object by using more of the resources. We will change the text font, the text color, put the text in a filled box, and rotate it all to an angle of 45 degrees. This requires the following set of TextItem resources:
 "txString"     :  "NCAR Graphics Text"
 "txFont"       :  "times-roman"        ; a high quality filled font
 "txFontColor"  :  5                    ; yellow in the "default" color map
 "txAngleF"     :  45.                  ; rotate counter clockwise 45 degs
 "txFontHeightF":  .03                  ; increase the character size

 "txPerimOn"    :  "True"               ; turn on the box perimeter
 "txPerimColor" :  5                    ; make the box perimeter yellow
 "txBackgroundFillColor"   : 6          ; fill the box with the color red

Note that the semicolon turns the remainder of an NCL line into a comment and that blank lines are ignored so they can be used as separators.

We will now copy the "Hello World" script, tx_template1.ncl, to a new file and add this set of resource selections to get the example tx_template2.ncl. It can be copied into your directory via the file/save as menus in your browser and executed in the command window by typing:

ncl < tx_template2.ncl

The graphic it creates in an X11 window should look like:



A default map visualization

A simple MapPlot script will differ from the simple TextItem script in two ways: we create a MapPlot object instead of a TextItem object, and we draw the new object. The new code:

map = create "map" mapPlotClass wks
end create

draw(map)
In this MapPlot example, let's also send the output to an NCGM file rather than directing our output to an X11 window. To make it easy for us to switch between workstations (X11 window, NCGM, or PostScript), we will implement the following NCL if-then logic into our scripts:
;
; Direct the output to an NCAR Computer Graphics Metafile (ncgm).
;
  NCGM=1
  X11=0
  PS=0
;                 ncl supports if-then and if-then-else logic.
;
  if (NCGM .eq. 1) then
;
; Create an ncgm workstation object.  The default name of an ncgm is gmeta.
;
      wks = create "wks" ncgmWorkstationClass defaultapp
      end create
  else
    if (X11 .eq. 1) then
;
; Create an XWorkstation object.
;
      wks = create "wks" xWorkstationClass defaultapp
      end create
    else
      if (PS .eq. 1) then
;
; Create a PostScript workstation object.  A PostScript file will
; be written and given the default name wks.ps.
;
	wks = create "wks" psWorkstationClass defaultapp
        end create
      end if
    end if
  end if
Notice that all three workstation objects are named "wks". This allows the create function for View objects to always use "wks" as their parent object. Also, the frame call will always be "frame(wks)". To switch between the three workstation options, we simply set one of the switches to 1 and the others to 0 as in:
NCGM = 1
X11  = 0
PS   = 0
Study the MapPlot template mp_template1.ncl and compare it to the TextItem template tx_template1.ncl. Now copy mp_template1.ncl into your directory via the file/save as menus of your browser and execute it with the command:

ncl < mp_template1.ncl

This NCL script will create and draw a default map into an NCAR Computer Graphics Metafile (NCGM) named mp_template1.ncgm. This metafile can be plotted with the NCAR NCGM interpreter ctrans via the command:

ctrans -d X11 mp_template1.ncgm

The graphic should look like:

The default MapPlot object visualization is a simple cylindrical equidistant map with continental outlines and a latitude and longitude grid. Suppose we want to switch to an orthographic projection. That requires that we add one line of NCL code (a resource assignment) to the MapPlot object, namely:

"mpProjection" : "orthographic"

The new example mp_template2.ncl can be copied into your directory via the file/save as menus of your browser and executed with the command:

ncl < mp_template2.ncl

An NCGM named mp_template2.ncgm is created. It can be plotted with the NCAR NCGM interpreter ctrans via the command:

ctrans -d X11 mp_template2.ncgm

The graphic should look like:

Although we now have an orthographic projection, this still isn't a very appealing map. Let's change it to have color-filled land and water. We need to add another line of NCL code (resource assignment) namely:

"mpFillOn" : "True"

The new example mp_template3.ncl can be copied into your directory via the file/save as menus of your browser and executed with the command:

ncl < mp_template3.ncl

An NCGM named mp_template3.ncgm is created. It can be plotted with the NCAR NCGM interpreter ctrans via the command:

ctrans -d X11 mp_template3.ncgm

The graphic should look like:


We now have a nice-looking filled orthographic map. A set of default colors have been assigned to the land and the water. If we want to specify other colors we will need to set new color indices using other MapPlot resources such as:

mpMonoFillColor
mpFillColor
mpFillColors
mpDefaultFillColor
mpOceanFillColor
mpLandFillColor
mpInlandWaterFillColor
mpSpecifiedFillColors
For example we might choose to add the resources:
"mpMonoFillColor"        : "False"      ; There will be more than 1 color
"mpOceanFillColor"       : 4            ; Ocean color blue
"mpLandFillColor"        : 19           ; Land color forest green
"mpInlandWaterFillColor" : 4            ; Inland waters like lakes blue
The above color indices come from the default color table.

Before we run this new map, let's use what we previously learned about TextItem objects to add a couple text annotations to this plot.

Add titles to the map

Although most of the high-level View objects have built in X, Y, and Main titles, we can also have complete freedom over where we draw text by using the TextItem object. In this case, we will add a title and a subtitle by using two TextItem objects. A quick way to do this is to copy our script mp_template3.ncl to a new file called mp_template4.ncl. Into this script we place two copies of the TextItem object from file tx_template2.ncl.
;---------------- The original tx_template2.ncl TextItem object ---
;
tx = create "tx" textItemClass wks
"txPosXF" : 0.5         ; The X location of our TextItem is at .5 NDC
"txPosYF" : 0.8         ; The Y location of our TextItem is at .8 NDC
;                         The viewport is always between 0 and 1. NDC
;                         in both dimensions.
;
"txJust"  : "CENTERCENTER"  ; The text is centered in X and Y within
;                             its defining box.  The defining box
;                             is centered at (txPosXF,txPosYF).
;
"txString" : "January Climatological Surface Temperature"  ; the text
"txFontHeightF" : .030                          ; text character size
"txFont" : "times-roman"                        ; text font type
end create
;---------------- The original tx_template2.ncl TextItem object ---
;---------------- gets repeated twice and changed as follows:   ---


;---------------- Create two TextItem objects -------------------
;
;  Create TextItem objects named "title" and "subtitle".  Title will
;  have "NCL Scientific Tutorial" as a txString resource, subtitle
;  will have "Filled Orthographic Projection" as a txString resource.
;
; Create title
;
title = create "tx1" textItemClass wks
;
"txPosXF" : 0.5         ; The X location of our TextItem is at .5 NDC
"txPosYF" : 0.85        ; Move the title up to .85 NDC.
;                         The viewport is always between 0 and 1. NDC
;                         in both dimensions.
;
"txJust"  : "CENTERCENTER"  ; The text is centered in X and Y within
;                             its defining box.  The defining box
;                             is centered at (txPosXF,txPosYF).
;
"txString" : "NCL Scientific Tutorial"          ; the title text
"txFontHeightF" : .030                          ; text character size
"txFont" : "times-roman"                        ; text font type
end create
;
; Create subtitle
;
subtitle = create "tx2" textItemClass wks
;
"txPosXF" : 0.5         ; The X location of our TextItem is at .5 NDC
"txPosYF" : 0.15        ; Move the subtitle down to .15 NDC.
;                         The viewport is always between 0 and 1. NDC
;                         in both dimensions.
;
"txJust"  : "CENTERCENTER"  ; The text is centered in X and Y within
;                             its defining box.  The defining box
;                             is centered at (txPosXF,txPosYF).
;
"txString" : "Filled Orthographic Projection"   ; the subtitle text
"txFontHeightF" : .025                          ; text character size
;                                                 smaller than the title
"txFont" : "times-roman"                        ; text font type
end create
;
;-----------------------------------------------------------------------

Now the only other thing we have to do is add two draw commands of the form:

	draw(title)
	draw(subtitle)
Note that our new script mp_template4.ncl now has three objects to be drawn onto our workstation device, the two text objects and the map object. In this case, we have placed the three objects in areas of the viewport where they will not overlap; thus, the order in which we draw them makes no difference. If, however, we were overlaying some text on top of a filled map, like the word "Africa" for example, we would want that text object drawn after the map object.

Copy the new script into your directory via the file/save as menus of your browser and execute it with the command:

ncl < mp_template4.ncl

An NCGM named mp_template4.ncgm is created. It can be plotted with the NCAR NCGM interpreter ctrans via the command:

ctrans -d X11 mp_template4.ncgm

The graphic should look like:

Let's review what we have learned so far. We have seen from these examples:


Return to NCL Scientific Tutorial.

User Guide Control Panel

NG4 Home, Index, Examples, Glossary, Feedback, UG Contents, UG WhereAmI?


$Revision: 1.6 $ $Date: 1996/05/30 13:48:18 $