pyncl
index
/Users/jsw/lib/python/pyncl/__init__.py

Purpose:
 
Generate NCL plots of cdms transient variables (Numeric arrays with
extra, netCDF like metadata).
 
*** Now included as a contributed CDAT package (http://esg.llnl.gov/cdat) ***
 
Background:
 
NCL (http://www.ncl.ucar.edu/) is an interpreted programming language
with superb 2-D graphics capabilities (see
http://www.ncl.ucar.edu/gallery.shtml for examples).
This class provides access to NCL's GSUN plot interface
using (http://esg.llnl.gov/cdat/cdms_html/cdms.htm) transient variables. 
It lets you to embed NCL plotting commands directly in your python code,
transparently transferring data (in the form of cdms variables) to NCL.
 
Source for latest version available at 
/people/jeffrey.s.whitaker/python/pyncl.tgz
 
Requires: cdms module from CDAT (http://esg.llnl.gov/cdat) and 
          NCL version 4.2.0a28 or higher (http://www.ncl.ucar.edu/).
          A stripped-down version of CDAT, which includes just the
          cdms module and pyncl is available at 
          /people/jeffrey.s.whitaker/python/cdat-4.0-pyncl.tar.gz.
          ImageMagick required to use "png" or "gif" workstation device,
          Should run on any platform CDAT runs on.
          Not tested with python < 2.2.
 
Usage:
 
Creating an NCL plot within your python script is a four step process.
 
(1) Import the pyncl module
 
>>> from pyncl import *
 
then create an Ncl class instance
 
>>> plot1 = Ncl(NCARG_ROOT="/usr/local/ncl")
 
or 
 
>>> plot1 = Ncl()
 
if NCARG_ROOT is set as an environment variable. The ncl executable is assumed 
to live in NCARG_ROOT/bin.
 
(2)  Convert the Numeric arrays you want to plot to cdms transient variables 
(Numeric masked arrays with extra, netCDF-like metadata).  See the cdms
documentation at http://esg.llnl.gov/cdat/cdms_html/cdms.htm for details.
Add the names of these variables to the class instance variable dictionary.
 
>>> # create Numeric arrays with some data. xdata are the abscissa values 
>>> # and ydata are the ordinate values.
>>> npts = 51
>>> xdata = (Numeric.arange(npts)*2.*math.pi/(npts-1))
>>> ydata = Numeric.sin(xdata)
>>> # create cdms transient variable.
>>> x_axis = cdms.createAxis(xdata)
>>> x_axis.id = 'xdata'
>>> x_axis.long_name = 'X'
>>> ydata = cdms.createVariable(ydata,axes=[x_axis])
>>> ydata.long_name = 'sin(X)'
>>> # add variable to ncl variable dictionary
>>> # accessed in NCL script using key ('ydata' in this case).
>>> plot1['ydata']=ydata
 
(3) Set some plot attributes.  Available attributes are:
 
plotdev:  (string) workstation plotting device.
    Valid values are x11,ps,eps,epsi,pdf,png,gif or ncgm.
    If plot1.plotdev = "png" a png image file containing the plot
    will be generated. Default value is "ps".
plotname: (string) name of graphics workstation
    If plot1.plotname = "pyncl_test" and plot1.plotdev = "ps", 
    a file called "pyncl_test.ps" will be created.
    Default value is "pyncl"
xsize: Plot width in pixels (default 512).
ysize: Plot height in pixels (default 512).
    xsize and ysize only used if plotdev = ncgm,x11,png or gif.
fontname: (string) Font used for titles and legends (default "helvetica").
    See http://www.ncl.ucar.edu/Document/Graphics/font_tables.shtml
    for list of fonts.
whitespace: Extra whitespace around cropped png or gif plot (default 0).
funccode:  (string) NCL text function code 
    (default "~" instead of NCL default ":")
fgcolor: (string) Foreground color (default "White")
bgcolor: (string) Background color (default "Black")
    fgcolor and bgcolor must be one of choices given 
    in file $NCARG_ROOT/lib/ncarg/database/rgb.txt.
wksname: (string) name of ncl workstation id.  Default is "wks".
    You must use this name in your ncl script.  Simplest thing is
    to leave the default value and use "wks" in your ncl script.
-- the last three attributes are only used if the plotdev is "ps" or "pdf" --
landscape: Set to True if you want a landscape pdf or ps plot.
    Default is False (portrait plot).
cmykcolors:  If True, NCL will use CMYK color model instead of RGB.
monochrome:  If True, NCL will produce monochrome output (default is color).
 
Back to our simple example:
 
>>> plot1.plotdev = "x11" # plot will appear in an X-window.
>>> plot1.xsize = 800    
>>> plot1.ysize = 800
 
(3) Create an NCL script 
(as one big multi-line string or one command at a time).
 
This can be done by passing a string as an argument to the class instance,
or by attaching a multi-line string to the nclcommands class attribute
directly. If the class instance is called with a string argument, that
string is appended to the nclcommands class attribute.
Variables in data dictionary are accessed with the NCL script
by their key values.
 
one big multi-line string:
 
>>> # create the NCL script.
>>> # see http://www.ncl.ucar.edu/Applications/
>>> # for lots of nifty NCL graphics examples. 
>>> plot1("""
>>> ; no 'begin', 'end' or 'gsn_open_wks' statements are needed.
>>> ; gsn scripts are loaded automatically.
>>>   res              = True
>>>   res@tiMainString = "Sine Wave"
>>> ; cdms transient variables are accessible via their key values
>>> ; The "&" modifier is used to access coordinate 
>>> ; variables (see NCL docs at http://www.ncl.ucar.edu/).
>>> ; default workstation id is "wks"
>>>   plot             = gsn_xy(wks,ydata&xdata,ydata,res)  
>>> """)
 
one command at a time:
 
>>> plot1('res=True')
>>> plot1('res@tiMainString="Sine Wave"')
>>> plot1('plot=gsn_xy(wks,ydata&xdata,ydata,res)')
 
to see the entire NCL script (plus other class instance info)
 
>>> print plot1
 
If you use IPython (http://ipython.scipy.org), you can edit your NCL 
script inside the interactive shell using "@ed -x plot1.nclcommands".
After exiting, @ed will return as output the code you edited.
You can then set plot1.nclcommands = _<NUMBER>, where <NUMBER> 
is the prompt number of the output.
 
(4) Run the NCL script using the nclrun method of the Ncl class
instance.  The nclrun method can take optional arguments "Save" and 
"loadscripts".
"Save=1" will cause the NCL script, data and plot resources to be
saved to the present working directory (by default "Save=0" and they
are written to temporary files and deleted).
The argument loadscripts can contain a list of external NCL scripts
to load (all of the csm and wrf scripts that come with NCL
are loaded automatically).
 
>>> plot1.nclrun() # plot appears in an 800x800 X window.
>>> plot1.plotdev = "ps" # reset plot device to postscript
>>> plot1.plotname = "pyncl_example"
>>> plot1.nclrun() # a postscript file named "pyncl_example.ps" is created.
 
The plot should look like this:
    /people/jeffrey.s.whitaker/python/pyncl_example.png
 
Notes:
 
**   Only one NCL graphics workstation is created in each Ncl class 
instance.  This workstation is created automatically, so nclcommands
should not contain a gsn_open_wks call. The workstation name is "wks"
unless overridden with the wksname attribute.
 
**   You may use "png" or "gif" workstation devices, 
even though this is not supported by NCL. Image file will be created using
ImageMagick convert if available, otherwise the plot will be saved in
an ncgm file.
 
**   plot.keys() will show all the variables defined in the data
dictionary.  To print summary information about all the cdms
transient variables in the dictionary: 
>>> for key in plot.keys(): print plot[key]
 
**   extra colormaps (beyond the ncl built-in colormaps) are available.
Their names are given in the list 'extracolormaps'.  Run the script
plot_colormaps.py in the examples directory to see what these 
colormaps look like. They are taken from Cindy Brewer's web site
(http://www.personal.psu.edu/faculty/c/a/cab38/ColorBrewerBeta2.html)
and University of Oregon's Data Graphics Research Program web site
(http://geography.uoregon.edu/datagraphics/color_scales.htm). You can use
these colormaps just as you would the built-in ncl-colormaps (i.e.
by setting with gsn_define_colormap(wks,"<insert color map name here>") ).
 
To test, execute "python pyncl.py". A plot should pop up in an X-window.
/people/jeffrey.s.whitaker/python/pyncl_examples.py containes more examples.
The plots generated by this script should look like these:
/people/jeffrey.s.whitaker/python/pyncl_ex1.png (line plot w/missing vals)
/people/jeffrey.s.whitaker/python/pyncl_ex2.png (polar color-filled contour plot)
/people/jeffrey.s.whitaker/python/pyncl_ex3.png (panel plot with fig labels)
 
Author: Jeff Whitaker <Jeffrey.S.Whitaker@noaa.gov>
 
Version 1.4.1 (20050222)

 
Package Contents
       
colormaps
pyncl

 
Data
        extracolormaps = ['Spectral', 'RdYlGn', 'PuBu', 'Accent', 'OrRd', 'Set1', 'Set2', 'Set3', 'BuPu', 'Dark2', 'RdBu', 'Oranges', 'BuGn', 'PiYG', 'YlOrBr', 'YlGn', 'Reds', 'RdPu', 'Greens', 'PRGn', ...]