Professional Documents
Culture Documents
NCL and NetCDF PDF
NCL and NetCDF PDF
Language (NCL)
http://www.ncl.ucar.edu/index.shtml
Where Can I Learn More?
Manual, Lectures, and NCL-Talk
Reference Manuals
http://www.ncl.ucar.edu/Document/Manuals/
1) Introduction.
2) Language Basics.
3) File Input / Output.
4) Data Analysis.
5) Graphics.
6) Tips and Tricks.
1) Introduction
What is NCL?
• NCL is a complete language with types, variables,
operators, expressions, conditional statements,
loops, and functions and procedures.
• NCL can read many data formats: NetCDF, HDF,
GRIB, ascii and csv, binary, WRF output, and
more.
• NCL like MATLAB is an array based language.
Arrays can be sent to functions (100s and
growing) which perform computations, plotting
functions (dozens and growing), or files (typically
NetCDF but also ascii and binary).
NCVIEW
http://meteora.ucsd.edu/~pierce/ncview_home_page.html
http://www.ncl.ucar.edu/Applications/
Function Documentation
float prr(time, y, x)
prr:_FillValue = -9999.f ; CF
prr:missing_value = -9999.f ; COARDS
prr:long_name = "Liquid Precipitation" ; CF, COARDS
prr:grid_mapping = "Lambert_Conformal" ;
prr:units = "kg m-2 s-1" ; CF, COARDS
prr:height = "surface" ;
prr:coordinates = "lon lat" ; CF
netCDF/NCL variable
• array [could be of length 1 (scalar)]
• (may) have additional information
4.35 4.39 0.27 -3.35 -6.90
4.36 4.66 3.77 -1.66 4.06
9.73 -5.84 0.89 8.46 10.39
17 3.68 5.08 0.14 -5.63
-0.63 -4.12 -2.51 1.76 -1.43
-4.29 0.07 5.85 0.87 8.65
name: x
type: float [real]
shape: 2-dimensions
size: 6 (rows) x 5 (columns)
values: x(2,3) = 8.46 [row major, 0-based indexing]
long_name: “Temperature”
units: “degC” Meta data
named dimensions: x(time,lat)
lat: (/ -60, -30 ,0, 30, 60 /)
time: (/2000, 2001, 2002, 2003, 2004, 2005, 2006 /)
Detailed Look netCDF Variable (NCL)
ncl <return> ; interactive mode
ncl 0 > f = addfile ("UV300.nc", "r") ; open file (nc, grb, hdf, hdfeos)
ncl 1 > u = f->U ; import STRUCTURE
ncl 2 > printVarSummary (u) ; overview of variable
p
NetCDF [NCL] Variable model accessed via @ accessed via &
http://www.ncl.ucar.edu/Document/Manuals/Ref_Manual/Ncl
DataTypes.shtml#BasicNumericTypes
Variable Creation and Deletion
a = 2.0
pi = 4.0*atan(1.0)
s = (/ “Melbourne”, “Sydney”, “Toulouse”, “Boulder” /)
r = f->precip ; (time,lat,lon)
R = random_normal(20,7, (/N,M/) ) ; R(N,M)
q = new ( (/ntim, klev, nlat, mlon/), “double” )
; free memory; Generally, do not need to do this
; delete each variable individually
delete(a)
delete(pi)
delete(s)
delete(r)
delete(R)
; delete multiple variables in one line
delete( [/ a, pi, s, r, R, q /] ) ; [/…/] list syntax
Conversion between data types
●
NCL is a ‘strongly typed’ language
●
constraints on mixing data types
●
coercion
●
implicit conversion of one type to another
●
automatic coercion when no info is lost
●
let i be integer and x be float or double
●
fortran: x=i and i=x
●
NCL: x=i and i=toint(x)
●
many functions to perform conversions
Variable Reassignment
• NCL = will not allow the following
k = (/ 1, 3, 4, 9 /) ; 1d array, type integer
… later in code …
k = (/17.5, 21.4/) ; different size and type
●
Two approaches
●
Up to version 6.1.1, 2 steps required
delete(k) ; delete existing variable
k = (/17.5, 21.4/) ; new assignment
Version 6.1.2
k := (/17.5, 21.4/) ; delete previous variable
; and reassign ‘k’
Meta Data
• information associated with variable or file
●
attributes: @ (numeric, text)
●
named dimensions: ! (text)
●
coordinates: & (numeric)
• @, !, & can be used to create/assign,
retrieve
• most frequently, meta data is read from files
●
NCL functions recognize _FillValue
●
most functions will ignore for computations (eg, “avg”)
●
use built-in function “ismissing” to check for _FillValue
●
if (any (ismissing(T) )) then … end if
●
NOTE: if (any(T.eq.T@_FillValue)) will not work
Consider T(time,lat,lon)
T entire array [ don't use T(:,:,:) ]
T(0,:,::5) 1st time index, all lat, every 5th lon
T(:3, ::-1, :50) 1st 4 time indices, reverse, 1st 51 lon
Named Dimensions
• only used for dimension reordering
• indicated by |
• dim names must be used for each subscript
• named/coordinate subscripting can be mixed
Consider T(time,lat,lon)
t = T(lat|:, lon|:, time|:) makes t(lat,lon,time)
t = T(time|:,{lon|90:120},{lat|-20:20}) all times,
90-120° lon, -20-20° lat
Subscripting: Index, CV
Latitude coordinate variable (1D)
Standard:
T(9:13,1:8)
Coordinate:
T({-10:20},{-170:-110})
Combined:
Longitude coordinate variable (1D) T({-10:20}, 1:8)
“printing”
• PrintVarSummary
gives gross overview of a variable
• Print
includes same info as printVarSummary but
prints each value
• write_matrix
●
print to standard out or a file
●
format control of numerical output
●
can write to file also
printVarSummary
• Print overview of variable contents
●
type
●
dimension information
●
coordinate information (if present)
●
attributes (if present)
• printVarSummary (u)
Variable: u
Type: double
Total Size: 1179648 bytes
147456 values
Number of Dimensions: 4
Dimensions / Sizes: [time | 1] x [lev | 18] x [lat | 64] x [lon | 128]
Coordinates:
time: [4046..4046]
lev: [4.809 .. 992.5282]
lat: [-87.86379 .. 87.86379]
lon: [ 0. 0 .. 357.1875]
Number of Attributes: 2
long_name: zonal wind component
units: m/s
print (1 of 3)
• Prints out all variable information including
●
All meta data, values
●
T(lat,lon): print (T)
Variable: T
Type: float
Total Size: 32768 bytes
8192 values
Number of Dimensions: 2
Dimensions / Sizes: [lat | 64] x [lon | 128]
Coordinates:
lat: [-87.86379 .. 87.86379]
lon: [ 0. 0 .. 357.1875]
Number of Attributes: 2
long_name: Temperature
units: degC
(0,0) -31.7
(0,1) -31.4
(0,2) -32.3
(0,3) -33.4
(0,4) -31.3 etc. [entire T array will be printed]
print (2 of 3)
• can be used to print a subset of array
●
meta data, values
●
T(lat,lon): print( T(:,103) ) or print( T(:,{110}) )
Variable: T (subsection)
Type: float
Total Size: 256 bytes
64 values
Number of Dimensions: 1
Dimensions / Sizes: [lat | 64]
Coordinates:
lat: [-87.86379 .. 87.86379]
Number of Attributes: 3
long_name: Temperature
units: degC
lon: 109.6875 [ added ]
(0) -40.7
(1) -33.0
• -25.1
• -20.0
(4) -15.3 etc.
print (3 of 3)
• print with embedded strings
●
no meta data
●
print ( ”T: min="+min(T)+" max="+max(T) )
(0) T: min=-53.8125 max=25.9736
●
Binary
Can be a little tricky.
https://www.ncl.ucar.edu/Applications/r-binary.shtml
●
ASCII
Fairly easy if the file is just a matrix.
https://www.ncl.ucar.edu/Applications/read_ascii.shtml
ncl_filedump
http://www.ncl.ucar.edu/Document/Tools/ncl_filedump.shtml
− .nc .grb .hdf .hdfeos .he5 .h5 .ccm .shp [case insensitive]
− suffix used as identifier only, actual file need not have
• ncl_filedump file_name.[grb/nc/hdf/hdfeos]
- output can be sent to file or viewer via Unix redirection/ pipe
ncl_filedump foo.grb > foo.txt [send to file]
ncl_filedump foo.hdf | less [send to viewer]
ncl_convert2nc
http://www.ncl.ucar.edu/Document/Tools/
ncl_convert2nc gribFile(s) OPTIONS
command line utility
converts GRIB/HDF/SHAPE file(s) to netCDF
output name same as input with .nc extension
ncl_convert2nc –h
provides usage option information
ncl_convert2nc foo.grb
will create foo.nc
ncl_convert2nc foo.hdf –L –nc4c –cl 1
-L (files> 2GB); -nc4c (netCDF4); -cl 1 (compression lvl 1)
setfileoption
www.ncl.ucar.edu/Document/Functions/Built_in/setfileoption.shtml
allows user to specify file-format-specific options
netCDF, GRIB and Binary options [currently]
sample usage of selected options
writing netCDF
setfileoption(f, "DefineMode" ,True)
setfileoption("nc","Format","LargeFile")
setfileoption("nc","Format",”netCDF4Classic")
reading GRIB
setfileoption("grb" ,"ThinnedGridInterpolation", "cubic")
setfileoption("grb", "InitialTimeCoordinateType" \
, "Numeric")
reading/writing Binary
setfileoption("bin", "ReadByteOrder", "LittleEndian")
setfileoption("bin", “WriteByteOrder", “BigEndian")
addfile (1 of 3)
• Opens a supported format
• Variables look like netCDF (Grib, HDF, HDF-EOS)
• f_p = addfile (file_name.ext, status )
− file_name => any valid file name; string
− ext => extension that identifies the type of file; string
netCDF: "nc" or "cdf" [read/write]
HDF: "hdf" , "hdfeos”, "h5”, "he5" [read/write]
GRIB: "grb" , "grib" [read only; GRIB1 or GRIB2]
CCMHT: "ccm" [read only]
SHAPE (GIS): ”shp" [read only]
extension not required to be attached to file
http://www.ncl.ucar.edu/Document/Manuals/Ref_Manual/NclFormatSupport.shtml
addfile (2 of 3)
• Examples: opening a single file
●
fin = addfile ("0005-12.nc" , "r")
●
fout = addfile ("./ncOutput.nc" , "c")
●
fio = addfile ("/tmp/shea/sample.hdf" , "w")
●
g = addfile ("/dss/dsxxx/Y12345.grb", "r" )
●
s = addfile ("foo.shp" , ”r")
fout->U =u
fout->T = Temp
●
commonly used
●
writes all variable components [data object ;-) ]
●
may be inefficient (possibly, very inefficient)
●
use for file with few variables/records
Efficient netCDF Creation
• requires ‘a priori’ definition of file contents
− must be done in other languages/tools also [F, C, IDL, ..]
• NCL functions to predefine a netCDF/HDF file:
− setfileoption: specify entering define mode
− filevardef: define name(s) of one or more variables
− filevarattdef: copy attributes from a variable to one
or more file variables
− filedimdef: defines dimensions including unlimited
− fileattdef: copy attributes from a variable to a file
as global attributes
●
if-then-end if (note: end if has space)
if ( all(a.gt.0.) ) then
…statements
end if
●
if-then-else-end if
if ( any(ismissing(a)) ) then
…statements
else
…statements
end if
●
lazy expression evaluation [left-to-right]
if ( any(b.lt.0.) .and. all(a.gt.0.) ) then
…statements
end if
loops
●
do loop (traditional structure; end do has space)
●
do i=scalar_start_exp, scalar_end_exp [, scalar_skip_exp]
do n = nStrt, nLast [,stride]
… statements
end do ; 'end do' has a space
●
if start > end
●
identifier 'n' is decremented by a positive stride
●
stride must always be present when start>end
●
do while loop
do while (x .gt. 100)
… statements
end do
●
break: loop to abort [f90: exit]
●
continue: proceed to next iteration [f90: cycle]
●
minimize loop usage in any interpreted language
●
use array syntax, built-in functions, procedures
●
use Fortran/C codes when efficient looping is required
Built-in Functions and Procedures(1 of 2)
●
use whenever possible
●
learn and use utility functions
●
all, any, conform, ind, ind_resolve, dimsizes
●
fspan, ispan, ndtooned, onedtond,
●
mask, ismissing, where
●
system, systemfunc [use local system]
●
functions may require dimension reordering
●
*must* use named dimensions to reorder
; compute zonal and time averages of variable
; T(time,lev,lat,lon) T(0,1,2,3)
; (zonal average requires rectilinear grid)
●
time = (/ 17522904, 17522928, 17522952/)
●
time@units = “hours since 1-1-1 00:00:0.0”
●
date = cd_calendar(time,-2)
●
date = cd_calendar(time, 0)
●
print(date)
●
print(date)
Variable: date
Variable: date Type: integer
Type: float Total Size: 12 bytes 3 values
Total Size: 72 bytes 18 values Number of Dimensions: 1
Number of Dimensions: 2 Dimensions and sizes: [3]
Dimensions and sizes: [3] x [6] (0) 20000101
(0,0:5) 2000 1 1 0 0 0 (1) 20000102
(1,0:5) 2000 1 2 0 0 0 (2) 20000103
(2,0:5) 2000 1 3 0 0 0
●
TIME = cd_inv_calendar (iyr, imo, iday, ihr, imin, sec \
●
,“hours since 1-1-1 00:00:0.0” ,0)
system, systemfunc (1 of 2)
●
system passes to the shell a command to perform an action
●
NCL executes the Bourne shell (can be changed)
●
create a directory if it does not exist (Bourne shell syntax)
●
DIR = “/ptmp/shea/SAMPLE”
●
system (“if ! test –d “+DIR+” ; then mkdir “+DIR+” ; fi”)
●
same but force the C-shell (csh) to be used
●
the single quotes (‘) prevent the Bourne shell from interpreting csh syntax
●
system ( “csh –c ‘ if (! –d “+DIR+”) then ; mkdir “+DIR+” ; endif ’
”)
●
execute some local command
●
system (“convert foo.eps foo.png ; /bin/rm foo.eps ”)
●
system (“ncrcat -v T,Q foo*.nc FOO.nc ”)
●
system (“/bin/rm –f “ + file_name)
system, systemfunc (1 of 2)
• systemfunc returns to NCL information from the system
• NCL executes the Bourne shell (can be changed)
●
UTC = systemfunc(“date”) ; *nix date
●
Date = systemfunc(“date ‘+%a %m%d%y %H%M’ ”) ; single quote
●
fils = systemfunc (“cd /some/directory ; ls foo*nc”) ; multiple cmds
●
city = systemfunc ("cut -c100-108 " + fname)
User-built Functions and Procedures(1 of 2)
●
two ways to load existing files w functions/proc
●
load "/path/my_script.ncl"
●
use environment variable: NCL_DEFAULT_SCRIPTS_DIR
●
must be loaded prior to use
●
unlike in compiled language
●
avoid function conflict (undef)
●
Use (…) to circumvent precedence rules
●
All support scalar and array operations [like f90]
●
+ is overloaded operator
●
algebraic operator: 5.3 + 7.95 13.25
●
concatenate string: “pine” + “apple” “pineapple”
●
algebraic operator and string concatenator
●
"alpha” + ”_" + (5.3 + 7) "alpha_12.3”
Logical Expressions
●
if-then-end if (note: end if has space)
if ( all(a.gt.0.) ) then
…statements
end if
●
if-then-else-end if
if ( any(ismissing(a)) ) then
…statements
else
…statements
end if
●
lazy expression evaluation [left-to-right]
if ( any(b.lt.0.) .and. all(a.gt.0.) ) then
…statements
end if
loops
●
do loop (traditional structure; end do has space)
●
do i=scalar_start_exp, scalar_end_exp [, scalar_skip_exp]
do n = nStrt, nLast [,stride]
… statements
end do ; 'end do' has a space
●
if start > end
●
identifier 'n' is decremented by a positive stride
●
stride must always be present when start>end
●
do while loop
do while (x .gt. 100)
… statements
end do
●
break: loop to abort [f90: exit]
●
continue: proceed to next iteration [f90: cycle]
●
minimize loop usage in any interpreted language
●
use array syntax, built-in functions, procedures
●
use Fortran/C codes when efficient looping is required
Built-in Functions and Procedures(1 of 2)
●
use whenever possible
●
learn and use utility functions
●
all, any, conform, ind, ind_resolve, dimsizes
●
fspan, ispan, ndtooned, onedtond,
●
mask, ismissing, where
●
system, systemfunc [use local system]
●
functions may require dimension reordering
●
*must* use named dimensions to reorder
●
time = (/ 17522904, 17522928, 17522952/)
●
time@units = “hours since 1-1-1 00:00:0.0”
●
date = cd_calendar(time,-2)
●
date = cd_calendar(time, 0)
●
print(date)
●
print(date)
Variable: date
Variable: date Type: integer
Type: float Total Size: 12 bytes 3 values
Total Size: 72 bytes 18 values Number of Dimensions: 1
Number of Dimensions: 2 Dimensions and sizes: [3]
Dimensions and sizes: [3] x [6] (0) 20000101
(0,0:5) 2000 1 1 0 0 0 (1) 20000102
(1,0:5) 2000 1 2 0 0 0 (2) 20000103
(2,0:5) 2000 1 3 0 0 0
●
TIME = cd_inv_calendar (iyr, imo, iday, ihr, imin, sec \
●
,“hours since 1-1-1 00:00:0.0” ,0)
system, systemfunc (1 of 2)
●
system passes to the shell a command to perform an action
●
NCL executes the Bourne shell (can be changed)
●
create a directory if it does not exist (Bourne shell syntax)
●
DIR = “/ptmp/shea/SAMPLE”
●
system (“if ! test –d “+DIR+” ; then mkdir “+DIR+” ; fi”)
●
same but force the C-shell (csh) to be used
●
the single quotes (‘) prevent the Bourne shell from interpreting csh syntax
●
system ( “csh –c ‘ if (! –d “+DIR+”) then ; mkdir “+DIR+” ; endif ’
”)
●
execute some local command
●
system (“convert foo.eps foo.png ; /bin/rm foo.eps ”)
●
system (“ncrcat -v T,Q foo*.nc FOO.nc ”)
●
system (“/bin/rm –f “ + file_name)
system, systemfunc (1 of 2)
• systemfunc returns to NCL information from the system
• NCL executes the Bourne shell (can be changed)
●
UTC = systemfunc(“date”) ; *nix date
●
Date = systemfunc(“date ‘+%a %m%d%y %H%M’ ”) ; single quote
●
fils = systemfunc (“cd /some/directory ; ls foo*nc”) ; multiple cmds
●
city = systemfunc ("cut -c100-108 " + fname)
User-built Functions and Procedures(1 of 4)
●
two ways to load existing files w
functions/proc
●
load "/path/my_script.ncl"
●
use environment variable:
NCL_DEFAULT_SCRIPTS_DIR
●
must be loaded prior to use
●
unlike in compiled language
●
avoid function conflict (undef)
undef ("mult")
function mult(x1,x2,x3,x4)undef ("mult")
begin function mult(x1,x2,x3,x4)
return ( x1*x2*x3*x4) begin
end return ( x1*x2*x3*x4)
end
load “/some/path/myLIB.ncl“
begin begin
x = mult(4.7, 34, 567, 2) x = mult(4.7, 34, 567, 2)
end end
User-Built Functions and Procedures(2 of 4)
• Development process similar to Fortran/C/IDL
• General Structure:
Ice thickness
(filled contours)
Topo map
(filled contours)
UV winds
Vertically-integrated
clouds (partially
transparent
filled contours)
Types of graphics you can create with NCL
• Over 40 plotting templates
• XY
• Contour
• Vector
• Streamline
• Overlays
− Contours over maps, vectors over contours, etc.
• Primitives
− markers, polylines, polygons, text
• Specialized plots
− bar charts, skew-T, wind roses, taylor diagrams
Introduction to NCL Graphics
Filled polygons with text
skew-t.ncl
Wind Rose
Histograms
Skew T
Introduction to NCL Graphics
More Special Templates and Scripts
Tables
Pie Charts
Bar plots
Blank plots
automatic subtitles
http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml
http://www.ncl.ucar.edu/Document/Graphics/create_color_table.shtml
Introduction to NCL Graphics
Step 3: Define a color map (optional)
• A default color map (256 colors) is provided
• If you want to change it, do so before
drawing any graphics to a page:
gsn_define_colormap(wks, “rainbow”)
• If you use the same color map a lot, can put it
in the “.hluresfile” file (more later)
• Can use one of the other 90+ color maps, or
create your own.
Step 4: Set plot options (resources)
• Resources are the heart of your NCL
graphics code. There are over 1,400
resources!
• Use resources to change the look of a plot
• They are grouped by object type.
• There are 11 “graphical” objects: contours,
labelbars, legends, maps, primitives,
streamlines, text strings, tickmarks, titles,
vectors, XY plots
http://www.ncl.ucar.edu/Document/Graphics/Resources/
Step 5: Select a plotting function
● Color-coded code is
much easier to read!
● Some enhancements
will auto-complete or
provide documentation
on a function or
procedure.
● My personal favorite is
Kate.
http://kate-editor.org/
Fortran / C Interface
https://www.ncl.ucar.edu/Document/Tools/WRAPIT.shtml
● Computing trajectories.