\input texinfo @c -*-texinfo-*- 
@c \input /home/zender/texinfo_fedora.tex
@c \input /home/zender/texinfo_ubuntu.tex

@c 19980817: TeX-based systems (texi2dvi, texi2dvi --pdf) require texinfo.tex
@c Hyper-text systems (texi2html, makeinfo) do not require texinfo.tex

@ignore

$Header: /cvsroot/nco/nco/doc/nco.texi,v 1.968 2014/02/19 17:28:06 zender Exp $

Purpose: TeXInfo documentation for NCO suite

URL: http://nco.sf.net/nco.texi

Copyright (C) 1995--2014 Charlie Zender
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. The license is available online at 
http://www.gnu.org/copyleft/fdl.html

The original author of this software, Charlie Zender, seeks to improve
it with your suggestions, contributions, bug-reports, and patches.
Charlie Zender <surname at uci dot edu> (yes, my surname is zender)
Department of Earth System Science
3200 Croul Hall
University of California, Irvine
Irvine, CA 92697-3100

After editing any hyperlink locations, Emacs users update indices with
C-c C-u C-a	texinfo-all-menus-update
C-c C-u C-e	texinfo-every-node-updatexb

Multiple files:
M-x texinfo-multiple-files-update

Usage: 
export TEX='tex --src-specials'
cd ~/nco/doc;texi2dvi nco.texi; makeinfo --html --ifinfo --no-split --output=nco.html nco.texi; makeinfo nco.texi; dvips -o nco.ps nco.dvi;texi2dvi --pdf nco.texi;makeinfo --xml --ifinfo --no-split --output=nco.xml nco.texi;makeinfo --no-headers --output=nco.txt nco.texi
dvips -o nco.ps nco.dvi 
dvips -Ppdf -G0 -o nco.ps nco.dvi 
makeinfo --html --ifinfo --no-split --output=nco.html nco.texi
makeinfo --no-split --output=nco.info nco.texi
makeinfo --no-headers --no-split --output=nco.txt nco.texi
makeinfo --xml --no-split --output=nco.xml nco.texi
makeinfo --docbook --no-split --output=nco.xml nco.texi
pdftotext nco.pdf nco.txt
ps2pdf -dMaxSubsetPct=100 -dCompatibilityLevel=1.2 -dSubsetFonts=true -dEmbedAllFonts=true nco.ps nco.pdf
texi2dvi --output=nco.dvi nco.texi 
texi2dvi --pdf --output=nco.pdf nco.texi
texi2html -monolithic -verbose nco.texi
texi2html -l2h -l2h_tmp=./l2h_tmp -monolithic -verbose nco.texi # Invoke latex2html
cd ~/nco/doc;/usr/bin/scp index.shtml nco_news.shtml ChangeLog TODO README VERSION nco.dvi nco.html nco.info* nco.pdf nco.ps nco.texi nco.txt nco.xml ../data/ncap.in ../data/ncap2.in zender,nco@web.sf.net:/home/project-web/nco/htdocs;cd -
cd ~/nco/doc;      scp -p index.shtml nco_news.shtml ChangeLog TODO README VERSION nco.dvi nco.html nco.info* nco.pdf nco.ps nco.texi nco.txt nco.xml ../data/ncap.in ../data/ncap2.in dust.ess.uci.edu:/var/www/html/nco;cd -
# 20130806 Copy CMIP5 images (takes additional time)
cd ~/nco/doc/xmp;/usr/bin/scp fgr*.png fgr*.eps zender,nco@web.sf.net:/home/project-web/nco/htdocs/xmp;cd -
cd ~/nco/doc/xmp;/usr/bin/scp fgr*.png fgr*.eps                 dust.ess.uci.edu:/var/www/html/nco/xmp;cd -
# 20120203 Copy all nco.html PNG images (takes additional time)
cd ~/nco/doc;/usr/bin/scp nco_*.png zender,nco@web.sf.net:/home/project-web/nco/htdocs;cd -
cd ~/nco/doc;scp -p nco_*.png dust.ess.uci.edu:/var/www/html/nco;cd -
# 20130801 Copy nco.texi to Ubuntu machine for quick build-tests
scp ~/nco/doc/nco.texi givre.ess.uci.edu:nco/doc

NB: @cindex references in footnotes propagate to PDF file, not to
    HTML files, bug-report sent to makeinfo people 20040229

Producing HTML, makeinfo vs. texi2html:
makeinfo: Better format overall 
          Uses node names for cross references and index
          Acronyms look better
          Excludes @ifinfo sections by default (override with --ifinfo)
texi2html: Index sub-divided by first character
           More fancy options (e.g., latex2html), though none very useful 
           Misprints title
           Includes @ifinfo sections by default

Legend (defined in "highlighting" section of TeXInfo manual):
@code{}: Program text, e.g., @code{if(foo) x=y;}
@command{}: Commands, e.g., @command{ncra}
@dfn{}: Define use of term, e.g., @dfn{supercalifragilisticexpialidocious}
@email{}: E-mail address, e.g., @email{surname at uci dot edu}
@env{}: Environment variable, e.g., @env{HOME}
@file{}: Filename, e.g., @file{in.nc}
@html: Text until @end html passed without translation
@ifhtml: Text until @end ifhtml passed with translation
@kbd{}: Keyboard input, e.g., @kbd{ncra in.nc out.nc}
@key{}: Key name, e.g., @key{ESC} (rarely needed)
@option{}: Command-line option, e.g., @option{--dbg}
@samp{}: Extended commands, character sequences, e.g., @samp{ncra in.nc out.nc}
@uref{}: URL with optional alternate text, e.g., @uref{http://nco.sf.net,NCO homepage}
@url{}: URL, synonym for @uref
@var{}: Metasyntactic variable, e.g., @var{}
@verbatim: Anything goes inside environment (no @'s needed to protect special characters like braces)
@example: Quoted environment (@'s needed to protect special characters like braces)
@w{}: Unbreakable text, e.g., @w{of 1}

Use '@*' to force hard carriage return
Use '@:', after periods, questions marks, exclamation marks, or colons
that do not end sentences, e.g., 'vs.@:'
Use '@.', '@!', and `@?' to end sentences that end with single capital letters (e.g., initials)

Resources:
Octave TeXInfo manual shows clean TeXInfo structure
/usr/share/doc/octave-2.1.34/interpreter/octave.texi
@end ignore

@c Start of header

@c No variables may be defined before TeXInfo @setfilename header
@setfilename nco.info

@c Define edition, date, ...
@set nco-edition 4.4.2
@set doc-edition 4.4.2
@set copyright-years 1995--2014
@set update-year 2014
@set update-date 19 February 2014
@set update-month February 2014

@settitle @acronym{NCO} @value{nco-edition} User Guide

@c Uncomment following line to produce guide in smallbook format
@c @smallbook
@c Merge function index into concept index
@syncodeindex fn cp

@c 20090226 Add bibliography capabilities as per
@c http://lists.gnu.org/archive/html//help-texinfo/2004-12/txtPW9h_VG8ez.txt
@include my-bib-macros.texi
@mybibuselist{References}

@c end of header

@c TeXInfo macros may not appear before TeXInfo @setfilename header
@c [idx] Index
@macro idx {}
i
@end macro
@c [m s-1] Meridional wind speed
@macro wndmrd {}
v
@end macro
@c [m s-1] Zonal wind speed
@macro wndznl {}
u
@end macro
@macro xxx {}
x
@end macro
@c TeX macros may appear anywhere after line 1
@tex
% Define TeX macros to roughly correspond to LaTeX style files
% Use \gdef instead of \def to make definition persistent across TeX blocks
% These should be consistent with any TeXInfo macros
% 1. Primary commands
\gdef\dmn{D} % [dmn] Variable dimension
\gdef\rdr{R} % [dmn] Re-order dimension
\gdef\shr{S} % [dmn] Share dimension
\gdef\dmnidx{n} % [idx] Dimension index
\gdef\dmnnbr{N} % [nbr] Dimension number
\gdef\rdridx{r} % [idx] Re-order index
\gdef\rdrnbr{R} % [nbr] Re-order number
\gdef\shridx{s} % [idx] Share index
\gdef\shrnbr{S} % [nbr] Share number
\gdef\dfr{{\rm d}} % [frc] Math differential fxm: upright
\gdef\idx{i} % [idx] Index
\gdef\iii{i} % [idx] i
\gdef\jjj{j} % [idx] j
\gdef\kkk{k} % [idx] k
\gdef\lmnidx{i} % [idx] Element index
\gdef\outnbr{J} % [nbr] Number of elements in output hyperslab
\gdef\lmnnbr{N} % [nbr] Number of elements in input hyperslab
\gdef\tllnbr{M} % [nbr] Tally (number of valid elements in input hyperslab)
\gdef\me{{\rm e}} % [frc] Math e fxm: upright
\gdef\mi{{\rm i}} % [frc] Math i fxm: upright
\gdef\mpi{\pi} % [frc] Math pi
\gdef\mpp{\cal{M}} % [map] Map
\gdef\mskflg{m} % [flg] Mask flag
\gdef\mssflg{\mu} % [flg] Missing value flag
\gdef\tm{t} % [s] Time
\gdef\prmsbs{\prime} % [sbs] Prime subscript
\gdef\wgt{w} % [frc] Weight
\gdef\wndmrd{v} % [m s-1] Meridional wind speed
\gdef\wndznl{u} % [m s-1] Zonal wind speed
\gdef\xxx{x} % [ltr] x
\gdef\yyy{y} % [ltr] y

% 2. Derived commands
\gdef\dmnvct{{\bf \dmn}} % [vct] Dimension vector
\gdef\dmnprm{\dmn^{\prmsbs}} % [vct] Dimension prime
\gdef\dmnsubnnn{\dmn_{\dmnidx}} % [dmn] Dimension sub nnn
\gdef\shrsubnnn{\shr_{\dmnidx}} % [dmn] Share dimension sub nnn
\gdef\shrsubsss{\shr_{\shridx}} % [dmn] Share dimension sub sss
\gdef\dmnsubnnnprm{\dmn_{\dmnidx}^{\prmsbs}} % [vct] Dimension prime sub nnn 
\gdef\dmnvctprm{{\bf \dmn}^{\prmsbs}} % [vct] Dimension vector prime
\gdef\rdrvct{{\bf \rdr}} % [vct] Re-order vector
\gdef\shrvct{{\bf \shr}} % [vct] Share vector
\gdef\xxxprm{\xxx^{\prmsbs}} % [ltr] x prime

% 3. Doubly derived commands

@end tex

@c install-info installs NCO info into this category
@dircategory netCDF
@direntry
* NCO::        User Guide for the netCDF Operator suite
@end direntry
@iftex
@tolerance 10000
@end iftex

@c Set smallbook if printing in smallbook format
@c Example of smallbook font is actually written using smallbook
@c In bigbook, a kludge is used for TeX output
@c set smallbook
@clear smallbook

@tex
% fxm: Try to get thumbnails working with texinfo --pdf -generated PDF files
% \input thumbpdf.sty
% Experiment with smaller amounts of whitespace between chapters and sections
\global\chapheadingskip = 15pt plus 4pt minus 2pt 
\global\secheadingskip = 12pt plus 3pt minus 2pt
\global\subsecheadingskip = 9pt plus 2pt minus 2pt
@end tex

@c Experiment with smaller amounts of whitespace between paragraphs in the 8.5 by 11 inch format
@ifclear smallbook
@tex
\global\parskip 6pt plus 1pt
@end tex
@end ifclear

@c Uncomment next line to remove ugly TeX warning blocks from overfull hboxes
@finalout

@ifinfo
This file documents @acronym{NCO}, a collection of utilities to
manipulate and analyze netCDF files.

Copyright @copyright{} @value{copyright-years} Charlie Zender

This is the first edition of the @cite{NCO User Guide},@*
and is consistent with @w{version 2} of @file{texinfo.tex}.

Permission is granted to copy, distribute and/or modify this document 
under the terms of the @acronym{GNU} Free Documentation License, @w{Version 1.3}
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. The license is available online at 
@uref{http://www.gnu.org/copyleft/fdl.html}

The original author of this software, Charlie Zender, wants to improve it
with the help of your suggestions, improvements, bug-reports, and patches.@*
Charlie Zender <surname at uci dot edu> (yes, my surname is zender)@*
3200 Croul Hall@*
Department of Earth System Science@*
University of California, Irvine@*
Irvine, CA 92697-3100@*

@ignore
Permission is granted to process this file through TeX and print the 
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).
@end ignore
@end ifinfo

@setchapternewpage odd

@titlepage
@html
<meta name="Author" content="Charlie Zender">
<meta name="Keywords" content="NCO documentation, NCO User Guide,
netCDF, operator, GCM, CCM, scientific data, ncbo, ncfe, ncecat,
ncflint, ncks, ncra, ncrcat, ncrename, ncwa">
@end html
@html
<body text="#000000" link="#0000EF" vlink="#008080" alink="#FF0000">
<font face="Arial">
@end html
@ignore
@end ignore
@title NCO User Guide
@subtitle A suite of netCDF operators
@subtitle Edition @value{doc-edition}, for @acronym{NCO} Version @value{nco-edition}
@subtitle @value{update-month}

@author by Charlie Zender
@author Department of Earth System Science
@author University of California, Irvine
@html
<p>WWW readers: Having trouble finding the section you want?</p> 
<p>Search for keywords in the <a href="#index">(hyper) index</a> at the end</p>
@end html

@c Include Distribution inside titlepage so that headings are turned off
@page
@vskip 0pt plus 1filll
Copyright @copyright{} @value{copyright-years} Charlie Zender.

@sp 2
This is the first edition of the @cite{NCO User Guide},@*
and is consistent with @w{version 2} of @file{texinfo.tex}.
@sp 2

Published by Charlie Zender@*
Department of Earth System Science@*
3200 Croul Hall@*
University of California, Irvine@*
Irvine, CA 92697-3100 USA@*

Permission is granted to copy, distribute and/or modify this document
under the terms of the @acronym{GNU} Free Documentation License, @w{Version 1.3}
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. The license is available online at 
@uref{http://www.gnu.org/copyleft/fdl.html}
@sp 2
The original author of this software, Charlie Zender, wants to improve it
with the help of your suggestions, improvements, bug-reports, and patches.@*
Charlie Zender <surname at uci dot edu> (yes, my surname is zender)@*
Department of Earth System Science@*
3200 Croul Hall@*
University of California, Irvine@*
Irvine, CA 92697-3100@*
@sp 2
@c Cover art by Robynn Rudel
@end titlepage

@c Print table of contents
@contents

@node Top, Foreword, (dir), (dir)
@ifinfo
@top NCO User Guide
@c node format: node-name, next, previous, up

@ifhtml
@cartouche
@html
<p><b>Note to readers of the NCO User Guide in HTML format</b>: 
<b>The <a href="./nco.pdf">NCO User Guide in PDF format</a> 
(also on <a href="http://nco.sf.net/nco.pdf">SourceForge</a>)
contains the complete NCO documentation.</b> 
<br>This HTML documentation is equivalent except it refers you to the
printed (i.e., DVI, PostScript, and PDF) documentation for description
of complex mathematical expressions. Also, images appear only in the
PDF document due to SourceForge limitations.
@end html
@end cartouche
@end ifhtml
@ifnothtml
@emph{Note to readers of the NCO User Guide in Info format}: 
@emph{The @uref{./nco.pdf,NCO User Guide in PDF format}
(also on @uref{http://nco.sf.net/nco.pdf,SourceForge})
contains the complete @acronym{NCO} documentation.}
This Info documentation is equivalent except it refers you to the 
printed (i.e., DVI, PostScript, and PDF) documentation for description 
of complex mathematical expressions. Also, images appear only in the
PDF document due to SourceForge limitations.
@end ifnothtml

The netCDF Operators, or @acronym{NCO}, are a suite of programs known as 
operators. 
The operators facilitate manipulation and analysis of data stored in the 
self-describing netCDF format, available from
(@uref{http://www.unidata.ucar.edu/packages/netcdf}).
Each @acronym{NCO} operator (e.g., ncks) takes netCDF input
file(s), performs an operation (e.g., averaging, hyperslabbing, or
renaming), and outputs a processed netCDF file. 
Although most users of netCDF data are involved in scientific research,
these data formats, and thus @acronym{NCO}, are generic and are equally
useful in fields from agriculture to zoology.
The @acronym{NCO} User Guide illustrates @acronym{NCO} use with
examples from the field of climate modeling and analysis. 
The @acronym{NCO} homepage is @uref{http://nco.sf.net}, and
there is a mirror at @uref{http://dust.ess.uci.edu/nco}.

This documentation is for @acronym{NCO} version @value{nco-edition}.
It was last updated @value{update-date}.
Corrections, additions, and rewrites of this documentation are very
welcome.

Enjoy,@*
Charlie Zender
@end ifinfo

@menu
* Foreword::
* Summary::
* Introduction::
* Strategies::
* Common features::
* Operator Reference Manual::
* Contributing::
* Quick Start::
* CMIP5 Example::
* Parallel::
* CCSM Example::
* mybibnode::
* General Index::
@end menu

@html
<a name="fwd"></a> <!-- http://nco.sf.net/nco.html#fwd -->
@end html
@node Foreword, Summary, Top, Top
@unnumbered Foreword
@cindex foreword
@cindex Charlie Zender
@acronym{NCO} is the result of software needs that arose while I worked
on projects funded by @acronym{NCAR}, @acronym{NASA}, and @acronym{ARM}.
Thinking they might prove useful as tools or templates to others,  
it is my pleasure to provide them freely to the scientific community.  
Many users (most of whom I have never met) have encouraged the
development of @acronym{NCO}.  
Thanks espcially to Jan Polcher, Keith Lindsay, Arlindo @w{da Silva},
John Sheldon, and William Weibel for stimulating suggestions and
correspondence. 
Your encouragment motivated me to complete the @cite{NCO User Guide}.
So if you like @acronym{NCO}, send me a note!
@w{I should} mention that @acronym{NCO} is not connected to or
officially endorsed by Unidata, @acronym{ACD}, @acronym{ASP},
@acronym{CGD}, or Nike.@* 
@sp 1
@noindent
Charlie Zender@*
May 1997@*
Boulder, Colorado@*

@sp 2
Major feature improvements entitle me to write another Foreword.
In the last five years a lot of work has been done to refine
@acronym{NCO}. 
@cindex open source
@acronym{NCO} is now an open source project and appears to be much
healthier for it. 
The list of illustrious institutions that do not endorse @acronym{NCO}     
continues to grow, and now includes @acronym{UCI}.@* 
@sp 1
@noindent
Charlie Zender@*
October 2000@*
Irvine, California@*

@sp 2
The most remarkable advances in @acronym{NCO} capabilities in the last  
few years are due to contributions from the Open Source community.
Especially noteworthy are the contributions of Henry Butowsky and Rorik 
Peterson.@* 
@sp 1
@noindent
Charlie Zender@*
January 2003@*
Irvine, California@*

@sp 2
@acronym{NCO} was generously supported from 2004--2008 by US 
National Science Foundation (@acronym{NSF}) grant 
@uref{http://www.nsf.gov/awardsearch/showAward.do?AwardNumber=0431203,IIS-0431203}. 
This support allowed me to maintain and extend core @acronym{NCO} code,
and others to advance @acronym{NCO} in new directions: 
Gayathri Venkitachalam helped implement @acronym{MPI};
Harry Mangalam improved regression testing and benchmarking;
Daniel Wang developed the server-side capability, @acronym{SWAMP};
and Henry Butowsky, a long-time contributor, developed @command{ncap2}.
This support also led @acronym{NCO} to debut in professional journals
and meetings.  
The personal and professional contacts made during this evolution have
been immensely rewarding.@*
@sp 1
@noindent
Charlie Zender@*
March 2008@*
Grenoble, France@*

@sp 2
The end of the @acronym{NSF} SEI grant in August, 2008 curtailed @acronym{NCO}
development.  
Fortunately we could justify supporting Henry Butowsky on other research 
grants until May, 2010 while he developed the key @command{ncap2}
features used in our climate research.
And recentely the NASA ACCESS program commenced funding NCO support for
netCDF4 group functionality.@* 
Thus @acronym{NCO} will grow and evade bit-rot for the foreseeable future.

On a personal level, I continue to receive with gratitude the thanks of
@acronym{NCO} users at nearly every scientific meeting I attend. 
People introduce themselves, shake my hand and extol, sometimes rather
effusively, these time-saving tools.
These exchanges lighten me like anti-gravity.
Sometimes I daydream how many hours @acronym{NCO} has turned from grunt
work to productive research for researchers world-wide, or from research
into early happy hours. 
It's a cool feeling.

@c @uref{http://www.nasa.gov/mission_pages/IPY/main/PolarExploration.html,NNX07AR23G}.@*
@sp 1
@noindent
Charlie Zender@*
April, 2012@*
Irvine, California@*

@html
<a name="smr"></a> <!-- http://nco.sf.net/nco.html#smr -->
@end html
@node Summary, Introduction, Foreword, Top
@unnumbered Summary
@cindex operators
@cindex summary
This manual describes @acronym{NCO}, which stands for netCDF Operators.
@acronym{NCO} is a suite of programs known as @dfn{operators}.
Each operator is a standalone, command line program executed at the
shell-level like, e.g., @command{ls} or @command{mkdir}.  
The operators take netCDF files (including @acronym{HDF5} files
constructed using the netCDF @acronym{API}) as input, perform an
operation (e.g., averaging or hyperslabbing), and produce a netCDF file 
as output.  
The operators are primarily designed to aid manipulation and analysis of 
data.
The examples in this documentation are typical applications of the
operators for processing climate model output. 
This stems from their origin, though the operators are as general as
netCDF itself.

@html
<a name="ntr"></a> <!-- http://nco.sf.net/nco.html#ntr -->
@end html
@node Introduction, Strategies, Summary, Top
@chapter Introduction
@cindex introduction

@menu
* Availability::
* How to Use This guide::
* Compatability::
* Symbolic Links::
* Libraries::
* netCDF2/3/4 and HDF4/5 Support::
* Help Requests and Bug Reports::
@end menu

@node Availability, How to Use This guide, Introduction, Introduction
@section Availability
@cindex @acronym{NCO} availability
@cindex source code
The complete @acronym{NCO} source distribution is currently distributed
as a @dfn{compressed tarfile} from
@uref{http://sf.net/projects/nco}
and from
@uref{http://dust.ess.uci.edu/nco/nco.tar.gz}.
The compressed tarfile must be uncompressed and untarred before building
@acronym{NCO}.
Uncompress the file with @samp{gunzip nco.tar.gz}. 
Extract the source files from the resulting tarfile with @samp{tar -xvf
nco.tar}.    
@acronym{GNU} @code{tar} lets you perform both operations in one step
with @samp{tar -xvzf nco.tar.gz}. 

@cindex documentation 
@cindex WWW documentation
@cindex on-line documentation
@cindex @acronym{HTML}
@cindex @TeX{}info
@cindex Info
@cindex @cite{User Guide}
@cindex @cite{NCO User Guide}
The documentation for @acronym{NCO} is called the 
@cite{NCO User Guide}. 
The @cite{User Guide} is available in @acronym{PDF}, Postscript,
@acronym{HTML}, @acronym{DVI}, @TeX{}info, and Info formats.
These formats are included in the source distribution in the files
@file{nco.pdf}, @file{nco.ps}, @file{nco.html}, @file{nco.dvi},
@file{nco.texi}, and @file{nco.info*}, respectively.
All the documentation descends from a single source file,
@file{nco.texi}
@footnote{   
To produce these formats, @file{nco.texi} was simply run through the
freely available programs @code{texi2dvi}, @code{dvips},
@code{texi2html}, and @code{makeinfo}.    
Due to a bug in @TeX{}, the resulting Postscript file, @file{nco.ps},
contains the Table of Contents as the final pages. 
Thus if you print @file{nco.ps}, remember to insert the Table of
Contents after the cover sheet before you staple the manual.
}.
Hence the documentation in every format is very similar.
However, some of the complex mathematical expressions needed to describe
@command{ncwa} can only be displayed in @acronym{DVI}, Postscript, and 
@acronym{PDF} formats. 

@cindex publications
@cindex presentations
A complete list of papers and publications on/about @acronym{NCO} 
is available on the @acronym{NCO} homepage.
Most of these are freely available. 
@c 20130526 fxm Replace mybibnode with @mybibnode{}
@c 20130526 Doing so, unfortunately, produces error "TeX capacity exceeded, sorry [input stack size=5000]."
@c 20130526 Denude document of @mybibcite{} until it works
@c The primary refereed publications are @mybibcite{ZeM06} and @mybibcite{Zen08}. 
The primary refereed publications are ZeM06 and Zen08. 
These contain copyright restrictions which limit their redistribution,
but they are freely available in preprint form from the @acronym{NCO}.

@cindex @acronym{NCO} homepage
If you want to quickly see what the latest improvements in @acronym{NCO}
are (without downloading the entire source distribution), visit the
@acronym{NCO} homepage at 
@uref{http://nco.sf.net}.
The @acronym{HTML} version of the @cite{User Guide} is also available 
online through the World Wide Web at @acronym{URL}
@uref{http://nco.sf.net/nco.html}.
@cindex netCDF
To build and use @acronym{NCO}, you must have netCDF installed.
The netCDF homepage is
@uref{http://www.unidata.ucar.edu/packages/netcdf}.

New @acronym{NCO} releases are announced on the netCDF list 
and on the @code{nco-announce} mailing list 
@uref{http://lists.sf.net/mailman/listinfo/nco-announce}.

@ignore
This tests incorporates an image using the @code{@@image} command.
@image{/data/zender/ps/odxc,6in,}
@end ignore

@node How to Use This guide, Compatability, Availability, Introduction
@section How to Use This Guide
@cindex contents
@cindex introduction
Detailed instructions about
@uref{http://nco.sf.net/#Source, how to download the newest version}, 
and @uref{http://nco.sf.net/#bld, how to complie source code},
as well as a @uref{http://nco.sf.net/#FAQ, @acronym{FAQ}} and 
descriptions of @uref{http://nco.sf.net/#bug, Known Problems} etc.
are on our homepage 
(@uref{http://nco.sf.net/}).

There are twelve operators in the current version (@value{nco-edition}).
The function of each is explained in @ref{Operator Reference Manual, Operator Reference Manual}.
Many of the tasks that @acronym{NCO} can accomplish are described during
the explanation of common @acronym{NCO} Features (@pxref{Common features}).
More specific use examples for each operator can be seen by visiting the
operator-specific examples in the @ref{Operator Reference Manual}.
These can be found directly by prepending the operator name with the
@code{xmp_} tag, e.g., @uref{http://nco.sf.net/nco.html#xmp_ncks}.
Also, users can type the operator name on the shell command line to 
see all the available options, or type, e.g., @samp{man ncks} to see
a help man-page.

@acronym{NCO} is a command-line language.
You can either use an operator after the prompt (e.g., @samp{$} here),
like, 
@example
$ @command{operator} @option{[options]} @file{input} @file{[output]}
@end example
or write all commands lines into a shell script, as in
the @acronym{CMIP5} Example (@pxref{CMIP5 Example}).

If you are new to @acronym{NCO}, the Quick Start (@pxref{Quick Start})
shows simple examples about how to use @acronym{NCO} on different kinds
of data files.  
More detailed ``real-world'' examples are in the
@ref{CMIP5 Example, @acronym{CMIP5} Example}. 
The @ref{General Index, Index} is presents multiple keyword entries for
the same subject. 
If these resources do not help enough, please 
@pxref{Help Requests and Bug Reports}.

@node Compatability, Symbolic Links, How to Use This guide, Introduction
@section Operating systems compatible with @acronym{NCO}
@cindex @acronym{OS}
@cindex @acronym{IBM}
@cindex @acronym{NEC}
@cindex @acronym{SGI}
@cindex @acronym{HP}
@cindex @acronym{DEC}
@cindex @acronym{PGI}
@cindex Cray
@cindex Digital
@cindex Sun
@cindex Intel
@cindex Comeau
@cindex Compaq
@cindex Macintosh
@cindex Microsoft
@cindex Windows
@cindex PathScale
@cindex QLogic
@cindex compatability
@cindex portability
@cindex installation
@acronym{NCO} has been successfully ported and tested and is known to
work on the following 32- and 64-bit platforms:  
@c alphabetize by OS name
@acronym{IBM AIX} 4.x, 5.x,
FreeBSD 4.x, 
@acronym{GNU}/Linux 2.x, LinuxPPC, LinuxAlpha, LinuxARM, LinuxSparc64,
@acronym{SGI IRIX} 5.x and 6.x,
@w{MacOS X} 10.x, 
@acronym{NEC} Super-UX 10.x, 
@acronym{DEC OSF}, 
Sun SunOS 4.1.x, Solaris 2.x, 
@acronym{Cray UNICOS} 8.x--10.x,
and MS Windows95 and all later versions.
If you port the code to a new operating system, please send me a note 
and any patches you required.

@cindex @acronym{UNIX}
@cindex Unidata
@cindex UDUnits
The major prerequisite for installing @acronym{NCO} on a particular
platform is the successful, prior installation of the netCDF library
(and, as of 2003, the UDUnits library).
Unidata has shown a commitment to maintaining netCDF and UDUnits on all
popular @acronym{UNIX} platforms, and is moving towards full support for 
the Microsoft Windows operating system (@acronym{OS}).
Given this, the only difficulty in implementing @acronym{NCO} on a
particular platform is standardization of various @w{C}-language API
system calls. 
@acronym{NCO} code is tested for @acronym{ANSI} compliance by
compiling with @w{C99 compilers} including those from 
@cindex @command{CC}
@cindex @command{c++}
@cindex @command{cc}
@cindex @command{clang}
@cindex @command{como}
@cindex @command{cxx}
@cindex @command{gcc}
@cindex @command{g++}
@cindex @command{icc}
@cindex @command{MVS}
@cindex @command{pgcc}
@cindex @command{pgCC}
@cindex @command{pathcc}
@cindex @command{pathCC}
@cindex @command{xlC}
@cindex @command{xlc}
@acronym{GNU} (@samp{gcc -std=c99 -pedantic -D_BSD_SOURCE -D_POSIX_SOURCE} -Wall)
@footnote{
The @samp{_BSD_SOURCE} token is required on some Linux platforms where 
@command{gcc} dislikes the network header files like
@file{netinet/in.h}).},
Comeau Computing (@samp{como --c99}),
Cray (@samp{cc}),
@acronym{HP}/Compaq/@acronym{DEC} (@samp{cc}),
@acronym{IBM} (@samp{xlc -c -qlanglvl=extc99}),
Intel (@samp{icc -std=c99}),
@cindex @acronym{LLVM}
@acronym{LLVM} (@samp{clang}),
@acronym{NEC} (@samp{cc}),
PathScale (QLogic) (@samp{pathcc -std=c99}),
@acronym{PGI} (@samp{pgcc -c9x}),
@acronym{SGI} (@samp{cc -c99}),
and
Sun (@samp{cc}).
@cindex C++
@cindex @acronym{ISO}
@cindex @command{libnco}
@acronym{NCO} (all commands and the @command{libnco} library) and
the C++ interface to netCDF (called @command{libnco_c++}) comply with
the @acronym{ISO} C++ standards as implemented by
Comeau Computing (@samp{como}),
Cray (@samp{CC}),
@acronym{GNU} (@samp{g++ -Wall}),
@acronym{HP}/Compaq/@acronym{DEC} (@samp{cxx}),
@acronym{IBM} (@samp{xlC}),
Intel (@samp{icc}),
Microsoft (@samp{MVS}),
@acronym{NEC} (@samp{c++}),
PathScale (Qlogic) (@samp{pathCC}),
@acronym{PGI} (@samp{pgCC}),
@acronym{SGI} (@samp{CC -LANG:std}),
and
Sun (@samp{CC -LANG:std}).
@cindex @file{Makefile}
See @file{nco/bld/Makefile} and @file{nco/src/nco_c++/Makefile.old} for
more details and exact settings. 

@cindex @acronym{ANSI}
@cindex C89
@cindex @code{printf} 
Until recently (and not even yet), @acronym{ANSI}-compliant has meant
compliance with the 1989 @acronym{ISO} C-standard, usually called C89 (with
minor revisions made in 1994 and 1995).
C89 lacks variable-size arrays, restricted pointers, some useful
@code{printf} formats, and many mathematical special functions.
@cindex C99
These are valuable features of C99, the 1999 @acronym{ISO} C-standard. 
@acronym{NCO} is C99-compliant where possible and C89-compliant where
necessary. 
Certain branches in the code are required to satisfy the native
@acronym{SGI} and SunOS @w{C compilers}, which are strictly @acronym{ANSI} 
C89 compliant, and cannot benefit from C99 features.
However, C99 features are fully supported by modern @acronym{AIX},
@acronym{GNU}, Intel, @acronym{NEC}, Solaris, and @acronym{UNICOS}
compilers. 
@acronym{NCO} requires a C99-compliant compiler as of @acronym{NCO}
@w{version 2.9.8}, released in August, 2004.

The most time-intensive portion of @acronym{NCO} execution is spent in
arithmetic operations, e.g., multiplication, averaging, subtraction.
These operations were performed in Fortran by default until August,
1999.  
This was a design decision based on the relative speed of Fortran-based
object code vs.@: C-based object code in late 1994.
@w{C compiler} vectorization capabilities have dramatically improved 
since 1994.
We have accordingly replaced all Fortran subroutines with @w{C functions}.
This greatly simplifies the task of building @acronym{NCO} on nominally
unsupported platforms.  
@cindex C language
As of August 1999, @acronym{NCO} built entirely @w{in C} by default.
This allowed @acronym{NCO} to compile on any machine with an
@acronym{ANSI} @w{C compiler}. 
@cindex C99
@cindex C89
@cindex @code{restrict}
In August 2004, the first C99 feature, the @code{restrict} type
qualifier, entered @acronym{NCO} in version 2.9.8. 
@w{C compilers} can obtain better performance with C99 restricted 
pointers since they inform the compiler when it may make Fortran-like
assumptions regarding pointer contents alteration.
Subsequently, @acronym{NCO} requires a C99 compiler to build correctly
@footnote{@acronym{NCO} may still build with an 
@acronym{ANSI} or @acronym{ISO} C89 or C94/95-compliant compiler if the
@w{C pre-processor} undefines the @code{restrict} type qualifier, e.g.,
by invoking the compiler with @samp{-Drestrict=''}.}.

@cindex @acronym{GSL}
@findex ncap2
In January 2009, @acronym{NCO} version 3.9.6 was the first to link
to the GNU Scientific Library (@acronym{GSL}).
@acronym{GSL} must be @w{version 1.4} or later. 
@acronym{NCO}, in particular @command{ncap2}, uses the @acronym{GSL}
special function library to evaluate geoscience-relevant mathematics
such as Bessel functions, Legendre polynomials, and incomplete gamma
functions (@pxref{GSL special functions}).
 
@cindex @var{gamma}
In June 2005, @acronym{NCO} version 3.0.1 began to take advantage
of C99 mathematical special functions.
These include the standarized gamma function (called @code{tgamma()} 
for ``true gamma''). 
@cindex automagic
@acronym{NCO} automagically takes advantage of some @acronym{GNU}
Compiler Collection (@acronym{GCC}) extensions to @w{@acronym{ANSI} C}.

As of July 2000 and @acronym{NCO} @w{version 1.2}, @acronym{NCO} no
longer performs arithmetic operations in Fortran.
We decided to sacrifice executable speed for code maintainability.
Since no objective statistics were ever performed to quantify 
the difference in speed between the Fortran and @w{C code},
the performance penalty incurred by this decision is unknown.
Supporting Fortran involves maintaining two sets of routines for every
arithmetic operation. 
The @code{USE_FORTRAN_ARITHMETIC} flag is still retained in the
@file{Makefile}.
The file containing the Fortran code, @file{nco_fortran.F}, has been
deprecated but a volunteer (@w{Dr.@: Frankenstein}?) could resurrect it.
If you would like to volunteer to maintain @file{nco_fortran.F} please 
contact me. 

@c Following section is obsolete
@ignore
It is still possible to request Fortran routines to perform arithmetic
operations, however.
@cindex preprocessor tokens
@cindex @code{USE_FORTRAN_ARITHMETIC}
This can be accomplished by defining the preprocessor token
@code{USE_FORTRAN_ARITHMETIC} and rebuilding @acronym{NCO}.
@cindex performance
As its name suggests, the @code{USE_FORTRAN_ARITHMETIC} token instructs
@acronym{NCO} to attempts to interface the @w{C routines} with Fortran
arithmetic. 
Although using Fortran calls instead @w{of C} reduces the portability and
and increases the maintenance of the @acronym{NCO} operators, it may
also increase the performance of the numeric operators.
Presumably this will depend on your machine type, the quality of @w{the C}
and Fortran compilers, and the size of the data files
@footnote{If you decide to test the efficiency of the averagers compiled
with @code{USE_FORTRAN_ARITHMETIC} versus the default @w{C averagers} I
would be most interested to hear the results.
Please E-mail me the results including the size of the datasets, the
platform, and the change in the wallclock time for execution.}.
@end ignore

@menu
* Windows Operating System::
@end menu

@html
<a name="wnd"></a> <!-- http://nco.sf.net/nco.html#wnd -->
<a name="windows"></a> <!-- http://nco.sf.net/nco.html#windows -->
<a name="qt"></a> <!-- http://nco.sf.net/nco.html#qt -->
@end html
@node Windows Operating System,  , Compatability, Compatability
@subsection Compiling @acronym{NCO} for Microsoft Windows @acronym{OS}
@cindex Windows
@cindex Microsoft
@cindex XP (Microsoft operating system)
@cindex NT (Microsoft operating system)
@cindex Vista (Microsoft operating system)
@cindex @acronym{MVS}
@cindex Microsoft Visual Studio

@acronym{NCO} has been successfully ported and tested on most Microsoft  
Windows operating systems including: XP SP2/Vista/7.
Support is provided for compiling either native Windows executables,
using the Microsoft Visual Studio 2010 Compiler, or with Cygwin, the
UNIX-emulating compatibility layer with the GNU toolchain.
The switches necessary to accomplish both are included in the standard
distribution of @acronym{NCO}.

@cindex Qt
@cindex C99
Using Microsoft Visual Studio (@acronym{MVS}), one must build
@acronym{NCO} with the C++ compiler since MVS does not support C99.
Qt, a convenient integrated development environment, was used to convert
the project files to @acronym{MVS} format.
The Qt files themselves are distributed in the @file{nco/qt} directory.

Using the freely available Cygwin (formerly gnu-win32) development
environment  
@footnote{The Cygwin package is available from@*
@code{http://sourceware.redhat.com/cygwin}@*
@cindex @code{gcc}
@cindex @code{g++}
Currently, @w{Cygwin 20.x} comes with the @acronym{GNU} C/C++
compilers (@command{gcc}, @command{g++}.
These @acronym{GNU} compilers may be used to build the netCDF
distribution itself.}, the compilation process is very similar to
installing @acronym{NCO} on a @acronym{UNIX} system.  
@cindex preprocessor tokens
@cindex Cygwin
@cindex @code{gnu-win32}
@cindex @code{WIN32}
@cindex @file{GNUmakefile}
@cindex @file{Makefile}
@cindex @code{f90}
Set the @code{PVM_ARCH} preprocessor token to @code{WIN32}.  
Note that defining @code{WIN32} has the side effect of disabling
Internet features of @acronym{NCO} (see below). 
@acronym{NCO} should now build like it does on @acronym{UNIX}.

@cindex @acronym{UNIX}
@cindex @code{getuid}
@cindex @code{gethostname}
@findex @file{<arpa/nameser.h>}
@findex @file{<resolv.h>}
The least portable section of the code is the use of standard
@acronym{UNIX} and Internet protocols (e.g., @code{ftp}, @code{rcp},
@code{scp}, @code{sftp}, @code{getuid}, @code{gethostname}, and header
files @file{<arpa/nameser.h>} and 
@file{<resolv.h>}). 
@cindex @code{ftp}
@cindex @code{sftp}
@cindex @code{rcp}
@cindex @code{scp}
@cindex @acronym{SSH}
@cindex remote files
Fortunately, these @acronym{UNIX}-y calls are only invoked by the single  
@acronym{NCO} subroutine which is responsible for retrieving files
stored on remote systems (@pxref{Remote storage}).
In order to support @acronym{NCO} on the Microsoft Windows platforms,
this single feature was disabled (on Windows @acronym{OS} only).
This was required by @w{Cygwin 18.x}---newer versions of Cygwin may
support these protocols (let me know if this is the case).
The @acronym{NCO} operators should behave identically on Windows and
@acronym{UNIX} platforms in all other respects.

@html
<a name="sym"></a> <!-- http://nco.sf.net/nco.html#sym -->
@end html
@node Symbolic Links, Libraries, Compatability, Introduction
@section Symbolic Links
@cindex symbolic links
@acronym{NCO} relies on a common set of underlying algorithms.
To minimize duplication of source code, multiple operators sometimes
share the same underlying source.
This is accomplished by symbolic links from a single underlying
executable program to one or more invoked executable names.
For example, @command{nces} and @command{ncrcat} are symbolically linked  
to the @command{ncra} executable.
The @command{ncra} executable behaves slightly differently based on its
invocation name (i.e., @samp{argv[0]}), which can be 
@command{nces}, @command{ncra}, or @command{ncrcat}.
Logically, these are three different operators that happen to share 
the same executable.

@cindex Cygwin
@cindex synonym
@cindex pseudonym
@cindex @code{--pseudonym}
For historical reasons, and to be more user friendly, multiple synonyms 
(or pseudonyms) may refer to the same operator invoked with different
switches. 
For example, @command{ncdiff} is the same as @command{ncbo} and
@command{ncpack} is the same as @command{ncpdq}.
We implement the symbolic links and synonyms by the executing the
following @acronym{UNIX} commands in the directory where the
@acronym{NCO} executables are installed.
@example
ln -s -f ncbo ncdiff    # ncbo --op_typ='+'
ln -s -f ncra ncecat    # ncra --pseudonym='ncecat'
ln -s -f ncra ncrcat    # ncra --pseudonym='ncrcat'
ln -s -f ncbo ncadd     # ncbo --op_typ='+'
ln -s -f ncbo ncsubtract # ncbo --op_typ='-'
ln -s -f ncbo ncmultiply # ncbo --op_typ='*'
ln -s -f ncbo ncdivide   # ncbo --op_typ='/'
ln -s -f ncpdq ncpack    # ncpdq
ln -s -f ncpdq ncunpack  # ncpdq --unpack
# NB: Cygwin executable (and link) names have an '.exe' suffix, e.g.,
ln -s -f ncbo.exe ncdiff.exe
...
@end example
The imputed command called by the link is given after the comment.
As can be seen, some these links impute the passing of a command line
argument to further modify the behavior of the underlying executable.
For example, @command{ncdivide} is a pseudonym for
@command{ncbo --op_typ='/'}.

@html
<a name="lbr"></a> <!-- http://nco.sf.net/nco.html#lbr -->
@end html
@node Libraries, netCDF2/3/4 and HDF4/5 Support, Symbolic Links, Introduction
@section Libraries
@cindex libraries
@cindex @code{LD_LIBRARY_PATH}
@cindex dynamic linking
@cindex static linking
Like all executables, the @acronym{NCO} operators can be built using dynamic
linking. 
@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
This reduces the size of the executable and can result in significant
performance enhancements on multiuser systems.
Unfortunately, if your library search path (usually the
@env{LD_LIBRARY_PATH} environment variable) is not set correctly, or if
the system libraries have been moved, renamed, or deleted since
@acronym{NCO} was installed, it is possible @acronym{NCO} operators
will fail with a message that they cannot find a dynamically loaded (aka
@dfn{shared object} or @samp{.so}) library. 
This will produce a distinctive error message, such as
@samp{ld.so.1:@- /usr/local/bin/nces:@- fatal:@- libsunmath.@-so.1:@- can't
open@- file:@- errno@-=2}.   
If you received an error message like this, ask your system 
administrator to diagnose whether the library is truly missing
@footnote{The @command{ldd} command, if it is available on your system,
will tell you where the executable is looking for each dynamically
loaded library. Use, e.g., @code{ldd `which nces`}.}, or whether you
simply need to alter your library search path.
As a final remedy, you may re-compile and install @acronym{NCO} with all
operators statically linked.  

@node netCDF2/3/4 and HDF4/5 Support, Help Requests and Bug Reports, Libraries, Introduction
@section netCDF2/3/4 and HDF4/5 Support
@cindex netCDF2
@cindex netCDF3
netCDF @w{version 2} was released in 1993.
@acronym{NCO} (specifically @command{ncks}) began soon after this in 1994.  
@w{netCDF 3.0} was released in 1996, and we were not exactly eager to 
convert all code to the newer, less tested netCDF implementation.
One @w{netCDF3} interface call (@code{nc_inq_libvers}) was added to 
@acronym{NCO} in January, 1998, to aid in maintainance and debugging. 
In March, 2001, the final @acronym{NCO} conversion to @w{netCDF3} 
was completed (coincidentally on the same day @w{netCDF 3.5} was
released). 
@acronym{NCO} @w{versions 2.0} and higher are built with the
@code{-DNO_NETCDF_2} flag to ensure no @w{netCDF2} interface calls   
are used.
@cindex @code{NO_NETCDF_2}

@cindex @acronym{HDF}
@cindex Hierarchical Data Format
@cindex Mike Folk
However, the ability to compile @acronym{NCO} with only @w{netCDF2}
calls is worth maintaining because @acronym{HDF} @w{version 4}, 
aka @acronym{HDF4} or simply @acronym{HDF}, 
@footnote{The Hierarchical Data Format, or @acronym{HDF}, is another
self-describing data format similar to, but more elaborate than,
netCDF. 
@acronym{HDF} comes in two flavors, @acronym{HDF4} and @acronym{HDF5}. 
Often people use the shorthand @acronym{HDF} to refer to the older
format @acronym{HDF4}.
People almost always use @acronym{HDF5} to refer to @acronym{HDF5}.} 
(available from @uref{http://hdfgroup.org, HDF})
supports only the @w{netCDF2} library calls
(see @uref{http://hdfgroup.org/UG41r3_html/SDS_SD.fm12.html#47784}).
There are two versions of @acronym{HDF}.
Currently @acronym{HDF} @w{version 4.x} supports the full @w{netCDF2}
@acronym{API} and thus @acronym{NCO} @w{version 1.2.x}. 
If @acronym{NCO} @w{version 1.2.x} (or earlier) is built with only
@w{netCDF2} calls then all @acronym{NCO} operators should work with 
@acronym{HDF4} files as well as netCDF files
@footnote{One must link the @acronym{NCO} code to the @acronym{HDF4}
@acronym{MFHDF} library instead of the usual netCDF library. 
Apparently @samp{MF} stands for Multi-file not for Mike Folk.
In any case, until about 2007 the @acronym{MFHDF} library only supported 
@w{netCDF2} calls. 
Most people will never again install @acronym{NCO} 1.2.x and so will
never use @acronym{NCO} to write @acronym{HDF4} files.
It is simply too much trouble.}.
@cindex @code{NETCDF2_ONLY}
The preprocessor token @code{NETCDF2_ONLY} exists
in @acronym{NCO} @w{version 1.2.x} to eliminate all @w{netCDF3}
calls.  
Only versions of @acronym{NCO} numbered 1.2.x and earlier have this
capability. 

@cindex Unidata
@cindex @acronym{NCSA}
@cindex netCDF4
@cindex @acronym{HDF5}
@acronym{HDF} @w{version 5} became available in 1999, but did not
support netCDF (or, for that matter, Fortran) as of December 1999.
By early 2001, @acronym{HDF5} did support Fortran90.
Thanks to an @acronym{NSF}-funded ``harmonization'' partnership,
@acronym{HDF} began to fully support the @w{netCDF3} read interface
(which is employed by @w{@acronym{NCO} 2.x} and later). 
In 2004, Unidata and @acronym{THG} began a project to implement
the @acronym{HDF5} features necessary to support the netCDF API.
@acronym{NCO} version 3.0.3 added support for reading/writing
netCDF4-formatted @acronym{HDF5} files in October, 2005.
See @ref{File Formats and Conversion} for more details.

HDF support for netCDF was completed with HDF5 version 
@w{version 1.8} in 2007. 
The netCDF front-end that uses this @acronym{HDF5} back-end 
was completed and released soon after as netCDF @w{version 4}.
Download it from the
@uref{http://my.unidata.ucar.edu/content/software/netcdf/netcdf-4,netCDF4}
website. 

@html
<a name="nco4"></a> <!-- http://nco.sf.net/nco.html#nco4 -->
@end html
@acronym{NCO} version 3.9.0, released in May, 2007, added support for
all netCDF4 atomic data types except @code{NC_STRING}.
Support for @code{NC_STRING}, including ragged arrays of strings,
was finally added in version 3.9.9, released in June, 2009.
Support for additional netCDF4 features has been incremental.
We add one netCDF4 feature at a time.
You must build @acronym{NCO} with netCDF4 to obtain this support.

@cindex @code{NC_UBYTE}
@cindex @code{NC_USHORT}
@cindex @code{NC_UINT}
@cindex @code{NC_INT64}
@cindex @code{NC_UINT64}
The main netCDF4 features that NCO currently supports are the new 
atomic data types, Lempel-Ziv compression (deflation), and chunking. 
The new atomic data types are @code{NC_UBYTE}, @code{NC_USHORT}, 
@code{NC_UINT}, @code{NC_INT64}, and @code{NC_UINT64}.
Eight-byte integer support is an especially useful improvement from
netCDF3. 
All @acronym{NCO} operators support these types, e.g., @command{ncks}
copies and prints them, @command{ncra} averages them, and
@command{ncap2} processes algebraic scripts with them.
@command{ncks} prints compression information, if any, to screen.

@cindex deflation
@acronym{NCO} version 3.9.1 (June, 2007) added support for netCDF4 
Lempel-Ziv deflation.
Lempel-Ziv deflation is a lossless compression technique.
See @ref{Deflation} for more details.

@cindex chunking
@acronym{NCO} version 3.9.9 (June, 2009) added support for netCDF4
chunking in @command{ncks} and @command{ncecat}.
@acronym{NCO} version 4.0.4 (September, 2010) completed support for
netCDF4 chunking in the remaining operators.
See @ref{Chunking} for more details.

@cindex groups
@acronym{NCO} version 4.2.2 (October, 2012) added support for netCDF4
groups in @command{ncks} and @command{ncecat}.
Group support for these operators was complete (e.g., regular
expressions to select groups and Group Path Editing) as of 
@acronym{NCO} version 4.2.6 (March, 2013).
See @ref{Group Path Editing} for more details.
Group support for all other operators was finished in the
@acronym{NCO} version 4.3.x series completed in December, 2013.

@cindex broadcasting groups
Support for netCDF4 in the first arithmetic operator, @command{ncbo},
was introduced in @acronym{NCO} version 4.3.0 (March, 2013).
@acronym{NCO} version 4.3.1 (May, 2013) completed this support and
introduced the first example of automatic group broadcasting.
See @ref{ncbo netCDF Binary Operator} for more details.

@cindex @acronym{HDF5}
@cindex @code{-4}
@cindex @code{-3}
netCDF4-enabled @acronym{NCO} handles netCDF3 files without change.
In addition, it automagically handles netCDF4 (@acronym{HDF5}) files:
If you feed @acronym{NCO} netCDF3 files, it produces netCDF3 output.
If you feed @acronym{NCO} netCDF4 files, it produces netCDF4 output.
Use the handy-dandy @samp{-4} switch to request netCDF4 output from 
netCDF3 input, i.e., to convert netCDF3 to netCDF4.
See @ref{File Formats and Conversion} for more details.

@html
<a name="hdf4"></a> <!-- http://nco.sf.net/nco.html#hdf4 -->
<a name="HDF4"></a> <!-- http://nco.sf.net/nco.html#HDF4 -->
@end html
@cindex @acronym{HDF4}
@cindex @samp{--hdf4}
When linked to a netCDF library that was built with @acronym{HDF4}
support
@footnote{The procedure for doing this is documented at
@uref{http://www.unidata.ucar.edu/software/netcdf/docs/build_hdf4.html}.},
@acronym{NCO} automatically supports reading @acronym{HDF4} 
files and writing them as netCDF3/netCDF4/@acronym{HDF5} files.
@acronym{NCO} can only write through the netCDF @acronym{API}, which
can only write netCDF3/netCDF4/@acronym{HDF5} files. 
So @acronym{NCO} can @emph{read} @acronym{HDF4} files, perform
manipulations and calculations, and then @emph{write} the results in
netCDF format. 

Full support for these features is forthcoming, yet support as of
December, 2013 is quite functional.
For best results install @acronym{NCO} versions 4.4.0 or later on top of
netCDF versions 4.3.1 or later. 
Getting to this point has been an iterative effort where Unidata
improved netCDF library capabilities in response to our requests.
@acronym{NCO} versions 4.3.6 and earlier do not explicitly support
@acronym{HDF4}, yet should work with @acronym{HDF4} if compiled with 
a version of netCDF (4.3.2 or later?) that does not unexpectedly die
when probing @acronym{HDF4} files with standard netCDF calls.
@acronym{NCO} versions 4.3.7--4.3.9 (October--December, 2013)
use a special flag to workaround netCDF @acronym{HDF4} issues.
The user must tell these versions of @acronym{NCO} that an input file is
@acronym{HDF4} format by using the @samp{--hdf4} switch. 

When compiled with netCDF version 4.3.1 (20140116) or later, 
@acronym{NCO} versions 4.4.0 (January, 2014) and later more gracefully 
handle @acronym{HDF4} files.
In particular, the @samp{--hdf4} switch is obsolete. 
Current versions of @acronym{NCO} use netCDF to determine automatically
whether the underlying file is @acronym{HDF4}, and then take appropriate
precautions to avoid calls not yet supported by the netCDF4 subset
@acronym{HDF4}. 
The @samp{--hdf4} switch is supported (for backwards compatibility) yet
redundant (i.e., does no harm) with current versions of @acronym{NCO}
and netCDF. 

Converting @acronym{HDF4} files to netCDF:
Since @acronym{NCO} reads @acronym{HDF4} files natively, it is now easy  
to convert @acronym{HDF4} files to netCDF files directly, e.g.,
@example
ncks        fl.hdf fl.nc # Convert HDF4->netCDF4 (NCO 4.4.0+, netCDF 4.3.1+)
ncks --hdf4 fl.hdf fl.nc # Convert HDF4->netCDF4 (NCO 4.3.7-4.3.9)
@end example
The most efficient and accurate way to convert @acronym{HDF4} data to
netCDF format is to convert to netCDF4 using @acronym{NCO} as above.
It suffices when the data will only be processed by @acronym{NCO}, or
other netCDF4-aware tools. 
However, many tools are not fully netCDF4-aware, and so conversion to
netCDF3 may be desirable.

Obtaining a netCDF3 file from an @acronym{HDF4} is now easy, even though
the @acronym{HDF4} file may contain netCDF4 atomic types (e.g., unsigned
bytes, 64-bit integers): 
@example
ncks -3 fl.hdf fl.nc      # HDF4->netCDF3 (NCO 4.4.0+, netCDF 4.3.1+)
ncks -7 -L 1 fl.hdf fl.nc # HDF4->netCDF4 (NCO 4.4.0+, netCDF 4.3.1+)
ncks --hdf4 -3 fl.hdf fl.nc # HDF4->netCDF3 (netCDF 4.3.0-)
ncks --hdf4 -7 fl.hdf fl.nc # HDF4->netCDF4 classic (netCDF 4.3.0-)
@end example
As of @acronym{NCO} version 4.4.0 (January, 2014), these commands work
with netCDF4 atomic types
@footnote{
Prior to @acronym{NCO} version 4.4.0 (January, 2014), we recommend the
@command{ncl_convert2nc} tool to convert @acronym{HDF} to netCDF3 when
both these are true: @w{1. You} must have netCDF3 and @w{2. the}
@acronym{HDF} file contains netCDF4 atomic types. 
More recent versions of @acronym{NCO} handle this problem fine, so we
no longer recommend @command{ncl_convert2nc} because @command{ncks}
is faster and more space-efficient.
Both automatically convert netCDF4 types to netCDF3 types, yet
@command{ncl_convert2nc} cannot produce full netCDF4 files.
In contrast, @command{ncks} will happily convert @acronym{HDF} straight
to netCDF4 files with netCDF4 types. 
Hence @command{ncks} can and does preserve the variable types.
Unsigned bytes stay unsigned bytes. 
64-bit integers stay 64-bit integers. 
Strings stay strings. 
Hence, @command{ncks} conversions often result in smaller files than
@command{ncl_convert2nc} conversions.}.  
Many @acronym{HDF4} producers (@acronym{NASA}!) love to use netCDF4
types, e.g., unsigned bytes. 

@cindex @acronym{RPM}
@cindex Debian
As of 2012, netCDF4 is relatively stable software.
Problems with netCDF4 and @acronym{HDF} libraries have mainly been fixed.
Binary @acronym{NCO} distributions shipped as @acronym{RPM}s and as debs
have used the netCDF4 library since 2010 and 2011, respectively.

@cindex @code{NETCDF4_ROOT}
One must often build @acronym{NCO} from source to obtain netCDF4
support. 
Typically, one specifies the root of the netCDF4
installation directory. Do this with the @code{NETCDF4_ROOT} variable.
Then use your preferred @acronym{NCO} build mechanism, e.g.,
@example
export NETCDF4_ROOT=/usr/local/netcdf4 # Set netCDF4 location
cd ~/nco;./configure --enable-netcdf4  # Configure mechanism -or-
cd ~/nco/bld;./make NETCDF4=Y allinone # Old Makefile mechanism
@end example

We carefully track the netCDF4 releases, and keep the netCDF4 atomic
type support and other features working.
Our long term goal is to utilize more of the extensive new netCDF4
feature set. The next major netCDF4 feature we are likely to utilize
is parallel I/O. We will enable this in the @acronym{MPI} netCDF
operators. 

@html
<a name="help"></a> <!-- http://nco.sf.net/nco.html#help -->
<a name="hlp"></a> <!-- http://nco.sf.net/nco.html#hlp -->
<a name="bug"></a> <!-- http://nco.sf.net/nco.html#bug -->
@end html
@node Help Requests and Bug Reports,  , netCDF2/3/4 and HDF4/5 Support, Introduction
@section Help Requests and Bug Reports
@cindex reporting bugs
@cindex bugs, reporting
@cindex core dump
@cindex help
@cindex features, requesting
We generally receive three categories of mail from users: help requests,
bug reports, and feature requests.
Notes saying the equivalent of "Hey, @acronym{NCO} continues to work
great and it saves me more time everyday than it took to write this
note" are a distant fourth.

There is a different protocol for each type of request.
The preferred etiquette for all communications is via @acronym{NCO}
Project Forums. 
Do not contact project members via personal e-mail unless your request
comes with money or you have damaging information about our personal
lives.
@emph{Please use the Forums}---they preserve a record of the questions
and answers so that others can learn from our exchange.
Also, since @acronym{NCO} is government-funded, this record helps us
provide program officers with information they need to evaluate our
project. 

Before posting to the @acronym{NCO} forums described below, you might
first @uref{https://sf.net/account/register.php, register}
your name and email address with SourceForge.net or else all of your
postings will be attributed to "nobody".
Once registered you may choose to "monitor" any forum and to receive
(or not) email when there are any postings including responses to your
questions.
We usually reply to the forum message, not to the original poster.

If you want us to include a new feature in @acronym{NCO}, check first to 
see if that feature is already on the @uref{file:./TODO,TODO} list.
If it is, why not implement that feature yourself and send us the patch?
If the feature is not yet on the list, then send a note to the
@uref{http://sf.net/projects/nco/forums/forum/9829, NCO Discussion forum}.

Read the manual before reporting a bug or posting a help request.
Sending questions whose answers are not in the manual is the best
way to motivate us to write more documentation.  
We would also like to accentuate the contrapositive of this statement.  
If you think you have found a real bug @emph{the most helpful thing you 
can do is simplify the problem to a manageable size and then report it}.
The first thing to do is to make sure you are running the latest
publicly released version of @acronym{NCO}.  

Once you have read the manual, if you are still unable to get
@acronym{NCO} to perform a documented function, submit a help request.
Follow the same procedure as described below for reporting bugs
(after all, it might be a bug).
@cindex debugging
@cindex @code{-r}
@cindex @code{-D}
That is, describe what you are trying to do, and include the complete
commands (run with @samp{-D 5}), error messages, and version of
@acronym{NCO} (with @samp{-r}).  
Post your help request to the 
@uref{http://sf.net/projects/nco/forums/forum/9830, NCO Help forum}.

If you think you used the right command when @acronym{NCO} misbehaves,
then you might have found a bug.  
Incorrect numerical answers are the highest priority.
We usually fix those within one or two days.
Core dumps and sementation violations receive lower priority.
They are always fixed, eventually. 

How do you simplify a problem that reveal a bug?
Cut out extraneous variables, dimensions, and metadata from the
offending files and re-run the command until it no longer breaks.  
Then back up one step and report the problem.
Usually the file(s) will be very small, i.e., one variable with one or
two small dimensions ought to suffice.
@html
<a name="dbg"></a> <!-- http://nco.sf.net/nco.html#dbg -->
<a name="-D"></a> <!-- http://nco.sf.net/nco.html#-D -->
@end html
@cindex @code{-r}
@cindex @code{--revision}
@cindex @code{--version}
@cindex @code{--vrs}
@cindex @code{-D @var{debug-level}}
@cindex @code{--debug-level @var{debug-level}}
@cindex @code{--dbg_lvl @var{debug-level}}
@cindex @var{debug-level}
@cindex @var{dbg_lvl}
Run the operator with @samp{-r} and then run the command with 
@samp{-D 5} to increase the verbosity of the debugging output.
It is very important that your report contain the exact error messages 
and compile-time environment.
Include a copy of your sample input file, or place one on a 
publically accessible location, of the file(s).
Post the full bug report to the 
@uref{http://sf.net/bugs/?group_id=3331, NCO Project buglist}.

@cindex installation
@cindex @command{autoconf}
@cindex @file{nco.configure.$@{GNU_TRP@}.foo}
@cindex @file{nco.config.log.$@{GNU_TRP@}.foo}
@cindex @file{nco.make.$@{GNU_TRP@}.foo}
@cindex @file{config.guess}
@cindex @file{configure.eg}
Build failures count as bugs.
Our limited machine access means we cannot fix all build failures.
The information we need to diagnose, and often fix, build failures
are the three files output by @acronym{GNU} build tools,  
@file{nco.config.log.$@{GNU_TRP@}.foo},
@file{nco.configure.$@{GNU_TRP@}.foo}, 
and @file{nco.make.$@{GNU_TRP@}.foo}.
The file @file{configure.eg} shows how to produce these files.
Here @code{$@{GNU_TRP@}} is the "@acronym{GNU} architecture triplet",
the @var{chip-vendor-OS} string returned by @file{config.guess}.
Please send us your improvements to the examples supplied in
@file{configure.eg}.
@cindex regressions archive
The regressions archive at @url{http://dust.ess.uci.edu/nco/rgr}
contains the build output from our standard test systems.
You may find you can solve the build problem yourself by examining the
differences between these files and your own.

@html
<a name="str"></a> <!-- http://nco.sf.net/nco.html#str -->
@end html
@node Strategies, Common features, Introduction, Top
@chapter Operator Strategies

@menu
* Philosophy::
* Climate Model Paradigm::
* Temporary Output Files::
* Appending Variables::
* Simple Arithmetic and Interpolation::
* Statistics vs. Concatenation::
* Large Numbers of Files::
* Large Datasets::
* Memory Requirements::
* Performance::
@end menu

@html
<a name="phl"></a> <!-- http://nco.sf.net/nco.html#phl -->
@end html
@node Philosophy, Climate Model Paradigm, Strategies, Strategies
@section Philosophy
@cindex philosophy
@cindex climate model

The main design goal is command line operators which perform useful,
scriptable operations on netCDF files.  
Many scientists work with models and observations which produce too much
data to analyze in tabular format.
Thus, it is often natural to reduce and massage this raw or primary
level data into summary, or second level data, e.g., temporal or spatial
averages. 
These second level data may become the inputs to graphical and
statistical packages, and are often more suitable for archival and
dissemination to the scientific community.
@acronym{NCO} performs a suite of operations useful in manipulating data
from the primary to the second level state.
@cindex @acronym{IDL}
@cindex Matlab
@cindex @acronym{NCL}
@cindex Perl
@cindex Yorick
Higher level interpretive languages (e.g., @acronym{IDL}, Yorick,
Matlab, @acronym{NCL}, Perl, Python),
and lower level compiled languages (e.g., C, Fortran) can always perform  
any task performed by @acronym{NCO}, but often with more overhead.
NCO, on the other hand, is limited to a much smaller set of arithmetic
and metadata operations than these full blown languages.

@cindex command line switches
Another goal has been to implement enough command line switches so that 
frequently used sequences of these operators can be executed from a
shell script or batch file.
Finally, @acronym{NCO} was written to consume the absolute minimum
amount of system memory required to perform a given job.
The arithmetic operators are extremely efficient; their exact memory
usage is detailed in @ref{Memory Requirements}.

@html
<a name="clm"></a> <!-- http://nco.sf.net/nco.html#clm -->
@end html
@node Climate Model Paradigm, Temporary Output Files, Philosophy, Strategies
@section Climate Model Paradigm
@cindex climate model
@cindex @acronym{NCAR}
@cindex @acronym{GCM}

@acronym{NCO} was developed at @acronym{NCAR} to aid analysis and
manipulation of datasets produced by General Circulation Models
(@acronym{GCM}s).  
@acronym{GCM} datasets share many features with other gridded scientific
datasets and so provide a useful paradigm for the explication of the
@acronym{NCO} operator set. 
Examples in this manual use a @acronym{GCM} paradigm because latitude,
longitude, time, temperature and other fields related to our natural
environment are as easy to visualize for the layman as the expert.

@html
<a name="out"></a> <!-- http://nco.sf.net/nco.html#out -->
@end html
@node Temporary Output Files, Appending Variables, Climate Model Paradigm, Strategies
@section Temporary Output Files 
@cindex data safety
@cindex error tolerance
@cindex safeguards
@cindex temporary output files
@cindex temporary files
@acronym{NCO} operators are designed to be reasonably fault tolerant, so
that a system failure or user-abort of the operation (e.g., with
@kbd{C-c}) does not cause loss of data.
The user-specified @var{output-file} is only created upon successful
completion of the operation  
@footnote{The @command{ncrename} and @command{ncatted} operators are
exceptions to this rule.
@xref{ncrename netCDF Renamer}.}.
This is accomplished by performing all operations in a temporary copy
of @var{output-file}.
The name of the temporary output file is constructed by appending
@code{.pid@var{<process ID>}.@var{<operator name>}.tmp} to the
user-specified @var{output-file} name.  
When the operator completes its task with no fatal errors, the temporary
output file is moved to the user-specified @var{output-file}.
This imbues the process with fault-tolerance since fatal error
(e.g., disk space fills up) affect only the temporary output file,
leaving the final output file not created if it did not already exist. 
Note the construction of a temporary output file uses more disk space
than just overwriting existing files ``in place'' (because there may be
two copies of the same file on disk until the @acronym{NCO} operation
successfully concludes and the temporary output file overwrites the
existing @var{output-file}).  
@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
Also, note this feature increases the execution time of the operator
by approximately the time it takes to copy the @var{output-file}
@footnote{The OS-specific system move command is used.
This is @command{mv} for UNIX, and @command{move} for Windows.}.
Finally, note this fault-tolerant feature allows the @var{output-file}
to be the same as the @var{input-file} without any danger of
``overlap''. 

@html
<a name="tmp_fl"></a> <!-- http://nco.sf.net/nco.html#tmp_fl -->
<a name="no_tmp_fl"></a> <!-- http://nco.sf.net/nco.html#no_tmp_fl -->
<a name="wrt_tmp_fl"></a> <!-- http://nco.sf.net/nco.html#wrt_tmp_fl -->
@end html
@cindex @code{--no_tmp_fl}
@cindex @code{--wrt_tmp_fl}
@cindex @code{--write_tmp_fl}
@cindex @code{--create_ram}
@cindex @code{--open_ram}
@cindex @acronym{RAM} disks
@cindex @acronym{RAM} files
Over time many ``power users'' have requested a way to turn-off the
fault-tolerance safety feature of automatically creating a temporary
file. 
Often these users build and execute production data analysis scripts
that are repeated frequently on large datasets.
Obviating an extra file write can then conserve significant disk space
and time.  
For this purpose @acronym{NCO} has, since version 4.2.1 in August, 2012, 
made configurable the controls over temporary file creation.
The @samp{--wrt_tmp_fl} and equivalent @samp{--write_tmp_fl} switches 
ensure @acronym{NCO} writes output to an intermediate temporary file.
This is and has always been the default behavior so there is currently
no need to specify these switches.
However, the default may change some day, especially since writing to
RAM disks (@pxref{RAM disks}) may some day become the default.
The @samp{--no_tmp_fl} switch causes @acronym{NCO} to write directly to
the final output file instead of to an intermediate temporary file. 
``Power users'' may wish to invoke this switch to increase performance
(i.e., reduce wallclock time) when manipulating large files. 
When eschewing temporary files, users may forsake the ability to have
the same name for both @var{output-file} and @var{input-file} since, as   
described above, the temporary file prevented overlap issues.
However, if the user creates the output file in @acronym{RAM} (@pxref{RAM disks})
then it is still possible to have the same name for both
@var{output-file} and @var{input-file}.
@example
ncks in.nc out.nc # Default: create out.pid.tmp.nc then move to out.nc
ncks --wrt_tmp_fl in.nc out.nc # Same as default
ncks --no_tmp_fl in.nc out.nc # Create out.nc directly on disk
ncks --no_tmp_fl in.nc in.nc # ERROR-prone! Overwrite in.nc with itself
ncks --create_ram --no_tmp_fl in.nc in.nc # Create in RAM, write to disk
ncks --open_ram --no_tmp_fl in.nc in.nc # Read into RAM, write to disk
@end example
@noindent
There is no reason to expect the fourth example to work.
The behavior of overwriting a file while reading from the same file is
undefined, much as is the shell command @samp{cat foo > foo}.
Although it may ``work'' in some cases, it is unreliable.
One way around this is to use @samp{--create_ram} so that the
output file is not written to disk until the input file is closed,
@xref{RAM disks}.
However, as of 20130328, the behavior of the @samp{--create_ram} and
@samp{--open_ram} examples has not been thoroughly tested.

The @acronym{NCO} authors have seen compelling use cases for utilizing
the @acronym{RAM} switches, though not (yet) for combining them with
@samp{--no_tmp_fl}. 
@acronym{NCO} implements both options because they are largely
independent of eachother.
It is up to ``power users'' to discover which best fit their needs.
We welcome accounts of your experiences posted to the forums.

@html
<a name="-A"></a> <!-- http://nco.sf.net/nco.html#-A -->
<a name="-O"></a> <!-- http://nco.sf.net/nco.html#-O -->
@end html
@cindex @code{-A}
@cindex @code{-O}
@cindex @code{--apn}
@cindex @code{--append}
@cindex @code{--ovr}
@cindex @code{--overwrite}
@cindex overwriting files
@cindex appending variables
@cindex appending to files
Other safeguards exist to protect the user from inadvertently
overwriting data.
If the @var{output-file} specified for a command is a pre-existing file,
then the operator will prompt the user whether to overwrite (erase) the
existing @var{output-file}, attempt to append to it, or abort the
operation. 
However, in processing large amounts of data, too many interactive
questions slows productivity.
Therefore @acronym{NCO} also implements two ways to override its own
safety features, the @samp{-O} and @samp{-A} switches.
Specifying @samp{-O} tells the operator to overwrite any existing
@var{output-file} without prompting the user interactively.
Specifying @samp{-A} tells the operator to attempt to append to any
existing @var{output-file} without prompting the user interactively.
These switches are useful in batch environments because they suppress
interactive keyboard input.

@html
<a name="apn"></a> <!-- http://nco.sf.net/nco.html#apn -->
<a name="append"></a> <!-- http://nco.sf.net/nco.html#append -->
@end html
@node Appending Variables, Simple Arithmetic and Interpolation, Temporary Output Files, Strategies
@section Appending Variables
Adding variables from one file to another is often desirable.
@cindex concatenation
@cindex appending variables
@cindex merging files
@cindex pasting variables
This is referred to as @dfn{appending}, although some prefer the
terminology @dfn{merging} @footnote{The terminology @dfn{merging} is
reserved for an (unwritten) operator which replaces hyperslabs of a
variable in one file with hyperslabs of the same variable from another 
file} or @dfn{pasting}. 
Appending is often confused with what @acronym{NCO} calls
@dfn{concatenation}. 
@cindex record dimension
In @acronym{NCO}, concatenation refers to splicing a variable
along the record dimension.  
The length along the record dimension of the output is the sum of the
lengths of the input files. 
Appending, on the other hand, refers to copying a variable from one file
to another file which may or may not already contain the variable 
@footnote{Yes, the terminology is confusing. 
By all means mail me if you think of a better nomenclature.
Should @acronym{NCO} use @dfn{paste} instead of @dfn{append}?
}. 
@acronym{NCO} can append or concatenate just one variable, or all the
variables in a file at the same time.

In this sense, @command{ncks} can append variables from one file to
another file. 
This capability is invoked by naming two files on the command line,
@var{input-file} and @var{output-file}. 
When @var{output-file} already exists, the user is prompted whether to
@dfn{overwrite}, @dfn{append/replace}, or @dfn{exit} from the command.
Selecting @dfn{overwrite} tells the operator to erase the existing
@var{output-file} and replace it with the results of the operation.
Selecting @dfn{exit} causes the operator to exit---the @var{output-file}
will not be touched in this case.
Selecting @dfn{append/replace} causes the operator to attempt to place
the results of the operation in the existing @var{output-file}, 
@xref{ncks netCDF Kitchen Sink}.

@html
<a name="unn"></a> <!-- http://nco.sf.net/nco.html#unn -->
@end html
@cindex union of files
@cindex disjoint files
The simplest way to create the union of two files is
@example
ncks -A fl_1.nc fl_2.nc
@end example
This puts the contents of @file{fl_1.nc} into @file{fl_2.nc}. 
The @samp{-A} is optional. 
On output, @file{fl_2.nc} is the union of the input files,
regardless of whether they share dimensions and variables, 
or are completely disjoint.
The append fails if the input files have differently named record
dimensions (since netCDF supports only one), or have dimensions of the
same name but different sizes.

@html
<a name="bnr"></a> <!-- http://nco.sf.net/nco.html#bnr -->
@end html
@node Simple Arithmetic and Interpolation, Statistics vs. Concatenation, Appending Variables, Strategies
@section Simple Arithmetic and Interpolation

Users comfortable with @acronym{NCO} semantics may find it easier to
perform some simple mathematical operations in @acronym{NCO} rather than  
higher level languages. 
@command{ncbo} (@pxref{ncbo netCDF Binary Operator}) does file
addition, subtraction, multiplication, division, and broadcasting. 
It even does group broadcasting.
@command{ncflint} (@pxref{ncflint netCDF File Interpolator}) does
file addition, subtraction, multiplication and interpolation. 
Sequences of these commands can accomplish simple yet powerful
operations from the command line.

@html
<a name="statisticians"></a> <!-- http://nco.sf.net/nco.html#statisticians -->
<a name="averagers"></a> <!-- http://nco.sf.net/nco.html#averagers -->
@end html
@node Statistics vs. Concatenation, Large Numbers of Files, Simple Arithmetic and Interpolation, Strategies
@section Statistics vs.@: Concatenation

@html
<a name="sym_ncea"></a> <!-- http://nco.sf.net/nco.html#sym_ncea -->
<a name="sym_nces"></a> <!-- http://nco.sf.net/nco.html#sym_nces -->
<a name="sym_ncrcat"></a> <!-- http://nco.sf.net/nco.html#sym_ncrcat -->
@end html
@cindex symbolic links
The most frequently used operators of @acronym{NCO} are probably the
@dfn{statisticians} (i.e., tools that do statistics) and concatenators.
Because there are so many types of statistics like averaging (e.g.,
across files, within a file, over the record dimension, over other
dimensions, with or without weights and masks) and of concatenating
(across files, along the record dimension, along other dimensions),
there are currently no fewer than five operators which tackle these two
purposes: @command{ncra}, @command{nces}, @command{ncwa},
@command{ncrcat}, and @command{ncecat}.  
These operators do share many capabilities @footnote{Currently
@command{nces} and @command{ncrcat} are symbolically linked to the
@command{ncra} executable, which behaves slightly differently based on
its invocation name (i.e., @samp{argv[0]}). 
These three operators share the same source code, and merely have
different inner loops.}, though each has its unique specialty.
Two of these operators, @command{ncrcat} and @command{ncecat}, 
concatenate hyperslabs across files. 
The other two operators, @command{ncra} and @command{nces}, compute
statistics across (and/or within) files 
@footnote{The third averaging operator, @command{ncwa}, is the most
sophisticated averager in @acronym{NCO}. 
However, @command{ncwa} is in a different class than @command{ncra} and
@command{nces} because it operates on a single file per invocation (as
opposed to multiple files).    
On that single file, however, @command{ncwa} provides a richer set of 
averaging options---including weighting, masking, and broadcasting.}.  
First, let's describe the concatenators, then the statistics tools.

@menu
* Concatenation::
* Averaging::
* Interpolating::
@end menu

@html
<a name="cnc"></a> <!-- http://nco.sf.net/nco.html#cnc -->
@end html
@node Concatenation, Averaging, Statistics vs. Concatenation, Statistics vs. Concatenation
@subsection Concatenators @command{ncrcat} and @command{ncecat}
@cindex @command{ncecat}
@cindex @command{ncrcat}

Joining together independent files along a common record dimension is
called @dfn{concatenation}.    
@command{ncrcat} is designed for concatenating record variables, while
@command{ncecat} is designed for concatenating fixed length variables.
Consider five files, @file{85.nc}, @file{86.nc}, 
@w{@dots{} @file{89.nc}} each containing a year's worth of data.  
Say you wish to create from them a single file, @file{8589.nc}
containing all the data, i.e., spanning all five years.
If the annual files make use of the same record variable, then
@command{ncrcat} will do the job nicely with, e.g., 
@code{ncrcat 8?.nc 8589.nc}. 
The number of records in the input files is arbitrary and can vary from
file to file. 
@xref{ncrcat netCDF Record Concatenator}, for a complete description of
@command{ncrcat}. 

However, suppose the annual files have no record variable, and thus
their data are all fixed length. 
@cindex ensemble
@cindex climate model
For example, the files may not be conceptually sequential, but rather
members of the same group, or @dfn{ensemble}. 
Members of an ensemble may have no reason to contain a record dimension.
@command{ncecat} will create a new record dimension (named @var{record}
by default) with which to glue together the individual files into the
single ensemble file.
If @command{ncecat} is used on files which contain an existing record
dimension, that record dimension is converted to a fixed-length
dimension of the same name and a new record dimension (named
@code{record}) is created.  
Consider five realizations, @file{85a.nc}, @file{85b.nc}, 
@w{@dots{} @file{85e.nc}} of 1985 predictions from the same climate
model. 
Then @code{ncecat 85?.nc 85_ens.nc} glues together the individual
realizations into the single file, @file{85_ens.nc}. 
If an input variable was dimensioned [@code{lat},@code{lon}], it will
have dimensions [@code{record},@code{lat},@code{lon}] in the output file.
@w{A restriction} of @command{ncecat} is that the hyperslabs of the
processed variables must be the same from file to file.
Normally this means all the input files are the same size, and contain 
data on different realizations of the same variables.
@xref{ncecat netCDF Ensemble Concatenator}, for a complete description
of @command{ncecat}. 

@cindex @command{ncpdq}
@html
<a name="dmn_cat"></a> <!-- http://nco.sf.net/nco.html#dmn_cat -->
@end html
@command{ncpdq} makes it possible to concatenate files along any
dimension, not just the record dimension.
First, use @command{ncpdq} to convert the dimension to be concatenated
(i.e., extended with data from other files) into the record dimension. 
Second, use @command{ncrcat} to concatenate these files.
Finally, if desirable, use @command{ncpdq} to revert to the original
dimensionality.
As a concrete example, say that files @file{x_01.nc}, @file{x_02.nc},
@w{@dots{} @file{x_10.nc}} contain time-evolving datasets from spatially
adjacent regions.
The time and spatial coordinates are @code{time} and @code{x}, respectively.
Initially the record dimension is @code{time}.
Our goal is to create a single file that contains joins all the
spatially adjacent regions into one single time-evolving dataset.
@example
for idx in 01 02 03 04 05 06 07 08 09 10; do # Bourne Shell
  ncpdq -a x,time x_$@{idx@}.nc foo_$@{idx@}.nc # Make x record dimension
done
ncrcat foo_??.nc out.nc       # Concatenate along x
ncpdq -a time,x out.nc out.nc # Revert to time as record dimension
@end example

Note that @command{ncrcat} will not concatenate fixed-length variables, 
whereas @command{ncecat} concatenates both fixed-length and record
variables along a new record variable.
To conserve system memory, use @command{ncrcat} where possible.

@html
<a name="avg"></a> <!-- http://nco.sf.net/nco.html#avg -->
@end html
@node Averaging, Interpolating, Concatenation, Statistics vs. Concatenation
@subsection Averagers @command{nces}, @command{ncra}, and @command{ncwa} 
@cindex @command{nces}
@cindex @command{ncra}
@cindex @command{ncwa}

The differences between the averagers @command{ncra} and @command{nces}
are analogous to the differences between the concatenators.
@command{ncra} is designed for averaging record variables from at least
one file, while @command{nces} is designed for averaging fixed length
variables from multiple files.
@command{ncra} performs a simple arithmetic average over the record
dimension of all the input files, with each record having an equal
weight in the average. 
@command{nces} performs a simple arithmetic average of all the input
files, with each file having an equal weight in the average. 
Note that @command{ncra} cannot average fixed-length variables,
but @command{nces} can average both fixed-length and record variables.  
To conserve system memory, use @command{ncra} rather than
@command{nces} where possible (e.g., if each @var{input-file} is one
record long). 
The file output from @command{nces} will have the same dimensions
(meaning dimension names as well as sizes) as the input hyperslabs  
(@pxref{nces netCDF Ensemble Statistics}, for a complete description of 
@command{nces}).  
The file output from @command{ncra} will have the same dimensions as
the input hyperslabs except for the record dimension, which will have a   
size @w{of 1} (@pxref{ncra netCDF Record Averager}, for a complete
description of @command{ncra}). 

@html
<a name="ntp"></a> <!-- http://nco.sf.net/nco.html#ntp -->
@end html
@node Interpolating,  , Averaging, Statistics vs. Concatenation
@subsection Interpolator @command{ncflint}
@cindex @command{ncflint}

@command{ncflint} can interpolate data between or two files.
Since no other operators have this ability, the description of
interpolation is given fully on the @command{ncflint} reference page
(@pxref{ncflint netCDF File Interpolator}). 
Note that this capability also allows @command{ncflint} to linearly
rescale any data in a netCDF file, e.g., to convert between differing
units. 

@html
<a name="lrg"></a> <!-- http://nco.sf.net/nco.html#lrg -->
@end html
@node Large Numbers of Files, Large Datasets, Statistics vs. Concatenation, Strategies
@section Large Numbers of Files
@cindex files, numerous input
@cindex @code{-n @var{loop}}

Occasionally one desires to digest (i.e., concatenate or average)
hundreds or thousands of input files.
@cindex automagic
@cindex @acronym{NASA EOSDIS}
Unfortunately, data archives (e.g., @acronym{NASA EOSDIS}) may not
name netCDF files in a format understood by the @samp{-n @var{loop}}
switch (@pxref{Specifying Input Files}) that automagically generates
arbitrary numbers of input filenames. 
The @samp{-n @var{loop}} switch has the virtue of being concise,
and of minimizing the command line.
This helps keeps output file small since the command line is stored
as metadata in the @code{history} attribute 
(@pxref{History Attribute}). 
However, the @samp{-n @var{loop}} switch is useless when there is no
simple, arithmetic pattern to the input filenames (e.g.,
@file{h00001.nc}, @file{h00002.nc}, @w{@dots{} @file{h90210.nc}}).
Moreover, filename globbing does not work when the input files are too
numerous or their names are too lengthy (when strung together as a
single argument) to be passed by the calling shell to the @acronym{NCO}
operator
@footnote{The exact length which exceeds the operating system internal
limit for command line lengths varies from @acronym{OS} to @acronym{OS}
and from shell to shell.  
@acronym{GNU} @code{bash} may not have any arbitrary fixed limits to the
size of command line arguments. 
Many @acronym{OS}s cannot handle command line arguments (including
results of file globbing) exceeding 4096 characters.}.
When this occurs, the @acronym{ANSI} C-standard @code{argc}-@code{argv} 
method of passing arguments from the calling shell to a C-program (i.e.,
an @acronym{NCO} operator) breaks down. 
There are (at least) three alternative methods of specifying the input 
filenames to @acronym{NCO} in environment-limited situations.

@html
<a name="stdin"></a> <!-- http://nco.sf.net/nco.html#stdin -->
@end html
@cindex standard input
@cindex @code{stdin}
The recommended method for sending very large numbers (hundreds or
more, typically) of input filenames to the multi-file operators is
to pass the filenames with the @acronym{UNIX} @dfn{standard input}
feature, aka @code{stdin}: 
@example
# Pipe large numbers of filenames to stdin
/bin/ls | grep $@{CASEID@}_'......'.nc | ncecat -o foo.nc
@end example
This method avoids all constraints on command line size imposed by
the operating system. 
A drawback to this method is that the @code{history} attribute
(@pxref{History Attribute}) does not record the name of any input 
files since the names were not passed on the command line.
This makes determining the data provenance at a later date difficult.
@cindex @code{nco_input_file_number}
@cindex @code{nco_input_file_list}
@cindex global attributes
@cindex attributes, global
To remedy this situation, multi-file operators store the number of
input files in the @code{nco_input_file_number} global attribute and the
input file list itself in the @code{nco_input_file_list} global attribute
(@pxref{File List Attributes}).
Although this does not preserve the exact command used to generate the
file, it does retains all the information required to reconstruct the
command and determine the data provenance.

@cindex globbing
@cindex shell
@cindex extended regular expressions
@cindex regular expressions
@cindex pattern matching
@cindex @command{xargs}
@cindex @acronym{UNIX}
A second option is to use the @acronym{UNIX} @command{xargs} command.
This simple example selects as input to @command{xargs} all the
filenames in the current directory that match a given pattern.
For illustration, consider a user trying to average millions of 
files which each have a six character filename. 
If the shell buffer cannot hold the results of the corresponding
globbing operator, @file{??????.nc}, then the filename globbing
technique will fail. 
Instead we express the filename pattern as an extended regular 
expression, @file{......\.nc} (@pxref{Subsetting Files}).
We use @command{grep} to filter the directory listing for this pattern
and to pipe the results to @command{xargs} which, in turn, passes the
matching filenames to an @acronym{NCO} multi-file operator, e.g.,
@command{ncecat}.
@example
# Use xargs to transfer filenames on the command line
/bin/ls | grep $@{CASEID@}_'......'.nc | xargs -x ncecat -o foo.nc
@end example
@cindex pipes
The single quotes protect the only sensitive parts of the extended
regular expression (the @command{grep} argument), and allow shell
interpolation (the @code{$@{CASEID@}} variable substitution) to
proceed unhindered on the rest of the command.
@command{xargs} uses the @acronym{UNIX} pipe feature to append the
suitably filtered input file list to the end of the @command{ncecat}
command options.  
@cindex output file
@cindex input files
@cindex @code{-o @var{fl_out}}
The @code{-o foo.nc} switch ensures that the input files supplied by
@command{xargs} are not confused with the output file name. 
@command{xargs} does, unfortunately, have its own limit (usually about 
20,000 characters) on the size of command lines it can pass.
Give @command{xargs} the @samp{-x} switch to ensure it dies if it
reaches this internal limit.
When this occurs, use either the @code{stdin} method above, or the
symbolic link presented next.

@cindex symbolic links
Even when its internal limits have not been reached, the
@command{xargs} technique may not be sophisticated enough to handle 
all situations. 
A full scripting language like Perl can handle any level of complexity
of filtering input filenames, and any number of filenames.
The technique of last resort is to write a script that creates symbolic 
links between the irregular input filenames and a set of regular,
arithmetic filenames that the @samp{-n @var{loop}} switch understands. 
@cindex Perl
For example, the following Perl script creates a monotonically
enumerated symbolic link to up to one million @file{.nc} files in a
directory. If there are 999,999 netCDF files present, the links are
named @file{000001.nc} to @file{999999.nc}: 
@cindex @code{-n @var{loop}}
@example
# Create enumerated symbolic links
/bin/ls | grep \.nc | perl -e \
'$idx=1;while(<STDIN>)@{chop;symlink $_,sprintf("%06d.nc",$idx++);@}'
ncecat -n 999999,6,1 000001.nc foo.nc
# Remove symbolic links when finished
/bin/rm ??????.nc
@end example
The @samp{-n @var{loop}} option tells the @acronym{NCO} operator to
automatically generate the filnames of the symbolic links.
This circumvents any @acronym{OS} and shell limits on command line size.
The symbolic links are easily removed once @acronym{NCO} is finished.
@cindex @code{history}
One drawback to this method is that the @code{history} attribute
(@pxref{History Attribute}) retains the filename list of the symbolic
links, rather than the data files themselves. 
This makes it difficult to determine the data provenance at a later
date. 

@node Large Datasets, Memory Requirements, Large Numbers of Files, Strategies
@section Large Datasets
@cindex large datasets
@cindex LFS
@cindex Large File Support

@dfn{Large datasets} are those files that are comparable in size to the
amount of random access memory (@acronym{RAM}) in your computer.
Many users of @acronym{NCO} work with files larger than @w{100 MB}.
Files this large not only push the current edge of storage technology, 
they present special problems for programs which attempt to access the  
entire file at once, such as @command{nces} and @command{ncecat}.
@cindex swap space
If you work with a @w{300 MB} files on a machine with only @w{32 MB} of
memory then you will need large amounts of swap space (virtual memory on
disk) and @acronym{NCO} will work slowly, or even fail. 
There is no easy solution for this.
The best strategy is to work on a machine with sufficient amounts of
memory and swap space. 
Since about 2004, many users have begun to produce or analyze files
exceeding @w{2 GB} in size. 
These users should familiarize themselves with @acronym{NCO}'s Large
File Support (@acronym{LFS}) capabilities (@pxref{Large File Support}).
The next section will increase your familiarity with @acronym{NCO}'s
memory requirements.
With this knowledge you may re-design your data reduction approach to
divide the problem into pieces solvable in memory-limited situations.   

@cindex server
@cindex @acronym{UNICOS}
@cindex Cray
If your local machine has problems working with large files, try running
@acronym{NCO} from a more powerful machine, such as a network server.  
Certain machine architectures, e.g., Cray @acronym{UNICOS}, have special 
commands which allow one to increase the amount of interactive memory.
@cindex @code{ilimit}
On Cray systems, try to increase the available memory with the
@code{ilimit} command.    
@cindex @acronym{GNU}/Linux
@cindex @code{ulimit}
@cindex @code{core dump}
If you get a memory-related core dump 
(e.g., @samp{Error exit (core dumped)}) on a @acronym{GNU}/Linux system,
try increasing the process-available memory with @code{ulimit}.

@cindex speed
The speed of the @acronym{NCO} operators also depends on file size.
When processing large files the operators may appear to hang, or do
nothing, for large periods of time.
In order to see what the operator is actually doing, it is useful to
activate a more verbose output mode.
This is accomplished by supplying a number greater @w{than 0} to the
@samp{-D @var{debug-level}} (or @samp{--debug-level}, or
@samp{--dbg_lvl}) switch.
@cindex @code{-D @var{debug-level}}
@cindex @code{--debug-level @var{debug-level}}
@cindex @code{--dbg_lvl @var{debug-level}}
@cindex @var{debug-level}
@cindex @var{dbg_lvl}
@cindex debugging
When the @var{debug-level} is nonzero, the operators report their
current status to the terminal through the @var{stderr} facility.
Using @samp{-D} does not slow the operators down. 
Choose a @var{debug-level} @w{between 1} @w{and 3} for most situations,
e.g., @code{nces -D 2 85.nc 86.nc 8586.nc}.
@w{A full} description of how to estimate the actual amount of memory the
multi-file @acronym{NCO} operators consume is given in 
@ref{Memory Requirements}. 

@html
<a name="mmr"></a> <!-- http://nco.sf.net/nco.html#mmr -->
@end html
@node Memory Requirements, Performance, Large Datasets, Strategies
@section Memory Requirements
@cindex memory requirements
@cindex memory available
@cindex @acronym{RAM}
@cindex swap space
@cindex peak memory usage
@cindex @code{--ram_all}
@cindex @code{--open_ram}
@cindex @code{--diskless_all}

Many people use @acronym{NCO} on gargantuan files which dwarf the
memory available (free @acronym{RAM} plus swap space) even on today's powerful
machines. 
These users want @acronym{NCO} to consume the least memory possible
so that their scripts do not have to tediously cut files into smaller
pieces that fit into memory. 
We commend these greedy users for pushing @acronym{NCO} to its limits!

@cindex threads
@cindex OpenMP
@cindex shared memory machines
This section describes the memory @acronym{NCO} requires during
operation.
The required memory is based on the underlying algorithms.
The description below is the memory usage per thread.
Users with shared memory machines may use the threaded @acronym{NCO}
operators (@pxref{OpenMP Threading}).
The peak and sustained memory usage will scale accordingly,
i.e., by the number of threads.
Memory consumption patterns of all operators are similar, with
the exception of @command{ncap2}.

@menu
* Single and Multi-file Operators::
* Memory for ncap2::
@end menu

@node Single and Multi-file Operators, Memory for ncap2, Memory Requirements, Memory Requirements
@subsection Single and Multi-file Operators

@cindex multi-file operators
The multi-file operators currently comprise the record operators,
@command{ncra} and @command{ncrcat}, and the ensemble operators,
@command{nces} and @command{ncecat}. 
The record operators require @emph{much less} memory than the ensemble 
operators. 
This is because the record operators operate on one single record (i.e.,
time-slice) at a time, whereas the ensemble operators retrieve the
entire variable into memory. 
Let @math{MS} be the peak sustained memory demand of an operator,
@math{FT} be the memory required to store the entire contents of all the 
variables to be processed in an input file,
@math{FR} be the memory required to store the entire contents of a
single record of each of the variables to be processed in an input file, 
@math{VR} be the memory required to store a single record of the
largest record variable to be processed in an input file, 
@math{VT} be the memory required to store the largest variable 
to be processed in an input file,
@math{VI} be the memory required to store the largest variable 
which is not processed, but is copied from the initial file to the
output file. 
All operators require @math{MI = VI} during the initial copying of
variables from the first input file to the output file. 
This is the @emph{initial} (and transient) memory demand.
The @emph{sustained} memory demand is that memory required by the
operators during the processing (i.e., averaging, concatenation)
phase which lasts until all the input files have been processed.
The operators have the following memory requirements: 
@command{ncrcat} requires @math{MS <= VR}. 
@command{ncecat} requires @math{MS <= VT}. 
@command{ncra} requires @math{MS = 2FR + VR}. 
@command{nces} requires @math{MS = 2FT + VT}. 
@command{ncbo} requires @math{MS <= 3VT} 
(both input variables and the output variable).
@command{ncflint} requires @math{MS <= 3VT}
(both input variables and the output variable).
@command{ncpdq} requires @math{MS <= 2VT}
(one input variable and the output variable).
@command{ncwa} requires @math{MS <= 8VT} (see below).
Note that only variables that are processed, e.g., averaged,
concatenated, or differenced, contribute to @math{MS}. 
Variables which do not appear in the output file 
(@pxref{Subsetting Files}) are never read and contribute nothing
to the memory requirements. 

Further note that some operators perform internal type-promotion on some
variables prior to arithmetic (@pxref{Type Conversion}).
For example, @command{ncra} and @command{nces} both promote integer
types to double-precision floating point prior to arithmetic, then 
perform the arithmetic, then demote back to the original integer type
after arithmetic.
This preserves the on-disk storage type while obtaining the accuracy
advantages of floating point arithmetic. 
Since version 4.3.6 (released in September, 2013), @acronym{NCO} also
by default converts single-precision floating point to double-precision
prior to arithmetic, which incurs the same @acronym{RAM} penalty.
Hence, the sustained memory required for integer variables and
single-precision floats are two or four-times their on-disk,
uncompressed, unpacked sizes if they meet the rules for automatic
internal promotion. 
Put another way, disabling auto-promotion of single-precision variables
(with @samp{--flt}) considerably reduces the @acronym{RAM} footprint 
of arithmetic operators.

The @samp{--open_ram} switch (and switches that invoke it like
@samp{--ram_all} and @samp{--diskless_all}) incurs a @acronym{RAM}
penalty.
These switches cause each input file to be copied to @acronym{RAM} upon
opening. 
Hence any operator invoking these switches utilizes an additional
@math{FT} of @acronym{RAM} (i.e., @math{MS += FT}).
See @ref{RAM disks} for further details. 

@html
<a name="mmr_ncwa"></a> <!-- http://nco.sf.net/nco.html#mmr_ncwa -->
@end html
@command{ncwa} consumes between two and seven times the memory of a
variable in order to process it. 
Peak consumption occurs when storing simultaneously in memory 
one input variable, one tally array,
one input weight, one conformed/working weight, one weight tally, 
one input mask, one conformed/working mask, and
one output variable. 
When invoked, the weighting and masking features contribute up to
three-sevenths and two-sevenths of these requirements apiece.
If weights and masks are @emph{not} specified 
(i.e., no @samp{-w} or @samp{-a} options)
then @command{ncwa} requirements drop to @math{MS <= 3VT}
(one input variable, one tally array, and the output variable). 

@cindex OpenMP
@cindex threads
The above memory requirements must be multiplied by the number of
threads @var{thr_nbr} (@pxref{OpenMP Threading}).
@cindex @code{-t @var{thr_nbr}}
If this causes problems then reduce (with @samp{-t @var{thr_nbr}}) the
number of threads.

@node Memory for ncap2,  , Single and Multi-file Operators, Memory Requirements
@subsection Memory for @command{ncap2}
@cindex @command{ncap2}
@cindex binary operations
@cindex unary operations
@cindex memory leaks
@cindex left hand casting
@command{ncap2} has unique memory requirements due its ability to process
arbitrarily long scripts of any complexity.
All scripts acceptable to @command{ncap2} are ultimately processed as a
sequence of binary or unary operations.
@command{ncap2} requires @math{MS <= 2VT} under most conditions.
An exception to this is when left hand casting (@pxref{Left hand
casting}) is used to stretch the size of derived variables beyond the
size of any input variables.
Let @math{VC} be the memory required to store the largest variable
defined by left hand casting.
In this case, @math{MS <= 2VC}.

@findex malloc()
@command{ncap2} scripts are complete dynamic and may be of arbitrary
length. 
A script that contains many thousands of operations, may uncover a
slow memory leak even though each single operation consumes little
additional memory. 
Memory leaks are usually identifiable by their memory usage signature.
Leaks cause peak memory usage to increase monotonically with time
regardless of script complexity. 
Slow leaks are very difficult to find.
Sometimes a @command{malloc()} (or @command{new[]}) failure is the
only noticeable clue to their existance.
If you have good reasons to believe that a memory allocation failure  
is ultimately due to an @acronym{NCO} memory leak (rather than
inadequate @acronym{RAM} on your system), then we would be very
interested in receiving a detailed bug report. 

@node Performance,  , Memory Requirements, Strategies
@section Performance

@cindex papers
@cindex overview
An overview of @acronym{NCO} capabilities as of about 2006 is in
Zender, C. S. (2008), 
``Analysis of Self-describing Gridded Geoscience Data with netCDF Operators (NCO)'',
Environ. Modell. Softw., doi:10.1016/j.envsoft.2008.03.004.
This paper is also available at
@url{http://dust.ess.uci.edu/ppr/ppr_Zen08.pdf}.

@cindex scaling
@cindex performance
@acronym{NCO} performance and scaling for arithmetic operations is
described in 
Zender, C. S., and H. J. Mangalam (2007), 
``Scaling Properties of Common Statistical Operators for Gridded Datasets'', 
Int. @w{J. High} Perform. Comput. Appl., 21(4), 485-498,
doi:10.1177/1094342007083802. 
This paper is also available at
@url{http://dust.ess.uci.edu/ppr/ppr_ZeM07.pdf}.

It is helpful to be aware of the aspects of @acronym{NCO} design 
that can limit its performance:
@enumerate
@item 
@cindex buffering
No data buffering is performed during @command{nc_get_var} and
@command{nc_put_var} operations.  
@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
Hyperslabs too large too hold in core memory will suffer substantial
performance penalties because of this. 

@item 
@cindex monotonic coordinates
Since coordinate variables are assumed to be monotonic, the search for 
bracketing the user-specified limits should employ a quicker algorithm,
like bisection, than the two-sided incremental search currently
implemented.  

@item 
@cindex @var{C_format}
@cindex @var{FORTRAN_format}
@cindex @var{signedness}
@cindex @var{scale_format} 
@cindex @var{add_offset} 
@var{C_format}, @var{FORTRAN_format}, @var{signedness},
@var{scale_format} and @var{add_offset} attributes are ignored by
@command{ncks} when printing variables to screen. 

@item
@cindex Yorick
In the late 1990s it was discovered that some random access operations
on large files on certain architectures (e.g., @acronym{UNICOS}) were
much slower with @acronym{NCO} than with similar operations performed
using languages that bypass the netCDF interface (e.g., Yorick).    
This may have been a penalty of unnecessary byte-swapping in the netCDF 
interface.  
It is unclear whether such problems exist in present day (2007)
netCDF/@acronym{NCO} environments, where unnecessary byte-swapping has
been reduced or eliminated.
@end enumerate

@html
<a name="ftr"></a> <!-- http://nco.sf.net/nco.html#ftr -->
@end html
@node Common features, Operator Reference Manual, Strategies, Top
@chapter NCO Features

Many features have been implemented in more than one operator and are
described here for brevity. 
The description of each feature is preceded by a box listing the
operators for which the feature is implemented. 
@cindex command line switches
Command line switches for a given feature are consistent across all
operators wherever possible. 
If no ``key switches'' are listed for a feature, then that particular
feature is automatic and cannot be controlled by the user. 

@menu
* Internationalization::
* Metadata Optimization::
* OpenMP Threading::
* Command Line Options::
* Specifying Input Files::
* Specifying Output Files::
* Remote storage::
* Retaining Retrieved Files::
* File Formats and Conversion::
* Large File Support::
* Subsetting Files::
* Subsetting Coordinate Variables::
* Group Path Editing::
* C and Fortran Index Conventions::
* Hyperslabs::
* Stride::
* Record Appending::
* Subcycle::
* Multislabs::
* Wrapped Coordinates::
* Auxiliary Coordinates::
* UDUnits Support::
* Rebasing Time Coordinate::
* Multiple Record Dimensions::
* Missing Values::
* Chunking::
* Deflation::
* MD5 digests::
* Buffer sizes::
* RAM disks::
* Packed data::
* Operation Types::
* Type Conversion::
* Batch Mode::
* History Attribute::
* File List Attributes::
* CF Conventions::
* ARM Conventions::
* Operator Version::
@end menu

@html
<a name="i18n"></a> <!-- http://nco.sf.net/nco.html#i18n -->
@end html
@node Internationalization, Metadata Optimization, Common features, Common features
@section Internationalization
@cindex Internationalization
@cindex I18N
@cartouche
Availability: All operators@*
@end cartouche
@cindex L10N
@acronym{NCO} support for @dfn{internationalization} of textual input
and output (e.g., Warning messages) is nascent.
We hope to produce foreign language string catalogues in 2004.
@c fxm: Work on this section

@html
<a name="hdr"></a> <!-- http://nco.sf.net/nco.html#hdr -->
<a name="hdr_pad"></a> <!-- http://nco.sf.net/nco.html#hdr_pad -->
@end html
@node Metadata Optimization, OpenMP Threading, Internationalization, Common features
@section Metadata Optimization
@cindex metadata optimization
@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
@cindex @code{nc__enddef()}
@cindex @code{--hdr_pad @var{hdr_pad}}
@cindex @code{--header_pad @var{hdr_pad}}
@cartouche
Availability: All operators@*
Short options: None@*
Long options: @samp{--hdr_pad}, @samp{--header_pad}@* 
@end cartouche
@acronym{NCO} supports padding headers to improve the speed of future
metadata operations.
Use the @samp{--hdr_pad} and @samp{--header_pad} switches to request
that @var{hdr_pad} bytes be inserted into the metadata section of the
output file.
Future metadata expansions will not incur the netCDF3 performance
penalty of copying the entire output file unless the expansion exceeds
the amount of header padding exceeded.
This can be beneficial when it is known that some metadata will be added
at a future date.

This optimization exploits the netCDF library @code{nc__enddef()}
function, which behaves differently with different versions of netCDF.
It will improve speed of future metadata expansion with @code{CLASSIC}
and @code{64bit} netCDF files, though not necessarily with @code{NETCDF4} 
files, i.e., those created by the netCDF interface to the @acronym{HDF5}
library (@pxref{File Formats and Conversion}).

@html
<a name="omp"></a> <!-- http://nco.sf.net/nco.html#omp -->
<a name="openmp"></a> <!-- http://nco.sf.net/nco.html#openmp -->
@end html
@node OpenMP Threading, Command Line Options, Metadata Optimization, Common features
@section OpenMP Threading
@cindex OpenMP
@cindex threads
@cindex @acronym{SMP}
@cindex shared memory parallelism
@cindex parallelism
@cindex @code{nco_openmp_thread_number}
@cindex @code{--thr_nbr @var{thr_nbr}}
@cindex @code{--threads @var{thr_nbr}}
@cindex @code{--omp_num_threads @var{thr_nbr}}
@cindex @code{-t @var{thr_nbr}}
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncpdq}, @command{ncra}, @command{ncrcat},
@command{ncwa}@*
Short options: @samp{-t}@*
Long options: @samp{--thr_nbr}, @samp{--threads},
@samp{--omp_num_threads}@* 
@end cartouche
@acronym{NCO} supports shared memory parallelism (@acronym{SMP}) when
compiled with an OpenMP-enabled compiler.
Threads requests and allocations occur in two stages.
First, users may request a specific number of threads @var{thr_nbr} with
the @samp{-t} switch (or its long option equivalents, @samp{--thr_nbr},
@samp{--threads}, and @samp{--omp_num_threads}).
If not user-specified, OpenMP obtains @var{thr_nbr} from the
@code{OMP_NUM_THREADS} environment variable, if present, or from the
@acronym{OS}, if not.

@cartouche
Caveat:
Unfortunately, threading does not improve @acronym{NCO} throughput (i.e.,
wallclock time) because nearly all @acronym{NCO} operations are
I/O-bound. 
This means that @acronym{NCO} spends negligible time doing anything
compared to reading and writing. 
We have seen some and can imagine other use cases where
@command{ncwa}, @command{ncpdq}, and @command{ncap2} (with long scripts) 
will complete faster due to threading. 
The main benefits of threading so far have been to isolate the serial
from parallel portions of code. 
This parallelism is now exploited by OpenMP but then runs into the I/O
bottleneck during output. 
The bottleneck could be ameliorated for large files by the use of
MPI-enabled calls in the netCDF4 library when the underlying filesystem
is parallel (e.g., @acronym{PVFS} or @acronym{JFS}).
Implementation of the parallel output calls in @acronym{NCO} is not a
goal of our current funding and would require new volunteers or funding.  
@end cartouche

@cindex @var{thr_nbr}
@cindex @code{OMP_NUM_THREADS}
@cindex @command{ncrcat}
@cindex @command{ncwa}
@cindex @command{ncap2}
@cindex @command{ncpdq}
@cindex large datasets
@acronym{NCO} may modify @var{thr_nbr} according to its own internal
settings before it requests any threads from the system.
Certain operators contain hard-code limits to the number of threads they
request.
We base these limits on our experience and common sense, and to reduce
potentially wasteful system usage by inexperienced users.
For example, @code{ncrcat} is extremely I/O-intensive so we restrict
@math{@var{thr_nbr} <= 2} for @code{ncrcat}.
This is based on the notion that the best performance that can be
expected from an operator which does no arithmetic is to have one thread
reading and one thread writing simultaneously.
In the future (perhaps with netCDF4), we hope to demonstrate significant
threading improvements with operators like @code{ncrcat} by performing
multiple simultaneous writes. 

Compute-intensive operators (@code{ncap2}, @code{ncwa} and @code{ncpdq}) 
benefit most from threading.
The greatest increases in throughput due to threading occur on
large datasets where each thread performs millions, at least,
of floating point operations.
Otherwise, the system overhead of setting up threads probably outweighs 
the speed enhancements due to @acronym{SMP} parallelism.
However, we have not yet demonstrated that the @acronym{SMP} parallelism 
scales beyond four threads for these operators.
Hence we restrict @math{@var{thr_nbr} <= 4} for all operators.
We encourage users to play with these limits (edit file
@file{nco_omp.c}) and send us their feedback.

@cindex debugging
@cindex @var{dbg_lvl}
Once the initial @var{thr_nbr} has been modified for any
operator-specific limits, @acronym{NCO} requests the system to allocate 
a team of @var{thr_nbr} threads for the body of the code.
The operating system then decides how many threads to allocate
based on this request.
Users may keep track of this information by running the operator with
@math{@var{dbg_lvl} > 0}.

By default, threaded operators attach one global attribute,
@code{nco_openmp_thread_number}, to any file they create or modify. 
This attribute contains the number of threads the operator used to
process the input files. 
This information helps to verify that the answers with threaded and
non-threaded operators are equal to within machine precision.
@cindex benchmarks
This information is also useful for benchmarking.

@html
<a name="cmd_ln"></a> <!-- http://nco.sf.net/nco.html#cmd_ln -->
@end html
@node Command Line Options, Specifying Input Files, OpenMP Threading, Common features
@section Command Line Options
@cindex command line options
@cartouche
Availability: All operators@*
@end cartouche
@cindex @acronym{POSIX}
@cindex @acronym{UNIX}
@cindex @acronym{GNU}
@cindex switches
@acronym{NCO} achieves flexibility by using @dfn{command line options}.
These options are implemented in all traditional @acronym{UNIX} commands 
as single letter @dfn{switches}, e.g., @samp{ls -l}.
For many years @acronym{NCO} used only single letter option names.
In late 2002, we implemented @acronym{GNU}/@acronym{POSIX} extended
or long option names for all options.
This was done in a backward compatible way such that the full
functionality of @acronym{NCO} is still available through the familiar 
single letter options.
In the future, however, some features of @acronym{NCO} may require the
use of long options, simply because we have nearly run out of single
letter options.
More importantly, mnemonics for single letter options are often
non-intuitive so that long options provide a more natural way of
expressing intent.

@cindex long options
Extended options, also called long options, are implemented using the
system-supplied @file{getopt.h} header file, if possible. 
@cindex @code{BSD}
@cindex @code{getopt}
@cindex @code{getopt_long}
@cindex @file{getopt.h}
This provides the @command{getopt_long} function to @acronym{NCO}
@footnote{
If a @command{getopt_long} function cannot be found on the system, 
@acronym{NCO} will use the @command{getopt_long} from the
@command{my_getopt} package by Benjamin Sittler
@email{bsittler@@iname.com}.
This is @acronym{BSD}-licensed software available from  
@uref{http://www.geocities.com/ResearchTriangle/Node/9405/#my_getopt}.}. 

@cindex @code{-D @var{debug-level}}
@cindex @code{--dbg_lvl @var{debug-level}}
The syntax of @dfn{short options} (single letter options) is
@kbd{-@var{key} @var{value}} (dash-key-space-value).
Here, @var{key} is the single letter option name, e.g., 
@samp{-D 2}.

The syntax of @dfn{long options} (multi-letter options) is 
@kbd{--@var{long_name} @var{value}}
(dash-dash-key-space-value), e.g., @samp{--dbg_lvl 2} or
@kbd{--@var{long_name}=@var{value}}
(dash-dash-key-equal-value), e.g., @samp{--dbg_lvl=2}.
Thus the following are all valid for the @samp{-D} (short version)
or @samp{--dbg_lvl} (long version) command line option.
@example
ncks -D 3 in.nc        # Short option
ncks --dbg_lvl=3 in.nc # Long option, preferred form
ncks --dbg_lvl 3 in.nc # Long option, alternate form
@end example
@noindent
The last example is preferred for two reasons.
First, @samp{--dbg_lvl} is more specific and less ambiguous than
@samp{-D}.
The long option form makes scripts more self documenting and less error
prone.  
Often long options are named after the source code variable whose value 
they carry.
Second, the equals sign @kbd{=} joins the key (i.e., @var{long_name}) to   
the value in an uninterruptible text block. 
Experience shows that users are less likely to mis-parse commands when
restricted to this form.

@acronym{GNU} implements a superset of the @acronym{POSIX} standard 
which allows any unambiguous truncation of a valid option to be used.
@example
ncks -D 3 in.nc        # Short option
ncks --dbg_lvl=3 in.nc # Long option, full form
ncks --dbg=3 in.nc     # Long option, unambiguous truncation
ncks --db=3 in.nc      # Long option, unambiguous truncation
ncks --d=3 in.nc       # Long option, ambiguous truncation
@end example
@noindent
The first four examples are equivalent and will work as expected.
The final example will exit with an error since @command{ncks} cannot
disambiguate whether @samp{--d} is intended as a truncation of
@samp{--dbg_lvl}, of @samp{--dimension}, or of some other long option. 

@acronym{NCO} provides many long options for common switches.
For example, the debugging level may be set in all operators with any
of the switches @samp{-D}, @samp{--debug-level}, or @samp{--dbg_lvl}.
This flexibility allows users to choose their favorite mnemonic.
For some, it will be @samp{--debug} (an unambiguous truncation of
@samp{--debug-level}, and other will prefer @samp{--dbg}.
Interactive users usually prefer the minimal amount of typing, i.e.,
@samp{-D}.
We recommend that scripts which are re-usable employ some form of 
the long options for future maintainability.

This manual generally uses the short option syntax in examples.
This is for historical reasons and to conserve space in printed output.
Users are expected to pick the unambiguous truncation of each option
name that most suits their taste.

@html
<a name="fl_in"></a> <!-- http://nco.sf.net/nco.html#fl_in -->
<a name="in"></a> <!-- http://nco.sf.net/nco.html#in -->
<a name="input"></a> <!-- http://nco.sf.net/nco.html#input -->
@end html
@node Specifying Input Files, Specifying Output Files, Command Line Options, Common features
@section Specifying Input Files
@cindex input files
@cindex globbing
@cindex regular expressions
@cindex wildcards
@cindex @code{NINTAP}
@cindex Processor, @acronym{CCM}
@cindex @acronym{CCM} Processor
@cindex @code{-n @var{loop}}
@cindex @code{--nintap @var{loop}}
@cindex @code{-p @var{input-path}}
@cindex @code{--pth @var{input-path}}
@cindex @code{--path @var{input-path}}
@cindex @var{input-path}
@cartouche
Availability (@code{-n}): @command{nces}, @command{ncecat}, @command{ncra}, @command{ncrcat}@*
Availability (@code{-p}): All operators@*
Short options: @samp{-n}, @samp{-p}@*
Long options: @samp{--nintap}, @samp{--pth}, @samp{--path}@*
@end cartouche
It is important that users be able to specify multiple input files
without typing every filename in full, often a tedious task even
by graduate student standards.
@cindex @acronym{UNIX}
There are four different ways of specifying input files to @acronym{NCO}:
explicitly typing each, using @acronym{UNIX} shell wildcards, and using
the @acronym{NCO} @samp{-n} and @samp{-p} switches (or their long option
equivalents, @samp{--nintap} or @samp{--pth} and @samp{--path},
respectively). 
Techniques to augment these methods to specify arbitrary numbers (e.g.,
thousands) and patterns of filenames are discussed separately 
(@pxref{Large Numbers of Files}).

To illustrate these methods, consider the simple problem of using
@command{ncra} to average five input files, @file{85.nc}, @file{86.nc},
@w{@dots{} @file{89.nc}}, and store the results in @file{8589.nc}.
Here are the four methods in order.
They produce identical answers.
@example
ncra 85.nc 86.nc 87.nc 88.nc 89.nc 8589.nc
ncra 8[56789].nc 8589.nc
ncra -p @var{input-path} 85.nc 86.nc 87.nc 88.nc 89.nc 8589.nc
ncra -n 5,2,1 85.nc 8589.nc
@end example
The first method (explicitly specifying all filenames) works by brute 
force. 
The second method relies on the operating system shell to @dfn{glob}
(expand) the @dfn{regular expression} @code{8[56789].nc}.
The shell passes valid filenames which match the expansion to
@command{ncra}.
The third method uses the @samp{-p @var{input-path}} argument to specify 
the directory where all the input files reside.
@acronym{NCO} prepends @var{input-path} (e.g.,
@file{/data/usrname/model}) to all @var{input-files} (though not to
@var{output-file}).  
Thus, using @samp{-p}, the path to any number of input files need only
be specified once.
Note @var{input-path} need not end with @samp{/}; the @samp{/} is
automatically generated if necessary. 

The last method passes (with @samp{-n}) syntax concisely describing 
the entire set of filenames
@footnote{The @samp{-n} option is a backward compatible superset of the
@code{NINTAP} option from the @acronym{NCAR} @acronym{CCM} Processor.}. 
@cindex multi-file operators
@cindex files, multiple
This option is only available with the @dfn{multi-file operators}:
@command{ncra}, @command{ncrcat}, @command{nces}, and @command{ncecat}.
By definition, multi-file operators are able to process an arbitrary
number of @var{input-files}.
This option is very useful for abbreviating lists of filenames
representable as
@var{alphanumeric_prefix}+@var{numeric_suffix}+@file{.}+@var{filetype}
where @var{alphanumeric_prefix} is a string of arbitrary length and
composition, @var{numeric_suffix} is a fixed width field of digits, and
@var{filetype} is a standard filetype indicator. 
For example, in the file @file{ccm3_h0001.nc}, we have
@var{alphanumeric_prefix} = @file{ccm3_h}, @var{numeric_suffix} =
@file{0001}, and @var{filetype} = @file{nc}.

@acronym{NCO} is able to decode lists of such filenames encoded using the
@samp{-n} option. 
The simpler (3-argument) @samp{-n} usage takes the form 
@code{-n @var{file_number},@var{digit_number},@var{numeric_increment}}
where @var{file_number} is the number of files, @var{digit_number} is
the fixed number of numeric digits comprising the @var{numeric_suffix},
and @var{numeric_increment} is the constant, integer-valued difference
between the @var{numeric_suffix} of any two consecutive files.
The value of @var{alphanumeric_prefix} is taken from the input file,
which serves as a template for decoding the filenames.
In the example above, the encoding @code{-n 5,2,1} along with the input
file name @file{85.nc} tells @acronym{NCO} to
construct five (5) filenames identical to the template @file{85.nc}
except that the final two (2) digits are a numeric suffix to be
incremented by one (1) for each successive file.
Currently @var{filetype} may be either be empty, @file{nc},
@file{cdf}, @file{hdf}, or @file{hd5}. 
If present, these @var{filetype} suffixes (and the preceding @file{.})
are ignored by @acronym{NCO} as it uses the @samp{-n} arguments to
locate, evaluate, and compute the @var{numeric_suffix} component of
filenames. 

@cindex wrapped filenames
@cindex climate model
Recently the @samp{-n} option has been extended to allow convenient
specification of filenames with ``circular'' characteristics.
This means it is now possible for @acronym{NCO} to automatically
generate filenames which increment regularly until a specified maximum
value, and then wrap back to begin again at a specified minimum value. 
The corresponding @samp{-n} usage becomes more complex, taking one or
two additional arguments for a total of four or five, respectively: 
@code{-n
@var{file_number},@var{digit_number},@var{numeric_increment}[,@var{numeric_max}[,@var{numeric_min}]]}
where @var{numeric_max}, if present, is the maximum integer-value of 
@var{numeric_suffix} and @var{numeric_min}, if present, is the minimum
integer-value of @var{numeric_suffix}.
Consider, for example, the problem of specifying non-consecutive input
files where the filename suffixes end with the month index.  
In climate modeling it is common to create summertime and wintertime
averages which contain the averages of the months June--July--August,
and December--January--February, respectively:
@example
ncra -n 3,2,1 85_06.nc 85_0608.nc
ncra -n 3,2,1,12 85_12.nc 85_1202.nc
ncra -n 3,2,1,12,1 85_12.nc 85_1202.nc
@end example
The first example shows that three arguments to the @samp{-n} option
suffice to specify consecutive months (@code{06, 07, 08}) which do not
``wrap'' back to a minimum value.
The second example shows how to use the optional fourth and fifth
elements of the @samp{-n} option to specify a wrap value to @acronym{NCO}.
The fourth argument to @samp{-n}, if present, specifies the maximum
integer value of @var{numeric_suffix}.
In this case the maximum value @w{is 12,} and will be formatted as
@file{12} in the filename string. 
The fifth argument to @samp{-n}, if present, specifies the minimum
integer value of @var{numeric_suffix}.
The default minimum filename suffix @w{is 1,} which is formatted as
@file{01} in this case.   
Thus the second and third examples have the same effect, that is, they
automatically generate, in order, the filenames @file{85_12.nc},
@file{85_01.nc}, and @file{85_02.nc} as input to @acronym{NCO}.

@html
<a name="fl_out"></a> <!-- http://nco.sf.net/nco.html#fl_out -->
<a name="out"></a> <!-- http://nco.sf.net/nco.html#out -->
<a name="output"></a> <!-- http://nco.sf.net/nco.html#output -->
@end html
@node Specifying Output Files, Remote storage, Specifying Input Files, Common features
@section Specifying Output Files
@cindex output file
@cindex input files
@cindex positional arguments
@cindex command line switches
@cindex @code{-o @var{fl_out}}
@cindex @code{--output @var{fl_out}}
@cindex @code{--fl_out @var{fl_out}}
@cartouche
Availability: All operators@*
Short options: @samp{-o}@*
Long options: @samp{--fl_out}, @samp{--output}@*
@end cartouche
@acronym{NCO} commands produce no more than one output file, @var{fl_out}. 
Traditionally, users specify @var{fl_out} as the final argument to the
operator, following all input file names. 
This is the @dfn{positional argument} method of specifying input and
ouput file names.
The positional argument method works well in most applications.
@acronym{NCO} also supports specifying @var{fl_out} using the command
line switch argument method, @samp{-o @var{fl_out}}.

Specifying @var{fl_out} with a switch, rather than as a positional
argument, allows @var{fl_out} to precede input files in the argument
list. 
@cindex multi-file operators
This is particularly useful with multi-file operators for three reasons.
Multi-file operators may be invoked with hundreds (or more) filenames.
Visual or automatic location of @var{fl_out} in such a list is
difficult when the only syntactic distinction between input and output
files is their position.
@cindex @command{xargs}
@cindex input files
Second, specification of a long list of input files may be difficult
(@pxref{Large Numbers of Files}).
Making the input file list the final argument to an operator facilitates 
using @command{xargs} for this purpose.
Some alternatives to @command{xargs} are very ugly and undesirable.
Finally, many users are more comfortable specifying output files 
with @samp{-o @var{fl_out}} near the beginning of an argument list.
@cindex compilers
@cindex linkers
Compilers and linkers are usually invoked this way.

Users should specify @var{fl_out} using either (not both) method.
If @var{fl_out} is specified twice (once with the switch and once as
the last positional argument), then the positional argument takes
precedence. 

@html
<a name="rmt"></a> <!-- http://nco.sf.net/nco.html#rmt -->
@end html
@node Remote storage, Retaining Retrieved Files, Specifying Output Files, Common features
@section Accessing Remote Files
@cindex @code{rcp}
@cindex @code{scp}
@cindex @file{.rhosts}
@cindex @acronym{NCAR MSS}
@cindex @acronym{MSS}
@cindex Mass Store System
@cindex @acronym{URL}
@cindex @code{ftp}
@cindex @code{sftp}
@cindex @code{wget}
@cindex remote files
@cindex synchronous file access
@cindex asynchronous file access
@cindex @code{--pth @var{input-path}}
@cindex @code{--path @var{input-path}}
@cindex @code{--lcl @var{output-path}}
@cindex @code{--local @var{output-path}}
@cindex @code{-l @var{output-path}}
@cindex @file{.netrc}
@cindex @code{history}
@cartouche
Availability: All operators@*
Short options: @samp{-p}, @samp{-l}@*
Long options: @samp{--pth}, @samp{--path}, @samp{--lcl}, @samp{--local}@*
@end cartouche
All @acronym{NCO} operators can retrieve files from remote sites as well 
as from the local file system.
@w{A remote} site can be an anonymous @acronym{FTP} server, a machine on
which the user has @command{rcp}, @command{scp}, or @command{sftp}
privileges, @acronym{NCAR}'s Mass Storage System (@acronym{MSS}), or
an @acronym{OPeNDAP} server.
Examples of each are given below, following a brief description of the 
particular access protocol.

@html
<a name="ftp"></a> <!-- http://nco.sf.net/nco.html#ftp -->
@end html
To access a file via an anonymous @acronym{FTP} server, supply the
remote file's @acronym{URL}.
@acronym{FTP} is an intrinsically insecure protocol because it transfers
passwords in plain text format. 
Users should access sites using anonymous @acronym{FTP}, or better yet,
secure @acronym{FTP} when possible. 
Some @acronym{FTP} servers require a login/password combination for a
valid user account.
@acronym{NCO} allows these transactions so long as the required
information is stored in the @file{.netrc} file. 
Usually this information is the remote machine name, login, and
password, in plain text, separated by those very keywords, e.g.,
@example
machine dust.ess.uci.edu login zender password bushlied
@end example
Eschew using valuable passwords for @acronym{FTP} transactions, since
@file{.netrc} passwords are potentially exposed to eavesdropping
software
@footnote{@acronym{NCO} does not implement command line options to
specify @acronym{FTP} logins and passwords because copying those data
into the @code{history} global attribute in the output file (done by
default) poses an unacceptable security risk. 
}. 

@html
<a name="sftp"></a> <!-- http://nco.sf.net/nco.html#sftp -->
@end html
@acronym{SFTP}, i.e., secure @acronym{FTP}, uses @acronym{SSH}-based 
security protocols that solve the security issues associated with
plain @acronym{FTP}.  
@acronym{NCO} supports @acronym{SFTP} protocol access to files
specified with a homebrew syntax of the form
@example
sftp://machine.domain.tld:/path/to/filename
@end example
Note the second colon following the top-level-domain, @code{tld}.
This syntax is a hybrid between an @acronym{FTP URL} and a standard
remote file syntax.

@html
<a name="rcp"></a> <!-- http://nco.sf.net/nco.html#rcp -->
<a name="scp"></a> <!-- http://nco.sf.net/nco.html#scp -->
@end html
To access a file using @command{rcp} or @command{scp}, specify the
Internet address of the remote file.
Of course in this case you must have @command{rcp} or @command{scp}
privileges which allow transparent (no password entry required) access
to the remote machine. 
This means that @file{~/.rhosts} or @file{~/ssh/authorized_keys} must
be set accordingly on both local and remote machines.   

@cindex @acronym{HPSS}
@cindex @command{hsi}
@cindex @command{msrcp}
@cindex @command{msread}
@cindex @command{nrnet}
@html
<a name="hpss"></a> <!-- http://nco.sf.net/nco.html#hpss -->
<a name="HPSS"></a> <!-- http://nco.sf.net/nco.html#HPSS -->
<a name="hsi"></a> <!-- http://nco.sf.net/nco.html#hsi -->
<a name="HSI"></a> <!-- http://nco.sf.net/nco.html#HSI -->
<a name="msrcp"></a> <!-- http://nco.sf.net/nco.html#msrcp -->
<a name="msread"></a> <!-- http://nco.sf.net/nco.html#msread -->
<a name="nrnet"></a> <!-- http://nco.sf.net/nco.html#nrnet -->
@end html
To access a file on a High Performance Storage System (@acronym{HPSS}) 
(such as that at @acronym{NCAR}, @acronym{ECMWF}, @acronym{LANL},
@acronym{DKRZ}, @acronym{LLNL}) specify the full @acronym{HPSS} pathname
of the remote file.  
@acronym{NCO} will attempt to detect whether the local machine has direct
(synchronous) @acronym{HPSS} access. 
In this case, @acronym{NCO} attempts to use the Hierarchical Storage
Interface (@acronym{HSI}) command @command{hsi get}
@footnote{The @command{hsi} command must be in the user's path in one of
the following directories: @code{/usr/local/bin}, @code{/opt/hpss/bin},
or @code{/ncar/opt/hpss/hsi}.
Tell us if the @acronym{HPSS} installation at your site places the
@command{hsi} command in a different location, and we will add that
location to the list of acceptable paths to search for @command{hsi}.
}.

The following examples show how one might analyze files stored on  
remote systems.
@c HPSS syntax at http://www2.cisl.ucar.edu/docs/hpss/hsi
@example
ncks -l . ftp://dust.ess.uci.edu/pub/zender/nco/in.nc
ncks -l . sftp://dust.ess.uci.edu:/home/ftp/pub/zender/nco/in.nc
ncks -l . dust.ess.uci.edu:/home/zender/nco/data/in.nc
ncks -l . /ZENDER/nco/in.nc
ncks -l . /home/zender/nco/in.nc
ncks -l . http://thredds-test.ucar.edu/thredds/dodsC/testdods/in.nc 
@end example
@noindent
The first example works verbatim if your system is connected to the
Internet and is not behind a firewall. 
The second example works if you have @command{sftp} access to the
machine @code{dust.ess.uci.edu}.
The third example works if you have @command{rcp} or @command{scp}
access to the machine @code{dust.ess.uci.edu}. 
The fourth and fifth examples work on @acronym{NCAR} computers with
local access to the @acronym{HPSS} @command{hsi get} command
@footnote{@acronym{NCO} supported the old @acronym{NCAR} Mass Storage
System (@acronym{MSS}) until version 4.0.7 in April, 2011.
@acronym{NCO} supported @acronym{MSS}-retrievals via a variety of
mechanisms including the @command{msread}, @command{msrcp}, and
@command{nrnet} commands invoked either automatically or with sentinels
like @command{ncks -p mss:/ZENDER/nco -l . in.nc}.
Once the @acronym{MSS} was decommissioned in March, 2011, support for
these retrieval mechanisms was replaced by support for @acronym{HPSS}
in @acronym{NCO}.
}.
The sixth command works if your local version of @acronym{NCO} is
@acronym{OPeNDAP}-enabled (this is fully described in @ref{OPeNDAP}),
or if the remote file is accessible via @command{wget}.
The above commands can be rewritten using the @samp{-p @var{input-path}} 
option as follows: 
@cindex @code{-p @var{input-path}}
@cindex @var{input-path}
@cindex @code{-l @var{output-path}}
@cindex @var{output-path}
@example
ncks -p ftp://dust.ess.uci.edu/pub/zender/nco -l . in.nc
ncks -p sftp://dust.ess.uci.edu:/home/ftp/pub/zender/nco -l . in.nc
ncks -p dust.ess.uci.edu:/home/zender/nco -l . in.nc
ncks -p /ZENDER/nco -l . in.nc
ncks -p /home/zender/nco -l . in.nc # HPSS
ncks -p http://thredds-test.ucar.edu/thredds/dodsC/testdods \ 
     -l . in.nc
@end example
@noindent
Using @samp{-p} is recommended because it clearly separates the
@var{input-path} from the filename itself, sometimes called the
@dfn{stub}. 
@cindex stub
When @var{input-path} is not explicitly specified using @samp{-p},
@acronym{NCO} internally generates an @var{input-path} from the first
input filename.  
The automatically generated @var{input-path} is constructed by stripping 
the input filename of everything following the final @samp{/} character
(i.e., removing the stub).
The @samp{-l @var{output-path}} option tells @acronym{NCO} where to
store the remotely retrieved file.
It has no effect on locally-retrieved files, or on the output file.
Often the path to a remotely retrieved file is quite different than the
path on the local machine where you would like to store the file.
If @samp{-l} is not specified then @acronym{NCO} internally generates an
@var{output-path} by simply setting @var{output-path} equal to
@var{input-path} stripped of any machine names.
If @samp{-l} is not specified and the remote file resides on the
@acronym{NCAR} @acronym{HPSS} system, then the leading character of
@var{input-path}, @samp{/}, is also stripped from @var{output-path}.
Specifying @var{output-path} as @samp{-l ./} tells @acronym{NCO} to
store the remotely retrieved file and the output file in the current
directory. 
Note that @samp{-l .} is equivalent to @samp{-l ./} though the latter is
syntactically more clear.

@menu
* OPeNDAP::
@end menu

@html
<a name="dap"></a> <!-- http://nco.sf.net/nco.html#dap -->
<a name="DAP"></a> <!-- http://nco.sf.net/nco.html#DAP -->
<a name="DODS"></a> <!-- http://nco.sf.net/nco.html#DODS -->
<a name="OPeNDAP"></a> <!-- http://nco.sf.net/nco.html#OPeNDAP -->
<a name="dods"></a> <!-- http://nco.sf.net/nco.html#dods -->
<a name="opendap"></a> <!-- http://nco.sf.net/nco.html#opendap -->
@end html
@node OPeNDAP,  , Remote storage, Remote storage
@subsection @acronym{OPeNDAP}
@cindex @acronym{DAP}
@cindex @acronym{DODS}
@cindex @acronym{HTTP} protocol
@cindex @env{DODS_ROOT}
@cindex Distributed Oceanographic Data System
@cindex oceanography
@cindex data access protocol
@cindex Open-source Project for a Network Data Access Protocol
@cindex @acronym{OPeNDAP}.
@cindex server
@cindex client-server
The Distributed Oceanographic Data System (@acronym{DODS}) provides
useful replacements for common data interface libraries like netCDF.
The @acronym{DODS} versions of these libraries implement network
transparent access to data via a client-server data access protocol
that uses the @acronym{HTTP} protocol for communication.
Although @acronym{DODS}-technology originated with oceanography data,
it applyies to virtually all scientific data.
In recognition of this, the data access protocol underlying
@acronym{DODS} (which is what @acronym{NCO} cares about) has been 
renamed the Open-source Project for a Network Data Access Protocol, 
@acronym{OPeNDAP}.
We use the terms @acronym{DODS} and @acronym{OPeNDAP} interchangeably,
and often write @acronym{OPeNDAP}/@acronym{DODS} for now. 
In the future we will deprecate @acronym{DODS} in favor of
@acronym{DAP} or @acronym{OPeNDAP}, as appropriate
@footnote{
@cindex @acronym{NVODS}
@cindex National Virtual Ocean Data System
@cindex open source
@acronym{DODS} is being deprecated because it is ambiguous, referring
both to a protocol and to a collection of (oceanography) data.
It is superceded by two terms.
@acronym{DAP} is the discipline-neutral Data Access Protocol at the
heart of @acronym{DODS}.
The National Virtual Ocean Data System (@acronym{NVODS}) refers to the
collection of oceanography data and oceanographic extensions to
@acronym{DAP}. 
In other words, @acronym{NVODS} is implemented with @acronym{OPeNDAP}.
@acronym{OPeNDAP} is @emph{also} the open source project which
maintains, develops, and promulgates the @acronym{DAP} standard. 
@acronym{OPeNDAP} and @acronym{DAP} really are interchangeable.
Got it yet?}.

@acronym{NCO} may be @acronym{DAP}-enabled by linking
@acronym{NCO} to the @acronym{OPeNDAP} libraries. 
@cindex @file{Makefile}
This is described in the @acronym{OPeNDAP} documentation and
automagically implemented in @acronym{NCO} build mechanisms
@footnote{
Automagic support for @acronym{DODS} version 3.2.x was deprecated in 
December, 2003 after @acronym{NCO} version 2.8.4.
@acronym{NCO} support for @acronym{OPeNDAP} versions 3.4.x commenced in
December, 2003, with @acronym{NCO} version 2.8.5.
@acronym{NCO} support for @acronym{OPeNDAP} versions 3.5.x commenced in
June, 2005, with @acronym{NCO} version 3.0.1.
@acronym{NCO} support for @acronym{OPeNDAP} versions 3.6.x commenced in
June, 2006, with @acronym{NCO} version 3.1.3.
@acronym{NCO} support for @acronym{OPeNDAP} versions 3.7.x commenced in
January, 2007, with @acronym{NCO} version 3.1.9.}.
The @file{./configure} mechanism automatically enables @acronym{NCO} as
@acronym{OPeNDAP} clients if it can find the required
@acronym{OPeNDAP} libraries
@footnote{
The minimal set of libraries required to build @acronym{NCO} as
@acronym{OPeNDAP} clients, where @acronym{OPeNDAP} is supplied as a
separate library apart from @file{libnetcdf.a}, are, in link order,
@file{libnc-dap.a}, @file{libdap.a}, and 
@file{libxml2} and @file{libcurl.a}.}.
 in the usual locations.
The @env{$DODS_ROOT} environment variable may be used to override the 
default @acronym{OPeNDAP} library location at @acronym{NCO}
compile-time.  
Building @acronym{NCO} with @file{bld/Makefile} and the command
@code{make DODS=Y} adds the (non-intuitive) commands to link to the
@acronym{OPeNDAP} libraries installed in the @env{$DODS_ROOT}
directory.  
The file @file{doc/opendap.sh} contains a generic script intended to help
users install @acronym{OPeNDAP} before building @acronym{NCO}.
The documentation at the 
@uref{http://www.opendap.org, OPeNDAP Homepage}
is voluminous.
Check there and on the
@uref{http://www.unidata.ucar.edu/packages/dods/home/mailLists/, DODS mail lists}.
to learn more about the extensive capabilities of @acronym{OPeNDAP}
@footnote{
We are most familiar with the @acronym{OPeNDAP} ability to enable 
network-transparent data access.
@cindex constraint expressions
@cindex server-side processing
@acronym{OPeNDAP} has many other features, including sophisticated
hyperslabbing and server-side processing via @dfn{constraint expressions}.
If you know more about this, please consider writing a section
on "@acronym{OPeNDAP} Capabilities of Interest to @acronym{NCO} Users"
for incorporation in the @cite{NCO User Guide}.}.

Once @acronym{NCO} is @acronym{DAP}-enabled the operators are
@acronym{OPeNDAP} clients.  
All @acronym{OPeNDAP} clients have network transparent access to
any files controlled by a @acronym{OPeNDAP} server. 
Simply specify the input file path(s) in @acronym{URL} notation and all 
@acronym{NCO} operations may be performed on remote files made
accessible by a @acronym{OPeNDAP} server. 
This command tests the basic functionality of @acronym{OPeNDAP}-enabled  
@acronym{NCO} clients: 
@example
% ncks -O -o ~/foo.nc -C -H -v one -l /tmp \
  -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in.nc
% ncks -H -v one ~/foo.nc
one = 1
@end example
The @code{one = 1} outputs confirm (first) that @command{ncks} correctly
retrieved data via the  @acronym{OPeNDAP} protocol and (second) that 
@command{ncks} created a valid local copy of the subsetted remote file.
With minor changes to the above command, netCDF4 can be used as both the
input and output file format:
@example
% ncks -4 -O -o ~/foo.nc -C -H -v one -l /tmp \
  -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in_4.nc
% ncks -H -v one ~/foo.nc
one = 1
@end example
And, of course, @acronym{OPeNDAP}-enabled @acronym{NCO} clients continue
to support other, orthogonal features such as UDUnits 
(@pxref{UDUnits Support}):
@example
% ncks -u -C -H -v wvl -d wvl,'0.4 micron','0.7 micron' \
  -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in_4.nc
% wvl[0]=5e-07 meter
@end example

The next command is a more advanced example which demonstrates the real
power of @acronym{OPeNDAP}-enabled @acronym{NCO} clients.
The @command{ncwa} client requests an equatorial hyperslab from remotely
stored @acronym{NCEP reanalyses data} of the @w{year 1969}.
The @acronym{NOAA} @acronym{OPeNDAP} server (hopefully!) serves these data. 
The local @command{ncwa} client then computes and stores (locally) the
regional mean surface pressure @w{(in Pa)}. 
@example
ncwa -C -a lat,lon,time -d lon,-10.,10. -d lat,-10.,10. -l /tmp -p \
http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.dailyavgs/surface \
  pres.sfc.1969.nc ~/foo.nc
@end example
@noindent
@cindex packing
@cindex unpacking
All with one command!
The data in this particular input file also happen to be packed
(@pxref{Methods and functions}), although this is completely transparent
to the user since @acronym{NCO} automatically unpacks data before
attempting arithmetic. 

@acronym{NCO} obtains remote files from the @acronym{OPeNDAP} server
(e.g., @file{www.cdc.noaa.gov}) rather than the local machine. 
Input files are first copied to the local machine, then processed.
The @acronym{OPeNDAP} server performs data access, hyperslabbing,
and transfer to the local machine.
@cindex I/O
This allows the I/O to appear to @acronym{NCO} as if the input files
were local.  
The local machine performs all arithmetic operations.
Only the hyperslabbed output data are transferred over the network (to
the local machine) for the number-crunching to begin.
The advantages of this are obvious if you are examining small parts of
large files stored at remote locations.

@html
<a name="rtn"></a> <!-- http://nco.sf.net/nco.html#rtn -->
@end html
@node Retaining Retrieved Files, File Formats and Conversion, Remote storage, Common features
@section Retaining Retrieved Files
@cindex file deletion
@cindex file removal
@cindex file retention
@cindex @code{-R}
@cindex @code{--rtn}
@cindex @code{--retain}
@cartouche
Availability: All operators@*
Short options: @samp{-R}@*
Long options: @samp{--rtn}, @samp{--retain}@*
@end cartouche
In order to conserve local file system space, files retrieved from
remote locations are automatically deleted from the local file system 
once they have been processed.
Many @acronym{NCO} operators were constructed to work with numerous
large (e.g., @w{200 MB}) files. 
Retrieval of multiple files from remote locations is done serially. 
Each file is retrieved, processed, then deleted before the cycle
repeats.  
In cases where it is useful to keep the remotely-retrieved files on the
local file system after processing, the automatic removal feature may be 
disabled by specifying @samp{-R} on the command line.

Invoking @code{-R} disables the default printing behavior of
@command{ncks}.
This allows @command{ncks} to retrieve remote files without
automatically trying to print them.
See @ref{ncks netCDF Kitchen Sink}, for more details.

@cindex @acronym{FTP}
@cindex @acronym{SSH}
@cindex @acronym{msrcp}
Note that the remote retrieval features of @acronym{NCO} can always be
used to retrieve @emph{any} file, including non-netCDF files, via
@command{SSH}, anonymous @acronym{FTP}, or @command{msrcp}.
Often this method is quicker than using a browser, or running an
@acronym{FTP} session from a shell window yourself.
@cindex server
For example, say you want to obtain a @acronym{JPEG} file from a weather
server. 
@example
ncks -R -p ftp://weather.edu/pub/pix/jpeg -l . storm.jpg
@end example
@noindent
In this example, @command{ncks} automatically performs an anonymous
@acronym{FTP} login to the remote machine and retrieves the specified
file. 
When @command{ncks} attempts to read the local copy of @file{storm.jpg}
as a netCDF file, it fails and exits, leaving  @file{storm.jpg} in
the current directory.

@cindex @acronym{DODS}
@cindex server
If your @acronym{NCO} is @acronym{DAP}-enabled (@pxref{OPeNDAP}),
then you may use @acronym{NCO} to retrieve any files (including netCDF,
@acronym{HDF}, etc.) served by an @acronym{OPeNDAP} server to your local 
machine. 
For example, 
@example
ncks -R -l . -p \
http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.dailyavgs/surface \
  pres.sfc.1969.nc
@end example
It may occasionally be useful to use @acronym{NCO} to transfer files
when your other preferred methods are not available locally.

@html
<a name="fl_fmt"></a> <!-- http://nco.sf.net/nco.html#fl_fmt -->
<a name="hdf"></a> <!-- http://nco.sf.net/nco.html#hdf -->
<a name="64bit"></a> <!-- http://nco.sf.net/nco.html#64bit -->
<a name="netcdf4"></a> <!-- http://nco.sf.net/nco.html#netcdf4 -->
@end html
@node File Formats and Conversion, Large File Support, Retaining Retrieved Files, Common features
@section File Formats and Conversion
@cindex @acronym{HDF}
@cindex netCDF2
@cindex netCDF3
@cindex netCDF4
@cindex @code{NETCDF4_CLASSIC} files
@cindex @code{NETCDF4} files
@cindex @code{CLASSIC} files
@cindex @code{64BIT} files
@cindex @code{--3}
@cindex @code{-3}
@cindex @code{-4}
@cindex @code{-6}
@cindex @code{-7}
@cindex @code{--4}
@cindex @code{--7}
@cindex @code{--netcdf4}
@cindex @code{--fl_fmt}
@cindex @code{--file_format}
@cindex @code{--64bit}
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@*
Short options: @samp{-3}, @samp{-4}, @samp{-6}, @samp{-7}@*
Long options: @samp{--3}, @samp{--4}, @samp{--64bit}, @samp{--7}, @samp{--fl_fmt},
@samp{--netcdf4}@*  
@end cartouche
All @acronym{NCO} operators support (read and write) all three (or four, 
depending on how one counts) file formats supported by netCDF4.
The default output file format for all operators is the input file
format. 
The operators listed under ``Availability'' above allow the user to
specify the output file format independent of the input file format. 
These operators allow the user to convert between the various file
formats. 
(The operators @command{ncatted} and @command{ncrename} do not support
these switches so they always write the output netCDF file in the same
format as the input netCDF file.) 

@menu
* File Formats::
* Determining File Format::
* File Conversion::
* Autoconversion::
@end menu

@node File Formats, Determining File Format, File Formats and Conversion, File Formats and Conversion
@subsection File Formats
netCDF supports four types of files: @code{CLASSIC}, @code{64BIT},
@code{NETCDF4}, and @code{NETCDF4_CLASSIC}, 
The @code{CLASSIC} format is the traditional 32-bit offset written by
netCDF2 and netCDF3.
As of 2005, nearly all netCDF datasets were in @code{CLASSIC} format. 
The @code{64BIT} format was added in Fall, 2004.
As of 2010, many netCDF datasets were in @code{64BIT} format. 
As of 2013, many netCDF datasets are in @code{NETCDF4_CLASSIC} format. 

The @code{NETCDF4} format uses @acronym{HDF5} as the file storage layer. 
The files are (usually) created, accessed, and manipulated using the 
traditional netCDF3 @acronym{API} (with numerous extensions).
The @code{NETCDF4_CLASSIC} format refers to netCDF4 files created with
the @code{NC_CLASSIC_MODEL} mask.
Such files use @acronym{HDF5} as the back-end storage format (unlike
netCDF3), though they incorporate only netCDF3 features.
Hence @code{NETCDF4_CLASSIC} files are entirely readable by applications 
that use only the netCDF3 @acronym{API} (though the applications must be
linked with the netCDF4 library).
@acronym{NCO} must be built with @w{netCDF4} to write files in the new
@code{NETCDF4} and @code{NETCDF4_CLASSIC} formats, and to read files in
these formats. 
Datasets in the default @code{CLASSIC} or the newer @code{64BIT} formats 
have maximum backwards-compatibility with older applications. 
@acronym{NCO} has deep support for @code{NETCDF4} formats.
If performance or disk-space as important as backwards compatibility,
then use @code{NETCDF4_CLASSIC} instead of @code{CLASSIC} format files. 
As of 2014, @acronym{NCO} support for the @code{NETCDF4} format is
nearly complete and the most powerful and disk/@acronym{RAM} efficient 
workflows will utilize this format.

As mentioned above, all operators write use the input file format for
output files unless told otherwise.
Toggling the short option @samp{-6} or the long option @samp{--64bit}
switch (or its @var{key}-@var{value} equivalent @samp{--fl_fmt=64bit})
produces the netCDF3 64-bit offset format named @code{64BIT}. 
@acronym{NCO} must be built with @w{netCDF 3.6} or higher to produce
a @code{64BIT} file.
Using the @samp{-4} switch (or its long option equivalents
@samp{--4} or @samp{--netcdf4}), or setting its @var{key}-@var{value}
equivalent @samp{--fl_fmt=netcdf4} produces a @code{NETCDF4} file
(i.e., with all supported @acronym{HDF5} features).
Using the @samp{-7} switch (or its long option equivalent
@samp{--7}
@footnote{
The reason (and mnemonic) for @samp{-7} is that @code{NETCDF4_CLASSIC}
files include great features of both netCDF3 (compatibility) and
netCDF4 (compression, chunking) and, well, @math{3+4=7}.}, or 
setting its @var{key}-@var{value} equivalent
@samp{--fl_fmt=netcdf4_classic} produces a @code{NETCDF4_CLASSIC}  
file (i.e., with all supported @acronym{HDF5} features like compression
and chunking but without groups or new atomic types).
Operators given the @samp{-3} (or @samp{--3}) switch without arguments
will (attempt to) produce netCDF3 @code{CLASSIC} output, even from
netCDF4 input files.  

Note that @code{NETCDF4} and @code{NETCDF4_CLASSIC} are the same
binary format. 
The latter simply causes a writing application to fail if it attempts to 
write a @code{NETCDF4} file that cannot be completely read by the
netCDF3 library. 
Conversely, @code{NETCDF4_CLASSIC} indicates to a reading application
that all of the file contents are readable with the netCDF3 library. 
@acronym{NCO} has supported reading/writing basic @code{NETCDF4} and
@code{NETCDF4_CLASSIC} files since October, 2005.

@html
<a name="fmt_inq"></a> <!-- http://nco.sf.net/nco.html#fmt_inq -->
@end html
@node Determining File Format, File Conversion, File Formats, File Formats and Conversion
@subsection Determining File Format
Input files often end with the generic @code{.nc} suffix that leaves
(perhaps by intention) the internal file format ambiguous.
There are at least three ways to discover the internal format of a
netCDF-supported file.
These methods determine whether it is a classic (32-bit offset) or newer
64-bit offset netCDF3 format, or is a netCDF4 format. 
Each method returns the information using slightly different terminology 
that becomes easier to understand with practice.

First, examine the first line of global metadata output by @samp{ncks -M}:  
@cindex netCDF3 classic file format
@cindex netCDF4 classic file format
@cindex netCDF4 file format
@cindex 32-bit offset file format
@cindex 64-bit offset file format
@cindex @command{ncks} 
@cindex @code{-M}
@example
% ncks -M foo_3c.nc
Summary of foo_3c.nc: filetype = NC_FORMAT_CLASSIC, 0 groups ...
% ncks -M foo_364.nc
Summary of foo_364.nc: filetype = NC_FORMAT_64BIT, 0 groups ...
% ncks -M foo_4c.nc
Summary of foo_4c.nc: filetype = NC_FORMAT_NETCDF4_CLASSIC, 0 groups ...
% ncks -M foo_4.nc
Summary of foo_4.nc: filetype = NC_FORMAT_NETCDF4, 0 groups ...
@end example
This method requires a netCDF4-enabled @acronym{NCO} version 3.9.0+
(i.e., from 2007 or later).
@cindex extended file format
@cindex underlying file format
@cindex @code{NC_FORMAT_NC3}
@cindex @code{NC_FORMAT_NC_HDF5}
@cindex @code{NC_FORMAT_NC_HDF4}
@cindex @code{NC_FORMAT_PNETCDF}
@cindex @code{NC_FORMAT_DAP2}
@cindex @code{NC_FORMAT_DAP4}
As of @acronym{NCO} version 4.4.0 (January, 2014), @command{ncks} will
also print the extended or underlying format of the input file.
The extended filetype will be one of the six underlying formats that
are accessible through the netCDF @acronym{API}.
These formats are
@code{NC_FORMAT_NC3} (classic and 64-bit versions of netCDF3 formats),
@code{NC_FORMAT_NC_HDF5} (classic and extended versions of netCDF4, and
``pure'' HDF5 format),
@code{NC_FORMAT_NC_HDF4} (HDF4 format),
@code{NC_FORMAT_PNETCDF} (PnetCDF format),
@code{NC_FORMAT_DAP2} (accessed via DAP2 protocol), and
@code{NC_FORMAT_DAP4} (accessed via DAP2 protocol).
For example,
@example
% ncks -D 2 -M hdf.hdf
Summary of hdf.hdf: filetype = NC_FORMAT_NETCDF4 (representation of \
  extended/underlying filetype NC_FORMAT_HDF4), 0 groups ...
% ncks -D 2 -M http://thredds-test.ucar.edu/thredds/dodsC/testdods/in.nc
Summary of http://thredds-test.ucar.edu/thredds/dodsC/testdods/in.nc: \
  filetype = NC_FORMAT_CLASSIC (representation of extended/underlying \
  filetype NC_FORMAT_DAP2), 0 groups  
% ncks -D 2 -M foo_4.nc
Summary of foo_4.nc: filetype = NC_FORMAT_NETCDF4 (representation of \
  extended/underlying filetype NC_FORMAT_HDF5), 0 groups  
@end example
The extended filetype determines some of the capabilities that netCDF
has to alter the file.

Second, query the file with @samp{ncdump -k}:
@cindex @command{ncdump} 
@example
% ncdump -k foo_3c.nc
classic
% ncdump -k foo_364.nc
64-bit-offset
% ncdump -k foo_4c.nc
netCDF-4 classic model
% ncdump -k foo_4.nc
netCDF-4
@end example
This method requires a netCDF4-enabled @acronym{netCDF} 3.6.2+
(i.e., from 2007 or later).

The third option uses the POSIX-standard @command{od} (octal dump)
command:   
@cindex @command{od} 
@cindex octal dump
@example
% od -An -c -N4 foo_3c.nc
   C   D   F 001
% od -An -c -N4 foo_364.nc
   C   D   F 002
% od -An -c -N4 foo_4c.nc
 211   H   D   F
% od -An -c -N4 foo_4.nc
 211   H   D   F
@end example
This option works without @acronym{NCO} and @command{ncdump}.
Values of @samp{C D F 001} and @samp{C D F 002} indicate 32-bit
(classic) and 64-bit netCDF3 formats, respectively, while values of
@samp{211 H D F} indicate either of the newer netCDF4 file formats.

@html
<a name="hdf2nc"></a> <!-- http://nco.sf.net/nco.html#hdf2nc -->
<a name="3to4"></a> <!-- http://nco.sf.net/nco.html#3to4 -->
<a name="4to3"></a> <!-- http://nco.sf.net/nco.html#4to3 -->
@end html
@node File Conversion, Autoconversion, Determining File Format, File Formats and Conversion
@subsection File Conversion
Let us demonstrate converting a file from any netCDF-supported
input format into any netCDF output format (subject to limits of the
output format).  
Here the input file @file{in.nc} may be in any of these formats:
netCDF3 (classic and 64bit), netCDF4 (classic and extended), HDF4, HDF5,
HDF-EOS (version 2 or 5), and DAP. 
The switch determines the output format written in the comment:
@example
ncks --fl_fmt=classic in.nc foo_3c.nc # netCDF3 classic
ncks --fl_fmt=64bit in.nc foo_364.nc # netCDF3 64bit
ncks --fl_fmt=netcdf4_classic in.nc foo_4c.nc # netCDF4 classic
ncks --fl_fmt=netcdf4 in.nc foo_4.nc # netCDF4 
ncks -3 in.nc foo_3c.nc # netCDF3 classic
ncks --3 in.nc foo_3c.nc # netCDF3 classic
ncks -6 in.nc foo_364.nc # netCDF3 64bit
ncks --64 in.nc foo_364.nc # netCDF3 64bit
ncks -4 in.nc foo_4.nc # netCDF4 
ncks --4 in.nc foo_4.nc # netCDF4 
ncks -7 in.nc foo_4c.nc # netCDF4 classic
ncks --7 in.nc foo_4c.nc # netCDF4 classic
@end example
Of course since most operators support these switches, the
``conversions'' can be done at the output stage of arithmetic
or metadata processing rather than requiring a separate step.
Producing (netCDF3) @code{CLASSIC} or @code{64BIT} files from
@code{NETCDF4_CLASSIC} files will always work. 

@html
<a name="autoconversion"></a> <!-- http://nco.sf.net/nco.html#autoconversion -->
<a name="autocnv"></a> <!-- http://nco.sf.net/nco.html#autocnv -->
@end html
@node Autoconversion,  , File Conversion, File Formats and Conversion
@subsection Autoconversion
Because of the dearth of support for netCDF4 amongst tools and user
communities (including the @acronym{CF} conventions), it is often useful
to convert netCDF4 to netCDF3 for certain applications.
Until @acronym{NCO} version 4.4.0 (January, 2014), producing netCDF3
files from netCDF4 files only worked if the input files contained no 
netCDF4-specific features (e.g., atomic types, multiple record
dimensions, or groups). 
As of @acronym{NCO} version 4.4.0, @command{ncks} supports
@dfn{autoconversion} of many netCDF4 features to their closest
netCDF3-compatible representations.
Since converting netCDF4 to netCDF3 results in loss of features, 
``automatic down-conversion'' may be a more precise description of what  
we term autoconversion.

@acronym{NCO} employs three algorithms to downconvert netCDF4 to netCDF3:
@enumerate
@item 
@cindex autoconversion
Autoconversion of atomic types:
Autoconversion automatically promotes @code{NC_UBYTE} to @code{NC_SHORT}, 
and @code{NC_USHORT} to @code{NC_INT}.
It automatically demotes the three types @code{NC_UINT},
@code{NC_UINT64}, and @code{NC_INT64} to @code{NC_INT}. 
And it converts @code{NC_STRING} to @code{NC_CHAR}.
All numeric conversions work for attributes and variables of any rank.
Two numeric types (@code{NC_UBYTE} and @code{NC_USHORT}) are
@emph{promoted} to types with greater range (and greater storage). 
This extra range is often not used so promotion perhaps conveys
the wrong impression.
However, promotion never truncates values or loses data (this perhaps
justifies the extra storage).
Three numeric types (@code{NC_UINT}, @code{NC_UINT64} and
@code{NC_INT64}) are @emph{demoted}.
Since the input range is larger than the output range, demotion can
result in numeric truncation and thus loss of data. 
In such cases, it would possible to convert the data to floating point
values instead. 
If this feature interests you, please be the squeaky wheel and let us
know.

String conversions (to @code{NC_CHAR}) work for all attributes, but
not for variables.
This is because attributes are at most one-dimensional and may be of any
size whereas variables require gridded dimensions that usually do not
fit the ragged sizes of text strings.
Hence scalar @code{NC_STRING} attributes are correctly converted to and
stored as @code{NC_CHAR} attributes in the netCDF3 output file, but
@code{NC_STRING} variables are not correctly converted. 
If this limitation annoys or enrages you, please let us know by being
the squeaky wheel.

@item
@cindex @code{--fix_rec_dmn all}
Convert multiple record dimensions to fixed-size dimensions.
Many netCDF4 and @acronym{HDF5} datasets have multiple unlimited
dimensions.
Since a netCDF3 file may have at most one unlimited dimension, all but
possibly one unlimited dimension from the input file must be converted
to fixed-length dimensions prior to storing netCDF4 input as netCDF3
output.
By invoking @code{--fix_rec_dmn all} the user ensures the output file
will adhere to netCDF3 conventions and the user need not know the names
of the specific record dimensions to fix.
See @ref{ncks netCDF Kitchen Sink} for a description of the
@samp{--fix_rec_dmn} option. 

@item
@cindex flattening
Flattening (removal) of groups.
Many netCDF4 and @acronym{HDF5} datasets have group hierarchies.
Since a netCDF3 file may not have any groups, groups in the input file
must be removed.
This is also called ``flattening'' the hierarchical file.
See @ref{Group Path Editing} for a description of the @acronym{GPE}
option @samp{-G :} to flatten files.
@end enumerate

Putting the three algorithms together, one sees that the recipe to 
convert netCDF4 to netCDF4 becomes increasingly complex as the netCDF4
features in the input file become more elaborate:
@example
# Convert file with netCDF4 atomic types
ncks -3 in.nc4 out.nc3
# Convert file with multiple record dimensions + netCDF4 atomic types
ncks -3 --fix_rec_dmn=all in.nc4 out.nc3
# Convert file with groups, multiple record dimensions + netCDF4 atomic types
ncks -3 -G : --fix_rec_dmn=all in.nc4 out.nc3
@end example
Future versions of @acronym{NCO} may automatically invoke the record
dimension fixation and group flattening when converting to netCDF3
(rather than requiring it be specified manually).
If this feature would interest you, please let us know.

@html
<a name="lfs"></a> <!-- http://nco.sf.net/nco.html#lfs -->
@end html
@node Large File Support, Subsetting Files, File Formats and Conversion, Common features
@section Large File Support
@cindex LFS
@cindex Large File Support
@cartouche
Availability: All operators@*
Short options: none@*
Long options: none@*
@end cartouche
@acronym{NCO} has Large File Support (@acronym{LFS}), meaning that 
@acronym{NCO} can write files larger than @w{2 GB} on some 32-bit
operating systems with netCDF libraries earlier than @w{version 3.6}. 
If desired, LFS support must be configured when both netCDF and
@acronym{NCO} are installed.
netCDF @w{versions 3.6} and higher support 64-bit file addresses as part
of the netCDF standard.
We recommend that users ignore LFS support which is difficult to
configure and is implemented in @acronym{NCO} only to support netCDF
versions prior @w{to 3.6}.  
This obviates the need for configuring explicit LFS support in
applications (such as @acronym{NCO}) that now support 64-bit files   
directly through the netCDF interface.
See @ref{File Formats and Conversion} for instructions on accessing 
the different file formats, including 64-bit files, supported by the
modern netCDF interface. 

If you are still interested in explicit LFS support for netCDF versions
prior @w{to 3.6}, know that LFS support depends on a complex,
interlocking set of operating system  
@footnote{
Linux and @acronym{AIX} do support @acronym{LFS}.}
and netCDF support issues.
The netCDF LFS 
@uref{http://my.unidata.ucar.edu/content/software/netcdf/faq-lfs.html,FAQ}
describes the various file size limitations imposed by different
versions of the netCDF standard.
@acronym{NCO} and netCDF automatically attempt to configure LFS at
build time. 

@html
<a name="grp"></a> <!-- http://nco.sf.net/nco.html#grp -->
<a name="var"></a> <!-- http://nco.sf.net/nco.html#var -->
<a name="xcl"></a> <!-- http://nco.sf.net/nco.html#xcl -->
<a name="sbs"></a> <!-- http://nco.sf.net/nco.html#sbs -->
<a name="subset"></a> <!-- http://nco.sf.net/nco.html#subset -->
@end html
@node Subsetting Files, Subsetting Coordinate Variables, Large File Support, Common features
@section Subsetting Files
@cindex subsetting
@cindex union
@cindex intersection
@cindex exclusion
@cindex extraction
@cindex @code{-v @var{var}}
@cindex @code{--variable @var{var}}
@cindex @code{-g @var{grp}}
@cindex @code{--grp @var{grp}}
@cindex @code{--group @var{grp}}
@cindex @code{-x}
@cindex @code{--exclude}
@cindex @code{--xcl}
@cindex @code{--unn}
@cindex @code{--union}
@cartouche
Options @code{--unn}@*
Availability: @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@* 
Short options: @*
Long options: @samp{--unn} and @samp{--union}@*
Options @code{-g @var{grp}}@*
Availability: @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-g}@*
Long options: @samp{--grp} and @samp{--group}@*
Options @code{-v @var{var}} and @code{-x}@*
Availability: (@command{ncap2}), @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@*
Short options: @samp{-v}, @samp{-x}@*
Long options: @samp{--variable}, @samp{--exclude} or @samp{--xcl}@*
@end cartouche
Subsetting variables refers to explicitly specifying variables and
groups to be included or excluded from operator actions.
Subsetting is controlled by the @samp{-v @var{var}[,@dots{}]} and
@samp{-x} options for directly specifying variables.  
Specifying groups, whether in addition to or instead of variables,
is quite similar and is controlled by the @samp{-g @var{grp}[,@dots{}]}
and @samp{-x} options.
@w{A list} of variables or groups to extract is specified following the
@samp{-v} and @samp{-g} options, e.g., @samp{-v time,lat,lon} or
@samp{-g grp1,grp2}.
Both options may be specified simultaneously and @acronym{NCO} will
extract the intersection of the lists, i.e., only variables of the
specified names found in groups of the specified names.
The @samp{--unn} option causes @acronym{NCO} to extract the
union, rather than the intersection, of the specified groups and
variables. 
Not using the @samp{-v} or @samp{-g} option is equivalent to specifying
all variables or groupp, respectively.  
The @samp{-x} option causes the list of variables specified with
@samp{-v} to be @emph{excluded} rather than @emph{extracted}.
Thus @samp{-x} saves typing when you only want to extract fewer than
half of the variables in a file.

Variables or groups explicitly specified for extraction with
@samp{-v @var{var}[,@dots{}]} or @samp{-g @var{grp}[,@dots{}]}
@emph{must} be present in the input file or an error will result.
Variables explicitly specified for @emph{exclusion} with
@samp{-x -v @var{var}[,@dots{}]} need not be present in the input
file.
To accord with the sophistication of the underlying hierarchy,
group subsetting is controlled by a few powerful yet subtle syntactical
distinctions.
When learning this syntax it is helpful to keep in mind the similarity
between group hierarchies and directory structures. 

@cindex @command{mv}
@cindex @command{cp}
@cindex recursion
@cindex recursive
@cindex anchor
@cindex anchoring
@html
<a name="rcr"></a> <!-- http://nco.sf.net/nco.html#rcr -->
<a name="recursion"></a> <!-- http://nco.sf.net/nco.html#recursion -->
<a name="recursive"></a> <!-- http://nco.sf.net/nco.html#recursive -->
<a name="ncr"></a> <!-- http://nco.sf.net/nco.html#ncr -->
<a name="anchor"></a> <!-- http://nco.sf.net/nco.html#anchor -->
<a name="anchoring"></a> <!-- http://nco.sf.net/nco.html#anchoring -->
@end html
Two properties of subsetting, recursion and anchoring, are best
illustrated by reminding the user of their @acronym{UNIX} equivalents.
The @acronym{UNIX} command @command{mv src dst} moves @file{src}
@emph{and all its subdirectories} (and all their subdirectories etc.)
to @file{dst}.
In other words @command{mv} is, by default, @emph{recursive}.
In contrast, the @acronym{UNIX} command @command{cp src dst} moves
@file{src}, and only @file{src}, to @file{dst},
If @file{src} is a directory, not a file, then that command fails.
One must explicitly request to copy directories recursively, i.e.,
with @command{cp -r src dst}.
In @acronym{NCO} recursive extraction (and copying) of groups is the
default (like with @command{mv}, not with @command{cp}).
Recursion is turned off by appending a trailing slash to the path.

These @acronym{UNIX} commands also illustrate a property we call
@emph{anchoring}. 
The command @command{mv src dst} moves (recursively) the source
directory @file{src} to the destination directory @file{dst}. 
If @file{src} begins with the slash character then the specified path is
relative to the root directory, otherwise the path is relative to the
current working directory. 
In other words, an initial slash character anchors the subsequent path
to the root directory.
In @acronym{NCO} an initial slash anchors the path at the root group.
Paths that begin and end with slash characters (e.g., @file{//},
@file{/g1/}, and @file{/g1/g2/}) are both anchored and non-recursive. 

Consider the following commands, all of which may be assumed to end with
@samp{in.nc out.nc}:
@example       
ncks -g  g1  # Extract, recursively, all groups with a g1 component
ncks -g  g1/ # Extract, non-recursively, all groups terminating in g1
ncks -g /g1  # Extract, recursively, root group g1
ncks -g /g1/ # Extract, non-recursively root group g1
ncks -g //   # Extract, non-recursively the root group
@end example
The first command is probably the most useful and common.
It would extract these groups, if present, and all their direct
ancestors and children:
@file{/g1}, @file{/g2/g1}, and @file{/g3/g1/g2}.
In other words, the simplest form of @samp{-g grp} grabs all groups that 
(and their direct ancestors and children, recursively) that have
@file{grp} as a complete component of their path.
A simple string match is insufficient, @var{grp} must be a complete 
component (i.e., group name) in the path.
The option @samp{-g g1} would not extract these groups because @file{g1} 
is not a complete component of the path: @file{/g12}, @file{/fg1}, and
@file{/g1g1}.
The second command above shows how a terminating slash character
@kbd{/} cancels the recursive copying of groups.
An argument to @samp{-g} which terminates with a slash character
extracts the group and its direct ancestors, but none of its children. 
The third command above shows how an initial slash character @kbd{/}
anchors the argument to the root group.
The third command would not extract the group @file{/g2/g1} because 
the @file{g1} group is not at the root level, but it would extract,
any group @file{/g1} at the root level and all its children,
recursively.  
The fourth command is the non-recursive version of the third command.
The fifth command is a special case of the fourth command.

@html
<a name="unn"></a> <!-- http://nco.sf.net/nco.html#unn -->
<a name="nsx"></a> <!-- http://nco.sf.net/nco.html#nsx -->
<a name="union"></a> <!-- http://nco.sf.net/nco.html#union -->
<a name="intersection"></a> <!-- http://nco.sf.net/nco.html#intersection -->
@end html
@cindex union
@cindex intersection
@cindex @code{--unn}
@cindex @code{--union}
@cindex @code{--nsx}
@cindex @code{--intersection}
As mentioned above, both @samp{-v} and @samp{-g} options may be
specified simultaneously and @acronym{NCO} will, by default, extract the
intersection of the lists, i.e., the specified variables found in the
specified groups
@footnote{
Intersection-mode can also be explicitly invoked with the @samp{--nsx}
or @samp{--intersection} switches.
These switches are supplied for clarity and consistency and do
absolutely nothing since intersection-mode is the default.}.
The @samp{--unn} option causes @acronym{NCO} to extract the
union, rather than the intersection, of the specified groups and
variables. 
Consider the following commands (which may be assumed to end with
@samp{in.nc out.nc}):
@example       
# Intersection-mode subsetting (default)
ncks -g  g1  -v v1 # Yes: /g1/v1, /g2/g1/v1. No: /v1, /g2/v1
ncks -g /g1  -v v1 # Yes: /g1/v1, /g1/g2/v1. No: /v1, /g2/v1, /g2/g1/v1
ncks -g  g1/ -v v1 # Yes: /g1/v1, /g2/g1/v1. No: /v1, /g2/v1, /g1/g2/v1
ncks -v  g1/v1     # Yes: /g1/v1, /g2/g1/v1. No: /v1, /g2/v1, /g1/g2/v1
ncks -g /g1/ -v v1 # Yes: /g1/v1. No: /g2/g1/v1, /v1, /g2/v1 ...
ncks -v /g1/v1     # Yes: /g1/v1. No: /g2/g1/v1, /v1, /g2/v1 ...

# Union-mode subsetting (invoke with --unn or --union)
ncks -g  g1  -v v1 --unn # All variables in  g1 or progeny, or named v1
ncks -g /g1  -v v1 --unn # All variables in /g1 or progeny, or named v1
ncks -g  g1/ -v v1 --unn # All variables in  g1 or named v1
ncks -g /g1/ -v v1 --unn # All variables in /g1 or named v1
@end example
The first command (@samp{-g g1 -v v1}) extracts the variable @file{v1}
from any group named @file{g1} or descendent @file{g1}.
The second command extracts @file{v1} from any root group
named @file{g1} and any descendent groups as well.
The third and fourth commands are equivalent ways of extracting
@file{v1} only from the root group named @file{g1} (not its
descendents). 
The fifth and sixth commands are equivalent ways of extracting the 
variable @file{v1} only from the root group named @file{g1}.
Subsetting in union-mode (with @samp{--unn}) causes all variables to be
extracted which meet either one or both of the specifications of the 
variable and group specifications.
Union-mode subsetting is simply the logical ``OR'' of intersection-mode
subsetting. 
As discussed below, the group and variable specifications may be comma
separated lists of regular expressions for added control over
subsetting. 

@cindex memory requirements
Remember, if averaging or concatenating large files stresses your
systems memory or disk resources, then the easiest solution is often to
subset (with @samp{-g} and/or @samp{-v}) to retain only the most
important variables (@pxref{Memory Requirements}).
@example       
ncks          in.nc out.nc # Extract all groups and variables
ncks -v scl   # Extract variable scl from all groups
ncks -g g1    # Extract group g1 and descendents
ncks -x -g g1 # Extract all groups except g1 and descendents
ncks -g g2,g3 -v scl # Extract scl from groups g2 and g3
@end example
Overwriting and appending work as expected:
@example
# Replace scl in group g2 in out.nc with scl from group g2 from in.nc
ncks -A -g g2 -v scl in.nc out.nc
@end example

Due to its special capabilities, @command{ncap2} interprets the
@samp{-v} switch differently 
(@pxref{ncap2 netCDF Arithmetic Processor}). 
For @command{ncap2}, the @samp{-v} switch takes no arguments and
indicates that @emph{only} user-defined variables should be output. 
@command{ncap2} neither accepts nor understands the @var{-x} and
@var{-g} switches.

@html
<a name="rx"></a> <!-- http://nco.sf.net/nco.html#rx -->
<a name="wildcarding"></a> <!-- http://nco.sf.net/nco.html#wildcarding -->
@end html
@cindex extended regular expressions
@cindex regular expressions
@cindex pattern matching
@cindex wildcards
@cindex @command{grep -E}
@cindex @command{egrep}
@cindex @command{ncatted}
@cindex @acronym{GNU}
Regular expressions the syntax that @acronym{NCO} use pattern-match
object names in netCDF file against user requests.
The user can select all variables beginning with the string @samp{DST}
from an input file by supplying the regular expression @samp{^DST} to
the @samp{-v} switch, i.e., @samp{-v '^DST'}. 
The meta-characters used to express pattern matching operations are
@samp{^$+?.*[]@{@}|}. 
If the regular expression pattern matches @emph{any} part of a variable 
name then that variable is selected.
This capability is also called @dfn{wildcarding}, and is very useful for 
sub-setting large data files.

Extended regular expressions are defined by the @acronym{POSIX}
@command{grep -E} (aka @command{egrep}) command.  
As of @acronym{NCO} 2.8.1 (August, 2003), variable name arguments
to the @samp{-v} switch may contain @dfn{extended regular expressions}.
As of @acronym{NCO} 3.9.6 (January, 2009), variable names arguments 
to @command{ncatted} may contain @dfn{extended regular expressions}. 
As of @acronym{NCO} 4.2.4 (November, 2012), group name arguments 
to the @samp{-g} switch may contain @dfn{extended regular expressions}.

@cindex @acronym{POSIX}
@cindex @code{regex}
Because of its wide availability, @acronym{NCO} uses the @acronym{POSIX}  
regular expression library @code{regex}.  
Regular expressions of arbitary complexity may be used.
Since netCDF variable names are relatively simple constructs, only a 
few varieties of variable wildcards are likely to be useful.
For convenience, we define the most useful pattern matching operators
here: 
@cindex @code{.} (wildcard character)
@cindex @code{$} (wildcard character)
@cindex @code{^} (wildcard character)
@cindex @code{?} (filename expansion)
@cindex @code{*} (filename expansion)
@table @samp
@item ^
Matches the beginning of a string
@item $
Matches the end of a string
@item .
Matches any single character
@end table
@noindent
The most useful repetition and combination operators are
@cindex @code{?} (wildcard character)
@cindex @code{*} (wildcard character)
@cindex @code{+} (wildcard character)
@cindex @code{|} (wildcard character)
@table @samp
@item ?
The preceding regular expression is optional and matched at most once
@item *
The preceding regular expression will be matched zero or more times
@item +
The preceding regular expression will be matched one or more times
@item |
The preceding regular expression will be joined to the following regular
expression.
The resulting regular expression matches any string matching either
subexpression. 
@end table
@noindent

To illustrate the use of these operators in extracting variables
and groups, consider file @file{in_grp.nc} with groups
@code{g0}--@code{g9}, and subgroups @code{s0}--@code{s9}, in each of
those groups, and file @file{in.nc} with variables @code{Q},
@code{Q01}--@code{Q99}, @code{Q100}, @code{QAA}--@code{QZZ},
@code{Q_H2O}, @code{X_H2O}, @code{Q_CO2}, @code{X_CO2}.  
@example
ncks -v '.+' in.nc               # All variables (default)
ncks -v 'Q.?' in.nc              # Variables that contain Q
ncks -v '^Q.?' in.nc             # Variables that start with Q
ncks -v '^Q+.?.' in.nc           # Q, Q0--Q9, Q01--Q99, QAA--QZZ, etc.
ncks -v '^Q..' in.nc             # Q01--Q99, QAA--QZZ, etc.
ncks -v '^Q[0-9][0-9]' in.nc     # Q01--Q99, Q100
ncks -v '^Q[[:digit:]]@{2@}' in.nc # Q01--Q99
ncks -v 'H2O$' in.nc             # Q_H2O, X_H2O 
ncks -v 'H2O$|CO2$' in.nc        # Q_H2O, X_H2O, Q_CO2, X_CO2 
ncks -v '^Q[0-9][0-9]$' in.nc    # Q01--Q99
ncks -v '^Q[0-6][0-9]|7[0-3]' in.nc # Q01--Q73, Q100
ncks -v '(Q[0-6][0-9]|7[0-3])$' in.nc # Q01--Q73
ncks -v '^[a-z]_[a-z]@{3@}$' in.nc # Q_H2O, X_H2O, Q_CO2, X_CO2
ncks -g 'g.' in_grp.nc           # 10 Groups g0-g9
ncks -g 's.' in_grp.nc       # 100 sub-groups g0/s0, g0/s1, ... g9/s9
ncks -g 'g.' -v 'v.' in_grp.nc   # All variables 'v.' in groups 'g.'
@end example
Beware---two of the most frequently used repetition pattern matching
operators, @samp{*} and @samp{?}, are also valid pattern matching
operators for filename expansion (globbing) at the shell-level.
Confusingly, their meanings in extended regular expressions and in
shell-level filename expansion are significantly different.
In an extended regular expression, @samp{*} matches zero or more
occurences of the preceding regular expression. 
Thus @samp{Q*} selects all variables, and @samp{Q+.*} selects all
variables containing @samp{Q} (the @samp{+} ensures the preceding item 
matches at least once).
To match zero or one occurence of the preceding regular expression,   
use @samp{?}.
Documentation for the @acronym{UNIX} @command{egrep} command details the
extended regular expressions which @acronym{NCO} supports.

@html
<a name="globbing"></a> <!-- http://nco.sf.net/nco.html#globbing -->
<a name="glb"></a> <!-- http://nco.sf.net/nco.html#glb -->
@end html
@cindex globbing
@cindex shell
@cindex @command{bash}
@cindex @command{csh}
@cindex quotes
One must be careful to protect any special characters in the regular
expression specification from being interpreted (globbed) by the shell.
This is accomplish by enclosing special characters within single or
double quotes
@example
ncra -v Q?? in.nc out.nc   # Error: Shell attempts to glob wildcards
ncra -v '^Q+..' in.nc out.nc # Correct: NCO interprets wildcards
ncra -v '^Q+..' in*.nc out.nc # Correct: NCO interprets, Shell globs 
@end example
The final example shows that commands may use a combination of variable
wildcarding and shell filename expansion (globbing).
For globbing, @samp{*} and @samp{?} @emph{have nothing to do} with the 
preceding regular expression!
In shell-level filename expansion, @samp{*} matches any string,
including the null string and @samp{?} matches any single character. 
Documentation for @command{bash} and @command{csh} describe the rules of
filename expansion (globbing).

@html
<a name="crd"></a> <!-- http://nco.sf.net/nco.html#crd -->
<a name="-C"></a> <!-- http://nco.sf.net/nco.html#-C -->
<a name="-c"></a> <!-- http://nco.sf.net/nco.html#-c -->
@end html
@node Subsetting Coordinate Variables, Group Path Editing, Subsetting Files, Common features
@section Subsetting Coordinate Variables
@cindex subsetting
@cindex @code{-C}
@cindex @code{-c}
@cindex @code{--no-coords}
@cindex @code{--no-crd}
@cindex @code{--coords}
@cindex @code{--crd}
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-C}, @samp{-c}@*
Long options: @samp{--no-coords}, @samp{--no-crd}, @samp{--crd}, @samp{--coords}@*
@end cartouche
By default, coordinates variables associated with any variable appearing
in the @var{input-file} will be placed in the @var{output-file}, even
if they are not explicitly specified, e.g., with the @samp{-v} switch.
Thus variables with a latitude coordinate @code{lat} always carry the
values of @code{lat} with them into the @var{output-file}.
This feature can be disabled with @samp{-C}, which causes @acronym{NCO}
to not automatically add coordinates to the variables appearing in the
@var{output-file}. 
However, using @samp{-C} does not preclude the user from including some
coordinates in the output files simply by explicitly selecting the
coordinates with the @var{-v} option.
The @samp{-c} option, on the other hand, is a shorthand way of
automatically specifying that @emph{all} coordinate variables in the
@var{input-files} should appear in the @var{output-file}.
Thus @samp{-c} allows the user to select all the coordinate variables
without having to know their names.
@cindex @acronym{CF} conventions
As of @acronym{NCO} version 3.9.6 (January, 2009) 
both @samp{-c} and @samp{-C} honor the @acronym{CF} @code{coordinates}
convention described in @ref{CF Conventions}.
As of @acronym{NCO} version 4.0.8 (April, 2011) 
both @samp{-c} and @samp{-C} honor the @acronym{CF} @code{bounds}
convention described in @ref{CF Conventions}. 

@html
<a name="gpe"></a> <!-- http://nco.sf.net/nco.html#gpe -->
@end html
@node Group Path Editing, C and Fortran Index Conventions, Subsetting Coordinate Variables, Common features
@section Group Path Editing
@cindex @code{-G @var{gpe_dsc}}
@cindex @code{--gpe @var{gpe_dsc}}
@cartouche
Options @code{-G @var{gpe_dsc}}@*
Availability: @command{ncbo}, @command{ncecat}, @command{nces},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}, @command{ncwa}@*
Short options: @samp{-G}@*
Long options: @samp{--gpe}@*
@end cartouche

@dfn{Group Path Editing}, or @acronym{GPE}, allows the user to
restructure (i.e., add, remove, and rename groups) in the output file 
relative to the input file based on the instructions they provide.
As of  @acronym{NCO} 4.2.3 (November, 2012), all operators that accept  
netCDF4 files with groups accept the @samp{-G} switch, or its
long-option equivalent @samp{--gpe}.
To master @acronym{GPE} one must understand the meaning of the
required @var{gpe_dsc} structure/argument that specifies the
transformation of input-to-output group paths.

Each @var{gpe_dsc} contains up to three elements (two are optional) in
the following order:@*   
@var{gpe_dsc} = @var{grp_pth}:@var{lvl_nbr} or @var{grp_pth}@@@var{lvl_nbr}

@table @var
@item grp_pth
Group Path.
@cindex group path
This (optional) component specifies the output group path that should be 
appended after any editing (i.e., deletion or truncation) of the input
path is performed.
@item lvl_nbr
The number of levels to delete (from the head) or truncate (from the
tail) of the input path.
@end table
@noindent
If both components of the argument are present, then a single character,
either the colon or at-sign (@code{:} or @code{@@}), must separate them.
If only @var{grp_pth} is specifed, the separator character may be
omitted, e.g., @samp{-G g1}.
If only @var{lvl_nbr} is specifed, the separator character is still
required to indicate it is a @var{lvl_nbr} arugment and not a
@var{grp_pth}, e.g., @samp{-G :-1} or @samp{-G @@1}.

If the at-sign separator character @code{@@} is used instead of the colon
separator character @code{:}, then the following @var{lvl_nbr} arugment 
must be positive and it will be assumed to refer to Truncation-Mode.
Hence, @samp{-G :-1} is the same as @samp{-G @@1}. 
This is simply a way of making the @var{lvl_nbr} argument
positive-definite. 

@html
<a name="flatten"></a> <!-- http://nco.sf.net/nco.html#flatten -->
<a name="delete"></a> <!-- http://nco.sf.net/nco.html#delete -->
<a name="truncate"></a> <!-- http://nco.sf.net/nco.html#truncate -->
@end html
@cindex @code{@@} (separator character)
@cindex @code{:} (separator character)
@cindex delete (groups)
@cindex truncate (groups)
@cindex flatten (groups)
@acronym{GPE} has three editing modes: Delete, Truncate, and
Flatten.
Select one of @acronym{GPE}'s three editing modes by supplying a
@var{lvl_nbr} that is positive, negative, or zero for Delete-, 
Truncate- and Flatten-mode, respectively. 

In Delete-mode, @var{lvl_nbr} is a positive integer which specifies
the maximum number of group path components (i.e., groups) that
@acronym{GPE} will try to delete from the head of @var{grp_pth}. 
For example @math{@var{lvl_nbr} = 3} changes the input path
@file{/g1/g2/g3/g4/g5} to the output path @file{/g4/g5}.
Input paths with @var{lvl_nbr} or fewer components (groups)
are completely erased and the output path commences from the root  
level. 

In other words, @acronym{GPE} is tolerant of specifying too many group
components to delete. 
It deletes as many as possible, without complaint, and then begins to
flatten the file (which will fail if namespace conflicts arise).

In Truncate-mode, @var{lvl_nbr} is a negative integer which specifies
the maximum number of group path components (i.e., groups) that
@acronym{GPE} will try to truncate from the tail of @var{grp_pth}. 
For example @math{@var{lvl_nbr} = -3} changes the input path
@file{/g1/g2/g3/g4/g5} to the output path @file{/g1/g2}.
Input paths with @var{lvl_nbr} or fewer components (groups)
are completely erased and the output path commences from the root  
level. 

In Flatten-mode, indicated by the separator character alone
or with @math{@var{lvl_nbr} = 0}, @acronym{GPE} removes the entire group
path from the input file and constructs the output path beginning at the
root level.  
For example @code{-G :0} and @code{-G :} are identical and change the
input path @file{/g1/g2/g3/g4/g5} to the output path @file{/} whereas
@code{-G g1:0} and @code{-G g1:} are identical and result in the output 
path @file{/g1} for all variables.

Subsequent to the alteration of the input path by the specified
editing mode, if any, @acronym{GPE} prepends (in Delete Mode)
or Appends (in Truncate-mode) any specifed @var{grp_pth} to the output
path. 
For example @code{-G g2} changes the input paths @file{/} and @file{/g1}
to @file{/g2} and @file{/g1/g2}, respectively.
Likewise, @code{-G g2/g3} changes the input paths @file{/} and @file{/g1}
to @file{/g2/g3} and @file{/g1/g2/g3}, respectively.
When @var{grp_pth} and @var{lvl_nbr} are both specified, the editing
actions are taken in sequence so that, e.g., @code{-G g1/g2:2} 
changes the input paths @file{/} and @file{/h1/h2/h3/h4}
to @file{/g1/g2} and @file{/g1/g2/h3/h4}, respectively.
Likewise, @code{-G g1/g2:-2} changes the input paths @file{/} and
@file{/h1/h2/h3/h4} to @file{/g1/g2} and @file{/h1/h2/g1/g2},
respectively. 

Combining @acronym{GPE} with subsetting (@pxref{Subsetting Files}) 
yields powerful control over the extracted (or excluded) variables and
groups and their placement in the output file as shown by the following
commands. 
All commands below may be assumed to end with @samp{in.nc out.nc}.
@example       
# Prepending paths without editing:
ncks                   # /g?/v? -> /g?/v?
ncks             -v v1 # /g?/v1 -> /g?/v1
ncks       -g g1       # /g1/v? -> /g1/v?
ncks -G o1             # /g?/v? -> /o1/g?/v?
ncks -G o1 -g g1       # /g1/v? -> /o1/g1/v?
ncks       -g g1 -v v1 # /g1/v1 -> /g1/v1
ncks -G o1       -v v1 # /g?/v1 -> /o1/g?/v1
ncks -G o1 -g g1 -v v1 # /g1/v1 -> /o1/g1/v1
ncks -G g1 -g /  -v v1 # /v1    -> /g1/v1
ncks -G g1/g2    -v v1 # /g?/v1 -> /g1/g2/g?/v1
# Delete-mode: Delete from and Prepend to path head
# Syntax: -G [ppn]:lvl_nbr = # of levels to delete
ncks -G :1    -g g1    -v v1 # /g1/v1    -> /v1
ncks -G :1    -g g1/g1 -v v1 # /g1/g1/v1 -> /g1/v1
ncks -G :2    -g g1/g1 -v v1 # /g1/g1/v1 -> /v1
ncks -G :2    -g g1    -v v1 # /g1/v1    -> /v1
ncks -G g2:1  -g g1    -v v1 # /g1/v1    -> /g2/v1
ncks -G g2:2  -g g1/g1 -v v1 # /g1/g1/v1 -> /g2/v1
ncks -G g2:1  -g /     -v v1 # /v1       -> /g2/v1
ncks -G g2:1           -v v1 # /v1       -> /g2/v1
ncks -G g2:1  -g g1/g1 -v v1 # /g1/g1/v1 -> /g2/g1/v1
# Flatten-mode: Remove all input path components
# Syntax: -G [apn]: colon without numerical argument
ncks -G :            -v v1 # /g?/v1    -> /v1
ncks -G :   -g g1    -v v1 # /g1/v1    -> /v1
ncks -G :   -g g1/g1 -v v1 # /g1/g1/v1 -> /v1
ncks -G g2:          -v v1 # /g?/v1    -> /g2/v1
ncks -G g2:                # /g?/v?    -> /g2/v?
ncks -G g2: -g g1/g1 -v v1 # /g1/g1/v1 -> /g2/v1
# Truncate-mode: Truncate from and Append to path tail
# Syntax: -G [apn]:-lvl_nbr = # of levels to truncate
# NB: -G [apn]:-lvl_nbr is equivalent to -G [apn]@@lvl_nbr
ncks -G :-1   -g g1    -v v1 # /g1/v1    -> /v1
ncks -G :-1   -g g1/g2 -v v1 # /g1/g2/v1 -> /g1/v1
ncks -G :-2   -g g1/g2 -v v1 # /g1/g2/v1 -> /v1
ncks -G :-2   -g g1    -v v1 # /g1/v1    -> /v1
ncks -G g2:-1          -v v1 # /g?/v1    -> /g2/v1
ncks -G g2:-1 -g g1    -v v1 # /g1/v1    -> /g2/v1
ncks -G g1:-1 -g g1/g2 -v v1 # /g1/g2/v1 -> /g1/g1/v1
@end example

@html
<a name="mv"></a> <!-- http://nco.sf.net/nco.html#mv -->
<a name="move"></a> <!-- http://nco.sf.net/nco.html#move -->
@end html
@cindex move groups
@cindex groups, moving
@cindex rename groups
@cindex groups, renaming
Until fall 2013 (netCDF version 4.3.1-pre1), netCDF contained no library
function for renaming groups, and therefore @command{ncrename} cannot
rename groups.
However, @acronym{NCO} built on earlier versions of netCDF than 4.3.1
can use a @acronym{GPE}-based workaround mechanism to ``rename''
groups. 
The @acronym{GPE} mechanism actually @emph{moves} (i.e., copies to a new
location) groups, a more arduous procedure than simply renaming them.
@acronym{GPE} applies to all selected groups, so, in the general case,
one must move only the desired group to a new file, and then merge that
new file with the original to obtain a file where the desired group has
been ``renamed'' and all else is unchanged.
Here is how to ``rename'' group @file{/g4} to group @file{/f4} with
@acronym{GPE} instead of @command{ncrename}
@example
ncks -O -G f4:1 -g g4 ~/nco/data/in_grp.nc ~/tmp.nc # Move /g4 to /f4
ncks -O -x -g g4 ~/nco/data/in_grp.nc ~/out.nc # Excise /g4
ncks -A ~/tmp.nc ~/out.nc # Add /f4 to new file
@end example
If the original group @file{g4} is not excised from @file{out.nc} (step
two above), then the final output file would contain both @file{g4} and
a copy named @file{f4}.
Thus GPE can be used to both ``rename'' and copy groups.
The recommended way to rename groups when when netCDF version 4.3.1 is
availale is to use @command{ncrename} (@pxref{ncrename netCDF Renamer}).

@html
<a name="xmp_flt"></a> <!-- http://nco.sf.net/nco.html#xmp_flt -->
@end html
One may wish to flatten hierarchical group files for many reasons.
These include @w{1. Obtaining} flat netCDF3 files for use with tools
that do not work with netCDF4 files, @w{2. Splitting} apart
hierarchies to re-assemble into different hierarchies, and
@w{3. Providing} a subset of a hierarchical file with the simplest
possible storage structure.
@example
ncks -O -G : -g cesm -3 ~/nco/data/cmip5.nc ~/cesm.nc # Extract /cesm to /
@end example
The @option{-3} switch
@footnote{Note that the @option{-3} switch should appear @emph{after} the
@option{-G} and @option{-g} switches. 
This is due to an artifact of the @acronym{GPE} implementation which we
wish to remove in the future.}
specifies the output dataset should be in netCDF3
format, the @option{-G :} option flattens all extracted groups, and the
@option{-g cesm} option extracts only the @code{cesm} group and leaves
all other groups (e.g., @code{ecmwf}, @code{giss}).

@html
<a name="dismember"></a> <!-- http://nco.sf.net/nco.html#dismember -->
<a name="disaggregate"></a> <!-- http://nco.sf.net/nco.html#disaggregate -->
<a name="ncdismember"></a> <!-- http://nco.sf.net/nco.html#ncdismember -->
@end html
@cindex disaggregate
@cindex dismember
@findex ncdismember
Let us show how to completely disaggregate (or, more memorably)
@emph{dismember} a hierarchical dataset.
For now we take this to mean: store each group as a standalone flat
dataset in netCDF3 format.
This can be accomplished by looping the previous example over all
groups. 
This script @file{ncdismember} dismembers the input file @var{fl_in}
specified in the first argument and places the resulting files in the
directory @var{drc_out} specified by the second argument:
@example
@verbatim
cat > ~/ncdismember << 'EOF'
# Purpose: Dismember netCDF4/HDF5 hierarchical files. CF-check them.
# Place each input file group in separate netCDF3 output file
# Described in NCO User Guide at http://nco.sf.net/nco.html#dismember
# Requirements: NCO 4.3.x+, UNIX shell utilities awk, grep, sed
# Optional: CFchecker command https://bitbucket.org/mde_/cfchecker

# Usage:
# ncdismember <fl_in> <drc_out> [flg_cf] [cf_vrs] [opt]
# where fl_in is input file/URL to dismember, drc_out is output directory,
# CF-compliance check is performed when optional third argument is 'cf',
# Optional fourth argument cf_vrs is CF version to check
# Optional fifth argument opt passes straight through to ncks
# chmod a+x ~/sh/ncdismember
# ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp
# ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp
# ncdismember http://dust.ess.uci.edu/nco/mdl.nc /data/zender/nco/tmp
# ncdismember http://thredds-test.ucar.edu/thredds/dodsC/testdods/foo.nc /data/zender/nco/tmp
# ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp cf
# ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp cf 1.3
# ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp cf 1.5 --fix_rec_dmn=all

# Command line argument defaults
fl_in="${HOME}/nco/data/mdl.nc" # [sng] Input file to dismember/check
drc_out="${DATA}/nco/tmp" # [sng] Output directory
flg_cf='0' # [flg] Perform CF-compliance check
cf_vrs='1.5' # [sng] Compliance-check this CF version (e.g., '1.5')
opt='' # [flg] Additional ncks options (e.g., '--fix_rec_dmn=all')

# Command line argument option parsing
if [ -n "${1}" ]; then fl_in=${1}; fi
if [ -n "${2}" ]; then drc_out=${2}; fi
if [ -n "${3}" ]; then flg_cf=${3}; fi
if [ -n "${4}" ]; then cf_vrs=${4}; fi
if [ -n "${5}" ]; then opt=${5}; fi

# Prepare output directory
echo "NCO dismembering file ${fl_in}"
fl_stb=$(basename ${fl_in})
drc_out=${drc_out}/${fl_stb}
mkdir -p ${drc_out}
cd ${drc_out}
# Obtain group list
grp_lst=`ncks --cdl -m ${fl_in} | grep '// group' | awk '{$1=$2=$3="";sub(/^  */,"",$0);print}'`
IFS=$'\n' # Change Internal-Field-Separator from <Space><Tab><Newline> to <Newline>
for grp_in in ${grp_lst} ; do
    # Replace slashes by dots for output group filenames
    grp_out=`echo ${grp_in} | sed 's/\///' | sed 's/\//./g'`
    if [ "${grp_out}" = '' ]; then grp_out='root' ; fi
    # Tell older NCO/netCDF if HDF4 with --hdf4 switch (signified by .hdf/.HDF suffix)
    hdf4=`echo ${fl_in} | awk '{if(match(tolower($1),".hdf$")) hdf4="--hdf4"; print hdf4}'`
    # Flatten to netCDF3, anchor, no history, no temporary file, padding, HDF4 flag, options
    ncks -O -3 -G : -g ${grp_in}/ -h --no_tmp_fl --hdr_pad=40 ${hdf4} ${opt} ${fl_in} ${drc_out}/${grp_out}.nc
    if [ ${flg_cf} = 'cf' ]; then
       # cfchecker needs Conventions <= 1.5
       ncatted -h -a Conventions,global,o,c,"CF-${cf_vrs}" ${drc_out}/${grp_out}.nc
    else # !flg_cf
       echo ${drc_out}/${grp_out}.nc
    fi # !flg_cf
done
if [ ${flg_cf} = 'cf' ]; then
    echo "CFchecker reports CF-compliance of each group in flat netCDF3 format"
    cfchecker -c ${cf_vrs} *.nc
fi # !flg_cf
EOF
chmod 755 ~/ncdismember # Make command executable
/bin/mv -f ~/ncdismember ~/sh # Store in location on $PATH, e.g., /usr/local/bin

zender@roulee:~$ ncdismember ~/nco/data/mdl.nc ${DATA}/nco/tmp
NCO dismembering file /home/zender/nco/data/mdl.nc
/data/zender/nco/tmp/mdl.nc/cesm.cesm_01.nc
/data/zender/nco/tmp/mdl.nc/cesm.cesm_02.nc
/data/zender/nco/tmp/mdl.nc/cesm.nc
/data/zender/nco/tmp/mdl.nc/ecmwf.ecmwf_01.nc
/data/zender/nco/tmp/mdl.nc/ecmwf.ecmwf_02.nc
/data/zender/nco/tmp/mdl.nc/ecmwf.nc
/data/zender/nco/tmp/mdl.nc/root.nc
@end verbatim
@end example
A (potentially more portable) binary executable could be written to
dismember all groups with a single invocation, yet dismembering without
loss of information is possible now with this simple script on all 
platforms with UNIXy utilities.
Note that all dimensions inherited by groups in the input file are
correctly placed by @command{ncdismember} into the flat files.
Moreover, each output file preserves the group metadata of all ancestor
groups, including the global metadata from the input file.
As written, the script could fail on groups that contain advanced
netCDF4 features because the user requests (with the @samp{-3} switch)
that output be netCDF3 classic format.  
However, @command{ncks} detects many format incompatibilities in advance
and works around them.
For example, @command{ncks} autoconverts netCDF4-only atomic-types (such
as @code{NC_STRING} and @code{NC_UBYTE}) to corresponding netCDF3
atomic types (@code{NC_CHAR} and @code{NC_SHORT}) when the output format
is netCDF3. 

@cindex @acronym{CF} compliance checker
@findex cfchecker
@findex ncdismember
@cindex compliance checker
@cindex Martin Schultz
@cindex Michael Decker
One application of dismembering is to check the @acronym{CF}-compliance of each 
group in a file. 
When invoked with the optional third argumnt @samp{cf},
@command{ncdismember} passes each file it generates to the freely
available
@footnote{CFchecker is developed by Michael Decker and Martin Schultz at
Forschungszentrum J@"ulich and distributed at
@uref{https://bitbucket.org/mde_/cfchecker}.} 
@command{cfchecker} command.
@example
@verbatim
zender@roulee:~$ ncdismember ~/nco/data/mdl.nc /data/zender/nco/tmp cf
NCO dismembering file /home/zender/nco/data/mdl.nc
CFchecker reports CF-compliance of each group in flat netCDF3 format
WARNING: Using the default (non-CF) Udunits database
cesm.cesm_01.nc: 
INFO: INIT:     running CFchecker version 1.5.15
INFO: INIT:     checking compliance with convention CF-1.5
INFO: INIT:     using standard name table version: 25, last modified: 2013-07-05T05:40:30Z
INFO: INIT:     using area type table version: 2, date: 10 July 2013
INFO: 2.4:      no axis information found in dimension variables, not checking dimension order
WARNING: 3:     variable "tas1" contains neither long_name nor standard_name attribute
WARNING: 3:     variable "tas2" contains neither long_name nor standard_name attribute
INFO: 3.1:      variable "tas1" does not contain units attribute
INFO: 3.1:      variable "tas2" does not contain units attribute
--------------------------------------------------
cesm.cesm_02.nc: 
...
@end verbatim
@end example
By default the @acronym{CF} version checked is determined automatically by
@command{cfchecker}. 
The user can override this default by supplying a supported @acronym{CF} version,
e.g., @samp{1.3}, as an optional fourth argument to
@command{ncdismember}. 
Current valid @acronym{CF} options are @samp{1.0}, @samp{1.1},
@samp{1.2}, @samp{1.3}, @samp{1.4}, and @samp{1.5}. 

@html
<a name="diwg"></a> <!-- http://nco.sf.net/nco.html#diwg -->
@end html
Our development and testing of @command{ncdismember} is funded by our
involvement in @acronym{NASA}'s Dataset Interoperability Working Group 
(@uref{https://wiki.earthdata.nasa.gov/display/ESDSWG/Dataset+Interoperability+Working+Group,
DIWG}), though our interest extends beyond @acronym{NASA} datasets.
Taken together, @acronym{NCO}'s features (autoconversion to netCDF3  
atomic types, fixing multiple record dimensions, autosensing
@acronym{HDF4} input, scoping rules for CF conventions) make 
@command{ncdismember} reliable and friendly for both dismembering 
hierarchical files and for @acronym{CF}-compliance checks. 
Most @acronym{HDF4} and @acronym{HDF5} datasets can be checked for 
@acronym{CF}-compliance with a one-line command. 
Example compliance checks of common @acronym{NASA} datasets are at
@uref{http://dust.ess.uci.edu/diwg}.
Our long-term goal is to enrich the hierarchical data model with the 
expressivity and syntactic power of @acronym{CF} conventions.

@acronym{NASA} asked the @acronym{DIWG} to prepare a one-page summary
of the procedure necessary to check @acronym{HDF} files for
@acronym{CF}-compliance: 
@example
@verbatim
cat > ~/ncdismember.txt << 'EOF'
    Preparing an RPM-based OS to Test Hierarchical Files for CF-Compliance

By Charlie Zender, UCI & NASA Dataset Interoperability Working Group (DIWG)

Installation Summary:
1. HDF4 [with netCDF support _disabled_]
2. HDF5
3. netCDF version 4.3.1 (or later) [with HDF4 support _enabled_]
4. NCO version 4.4.0 (or later)
5. numpy
6. netcdf4-python
7. python-lxml
8. CFunits-python
9. CFChecker
10. ncdismember

All 10 packages can use default installs _except_ HDF4 and netCDF.
Following instructions for Fedora Core 20 (FC20), an RPM-based Linux OS
Feedback and changes for other Linux-based OS's welcome to zender at uci.edu
${H4DIR}, ${H5DIR}, ${NETCDFDIR}, ${NCODIR}, may all be different
For simplicity CZ sets them all to /usr/local

# 1. HDF4. Build in non-default manner. Turn-off its own netCDF support.
# Per http://www.unidata.ucar.edu/software/netcdf/docs/build_hdf4.html
# HDF4 support not necessary though it makes ncdismember more comprehensive
wget -c http://www.hdfgroup.org/ftp/HDF/HDF_Current/src/hdf-4.2.9.tar.gz
tar xvzf hdf-4.2.9.tar.gz
cd hdf-4.2.9
./configure --enable-shared --disable-netcdf --disable-fortran --prefix=${H4DIR}
make && make check && make install

# 2. HDF5. Build normally. RPM may work too. Please let me know if so.
# HDF5 is a necessary pre-requisite for netCDF4
wget -c ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf-4/hdf5-1.8.11.tar.gz
tar xvzf hdf5-1.8.11.tar.gz
cd hdf5-1.8.11
./configure --enable-shared --prefix=${H5DIR}
make && make check && make install

# 3. netCDF version 4.3.1. Build in non-default manner with HDF4. No RPM.
# Per http://www.unidata.ucar.edu/software/netcdf/docs/build_hdf4.html
# Earlier versions of netCDF may fail checking some HDF4 files
wget -c ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf-4.3.1.tar.gz
tar xvzf netcdf-4.3.1.tar.gz
cd netcdf-4.3.1
CPPFLAGS="-I${H5DIR}/include -I${H4DIR}/include" \
LDFLAGS="-L${H5DIR}/lib -L${H4DIR}/lib" \
./configure --enable-hdf4 --enable-hdf4-file-tests
make && make check && make installas

# 4. NCO version 4.4.2. No RPM for this version. Must install by hand.
# Earlier versions of NCO are relatively useless for ncdismember
cd ${DATA}/tmp
wget http://nco.sourceforge.net/src/nco-4.4.2.tar.gz .
tar xvzf nco-4.4.2.tar.gz
cd nco-4.4.2
./configure --prefix=${NCODIR}
make && make install

# 5. numpy
sudo yum install numpy -y

# 6. netcdf4-python
sudo yum install netcdf4-python -y

# 7. python-lxml
sudo yum install python-lxml -y

# 8. CFunits-python. No RPM available. Must install by hand.
# http://code.google.com/p/cfunits-python/
cd ${DATA}/tmp
wget http://cfunits-python.googlecode.com/files/cfunits-0.9.6.tar.gz .
cd cfunits-0.9.6
sudo python setup.py install

# 9. CFChecker. No RPM available. Must install by hand.
# https://bitbucket.org/mde_/cfchecker
cd ${DATA}/tmp
wget https://bitbucket.org/mde_/cfchecker/downloads/CFchecker-1.5.15.tar.bz2 . 
tar xvjf CFchecker-1.5.15.tar.bz2 
cd CFchecker
sudo python setup.py install

# 10. ncdismember. Copy script from http://nco.sf.net/nco.html#ncdismember
# Store dismembered files somewhere, e.g., ${DATA}/nco/tmp/hdf
mkdir -p ${DATA}/nco/tmp/hdf
# Many datasets work with a simpler command...
ncdismember ~/nco/data/in.nc ${DATA}/nco/tmp/hdf cf 1.5
ncdismember ~/nco/data/mdl.nc ${DATA}/nco/tmp/hdf cf 1.5
ncdismember ${DATA}/hdf/AMSR_E_L2_Rain_V10_200905312326_A.hdf \
            ${DATA}/nco/tmp/hdf cf 1.5
ncdismember ${DATA}/hdf/BUV-Nimbus04_L3zm_v01-00-2012m0203t144121.h5 \
            ${DATA}/nco/tmp/hdf cf 1.5
ncdismember ${DATA}/hdf/HIRDLS-Aura_L3ZAD_v06-00-00-c02_2005d022-2008d077.he5 ${DATA}/nco/tmp/hdf cf 1.5
# Some datasets, typically .h5, require the --fix_rec_dmn=all argument
ncdismember_${DATA}/hdf/GATMO_npp_d20100906_t1935191_e1935505_b00012_c20110707155932065809_noaa_ops.h5 ${DATA}/nco/tmp/hdf cf 1.5 --fix_rec_dmn=all
ncdismember ${DATA}/hdf/mabel_l2_20130927t201800_008_1.h5 \
            ${DATA}/nco/tmp/hdf cf 1.5 --fix_rec_dmn=all
EOF
@end verbatim
@end example
@c scp ~/ncdismember.pdf dust.ess.uci.edu:/var/www/html/diwg
A @acronym{PDF} version of these instructions is available
@uref{http://dust.ess.uci.edu/diwg/ncdismember.pdf, here}.

@html
<a name="ftn"></a> <!-- http://nco.sf.net/nco.html#ftn -->
<a name="-F"></a> <!-- http://nco.sf.net/nco.html#-F -->
@end html
@node C and Fortran Index Conventions, Hyperslabs, Group Path Editing, Common features
@section C and Fortran Index conventions
@cindex index convention
@cindex Fortran index convention
@cindex C index convention
@cindex @code{-F}
@cindex @code{--fortran}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-F}@*
Long options: @samp{--fortran}@*
@end cartouche
@cindex I/O
The @samp{-F} switch changes @acronym{NCO} to read and write with
the Fortran index convention. 
By default, @acronym{NCO} uses C-style (0-based) indices for all I/O. 
@w{In C}, indices count @w{from 0} (rather @w{than 1}), and
dimensions are ordered from slowest (inner-most) to fastest
(outer-most) varying.
In Fortran, indices count @w{from 1} (rather @w{than 0}), and
dimensions are ordered from fastest (inner-most) to slowest 
(outer-most) varying.  
@cindex transpose
Hence @w{C and} Fortran data storage conventions represent mathematical
transposes of eachother.
@cindex record variable
Note that record variables contain the record dimension as the most
slowly varying dimension.  
See @ref{ncpdq netCDF Permute Dimensions Quickly} for techniques
to re-order (including transpose) dimensions and to reverse data
storage order.

@cindex record dimension
Consider a file @file{85.nc} containing @w{12 months} of data in the
record dimension @code{time}.
The following hyperslab operations produce identical results, a
June-July-August average of the data:
@example
ncra -d time,5,7 85.nc 85_JJA.nc
ncra -F -d time,6,8 85.nc 85_JJA.nc
@end example

Printing variable @var{three_dmn_var} in file @file{in.nc} first with
the @w{C indexing} convention, then with Fortran indexing convention
results in the following output formats: 
@example
% ncks -v three_dmn_var in.nc
lat[0]=-90 lev[0]=1000 lon[0]=-180 three_dmn_var[0]=0 
...
% ncks -F -v three_dmn_var in.nc
lon(1)=0 lev(1)=100 lat(1)=-90 three_dmn_var(1)=0 
...
@end example

@html
<a name="-d"></a> <!-- http://nco.sf.net/nco.html#-d -->
<a name="dmn"></a> <!-- http://nco.sf.net/nco.html#dmn -->
<a name="hyp"></a> <!-- http://nco.sf.net/nco.html#hyp -->
<a name="hyperslab"></a> <!-- http://nco.sf.net/nco.html#hyperslab -->
@end html
@node Hyperslabs, Stride, C and Fortran Index Conventions, Common features
@section Hyperslabs 
@cindex hyperslab
@cindex dimension limits
@cindex coordinate limits
@cindex @code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
Long options: 
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]},@* 
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
@end cartouche
@w{A @dfn{hyperslab}} is a subset of a variable's data.
The coordinates of a hyperslab are specified with the 
@code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]} short
option (or with the same arguments to the @samp{--dimension} or
@samp{--dmn} long options).   
At least one hyperslab argument (@var{min}, @var{max}, or @var{stride})
must be present. 
The bounds of the hyperslab to be extracted are specified by the
associated @var{min} and @var{max} values. 
@w{A half}-open range is specified by omitting either the @var{min} or
@var{max} parameter.
The separating comma must be present to indicate the omission of one of
these arguments.
The unspecified limit is interpreted as the maximum or minimum value in 
the unspecified direction.  
@w{A cross}-section at a specific coordinate is extracted by specifying only
the @var{min} limit and omitting a trailing comma. 
Dimensions not mentioned are passed with no reduction in range.
The dimensionality of variables is not reduced (in the case of a
cross-section, the size of the constant dimension will be one). 
@example
# First and second indices of lon dimension
ncks -F -d lon,1,2 in.nc out.nc
# Second and third indices of lon dimension
ncks -d lon,1,2 in.nc out.nc
@end example

@cindex stride
Coordinate values should be specified using real notation with a decimal 
point required in the value, whereas dimension indices are specified
using integer notation without a decimal point. 
This convention serves only to differentiate coordinate values from
dimension indices.
It is independent of the type of any netCDF coordinate variables.
For a given dimension, the specified limits must both be coordinate
values (with decimal points) or dimension indices (no decimal points).

If values of a coordinate-variable are used to specify a range or
cross-section, then the coordinate variable must be monotonic (values
either increasing or decreasing). 
In this case, command-line values need not exactly match coordinate
values for the specified dimension. 
Ranges are determined by seeking the first coordinate value to occur in
the closed range [@var{min},@var{max}] and including all subsequent
values until one falls outside the range. 
The coordinate value for a cross-section is the coordinate-variable
value closest to the specified value and must lie within the range or
coordinate-variable values. 
The @var{stride} argument, if any, must be a dimension index, not a
coordinate value.
@xref{Stride}, for more information on the @var{stride} option.
@example
# All longitude values between 1 and 2 degrees
ncks -d lon,1.0,2.0 in.nc out.nc
# All longitude values between 1 and 2 degrees
ncks -F -d lon,1.0,2.0 in.nc out.nc
# Every other longitude value between 0 and 90 degrees
ncks -F -d lon,0.0,90.0,2 in.nc out.nc
@end example

As of version 4.2.1 (August, 2012), @acronym{NCO} allows one to extract
the last @var{N} elements of a hyperslab.
Negative integers as @var{min} or @var{max} elements of a hyperslab
specification indicate offsets from the end (Python also uses this
convention). 
Previously, for example, @samp{-d time,-2,-1} caused a domain error. 
Now it means select the second-to-last and penultimate timesteps.
Negative integers work for @var{min} and @var{max} indices, though not
for @var{stride}. 
@example
# Last two indices of lon dimension
ncks -F -d lon,1,-2 in.nc out.nc
# First to penultimate indices of lon dimension
ncks -F -d lon,1,-2 in.nc out.nc
# Third-to-last to last index of lon dimension
ncks -F -d lon,-3,-1 in.nc out.nc
# Third-to-last to last index of lon dimension
ncks -F -d lon,-3, in.nc out.nc
@end example
@noindent
As shown, we recommend using a full floating point suffix of @code{.0}
instead of simply @code{.} in order to make obvious the selection of
hyperslab elements based on coordinate value rather than index.

@cindex @code{NC_CHAR}
User-specified coordinate limits are promoted to double-precision values 
while searching for the indices which bracket the range. 
Thus, hyperslabs on coordinates of type @code{NC_CHAR} are computed
numerically rather than lexically, so the results are unpredictable. 

@cindex wrapped coordinates
The relative magnitude of @var{min} and @var{max} indicate to the
operator whether to expect a @dfn{wrapped coordinate}
(@pxref{Wrapped Coordinates}), such as longitude.
If @math{@var{min} > @var{max}}, the @acronym{NCO} expects the
coordinate to be wrapped, and a warning message will be printed.
When this occurs, @acronym{NCO} selects all values outside the domain
[@math{@var{max} < @var{min}}], i.e., all the values exclusive of the
values which would have been selected if @var{min} and @var{max} were
swapped. 
If this seems confusing, test your command on just the coordinate
variables with @command{ncks}, and then examine the output to ensure
@acronym{NCO} selected the hyperslab you expected (coordinate wrapping
is currently only supported by @command{ncks}). 

Because of the way wrapped coordinates are interpreted, it is very
important to make sure you always specify hyperslabs in the
monotonically increasing sense, i.e., @math{@var{min} < @var{max}}
(even if the underlying coordinate variable is monotonically
decreasing). 
The only exception to this is when you are indeed specifying a wrapped
coordinate.  
The distinction is crucial to understand because the points selected by, 
e.g., @code{-d longitude,50.,340.}, are exactly the complement of the
points selected by @code{-d longitude,340.,50.}.

Not specifying any hyperslab option is equivalent to specifying full
ranges of all dimensions. 
This option may be specified more than once in a single command 
(each hyperslabbed dimension requires its own @code{-d} option).

@html
<a name="srd"></a> <!-- http://nco.sf.net/nco.html#srd -->
<a name="stride"></a> <!-- http://nco.sf.net/nco.html#stride -->
@end html
@node Stride, Record Appending, Hyperslabs, Common features
@section Stride 
@cindex stride
@cindex @code{-d @var{dim},[@var{min}],[@var{max}],@var{stride}}
@cindex @code{--dimension @var{dim},[@var{min}],[@var{max}],@var{stride}}
@cindex @code{--dmn @var{dim},[@var{min}],[@var{max}],@var{stride}}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
Long options: 
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]},@* 
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
@end cartouche
All data operators support specifying a @dfn{stride} for any and all
dimensions at the same time.
The @var{stride} is the spacing between consecutive points in a
hyperslab. 
@w{A @var{stride}} @w{of 1} picks all the elements of the hyperslab, and
a @var{stride} @w{of 2} skips every other element, etc.@.
@command{ncks} multislabs support strides, and are more powerful than
the regular hyperslabs supported by the other operators
(@pxref{Multislabs}).
Using the @var{stride} option for the record dimension with
@command{ncra} and @command{ncrcat} makes it possible, for instance, to
average or concatenate regular intervals across multi-file input data sets.

The @var{stride} is specified as the optional fourth argument to the
@samp{-d} hyperslab specification:  
@code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}.
Specify @var{stride} as an integer (i.e., no decimal point) following
the third comma in the @samp{-d} argument.  
There is no default value for @var{stride}. 
Thus using @samp{-d time,,,2} is valid but @samp{-d time,,,2.0} and
@samp{-d time,,,} are not.
When @var{stride} is specified but @var{min} is not, there is an
ambiguity as to whether the extracted hyperslab should begin with (using
C-style, 0-based indexes) @w{element 0} or element @samp{stride-1}.
@acronym{NCO} must resolve this ambiguity and it chooses @w{element 0}
as the first element of the hyperslab when @var{min} is not specified.
Thus @samp{-d time,,,@var{stride}} is syntactically equivalent to
@samp{-d time,0,,@var{stride}}.
This means, for example, that specifying the operation 
@samp{-d time,,,2} on the array @samp{1,2,3,4,5} selects the hyperslab
@samp{1,3,5}. 
To obtain the hyperslab @samp{2,4} instead, simply explicitly specify
the starting index @w{as 1,} i.e., @samp{-d time,1,,2}. 

For example, consider a file @file{8501_8912.nc} which contains 60
consecutive months of data. 
Say you wish to obtain just the March data from this file.
Using 0-based subscripts (@pxref{C and Fortran Index Conventions}) these 
data are stored in records @w{2, 14, @dots{} 50} so the desired
@var{stride} @w{is 12.}
Without the @var{stride} option, the procedure is very awkward.
One could use @command{ncks} five times and then use @command{ncrcat} to  
concatenate the resulting files together:
@cindex Bourne Shell
@cindex C Shell
@example
for idx in 02 14 26 38 50; do # Bourne Shell
  ncks -d time,$@{idx@} 8501_8912.nc foo.$@{idx@}
done
foreach idx (02 14 26 38 50) # C Shell
  ncks -d time,$@{idx@} 8501_8912.nc foo.$@{idx@}
end
ncrcat foo.?? 8589_03.nc
rm foo.??
@end example
With the @var{stride} option, @command{ncks} performs this hyperslab
extraction in one operation:
@example
ncks -d time,2,,12 8501_8912.nc 8589_03.nc
@end example
@xref{ncks netCDF Kitchen Sink}, for more information on @command{ncks}.

Applying the @var{stride} option to the record dimension in
@command{ncra} and @command{ncrcat} makes it possible, for instance, to
average or concatenate regular intervals across multi-file input data
sets. 
@example
ncra -F -d time,3,,12 85.nc 86.nc 87.nc 88.nc 89.nc 8589_03.nc
ncrcat -F -d time,3,,12 85.nc 86.nc 87.nc 88.nc 89.nc 8503_8903.nc
@end example

@html
<a name="rec_apn"></a> <!-- http://nco.sf.net/nco.html#rec_apn -->
<a name="record_append"></a> <!-- http://nco.sf.net/nco.html#record_append -->
@end html
@node Record Appending, Subcycle, Stride, Common features
@section Record Appending
@cindex record append
@cindex @code{--rec_apn}
@cindex @code{--record_append}
@cartouche
Availability: @command{ncra}, @command{ncrcat}@* 
Short options: None@*
Long options: 
@samp{--rec_apn}, @samp{--record_append}@*
@end cartouche
As of version 4.2.6 (March, 2013), @acronym{NCO} allows both
Multi-File, Multi-Record operators (@command{ncra} and @command{ncrcat})
to append their output directly to the end of an existing file.
This feature may be used to augment a target file, rather than construct
it from scratch. 
This helps, for example, when a timeseries is concatenated from input
data that becomes available in stages rather than all at once.
In such cases this switch significantly speeds writing.

Consider the use case where one wishes to preserve the contents of
@file{fl_1.nc}, and add to them new records contained in
@file{fl_2.nc}. 
Previously the output had to be placed in a third file, @file{fl_3.nc}
(which could also safely be named @file{fl_2.nc}), via
@example
ncrcat -O fl_1.nc fl_2.nc fl_3.nc
@end example
Under the hood this operation copies all information in
@file{fl_1.nc} and @file{fl_2.nc} not once but twice.
The first copy is performed through the netCDF interface, as all
data from @file{fl_1.nc} and @file{fl_2.nc} are extracted and placed in
the output file.
The second copy occurs (usually much) more quickly as the (by default)
temporary output file is copied (sometimes a quick re-link suffices) to
the final output file (@pxref{Temporary Output Files}).
All this copying is expensive for large files. 

The new @samp{--record_append} switch causes all records in
@file{fl_2.nc} to be appended to the end of the corresponding records in
@file{fl_1.nc}: 
@example
ncrcat --rec_apn fl_2.nc fl_1.nc
@end example
The ordering of the filename arguments may seem non-intuitive.
If the record variable represents time in these files, then the
values in @file{fl_1.nc} precede those in @file{fl_2.nc}, so why
do the files appear in the reverse order on the command line?
@file{fl_1.nc} is the last file named because it is the pre-existing
output file to which we are appending all of the other input files
(in this case only @file{fl_2.nc}).
The contents of @file{fl_1.nc} are completely preserved, and only
values in @file{fl_2.nc} (and any other input files) are copied. 
This switch avoids the necessity of copying all of @file{fl_1.nc} 
through the netCDF interface to a new output file.
The @samp{--rec_apn} switch automatically puts @acronym{NCO} into 
append mode (@pxref{Appending Variables}), so specifying @samp{-A} is
redundant, and simultaneously specifying overwrite mode with @samp{-O}
causes an error.  
By default, NCO works in an intermediate temporary file.
Power users may combine @samp{--rec_apn} with the @samp{--no_tmp_fl}
switch (@pxref{Temporary Output Files}):
@example
ncrcat --rec_apn --no_tmp_fl fl_2.nc fl_1.nc
@end example
This avoids creating an intermediate file, and copies only the
minimal amount of data (i.e., all of @file{fl_2.nc}). 
Hence, it is fast.
We recommend users try to understand the safety trade-offs involved. 

@html
<a name="subcycle"></a> <!-- http://nco.sf.net/nco.html#subcycle -->
<a name="ssc"></a> <!-- http://nco.sf.net/nco.html#ssc -->
<a name="duration"></a> <!-- http://nco.sf.net/nco.html#duration -->
<a name="drn"></a> <!-- http://nco.sf.net/nco.html#drn -->
<a name="mro"></a> <!-- http://nco.sf.net/nco.html#mro -->
@end html
@node Subcycle, Multislabs, Record Appending, Common features
@section Subcycle
@cindex duration
@cindex sub-cycle
@cindex subcycle
@cindex MRO
@cindex Multi-Record Operator
@cindex @code{--mro}
@cindex @code{-d @var{dim},[@var{min}],[@var{max}],[@var{stride}],[@var{subcycle}]}
@cindex @code{--dimension @var{dim},[@var{min}],[@var{max}],[@var{stride}],[@var{subcycle}]}
@cindex @code{--dmn @var{dim},[@var{min}],[@var{max}],[@var{stride}],@var{subcycle}]}
@cartouche
Availability: @command{ncra}, @command{ncrcat}@* 
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}][,[@var{subcycle}]]]]}@*
Long options: 
@samp{--mro}
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}][,[@var{subcycle}]]]]}@*
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}][,[@var{subcycle}]]]]}@*
@end cartouche
As of version 4.2.1 (August, 2012), @acronym{NCO} allows both Multi-File,
Multi-Record operators, @command{ncra} and @command{ncrcat}, to extract
and operate on multiple groups of records. 
These groups may be connected to physical @emph{sub-cycles} of a
periodic nature, e.g., months of a year, or hours of a day. 
Or they may be thought of as groups of a specifed duration.
The feature and the terminology to describe it are new.
For now, we call this the @dfn{subcycle feature}, sometimes abbreviated
@acronym{SSC}
@footnote{When originally released in 2012 this was called the
@dfn{duration feature}, and was abbreviated @acronym{DRN}.}.

The subcycle feature allows processing of groups of records
separated by regular intervals of records.
It is perhaps best illustrated by an extended example which describes
how to solve the same problem both with and without the @acronym{SSC} feature.

The first task in climate data processing is often creating seasonal
cycles. 
Suppose a 150-year climate simulation produces 150 output files, each
comprising 12 records, each record a monthly mean:
@file{1850.nc}, @file{1851.nc}, ... @file{1999.nc}.
Our goal is to create a single file containing the summertime (June,
July, and August, aka JJA) mean.
Traditionally, we would first compute the climatological monthly
mean for each month of summer. 
Each of these is a 150-year mean, i.e., 
@example
# Step 1: Create climatological monthly files clm06.nc..clm08.nc
for mth in @{6..8@}; do
  mm=`printf "%02d" $mth`
  ncra -O -F -d time,$@{mm@},,12 -n 150,4,1 1850.nc clm$@{mm@}.nc
done
# Step 2: Average climatological monthly files into summertime mean
ncra -O clm06 clm07.nc clm08.nc clm_JJA.nc
@end example
@noindent
So far, nothing is unusual and this task can be performed by any
@acronym{NCO} version. 
The @acronym{SSC} feature makes obsolete the need for the shell loop
used in @w{Step 1} above. 

The new @acronym{SSC} option aggregates more than one input record at a time
before performing arithmetic operations, and, with an additional
switch, allows us to archive those results in multiple record output
(MRO) files.  
This reduces the task of producing the climatological summertime
mean to one step:
@example
# Step 1: Compute climatological summertime mean
ncra -O -F -d time,6,,12,3 -n 150,4,1 1850.nc clm_JJA.nc
@end example
@noindent
The @acronym{SSC} option instructs @command{ncra} (or @command{ncrcat})
to process  files in groups of three records. 
To better understand the meaning of each argument to the @samp{-d}
hyperslab option, read it this way: ``for the time dimension start with
the sixth record, continue without end, repeat the process every twelfth
record, and define a sub-cycle as three consecutive records''. 

A separate option, @samp{--mro}, instructs @command{ncra} to output 
its results from each sub-group, and to produce a @dfn{Multi-Record Output}
(MRO) file rather than a @dfn{Single-Record Output} (SRO) file.
Unless @samp{--mro} is specified, @command{ncra} collects together all
the sub-groups, operates on their ensemble, and produces a single
output record. 
The addition of @samp{--mro} to the above example causes @command{ncra}
to archive all (150) annual summertime means to one file:
@example
# Step 1: Archive all 150 summertime means in one file
ncra --mro -O -F -d time,6,,12,3 -n 150,4,1 1850.nc 1850_2009_JJA.nc
# ...or all (150) annual means...
ncra --mro -O -d time,,,12,12 -n 150,4,1 1850.nc 1850_2009.nc
@end example
@noindent
These operations generate and require no intermediate files.
This contrasts to previous @acronym{NCO} methods, which require
generating, averaging, then catenating 150 files.  
The @samp{--mro} option has no effect on, or rather is redundant for, 
@command{ncrcat} since @command{ncrcat} always outputs all selected
records.

@html
<a name="msa"></a> <!-- http://nco.sf.net/nco.html#msa -->
<a name="mlt"></a> <!-- http://nco.sf.net/nco.html#mlt -->
@end html
@node Multislabs, Wrapped Coordinates, Subcycle, Common features
@section Multislabs 
@cindex multislab
@cindex multi-hyperslab
@cindex @acronym{MSA}
@cindex @code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--msa}
@cindex @code{--msa_usr_rdr}
@cindex @code{--msa_user_order}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}@* 
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
Long options: 
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]},@* 
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
@samp{--msa_usr_rdr}, @samp{--msa_user_order}@*
@end cartouche
A @w{multislab} is a union of one or more hyperslabs.
One defines multislabs by chaining together hyperslab commands, i.e., 
@kbd{-d} options (@pxref{Hyperslabs}).
Support for specifying a @dfn{multi-hyperslab} or @dfn{multislab} for
any variable was first added to @command{ncks} in late 2002.
The other operators received these capabilities in April 2008.
Multi-slabbing is often referred to by the acronym @acronym{MSA},
which stands for ``Multi-Slabbing Algorithm''.
As explained below, the user may additionally request that the
multislabs be returned in the user-specified order, rather than the
on-disk storage order. 
Although @acronym{MSA} user-ordering has been available in all operators
since 2008, most users were unaware of it since the documentation
(below, and in the man pages) was not written until July 2013.

Multislabs overcome many restraints that limit simple hyperslabs.
@w{A single} @kbd{-d} option can only specify a contiguous and/or
a regularly spaced multi-dimensional data array.
Multislabs are constructed from multiple @kbd{-d} options and may
therefore have non-regularly spaced arrays.
For example, suppose it is desired to operate on all longitudes
from 10.0 to 20.0 and from 80.0 to @w{90.0 degrees}.
The combined range of longitudes is not selectable in a single 
hyperslab specfication of the form 
@samp{-d @var{dimension},@var{min},@var{max}} or  
@samp{-d @var{dimension},@var{min},@var{max},@var{stride}} because its
elements are irregularly spaced in coordinate space (and presumably 
in index space too). 
The multislab specification for obtaining these values is simply
the union of the hyperslabs specifications that comprise the multislab,
i.e., 
@example
ncks -d lon,10.,20. -d lon,80.,90. in.nc out.nc
ncks -d lon,10.,15. -d lon,15.,20. -d lon,80.,90. in.nc out.nc
@end example
@noindent
Any number of hyperslabs specifications may be chained together
to specify the multislab.
@acronym{MSA} creates an output dimension equal in size to the sum of
the sizes of the multislabs.
This can be used to extend and or pad coordinate grids.

@cindex stride
Users may specify redundant ranges of indices in a multislab, e.g., 
@example
ncks -d lon,0,4 -d lon,2,9,2 in.nc out.nc
@end example
@noindent
This command retrieves the first five longitudes, and then every other
longitude value up to the tenth.
Elements 0, 2, @w{and 4} are specified by both hyperslab arguments (hence
this is redundant) but will count only once if an arithmetic operation
is being performed.  
This example uses index-based (not coordinate-based) multislabs because
the @var{stride} option only supports index-based hyper-slabbing. 
@xref{Stride}, for more information on the @var{stride} option.

Multislabs are more efficient than the alternative of sequentially
performing hyperslab operations and concatenating the results.
@cindex I/O
This is because @acronym{NCO} employs a novel multislab algorithm to
minimize the number of I/O operations when retrieving irregularly spaced
data from disk.
The @acronym{NCO} multislab algorithm retrieves each element from disk
once and only once.
Thus users may take some shortcuts in specifying multislabs and the
algorithm will obtain the intended values.
Specifying redundant ranges is not encouraged, but may be useful on
occasion and will not result in unintended consequences.

Suppose the @var{Q} variable contains three dimensional arrays of
distinct chemical constituents in no particular order.
We are interested in the NOy species in a certain geographic range. 
Say that NO, NO2, and N2O5 are @w{elements 0}, 1, @w{and 5} of the
@var{species} dimension of @var{Q}.
The multislab specification might look something like
@example
ncks -d species,0,1 -d species,5 -d lon,0,4 -d lon,2,9,2 in.nc out.nc
@end example
@noindent
Multislabs are powerful because they may be specified for every
dimension at the same time.
Thus multislabs obsolete the need to execute multiple @command{ncks}
commands to gather the desired range of data.

@html
<a name="msa_usr_rdr"></a> <!-- http://nco.sf.net/nco.html#msa_usr_rdr -->
@end html
The @acronym{MSA} user-order switch @samp{--msa_usr_rdr} (or
@samp{--msa_user_order}, both of which shorten to @samp{--msa}) 
requests that the multislabs be output in the user-specified
order from the command-line, rather than in the input-file on-disk
storage order.  
This allows the user to perform complex data re-ordering in one
operation that would otherwise require cumbersome steps of
hyperslabbing, concatenating, and permuting. 
Consider the recent example of a user who needed to convert datasets
stored with the longitude coordinate @code{Lon} ranging from
[@minus{}180,180) to datasets that follow the [0,360) convention.
@example
% ncks -H -v Lon in.nc
Lon[0]=-180
Lon[1]=-90
Lon[2]=0
Lon[3]=90
@end example
@noindent
Although simple in theory, this task requires both mathematics to
change the numerical value of the longitude coordinate, data
hyperslabbing to split the input on-disk arrays at Greenwich, and data
re-ordering within to stitch the western hemisphere onto the eastern
hemisphere at the date-line.
The @samp{--msa} user-order switch overrides the default that data are
output in the same order in which they are stored on-disk in the input
file, and instead stores them in the same order as the multi-slabs are
given to the command line.
This default is intuitive and is not important in most uses.
However, the @acronym{MSA} user-order switch allows users to meet
their output order needs by specifying multi-slabs in a certain order.
Compare the results of default ordering to user-ordering for longitude:
@example
% ncks -O -H       -v Lon -d Lon,0.,180. -d Lon,-180.,-1.0 in.nc
Lon[0]=-180 
Lon[1]=-90 
Lon[2]=0 
Lon[3]=90 
% ncks -O -H --msa -v Lon -d Lon,0.,180. -d Lon,-180.,-1.0 in.nc
Lon[0]=0 
Lon[1]=90 
Lon[2]=-180 
Lon[3]=-90 
@end example
@noindent
The two multi-slabs are the same but they can be presented to screen,
or to an output file, in either order. 
The second example shows how to place the western hemisphere after the
eastern hemisphere, although they are stored in the opposite order in
the input file. 

With this background, one sees that the following commands suffice to
rotate the input file by 180 degrees longitude:
@example
% ncks -O -v LatLon --msa -d Lon,0.,180. -d Lon,-180.,-1.0 in.nc out.nc
% ncap2 -O -s 'where(Lon < 0) Lon=Lon+360' out.nc out.nc
% ncks -C -H -v LatLon ~/nco/data/in.nc
Lat[0]=-45 Lon[0]=-180 LatLon[0]=0 
Lat[0]=-45 Lon[1]=-90 LatLon[1]=1 
Lat[0]=-45 Lon[2]=0 LatLon[2]=2 
Lat[0]=-45 Lon[3]=90 LatLon[3]=3 
Lat[1]=45 Lon[0]=-180 LatLon[4]=4 
Lat[1]=45 Lon[1]=-90 LatLon[5]=5 
Lat[1]=45 Lon[2]=0 LatLon[6]=6 
Lat[1]=45 Lon[3]=90 LatLon[7]=7 
% ncks -C -H -v LatLon ~/out.nc
Lat[0]=-45 Lon[0]=0 LatLon[0]=2 
Lat[0]=-45 Lon[1]=90 LatLon[1]=3 
Lat[0]=-45 Lon[2]=180 LatLon[2]=0 
Lat[0]=-45 Lon[3]=270 LatLon[3]=1 
Lat[1]=45 Lon[0]=0 LatLon[4]=6 
Lat[1]=45 Lon[1]=90 LatLon[5]=7 
Lat[1]=45 Lon[2]=180 LatLon[6]=4 
Lat[1]=45 Lon[3]=270 LatLon[7]=5 
@end example
@noindent
There are other workable, valid methods to accomplish this rotation, yet
none are simpler nor more efficient than utilizing @acronym{MSA}
user-ordering. 
Some final comments on applying this algorithm:
Be careful to specify hemispheres that do not overlap, e.g., by
inadvertently specifying coordinate ranges that both include Greenwich. 
Some users will find using index-based rather than coordinate-based
hyperslabs makes this clearer.

@html
<a name="wrp"></a> <!-- http://nco.sf.net/nco.html#wrp -->
@end html
@node Wrapped Coordinates, Auxiliary Coordinates, Multislabs, Common features
@section Wrapped Coordinates
@cindex wrapped coordinates
@cindex longitude
@cindex @code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cartouche
Availability: @command{ncks}@*
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
Long options: 
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]},@* 
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
@end cartouche
@w{A @dfn{wrapped coordinate}} is a coordinate whose values increase or
decrease monotonically (nothing unusual so far), but which represents a
dimension that ends where it begins (i.e., wraps around on itself).
Longitude (i.e., degrees on a circle) is a familiar example of a wrapped
coordinate.
Longitude increases to the East of Greenwich, England, where it is
defined to be zero.
Halfway around the globe, the longitude is @w{180 degrees} East (or West). 
Continuing eastward, longitude increases to @w{360 degrees} East at
Greenwich. 
The longitude values of most geophysical data are either in the range
[0,360), or [@minus{}180,180).
In either case, the Westernmost and Easternmost longitudes are
numerically separated by @w{360 degrees}, but represent contiguous
regions on the globe.
For example, the Saharan desert stretches from roughly 340 to 
@w{50 degrees} East.
Extracting the hyperslab of data representing the Sahara from a global
dataset presents special problems when the global dataset is stored
consecutively in longitude from 0 to @w{360 degrees}.
This is because the data for the Sahara will not be contiguous in the
@var{input-file} but is expected by the user to be contiguous in the
@var{output-file}. 
In this case, @command{ncks} must invoke special software routines to
assemble the desired output hyperslab from multiple reads of the
@var{input-file}. 

Assume the domain of the monotonically increasing longitude coordinate
@code{lon} is @math{0 < @var{lon} < 360}. 
@command{ncks} will extract a hyperslab which crosses the Greenwich
meridian simply by specifying the westernmost longitude as @var{min} and
the easternmost longitude as @var{max}.
The following commands extract a hyperslab containing the Saharan desert:
@example
ncks -d lon,340.,50. in.nc out.nc
ncks -d lon,340.,50. -d lat,10.,35. in.nc out.nc
@end example
@noindent
The first example selects data in the same longitude range as the Sahara. 
The second example further constrains the data to having the same
latitude as the Sahara.
The coordinate @code{lon} in the @var{output-file}, @file{out.nc}, will
no longer be monotonic! 
The values of @code{lon} will be, e.g., @samp{340, 350, 0, 10, 20, 30,
40, 50}. 
This can have serious implications should you run @file{out.nc} through
another operation which expects the @code{lon} coordinate to be
monotonically increasing.
Fortunately, the chances of this happening are slim, since @code{lon}
has already been hyperslabbed, there should be no reason to hyperslab
@code{lon} again.
Should you need to hyperslab @code{lon} again, be sure to give
dimensional indices as the hyperslab arguments, rather than coordinate
values (@pxref{Hyperslabs}).

@html
<a name="aux"></a> <!-- http://nco.sf.net/nco.html#aux -->
<a name="auxiliary"></a> <!-- http://nco.sf.net/nco.html#auxiliary -->
<a name="-X"></a> <!-- http://nco.sf.net/nco.html#-X -->
<a name="std_nm"></a> <!-- http://nco.sf.net/nco.html#std_nm -->
<a name="standard_name"></a> <!-- http://nco.sf.net/nco.html#standard_name -->
@end html
@node Auxiliary Coordinates, UDUnits Support, Wrapped Coordinates, Common features
@section Auxiliary Coordinates
@cindex @code{-X}
@cindex @code{--auxiliary}
@cindex @code{standard_name}
@cindex @code{coordinates}
@cindex @acronym{CF} conventions
@cindex @code{-X @var{lon_min},@var{lon_max},@var{lat_min},@var{lat_max}}
@cindex @code{--auxiliary @var{lon_min},@var{lon_max},@var{lat_min},@var{lat_max}}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}@* 
Short options: @samp{-X @var{lon_min},@var{lon_max},@var{lat_min},@var{lat_max}}@*
Long options: 
@samp{--auxiliary @var{lon_min},@var{lon_max},@var{lat_min},@var{lat_max}}@*
@end cartouche
Utilize auxiliary coordinates specified in values of the coordinate
variable's @code{standard_name} attributes, if any, when interpreting 
hyperslab and multi-slab options. 
Also @samp{--auxiliary}.
This switch supports hyperslabbing cell-based grids over coordinate
ranges. 
This works on datasets that associate coordinate variables to
grid-mappings using the @acronym{CF}-convention (@pxref{CF Conventions})   
@code{coordinates} and @code{standard_name} attributes described 
@uref{http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.6/cf-conventions.html#coordinate-system, here}. 
Currently, @acronym{NCO} understands auxiliary coordinate variables 
pointed to by the @code{standard_name} attributes for @var{latitude} and 
@var{longitude}.   
Cells that contain a value within the user-specified range 
[@var{lon_min},@var{lon_max},@var{lat_min},@var{lat_max}] are
included in the output hyperslab.  

@cindex cell-based grids
A cell-based grid collapses the horizontal spatial information 
(latitude and longitude) and stores it along a one-dimensional
coordinate that has a one-to-one mapping to both latitude and longitude
coordinates. 
Rectangular (in longitude and latitude) horizontal hyperslabs cannot
be selected using the typical procedure (@pxref{Hyperslabs}) of
separately specifying @samp{-d} arguments for longitude and latitude.
Instead, when the @samp{-X} is used, @acronym{NCO} learns the names of
the latitude and longitude coordinates by searching the
@code{standard_name} attribute of all variables until it finds
the two variables whose @code{standard_name}'s are ``latitude'' and 
``longitude'', respectively. 
This @code{standard_name} attribute for latitude and longitude
coordinates follows the @acronym{CF}-convention  
(@pxref{CF Conventions}). 

Putting it all together, consider a variable @var{gds_3dvar} output from 
simulations on a cell-based geodesic grid. 
Although the variable contains three dimensions of data (time, latitude,
and longitude), it is stored in the netCDF file with only two dimensions,
@code{time} and @code{gds_crd}.  
@example
% ncks -m -C -v gds_3dvar ~/nco/data/in.nc
gds_3dvar: type NC_FLOAT, 2 dimensions, 4 attributes, chunked? no, \
 compressed? no, packed? no, ID = 41
gds_3dvar RAM size is 10*8*sizeof(NC_FLOAT) = 80*4 = 320 bytes
gds_3dvar dimension 0: time, size = 10 NC_DOUBLE, dim. ID = 20 \ 
 (CRD)(REC)
gds_3dvar dimension 1: gds_crd, size = 8 NC_FLOAT, dim. ID = 17 (CRD)
gds_3dvar attribute 0: long_name, size = 17 NC_CHAR, value = \ 
 Geodesic variable
gds_3dvar attribute 1: units, size = 5 NC_CHAR, value = meter
gds_3dvar attribute 2: coordinates, size = 15 NC_CHAR, value = \
 lat_gds lon_gds
gds_3dvar attribute 3: purpose, size = 64 NC_CHAR, value = \ 
 Test auxiliary coordinates like those that define geodesic grids
@end example
The @code{coordinates} attribute lists the names of the latitude and
longitude coordinates, @code{lat_gds} and @code{lon_gds}, respectively. 
The @code{coordinates} attribute is recommended though optional.
With it, the user can immediately identify which variables contain
the latitude and longitude coordinates.
Without a @code{coordinates} attribute it would be unclear at first
glance whether a variable resides on a cell-based grid.
In this example, @code{time} is a normal record dimension and
@code{gds_crd} is the cell-based dimension.

The cell-based grid file must contain two variables whose
@code{standard_name} attributes are ``latitude'', and ``longitude'':
@example
% ncks -m -C -v lat_gds,lon_gds ~/nco/data/in.nc
lat_gds: type NC_DOUBLE, 1 dimensions, 4 attributes, \
 chunked? no, compressed? no, packed? no, ID = 37
lat_gds RAM size is 8*sizeof(NC_DOUBLE) = 8*8 = 64 bytes
lat_gds dimension 0: gds_crd, size = 8 NC_FLOAT, dim. ID = 17 (CRD)
lat_gds attribute 0: long_name, size = 8 NC_CHAR, value = Latitude
lat_gds attribute 1: standard_name, size = 8 NC_CHAR, value = latitude
lat_gds attribute 2: units, size = 6 NC_CHAR, value = degree
lat_gds attribute 3: purpose, size = 62 NC_CHAR, value = \ 
 1-D latitude coordinate referred to by geodesic grid variables

lon_gds: type NC_DOUBLE, 1 dimensions, 4 attributes, \
 chunked? no, compressed? no, packed? no, ID = 38
lon_gds RAM size is 8*sizeof(NC_DOUBLE) = 8*8 = 64 bytes
lon_gds dimension 0: gds_crd, size = 8 NC_FLOAT, dim. ID = 17 (CRD)
lon_gds attribute 0: long_name, size = 9 NC_CHAR, value = Longitude
lon_gds attribute 1: standard_name, size = 9 NC_CHAR, value = longitude
lon_gds attribute 2: units, size = 6 NC_CHAR, value = degree
lon_gds attribute 3: purpose, size = 63 NC_CHAR, value = \
 1-D longitude coordinate referred to by geodesic grid variables
@end example
In this example @code{lat_gds} and @code{lon_gds} represent the 
latitude or longitude, respectively, of cell-based variables.
These coordinates (must) have the same single dimension (@code{gds_crd},
in this case) as the cell-based variables.
And the coordinates must be one-dimensional---multidimensional
coordinates will not work.

This infrastructure allows @acronym{NCO} to identify, interpret, and
process (e.g., hyperslab) the variables on cell-based grids as easily
as it works with regular grids.
To time-average all the values between zero and @w{180 degrees}
longitude and between plus and minus @w{30 degress} latitude, we use
@example
ncra -O -X 0.,180.,-30.,30. -v gds_3dvar in.nc out.nc
@end example
@acronym{NCO} accepts multiple @samp{-X} arguments for cell-based grid
multi-slabs, just as it accepts multiple @samp{-d} arguments for 
multi-slabs of regular coordinates.
@example
ncra -O -X 0.,180.,-30.,30. -X 270.,315.,45.,90. in.nc out.nc
@end example
The arguments to @samp{-X} are always interpreted as floating point
numbers, i.e., as coordinate values rather than dimension indices
so that these two commands produce identical results
@example
ncra -X 0.,180.,-30.,30. in.nc out.nc
ncra -X 0,180,-30,30 in.nc out.nc
@end example
In contrast, arguments to @samp{-d} require decimal places to be
recognized as coordinates not indices (@pxref{Hyperslabs}).  
We recommend always using decimal points with @samp{-X} arguments
to avoid confusion.

@html
<a name="UDUnits"></a> <!-- http://nco.sf.net/nco.html#UDUnits -->
<a name="UDUnits2"></a> <!-- http://nco.sf.net/nco.html#UDUnits2 -->
@end html
@node UDUnits Support, Rebasing Time Coordinate, Auxiliary Coordinates, Common features
@section UDUnits Support 
@cindex UDUnits
@cindex Unidata
@cindex @code{units}
@cindex attribute, @code{units}
@cindex @code{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cindex @code{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncks}, @command{ncpdq}, @command{ncra},
@command{ncrcat}, @command{ncwa}@* 
Short options: @samp{-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
Long options: 
@samp{--dimension @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]},@* 
@samp{--dmn @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]}@*
@end cartouche
There is more than one way to hyperskin a cat.
The @uref{http://www.unidata.ucar.edu/packages/udunits, UDUnits} package 
provides a library which, if present, @acronym{NCO} uses to translate
user-specified physical dimensions into the physical dimensions of data
stored in netCDF files.
Unidata provides UDUnits under the same terms as netCDF, so sites should
install both.
Compiling @acronym{NCO} with UDUnits support is currently optional but
may become required in a future version of @acronym{NCO}.

Two examples suffice to demonstrate the power and convenience of UDUnits  
support. 
@cindex MKS units
First, consider extraction of a variable containing non-record
coordinates with physical dimensions stored in MKS units.
In the following example, the user extracts all wavelengths
in the visible portion of the spectrum in terms of the units
very frequently used in visible spectroscopy, microns:
@example
% ncks -C -H -v wvl -d wvl,"0.4 micron","0.7 micron" in.nc
wvl[0]=5e-07 meter
@end example
@noindent
@cindex @code{units}
The hyperslab returns the correct values because the @var{wvl} variable
is stored on disk with a length dimension that UDUnits recognizes in the 
@code{units} attribute.
The automagical algorithm that implements this functionality is worth
describing since understanding it helps one avoid some potential
pitfalls. 
First, the user includes the physical units of the hyperslab dimensions 
she supplies, separated by a simple space from the numerical values of
the hyperslab limits.
She encloses each coordinate specifications in quotes so that the shell
does not break the @emph{value-space-unit} string into separate
arguments before passing them to @acronym{NCO}. 
Double quotes (@kbd{"foo"}) or single quotes (@kbd{'foo'}) are equally
valid for this purpose. 
Second, @acronym{NCO} recognizes that units translation is requested
because each hyperslab argument contains text characters and non-initial
spaces.  
Third, @acronym{NCO} determines whether the @var{wvl} is dimensioned
with a coordinate variable that has a @code{units} attribute. 
@cindex coordinate variable 
In this case, @var{wvl} itself is a coordinate variable.
The value of its @code{units} attribute is @code{meter}. 
Thus @var{wvl} passes this test so UDUnits conversion is attempted. 
If the coordinate associated with the variable does not contain a 
@code{units} attribute, then @acronym{NCO} aborts.
Fourth, @acronym{NCO} passes the specified and desired dimension strings  
(microns are specified by the user, meters are required by
@acronym{NCO}) to the UDUnits library.
Fifth, the UDUnits library that these dimension are commensurate
and it returns the appropriate linear scaling factors to convert from 
microns to meters to @acronym{NCO}.
If the units are incommensurate (i.e., not expressible in the same
fundamental MKS units), or are not listed in the UDUnits database, then 
NCO aborts since it cannot determine the user's intent.
Finally, @acronym{NCO} uses the scaling information to convert the
user-specified hyperslab limits into the same physical dimensions as
those of the corresponding cooridinate variable on disk.
At this point, @acronym{NCO} can perform a coordinate hyperslab using
the same algorithm as if the user had specified the hyperslab without
requesting units conversion.

@cindex @code{units}
@cindex @code{time} 
The translation and dimensional innterpretation of time coordinates
shows a more powerful, and probably more common, UDUnits application.
In this example, the user prints all data between @w{4 PM} and @w{7 PM}
on @w{December 8}, 1999, from a variable whose time dimension is hours 
since the year 1900:
@example
% ncks -u -H -C -v time_udunits -d time_udunits,"1999-12-08 \
  16:00:0.0","1999-12-08 19:00:0.0" in.nc
time_udunits[1]=876018 hours since 1900-01-01 00:00:0.0
@end example
@noindent
@cindex stride
@cindex whitespace
Here, the user invokes the stride (@pxref{Stride}) capability to obtain 
every other timeslice.
This is possible because the UDUnits feature is additive, not
exclusive---it works in conjunction with all other hyperslabbing
(@pxref{Hyperslabs}) options and in all operators which support
hyperslabbing.
The following example shows how one might average data in a 
time period spread across multiple input files
@example
ncra -d time,"1939-09-09 12:00:0.0","1945-05-08 00:00:0.0" \
  in1.nc in2.nc in3.nc out.nc
@end example
@noindent
Note that there is no excess whitespace before or after the individual
elements of the @samp{-d} argument.
@cindex shell 
This is important since, as far as the shell knows, @samp{-d} takes
only @emph{one} command-line argument.
Parsing this argument into its component
@code{@var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]} elements 
(@pxref{Hyperslabs}) is the job of @acronym{NCO}.
When unquoted whitespace is present between these elements, the shell
passes @acronym{NCO} arugment fragments which will not parse as
intended. 

@acronym{NCO} implemented support for the UDUnits2 library with version   
3.9.2 (August, 2007).
The
@uref{http://www.unidata.ucar.edu/software/udunits/udunits-2/udunits2.html,
UDUnits2} package supports non-ASCII characters and logarithmic units. 
We are interested in user-feedback on these features.

One aspect that deserves mention is that UDUnits, and thus
@acronym{NCO}, supports run-time definition of the location of the
relevant UDUnits databases. 
With UDUnits @w{version 1}, users may specify the directory which
contains the UDUnits database, @file{udunits.dat}, via the
@code{UDUNITS_PATH} environment variable.
With UDUnits @w{version 2}, users may specify the UDUnits database file 
itself, @file{udunits2.xml}, via the @code{UDUNITS2_XML_PATH} 
environment variable.
@example
# UDUnits1
export UDUNITS_PATH='/unusual/location/share/udunits'
# UDUnits2
export UDUNITS2_XML_PATH='/unusual/location/share/udunits/udunits2.xml'
@end example
This run-time flexibility can enable the full functionality of
pre-built binaries on machines with libraries in different locations.

@cindex Climate and Forecast Metadata Convention
@cindex @acronym{CF} conventions
The @uref{http://www.unidata.ucar.edu/packages/udunits, UDUnits}
package documentation describes the supported formats of time
dimensions. 
Among the metadata conventions that adhere to these formats are the  
@uref{http://cf-pcmdi.llnl.gov, 
Climate and Forecast (CF) Conventions} and the 
@uref{http://ferret.wrc.noaa.gov/noaa_coop/coop_cdf_profile.html,
Cooperative Ocean/Atmosphere Research Data Service (COARDS) Conventions}.
The following @samp{-d arguments} extract the same data using 
commonly encountered time dimension formats: 
@c fxm add more formats here
@example
-d time,'1918-11-11 00:00:0.0','1939-09-09 00:00:0.0'
-d time,'1918-11-11 00:00:0.0','1939-09-09 00:00:0.0'
-d time,'1918-11-11T00:00:0.0Z','1939-09-09T00:00:0.0Z'
-d time,'1918-11-11','1939-09-09'
-d time,'1918-11-11','1939-9-9'
@end example
@noindent
All of these formats include at least one dash @kbd{-} in a
non-leading character position (a dash in a leading character position 
is a negative sign). 
@acronym{NCO} assumes that a space, colon, or non-leading dash in a
limit string indicates that a UDUnits units conversion is requested.
Some date formats like YYYYMMDD that are valid in UDUnits are ambiguous
to @acronym{NCO} because it cannot distinguish a purely numerical date
(i.e., no dashes or text characters in it) from a coordinate or index
value: 
@example
-d time,1918-11-11 # Interpreted as the date November 11, 1918
-d time,19181111   # Interpreted as time-dimension index 19181111
-d time,19181111.  # Interpreted as time-coordinate value 19181111.0
@end example
Hence, use the YYYY-MM-DD format rather than YYYYMMDD for dates.

@noindent
As of version 4.0.0 (January, 2010), @acronym{NCO} supports some
calendar attributes specified by the @acronym{CF} conventions. 
@table @asis
@item @strong{Supported types:} 
"365_day"/"noleap", "360_day", "gregorian", "standard" 
@item  @strong{Unsupported types:} 
"366_day"/"all_leap","proleptic_gregorian","julian","none" 
@end table
Unsupported types default to mixed Gregorian/Julian as defined by 
UDUnits. 

@noindent An Example: Consider the following netCDF variable

@example
variables:
  double lon_cal(lon_cal) ;
    lon_cal:long_name = "lon_cal" ;
    lon_cal:units = "days since 1964-2-28 0:0:0" ;
    lon_cal:calendar = "365_day" ;
data:
  lon_cal = 1,2,3,4,5,6,7,8,9,10;
@end example 
@samp{ncks -v lon_cal -d lon_cal,'1964-3-1 0:00:0.0','1964-3-4 00:00:0.0'}
results in @code{lon_cal=1,2,3,4}.

@cindex MKS units
@cindex God
netCDF variables should always be stored with MKS (i.e., God's) units,
so that application programs may assume MKS dimensions apply to all
input variables. 
The UDUnits feature is intended to alleviate some of the @acronym{NCO}
user's pain when handling MKS units.
It connects users who think in human-friendly units (e.g.,
miles, millibars, days) to extract data which are always stored in God's
units, MKS (e.g., meters, Pascals, seconds). 
The feature is not intended to encourage writers to store data in 
esoteric units (e.g., furlongs, pounds per square inch, fortnights). 

@html
<a name="time_rebase"></a> <!-- http://nco.sf.net/nco.html#time_rebase -->
<a name="rbs"></a> <!-- http://nco.sf.net/nco.html#rbs -->
@end html
@node Rebasing Time Coordinate, Multiple Record Dimensions, UDUnits Support, Common features
@section Rebasing Time Coordinate
@cartouche
Availability: 
@command{ncra}, @command{ncrcat} 
Short options: None@*
@end cartouche

Time rebasing is invoked when numerous files share a common record
coordinate, and the record coordinate units change among input files.
The rebasing is performed automatically if and only if UDUnits is
installed. 
Usually rebasing occurs when the recoordinate is a time-based variable, 
and times are recorded in units of a time-since-basetime, and the
basetime changes from file to file.
Since the output file can have only one unit (i.e., one basetime) for
the record coordinate, @acronym{NCO}, in such cases, chooses the units
of the first input file to be the units of the output file.
It is necessary to ``rebase'' all the input record variables to this
output time unit in order for the output file to have the correct
values.  

For example suppose the time coordinate is in hours and each day in
January is stored in its own daily file.
Each daily file records the temperature variable @code{tpt(time)} 
with an (unadjusted) @code{time} coordinate value between 0--23 hours,
and uses the @code{units} attribute to advance the base time:
@example
file01.nc time:units="hours since 1990-1-1"   
file02.nc time:units="hours since 1990-1-2"   
...
file31.nc time:units="hours since 1990-1-31"   
@end example

@example
// Mean noontime temperature in January
ncra -v tpt -d time,"1990-1-1 12:00:00","1990-1-31 23:59:59",24 \
      file??.nc noon.nc    

// Concatenate day2 noon through day3 noon records
ncrcat -v tpt -d time,"1990-1-2 12:00:00","1990-1-3 11:59:59" \ 
      file01.nc file02.nc file03.nc noon.nc    

// Results: time is "re-based" to the time units in "file01.nc"
time=36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, \
     51, 52, 53, 54, 55, 56, 57, 58, 59 ;
  
// If we repeat the above command but with only two input files...
ncrcat -v tpt -d time,"1990-1-2 12:00:00","1990-1-3 11:59:59" \
      file02.nc file03 noon.nc    

// ...then output time coordinate is based on time units in "file02.nc"
time = 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, \ 
     26, 27, 28, 29, 30, 31, 32, 33, 34, 35 ;
@end example
As of @acronym{NCO} version 4.2.1 (August, 2012), @acronym{NCO}
automatically rebases not only the record coordinate (@code{time}, here) 
but also any bounds associated with the record coordinate (e.g.,
@code{time_bnds}) (@pxref{CF Conventions}).

@html
<a name="mrd"></a> <!-- http://nco.sf.net/nco.html#mrd -->
@end html
@node Multiple Record Dimensions, Missing Values, Rebasing Time Coordinate, Common features
@section Multiple Record Dimensions
@cindex netCDF4
@cindex @code{--mrd}
@cindex @code{--multiple_record_dimensions}
@cartouche
Availability: 
@command{ncecat}, @command{ncpdq} 
Short options: None@*
Long options: @samp{--mrd}@*
@end cartouche
The netCDF3 file format allows only one record dimension, and that
dimension must be the first dimension (i.e., the least rapidly varying 
dimension) of any variable in which it appears.
This imposes certain rules on how operators must perform operations
that alter the ordering of dimensions or the number of record variables.
The netCDF4 file format has no such restrictions.
Files and variables may have any number of record dimensions in any
order.
This additional flexibility of netCDF4 can only be realized by
selectively abandoning the constraints that would make operations
behave completely consistently between netCDF3 and netCDF4 files.

@acronym{NCO} chooses, by default, to impose netCDF3-based constraints
on netCDF4 files. 
This reduces the number of unanticipated consequences and keeps the
operators functioning in a familiar way.
Put another way, @acronym{NCO} limits production of additional record
dimensions so processing netCDF4 files leads to the same results as
processing netCDF4 files.
Users can override this default with the @samp{--mrd} (or 
@samp{--multiple_record_dimension}) switch, which enables netCDF4
variables to accumulate additional record dimensions.

How can additional record dimensions be produced?
Most commonly @command{ncecat} (in record-aggregate mode) defines a new
leading record dimension.
In netCDF4 files this becomes an additional record dimension unless the
original record dimension is changed to a fixed dimension (as must be
done in netCDF3 files). 
Also when @command{ncpdq} reorders dimensions it can preserve the
``record'' property of record variables.
@command{ncpdq} tries to define as a record dimension whichever
dimension ends up first in a record variable, and, in netCDF4 files,
this becomes an additional record dimension unless the original record
dimension is changed to a fixed dimension (as must be done in netCDF3
files). 
It it easier if @command{ncpdq} and @command{ncecat} do not increase
the number of record dimensions in a variable so that is the default.
Use @samp{--mrd} to override this.

@html
<a name="missing_value"></a> <!-- http://nco.sf.net/nco.html#missing_value -->
<a name="_FillValue"></a> <!-- http://nco.sf.net/nco.html#_FillValue -->
<a name="fll_val"></a> <!-- http://nco.sf.net/nco.html#fll_val -->
<a name="mss_val"></a> <!-- http://nco.sf.net/nco.html#mss_val -->
<a name="mss"></a> <!-- http://nco.sf.net/nco.html#mss -->
@end html
@node Missing Values, Chunking, Multiple Record Dimensions, Common features
@section Missing values
@cindex missing values
@cindex data, missing 
@cindex averaging data
@cindex @code{missing_value}
@cindex @code{_FillValue}
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncflint}, @command{ncpdq}, @command{ncra}, @command{ncwa}@* 
Short options: None@*
@end cartouche

The phrase @dfn{missing data} refers to data points that are missing,
invalid, or for any reason not intended to be arithmetically processed
in the same fashion as valid data.  
@cindex arithmetic operators
The @acronym{NCO} arithmetic operators attempt to handle missing data in
an intelligent fashion. 
There are four steps in the @acronym{NCO} treatment of missing data:
@enumerate
@item 
Identifying variables that may contain missing data. 

@acronym{NCO} follows the convention that missing data should be stored
with the @var{_FillValue} specified in the variable's @code{_FillValue} 
attributes. 
The @emph{only} way @acronym{NCO} recognizes that a variable @emph{may}
contain missing data is if the variable has a @code{_FillValue}
attribute. 
In this case, any elements of the variable which are numerically equal
to the @var{_FillValue} are treated as missing data.

@acronym{NCO} adopted the behavior that the default attribute name, if 
any, assumed to specify the value of data to ignore is @code{_FillValue} 
with version 3.9.2 (August, 2007).
Prior to that, the @code{missing_value} attribute, if any, was assumed to  
specify the value of data to ignore.
Supporting both of these attributes simultaneously is not practical.
Hence the behavior @acronym{NCO} once applied to @var{missing_value} it
now applies to any @var{_FillValue}. 
@acronym{NCO} now treats any @var{missing_value} as normal data 
@footnote{
The old functionality, i.e., where the ignored values are indicated by
@code{missing_value} not @code{_FillValue}, may still be selected 
@emph{at @acronym{NCO} build time} by compiling @acronym{NCO} 
with the token definition 
@c @kbd{CPPFLAGS='-DNCO_MSS_VAL_SNG=missing_value'}.
@kbd{CPPFLAGS='-UNCO_USE_FILL_VALUE'}.
}.

@findex ncrename
@findex ncatted
It has been and remains most advisable to create both @code{_FillValue} 
and @code{missing_value} attributes with identical values in datasets.
Many legacy datasets contain only @code{missing_value} attributes.
@acronym{NCO} can help migrating datasets between these conventions.
One may use @command{ncrename} (@pxref{ncrename netCDF Renamer}) to
rename all @code{missing_value} attributes to @code{_FillValue}:
@example
ncrename -a .missing_value,_FillValue inout.nc
@end example
Alternatively, one may use
@command{ncatted} (@pxref{ncatted netCDF Attribute Editor}) to
add a @code{_FillValue} attribute to all variables
@example
ncatted -O -a _FillValue,,o,f,1.0e36 inout.nc
@end example

@item 
Converting the @var{_FillValue} to the type of the variable, if
neccessary. 

Consider a variable @var{var} of type @var{var_type} with a
@code{_FillValue} attribute of type @var{att_type} containing the
value @var{_FillValue}.  
As a guideline, the type of the @code{_FillValue} attribute should be
the same as the type of the variable it is attached to.
If @var{var_type} equals @var{att_type} then @acronym{NCO}
straightforwardly compares each value of @var{var} to
@var{_FillValue} to determine which elements of @var{var} are to be
treated as missing data. 
@cindex C language
If not, then @acronym{NCO} converts @var{_FillValue} from
@var{att_type} to @var{var_type} by using the implicit conversion rules
@w{of C}, or, if @var{att_type} is @code{NC_CHAR}
@footnote{For example, the @acronym{DOE} @acronym{ARM} program often
uses @var{att_type} = @code{NC_CHAR} and @var{_FillValue} =
@samp{-99999.}. 
}, by typecasting the results of the @w{C function}
@code{strtod(@var{_FillValue})}. 
@cindex @command{ncatted}
You may use the @acronym{NCO} operator @command{ncatted} to change the
@code{_FillValue} attribute and all data whose data is
@var{_FillValue} to a new value
(@pxref{ncatted netCDF Attribute Editor}).

@item 
Identifying missing data during arithmetic operations.

@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
@cindex arithmetic operators
When an @acronym{NCO} arithmetic operator processes a variable @var{var}
with a @code{_FillValue} attribute, it compares each value of
@var{var} to @var{_FillValue} before performing an operation.
Note the @var{_FillValue} comparison imposes a performance penalty
on the operator.
Arithmetic processing of variables which contain the
@code{_FillValue} attribute always incurs this penalty, even when
none of the data are missing.
Conversely, arithmetic processing of variables which do not contain the
@code{_FillValue} attribute never incurs this penalty.
In other words, do not attach a @code{_FillValue} attribute to a
variable which does not contain missing data.
This exhortation can usually be obeyed for model generated data, but it
may be harder to know in advance whether all observational data will be
valid or not.

@item 
Treatment of any data identified as missing in arithmetic operators.

@cindex @command{nces}
@cindex @command{ncra}
@cindex @command{ncwa}
@cindex @command{ncbo}
@cindex @command{ncflint}
@acronym{NCO} averagers (@command{ncra}, @command{nces}, @command{ncwa})
do not count any element with the value @var{_FillValue} towards the
average. 
@command{ncbo} and @command{ncflint} define a @var{_FillValue} result  
when either of the input values is a @var{_FillValue}.
Sometimes the @var{_FillValue} may change from file to file in a
multi-file operator, e.g., @command{ncra}.
@acronym{NCO} is written to account for this (it always compares a
variable to the @var{_FillValue} assigned to that variable in the
current file). 
Suffice it to say that, in all known cases, @acronym{NCO} does ``the
right thing''. 

It is impossible to determine and store the correct result of a binary  
operation in a single variable.
One such corner case occurs when both operands have differing
@var{_FillValue} attributes, i.e., attributes with different
numerical values.
Since the output (result) of the operation can only have one
@var{_FillValue}, some information may be lost.
In this case, @acronym{NCO} always defines the output variable to have
the same @var{_FillValue} as the first input variable.
Prior to performing the arithmetic operation, all values of the second
operand equal to the second @var{_FillValue} are replaced with the
first @var{_FillValue}.
Then the arithmetic operation proceeds as normal, comparing each element 
of each operand to a single @var{_FillValue}.
Comparing each element to two distinct @var{_FillValue}'s would be
much slower and would be no likelier to yield a more satisfactory
answer. 
In practice, judicious choice of @var{_FillValue} values prevents any
important information from being lost.
@end enumerate

@html
<a name="chunking"></a> <!-- http://nco.sf.net/nco.html#chunking -->
<a name="cnk"></a> <!-- http://nco.sf.net/nco.html#cnk -->
<a name="cnk_sz"></a> <!-- http://nco.sf.net/nco.html#cnk_sz -->
<a name="chunk_size"></a> <!-- http://nco.sf.net/nco.html#chunk_size -->
@end html
@node Chunking, Deflation, Missing Values, Common features
@section Chunking
@cindex @code{--cnk_byt}
@cindex @code{--cnk_dmn}
@cindex @code{--cnk_map}
@cindex @code{--cnk_plc}
@cindex @code{--cnk_scl}
@cindex @code{--chunk_byte}
@cindex @code{--chunk_dimension}
@cindex @code{--chunk_map}
@cindex @code{--chunk_policy}
@cindex @code{--chunk_scalar}
@cindex chunking
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@*
Short options: none@*
Long options: 
@samp{--cnk_byt @var{cnk_sz}}, @samp{--chunk_byte @var{cnk_sz}}@*
@samp{--cnk_dmn @var{dmn_nm},@var{cnk_sz}},
@samp{--chunk_dimension @var{dmn_nm},@var{cnk_sz}}@*,
@samp{--cnk_map @var{cnk_map}}, @samp{--chunk_map @var{cnk_map}},@*
@samp{--cnk_plc @var{cnk_plc}}, @samp{--chunk_policy @var{cnk_plc}},@*
@samp{--cnk_scl @var{cnk_sz}}, @samp{--chunk_scalar @var{cnk_sz}}@*
@end cartouche

All netCDF4-enabled @acronym{NCO} operators that define variables 
support a plethora of chunksize options.
Chunking can significantly accelerate or degrade read/write access
to large datasets.
Dataset chunking issues are described in detail
@uref{http://www.hdfgroup.org/HDF5/doc/H5.user/Chunking.html,here},
@uref{http://www.unidata.ucar.edu/blogs/developer/en/entry/chunking_data_why_it_matters,here},
and
@uref{http://www.unidata.ucar.edu/blogs/developer/en/entry/chunking_data_choosing_shapes,here}.

@cindex chunking policy
@cindex chunking map
@cindex chunksize
The @acronym{NCO} chunking implementation is designed to be flexible. 
Users control three aspects of the chunking implementation.
These are known as the @dfn{chunking policy}, @dfn{chunking map},
and @dfn{chunksize}.
The first two are high-level mechanisms that apply to an entire file
and all variables and dimensions, while the third allows per-dimension
specification of parameters. 
@cindex hyperslab
@findex ncpdq
@cindex packing
The implementation is a hybrid of the @command{ncpdq} packing policies  
(@pxref{ncpdq netCDF Permute Dimensions Quickly}), and the hyperslab
specifications (@pxref{Hyperslabs}).
Each aspect is intended to have a sensible default, so that most users
will only need to set one switch to obtain sensible chunking.
Power users can tune the three switches in tandem to obtain optimal
performance. 

The user specifies the desired chunking policy with the @samp{-P} switch 
(or its long option equivalents, @samp{--cnk_plc} and
@samp{--chunk_policy}) and its @var{cnk_plc} argument.
Five chunking policies are currently implemented:@*   
@cindex @samp{all}
@cindex @samp{g2d}
@cindex @samp{g3d}
@cindex @samp{xpl}
@cindex @samp{xst}
@cindex @samp{cnk_all}
@cindex @samp{cnk_g2d}
@cindex @samp{cnk_g3d}
@cindex @samp{cnk_xpl}
@cindex @samp{cnk_xst}
@cindex @samp{plc_all}
@cindex @samp{plc_g2d}
@cindex @samp{plc_g3d}
@cindex @samp{plc_xpl}
@cindex @samp{plc_xst}
@table @dfn
@item Chunk All Variables [@emph{default}]
Definition: Chunk all variables possible.
For obvious reasons, scalar variables cannot be chunked.@*
Alternate invocation: @code{ncchunk}@*
@var{cnk_plc} key values: @samp{all}, @samp{cnk_all}, @samp{plc_all}@*
Mnemonic: All@*
@item Chunk Variables with at least Two Dimensions
Definition: Chunk all variables possible with at least two dimensions@*
Alternate invocation: none@*
@var{cnk_plc} key values: @samp{g2d}, @samp{cnk_g2d}, @samp{plc_g2d}@*
Mnemonic: @emph{G}reater than or equal to @emph{2} @emph{D}imensions@*
@item Chunk Variables with at least Three Dimensions
Definition: Chunk all variables possible with at least three dimensions@*
Alternate invocation: none@*
@var{cnk_plc} key values: @samp{g3d}, @samp{cnk_g3d}, @samp{plc_g3d}@*
Mnemonic: @emph{G}reater than or equal to @emph{3} @emph{D}imensions@*
@item Chunk Variables Containing Explicitly Chunked Dimensions
Definition: Chunk all variables possible that contain at least one
dimension whose chunksize was explicitly set with the @samp{--cnk_dmn} option.
Alternate invocation: none@*
@var{cnk_plc} key values: @samp{xpl}, @samp{cnk_xpl}, @samp{plc_xpl}@*
Mnemonic: E@emph{XPL}icitly specified dimensions@*
@item Chunk Variables with Existing Chunk Sizes
Definition: Chunk all variables possible that are already chunked in the
input file.
When used in conjunction with @samp{cnk_map=xst} this option preserves
and copies the chunking parameters from the input to the output file.
Alternate invocation: none@*
@var{cnk_plc} key values: @samp{xst}, @samp{cnk_xst}, @samp{plc_xst}@*
Mnemonic: E@emph{X}i@emph{ST}ing chunk sizes@*
@item Unchunking
Definition: Unchunk all variables possible. 
The @acronym{HDF5} storge layer requires that record variables (i.e.,
variables that contain at least one record dimension) must be chunked.
Also variables that are compressed or use checksums must be chunked.
Such variables cannot be unchunked.@*  
Alternate invocation: @code{ncunchunk}@*
@var{cnk_plc} key values: @samp{uck}, @samp{cnk_uck}, @samp{plc_uck}, @samp{unchunk}@*
Mnemonic: @emph{U}n@emph{C}hun@emph{K}@*
@end table
@noindent
Equivalent key values are fully interchangeable.
Multiple equivalent options are provided to satisfy disparate needs
and tastes of @acronym{NCO} users working with scripts and from the
command line.

@cindex chunking map
@cindex degenerate dimension
@cindex @var{cnk_map}
@cindex @code{-M @var{cnk_map}}
@cindex @code{--cnk_map @var{cnk_map}}
@cindex @code{--map @var{cnk_map}}
The chunking algorithms must know the chunksizes of each dimension of
each variable to be chunked.
The correspondence between the input variable shape and the chunksizes
is called the @dfn{chunking map}. 
The user specifies the desired chunking map with the @samp{-M} switch
(or its long option equivalents, @samp{--cnk_map} and
@samp{--chunk_map}) and its @var{cnk_map} argument.
Four chunking maps are currently implemented:@*
@cindex @samp{dmn}
@cindex @samp{scl}
@cindex @samp{prd}
@cindex @samp{lfp}
@cindex @samp{rd1}
@cindex @samp{xst}
@cindex @samp{rew}
@cindex @samp{cnk_dmn}
@cindex @samp{cnk_scl}
@cindex @samp{cnk_prd}
@cindex @samp{cnk_lfp}
@cindex @samp{cnk_rd1}
@cindex @samp{cnk_xst}
@cindex @samp{map_dmn}
@cindex @samp{map_scl}
@cindex @samp{map_prd}
@cindex @samp{map_lfp}
@cindex @samp{map_rd1}
@cindex @samp{map_xst}
@cindex Chris Barker
@table @dfn
@item Chunksize Equals Dimension Size [@emph{default}]
Definition: Chunksize defaults to dimension size. 
Explicitly specify chunksizes for particular dimensions with
@samp{--cnk_dmn} option.@*
@var{cnk_map} key values: @samp{dmn}, @samp{cnk_dmn}, @samp{map_dmn}@*
Mnemonic: @emph{D}i@emph{M}e@emph{N}sion@*
@item Chunksize Equals Dimension Size except Record Dimension
Definition: Chunksize equals dimension size except record dimension has size one.
Explicitly specify chunksizes for particular dimensions with
@samp{--cnk_dmn} option.@*
@var{cnk_map} key values: @samp{rd1}, @samp{cnk_rd1}, @samp{map_rd1}@*
Mnemonic: @emph{R}ecord @emph{D}imension size @emph{1}@*
@item Chunksize Equals Scalar Size Specified
Definition: Chunksize for all dimensions is set with the
@samp{--cnk_scl} option.@* 
@var{cnk_map} key values: @samp{xpl}, @samp{cnk_xpl}, @samp{map_xpl}@*
Mnemonic: E@emph{XPL}icitly specified dimensions@*
@item Chunksize Product Matches Scalar Size Specified
Definition: The product of the chunksizes for each variable
matches (approximately equals) the size specified with the
@samp{--cnk_scl} option.
A dimension of size one is said to be @emph{degenerate}.
For a variable of rank @var{R} (i.e., with @var{R} non-degenerate
dimensions), the chunksize in each non-degenerate dimension is the
@var{R}th root of @var{cnk_scl}.@*
@var{cnk_map} key values: @samp{prd}, @samp{cnk_prd}, @samp{map_prd}@*
Mnemonic: @emph{PR}o@emph{D}uct@*
@item Chunksize Lefter Product Matches Scalar Size Specified
Definition: The product of the chunksizes for each variable
(approximately) equals the size specified with the @samp{--cnk_scl} 
option.
This is accomplished by using dimension sizes as chunksizes for the
rightmost (most rapidly varying) dimensions, and then ``flexing'' the
chunksize of the leftmost (least rapidly varying) dimensions such that 
the product of all chunksizes matches the specified size.
All dimensions to the left of and including the first record dimension
define the left-hand side.
This map was first proposed by Chris Barker.@*
@var{cnk_map} key values: @samp{lfp}, @samp{cnk_lfp}, @samp{map_lfp}@*
Mnemonic: @emph{L}e@emph{F}ter @emph{P}roduct@*
@item Chunksize Equals Existing Chunksize
Definition: Chunksizes are copied from the input to the output
file for every variable that is chunked in the input file.
Variables not chunked in the input file will be chunked with 
default mappings.@*
@var{cnk_map} key values: @samp{xst}, @samp{cnk_xst}, @samp{map_xst}@*
Mnemonic: E@emph{X}i@emph{ST}@*
@item Chunksize Balances 1D and (N-1)-D Access to N-D Variable
Definition: Chunksizes are chosen so that 1-D and (@var{(N-1)})-D
hyperslabs of @var{3}-D variables (e.g., point-timeseries orn
latitude/longitude surfaces of 3-D fields) both require approximately
the number of chunks. 
Hence their access time should be balanced.
Russ Rew explains the motivation and derivation for this strategy 
@uref{http://www.unidata.ucar.edu/blogs/developer/en/entry/chunking_data_choosing_shapes,
here}.@*
@var{cnk_map} key values: @samp{rew}, @samp{cnk_rew}, @samp{map_rew}@*
Mnemonic: Russ @emph{REW}@*
@end table
@noindent
It is possible to combine the above chunking map algorithms with
user-specified per-dimension (though not per-variable) chunksizes that 
override specific chunksizes determined by the maps above. 
The user specifies the per-dimension chunksizes with the (equivalent) 
long options @samp{--cnk_dmn} or @samp{--chunk_dimension}).
The option takes two comma-separated arguments,
@var{dmn_nm},@var{cnk_sz}, which are the dimension name and its
chunksize, respectively. 
The @samp{--cnk_dmn} option may be used as many times as necessary.

@html
<a name="xmp_cnk"></a> <!-- http://nco.sf.net/nco.html#xmp_cnk -->
<a name="xmp_chunk"></a> <!-- http://nco.sf.net/nco.html#xmp_chunk -->
@end html
@example
# Simple chunking and unchunking
ncks -O -4 --cnk_plc=all     in.nc out.nc # Chunk in.nc
ncks -O -4 --cnk_plc=unchunk in.nc out.nc # Unchunk in.nc

# Chunk data then unchunk it, printing informative metadata
ncks -O -4 -D 4 --cnk_plc=all ~/nco/data/in.nc ~/foo.nc
ncks -O -4 -D 4 --cnk_plc=uck ~/foo.nc ~/foo.nc

# Set total chunksize to 8192 B
ncks -O -4 -D 4 --cnk_plc=all --cnk_byt=8192 ~/nco/data/in.nc ~/foo.nc

# More complex chunking procedures, with informative metadata
ncks -O -4 -D 4 --cnk_scl=8 ~/nco/data/in.nc ~/foo.nc
ncks -O -4 -D 4 --cnk_scl=8 dstmch90_clm.nc ~/foo.nc
ncks -O -4 -D 4 --cnk_dmn lat,64 --cnk_dmn lon,128 dstmch90_clm.nc \ 
 ~/foo.nc 
ncks -O -4 -D 4 --cnk_plc=uck ~/foo.nc ~/foo.nc
ncks -O -4 -D 4 --cnk_plc=g2d --cnk_map=rd1 --cnk_dmn lat,32 \
 --cnk_dmn lon,128 dstmch90_clm_0112.nc ~/foo.nc

# Chunking works with all operators...
ncap2 -O -4 -D 4 --cnk_scl=8 -S ~/nco/data/ncap2_tst.nco \ 
 ~/nco/data/in.nc ~/foo.nc
ncbo -O -4 -D 4 --cnk_scl=8 -p ~/nco/data in.nc in.nc ~/foo.nc
ncecat -O -4 -D 4 -n 12,2,1 --cnk_dmn lat,32 \ 
 -p /data/zender/dstmch90 dstmch90_clm01.nc ~/foo.nc
ncflint -O -4 -D 4 --cnk_scl=8 ~/nco/data/in.nc ~/foo.nc
ncpdq -O -4 -D 4 -P all_new --cnk_scl=8 -L 5 ~/nco/data/in.nc ~/foo.nc
ncrcat -O -4 -D 4 -n 12,2,1 --cnk_dmn lat,32 \ 
 -p /data/zender/dstmch90 dstmch90_clm01.nc ~/foo.nc
ncwa -O -4 -D 4 -a time --cnk_plc=g2d --cnk_map=rd1 --cnk_dmn lat,32 \ 
 --cnk_dmn lon,128 dstmch90_clm_0112.nc ~/foo.nc
@end example

@cindex record dimension
It is appropriate to conclude by informing users about an aspect of
chunking that may not be expected.
Three types of variables are @emph{always} chunked: Record variables,
Deflated (compressed) variables, and Checksummed variables.
Hence all variables that contain a record dimension are also chunked
(since data must be chunked in all dimensions, not just one).
Unless otherwise specified by the user, the other (fixed, non-record) 
dimensions of record variables are assigned default chunk sizes. 
The @acronym{HDF5} layer does all this automatically to optimize the
on-disk variable/file storage geometry of record variables.
Do not be surprised to learn that files created without any explicit
instructions to activate chunking nevertheless contain chunked
variables. 

@html
<a name="dfl_lvl"></a> <!-- http://nco.sf.net/nco.html#dfl_lvl -->
<a name="dfl"></a> <!-- http://nco.sf.net/nco.html#dfl -->
<a name="lz"></a> <!-- http://nco.sf.net/nco.html#lz -->
<a name="lz77"></a> <!-- http://nco.sf.net/nco.html#lz77 -->
<a name="deflate"></a> <!-- http://nco.sf.net/nco.html#deflate -->
<a name="deflation"></a> <!-- http://nco.sf.net/nco.html#deflation -->
@end html
@node Deflation, MD5 digests, Chunking, Common features
@section Deflation
@cindex @code{-L}
@cindex @code{--deflate}
@cindex @code{--dfl_lvl}
@cindex Lempel-Ziv deflation
@cindex compression
@cindex deflation
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncecat}, @command{ncflint}, @command{ncks}, @command{ncpdq},
@command{ncra}, @command{ncrcat}, @command{ncwa}@*
Short options: @samp{-L}@*
Long options: @samp{--dfl_lvl}, @samp{--deflate}@*  
@end cartouche

All @acronym{NCO} operators that define variables support 
the netCDF4 feature of storing variables compressed with Lempel-Ziv
deflation. 
The Lempel-Ziv algorithm is a lossless data compression technique.
Activate this deflation with the @code{-L @var{dfl_lvl}} short option
(or with the same argument to the @samp{--dfl_lvl} or @samp{--deflate} 
long options).
Specify the deflation level @var{dfl_lvl} on a scale from 
no deflation (@var{dfl_lvl = 0}) to maximum deflation 
(@var{dfl_lvl = 9}).
Minimal deflation (@var{dfl_lvl = 1}) achieves considerable storage
compression with little time penalty.
Higher deflation levels require more time for compression.
File sizes resulting from minimal (@var{dfl_lvl = 1}) and maximal   
(@var{dfl_lvl = 9}) deflation levels typically differ by a few
percent in size. 

To compress an entire file using deflation, use
@example
ncks -4 -L 0 in.nc out.nc # No deflation (fast, no time penalty)
ncks -4 -L 1 in.nc out.nc # Minimal deflation (little time penalty)
ncks -4 -L 9 in.nc out.nc # Maximal deflation (much slower)
@end example

Unscientific testing shows that deflation compresses typical climate
datasets by 30-60%.  
Packing, a lossy compression technique available for all netCDF files 
(see @ref{Packed data}), can easily compress files by 50%.
Packed data may be deflated to squeeze datasets by about 80%:
@example
ncks  -4 -L 1 in.nc out.nc # Minimal deflation (~30-60% compression)
ncks  -4 -L 9 in.nc out.nc # Maximal deflation (~31-63% compression)
ncpdq         in.nc out.nc # Standard packing  (~50% compression)
ncpdq -4 -L 9 in.nc out.nc # Deflated packing  (~80% compression)
@end example
@findex ncks
@command{ncks} prints deflation parameters, if any, to screen
(@pxref{ncks netCDF Kitchen Sink}).

@html
<a name="md5"></a> <!-- http://nco.sf.net/nco.html#md5 -->
<a name="digest"></a> <!-- http://nco.sf.net/nco.html#digest -->
<a name="hash"></a> <!-- http://nco.sf.net/nco.html#hash -->
<a name="integrity"></a> <!-- http://nco.sf.net/nco.html#integrity -->
<a name="security"></a> <!-- http://nco.sf.net/nco.html#security -->
@end html
@node MD5 digests, Buffer sizes, Deflation, Common features
@section MD5 digests
@cindex @code{--md5_digest}
@cindex @code{--md5_dgs}
@cindex @code{--md5_wrt_att}
@cindex @code{--md5_write_attribute}
@cindex integrity
@cindex security
@cindex digest
@cindex hash
@cindex MD5 digest
@cartouche
Availability: 
@command{ncecat}, @command{ncks}, @command{ncrcat}@*
Short options: @*
Long options: @samp{--md5_dgs}, @samp{--md5_digest}, @samp{--md5_wrt_att}, @samp{--md5_write_attribute}@*
@end cartouche

As of @acronym{NCO} version 4.1.0 (April, 2012), @acronym{NCO} 
supports data integrity verification using the @acronym{MD5} digest
algorithm. 
This support is currently implemented in @command{ncks} and in the
multifile concantenators @command{ncecat} and @command{ncrcat}.
Activate it with the @samp{--md5_dgs} or @samp{--md5_digest} long
options. 
As of @acronym{NCO} version 4.3.3 (July, 2013), @acronym{NCO} 
will write the @acronym{MD5} digest of each variable as an
@code{NC_CHAR} attribute named @code{MD5}.
This support is currently implemented in @command{ncks} and in the
multifile concantenators @command{ncecat} and @command{ncrcat}.
Activate it with the @samp{--md5_wrt_att} or
@samp{--md5_write_attribute} long options.

The behavior and verbosity of the @acronym{MD5} digest is
operator-dependent.
When activating @acronym{MD5} digests with @command{ncks} it is assumed
that the user simply wishes to see the digest of every variable and this
is done when the debugging level exceeds one.
This incurs only the minor overhead of performing the hash algorithm for
each variable read.
@acronym{MD5} digests may be activated in both the one- and two-filename
argument forms of @command{ncks}, which are used for printing and for
sub-setting, respectively.
The @acronym{MD5} digests are shown as a 32-character hexadecimal string 
in which each two characters represent one byte of the 16-byte digest:
@example
> ncks -O -D 2 -C --md5 -v md5_a,md5_abc ~/nco/data/in.nc
...
ncks: INFO MD5(md5_a) = 0cc175b9c0f1b6a831c399e269772661
md5_a = 'a' 
ncks: INFO MD5(md5_abc) = 900150983cd24fb0d6963f7d28e17f72
lev[0]=100 md5_abc[0--2]='abc' 
> ncks -O -D 2 -C -d lev,0 --md5 -v md5_a,md5_abc ~/nco/data/in.nc
...
ncks: INFO MD5(md5_a) = 0cc175b9c0f1b6a831c399e269772661
md5_a = 'a' 
ncks: INFO MD5(md5_abc) = 0cc175b9c0f1b6a831c399e269772661
lev[0]=100 md5_abc[0--0]='a' 
@end example
In fact these examples demonstrate the validity of the hash algorithm
since the @acronym{MD5} hashes of the strings ``a'' and ``abc'' are
widely known.
The second example shows that the hyperslab of variable @code{md5_abc}
(= ``abc'') consisting of only its first letter (= ``a'') has the same
hash as the variable @code{md5_a} (``a'').
This illustrates that @acronym{MD5} digests act only on variable data,
not on metadata. 

When activating @acronym{MD5} digests with @command{ncecat} or
@command{ncrcat} it is assumed that the user wishes to verify
that every variable written to disk has the same @acronym{MD5} digest 
as when it is subsequently read from disk.
This incurs the major additional overhead of reading in each variable
after it is written and performing the hash algorithm again on that to
compare to the original hash.
Moreover, it is assumed that such operations are generally done
``production mode'' where the user is not interested in actually
examining the digests herself.
The digests proceed silently unless the debugging level exceeds three:
@example
> ncecat -O -D 4 --md5 -p ~/nco/data in.nc in.nc ~/foo.nc | grep MD5
...
ncecat: INFO MD5(wnd_spd) = bec190dd944f2ce2794a7a4abf224b28
ncecat: INFO MD5 digests of RAM and disk contents for wnd_spd agree
> ncrcat -O -D 4 --md5 -p ~/nco/data in.nc in.nc ~/foo.nc | grep MD5
...
ncrcat: INFO MD5(wnd_spd) = 74699bb0a72b7f16456badb2c995f1a1
ncrcat: INFO MD5 digests of RAM and disk contents for wnd_spd agree
@end example
Regardless of the debugging level, an error is returned when the digests
of the variable read from the source file and from the output file
disagree.  

These rules are evolving and as @acronym{NCO} pays more attention to
data integrity. 
We welcome feedback and suggestions from users.

@html
<a name="bfr_sz_hnt"></a> <!-- http://nco.sf.net/nco.html#bfr_sz_hnt -->
<a name="bfr"></a> <!-- http://nco.sf.net/nco.html#bfr -->
<a name="buffer"></a> <!-- http://nco.sf.net/nco.html#buffer -->
@end html
@node Buffer sizes, RAM disks, MD5 digests, Common features
@section Buffer sizes
@cindex @code{--bfr_sz_hnt}
@cindex Buffer sizes
@cindex File buffers
@cindex @command{stat() system call}
@cindex I/O block size
@cindex System calls
@cartouche
Availability: All operators@*
Short options: @*
Long options: @samp{--bfr_sz_hnt}, @samp{--buffer_size_hint}@*  
@end cartouche

As of @acronym{NCO} version 4.2.0 (May, 2012), @acronym{NCO} 
allows the user to request specific buffer sizes to allocate for reading 
and writing files.
This buffer size determines how many system calls the netCDF layer must
invoke to read and write files.
By default, netCDF uses the preferred I/O block size returned as the
@samp{st_blksize} member of the @samp{stat} structure returned by the
@command{stat()} system call
@footnote{
On modern Linux systems the block size defaults to @w{8192 B}.
The GLADE filesystem at NCAR has a block size of @w{512 kB}.}.
Otherwise, netCDF uses twice the system pagesize.
Larger sizes can increase access speed by reducing the number of 
system calls netCDF makes to read/write data from/to disk.
Because netCDF cannot guarantee the buffer size request will be met, the 
actual buffer size granted by the system is printed as an INFO
statement. 
@example
# Request 2 MB file buffer instead of default 8 kB buffer
> ncks -O -D 3 --bfr_sz=2097152 ~/nco/data/in.nc ~/foo.nc
...
ncks: INFO nc__open() will request file buffer size = 2097152 bytes
ncks: INFO nc__open() opened file with buffer size = 2097152 bytes
...
@end example

@html
<a name="ram_all"></a> <!-- http://nco.sf.net/nco.html#ram_all -->
<a name="ram"></a> <!-- http://nco.sf.net/nco.html#ram -->
<a name="diskless"></a> <!-- http://nco.sf.net/nco.html#diskless -->
@end html
@node RAM disks, Packed data, Buffer sizes, Common features
@section RAM disks
@cindex @code{--ram_all}
@cindex @code{--create_ram}
@cindex @code{--open_ram}
@cindex @code{--diskless_all}
@cindex @acronym{RAM} disks
@cindex @acronym{RAM} files
@cindex @code{NC_DISKLESS}
@cindex diskless files
@cindex memory requirements
@cindex memory available
@cindex @acronym{RAM}
@cindex swap space
@cindex peak memory usage
@cartouche
Availability: All operators@*
Short options: @*
Long options: @samp{--ram_all}, @samp{--create_ram}, @samp{--open_ram},
@samp{--diskless_all}@*   
@end cartouche

As of @acronym{NCO} version 4.2.1 (August, 2012), @acronym{NCO} supports
the use of diskless files, aka @acronym{RAM} disks, for file access and creation. 
Two independent switches, @samp{--open_ram} and @samp{--create_ram},
control this feature. 
Before describing the specifics of these switches, we describe why many 
@acronym{NCO} operations will not benefit from them.
Essentially, reading/writing from/to @acronym{RAM} rather than disk only hastens 
the task when reads/writes to disk are avoided.
Most @acronym{NCO} operations are simple enough that they require a
single read-from/write-to disk for every block of input/output. 
Diskless access does not change this, but it does add an extra
read-from/write-to RAM. 
However this extra @acronym{RAM} write/read does avoid contention for limited
system resources like disk-head access.
Operators which may benefit from @acronym{RAM} disks include @command{ncwa}, which
may need to read weighting variables multiple times, the multi-file 
operators @command{ncra}, @command{ncrcat}, and @command{ncecat},
which may try to write output at least once per input file, and
@command{ncap2} scripts which may be arbitrarily long and convoluted. 

The @samp{--open_ram} switch causes input files to copied to @acronym{RAM} when
opened. 
All further metadata and data access occurs in @acronym{RAM} and thus avoids
access time delays caused by disk-head movement.
Usually input data is read at most once so it is unlikely that
requesting input files be stored in @acronym{RAM} will save much time.
The likeliest exceptions are files that are accessed numerous times,
such as those analyzed extensively analyzed by @command{ncap2}. 

Invoking @samp{--open_ram}, @samp{--ram_all}, or @samp{--diskless_all}
uses much more system memory.
To copy the input file to @acronym{RAM} increases the sustained
memory use by exactly the on-disk filesize of the input file, i.e.,
@math{MS += FT}.
For large input files this can be a huge memory burden that starves
the rest of the @acronym{NCO} analysis of sufficient @acronym{RAM}.
To be safe, use @samp{--open_ram}, @samp{--ram_all}, or
@samp{--diskless_all} only on files that are much (say at least a factor
of four) smaller than your available system @acronym{RAM}.
See @ref{Memory Requirements} for further details. 

@cindex @acronym{RAM} variables
The @samp{--create_ram} switch causes output files to be created in RAM,
rather than on disk. 
These files are copied to disk only when closed, i.e., when the
operator completes.
Creating files in @acronym{RAM} may save time, especially with @command{ncap2}
computations that are iterative, e.g., loops, and for multi-file
operators that write output every record (timestep) or file.
RAM files provide many of the same benefits as @acronym{RAM} variables in such
cases (@pxref{RAM variables}). 

Two switches, @samp{--ram_all} and @samp{--diskless_all}, are convenient
shortcuts for specifying both @samp{--create_ram} and
@samp{--diskless_ram}. 
Thus
@example
ncks in.nc out.nc # Default: Open in.nc on disk, write out.nc to disk
ncks --open_ram in.nc out.nc # Open in.nc in RAM, write out.nc to disk
ncks --create_ram in.nc out.nc # Create out.nc in RAM, write to disk
# Open in.nc in RAM, create out.nc in RAM, then write out.nc to disk
ncks --open_ram --create_ram in.nc out.nc
ncks --ram_all in.nc out.nc # Same as above
ncks --diskless_all in.nc out.nc # Same as above
@end example

It is straightforward to demonstrate the efficacy of @acronym{RAM} disks.
For @acronym{NASA} we constructed a test that employs @command{ncecat}
an arbitrary number (set to one hundred thousand) of files are all
symbolically linked to the same file. 
Everything is on the local filesystem (not @acronym{DAP}).
@example
# Create symbolic links for benchmark
cd $@{DATA@}/nco # Do all work here
for idx in @{1..99999@}; do
  idx_fmt=`printf "%05d" $@{idx@}`
  /bin/ln -s $@{DATA@}/nco/LPRM-AMSR_E_L3_D_SOILM3_V002-20120512T111931Z_20020619.nc \
             $@{DATA@}/nco/$@{idx_fmt@}.nc
done
# Benchmark time to ncecat one hundred thousand files
time ncecat --create_ram -O -u time -v ts -d Latitude,40.0 \ 
 -d Longitude,-105.0 -p $@{DATA@}/nco -n 99999,5,1 00001.nc ~/foo.nc
@end example
Run normally on a laptop in 201303, this completes in @w{21 seconds}.
The @samp{--create_ram} reduces the elapsed time to @w{9 seconds}.
Some of this speed may be due to using symlinks and caching.
However, the efficacy of @samp{--create_ram} is clear.
Placing the output file in @acronym{RAM} avoids thousands of disk writes.
It is not unreasonable to for @acronym{NCO} to process a million files
like this in a few minutes. 
However, there is no substitute for benchmarking with real files.

@cindex temporary output files
@cindex temporary files
@cindex @code{--no_tmp_fl}
A completely independent way to reduce time spent writing files is 
to refrain from writing temporary output files.
This is accomplished with the @samp{--no_tmp_fl} switch 
(@pxref{Temporary Output Files}).

@html
<a name="pck"></a> <!-- http://nco.sf.net/nco.html#pck -->
<a name="pack"></a> <!-- http://nco.sf.net/nco.html#pack -->
@end html
@node Packed data, Operation Types, RAM disks, Common features
@section Packed data
@cindex packing
@cindex unpacking
@cindex @code{add_offset}
@cindex @code{scale_factor}
@cindex @code{missing_value}
@cindex @code{_FillValue}
@cindex @command{pack(x)}
@cindex @command{unpack(x)}
@cindex @code{--hdf_upk}
@cindex @code{--hdf_unpack}
@cartouche
Availability: @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncflint}, @command{ncpdq}, @command{ncra}, @command{ncwa}@* 
Short options: None@*
Long options: @samp{--hdf_upk}, @samp{--hdf_unpack}@*
@end cartouche

The phrase @dfn{packed data} refers to data which are stored in the
standard netCDF3 packing format which employs a lossy algorithm.
See @ref{ncks netCDF Kitchen Sink} for a description of deflation, a 
lossless compression technique available with netCDF4 only.
Packed data may be deflated to save additional space.

@unnumberedsubsec Packing Algorithm
@dfn{Packing}
The standard netCDF packing algorithm (described
@uref{http://www.unidata.ucar.edu/software/netcdf/docs/netcdf/Attribute-Conventions.html, here})
produces data with
the same dynamic range as the original but which requires no more than
half the space to store.
Like all packing algorithms, it is @emph{lossy}.
The packed variable is stored (usually) as type @code{NC_SHORT}
with the two attributes required to unpack the variable,
@code{scale_factor} and @code{add_offset}, stored at the original
(unpacked) precision of the variable
@footnote{Although not a part of the standard, @acronym{NCO} enforces
the policy that the @code{_FillValue} attribute, if any, of a packed
variable is also stored at the original precision.}.
Let @var{min} and @var{max} be the minimum and maximum values 
@w{of @var{x}.} 
@tex
$$
\rm
\eqalign{\hbox{scale\_factor} &= (\hbox{max}-\hbox{min})/\hbox{ndrv}\cr
\hbox{add\_offset} &= (\hbox{min}+\hbox{max})/2\cr
\hbox{pck} &= (\hbox{upk}-\hbox{add\_offset})/\hbox{scale\_factor}\cr
 &= {\hbox{ndrv}\times[\hbox{upk}-(\hbox{min}+\hbox{max})/2]\over\hbox{max}-\hbox{min}}\cr}
$$
@end tex
@ifnottex
@sp 1
@var{scale_factor} = (@var{max}-@var{min})/@var{ndrv}@*
@var{add_offset} = 0.5*(@var{min}+@var{max})@*
@var{pck} = (@var{upk}-@var{add_offset})/@var{scale_factor} = (@var{upk}-0.5*(@var{min}+@var{max}))*@var{ndrv}/(@var{max}-@var{min})@* 
@sp 1
@end ifnottex
where @var{ndrv} is the number of discrete representable values for
given type of packed variable.
The theoretical maximum value for @var{ndrv} is two raised to the
number of bits used to store the packed variable.
Thus if the variable is packed into type @code{NC_SHORT}, a two-byte
datatype, then there are at most @math{2^{16} = 65536} distinct values
representable.
In practice, the number of discretely representible values is taken
to be two less than the theoretical maximum.
This leaves space for a missing value and solves potential problems with
rounding that may occur during the unpacking of the variable.
Thus for @code{NC_SHORT}, @math{ndrv = 65536 - 2 = 65534}.
Less often, the variable may be packed into type @code{NC_CHAR}, 
where @math{ndrv = 2^{8} - 2 = 256 - 2 = 254}, or type @code{NC_INT} where
where @math{ndrv = 2^{32} - 2 = 4294967295 - 2 = 4294967293}.
One useful feature of (lossy) netCDF packing algorithm is that
additional, loss-less packing algorithms perform well on top of it. 

@html
<a name="upk"></a> <!-- http://nco.sf.net/nco.html#upk -->
<a name="unpack"></a> <!-- http://nco.sf.net/nco.html#unpack -->
@end html
@unnumberedsubsec Unpacking Algorithm
@dfn{Unpacking}
The unpacking algorithm depends on the presence of two attributes,
@code{scale_factor} and @code{add_offset}.
If @code{scale_factor} is present for a variable, the data are
multiplied by the value @var{scale_factor} after the data are read.
If @code{add_offset} is present for a variable, then the
@var{add_offset} value is added to the data after the data are read.
If both @code{scale_factor} and @code{add_offset} attributes are
present, the data are first scaled by @var{scale_factor} before the
offset @var{add_offset} is added.   
@tex
$$
\rm
\eqalign{\hbox{upk} &= \hbox{scale\_factor}\times\hbox{pck} + \hbox{add\_offset}\cr 
&= {\hbox{pck}\times(\hbox{max}-\hbox{min})\over\hbox{ndrv}} + {\hbox{min}+\hbox{max}\over2}\cr} 
$$
@end tex
@ifnottex
@sp 1
@var{upk} = @var{scale_factor}*@var{pck} + @var{add_offset} = (@var{max}-@var{min})*@var{pck}/@var{ndrv} + 0.5*(@var{min}+@var{max})@*
@sp 1
@end ifnottex
When @code{scale_factor} and @code{add_offset} are used for packing, the
associated variable (containing the packed data) is typically of type
@code{byte} or @code{short}, whereas the unpacked values are intended to
be of type @code{int}, @code{float}, or @code{double}. 
An attribute's @code{scale_factor} and @code{add_offset} and
@code{_FillValue}, if any, should all be of the type intended for the
unpacked data, i.e., @code{int}, @code{float} or @code{double}. 

@unnumberedsubsec Default Handling of Packed Data
@html
<a name="hdf_upk"></a> <!-- http://nco.sf.net/nco.html#hdf_upk -->
<a name="hdf_unpack"></a> <!-- http://nco.sf.net/nco.html#hdf_unpack -->
@end html
@cindex interoperability
@cindex @acronym{HDF} unpacking
Most files originally written in @acronym{HDF} format use the
@acronym{HDF} packing/unpacking algorithm.
This algorithm is incompatible with the netCDF packing algorithm 
described above.   
The unpacking component of the @acronym{HDF} algorithm (described
@uref{http://www.hdfgroup.org/HDF5/doc/UG/UG_frame10Datasets.html, here}) is
@tex
$$
\rm
\hbox{upk} = \hbox{scale\_factor}\times(\hbox{pck} - \hbox{add\_offset})
$$
@end tex
@ifnottex
@sp 1
@var{upk} = @var{scale_factor}*(@var{pck} - @var{add_offset})@*
@sp 1
@end ifnottex
@ignore
NB: HDF packing documentation is hard to follow
MODIS HDF4 datasets definitely use the ``HDF algorithm''
However, must discriminate between HDF4 and HDF5 packing.
HDF4, or at least some HDF4 datasets implement the ``HDF algorithm'',
aka linear scale_factor and add_offset in other order from netCDF.
HDF5 only implements D-scaling, aka, decimal-scaling bit-packing.
D-Scaling uses add_offset (i.e., minimum data value) and scale_factor
(integer power of 10 by which the add_offset corrected data are divided
before storage) to control D-scaling.

@cindex scale-offset compression
@cindex scale-offset filter
@acronym{HDF} also calls this @dfn{scale-offset compression} and the
@dfn{scale-offset filter}.
@end ignore
Confusingly, the (incompatible) netCDF and @acronym{HDF} algorithms both 
store their parameters in attributes with the same names
(@code{scale_factor} and @code{add_offset}).
Data packed with one algorithm should never be unpacked with the other;
doing so will result in incorrect answers.
Unfortunately, few users are aware that their datasets may be packed,
and fewer know the details of the packing algorithm employed.
This is what we in the ``bizness'' call an @dfn{interoperability} issue
because it hampers data analysis performed on heterogeneous systems.

As described below, @acronym{NCO} automatically unpacks data before
performing arithmetic.
This automatic unpacking occurs silently since there is usually no
reason to bother users with these details. 
There is as yet no generic way for @acronym{NCO} to know which
packing convention was used, so @acronym{NCO} @emph{assumes} the netCDF 
convention was used. 
@acronym{NCO} uses the same convention for unpacking unless explicitly
told otherwise with the @samp{--hdf_upk} (also @samp{--hdf_unpack})
switch. 
Until and unless a method of automatically detecting the packing method 
is devised, it must remain the user's responsibility to tell
@acronym{NCO} when to use the @acronym{HDF} convention instead of the
netCDF convention to unpack. 

If your data originally came from an @acronym{HDF} file (e.g.,
@acronym{NASA} @acronym{EOS}) then it was likely packed with the
@acronym{HDF} convention and must be unpacked with the same convention.
Our recommendation is to only request @acronym{HDF} unpacking when you 
are certain. 
Most packed datasets encountered by @acronym{NCO} will have used the
netCDF convention.
Those that were not will hopefully produce noticeably weird values when
unpacked by the wrong algorithm.
Before or after panicking, treat this as a clue to re-try your commands
with the @samp{--hdf_upk} switch.
See @ref{ncpdq netCDF Permute Dimensions Quickly} for an easy technique
to unpack data packed with the @acronym{HDF} convention, and then
re-pack it with the netCDF convention.

@unnumberedsubsec Default Handling of Packed Data
All @acronym{NCO} arithmetic operators understand packed data.
The operators automatically unpack any packed variable in the input 
file which will be arithmetically processed.
For example, @command{ncra} unpacks all record variables, 
and @command{ncwa} unpacks all variable which contain a dimension to 
be averaged.
These variables are stored unpacked in the output file.

On the other hand, arithmetic operators do not unpack non-processed
variables. 
For example, @command{ncra} leaves all non-record variables packed, 
and @command{ncwa} leaves packed all variables lacking an averaged
dimension.  
These variables (called fixed variables) are passed unaltered from the
input to the output file. 
Hence fixed variables which are packed in input files remain packed in
output files.
Completely packing and unpacking files is easily accomplished with
@command{ncpdq} (@pxref{ncpdq netCDF Permute Dimensions Quickly}).
Pack and unpack individual variables with @command{ncpdq} and the
@command{ncap2} @command{pack()} and @command{unpack()} functions
(@pxref{Methods and functions}).

@html
<a name="op_typ"></a> <!-- http://nco.sf.net/nco.html#op_typ -->
@end html
@node Operation Types, Type Conversion, Packed data, Common features
@section Operation Types
@cindex operation types
@cindex @code{avg}
@cindex @code{sqravg}
@cindex @code{avgsqr}
@cindex @code{min}
@cindex @code{max}
@cindex @code{rmssdn}
@cindex @code{rms}
@cindex @code{ttl}
@cindex @code{sqrt}
@cindex average
@cindex mean
@cindex total
@cindex minimum
@cindex maximum
@cindex root-mean-square
@cindex standard deviation
@cindex variance
@cindex @code{-y @var{op_typ}}
@cindex @code{--operation @var{op_typ}}
@cindex @code{--op_typ @var{op_typ}}
@cartouche
Availability: @command{ncap2}, @command{ncra}, @command{nces}, @command{ncwa}@*
Short options: @samp{-y}@*
Long options: @samp{--operation}, @samp{--op_typ}@*
@end cartouche
@noindent
The @samp{-y @var{op_typ}} switch allows specification of many different
types of operations 
Set @var{op_typ} to the abbreviated key for the corresponding operation:
@table @code
@item avg
Mean value
@item sqravg
Square of the mean
@item avgsqr
Mean of sum of squares
@item max
Maximium value
@item min
Minimium value
@item rms
Root-mean-square (normalized by @var{N})
@item rmssdn
Root-mean square (normalized by @var{N-1})
@item sqrt
Square root of the mean
@item ttl
Sum of values
@end table
@noindent
@cindex coordinate variable 
@acronym{NCO} assumes coordinate variables represent grid axes, e.g.,
longitude. 
The only rank-reduction which makes sense for coordinate variables
is averaging.
Hence @acronym{NCO} implements the operation type requested with
@samp{-y} on all non-coordinate variables, not on coordinate variables.  
When an operation requires a coordinate variable to be reduced in
rank, i.e., from one dimension to a scalar or from one dimension to
a degenerate (single value) array, then @acronym{NCO} 
@emph{always averages} the coordinate variable regardless of the
arithmetic operation type performed on the non-coordinate variables.

The mathematical definition of each arithmetic operation is given below. 
@xref{ncwa netCDF Weighted Averager}, for additional information on
masks and normalization.
If an operation type is not specified with @samp{-y} then the operator
performs an arithmetic average by default.
Averaging is described first so the terminology for the other operations
is familiar. 

@ifhtml
@cartouche
@html
<p><b>Note for HTML users</b>: 
<br>The definition of mathematical operations involving rank reduction
(e.g., averaging) relies heavily on mathematical expressions which
cannot easily be represented in HTML.  
<b>See the <a href="./nco.pdf">printed manual</a> for much more detailed
and complete documentation of this subject.</b>
@end html
@end cartouche
@end ifhtml
@ifnothtml
@ifinfo
@emph{Note for Info users}: 
The definition of mathematical operations involving rank reduction
(e.g., averaging) relies heavily on mathematical expressions which
cannot be easily represented in Info.
@emph{See the @uref{./nco.pdf, printed manual} for much more detailed and
complete documentation of this subject.}
@end ifinfo
@end ifnothtml

@tex
The masked, weighted average of a variable $\xxx$ can be generally
represented as
$$
\bar \xxx_{\jjj} = {\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx}
\mskflg_{\idx} \wgt_{\idx} \xxx_{\idx} \over
\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx}}  
$$
where $\bar \xxx_{\jjj}$ is the $\jjj$'th element of the output
hyperslab, $\xxx_{\idx}$ is the $\idx$'th element of the input
hyperslab, $\mssflg_{\idx}$ is~1 unless $\xxx_{\idx}$ equals the missing  
value, $\mskflg_{\idx}$ is~1 unless $\xxx_{\idx}$ is masked, and
$\wgt_{\idx}$ is the weight.  
This formiddable looking formula represents a simple weighted average
whose bells and whistles are all explained below. 
It is not too early to note, however, that when 
$\mssflg_{\idx} = \mskflg_{\idx} = \wgt_{\idx} = 1$, the 
generic averaging expression above reduces to a simple arithmetic
average.  
Furthermore, $\mskflg_{\idx} = \wgt_{\idx} = 1$ for all operators
except @command{ncwa}.
These variables are included in the discussion below for completeness,
and for possible future use in other operators. 

The size $\outnbr$ of the output hyperslab for a given variable is the
product of all the dimensions of the input variable which are not
averaged over. 
The size $\lmnnbr$ of the input hyperslab contributing to each 
$\bar \xxx_{\jjj}$ is simply the product of the sizes of all dimensions
which are averaged over (i.e., dimensions specified with @samp{-a}).  
Thus $\lmnnbr$ is the number of input elements which @emph{potentially} 
contribute to each output element.
An input element $\xxx_{\idx}$ contributes to the output element
$\xxx_{\jjj}$ except in two conditions:  
@cindex missing values
@enumerate
@item $\xxx_{\idx}$ equals the @var{missing value} 
(@pxref{Missing Values}) for the variable. 
@item $\xxx_{\idx}$ is located at a point where the mask condition 
(@pxref{Mask condition}) is false.
@end enumerate
Points $\xxx_{\idx}$ in either of these two categories do not contribute 
to $\xxx_{\jjj}$---they are ignored.
We now define these criteria more rigorously.

Each~$\xxx_{\idx}$ has an associated Boolean weight~$\mssflg_{\idx}$
whose value is~0 or~1 (false or true). 
The value of~$\mssflg_{\idx}$ is~1 (true) unless $\xxx_{\idx}$ equals
the @var{missing value} (@pxref{Missing Values}) for the variable. 
Thus, for a variable with no @code{_FillValue} attribute,
$\mssflg_{\idx}$~is always~1.
All @acronym{NCO} arithmetic operators (@command{ncbo},
@command{ncra}, @command{nces}, @command{ncflint}, @command{ncwa}) treat  
missing values analogously. 

Besides (weighted) averaging, @command{ncwa}, @command{ncra}, and
@command{nces} also compute some common non-linear operations which may
be specified with the @samp{-y} switch (@pxref{Operation Types}).
The other rank-reducing operations are simple variations of the generic
weighted mean described above.
The total value of~$\xxx$ (@code{-y ttl}) is 
$$
\bar \xxx_{\jjj} = \sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx}
\mskflg_{\idx} \wgt_{\idx} \xxx_{\idx}  
$$
@cindex @code{-N}
@cindex @code{numerator}
Note that the total is the same as the numerator of the mean
of~$\xxx$, and may also be obtained in @command{ncwa} by using the
@samp{-N} switch (@pxref{ncwa netCDF Weighted Averager}).

The minimum value of~$\xxx$ (@code{-y min}) is 
$$
\bar \xxx_{\jjj} = \min [ \mssflg_{1} \mskflg_{1} \wgt_{1} \xxx_{1},
\mssflg_{2} \mskflg_{2} \wgt_{2} \xxx_{2}, \ldots, \mssflg_{\lmnnbr} 
\mskflg_{\lmnnbr} \wgt_{\lmnnbr} \xxx_{\lmnnbr} ] 
$$
Analogously, the maximum value of~$\xxx$ (@code{-y max}) is 
$$
\bar \xxx_{\jjj} = \max [ \mssflg_{1} \mskflg_{1} \wgt_{1} \xxx_{1},
\mssflg_{2} \mskflg_{2} \wgt_{2} \xxx_{2}, \ldots, \mssflg_{\lmnnbr} 
\mskflg_{\lmnnbr} \wgt_{\lmnnbr} \xxx_{\lmnnbr} ] 
$$
Thus the minima and maxima are determined after any weights are applied.

The square of the mean value of~$\xxx$ (@code{-y sqravg}) is 
$$
\bar \xxx_{\jjj} = \left( {\sum_{\idx=1}^{\idx=\lmnnbr}
\mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx} \xxx_{\idx} \over
\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx}} 
\right)^{2}    
$$
The mean of the sum of squares of~$\xxx$ (@code{-y avgsqr}) is 
$$
\bar \xxx_{\jjj} = {\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx}
\mskflg_{\idx} \wgt_{\idx} \xxx^{2}_{\idx} \over
\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx}} 
$$
If $\xxx$ represents a deviation from the mean of another variable,
$\xxx_{\idx} = \yyy_{\idx} - \bar{\yyy}$ (possibly created by
@command{ncbo} in a previous step), then applying @code{avgsqr} to
$\xxx$ computes the approximate variance of $\yyy$. 
Computing the true variance of~$\yyy$ requires subtracting~1 from the
denominator, discussed below.
For a large sample size however, the two results will be nearly
indistinguishable. 

The root mean square of~$\xxx$ (@code{-y rms}) is 
$$
\bar \xxx_{\jjj} = \sqrt{ {\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx}
\mskflg_{\idx} \wgt_{\idx} x^{2}_{\idx} \over
\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx}}} 
$$
Thus @code{rms} simply computes the squareroot of the quantity computed
by @code{avgsqr}.

The root mean square of~$\xxx$ with standard-deviation-like
normalization (@code{-y rmssdn}) is implemented as follows.
When weights are not specified, this function is the same as the root
mean square of~$\xxx$ except one is subtracted from the sum in the
denominator 
$$
\bar \xxx_{\jjj} = \sqrt{ {\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} 
\mskflg_{\idx} x^{2}_{\idx} \over -1 + \sum_{\idx=1}^{\idx=\lmnnbr}
\mssflg_{\idx} \mskflg_{\idx}} } 
$$
If $\xxx$ represents the deviation from the mean of another variable, 
$\xxx_{\idx} = \yyy_{\idx} - \bar{\yyy}$, then applying @code{rmssdn} to
$\xxx$ computes the standard deviation of~$\yyy$.
In this case the $-1$ in the denominator compensates for the degree of
freedom already used in computing $\bar{\yyy}$ in the numerator.
Consult a statistics book for more details.

When weights are specified it is unclear how to compensate for this
extra degree of freedom.
Weighting the numerator and denominator of the above by $\wgt_{\idx}$
and subtracting one from the denominator is only appropriate when all
the weights are~1.0.
When the weights are arbitrary (e.g., Gaussian weights), subtracting one 
from the sum in the denominator does not necessarily remove one degree
of freedom. 
Therefore when @code{-y rmssdn} is requested and weights are specified,
@command{ncwa} actually implements the @code{rms} procedure.
@command{nces} and @command{ncra}, which do not allow weights to be
specified, always implement the @code{rmssdn} procedure when asked.

@c 20130827: Fedora Core 19 (FC19) broke here with "./nco.texi:6394: Missing dollarsign inserted."
@c Ubuntu always built nco.texi fine
@c Adding a dollarsign character right here breaks Ubuntu builds too
@c Hence I must carefully spell-out the word dollarsign instead
@c 20130829: Making many smaller TeX environments does not solve problem
@c 20130910: Using latest texinfo.tex from GNU does not solve problem
@c 20130910: Karl Berry solved problem by fixing bug in texinfo.tex
@c Bug was triggered in Fedora by apostrophe in "User's Guide" (manual title)
@c Bug not present in texinfo.tex version 2008-04-18.10 (used by Ubuntu 13.04)
@c Bug     present in texinfo.tex version 2013-02-01.11 (used by FC19)
@c Bug just fixed  in texinfo.tex version 2013-09-11 (committed by Karl)
@c nco/autobld/texinfo.tex now contains fixed version
@c Breakage always occurs near here
The square root of the mean of~$\xxx$ (@code{-y sqrt}) is 
$$
\bar \xxx_{\jjj} = \sqrt{ {\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx}
\mskflg_{\idx} \wgt_{\idx} \xxx_{\idx} \over
\sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} \wgt_{\idx}}}  
$$
@end tex
The definitions of some of these operations are not universally useful.
Mostly they were chosen to facilitate standard statistical
computations within the @acronym{NCO} framework.
We are open to redefining and or adding to the above. 
If you are interested in having other statistical quantities
defined in @acronym{NCO} please contact the @acronym{NCO} project
(@pxref{Help Requests and Bug Reports}).  

@noindent
EXAMPLES

@html
<a name="min"></a> <!-- http://nco.sf.net/nco.html#min -->
<a name="max"></a> <!-- http://nco.sf.net/nco.html#max -->
<a name="rms"></a> <!-- http://nco.sf.net/nco.html#rms -->
@end html
@noindent
Suppose you wish to examine the variable @code{prs_sfc(time,lat,lon)} 
which contains a time series of the surface pressure as a function of
latitude and longitude.
Find the minimium value of @code{prs_sfc} over all dimensions:
@example
ncwa -y min -v prs_sfc in.nc foo.nc 
@end example
@noindent
Find the maximum value of @code{prs_sfc} at each time interval for each
latitude: 
@example
ncwa -y max -v prs_sfc -a lon in.nc foo.nc
@end example
@noindent
Find the root-mean-square value of the time-series of @code{prs_sfc} at
every gridpoint:
@example
ncra -y rms -v prs_sfc in.nc foo.nc
ncwa -y rms -v prs_sfc -a time in.nc foo.nc
@end example
@noindent
The previous two commands give the same answer but @command{ncra} is
preferred because it has a smaller memory footprint.
@cindex degenerate dimension
A dimension of size one is said to be @dfn{degenerate}.
By default, @command{ncra} leaves the (degenerate) @code{time}
dimension in the output file (which is usually useful) whereas
@command{ncwa} removes the @code{time} dimension (unless @samp{-b} is
given).

@noindent
These operations work as expected in multi-file operators.
Suppose that @code{prs_sfc} is stored in multiple timesteps per file
across multiple files, say @file{jan.nc}, @file{feb.nc},
@file{march.nc}.  
We can now find the three month maximium surface pressure at every point.
@example
nces -y max -v prs_sfc jan.nc feb.nc march.nc out.nc
@end example

@html
<a name="standard_deviation"></a> <!-- http://nco.sf.net/nco.html#standard_deviation -->
<a name="stddvn"></a> <!-- http://nco.sf.net/nco.html#stddvn -->
<a name="sdn"></a> <!-- http://nco.sf.net/nco.html#sdn -->
<a name="sdv"></a> <!-- http://nco.sf.net/nco.html#sdv -->
<a name="xmp_sdn"></a> <!-- http://nco.sf.net/nco.html#xmp_sdn -->
@end html
@noindent
@cindex standard deviation
It is possible to use a combination of these operations to compute
the variance and standard deviation of a field stored in a single file
or across multiple files.
The procedure to compute the temporal standard deviation of the surface
pressure at all points in a single file @file{in.nc} involves three
steps. 
@example
ncwa -O -v prs_sfc -a time in.nc out.nc
ncbo -O -v prs_sfc in.nc out.nc out.nc 
ncra -O -y rmssdn out.nc out.nc
@end example
First construct the temporal mean of @code{prs_sfc} in the file
@file{out.nc}.
Next overwrite @file{out.nc} with the anomaly (deviation from the mean).
Finally overwrite @file{out.nc} with the root-mean-square of itself. 
Note the use of @samp{-y rmssdn} (rather than @samp{-y rms}) in the
final step. 
This ensures the standard deviation is correctly normalized by one fewer
than the number of time samples.
The procedure to compute the variance is identical except for the use of 
@samp{-y var} instead of @samp{-y rmssdn} in the final step.

@command{ncap2} can also compute statistics like standard deviations.
Brute-force implementation of formulae is one option, e.g.,
@example
ncap2 -s 'prs_sfc_sdn=sqrt((prs_sfc-prs_sfc.avg($time)^2).total($time)/($time.size-1))'
      in.nc out.nc
@end example
The operation may, of course, be broken into multiple steps in order  
to archive intermediate quantities, such as the time-anomalies
@example
ncap2 -s 'prs_sfc_anm=prs_sfc-prs_sfc.avg($time)' \
      -s 'prs_sfc_sdn=sqrt((prs_sfc_anm^2).total($time)/($time.size-1))' \
      in.nc out.nc
@end example

@command{ncap2} supports intrinsic standard deviation functions
(@pxref{Operation Types}) which simplify the above expression to
@example
ncap2 -s 'prs_sfc_sdn=(prs_sfc-prs_sfc.avg($time)).rmssdn($time)' in.nc out.nc
@end example
These instrinsic functions compute the answer quickly and concisely.

The procedure to compute the spatial standard deviation of a field
in a single file @file{in.nc} involves three steps.
@example
ncwa -O -v prs_sfc,gw -a lat,lon -w gw in.nc out.nc
ncbo -O -v prs_sfc,gw in.nc out.nc out.nc
ncwa -O -y rmssdn -v prs_sfc -a lat,lon -w gw out.nc out.nc
@end example
First the appropriately weighted (with @samp{-w gw}) spatial mean values
are written to the output file.  
This example includes the use of a weighted variable specified with
@samp{-w gw}. 
When using weights to compute standard deviations one must remember to
include the weights in the initial output files so that they may be used
again in the final step. 
The initial output file is then overwritten with the gridpoint
deviations from the spatial mean.
Finally the root-mean-square of the appropriately weighted spatial
deviations is taken.  

The @command{ncap2} solution to the spatially-weighted standard
deviation problem is 
@example
ncap2 -s 'prs_sfc_sdn=(prs_sfc*gw-prs_sfc*gw.avg($lat,$lon)).rmssdn($lat,$lon)' \
      in.nc out.nc
@end example
Be sure to multiply the variable by the weight prior to computing the
the anomalies and the standard deviation.

The procedure to compute the standard deviation of a time-series across
multiple files involves one extra step since all the input must first be
collected into one file. 
@example
ncrcat -O -v tpt in.nc in.nc foo1.nc
ncwa -O -a time foo1.nc foo2.nc
ncbo -O -v tpt foo1.nc foo2.nc foo3.nc
ncra -O -y rmssdn foo3.nc out.nc
@end example
The first step assembles all the data into a single file.
Though this may consume a lot of temporary disk space, it is more or
less required by the @command{ncbo} operation in the third step.

@html
<a name="typ_cnv"></a> <!-- http://nco.sf.net/nco.html#typ_cnv -->
@end html
@node Type Conversion, Batch Mode, Operation Types, Common features
@section Type Conversion
@cindex type conversion
@cartouche
Availability (automatic type conversion): @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncflint}, @command{ncra}, @command{ncwa}@* 
Short options: None (it's @emph{automatic})@*
Availability (manual type conversion): @command{nces}, @command{ncra}, @command{ncwa}@* 
Short options: None@*
Long options: @samp{--dbl}, @samp{--flt}, @samp{--rth_dbl}, @samp{--rth_flt}@* 
@end cartouche
@cindex promotion
@cindex demotion
@cindex automatic type conversion
@cindex manual type conversion
Type conversion refers to the casting or coercion of one fundamental or
atomic data type to another, e.g., converting @code{NC_SHORT} (two
bytes) to @code{NC_DOUBLE} (eight bytes).  
Type conversion always @dfn{promotes} or @dfn{demotes} the range and/or 
precision of the values a variable can hold.
Type conversion is automatic when the language carries out this
promotion according to an internal set of rules without explicit user 
intervention. 
In contrast, manual type conversion refers to explicit user commands to
change the type of a variable or attribute.
Most type conversion happens automatically, yet there are situations in
which manual type conversion is advantageous.

@menu
* Automatic type conversion::
* Promoting Single-precision to Double::
* Manual type conversion::
@end menu

@node Automatic type conversion, Promoting Single-precision to Double, Type Conversion, Type Conversion
@subsection Automatic type conversion

There are at least two reasons to avoid type conversions.
First, type conversions are expensive since they require creating
(temporary) buffers and casting each element of a variable from its 
storage type to some other type and then, often, converting it back.
Second, a dataset's creator perhaps had a good reason for storing 
data as, say, @code{NC_FLOAT} rather than @code{NC_DOUBLE}.  
In a scientific framework there is no reason to store data with more
precision than the observations merit.
Normally this is single-precision, which guarantees 6--9 digits of
precision. 
Reasons to engage in type conversion include avoiding rounding 
errors and out-of-range limitations of less-precise types.
This is the case with most integers.
Thus @acronym{NCO} defaults to automatically promote integer types to
floating point when performing lengthy arithmetic, yet @acronym{NCO}
defaults to not promoting single to double-precision floats.

Before discussing the more subtle floating point issues, we first
examine integer promotion. 
We will show how following parsimonious conversion rules dogmatically
can cause problems, and what @acronym{NCO} does about that. 
That said, there are situations in which implicit conversion of
single- to double-precision is also warranted.
Understanding the narrowness of these situations takes time, and we
hope the reader appreciates the following detailed discussion.

Consider the average of the two @code{NC_SHORT}s @code{17000s} and
@code{17000s}.
A straightforward average without promotion results in garbage since the
intermediate value which holds their sum is also of type @code{NC_SHORT}
and thus overflows on (i.e., cannot represent) values greater than
32,767 
@footnote{
@set flg
@tex
$32767 = 2^{15}-1$
@clear flg
@end tex
@ifinfo
@math{32767 = 2^15-1}
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
32767 = 2^15@minus{}1
@clear flg
@end ifset
}.
There are valid reasons for expecting this operation to succeed and 
the @acronym{NCO} philosophy is to make operators do what you want, not
what is purest.
Thus, unlike C and Fortran, but like many other higher level interpreted
languages, @acronym{NCO} arithmetic operators will perform automatic type
conversion on integers when all the following conditions are met
@footnote{Operators began performing automatic type conversions before
arithmetic in @acronym{NCO} @w{version 1.2}, August, 2000. 
Previous versions never performed unnecessary type conversion for
arithmetic.}: 
@enumerate
@item The requested operation is arithmetic.
This is why type conversion is limited to the operators @command{ncap2}, 
@command{ncbo}, @command{nces}, @command{ncflint}, @command{ncra}, and
@command{ncwa}.   
@item The arithmetic operation could benefit from type conversion.
Operations that could benefit include averaging, summation, or any
"hard" arithmetic that could overflow or underflow.  
Larger representable sums help avoid overflow, and more precision
helps to avoid underflow.
Type conversion does not benefit searching for minima and maxima
(@samp{-y min}, or @samp{-y max}).
@item The variable on disk is of type @code{NC_BYTE}, @code{NC_CHAR},
@code{NC_SHORT}, or @code{NC_INT}.
Type @code{NC_DOUBLE} is not promoted because there is no type of
higher precision.
Conversion of type @code{NC_FLOAT} is discussed in detail below. 
When it occurs, it follows the same procedure (promotion then
arithmetic then demotion) as conversion of integer types.
@end enumerate

When these criteria are all met, the operator promotes the variable in
question to type @code{NC_DOUBLE}, performs all the arithmetic
operations, casts the @code{NC_DOUBLE} type back to the original type,
and finally writes the result to disk. 
The result written to disk may not be what you expect, because of
incommensurate ranges represented by different types, and because of
(lack of) rounding.
First, continuing the above example, the average (e.g., @samp{-y avg})
of @code{17000s} and @code{17000s} is written to disk as @code{17000s}. 
The type conversion feature of @acronym{NCO} makes this possible since
the arithmetic and intermediate values are stored as @code{NC_DOUBLE}s,
i.e., @code{34000.0d} and only the final result must be represented
as an @code{NC_SHORT}.
Without the type conversion feature of @acronym{NCO}, the average would
have been garbage (albeit predictable garbage near @code{-15768s}). 
Similarly, the total (e.g., @samp{-y ttl}) of @code{17000s} and
@code{17000s} written to disk is garbage (actually @code{-31536s}) since 
the final result (the true total) of @math{34000} is outside the range
of type @code{NC_SHORT}.  

@cindex @code{trunc()}
After arithmetic is computed in double-precision for promoted variables,
the intermediate double-precision values must be demoted to the
variables' original storage type (e.g., from @code{NC_DOUBLE} to
@code{NC_SHORT}). 
@acronym{NCO} has handled this demotion in three ways in its history.
Prior to October, 2011 (version 4.0.8), @acronym{NCO} employed the
@w{C library} truncate function, @code{trunc()}
@footnote{
@cindex C language
The actual type conversions with trunction were handled by intrinsic
type conversion, so the @code{trunc()} function was never explicitly
called, although the results would be the same if it were.}.
Truncation rounds @var{x} to the nearest integer not larger in absolute 
value.
For example, truncation rounds @code{1.0d}, @code{1.5d}, and
@code{1.8d} to the same value, @code{1s}. 
Clearly, truncation does not round floating point numbers to the nearest
integer! 
Yet truncation is how the @w{C language} performs implicit conversion of 
real numbers to integers.

@cindex Neil Davis
@acronym{NCO} stopped using truncation for demotion when an alert user
(Neil Davis) informed us that this caused a small bias in the packing
algorithm employed by @command{ncpdq}.
This led to @acronym{NCO} adopting rounding functions for demotion.
Rounding functions eliminated the small bias in the packing algorithm.

@findex @code{lround()}. 
From February, 2012 through March, 2013 (versions 4.0.9--4.2.6),
@acronym{NCO} employed the @w{C library} family of rounding functions,
@code{lround()}. 
These functions round @var{x} to the nearest integer, halfway cases away
from zero.
The problem with @code{lround()} is that it always rounds real values
ending in @code{.5} away from zero.
This rounds, for example, @code{1.5d} and @code{2.5d} to @code{1s}
and @code{2s}, respectively.

@findex @code{lrint()}. 
@cindex @acronym{IEEE}
Since April, 2013 (version 4.3.0), @acronym{NCO} has employed the 
other @w{C library} family of rounding functions, @code{lrint()}. 
This algorithm rounds @var{x} to the nearest integer, using the current 
rounding direction.
Halfway cases are rounded to the nearest even integer.
This rounds, for example, both @code{1.5d} and @code{2.5d} to the same
value, @code{2s}, as recommended by the @acronym{IEEE}.
This rounding is symmetric: up half the time, down half the time.
This is the current and hopefully final demotion algorithm employed by  
@acronym{NCO}.

Hence because of automatic conversion, @acronym{NCO} will compute the
average of @code{2s} and @code{3s} in double-precision arithmetic as 
@math{(@code{2.0d} + @code{3.0d})/@code{2.0d}) = @code{2.5d}}.
It then demotes this intermediate result back to @code{NC_SHORT} and
stores it on disk as  
@math{@code{trunc(2.5d)} = @code{2s}} (versions up to 4.0.8), 
@math{@code{lround(2.5d)} = @code{3s}} (versions 4.0.9--4.2.6), and
@math{@code{lrint(2.5d)} = @code{2s}} (versions 4.3.0 and later).

@html
<a name="sp_dp"></a> <!-- http://nco.sf.net/nco.html#sp_dp -->
<a name="dbl"></a> <!-- http://nco.sf.net/nco.html#dbl -->
@end html
@node Promoting Single-precision to Double, Manual type conversion, Automatic type conversion, Type Conversion
@subsection Promoting Single-precision to Double
@cindex promotion
@cindex implicit conversion
@cindex @code{--dbl}
@cindex @code{--rth_dbl}
@cindex @code{--flt}
@cindex @code{--rth_flt}
Promotion of real numbers from single- to double-precision is
fundamental to scientific computing.
When it should occur depends on the precision of the inputs and the
number of operations.
Single-precision (four-byte) numbers contain about seven significant
figures, while double-precision contain about sixteen.
More, err, precisely, the @acronym{IEEE} single-precision representation
gives from @w{6 to 9} significant decimal digits precision
@footnote{According to Wikipedia's summary of @acronym{IEEE} standard
754, ``If a decimal string with at most 6 significant digits is
converted to IEEE 754 single-precision and then converted back to the
same number of significant decimal, then the final string should match
the original; and if an IEEE 754 single-precision is converted to a
decimal string with at least 9 significant decimal and then converted
back to single, then the final number must match the original''.}.
And the @acronym{IEEE} double-precision representation
gives from @w{15 to 17} significant decimal digits precision
@footnote{According to Wikipedia's summary of @acronym{IEEE} standard
754, ``If a decimal string with at most 15 significant digits is
converted to IEEE 754 double-precision representation and then converted
back to a string with the same number of significant digits, then the
final string should match the original; and if an IEEE 754 double
precision is converted to a decimal string with at least 17 significant
digits and then converted back to double, then the final number must
match the original''.}. 
Hence double-precision numbers represent about nine digits more
precision than single-precision numbers.

Given these properties, there are at least two possible arithmetic
conventions for the treatment of real numbers:
@cindex C language
@cindex Fortran
@enumerate
@item Conservative, aka Fortran Convention
Automatic type conversion during arithmetic in the Fortran language is,
by default, performed only when necessary. 
All operands in an operation are converted to the most precise type
involved the operation before the arithmetic operation.
Expressions which involve only single-precision numbers are computed
entirely in single-precision.
Expressions involving mixed precision types are computed in the type
of higher precision.
@acronym{NCO} by default employs the Fortan Convention for promotion.
@item Aggressive, aka C Convention
The @w{C language} is by default much more aggressive (and thus
wasteful) than Fortran, and will always implicitly convert single- 
to double-precision numbers for no good reason.
All real-number standard @w{C library} functions are double-precision, 
and @w{C programmers} must take extra steps to only utilize single
precision arithmetic.
The high level interpreted data analysis languages @acronym{IDL},
Matlab, and @acronym{NCL} all adopt the @w{C Convention}.
@end enumerate

@acronym{NCO} does not automatically promote @code{NC_FLOAT} because, in
our judgement, the performance penalty of always doing so would outweigh
the potential benefits. 
The now-classic text ``Numerical Recipes @w{in C}'' discusses this point
under the section ``Implicit Conversion of Float to Double''
@footnote{See @w{page 21} in Section 1.2 of the First edition for this
gem:
@quotation
One does not need much experience in scientific computing to recognize
that the implicit conversion rules are, in fact, sheer madness!
In effect, they make it impossible to write efficient numerical
programs. 
@end quotation
}.
That said, such promotion is warranted in some circumstances.

For example, rounding errors can accumulate to worrisome levels during
arithmetic performed on large arrays of single-precision floats. 
This use-case occurs often in geoscientific studies of climate where
thousands-to-millions of gridpoints may contribute to a single average.
If the inputs are all single-precision, then so should be the output.
However the intermediate results where running sums are accumulated may  
suffer from too much rounding or from underflow unless computed in
double-precision. 

The order of operations matters to floating point math even when the
analytic expressions are equal. 
Cautious users feel disquieted when results from equally valid analyses
differ in the final bits instead of agreeing bit-for-bit.
For example, averaging arrays in multiple stages produces different
answers than averaging them in one step. 
This is easily seen in the computation of ensemble averages by two
different methods.
The @acronym{NCO} test file @file{in.nc} contains single- and
double-precision representations of the same temperature timeseries as 
@code{tpt_flt} and @code{tpt_dbl}.  
Pretend each datapoint in this timeseries represents a monthly-mean
temperature. 
We will mimic the derivation of a fifteen-year ensemble-mean January
temperature by concatenating the input file five times, and then
averaging the datapoints representing January two different ways.
In @w{Method 1} we derive the 15-year ensemble January average in two 
steps, as the average of three five-year averages.
This method is naturally used when each input file contains multiple
years and multiple input files are needed
@footnote{For example, the @acronym{CMIP5} archive tends to distribute
monthly average timeseries in 50-year chunks.}.
In @w{Method 2} we obtain 15-year ensemble January average in a single
step, by averaging all 15 Januaries at one time:
@example
# tpt_flt and tpt_dbl are identical except for precision
ncks --cdl -C -v tpt_flt,tpt_dbl ~/nco/data/in.nc
# tpt_dbl = 273.1, 273.2, 273.3, 273.4, 273.5, 273.6, 273.7, 273.8, 273.9, 274
# tpt_flt = 273.1, 273.2, 273.3, 273.4, 273.5, 273.6, 273.7, 273.8, 273.9, 274
# Create file with five "ten-month years" (i.e., 50 timesteps) of temperature data
ncrcat -O -v tpt_flt,tpt_dbl -p ~/nco/data in.nc in.nc in.nc in.nc in.nc ~/foo.nc
# Average 1st five "Januaries" (elements 1, 11, 21, 31, 41)
ncra --flt -O -F -d time,1,,10 ~/foo.nc ~/foo_avg1.nc
# Average 2nd five "Januaries" (elements 2, 12, 22, 32, 42)
ncra --flt -O -F -d time,2,,10 ~/foo.nc ~/foo_avg2.nc
# Average 3rd five "Januaries" (elements 3, 13, 23, 33, 43)
ncra --flt -O -F -d time,3,,10 ~/foo.nc ~/foo_avg3.nc
# Method 1: Obtain ensemble January average by averaging the averages
ncra --flt -O ~/foo_avg1.nc ~/foo_avg2.nc ~/foo_avg3.nc ~/foo_avg_mth1.nc
# Method 2: Obtain ensemble January average by averaging the raw data
# Employ ncra's "subcycle" feature (http://nco.sf.net/nco.html#ssc)
ncra --flt -O -F -d time,1,,10,3 ~/foo.nc ~/foo_avg_mth2.nc
# Difference the two methods
ncbo -O ~/foo_avg_mth1.nc ~/foo_avg_mth2.nc ~/foo_avg_dff.nc
ncks --cdl ~/foo_avg_dff.nc
# tpt_dbl = 5.6843418860808e-14 ;
# tpt_flt = -3.051758e-05 ;
@end example
Although the two methods are arithmetically equivalent, they produce
slightly different answers due to the different order of operations.
Moreover, it appears at first glance that the single-precision
answers suffer from greater error than the double-precision answers.
In fact both precisions suffer from non-zero rounding errors.
The answers differ negligibly to machine precision, which is about 
seven significant figures for single precision floats (@code{tpt_flt}),
and sixteen significant figures for double precision (@code{tpt_dbl}).
The input precision determines the answer precision.

IEEE arithmetic guarantees that two methods will produce bit-for-bit
identical answers only if they compute the same operations in the same  
order.  
Bit-for-bit identical answers may also occur by happenstance when 
rounding errors exactly compensate one another.
This is demonstrated by repeating the example above with the
@samp{--dbl} (or @samp{--rth_dbl} for clarity) option which forces
conversion of single-precision numbers to double-precision prior to
arithmetic. 
Now @command{ncra} will treat the first value of @code{tpt_flt},
@code{273.1000f}, as @code{273.1000000000000d}. 
Arithmetic on @code{tpt_flt} then proceeds in double-precision until the
final answer, which is converted back to single-precision for final
storage. 
@example
# Average 1st five "Januaries" (elements 1, 11, 21, 31, 41)
ncra --dbl -O -F -d time,1,,10 ~/foo.nc ~/foo_avg1.nc
# Average 2nd five "Januaries" (elements 2, 12, 22, 32, 42)
ncra --dbl -O -F -d time,2,,10 ~/foo.nc ~/foo_avg2.nc
# Average 3rd five "Januaries" (elements 3, 13, 23, 33, 43)
ncra --dbl -O -F -d time,3,,10 ~/foo.nc ~/foo_avg3.nc
# Method 1: Obtain ensemble January average by averaging the averages
ncra --dbl -O ~/foo_avg1.nc ~/foo_avg2.nc ~/foo_avg3.nc ~/foo_avg_mth1.nc
# Method 2: Obtain ensemble January average by averaging the raw data
# Employ ncra's "subcycle" feature (http://nco.sf.net/nco.html#ssc)
ncra --dbl -O -F -d time,1,,10,3 ~/foo.nc ~/foo_avg_mth2.nc
# Difference the two methods
ncbo -O ~/foo_avg_mth1.nc ~/foo_avg_mth2.nc ~/foo_avg_dff.nc
# Show differences
ncks --cdl ~/foo_avg_dff.nc
# tpt_dbl = 5.6843418860808e-14 ;
# tpt_flt = 0 ;
@end example
The @samp{--dbl} switch has no effect on the results computed from
double-precision inputs.
But now the two methods produce bit-for-bit identical results from the
single-precision inputs!
This is due to the happenstance of rounding along with the effects of 
the @samp{--dbl} switch.
The @samp{--flt} and @samp{--rth_flt} switches are provided for
symmetry.
They enforce the traditional @acronym{NCO} and Fortran convention of
keeping single-precision arithmetic in single-precision unless a
double-precision number is explicitly involved.

As has been seen, forced promotion of single- to double-precision
prior to arithmetic has advantages and disadvantages. 
The primary disadvantages are speed and size. 
Double-precision arithmetic is 10--60% slower than, and requires
twice the memory of single-precision arithmetic. 
The primary advantage is that rounding errors in double-precision are 
much less likely to accumulate to values near the precision of the 
underlying geophysical variable. 

For example, if we know temperature to five significant digits, then a
rounding error of 1-bit could affect the least precise digit of
temperature after 1,000--10,000 consecutive one-sided rounding
errors under the worst possible scenario.
Many geophysical grids have tens-of-thousands to millions of points
that must be summed prior to normalization to compute an average.
It is possible for single-precision rouding errors to accumulate and
degrade the precision in such situtations. 
Double-precision arithmetic mititgates this problem, so @samp{--dbl}
would be warranted. 

@cindex @acronym{TREFHT}
@cindex @acronym{CAM3}
@cindex @acronym{GCM}
This can be seen with another example, averaging a global surface
temperature field with @command{ncwa}.
The input contains a single-precision global temperature field
(stored in @code{TREFHT}) produced by the @acronym{CAM3} general
circulation model (@acronym{GCM}) run and stored at @w{1.9 by 2.5}
degrees resolution. 
This requires @w{94 latitudes} and @w{144 longitudes}, or @math{13,824} 
total surface gridpoints, a typical GCM resolution these days.
These input characteristics are provided only to show the context
to the interested reader, equivalent results would be found in 
statistics of any dataset of comparable size.
Models often represent Earth on a spherical grid where global averages 
must be created by weighting each gridcell by its latitude-dependent
weight (i.e., the Gaussian weight stored in @code{gw}), or by the
surface area of each contributing gridpoint (stored in @code{area}).

Like many geophysical models and most @acronym{GCM}s, @acronym{CAM3}
runs completely in double-precision yet stores its archival output in
single-precision to save space.
In practice such models usually save multi-dimensional prognostic and
diagnostic fields (like @code{TREFHT(lat,lon)} and @code{area(lat,lon)})
as single-precision, while saving all one-dimensional coordinates and
weights (here @code{lat}, @code{lon}, and @code{gw(lon)}) as
double-precision.  
To obtain pure double-precision arithmetic @emph{and} storage of the 
globla mean temperature, we first create and store double-precision
versions of the single-precision fields:
@example
ncap2 -O -s 'TREFHT_dbl=double(TREFHT);area_dbl=double(area)' in.nc in.nc
@end example
The single- and double-precision temperatures may each be averaged
globally using four permutations for the precision of the weight
and of the intermediate arithmetic representation:
@enumerate
@item Single-precision weight (@code{area}), single-precision arithmetic
@item Double-precision weight (@code{gw}),   single-precision arithmetic
@item Single-precision weight (@code{area}), double-precision arithmetic
@item Double-precision weight (@code{gw}),   double-precision arithmetic
@end enumerate
@example
# NB: Values below are printed with C-format %5.6f using
# ncks -H -C -s '%5.6f' -v TREFHT,TREFHT_dbl out.nc
# Single-precision weight (area), single-precision arithmetic
ncwa --flt -O -a lat,lon -w area in.nc out.nc
# TREFHT     = 289.246735 
# TREFHT_dbl = 289.239964
# Double-precision weight (gw),   single-precision arithmetic
ncwa --flt -O -a lat,lon -w gw   in.nc out.nc
# TREFHT     = 289.226135
# TREFHT_dbl = 289.239964
# Single-precision weight (area), double-precision arithmetic
ncwa --dbl -O -a lat,lon -w area in.nc out.nc
# TREFHT     = 289.239960
# TREFHT_dbl = 289.239964
# Double-precision weight (gw),   double-precision arithmetic
ncwa --dbl -O -a lat,lon -w gw   in.nc out.nc
# TREFHT     = 289.239960
# TREFHT_dbl = 289.239964
@end example
First note that the @code{TREFHT_dbl} average never changes because 
@code{TREFHT_dbl(lat,lon)} is double-precision in the input file.
As described above, @acronym{NCO} automatically converts all operands
involving to the highest precision involved in the operation.
So specifying @samp{--dbl} is redundant for double-precision inputs.

Second, the single-precision arithmetic averages of the single-precision
input @code{TREFHT} differ by @math{289.246735 - 289.226135 = 0.0206}
from eachother, and, more importantly, by as much as 
@math{289.239964 - 289.226135 = 0.013829} from the correct
(double-precision) answer.
These averages differ in the fifth digit, i.e., they agree only to four
significant figures!
Given that climate scientists are concerned about global temperature
variations of a tenth of a degree or less, this difference is large.
It means that the global mean temperature changes scientists are looking
for are comparable in size to the numerical artifacts produced by the
averaging procedure. 

@cindex rounding
@cindex random walk
Why are the single-precision numerical artifacts so large?
Each global average is the result of multiplying almost 15,000 elements
each by its weight, summing those, and then dividing by the summed 
weights.  
Thus about 50,000 single-precision floating point operations caused
the loss of two to three significant digits of precision.
The net error of a series of independent rounding errors is a random
walk phenomena
@footnote{
@cindex Michael Prather
Thanks to @w{Michael J.} Prather for explaining this to me.}.
Successive rounding errors displace the answer further from the truth.
An ensemble of such averages will, on average, have no net bias.
In other words, the expectation value of a series of @acronym{IEEE}
rounding errors is zero.
And the error of any given sequence of rounding errors obeys, for large 
series, a Gaussian distribution centered on zero.

@cindex mantissa
@cindex exponent
Single-precision numbers use three of their four eight-bit bytes to
represent the mantissa so the smallest representable single-precision
mantissa is @math{\epsilon \equiv 2^{-23} = 1.19209 \times 10^{-7}}.
This @math{\epsilon} is the smallest @var{x} such that 
@math{1.0 + x \ne 1.0}.
This is the rounding error for non-exact precision-numbers.
Applying random walk theory to rounding, it can be shown that the
expected rounding error after @var{n} inexact operations is
@math{\sqrt{2n/\pi}} for @w{large @var{n}}.
The expected (i.e., mean absolute) rounding error in our example with
@math{13,824} additions is about 
@math{\sqrt{2 \times 13824 / \pi} = 91.96}.
Hence, addition alone of about fifteen thousand single-precision floats
is expected to consume about two significant digits of precision.
This neglects the error due to the inner product (weights times values)
and normalization (division by tally) aspects of a weighted average.
the ratio of two numbers each containing a numerical bias can magnify
the size of the bias. 
In summary, a global mean number computed from about 15,000 gridpoints
each with weights can be expected to lose up to three significant digits.
Since single-precision starts with about seven significant digits, we
should not expect to retain more than four significant digits after
computing weighted averages in single-precision.
The above example with @code{TREFHT} shows the expected four digits of
agreement. 
@c For example, 50,000 coin flips would lead to 25,500 or more ``heads''
@c only a small percentage of the time.
@c P(k,n)= 50000_C_25500 p^k(1-p)^(n-k)
@c P(25500,50000)= 50000_C_25500 (0.5)^(25500)(0.5)^(24500)
@c P(>=25500,50000)= ?
@c fxm: Use Gaussian distribution/Random Walk

@cindex beer
The @acronym{NCO} results have been independently validated to the
extent possible in three other languages: 
@w{C}, Matlab, and @acronym{NCL}. 
C and @acronym{NCO} are the only languages that permit single-precision 
numbers to be treated with single precision arithmetic:
@example
# Double-precision weight (gw),   single-precision arithmetic (C)
ncwa_3528514.exe
# TREFHT     = 289.240112
# Double-precision weight (gw),   double-precision arithmetic (C)
# TREFHT     = 289.239964
# Single-precision weight (area), double-precision arithmetic (Matlab)
# TREFHT     = 289.239964
# Double-precision weight (gw),   double-precision arithmetic (Matlab)
# TREFHT     = 289.239964
# Single-precision weight (area), double-precision arithmetic (NCL)
ncl < ncwa_3528514.ncl
# TREFHT     = 289.239960
# TREFHT_dbl = 289.239964
# Double-precision weight (gw),   double-precision arithmetic (NCL)
# TREFHT     = 289.239960
# TREFHT_dbl = 289.239964
@end example
All languages tested (C, Matlab, @acronym{NCL}, and @acronym{NCO}) agree
to machine precision with double-precision arithmetic.
Users are fortunate to have a variety of high quality software that 
liberates them from the drudgery of coding their own.
Many packages are free (as in beer)!
As shown above @acronym{NCO} permits one to shift to their
float-promotion preferences as desired. 
No other language allows this with a simple switch.

To summarize, until version 4.3.6 (September, 2013), the default
arithmetic convention of @acronym{NCO} followed the behavior of Fortran,
and automatically promoted single-precision to double-precision in all
mixed-precision expressions, and left-alone pure single-precision
expressions.  
This is faster and more memory efficient than other conventions.
However, pure single-precision arithmetic can lose too much precision
when used to condense (e.g., average) large arrays.
Statistics involving about @math{n = 10,000} single-precision inputs
will lose about @w{2--3} digits if not promoted to double-precision
prior to arithmetic. 
The loss scales with the squareroot @w{of @var{n}}. 
For larger @var{n}, users should promote floats with the @samp{--dbl} 
option if they want to preserve more than four significant digits in
their results. 

The @samp{--dbl} and @samp{--flt} switches are only available with the
@acronym{NCO} arithmetic operators that could potentially perform more
than a few  single-precision floating point operations per result.
These are @command{nces}, @command{ncra}, and @command{ncwa}.
Each is capable of thousands to millions or more operations per result. 
By contrast, the arithmetic operators @command{ncbo} and
@command{ncflint} perform at most one floating point operation per
result. 
Providing the @samp{--dbl} option for such trivial operations makes 
little sense, so the option is not currently made available.

At the time of this writing (September 2013), we are interested in
users' opinions on these matters. 
Currently the default behavior is @samp{--flt}.
We are willing to change the default to @samp{--dbl} if users prefer.
Or we could set a threshold (e.g., @math{n \ge 10000}) after which
single- to double-precision promotion is automatically invoked.
Or we could make the default promotion convention settable via an
environment variable (@acronym{GSL} does this a lot).
Please let us know what you think of the selected defaults and options.

@node Manual type conversion,  , Promoting Single-precision to Double, Type Conversion
@subsection Manual type conversion
@cindex @command{ncap2}
@command{ncap2} provides intrinsic functions for performing manual type
conversions.
This, for example, converts variable @code{tpt} to external type
@code{NC_SHORT} (a C-type @code{short}), and variable @code{prs} to
external type @code{NC_DOUBLE} (a C-type @code{double}). 
@example
ncap2 -s 'tpt=short(tpt);prs=double(prs)' in.nc out.nc
@end example
@xref{ncap2 netCDF Arithmetic Processor}, for more details.

@html
<a name="ovr"></a> <!-- http://nco.sf.net/nco.html#ovr -->
<a name="-O"></a> <!-- http://nco.sf.net/nco.html#-O -->
@end html
@node Batch Mode, History Attribute, Type Conversion, Common features
@section Batch Mode
@cindex batch mode
@cindex overwriting files
@cindex appending to files
@cindex force overwrite
@cindex force append
@cindex @code{-O}
@cindex @code{-A}
@cindex @code{--overwrite}
@cindex @code{--ovr}
@cindex @code{--apn}
@cindex @code{--append}
@cartouche
Availability: All operators@*
Short options: @samp{-O}, @samp{-A}@*
Long options: @samp{--ovr}, @samp{--overwrite}, @samp{--apn}, @samp{--append}@*
@end cartouche
If the @var{output-file} specified for a command is a pre-existing file,
then the operator will prompt the user whether to overwrite (erase) the
existing @var{output-file}, attempt to append to it, or abort the
operation. 
However, interactive questions reduce productivity when processing large
amounts of data.
Therefore @acronym{NCO} also implements two ways to override its own safety
features, the @samp{-O} and @samp{-A} switches.
Specifying @samp{-O} tells the operator to overwrite any existing
@var{output-file} without prompting the user interactively.
Specifying @samp{-A} tells the operator to attempt to append to any
existing @var{output-file} without prompting the user interactively.
These switches are useful in batch environments because they suppress
interactive keyboard input.
NB: As of 20120515, @command{ncap2} is unable to append to files that
already contain the appended dimensions. 

@html
<a name="hst"></a> <!-- http://nco.sf.net/nco.html#hst -->
<a name="history"></a> <!-- http://nco.sf.net/nco.html#history -->
<a name="-h"></a> <!-- http://nco.sf.net/nco.html#-h -->
@end html
@node History Attribute, File List Attributes, Batch Mode, Common features
@section History Attribute
@cindex @code{history}
@cindex timestamp
@cindex global attributes
@cindex attributes, global
@cindex @code{-h}
@cindex @code{--hst}
@cindex @code{--history}
@cartouche
Availability: All operators@*
Short options: @samp{-h}@*
Long options: @samp{--hst}, @samp{--history}@*
@end cartouche
All operators automatically append a @code{history} global attribute to
any file they create or modify.
The @code{history} attribute consists of a timestamp and the full string
of the invocation command to the operator, e.g., @samp{Mon May 26 20:10:24
1997: ncks in.nc foo.nc}.
The full contents of an existing @code{history} attribute are copied
from the first @var{input-file} to the @var{output-file}.
The timestamps appear in reverse chronological order, with the most
recent timestamp appearing first in the @code{history} attribute.
Since @acronym{NCO} and many other netCDF operators adhere to the
@code{history} convention, the entire data processing path of a given
netCDF file may often be deduced from examination of its @code{history}
attribute. 
As of May, 2002, @acronym{NCO} is case-insensitive to the spelling
of the @code{history} attribute name.
Thus attributes named @code{History} or @code{HISTORY} (which are
non-standard and not recommended) will be treated as valid history
attributes. 
When more than one global attribute fits the case-insensitive search
for "history", the first one found will be used.
@code{history} attribute
@cindex @command{ncatted}
To avoid information overkill, all operators have an optional switch
(@samp{-h}, @samp{--hst}, or @samp{--history}) to override
automatically appending the @code{history} attribute 
(@pxref{ncatted netCDF Attribute Editor}).   
Note that the @samp{-h} switch also turns off writing the
@code{nco_input_file_list} attribute for multi-file operators
(@pxref{File List Attributes}).

@html
<a name="fl_lst_in_att"></a> <!-- http://nco.sf.net/nco.html#fl_lst_in_att -->
@end html
@node File List Attributes, CF Conventions, History Attribute, Common features
@section File List Attributes
@cindex @code{nco_input_file_list}
@cindex @code{nco_input_file_number}
@cindex @code{stdin}
@cindex global attributes
@cindex attributes, global
@cindex @code{-H}
@cindex @code{--fl_lst_in}
@cindex @code{--file_list}
@cartouche
Availability: @command{nces}, @command{ncecat}, @command{ncra}, @command{ncrcat}@*
Short options: @samp{-H}@*
Long options: @samp{--fl_lst_in}, @samp{--file_list}@*
@end cartouche
Many methods of specifying large numbers of input file names pass
these names via pipes, encodings, or argument transfer programs
(@pxref{Large Numbers of Files}).
When these methods are used, the input file list is not explicitly
passed on the command line.
This results in a loss of information since the @code{history}
attribute no longer contains the exact command by which the file
was created.

@acronym{NCO} solves this dilemma by archiving input file list
attributes.
When the input file list to a multi-file operator is specified
via @code{stdin}, the operator, by default, attaches two global
attributes to any file they create or modify.
The @code{nco_input_file_number} global attribute contains the number of
input files, and @code{nco_input_file_list} contains the file names,
specified as standard input to the multi-file operator. 
This information helps to verify that all input files the user thinks
were piped through @code{stdin} actually arrived.
Without the @code{nco_input_file_list} attribute, the information is lost
forever and the ``chain of evidence'' would be broken.

The @samp{-H} switch overrides (turns off) the default behavior of
writing the input file list global attributes when input is from
@code{stdin}. 
The @samp{-h} switch does this too, and turns off the @code{history}
attribute as well (@pxref{History Attribute}).
Hence both switches allows space-conscious users to avoid storing what
may amount to many thousands of filenames in a metadata attribute.

@html
<a name="CF"></a> <!-- http://nco.sf.net/nco.html#CF -->
<a name="cnv"></a> <!-- http://nco.sf.net/nco.html#cnv -->
<a name="cnv_CF"></a> <!-- http://nco.sf.net/nco.html#cnv_CF -->
<a name="cnv_CCSM"></a> <!-- http://nco.sf.net/nco.html#cnv_CCSM -->
@end html
@node CF Conventions, ARM Conventions, File List Attributes, Common features
@section @acronym{CF} Conventions
@cindex @acronym{CF} conventions
@cindex @acronym{CCSM} conventions
@cindex UDUnits
@cindex @code{ORO}
@cindex @code{area}
@cindex @code{datesec}
@cindex @code{date}
@cindex @code{gw}
@cindex @code{hyai}
@cindex @code{hyam}
@cindex @code{hybi}
@cindex @code{hybm}
@cindex @code{lat_bnds}
@cindex @code{lon_bnds}
@cindex @code{msk_*}
@cartouche
Availability: @command{ncbo}, @command{nces}, @command{ncecat},
@command{ncflint}, @command{ncpdq}, @command{ncra}, @command{ncwa}@*
Short options: None@*
@end cartouche
@acronym{NCO} recognizes some Climate and Forecast (@acronym{CF})
metadata conventions, and applies special rules to such data.
@acronym{NCO} was contemporaneous with @acronym{COARDS} and still
contains some rules to handle older @acronym{NCAR} model datasets, such as 
@acronym{CCM} and early @acronym{CCSM} datasets, that pre-date 
@acronym{CF}.
Such datasets may not contain an explicit @code{Conventions} attribute
(e.g., @samp{CF-1.0}). 
Nevertheless, we refer to all such metadata collectively as @acronym{CF} 
metadata. 
Skip this section if you never work with @acronym{CF} metadata.

The @acronym{CF} netCDF conventions are described 
@uref{http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.6/cf-conventions.html#coordinate-system, here}. 
Most @acronym{CF} netCDF conventions are transparent to @acronym{NCO}  
@footnote{
The exception is appending/altering the attributes @code{x_op},
@code{y_op}, @code{z_op}, and @code{t_op} for variables which have been
averaged across space and time dimensions.
This feature is scheduled for future inclusion in @acronym{NCO}.
}.
There are no known pitfalls associated with using any @acronym{NCO}
operator on files adhering to these conventions
@footnote{
The @acronym{CF} conventions recommend @code{time} be stored in the
format @var{time} since @var{base_time}, e.g., the @code{units}
attribute of @code{time} might be 
@samp{days since 1992-10-8 15:15:42.5 -6:00}. 
@w{A problem} with this format occurs when using @command{ncrcat} to
concatenate multiple files, each with a different @var{base_time}. 
That is, any @code{time} values from files following the first file to
be concatenated should be corrected to the @var{base_time} offset
specified in the @code{units} attribute of @code{time} from the first
file. 
The analogous problem has been fixed in @acronym{ARM} files 
(@pxref{ARM Conventions}) and could be fixed for @acronym{CF} files if
there is sufficient lobbying.
}.
However, to facilitate maximum user friendliness, @acronym{NCO} applies 
special rules to certain variables in @acronym{CF} files.
The special functions are not required by the @acronym{CF} netCDF
conventions, yet experience shows that they simplify data analysis.

@html
<a name="prc_xcp"></a> <!-- http://nco.sf.net/nco.html#prc_xcp -->
@end html
Currently, @acronym{NCO} determines whether a datafile is a
@acronym{CF} output datafile simply by checking (case-insensitively)
whether the value of the global attribute @code{Conventions} (if any)
equals @samp{CF-1.0} or @samp{NCAR-CSM} 
Should @code{Conventions} equal either of these in the (first)
@var{input-file}, @acronym{NCO} will apply special rules to certain
variables because of their usual meaning in @acronym{CF} files. 
@acronym{NCO} will not average the following variables often found in
@acronym{CF} files: 
@code{ntrm}, @code{ntrn}, @code{ntrk}, @code{ndbase}, @code{nsbase},
@code{nbdate}, @code{nbsec}, @code{mdt}, @code{mhisf}.
These variables contain scalar metadata such as the resolution of the
host geophysical model and it makes no sense to change their values.

@cindex non-coordinate grid properties
Furthermore, the @dfn{size and rank-preserving arithmetic operators} try
not to operate on certain grid properties.
These operators are @command{ncap2}, @command{ncbo}, @command{nces},
@command{ncflint}, and @command{ncpdq} (when used for packing, not for
permutation).  
These operators do not operate, by default, on (i.e., add, subtract,
pack, etc.) the following variables:   
@code{ORO}, 
@code{area}, 
@code{datesec}, 
@code{date}, 
@code{gw}, 
@code{hyai}, 
@code{hyam},
@code{hybi}. 
@code{hybm}, 
@code{lat_bnds}, 
@code{lon_bnds},
@code{msk_*}.
These variables represent the Gaussian weights, the orography field,
time fields, hybrid pressure coefficients, and latititude/longitude
boundaries.
We call these fields non-coordinate @dfn{grid properties}.
Coordinate grid properties are easy to identify because they are 
coordinate variables such as @code{latitude} and @code{longitude}.

Users usually want @emph{all} grid properties to remain unaltered in the
output file. 
To be treated as a grid property, the variable name must @emph{exactly}
match a name in the above list, or be a coordinate variable. 
The handling of @code{msk_*} is exceptional in that @emph{any} variable 
name beginning with the string @code{msk_} is considered to be a
``mask'' and is thus preserved (not operated on arithmetically).

You must spoof @acronym{NCO} if you would like any grid properties
or other special @acronym{CF} fields processed normally.
For example rename the variables first with @command{ncrename}, 
or alter the @code{Conventions} attribute.

@html
<a name="cnv_CF_bnd"></a> <!-- http://nco.sf.net/nco.html#cnv_CF_bnd -->
<a name="bnd"></a> <!-- http://nco.sf.net/nco.html#bnd -->
@end html
@cindex @code{bounds}
@cindex bounds convention
As of @acronym{NCO} version 4.0.8 (April, 2011), @acronym{NCO} 
supports the @acronym{CF} @code{bounds} convention for cell boundaries
described 
@uref{http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.6/cf-conventions.html#cell-boundaries, here}.
This convention allows coordinate variables (including multidimensional
coordinates) to describe the boundaries of their cells.
This is done by naming the variable which contains the bounds in
in the @code{bounds} attribute. 
Note that coordinates of rank @math{N} have bounds of rank @math{N+1}.
NCO-generated subsets of @acronym{CF}-compliant files with @code{bounds}
attributes will include the coordinates specified by the @code{bounds}
attribute, if any.  
Hence the subsets will themselves be @acronym{CF}-compliant.

@html
<a name="cnv_CF_crd"></a> <!-- http://nco.sf.net/nco.html#cnv_CF_crd -->
@end html
@cindex @code{coordinates}
@cindex coordinates convention
@cindex coordinate variable 
@cindex auxiliary coordinates
@cindex subsetting
@cindex @code{-C}
@cindex @code{-c}
@cindex @code{--no-coords}
@cindex @code{--no-crd}
@cindex @code{--coords}
@cindex @code{--crd}
As of @acronym{NCO} version 3.9.6 (January, 2009), @acronym{NCO}
supports the @acronym{CF} @code{coordinates} convention described 
@uref{http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.6/cf-conventions.html#coordinate-system, here}. 
This convention allows variables to specify additional coordinates
(including multidimensional coordinates) in a space-separated string
attribute named @code{coordinates}. 
NCO attaches any such coordinates to the extraction list along with
variable and its usual (one-dimensional) coordinates, if any.
These auxiliary coordinates are subject to the user-specified overrides
described in @ref{Subsetting Coordinate Variables}.

@html
<a name="cnv_CF_cll_mth"></a> <!-- http://nco.sf.net/nco.html#cnv_CF_cll_mth -->
<a name="cll_mth"></a> <!-- http://nco.sf.net/nco.html#cll_mth -->
<a name="no_cll_mth"></a> <!-- http://nco.sf.net/nco.html#no_cll_mth -->
<a name="cell_methods"></a> <!-- http://nco.sf.net/nco.html#cell_methods -->
@end html
@cindex @code{cell_methods}
@cindex @code{--cll_mth}
@cindex @code{--no_cll_mth}
@cindex @code{--cell_methods}
@cindex @code{--no_cell_methods}
@cindex cell methods convention
As of @acronym{NCO} version 4.4.2 (February, 2014), @acronym{NCO} 
supports some of the @acronym{CF} @code{cell_methods} 
@uref{http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.7-draft1/cf-conventions.html#cell-methods, convention}
to describe the analysis procedures that have been applied to data.
The convention creates (or appends to an existing) @code{cell_methods}
attribute a space-separated list of couplets of the form @var{dmn: op}
where @var{dmn} is a comma-separated list of dimensions previously
contained in the variable that have been reduced by the arithmetic
operation @var{op}.
For example, the @code{cell_methods} value @code{time: mean} says that
the variable in question was averaged over the @code{time} dimension.
In such cases @code{time} will either be a scalar variable or a
degenerate dimension or coordinate. 
This simply means that it has been averaged-over.
The value @code{time, lon: mean lat: max} says that the variable in
question is the maximum zonal mean of the time averaged original
variable.
Which is to say that the variable was first averaged over time and
longitude, and then the residual latitudinal array was reduced by
choosing the maximum value.
Since the @code{cell methods} convention may alter metadata in an
undesirable (or possibly incorrect) fashion, we provide switches
to ensure it is always or never used.
Use long-options @samp{--cll_mth} or @samp{--cell_methods} to invoke the
algorithm (true by default), and options @samp{--no_cll_mth} or 
@samp{--no_cell_methods} to turn it off.
These options are only available in the operators @command{ncwa} and
@command{ncra}.

@html
<a name="cnv_ARM"></a> <!-- http://nco.sf.net/nco.html#cnv_ARM -->
@end html
@node ARM Conventions, Operator Version, CF Conventions, Common features
@section @acronym{ARM} Conventions
@cindex @acronym{ARM} conventions
@cindex @code{time_offset}
@cindex @code{base_time}
@cindex @code{time}
@cartouche
Availability: @command{ncrcat}@*
Short options: None@*
@end cartouche
@command{ncrcat} has been programmed to correctly handle data files
which utilize the Atmospheric Radiation Measurement (@acronym{ARM})
Program @uref{http://www.arm.gov/data/time.stm,convention} for
time and time offsets.
If you do not work with @acronym{ARM} data then you may skip this
section. 
@acronym{ARM} data files store time information in two variables, a
scalar, @code{base_time}, and a record variable, @code{time_offset}.
Subtle but serious problems can arise when these type of files are
just blindly concatenated.
Therefore @command{ncrcat} has been specially programmed to be able to
chain together consecutive @acronym{ARM} @var{input-files} and produce
and an @var{output-file} which contains the correct time information.
Currently, @command{ncrcat} determines whether a datafile is an
@acronym{ARM} datafile simply by testing for the existence of the
variables @code{base_time}, @code{time_offset}, and the dimension
@code{time}.  
If these are found in the @var{input-file} then @command{ncrcat} will 
automatically perform two non-standard, but hopefully useful,
procedures. 
First, @command{ncrcat} will ensure that values of @code{time_offset}
appearing in the @var{output-file} are relative to the @code{base_time}
appearing in the first @var{input-file} (and presumably, though not
necessarily, also appearing in the @var{output-file}).
Second, if a coordinate variable named @code{time} is not found in the
@var{input-files}, then @command{ncrcat} automatically creates the
@code{time} coordinate in the @var{output-file}.  
The values of @code{time} are defined by the @acronym{ARM} conventions 
@math{@var{time} = @var{base_time} + @var{time_offset}}.
Thus, if @var{output-file} contains the @code{time_offset}
variable, it will also contain the @code{time} coordinate.
@cindex @code{history}
@cindex global attributes
@cindex attributes, global
@w{A short} message is added to the @code{history} global attribute
whenever these @acronym{ARM}-specific procedures are executed.

@html
<a name="vrs"></a> <!-- http://nco.sf.net/nco.html#vrs -->
<a name="version"></a> <!-- http://nco.sf.net/nco.html#version -->
@end html
@node Operator Version,  , ARM Conventions, Common features
@section Operator Version
@cindex version
@cindex @acronym{RCS}
@cindex @code{-r}
@cindex @code{--revision}
@cindex @code{--version}
@cindex @code{--vrs}
@cartouche
Availability: All operators@*
Short options: @samp{-r}@*
Long options: @samp{--revision}, @samp{--version}, or @samp{--vrs}@*
@end cartouche
All operators can be told to print their version information,
library version, copyright notice, and compile-time configuration 
with the @samp{-r} switch, or its long-option equivalent
@samp{revision}. 
The @samp{--version} or @samp{--vrs} switches print the operator
version information only.
The internal version number varies between operators, and indicates the 
most recent change to a particular operator's source code.
This is useful in making sure you are working with the most recent
operators.
The version of @acronym{NCO} you are using might be, e.g., @code{3.9.5}.
Using @samp{-r} on, say, @command{ncks}, produces something like 
@samp{NCO netCDF Operators version "3.9.5" last modified 2008/05/11 built May 12 2008 on neige by zender 
Copyright (C) 1995--2008 Charlie Zender
ncks version 20090918}.
This tells you that @command{ncks} contains all patches up to version 
@code{3.9.5}, which dates from @w{May 11}, 2008.
@html
<a name="rfr"></a> <!-- http://nco.sf.net/nco.html#rfr -->
@end html
@node Operator Reference Manual, Contributing, Common features, Top
@chapter Operator Reference Manual

This chapter presents reference pages for each of the operators
individually. 
The operators are presented in alphabetical order.
@cindex command line switches
All valid command line switches are included in the syntax statement.
Recall that descriptions of many of these command line switches are
provided only in @ref{Common features}, to avoid redundancy.
Only options specific to, or most useful with, a particular operator are 
described in any detail in the sections below.  

@menu
* ncap2 netCDF Arithmetic Processor::
* ncatted netCDF Attribute Editor::
* ncbo netCDF Binary Operator::
* nces netCDF Ensemble Statistics::
* ncecat netCDF Ensemble Concatenator::
* ncflint netCDF File Interpolator::
* ncks netCDF Kitchen Sink::
* ncpdq netCDF Permute Dimensions Quickly::
* ncra netCDF Record Averager::
* ncrcat netCDF Record Concatenator::
* ncrename netCDF Renamer::
* ncwa netCDF Weighted Averager::
@end menu

@page
@html
<a name="ncap"></a> <!-- http://nco.sf.net/nco.html#ncap -->
<a name="ncap2"></a> <!-- http://nco.sf.net/nco.html#ncap2 -->
@end html
@node ncap2 netCDF Arithmetic Processor, ncatted netCDF Attribute Editor, Operator Reference Manual, Operator Reference Manual
@section @command{ncap2} netCDF Arithmetic Processor
@cindex parser
@cindex lexer
@cindex arithmetic processor
@findex ncap
@findex ncap2

@cartouche
@command{ncap2} understands a relatively full-featured 
language of operations, including loops, conditionals, arrays,
and math functions.
@command{ncap2} is the most rapidly changing @acronym{NCO} operator and
its documentation is incomplete.
The distribution file @file{data/ncap2_tst.nco} contains an up-to-date
overview of its syntax and capabilities. 
The @file{data/*.nco} distribution files (especially
@file{bin_cnt.nco}, @file{psd_wrf.nco}, and @file{rgr.nco}) contain
in-depth examples of @command{ncap2} solutions to complex problems.
@end cartouche

@c fxm: TODO nco549 hyper-link all switches to explanatory sections?
@c Problem is that only works well in HTML mode
@c TeXInfo has no native mode for concise hyperlinks in text mode
@c Currently in TeX/PDF mode, TeXInfo opens browser to find link,
@c rather than jumping to internal link within document
@noindent
SYNTAX
@example
ncap2 [-3] [-4] [-6] [-7] [@uref{http://nco.sf.net/nco.html#-A,,-A}] [-C] [-c] 
[-D @var{dbg}] [-F] [-f] [-h] [--hdf] [--hdr_pad @var{nbr}] [-L @var{dfl_lvl}] [-l @var{path}]
[--no_tmp_fl] [-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all]
[-s @var{algebra}] [-S @var{fl.nco}] [-t @var{thr_nbr}] [-v]
@var{input-file} [@var{output-file}]  
@end example
 
@noindent
DESCRIPTION

@command{ncap2} arithmetically processes netCDF files
@footnote{@command{ncap2} is the successor to @command{ncap} which was
put into maintenance mode in November, 2006. 
This documentation refers to @command{ncap2}, which has a superset of
the @command{ncap} functionality. 
Eventually @command{ncap} will be deprecated in favor @command{ncap2}.
@command{ncap2} may be renamed @command{ncap} in 2013.}.
@cindex script file
@cindex @code{--script-file}
@cindex @code{--fl_spt}
@cindex @code{--script}
@cindex @code{--spt}
The processing instructions are contained either in the @acronym{NCO}
script file @file{fl.nco} or in a sequence of command line arguments.
The options @samp{-s} (or long options @samp{--spt} or @samp{--script})
are used for in-line scripts and @samp{-S} (or long options
@samp{--fl_spt} or @samp{--script-file}) are used to provide the
filename where (usually multiple) scripting commands are pre-stored.   
@command{ncap2} was written to perform arbitrary algebraic
transformations of data and archive the results as easily as possible.
@cindex derived fields
@xref{Missing Values}, for treatment of missing values.
The results of the algebraic manipulations are called 
@dfn{derived fields}. 

Unlike the other operators, @command{ncap2} does not accept a list of
variables to be operated on as an argument to @samp{-v} 
(@pxref{Subsetting Files}).
Rather, the @samp{-v} switch takes no arguments and indicates
that @command{ncap2} should output @emph{only} user-defined variables.
@command{ncap2} neither accepts nor understands the @var{-x} switch.
@cindex appending variables
NB: As of 20120515, @command{ncap2} is unable to append to files that
already contain the appended dimensions. 

@c @subsection Scripting Mathematical Processing with @command{ncap2}

@menu
* Syntax of ncap2 statements::
* Expressions::
* Dimensions::
* Left hand casting::
* Arrays and hyperslabs::
* Attributes::
* Number literals::
* if statement::
* print statement::
* Missing values ncap2::
* Methods and functions::
* RAM variables::
* Where statement::
* Loops::
* Include files::
* Sort methods::
* Irregular grids::
* Bilinear interpolation::
* GSL special functions::
* GSL interpolation::
* GSL least-squares fitting::
* GSL statistics::
* GSL random number generation::
* Examples ncap2::
* Intrinsic mathematical methods::
* Operator precedence and associativity ::
* ID Quoting::
@end menu

@html
<a name="att_prp"></a> <!-- http://nco.sf.net/nco.html#att_prp -->
@end html
Defining new variables in terms of existing variables is a powerful
feature of @command{ncap2}. 
@cindex derived fields
Derived fields inherit the metadata (i.e., attributes) of their
ancestors, if any, in the script or input file. 
When the derived field is completely new (no identically-named ancestors
exist), then it inherits the metadata (if any) of the left-most variable
on the right hand side of the defining expression.
This metadata inheritance is called @dfn{attribute propagation}.
Attribute propagation is intended to facilitate well-documented 
data analysis, and we welcome suggestions to improve this feature.

The only exception to this rule of attribute propagation is in cases of
left hand casting (@pxref{Left hand casting}).
The user must manually define the proper metadata for variables defined
using left hand casting. 

@html
<a name="syn"></a> <!-- http://nco.sf.net/nco.html#syn -->
@end html
@node Syntax of ncap2 statements, Expressions, ncap2 netCDF Arithmetic Processor, ncap2 netCDF Arithmetic Processor
@subsection Syntax of @command{ncap2} statements
@cindex statement
@cindex syntax
Mastering @command{ncap2} is relatively simple.
Each valid statement @var{statement} consists of standard forward
algebraic expression. 
The @file{fl.nco}, if present, is simply a list of such statements,
whitespace, and comments.
@cindex C language
The syntax of statements is most like the computer @w{language C}.
The following characteristics @w{of C} are preserved:
@table @asis
@item Array syntax
@cindex array syntax
@cindex @code{[]} (array delimiters)
Arrays elements are placed within @code{[]} characters;
@item Array indexing
@cindex array indexing
Arrays are 0-based;
@item Array storage
@cindex array storage
Last dimension is most rapidly varying;
@item Assignment statements
@cindex assignment statement
@cindex semi-colon
@cindex @code{;} (end of statement)
@w{A semi}-colon @samp{;} indicates the end of an assignment statement.
@item Comments
@cindex comments
@cindex @code{/*...*/} (comment)
@cindex @code{//} (comment)
Multi-line comments are enclosed within @code{/* */} characters.
Single line comments are preceded by @code{//} characters.
@item Nesting
@cindex including files
@cindex nesting
@cindex @code{#include}
Files may be nested in scripts using @code{#include @var{script}}.
Note that the @code{#include} command is not followed by a semi-colon
because it is a pre-processor directive, not an assignment statement.
The filename @file{script} is interpreted relative to the run directory.
@item Attribute syntax
@cindex attribute syntax
@cindex @code{@@} (attribute)
The at-sign @code{@@} is used to delineate an attribute name from a
variable name.
@end table 

@html
<a name="ncap_xpr"></a> <!-- http://nco.sf.net/nco.html#ncap_xpr -->
@end html
@node Expressions, Dimensions, Syntax of ncap2 statements, ncap2 netCDF Arithmetic Processor
@cindex expressions
@subsection Expressions
Expressions are the fundamental building block of @command{ncap2}. 
Expressions are composed of variables, numbers, literals, and
attributes. 
@cindex C language
The following @w{C operators} are ``overloaded'' and work with scalars 
and multi-dimensional arrays:
@example
Arithmetic Operators: * / % + - ^
Binary Operators:     > >= < <= == != == || && >> <<
Unary Operators:      + - ++ -- !
Conditional Operator: exp1 ? exp2 : exp3
Assign Operators:     = += -= /= *=
@end example

In the following section a @dfn{variable} also refers to a 
number literal which is read in as a scalar variable:

@strong{Arithmetic and Binary Operators }

Consider @emph{var1 'op' var2}

@strong{Precision}
@itemize @bullet
@item When both operands are variables, the result has the precision of the higher precision operand.
@item When one operand is a variable and the other an attribute, the result has the precision of the variable. 
@item When both operands are attributes, the result has the precision of the more precise attribute.
@item The exponentiation operator ``^'' is an exception to the above rules. 
When both operands have type less than @code{NC_FLOAT}, the result is @code{NC_FLOAT}. 
When either type is @code{NC_DOUBLE}, the result is also @code{NC_DOUBLE}. 
@end itemize
@c csz got to here editing

@cindex broadcasting variables
@cindex rank
@strong{Rank}
@itemize @bullet 
@item The Rank of the result is generally equal to Rank of the operand
that has the greatest number of dimensions.  
@item If the dimensions in var2 are a subset of the dimensions in var1
then its possible to  make var2 conform to var1 through broadcasting and
or dimension reordering.  
@item Broadcasting a variable means creating data in non-existing
dimensions by copying data in existing dimensions. 
@item More specifically: If the numbers of dimensions in var1 is greater 
than or equal to the number of dimensions in var2 then an attempt is
made to make var2 conform to var1 ,else var1 is made to conform to
var2. If conformance  is not possible then an error message will be
emitted and script execution will cease.@* 
@end itemize

@noindent Even though the logical operators return True(1) or False(0)
they are treated in the same way as the arithmetic operators with regard
to precision and rank.@* 
Examples:

@example
dimensions: time=10, lat=2, lon=4
Suppose we have the two variables:

double  P(time,lat,lon);
float   PZ0(lon,lat);  // PZ0=1,2,3,4,5,6,7,8;

Consider now the expression:
 PZ=P-PZ0

PZ0 is made to conform to P and the result is
PZ0 =
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,
   1,3,5,7,2,4,6,8,

Once the expression is evaluated then PZ will be of type double;

Consider now 
 start=four-att_var@@double_att;  // start =-69  and is of type intger;
 four_pow=four^3.0f               // four_pow=64 and is of type float  
 three_nw=three_dmn_var_sht*1.0f; // type is now float
 start@@n1=att_var@@short_att*att_var@@int_att; 
                                  // start@@n1=5329 and is type int 
@end example

@noindent @strong{Binary Operators} @* 
@cindex binary Operators
Unlike C the binary operators return an array of values. 
There is no such thing as short circuiting with the AND/OR operators. 
Missing values are carried into the result in the same way they are with
the arithmetic operators. 
When an expression is evaluated in an if() the missing values are
treated as true.@*  
The binary operators are, in order of precedence: 
@example
	
!   Logical Not
----------------------------
<<  Less Than Selection
>>  Greater Than Selection
----------------------------
>   Greater than
>=  Greater than or equal to
<   Less than
<=  Less than or equal to
----------------------------
==  Equal to
!=  Not equal to
----------------------------
&&  Logical AND
----------------------------
||  Logical OR
----------------------------
@end example

To see all operators: @pxref{Operator precedence and associativity} 
Examples:
@example
tm1=time>2 && time <7;  // tm1=0, 0, 1, 1, 1, 1, 0, 0, 0, 0 double
tm2=time==3 || time>=6; // tm2=0, 0, 1, 0, 0, 1, 1, 1, 1, 1 double
tm3=int(!tm1);          // tm3=1, 1, 0, 0, 0, 0, 1, 1, 1, 1 int
tm4=tm1 && tm2;         // tm4=0, 0, 1, 0, 0, 1, 0, 0, 0, 0 double
tm5=!tm4;               // tm5=1, 1, 0, 1, 1, 0, 1, 1, 1, 1 double
@end example
	
@noindent @strong{Regular Assign Operator}@*
@noindent @emph{var1 '=' exp1} @*
If var1 does not already exist in Output then var1 is written to Output with the values and dimensions from expr1. If var1 already exists in Output, then the only requirement on expr1 is that the number of elements must match the number already on disk. The type of expr1 is converted if necessary to the disk type.

@noindent @strong{ Other Assign Operators +=,-=,*=./= }@*
        @noindent  @emph{var1 'ass_op' exp1 }@*
if exp1 is a variable and it doesn't conform to var1 then an attempt is made to make it conform to var1. If exp1 is an attribute it must have unity size or else have the same number of elements as var1. If expr1 has a different type to var1 the it is converted to the var1 type.
@example
z1=four+=one*=10 // z1=14 four=14 one=10;	
time-=2          // time= -1,0,1,2,3,4,5,6,7,8
@end example

@noindent @strong{Increment/ Decrement Operators @* } 
These work in a similar fashion to their regular C counterparts. If say the variable "four" is input only then the statement "++four" effectively means -read four from input increment each element by one , then write the new values to Output;

Example:
@example
n2=++four;   n2=5, four=5 
n3=one--+20; n3=21  one=0;	 
n4=--time;   n4=time=0.,1.,2.,3.,4.,5.,6.,7.,8.,9.;
@end example

@noindent @strong{Conditional Operator ?: } @*
@cindex conditional Operator
@noindent @emph{exp1 ? exp2 : exp3 } @*
The conditional operator (or ternary Operator) is a succinct way
of writing an if/then/else. If exp1 evaluates to true then exp2 is
returned else exp3 is returned. 

Example:
@example
weight_avg=weight.avg();
weight_avg@@units= (weight_avg == 1 ? "kilo" : "kilos");  
PS_nw=PS-(PS.min() > 100000 ? 100000 : 0);
@end example

@html
<a name="clp"></a> <!-- http://nco.sf.net/nco.html#clp -->
<a name="clipping"></a> <!-- http://nco.sf.net/nco.html#clipping -->
@end html
@noindent @strong{Clipping Operators}
@cindex clipping operators
@table @asis
@item << Less-than Clipping@*
For arrays, the less-than selection operator selects all values in the
left operand that are less than the corresponding value in the right
operand. 
If the value of the left side is greater than or equal to the
corresponding value of the right side, then the right side value is 
placed in the result	 
@item >> Greater-than Clipping@*
For arrays, the greater-than selection operator selects all values in
the left operand that are greater than the corresponding value in the
right operand. 
If the value of the left side is less than or equal to the corresponding
value of the right side, then the right side value is placed in the
result.  
@end table

Example:
@example
RDM2=RDM >> 100.0 // 100,100,100,100,126,126,100,100,100,100 double
RDM2=RDM <<  90s  // 1, 9, 36, 84, 90, 90, 84, 36, 9, 1 int
@end example

@html
<a name="ncap_dims"></a> <!-- http://nco.sf.net/nco.html#ncap_dims -->
<a name="defdim"></a> <!-- http://nco.sf.net/nco.html#defdim -->
@end html
@node Dimensions, Left hand casting, Expressions, ncap2 netCDF Arithmetic Processor
@subsection Dimensions
@cindex defining dimensions in @command{ncap2}
@cindex @code{defdim()}
Dimensions are defined in Output using the @code{defdim()} function.
@example
defdim("cnt",10);
@end example

This dimension name must then be prefixed with a dollar-sign @samp{$}
when referred to in method arguments or left-hand-casting, e.g.,
@example
new_var[$cnt]=time;
temperature[$time,$lat,$lon]=35.5;
temp_avg=temperature.avg($time);
@end example

The @code{size} method allows the dimension size to be used in an
arithmetic expression:
@example
time_avg=time.total() / $time.size;
@end example

Increase the size of a new variable by one and set new member to zero:
@example
defdim("cnt_new",$cnt.size+1);
new_var[$cnt_new]=0.0;
new_var(0:($cnt_new.size-2))=old_var;
@end example

@noindent @strong{Dimension Abbreviations @*}
It is possible to use dimension abbreviations as method arguments:@*
@code{$0} is the first dimension of a variable@*
@code{$1} is the second dimension of a variable@*
@code{$n} is the n+1 dimension of a variable@*

@example
float four_dmn_rec_var(time,lat,lev,lon);
double three_dmn_var_dbl(time,lat,lon);

four_nw=four_dmn_rev_var.reverse($time,$lon)
four_nw=four_dmn_rec_var.reverse($0,$3);

four_avg=four_dmn_rec_var.avg($lat,$lev);  
four_avg=four_dmn_rec_var.avg($1,$2);  

three_mw=three_dmn_var_dbl.permute($time,$lon,$lat);
three_mw=three_dmn_var_dbl.permute($0,$2,$1);
@end example

@noindent @strong{ID Quoting @*}
If the dimension name contains non-regular characters use ID quoting. 
See @pxref{ID Quoting}
@example
defdim("a--list.A",10);
A1['$a--list.A']=30.0;
@end example

@noindent @strong{GOTCHA @*}
@noindent It is not possible to manually define in Output any dimensions that exist in Input. When a variable from Input appears in an expression or statement its  dimensions in Input are  automagically copied to Output (if they are not already present)

@html
<a name="lhc"></a> <!-- http://nco.sf.net/nco.html#lhc -->
<a name="lhs"></a> <!-- http://nco.sf.net/nco.html#lhs -->
@end html
@node Left hand casting, Arrays and hyperslabs, Dimensions, ncap2 netCDF Arithmetic Processor
@subsection Left hand casting
@cindex hybrid coordinate system 
@cindex left hand casting
@cindex @acronym{LHS}
The following examples demonstrate the utility of the 
@dfn{left hand casting} ability of @command{ncap2}.
Consider first this simple, artificial, example.
If @var{lat} and @var{lon} are one dimensional coordinates of
dimensions @var{lat} and @var{lon}, respectively, then addition
of these two one-dimensional arrays is intrinsically ill-defined because 
whether @var{lat_lon} should be dimensioned @var{lat} by @var{lon}
or @var{lon} by @var{lat} is ambiguous (assuming that addition is to
remain a @dfn{commutative} procedure, i.e., one that does not depend on 
the order of its arguments).
Differing dimensions are said to be @dfn{orthogonal} to one another,
and sets of dimensions which are mutually exclusive are orthogonal
as a set and any arithmetic operation between variables in orthogonal
dimensional spaces is ambiguous without further information.

The ambiguity may be resolved by enumerating the desired dimension 
ordering of the output expression inside square brackets on the
left hand side (@acronym{LHS}) of the equals sign.
This is called @dfn{left hand casting} because the user resolves the 
dimensional ordering of the @acronym{RHS} of the expression by
specifying the desired ordering on the @acronym{LHS}.
@example
ncap2 -s 'lat_lon[lat,lon]=lat+lon' in.nc out.nc
ncap2 -s 'lon_lat[lon,lat]=lat+lon' in.nc out.nc
@end example
The explicit list of dimensions on the @acronym{LHS}, @code{[lat,lon]}
resolves the otherwise ambiguous ordering of dimensions in
@var{lat_lon}. 
In effect, the @acronym{LHS} @dfn{casts} its rank properties onto the 
@acronym{RHS}.
Without @acronym{LHS} casting, the dimensional ordering of @var{lat_lon}
would be undefined and, hopefully, @command{ncap2} would print an error
message. 

Consider now a slightly more complex example.
In geophysical models, a coordinate system based on 
a blend of terrain-following and density-following surfaces is 
called a @dfn{hybrid coordinate system}.
In this coordinate system, four variables must be manipulated to
obtain the pressure of the vertical coordinate:
@var{PO} is the domain-mean surface pressure offset (a scalar),
@var{PS} is the local (time-varying) surface pressure (usually two
horizontal spatial dimensions, i.e. latitude by longitude), @var{hyam}
is the weight given to surfaces of constant density (one spatial
dimension, pressure, which is orthogonal to the horizontal
dimensions), and @var{hybm} is the weight given to surfaces of
constant elevation (also one spatial dimension). 
This command constructs a four-dimensional pressure @code{prs_mdp}
from the four input variables of mixed rank and orthogonality:
@example
ncap2 -s 'prs_mdp[time,lat,lon,lev]=P0*hyam+PS*hybm' in.nc out.nc
@end example
Manipulating the four fields which define the pressure in a hybrid
coordinate system is easy with left hand casting.

@html
<a name="ncap_arr"></a> <!-- http://nco.sf.net/nco.html#ncap_arr -->
@end html
@node Arrays and hyperslabs, Attributes, Left hand casting, ncap2 netCDF Arithmetic Processor
@subsection Arrays and hyperslabs

@findex array
@cindex @code{array} function
@cindex arrays
@cindex findgen-equivalent
@cindex indgen-equivalent
Generating a regularly spaced one-dimensional array with @command{ncap2}
is simple with the @code{array()} function. 
The syntax is 
@example
var_out=array(val_srt,val_ncr,$dmn_nm); // One-dimensional output
var_out=array(val_srt,val_ncr,var_tpl); // Multi-dimensional output
@end example
@noindent
where the arguments are the starting value @var{val_srt}, 
incremental value @var{val_ncr}, and, for one-dimensional output, the
single dimension @code{$dmn_nm}, or, for multi-dimensional output, a
template variable @code{var_tpl}, i.e., a variable with the same shape
as the desired output. 
The type of @code{var_out} will be the same as @code{val_srt}.
Be sure to encode this type with the appropriate decimal point
and floating point suffix when @code{val_srt} is a ``naked constant''
rather than a variable.
For example, to produce an array of shorts (signed two-byte integers), 
integers (signed four-byte integers), unsigned 64-bit integers,
floats, or doubles use
@example
var_out=array(1s,val_ncr,$dmn_nm); // NC_SHORT array
var_out=array(1,val_ncr,$dmn_nm); // NC_INT array
var_out=array(1ull,val_ncr,$dmn_nm); // NC_UINT64 array
var_out=array(1f,val_ncr,$dmn_nm); // NC_FLOAT array
var_out=array(1.,val_ncr,$dmn_nm); // NC_DOUBLE array
@end example

Once the associated dimensions have been defined, the start and
increment arguments may be supplied as values, mathmatical expressions,
or variables:
@example
var_out=array(1,1,$time); // 1,2,3,4,5,6,7,8,9,10
var_out=array(1+2-2,one,$time); // 1,2,3,4,5,6,7,8,9,10
var_out=array(1,2,three_dmn_rec_var); // 1,3,5,...155,157,159
@end example

@cindex hyperslabs
Hyperslabs in @command{ncap2} are more limited than hyperslabs with the
other @acronym{NCO} operators. 
@command{ncap2} does not understand the shell command-line syntax
used to specify multi-slabs, wrapped co-ordinates, negative stride or
coordinate value limits.
However with a bit of syntactic magic they are all are possible. 
@command{ncap2} accepts (in fact, it requires) @var{N}-hyperslab
arguments for a variable of rank @var{N}:
@example
var1(arg1,arg2 ... argN);
@end example
where each hyperslab argument is of the form
@example
start:end:stride 
@end example
and the arguments for different dimensions are separated by commas.
@noindent 
If "start" is omitted, it defaults to 0.
If "end" is omitted, it defaults to dimension size minus one.
If "stride" is omitted, it defaults to 1.
@sp 1
@noindent If a single value is present then it is assumed that that
dimension collapses to a single value (i.e., a cross-section). 
The number of hyperslab arguments MUST equal the variable's rank.
@sp 1

@noindent @strong{Hyperslabs on the Right Hand Side of an assign@*}

A simple 1D example:
@example 
($time.size=10)
od[$time]=@{20,22,24,26,28,30,32,34,36,38@};

od(7);     // 34
od(7:);    // 34,36,38
od(:7);    // 20,22,24,26,28,30,32,34 
od(::4);   // 20,28,36
od(1:6:2)  // 22,26,30
od(:)      // 20,22,24,26,28,30,32,34,36,38 
@end example

A more complex three dimensional example:
@example
($lat.size=2,$lon.size=4)
th[$time,$lat,$lon]=      
                          @{1, 2, 3, 4, 5, 6, 7, 8,
                          9,10,11,12,13,14,15,16,
                          17,18,19,20,21,22,23,24,
                          -99,-99,-99,-99,-99,-99,-99,-99,
                          33,34,35,36,37,38,39,40,
                          41,42,43,44,45,46,47,48,
                          49,50,51,52,53,54,55,56,
                          -99,58,59,60,61,62,63,64,
                          65,66,67,68,69,70,71,72,
                          -99,74,75,76,77,78,79,-99 @};

th(1,1,3);        // 16
th(2,0,:);        // 17, 18, 19, 20
th(:,1,3);        // 8, 16, 24, -99, 40, 48, 56, 64, 72, -99 
th(::5,:,0:3:2); // 1, 3, 5, 7, 41, 43, 45, 47
@end example

If hyperslab arguments collapse to a single value (a cross-section has
been specified), then that dimension is removed from the returned
variable. 
If all the values collapse then a scalar variable is returned.
So, for example, the following is valid: 
@example
th_nw=th(0,:,:)+th(9,:,:); 
// th_nw has dimensions $lon,$lat 
// NB: the time dimension has become degenerate
@end example

The following is invalid:
@example
th_nw=th(0,:,0:1)+th(9,:,0:1);
@end example
because the @code{$lon} dimension now only has two elements.
The above can be calculated by using a LHS cast with 
@code{$lon_nw} as replacement dim for @code{$lon}: 
@example
defdim("lon_nw",2);
th_nw[$lat,$lon_nw]=th(0,:,0:1) +th(9,:,0:1);
@end example

@noindent @strong{Hyperslabs on the Left Hand Side of an assign@*}
@noindent When hyperslabing on the LHS, the expression on the RHS must 
evaluate to a scalar or a variable/attribute with the same number of 
elements as the LHS hyperslab.
Set all elements of the last record to zero:
@example
th(9,:,:)=0.0;
@end example
Set first element of each lon element to 1.0:
@example
th(:,:,0)=1.0;
@end example
One may hyperslab on both sides of an assign.
For example, this sets the last record to the first record:
@example
th(9,:,:)=th(0,:,:);
@end example
Say @var{th0} represents pressure at height=0 and 
@var{th1} represents pressure at height=1.
Then it is possible to insert these hyperslabs into the records
@example
prs[$time,$height,$lat,$lon]=0.0;
prs(:,0,:,:)=th0;
prs(:,1,:,:)=th1
@end example

@noindent @strong{Reverse method}@*
@cindex reverse()
Use the @code{reverse()} method to reverse a dimension's elements in a
variable with at least one dimension.
This is equivalent to a negative stride, e.g., 
@example 
th_rv=th(1 ,:,:).reverse($lon); // @{12,11,10,9 @}, @{16,15,14,13@}
od_rv=od.reverse($time);        // @{38,36,34,32,30,28,26,24,22,20@}
@end example

@noindent @strong{Permute method}p@*
@cindex permute()
Use the @code{permute()} method to swap the dimensions of a variable.
The number and names of dimension arguments must match the dimensions in
the variable. 
If the first dimension in the variable is of record type then this must
remain the first dimension. 
If you want to change the record dimension then consider using
@command{ncpdq}. 

Consider the variable:
@example
float three_dmn_var(lat,lev,lon);
three_dmn_var_prm=three_dmn_var.permute($lon,$lat,$lev);
// The permuted values are
three_dmn_var_prm= 
  0,4,8,
  12,16,20,
  1,5,9,
  13,17,21,
  2,6,10,
  14,18,22,
  3,7,11,
  15,19,23;
@end example

@html
<a name="ncap_att"></a> <!-- http://nco.sf.net/nco.html#ncap_att -->
@end html
@node Attributes, Number literals, Arrays and hyperslabs, ncap2 netCDF Arithmetic Processor
@subsection Attributes
@cindex attributes@command{ncap2}
@noindent Attributes are referred to by @emph{var_nm@@att_nm} @*
All the following are valid statements:
@example
global@@text="Test Attributes"; /* Assign a global variable attribute */
a1[$time]=time*20;
a1@@long_name="Kelvin";
a1@@min=a1.min();
a1@@max=a1.max();
a1@@min++;
--a1@@max; q
a1(0)=a1@@min;
a1($time.size-1)=a1@@max;
@end example

A @emph{value list} can be used on the RHS of an assign...
@cindex value list
@example
a1@@trip1=@{1,2,3@} ;
a1@@triplet=@{a1@@min,(a1@@min+a1@@max)/2,a1@@max@}; 
@end example
The netCDF specification allows all attribute types to have a size
greater than one. 
The maximum is defined by @code{NC_MAX_ATTRS}.
The following is an @command{ncdump} of the metadata for variable @var{a1} 
@example 
double a1(time) ;
  a1:long_name = "Kelvin" ;
  a1:max = 199. ;
  a1:min = 21. ;
  a1:trip1 = 1, 2, 3 ;
  a1:triplet = 21., 110., 199. ;
@end example

The @code{size()} method can be used with attributes.
For example, to save an attribute text string in a variable,
@example
defdim("sng_len", a1@@long_name.size());
sng_arr[$sng_len]=a1@@long_name; // sng_arr now contains "Kelvin" 
@end example
Attributes defined in a script are stored in memory and are written to Output after script completion.
To stop the attribute being written use the ram_delete() method or use a bogus variable name.

@noindent @strong{Attribute Propagation and Inheritance}
@cindex attribute propagation
@cindex attribute inheritance
@itemize @bullet
  @item Attribute propagation occurs in a regular  assign statement. The variable being defined on the LHS gets copies of the attributes from the leftermost variable on the RHS

  @item Attribute Inheritance: The LHS variable "inherits" attributes from an Input variable with the same name

  @item It is possible to have a regular assign statement for which both propagation and inheritance occur.
@end itemize

@example
// prs_mdp inherits attributes from P0:
prs_mdp[time,lat,lon,lev]=P0*hyam+hybm*PS;
// th_min inherits attributes from three_dmn_var_dbl:
th_min=1.0 + 2*three_dmn_var_dbl.min($time);
@end example

If the attribute name contains non-regular characters use ID quoting. See @pxref{ID Quoting}
@example
'b..m1@@c--lost'=23;
@end example

@html
<a name="ncap_num"></a> <!-- http://nco.sf.net/nco.html#ncap_num -->
@end html
@node Number literals, if statement, Attributes, ncap2 netCDF Arithmetic Processor
@subsection Number literals
@cindex number literals @command{ncap2}
The table below lists the postfix character(s) to add to a number
literal for type cohesion. 
To use the new netCDF4 types @acronym{NCO} must be compiled/linked to
the netCDF4 library and the output file must be @acronym{HDF5}.

@example
n1[$time]=1UL; // n1 will now by type @code{NC_UINT}
n2[$lon]=4b;   // n2 will be of type @code{NC_BYTE}
n3[$lat]=5ull; // n3 will be of type @code{NC_UINT64}  
n3@@a1=6.0d;   // attribute will be type @code{NC_DOUBLE}
n3@@a2=-666L;  // attribute will be type @code{NC_INT}
@end example

A floating point number without a postfix will default to
@code{NC_DOUBLE}. 
An integer without a postfix will default to type @code{NC_INT}. 
There is no postfix for characters, use a quoted string instead.
@example
n4[$rlev]=0.1      // n4 will be of type @code{NC_DOUBLE}
n5[$lon_grd]=2.0   // n5 will be of type @code{NC_DOUBLE}
n6[$gds_crd]=2e3;  // n6 will be of type @code{NC_DOUBLE}
n7[$gds_crd]=2e3f;  // n7 will be of type @code{NC_FLOAT}
n6@@a1=41;         // attribute will be type @code{NC_INT}
n6@@a2=-21;        // attribute will be type @code{NC_INT}  
n6@@units="kelvin" // attribute will be type @code{NC_CHAR}
@end example 

@table @asis
@item @strong{netCDF3/4 Types}
@item b|B	 
  @code{NC_BYTE}, a signed 1-byte integer 
@item none	 
  @code{NC_CHAR}, an ISO/ASCII character 
@item s|S	 
  @code{NC_SHORT}, a signed 2-byte integer 
@item l|L	 
  @code{NC_INT}, a signed 4-byte integer 
@item f|F	 
  @code{NC_FLOAT}, a single-precision (4-byte) floating point number 
@item d|D
  @code{NC_DOUBLE}, a double-precision (8-byte) floating point number 
@item @strong{netCDF4 Types}
@item ub|UB	 
  @code{NC_UBYTE}, an unsigned 1-byte integer 
@item us|US 
  @code{NC_USHORT}, an unsigned 2-byte integer 
@item u|U|ul|UL	 
  @code{NC_UINT}, an unsigned 4-byte integer 
@item ll|LL	 
  @code{NC_INT64}, a signed 8-byte integer 
@item ull|ULL 
  @code{NC_UINT64}, an unsigned 8-byte integer 
@end table

@html
<a name="ncap_if"></a> <!-- http://nco.sf.net/nco.html#ncap_if -->
@end html
@node if statement, print statement, Number literals, ncap2 netCDF Arithmetic Processor
@subsection if statement
@cindex if() 
The syntax of the if statement is similar to its C counterpart. 
The @emph{Conditional Operator (ternary operator)} has also been
implemented. 
@example
if(exp1)
   stmt1;
else if(exp2)     
   stmt2;
else
   stmt3;

# Can use code blocks as well:
if(exp1)@{
   stmt1;
   stmt1a;
   stmt1b;
@} else if(exp2)     
   stmt2; 
else @{
   stmt3;
   stmt3a;
   stmt3b;
@}     
@end example

@comment Truth
@noindent For a variable or attribute expression to be logically true
all its non-missing value elements must be logically true, i.e.,
non-zero. 
The expression can be of any type. 
@w{Unlike C} there is no short-circuiting of an expression with the 
OR (@code{||}) and AND (@code{&&}) operators. 
The whole expression is evaluated regardless if one of the AND/OR
operands are True/False.
@example
# Simple example
if(time>0)
  print("All values of time are greater than zero\n");
else if( time<0)
  print("All values of time are less than zero\n");   
else @{
  time_max=time.max();
  time_min=time.min();
  print("min value of time=");print(time_min,"%f");
  print("max value of time=");print(time_max,"%f");
@}

# Example from ddra.nco
if(fl_typ==fl_typ_gcm)@{
  var_nbr_apx=32;
  lmn_nbr=1.0*var_nbr_apx*varsz_gcm_4D; /* [nbr] Variable size */
  if(nco_op_typ==nco_op_typ_avg)@{
    lmn_nbr_avg=1.0*var_nbr_apx*varsz_gcm_4D; // Block size
    lmn_nbr_wgt=dmnsz_gcm_lat; /* [nbr] Weight size */
  @} // !nco_op_typ_avg
@}else if(fl_typ==fl_typ_stl)@{
  var_nbr_apx=8;
  lmn_nbr=1.0*var_nbr_apx*varsz_stl_2D; /* [nbr] Variable size */
  if(nco_op_typ==nco_op_typ_avg)@{
    lmn_nbr_avg=1.0*var_nbr_apx*varsz_stl_2D; // Block size
    lmn_nbr_wgt=dmnsz_stl_lat; /* [nbr] Weight size */
  @} // !nco_op_typ_avg
@} // !fl_typ
@end example

@noindent @strong{Conditional Operator @*}
@example
// netCDF4 needed for this example
th_nw=(three_dmn_var_sht >= 0 ? three_dmn_var_sht.uint() : \
       three_dmn_var_sht.int()); 
@end example

@html
<a name="ncap_prn"></a> <!-- http://nco.sf.net/nco.html#ncap_prn -->
@end html
@node print statement, Missing values ncap2, if statement, ncap2 netCDF Arithmetic Processor
@subsection print statement
@cindex print() @command{ncap2}
@example
print(variable_name/attribute name/string, format string);
@end example  

@noindent The print function takes a variable name or attribute name or
a quoted string and prints the contents in a in a similar fashion to
@code{ncks -H}.
There is also an optional C-language style format string argument. 
Currently the print function cannot print @acronym{RAM} variables or expressions 
such as @code{'print(var_msk*3+4)'}. 
To print an expression, first evaluate it as a non-@acronym{RAM} variable (so it
will be saved and can be printed), and then print the variable.

@noindent examples
@example
print(lon);
lon[0]=0 
lon[1]=90 
lon[2]=180 
lon[3]=270 

print(lon_2D_rrg,"%3.2f,");
0.00,0.00,180.00,0.00,180.00,0.00,180.00,0.00,

print(mss_val_fst@@_FillValue);
mss_val_fst@@_FillValue, size = 1 NC_FLOAT, value = -999

print("This function \t is monotonic\n");
This function is 	  monotonic
@end example

@html
<a name="ncap_miss"></a> <!-- http://nco.sf.net/nco.html#ncap_miss -->
@end html
@node Missing values ncap2, Methods and functions, print statement, ncap2 netCDF Arithmetic Processor
@subsection Missing values ncap2
@cindex missing values ncap2
Missing values operate slightly differently in @command{ncap2} 
Consider the expression where op is any of the following operators (excluding '=')
@example
Arithmetic operators ( * / % + - ^ )
Binary Operators     ( >, >= <, <= ==, !=,==,||,&&, >>,<< ) 
Assign Operators     ( +=,-=,/=, *= ) 

var1 'op' var2
@end example

@noindent If var1 has a missing value then this is the value used in the 
operation, otherwise the missing value for var2 is used. 
If during the element-by-element operation an element from either
operand is equal to the missing value then the missing value is carried 
through. 
In this way missing values 'percolate' or propagate through an
expression.@*  
Missing values associated with Output variables are stored in memory and
are written to disk after the script finishes. 
During script execution its possible (and legal) for the missing value
of a variable to take on several different values. 
@example 
# Consider the variable:
int rec_var_int_mss_val_int(time); =-999,2,3,4,5,6,7,8,-999,-999;
rec_var_int_mss_val_int:_FillValue = -999;

n2=rec_var_int_mss_val_int + rec_var_int_mss_val_int.reverse($time); 

n2=-999,-999,11,11,11,11,11,11,999,-999;
@end example

@html
<a name="set_miss"></a> <!-- http://nco.sf.net/nco.html#set_miss -->
<a name="get_miss"></a> <!-- http://nco.sf.net/nco.html#get_miss -->
<a name="change_miss"></a> <!-- http://nco.sf.net/nco.html#change_miss -->
<a name="number_miss"></a> <!-- http://nco.sf.net/nco.html#number_miss -->
@end html
The following methods manipulate missing value information associated
with a variable. 
They only work on variables in Output. 
@table @code
@item set_miss(expr)
@cindex @code{set_miss()}
 The numeric argument @var{expr} becomes the new missing value,
 overwriting the old missing value, if any.
 The argument given is converted if necessary to the variable type.
 NB: This only changes the missing value attribute. 
 Missing values in the original variable remain unchanged, and thus 
 are no long considered missing values.
 They are ``orphaned''.
 Thus @code{set_miss()} is normally used only when creating new
 variables.
 The intrinsic function @code{change_miss()} (see below) is typically 
 used to edit values of existing variables.
@item change_miss(expr)
@cindex @code{change_miss()}
 Sets or changes (any pre-existing) missing value attribute and missing 
 data values to @var{expr}. 
 NB: This is an expensive function since all values must be examined. 
 Use this function when changing missing values for pre-existing
 variables. 
@item get_miss() 
@cindex @code{get_miss()}
 Returns the missing value of a variable. 
 If the variable exists in Input and Output then the missing value of
 the variable in Output is returned. 
 If the variable has no missing value then an error is returned.   
@item delete_miss()
@cindex @code{delete_miss()}
 Deletes the missing value associated with a variable.
@item number_miss()
@cindex @code{number_miss()}
 Counts the number of missing values a variable contains.
@end table

@example
th=three_dmn_var_dbl;
th.change_miss(-1e10d);
/* Set values less than 0 or greater than 50 to missing value */
where(th < 0.0 || th > 50.0) th=th.get_miss();

# Another example:
new[$time,$lat,$lon]=1.0;
new.set_miss(-997.0);

// Extract only elements divisible by 3
where (three_dmn_var_dbl%3 == 0)
     new=three_dmn_var_dbl; 
elsewhere
     new=new.get_miss();   

// Print missing value and variable summary
mss_val_nbr=three_dmn_var_dbl.number_miss();
print(three_dmn_var_dbl@@_FillValue);
print("Number of missing values in three_dmn_var_dbl: ");
print(mss_val_nbr,"%d");
print(three_dmn_var_dbl);
@end example

@html
<a name="ncap_mtd"></a> <!-- http://nco.sf.net/nco.html#ncap_mtd -->
@end html
@node Methods and functions, RAM variables, Missing values ncap2, ncap2 netCDF Arithmetic Processor
@subsection Methods and functions

The convention within this document is that methods can be used as 
functions. 
However, functions are not and cannot be used as methods.
Methods can be daisy-chained d and their syntax is cleaner than functions. 
Method names are reserved words and CANNOT be used as variable names.  
The command @code{ncap2 -f} shows the complete list of methods available
on your build. 
@example
n2=sin(theta) 
n2=theta.sin() 
n2=sin(theta)^2 + cos(theta)^2 
n2=theta.sin().pow(2) + theta.cos()^2
@end example

This statement chains together methods to convert three_dmn_var_sht to
type double, average it, then convert this back to type short: 
@example
three_avg=three_dmn_var_sht.double().avg().short();
@end example

@sp 1
@noindent @strong{Aggregate Methods @*} 
@noindent These methods mirror the averaging types available in @command{ncwa}. The arguments to the methods are the dimensions to average over. Specifying no dimensions is equivalent to specifying all dimensions i.e., averaging over all dimensions. A masking variable and a weighting variable can be manually created and applied as needed.

@table @code
@item avg()
@cindex avg()
Mean value 
@item sqravg()
@cindex sqravg()
Square of the mean
@item avgsqr()
Mean of sum of squares
@item max()
@cindex max()
Maximum value
@item min()
@cindex min()
Minimum value
@item rms()
Root-mean-square (normalize by @var{N})
@item rmssdn()
@cindex rmssdn()
Root-mean square (normalize by @var{N-1})
@item ttl() or total()
@cindex ttl()
Sum of values
@end table

@example
// Average a variable over time
four_time_avg=four_dmn_rec_var($time);
@end example

@sp 1
@noindent @strong{ Packing Methods @* } 
For more information see @pxref{Packed data} and @pxref{ncpdq netCDF Permute Dimensions Quickly}@*
@table @code
@item pack() & pack_short()
@cindex pack()
The default packing algorithm is applied and variable is packed to @code{NC_SHORT}
@item pack_byte()
@cindex pack_byte()
Variable is packed to @code{NC_BYTE}
@item pack_short()
@cindex pack_short()
Variable is packed to @code{NC_SHORT}
@item pack_int()
@cindex pack_int()
Variable is packed to @code{NC_INT}
@item unpack()
@cindex unpack()
The standard unpacking algorithm is applied. 
@end table

@noindent @strong{Basic Methods @*}
These methods work with variables and attributes. They have no arguments

@table @code
@item size()	
@cindex size()
Total number of elements 
@item ndims()
@cindex ndims()
Number of dimensions in variable
@item type() 
@cindex type()
Returns the netcdf type (see previous section)
@end table

@sp 1
@noindent @strong{Utility Methods @*}
These functions are used to manipulate missing values and @acronym{RAM} variables.
@pxref{Missing values ncap2} 

@table @code
@item set_miss(expr)
 Takes one argument the missing value. Sets or overwrites the existing missing value. The argument given is converted if necessary to the variable type
@item change_miss(expr)
 Changes the missing value elements of the variable to the new missing value (n.b. an expensive function).
@item get_miss() 
 Returns the missing value of a variable in Input or Output  
@item delete_miss()
 Deletes the missing value associated with a variable.
@item ram_write()
 Writes a @acronym{RAM} variable to disk i.e., converts it to a regular disk type variable
@item ram_delete()
 Deletes a @acronym{RAM} variable or an attribute 
@end table

@sp 1
@noindent @strong{PDQ Methods @*}
See @pxref{ncpdq netCDF Permute Dimensions Quickly}
@table @code
@item reverse(dim args)
 Reverses the dimension ordering of elements in a variable. 
@item permute(dim args)
 Re-shapes variables by re-ordering the dimensions. All the dims of the variable must be specified in the arguments. A limitation of this permute (unlike ncpdq) is that the record dimension cannot be re-assigned. 
@end table 
// Swap dimensions about and reorder along lon
@example
lat_2D_rrg_new=lat_2D_rrg.permute($lon,$lat).reverse($lon);
lat_2D_rrg_new=0,90,-30,30,-30,30,-90,0
@end example

@sp 1
@noindent @strong{Type Conversion Methods @*}
@noindent These methods allow @command{ncap2} to convert variables and attributes to the different netcdf types. For more details on automatic and manual type conversion see (@pxref{Type Conversion}). You can only use the new netCDF4 types if you have compiled/links @acronym{NCO} with the netCDF4 library and the Output file is HDF5.

@table @code
@item @strong{netCDF3/4 Types}
@item byte()	 
@cindex byte()
 convert to @code{NC_BYTE},  a signed 1-byte integer 
@item char()
@cindex char()	 
 convert to @code{NC_CHAR},  an ISO/ASCII character
@item short()	
@cindex sshort() 
 convert to @code{NC_SHORT}, a signed 2-byte integer 
@item int()	 
@cindex int()
 convert to @code{NC_INT},   a signed 4-byte integer 
@item float()
@cindex float()	 
 convert to @code{NC_FLOAT}, a single-precision (4-byte) floating point number 
@item double() 
@cindex double()
 convert to @code{NC_DOUBLE}, a double-precision (8-byte) floating point number 
@item @strong{netCDF4 Types}
@item ubyte()	 
@cindex ubyte()
 convert to @code{NC_UBYTE}, an unsigned 1-byte integer 
@item ushort() 
@cindex ushort()
 convert to @code{NC_USHORT}, an unsigned 2-byte integer 
@item uint()
@cindex uint()	 
 convert to @code{NC_UINT}, an unsigned 4-byte integer 
@item int64()	
@cindex int64() 
 convert to @code{NC_INT64}, a signed 8-byte integer 
@item uint64() 
@cindex unit64()
 convert to @code{NC_UINT64}, an unsigned 8-byte integer
@end table

@noindent @strong{Intrinsic Mathematical Methods @*}
The list of mathematical methods is system dependant.
For the full list @pxref{Intrinsic mathematical methods} 

All the mathematical methods take a single argument except @code{atan2()}
and @code{pow()} which take two. 
If the operand type is less than @emph{float} then the result will be of
type @emph{float}. 
Arguments of type @emph{double} yield results of type @emph{double}. 
Like the other methods, you are free to use the mathematical methods as functions. 

@example
n1=pow(2,3.0f)    // n1 type float
n2=atan2(2,3.0)   // n2 type double
n3=1/(three_dmn_var_dbl.cos().pow(2))-tan(three_dmn_var_dbl)^2; // n3 type double
@end example

@html
<a name="ncap_ram"></a> <!-- http://nco.sf.net/nco.html#ncap_ram -->
@end html
@cindex @acronym{RAM} variables
@node RAM variables, Where statement, Methods and functions, ncap2 netCDF Arithmetic Processor
@subsection @acronym{RAM} variables
Unlike regular variables, @acronym{RAM} variables are never written to disk.
Hence using @acronym{RAM} variables in place of regular variables (especially
within loops) significantly increases execution speed.
Variables that are frequently accessed within @code{for} or @code{where}
clauses provide the greatest opportunities for optimization. 
To declare and define a @acronym{RAM} variable simply prefix the variable name
with an asterisk (@code{*}) when the variable is declared/initialized.
To delete a @acronym{RAM} variables (and recover their memory) use the
@code{ram_delete()} method. 
To write a @acronym{RAM} variable to disk (like a regular variable) use
@code{ram_write()}. 
@cindex ram_write()
@cindex ram_delete()
@example
*temp[$time,$lat,$lon]=10.0;     // Cast
*temp_avg=temp.avg($time);      // Regular assign
temp.ram_delete();              // Delete RAM variable
temp_avg.ram_write();           // Write Variable to output

// Create and increment a RAM variable from "one" in Input
*one++;   
// Create RAM variables from the variables three and four in Input.
// Multiply three by 10 and add it to four. 
*four+=*three*=10; // three=30, four=34 
@end example

@html
<a name="where"></a> <!-- http://nco.sf.net/nco.html#where -->
<a name="ncap_whr"></a> <!-- http://nco.sf.net/nco.html#ncap_whr -->
<a name="ncap_where"></a> <!-- http://nco.sf.net/nco.html#ncap_where -->
@end html
@node Where statement, Loops, RAM variables, ncap2 netCDF Arithmetic Processor
@subsection Where statement
@cindex where()
A @code{where()} combines the definition and application of a mask all in one go and can lead to succinct code. 
The full syntax of a @code{where()} statement is as follows:

@example
// Single assign (the 'elsewhere' block is optional)
where(mask) 
   var1=expr1;
elsewhere
   var1=expr2;	   	

// Multiple assigns
where(mask)@{
    var1=expr1;
    var2=expr2;
    ...
@}elsewhere@{
    var1=expr3
    var2=expr4
    var3=expr5;
    ...
@}
@end example

@itemize @bullet
@item The only expression allowed in the predicate of a where is assign,
i.e., 'var=expr'. 
This assign differs from a regular @command{ncap2} assign. 
The LHS var must already exist in Input or Output. 
The RHS expression must evaluate to a scalar or a variable/attribute of
the same size as the LHS variable.
@item Consider when both the LHS and RHS are variables: 
For every element where mask condition is True, the corresponding LHS
variable element is re-assigned to its partner element on the RHS. 
In the elsewhere part the mask is logically inverted and the assign
process proceeds as before.
@item If the mask dimensions are a subset of the LHS variable's
dimensions, then it is made to conform; if it cannot be made to conform 
then script execution halts.   
@item Missing values in the mask evaluate to False in the where 
code/block statement and to True in the elsewhere block/statement. 
LHS variable elements set to missing value are not re-assigned.
For these reasons, do not explicitly reference missing values in the
masking condition, e.g., @code{where(foo=foo.get_missing()) foo=1;}
will not work as expected.
@end itemize

Example:
Consider the variables @code{float lon_2D_rct(lat,lon);} and
@code{float var_msk(lat,lon);}. 
Suppose we wish to multiply by two the elements for which @code{var_msk} 
@w{equals 1}: 
@example
where(var_msk==1) lon_2D_rct=2*lon_2D_rct;
@end example
Suppose that we have the variable @code{int RDM(time)} and that we want
to set its values less than 8 or greater than 80 @w{to 0}:
@example
where(RDM < 8 || RDM > 80) RDM=0;          
@end example

Consider irregularly gridded data, described using @w{rank 2} coordinates: 
@code{double lat(south_north,east_west)},
@code{double lon(south_north,east_west)}, 
@code{double temperature(south_north,east_west)}.
To find the average temperature in a region bounded by
[@var{lat_min},@var{lat_max}] and [@var{lon_min},@var{lon_max}]:
@example
temperature_msk[$south_north,$east_west]=0.0;
where(lat >= lat_min && lat <= lat_max) && (lon >= lon_min && lon <= lon_max)
  temperature_msk=temperature;	
elsewhere
  temperature_msk=temperature@@_FillValue;

temp_avg=temperature_msk.avg();
temp_max=temperature.max();
@end example

@html
<a name="ncap_lop"></a> <!-- http://nco.sf.net/nco.html#ncap_lop -->
@end html
@node Loops, Include files, Where statement, ncap2 netCDF Arithmetic Processor
@subsection Loops
@cindex while()
@cindex for()
@command{ncap2} supplies @command{for()} loops and @command{while()} loops. 
They are completely unoptimized so use them only with @acronym{RAM} 
variables unless you want thrash your disk to death. 
To break out of a loop use the @command{break} command. 
To iterate to the next cycle use the @command{continue} command. 

@example
// Set elements in variable double temp(time,lat) 
// If element < 0 set to 0, if element > 100 set to 100
*sz_idx=$time.size;
*sz_jdx=$lat.size;

for(*idx=0;idx<sz_idx;idx++)
  for(*jdx=0;jdx<sz_jdx;jdx++)
    if(temp(idx,jdx) > 100) temp(idx,jdx)=100.0; 
      else if(temp(idx,jdx) < 0) temp(idx,jdx)=0.0;

// Are values of co-ordinate variable double lat(lat) monotonic?
*sz=$lat.size;

for(*idx=1;idx<sz;idx++)
  if(lat(idx)-lat(idx-1) < 0.0) break;

if(idx == sz) print("lat co-ordinate is monotonic\n");
   else print("lat co-ordinate is NOT monotonic\n");

// Sum odd elements	
*idx=0;
*sz=$lat_nw.size;
*sum=0.0;

while(idx<sz)@{
  if(lat(idx)%2) sum+=lat(idx);
  idx++;
@}

ram_write(sum);
print("Total of odd elements ");print(sum);print("\n"); 
@end example

@html
<a name="ncap_inc"></a> <!-- http://nco.sf.net/nco.html#ncap_inc -->
@end html
@node Include files, Sort methods, Loops, ncap2 netCDF Arithmetic Processor
@subsection Include files
@cindex @command{include}
The syntax of an @var{include-file} is:
@example
#include "script.nco"
@end example
The script filename is searched relative to the run directory. 
It is possible to nest include files to an arbitrary depth. 
A handy use of inlcude files is to store often used constants. 
Use @acronym{RAM} variables if you do not want these constants written to
@var{output-file}.  
@example
// script.nco
// Sample file to #include in ncap2 script
*pi=3.1415926535; // RAM variable, not written to output
*h=6.62607095e-34; // RAM variable, not written to output
e=2.71828; // Regular (disk) variable, written to output
@end example

@html
<a name="srt"></a> <!-- http://nco.sf.net/nco.html#srt -->
<a name="sort"></a> <!-- http://nco.sf.net/nco.html#sort -->
<a name="remap"></a> <!-- http://nco.sf.net/nco.html#remap -->
@end html
@node Sort methods, Irregular grids, Include files, ncap2 netCDF Arithmetic Processor
@subsection @command{sort} methods
@cindex @command{sort}
@cindex @command{asort}
@cindex @command{dsort}
@cindex @command{remap}
@cindex @command{unmap}
@cindex @command{invert_map}
In @acronym{ncap2} there are multiple ways to sort data. 
Beginning with @acronym{NCO} 4.1.0 (March, 2012), @acronym{ncap2} 
support six sorting functions:
@example
var_out=sort(var_in,&srt_map); // Ascending sort
var_out=asort(var_in,&srt_map); // Accending sort 
var_out=dsort(var_in,&srt_map); // Desending sort     
var_out=remap(var_in,srt_map); // Apply srt_map to var_in
var_out=unmap(var_in,srt_map); // Reverse what srt_map did to var_in
dsr_map=invert_map(srt_map); // Produce "de-sort" map that inverts srt_map
@end example
The first two functions, @command{sort()} and @command{asort()}
sort, in ascending order, all the elements of @var{var_in} (which can be
a variable or attribute) without regard to any dimensions.
The third function, @command{dsort()} does the same but sorts in
descending order. 
Remember that ascending and descending sorts are specified by
@command{asort()} and @command{dsort()}, respectively.

These three functions are overloaded to take a second, optional argument 
called the sort map @var{srt_map}, which should be supplied as a
call-by-reference variable, i.e., preceded with an ampersand.
If the sort map does not yet exist, then it will be created and 
returned as an integer type the same shape as the input variable.

The output @var{var_out} of each sort function is a sorted version of
the input, @var{var_in}.
The output @var{var_out} of the two mapping functions the result of
applying (with @command{remap()} or un-applying (with @command{unmap()}) 
the sort map @var{srt_map} to the input @var{var_in}.
To apply the sort map with @command{remap()} the size of the variable
must be exactly divisible by the size of the sort map. 

The final function @command{invert_map()} returns the so-called
de-sorting map @var{dsr_map} which is inverse map of the input map
@var{srt_map}. 
This gives the user access to both the forward and inverse sorting maps
which can be useful in special situations.
@example
a1[$time]=@{10,2,3,4,6,5,7,3,4,1@};
a1_sort=sort(a1);
print(a1_sort);
// 1, 2, 3, 3, 4, 4, 5, 6, 7, 10;

a2[$lon]=@{2,1,4,3@};
a2_sort=sort(a2,&a2_map);
print(a2);
// 1, 2, 3, 4
print(a2_map);
// 1, 0, 3, 2;
@end example  

If the map variable does not exist prior to the @command{sort()} call,
then it will be created with the same shape as the input variable and be
of type @code{NC_INT}. 
If the map variable already exists, then the only restriction is that it
be of at least the same size as the input variable. 
To apply a map use @code{remap(var_in,srt_map)}. 
@example
defdim("nlat",5);

a3[$lon]=@{2,5,3,7@};
a4[$nlat,$lon]=@{
 1, 2, 3, 4, 
 5, 6, 7, 8,
 9,10,11,12,
 13,14,15,16,
 17,18,19,20@};

a3_sort=sort(a3,&a3_map);
print(a3_map);
// 0, 2, 1, 3;

a4_sort=remap(a4,a3_map);
print(a4_sort);
// 1, 3, 2, 4,
// 5, 7, 6, 8,
// 9,11,10,12,
// 13,15,14,16,
// 17,19,18,20;

a3_map2[$nlat]=@{4,3,0,2,1@};

a4_sort2=remap(a4,a3_map2);
print(a4_sort2);
// 3, 5, 4, 2, 1
// 8, 10, 9,7, 6, 
// 13,15,14,12,11, 
// 18,20,19,17,16
@end example
As in the above example you may create your own sort map.
To sort in descending order, apply the @code{reverse()} method after the
@command{sort()}.    

Here is an extended example of how to use @command{ncap2} features to
hyperslab an irregular region based on the values of a variable not a
coordinate. 
The distinction is crucial: hyperslabbing based on dimensional indices
or coordinate values is straightforward.
Using the values of single or multi-dimensional variable to define a
hyperslab is quite different.
@example
cat > ~/ncap2_foo.nco << 'EOF'
// Purpose: Save irregular 1-D regions based on variable values

// Included in NCO User Guide at http://nco.sf.net/nco.html#sort

/* NB: Single quotes around EOF above turn off shell parameter 
    expansion in "here documents". This in turn prevents the
    need for protecting dollarsign characters in NCO scripts with
    backslashes when the script is cut-and-pasted (aka "moused") 
    from an editor or e-mail into a shell console window */

/* Copy coordinates and variable(s) of interest into RAM variable(s)
   Benefits:
   1. ncap2 defines writes all variables on LHS of expression to disk
      Only exception is RAM variables, which are stored in RAM only
      Repeated operations on regular variables takes more time, 
      because changes are written to disk copy after every change.
      RAM variables are only changed in RAM so script works faster
      RAM variables can be written to disk at end with ram_write()
   2. Script permutes variables of interest during processing
      Safer to work with copies that have different names
      This discourages accidental, mistaken use of permuted versions
   3. Makes this script a more generic template:
      var_in instead of specific variable names everywhere */
*var_in=one_dmn_rec_var;
*crd_in=time;
*dmn_in_sz=$time.size; // [nbr] Size of input arrays

/* Create all other "intermediate" variables as RAM variables 
   to prevent them from cluttering the output file.
   Mask flag and sort map are same size as variable of interest */
*msk_flg=var_in;
*srt_map=var_in;

/* In this example we mask for all values evenly divisible by 3
   This is the key, problem-specific portion of the template
   Replace this where() condition by that for your problem
   Mask variable is Boolean: 1=Meets condition, 0=Fails condition */
where(var_in % 3 == 0) msk_flg=1; elsewhere msk_flg=0;

// print("msk_flg = ");print(msk_flg); // For debugging...

/* The sort() routine is overloaded, and takes one or two arguments
   The second argument (optional) is the "sort map" (srt_map below)
   Pass the sort map by reference, i.e., prefix with an ampersand
   If the sort map does not yet exist, then it will be created and 
   returned as an integer type the same shape as the input variable.
   The output of sort(), on the LHS, is a sorted version of the input
   msk_flg is not needed in its original order after sort()
   Hence we use msk_flg as both input to and output from sort()
   Doing this prevents the need to define a new, unneeded variable */
msk_flg=sort(msk_flg,&srt_map);

// Count number of valid points in mask by summing the one's
*msk_nbr=msk_flg.total();

// Define output dimension equal in size to number of valid points
defdim("crd_out",msk_nbr);

/* Now sort the variable of interest using the sort map and remap()
   The output, on the LHS, is the input re-arranged so that all points
   meeting the mask condition are contiguous at the end of the array
   Use same srt_map to hyperslab multiple variables of the same shape
   Remember to apply srt_map to the coordinate variables */
crd_in=remap(crd_in,srt_map);
var_in=remap(var_in,srt_map);

/* Hyperslab last msk_nbr values of variable(s) of interest */
crd_out[crd_out]=crd_in((dmn_in_sz-msk_nbr):(dmn_in_sz-1));
var_out[crd_out]=var_in((dmn_in_sz-msk_nbr):(dmn_in_sz-1));

/* NB: Even though we created all variables possible as RAM variables,
   the original coordinate of interest, time, is written to the ouput.
   I'm not exactly sure why. For now, delete it from the output with: 
   ncks -O -x -v time ~/foo.nc ~/foo.nc
   */ 
EOF
ncap2 -O -v -S ~/ncap2_foo.nco ~/nco/data/in.nc ~/foo.nc
ncks -O -x -v time ~/foo.nc ~/foo.nc
ncks ~/foo.nc
@end example

Here is an extended example of how to use @command{ncap2} features to
sort multi-dimensional arrays based on the coordinate values along a
single dimension. 
@example
cat > ~/ncap2_foo.nco << 'EOF'
/* Purpose: Sort multi-dimensional array based on coordinate values
   This example sorts the variable three_dmn_rec_var(time,lat,lon)
   based on the values of the time coordinate. */

// Included in NCO User Guide at http://nco.sf.net/nco.html#sort

// Randomize the time coordinate
time=10.0*gsl_rng_uniform(time);
//print("original randomized time =\n");print(time);

/* The sort() routine is overloaded, and takes one or two arguments
   The first argument is a one dimensional array
   The second argument (optional) is the "sort map" (srt_map below)
   Pass the sort map by reference, i.e., prefix with an ampersand
   If the sort map does not yet exist, then it will be created and 
   returned as an integer type the same shape as the input variable.
   The output of sort(), on the LHS, is a sorted version of the input */

time=sort(time,&srt_map);
//print("sorted time (ascending order) and associated sort map =\n");print(time);print(srt_map);

/* sort() always sorts in ascending order
   The associated sort map therefore re-arranges the original,
   randomized time array into ascending order.
   There are two methods to obtain the descending order the user wants
   1) We could solve the problem in ascending order (the default)
   and then apply the reverse() method to re-arrange the results.
   2) We could change the sort map to return things in descending
   order of time and solve the problem directly in descending order. */

// Following shows how to do method one:

/* Expand the sort map to srt_map_3d, the size of the data array
   1. Use data array to provide right shape for the expanded sort map
   2. Coerce data array into an integer so srt_map_3d is an integer
   3. Multiply data array by zero so 3-d map elements are all zero
   4. Add the 1-d sort map to the 3-d sort map (NCO automatically resizes)
   5. Add the spatial (lat,lon) offsets to each time index 
   6. de-sort using the srt_map_3d
   7. Use reverse to obtain descending in time order
   Loops could accomplish the same thing (exercise left for reader)
   However, loops are slow for large datasets */

/* Following index manipulation requires understanding correspondence
   between 1-d (unrolled, memory order of storage) and access into that
   memory as a multidimensional (3-d, in this case) rectangular array.
   Key idea to understand is how dimensionality affects offsets */ 
// Copy 1-d sort map into 3-d sort map
srt_map_3d=(0*int(three_dmn_rec_var))+srt_map;
// Multiply base offset by factorial of lesser dimensions
srt_map_3d*=$lat.size*$lon.size;
lon_idx=array(0,1,$lon);
lat_idx=array(0,1,$lat)*$lon.size;
lat_lon_idx[$lat,$lon]=lat_idx+lon_idx;
srt_map_3d+=lat_lon_idx;

print("sort map 3d =\n");print(srt_map_3d);

// Use remap() to re-map the data
three_dmn_rec_var=remap(three_dmn_rec_var,srt_map_3d);

// Finally, reverse data so time coordinate is descending
time=time.reverse($time);
//print("sorted time (descending order) =\n");print(time);
three_dmn_rec_var=three_dmn_rec_var.reverse($time);

// Method two: Key difference is srt_map=$time.size-srt_map-1;
EOF
ncap2 -O -v -S ~/ncap2_foo.nco ~/nco/data/in.nc ~/foo.nc
@end example

@html
<a name="grd"></a> <!-- http://nco.sf.net/nco.html#grd -->
<a name="rrg"></a> <!-- http://nco.sf.net/nco.html#rrg -->
<a name="rct"></a> <!-- http://nco.sf.net/nco.html#rct -->
@end html

@node Irregular grids, Bilinear interpolation, Sort methods, ncap2 netCDF Arithmetic Processor
@subsection Irregular Grids
@cindex irregular grids
@cindex rectangular grids
@cindex non-rectangular grids
@cindex non-standard grids
@cindex mask
@c fxm need to edit rrg sxn beginning here
@acronym{NCO} is capable of analyzing datasets for many different
underlying coordinate grid types.
netCDF was developed for and initially used with grids comprised of
orthogonal dimensions forming a rectangular coordinate system.
We call such grids @emph{standard} grids.
It is increasingly common for datasets to use metadata to describe
much more complex grids.
Let us first define three important coordinate grid properties:
rectangularity, regularity, and fxm.

Grids are @emph{regular} if the spacing between adjacent is constant. 
For example, a 4-by-5 degree latitude-longitude grid is regular
because the spacings between adjacent latitudes (@w{4 degrees}) are
constant as are the (@w{5 degrees}) spacings between adjacent
longitudes. 
Spacing in @emph{irregular} grids depends on the location along the
coordinate. 
Grids such as Gaussian grids have uneven spacing in latitude (points 
cluster near the equator) and so are irregular.

Grids are @emph{rectangular} if the number of elements in any
dimension is not a function of any other dimension.
For example, a T42 Gaussian latitude-longitude grid is rectangular
because there are the same number of longitudes (128) for each of the 
(64) latitudes.
Grids are @emph{non-rectangular} if the elements in any dimension
depend on another dimension.
Non-rectangular grids present many special challenges to 
analysis software like @acronym{NCO}.

Wrapped coordinates (@pxref{Wrapped Coordinates}), such as longitude,
are independent of these grid properties (regularity,
rectangularity). 

@cindex wrapped coordinates
The preferred @acronym{NCO} technique to analyze data on non-standard
coordinate grids is to create a region mask with @command{ncap2}, and
then to use the mask within @command{ncap2} for variable-specific
processing, and/or with other operators (e.g., @command{ncwa},
@command{ncdiff}) for entire file processing. 

Before describing the construction of masks, let us review how
irregularly gridded geoscience data are described.
Say that latitude and longitude are stored as @var{R}-dimensional
arrays and the product of the dimension sizes is the total number of  
elements N in the other variables.
Geoscience applications tend to use @math{@var{R}=1}, 
@math{@var{R}=2}, and @math{@var{R}=3}.

If the grid is has no simple representation (e.g., discontinuous) then
it makes sense to store all coordinates as 1D arrays with the same
size as the number of grid points. 
These gridpoints can be completely independent of all the other (own
weight, area, etc.).  

@var{R}=1: lat(number_of_gridpoints) and lon(number_of_gridpoints)

If the horizontal grid is time-invariant then @var{R}=2 is common:

@var{R}=2: lat(south_north,east_west) and lon(south_north,east_west)

The Weather and Research Forecast (@acronym{WRF}) model uses @var{R}=3:

@var{R}=3: lat(time,south_north,east_west), lon(time,south_north,east_west)

and so supports grids that change with time.

Grids with @var{R} > 1 often use missing values to indicated empty points.
For example, so-called "staggered grids" will use fewer east_west
points near the poles and more near the equator. netCDF only accepts
rectangular arrays so space must be allocated for the maximum number
of east_west points at all latitudes. Then the application writes
missing values into the unused points near the poles.

We demonstrate the @command{ncap2} analysis technique for irregular
regions by constructing a mask for an @var{R}=2 grid.
We wish to find, say, the mean temperature within 
[@var{lat_min},@var{lat_max}] and [@var{lon_min},@var{lon_max}]: 
@example
ncap2 -s 'mask_var= (lat >= lat_min && lat <= lat_max) && \
                    (lon >= lon_min && lon <= lon_max);' in.nc out.nc
@end example
Arbitrarily shaped regions can be defined by more complex conditional
statements. 
Once defined, masks can be applied to specific variables,
and to entire files:
@example
ncap2 -s 'temperature_avg=(temperature*mask_var).avg()' in.nc out.nc
ncwa -a lat,lon -m mask_var -w area in.nc out.nc
@end example
Crafting such commands on the command line is possible though unwieldy.
In such cases, a script is often cleaner and allows you to document the
procedure:
@example
@verbatim
cat > ncap2.in << 'EOF'
mask_var = (lat >= lat_min && lat <= lat_max) && (lon >= lon_min && > lon <= lon_max);
if(mask_var.total() > 0){ // Check that mask contains some valid values
  temperature_avg=(temperature*mask_var).avg(); // Average temperature
  temperature_max=(temperature*mask_var).max(); // Maximum temperature
}
EOF
ncap2 -S ncap2.in in.nc out.nc
@end verbatim
@end example

@html
<a name="wrf"></a> <!-- http://nco.sf.net/nco.html#wrf -->
<a name="WRF"></a> <!-- http://nco.sf.net/nco.html#WRF -->
@end html
@ignore
http://foehn.colorado.edu/wrfout_to_cf/wrfout_to_cf.ncl
ncl 'file_in="wrfout.nc"' 'file_out="wrfpost.nc"' wrfout_to_cf.ncl
ncl 'file_in="wrfout_d02_2013-10-04_20:00:00"' 'file_out="wrfout_d02_2013-10-04_20:00:00_cf.nc"' wrfout_to_cf.ncl
ncl 'file_in="wrfout_v2_Lambert"' 'file_out="wrfout_v2_Lambert.nc"' wrfout_to_cf.ncl
@end ignore
@cindex @acronym{WRF}
Grids like those produced by the @acronym{WRF} model are complex because
one must use global metadata to determine the grid staggering and
offsets to translate @code{XLAT} and @code{XLONG} into real latitudes, 
longitudes, and missing points. 
The @acronym{WRF} grid documentation should describe this.
For @acronym{WRF} files creating regional masks looks like 
@example
mask_var = (XLAT >= lat_min && XLAT <= lat_max) && (XLONG >= lon_min && XLONG <= lon_max);
@end example

A few notes:
Irregular regions are the union of arrays lat/lon_min/max's. 
The mask procedure is identical for all @var{R}.
@c fxm need to edit rrg sxn down to here

@html
<a name="bln_ntp"></a> <!-- http://nco.sf.net/nco.html#bln_ntp -->
<a name="bil_int"></a> <!-- http://nco.sf.net/nco.html#bil_int -->
@end html
@node Bilinear interpolation, GSL special functions, Irregular grids, ncap2 netCDF Arithmetic Processor
@subsection Bilinear interpolation
@noindent As of version 4.0.0 @acronym{NCO} has internal routines to
perform bilinear interpolation on gridded data sets.
In mathematics, bilinear interpolation is an extension of linear
interpolation for interpolating functions of two variables on a regular
grid. 
The idea is to perform linear interpolation first in one direction, and
then again in the other direction.

Suppose we have an irregular grid of data @code{temperature[lat,lon]},
with co-ordinate vars @code{lat[lat], lon[lon]}. 
We wish to find the temperature at an arbitary point [@var{X},@var{Y}]
within the grid. 
If we can locate lat_min,lat_max and lon_min,lon_max such that 
@code{lat_min <= X <= lat_max} and @code{lon_min <= Y <= lon_max} 
then we can interpolate in two dimensions the temperature at
[@var{X},@var{Y}]. 

The general form of the @command{ncap2} interpolation function is
@example
var_out=bilinear_interp(grid_in,grid_out,grid_out_x,grid_out_y,grid_in_x,grid_in_y)
@end example
where
@table @code
@item grid_in
Input function data. 
Usually a two dimensional variable. 
It must be of size @code{grid_in_x.size()*grid_in_y.size()}        
@item grid_out
This variable is the shape of @code{var_out}. 
Usually a two dimensional variable. 
It must be of size @code{grid_out_x.size()*grid_out_y.size()}
@item grid_out_x
@var{X} output values 
@item grid_out_y
@var{Y} output values 
@item grid_in_x
@var{X} input values values. Must be monotonic (increasing or decreasing).
@item grid_in_y
@var{Y} input values values. Must be monotonic (increasing or decreasing).
@end table
@noindent
Prior to calculations all arguments are converted to type
@code{NC_DOUBLE}.
After calculations @code{var_out} is converted to the input type of
@code{grid_in}. 

Suppose the first part of an @command{ncap2} script is
@example
defdim("X",4);
defdim("Y",5);

// Temperature
T_in[$X,$Y]=
 @{100, 200, 300, 400, 500,
  101, 202, 303, 404, 505,
  102, 204, 306, 408, 510,
  103, 206, 309, 412, 515.0 @};

// Coordinate variables
x_in[$X]=@{0.0,1.0,2.0,3.01@};
y_in[$Y]=@{1.0,2.0,3.0,4.0,5@};
@end example
Now we interpolate with the following variables:
@example
defdim("Xn",3);
defdim("Yn",4); 
T_out[$Xn,$Yn]=0.0;
x_out[$Xn]=@{0.0,0.02,3.01@};
y_out[$Yn]=@{1.1,2.0,3,4@};

var_out=bilinear_interp(T_in,T_out,x_out,y_out,x_in,y_in);
print(var_out);
// 110, 200, 300, 400,
// 110.022, 200.04, 300.06, 400.08,
// 113.3, 206, 309, 412 ;
@end example 

It is possible to interpolate a single point:
@example
var_out=bilinear_interp(T_in,0.0,3.0,4.99,x_in,y_in);
print(var_out);
// 513.920594059406
@end example

@noindent @strong{Wrapping and Extrapolation} @*
@noindent The function @code{bilinear_interp_wrap()} takes the same
arguments as @code{bilinear_interp()} but performs wrapping (@var{Y})
and extrapolation (@var{X}) for points off the edge of the grid.
If the given range of longitude is say (25-335) and we have a point at
20 degrees, then the endpoints of the range are used for the
interpolation. 
This is what wrapping means.   
For wrapping to occur @var{Y} must be longitude and must be in the range
(0,360) or (-180,180). 
There are no restrictions on the longitude (@var{X}) values, though
typically these are in the range (-90,90).
This @command{ncap2} script illustrates both wrapping and extrapolation
of end points:
@example
defdim("lat_in",6);
defdim("lon_in",5);

// Coordinate input vars
lat_in[$lat_in]=@{-80,-40,0,30,60.0,85.0@};
lon_in[$lon_in]=@{30, 110, 190, 270, 350.0@};

T_in[$lat_in,$lon_in]=
  @{10,40,50,30,15,   
    12,43,52,31,16,   
    14,46,54,32,17,   
    16,49,56,33,18,   
    18,52,58,34,19,   
    20,55,60,35,20.0 @};
   
defdim("lat_out",4);
defdim("lon_out",3);

// Coordinate variables
lat_out[$lat_out]=@{-90,0,70,88.0@};   
lon_out[$lon_out]=@{0,190,355.0@};

T_out[$lat_out,$lon_out]=0.0;

T_out=bilinear_interp_wrap(T_in,T_out,lat_out,lon_out,lat_in,lon_in);
print(T_out); 
// 13.4375, 49.5, 14.09375,
// 16.25, 54, 16.625,
// 19.25, 58.8, 19.325,
// 20.15, 60.24, 20.135 ;
@end example

@html
<a name="gsl"></a> <!-- http://nco.sf.net/nco.html#gsl -->
@end html
@node GSL special functions, GSL interpolation, Bilinear interpolation, ncap2 netCDF Arithmetic Processor
@subsection GSL special functions
@cindex @acronym{GSL}
@noindent As of version 3.9.6 (released January, 2009), @acronym{NCO} 
can link to the GNU Scientific Library (@acronym{GSL}). 
@command{ncap2} can access most @acronym{GSL} special functions including
Airy, Bessel, error, gamma, beta, hypergeometric, and Legendre functions
and elliptical integrals. 
@acronym{GSL} must be @w{version 1.4} or later. 
To list the @acronym{GSL} functions available with your @acronym{NCO} 
build, use @command{ncap2 -f | grep ^gsl}.

@noindent The function names used by @acronym{ncap2} mirror their
@acronym{GSL} names.
The @acronym{NCO} wrappers for @acronym{GSL} functions automatically
call the error-handling version of the @acronym{GSL} function when
available  
@footnote{   
These are the @acronym{GSL} standard function names postfixed with
@code{_e}.  
@acronym{NCO} calls these functions automatically, without the 
@acronym{NCO} command having to specifically indicate the @code{_e}
function suffix.
}.
This allows @acronym{NCO} to return a missing value when the
@acronym{GSL} library encounters a domain error or a floating point 
exception. 
The slow-down due to calling the error-handling version of the 
@acronym{GSL} numerical functions was found to be negligible (please let
us know if you find otherwise).

@cindex gamma function
@cindex @var{gsl_sf_gamma}
@noindent Consider the gamma function.@*
@noindent The @acronym{GSL} function prototype is @*
@code{int gsl_sf_gamma_e(const double x, gsl_sf_result * result)}
The @command{ncap2} script would be:
@example
lon_in[lon]=@{-1,0.1,0,2,0.3@};
lon_out=gsl_sf_gamma(lon_in);
lon_out= _, 9.5135, 4.5908, 2.9915 
@end example

@noindent The first value is set to @code{_FillValue} since the gamma
function is undefined for negative integers.
If the input variable has a missing value then this value is used.
Otherwise, the default double fill value is used
(defined in the netCDF header @file{netcdf.h} as 
@code{NC_FILL_DOUBLE = 9.969e+36}).

@cindex Bessel function
@cindex @var{gsl_sf_bessel_Jn}
@noindent Consider a call to a Bessel function with @acronym{GSL}
prototype@* 
@code{int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result)} 

An @command{ncap2} script would be
@example
lon_out=gsl_sf_bessel_Jn(2,lon_in);  
lon_out=0.11490, 0.0012, 0.00498, 0.011165
@end example
This computes the Bessel function of order @var{n=2} for every value in
@code{lon_in}.
The Bessel order argument, an integer, can also be a non-scalar
variable, i.e., an array.  
@example
n_in[lon]=@{0,1,2,3@};
lon_out=gsl_sf_bessel_Jn(n_in,0.5);
lon_out= 0.93846, 0.24226, 0.03060, 0.00256
@end example

@noindent Arguments to @acronym{GSL} wrapper functions in @command{ncap2}
must conform to one another, i.e., they must share the same sub-set of
dimensions.  
For example: @code{three_out=gsl_sf_bessel_Jn(n_in,three_dmn_var_dbl)}
is valid because the variable @code{three_dmn_var_dbl} has a @var{lon} 
dimension, so @code{n_in} in can be broadcast to conform to
@code{three_dmn_var_dbl}.  
However @code{time_out=gsl_sf_bessel_Jn(n_in,time)} is invalid.

@cindex Elliptic integrals
Consider the elliptical integral with prototype
@code{int gsl_sf_ellint_RD_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result)}
@example
three_out=gsl_sf_ellint_RD(0.5,time,three_dmn_var_dbl);
@end example

@noindent The three arguments are all conformable so the above @command{ncap2} call is valid. The mode argument in the function prototype controls the convergence of the algorithm. It also appears  in the Airy Function prototypes. It can be set by defining the environment variable @code{GSL_PREC_MODE}. If unset it defaults to the value @code{GSL_PREC_DOUBLE}. See the @acronym{GSL} manual for more details. 
@example
export GSL_PREC_MODE=0 // GSL_PREC_DOUBLE
export GSL_PREC_MODE=1 // GSL_PREC_SINGLE
export GSL_PREC_MODE=2 // GSL_PREC_APPROX
@end example

@noindent The @command{ncap2} wrappers to the array functions are
slightly different. 
Consider the following @acronym{GSL} prototype @* 
@code{int gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double *result_array)}
@example
b1=lon.double();
x=0.5;
status=gsl_sf_bessel_Jn_array(1,4,x,&b1);
print(status);
b1=0.24226,0.0306,0.00256,0.00016;
@end example
@noindent This calculates the Bessel function of @var{x}=0.5 for
@var{n}=1 to 4. 
The first three arguments are scalar values. 
If a non-scalar variable is supplied as an argument then only the first
value is used. 
The final argument is the variable where the results are stored (NB: the
@code{&} indicates this is a call by reference). 
This final argument must be of type @code{double} and must be of least
size @var{nmax-nmin+1}. 
If either of these conditions is not met then then the function 
returns an error message. 
The function/wrapper returns a status flag. 
Zero indicates success. 

@noindent Consider another array function @* 
@code{int gsl_sf_legendre_Pl_array( int lmax, double x, double *result_array);}
@cindex Legendre polynomial
@findex gsl_sf_legendre_Pl
@example
a1=time.double();
x=0.3;
status=gsl_sf_legendre_Pl_array(a1.size()-1, x,&a1);  
print(status);
@end example
@noindent This call calculates @var{P_l}(0.3) for @var{l}=0..9. 
Note that @var{|x|<=1}, otherwise there will be a domain error. 
See the @acronym{GSL} 
documentation for more details.  

@noindent The @acronym{GSL} functions implemented in @acronym{NCO} are 
listed in the table below. 
This table is correct for @acronym{GSL} version 1.10. 
To see what functions are available on your build run the command
@command{ncap2 -f |grep ^gsl} . 
To see this table along with the @acronym{GSL} @w{C-function}
prototypes look at the spreadsheet @strong{doc/nco_gsl.ods}. @* @* 

@multitable @columnfractions .35 .05 .60 
@item @strong{GSL NAME} @tab @strong{I} @tab @strong{NCAP FUNCTION CALL}
@item gsl_sf_airy_Ai_e @tab Y @tab gsl_sf_airy_Ai(dbl_expr)
@item gsl_sf_airy_Bi_e @tab Y @tab gsl_sf_airy_Bi(dbl_expr)
@item gsl_sf_airy_Ai_scaled_e @tab Y @tab gsl_sf_airy_Ai_scaled(dbl_expr)
@item gsl_sf_airy_Bi_scaled_e @tab Y @tab gsl_sf_airy_Bi_scaled(dbl_expr)
@item gsl_sf_airy_Ai_deriv_e @tab Y @tab gsl_sf_airy_Ai_deriv(dbl_expr)
@item gsl_sf_airy_Bi_deriv_e @tab Y @tab gsl_sf_airy_Bi_deriv(dbl_expr)
@item gsl_sf_airy_Ai_deriv_scaled_e @tab Y @tab gsl_sf_airy_Ai_deriv_scaled(dbl_expr)
@item gsl_sf_airy_Bi_deriv_scaled_e @tab Y @tab gsl_sf_airy_Bi_deriv_scaled(dbl_expr)
@item gsl_sf_airy_zero_Ai_e @tab Y @tab gsl_sf_airy_zero_Ai(uint_expr)
@item gsl_sf_airy_zero_Bi_e @tab Y @tab gsl_sf_airy_zero_Bi(uint_expr)
@item gsl_sf_airy_zero_Ai_deriv_e @tab Y @tab gsl_sf_airy_zero_Ai_deriv(uint_expr)
@item gsl_sf_airy_zero_Bi_deriv_e @tab Y @tab gsl_sf_airy_zero_Bi_deriv(uint_expr)
@item gsl_sf_bessel_J0_e @tab Y @tab gsl_sf_bessel_J0(dbl_expr)
@item gsl_sf_bessel_J1_e @tab Y @tab gsl_sf_bessel_J1(dbl_expr)
@item gsl_sf_bessel_Jn_e @tab Y @tab gsl_sf_bessel_Jn(int_expr,dbl_expr)
@item gsl_sf_bessel_Jn_array @tab Y @tab status=gsl_sf_bessel_Jn_array(int,int,double,&var_out)
@item gsl_sf_bessel_Y0_e @tab Y @tab gsl_sf_bessel_Y0(dbl_expr)
@item gsl_sf_bessel_Y1_e @tab Y @tab gsl_sf_bessel_Y1(dbl_expr)
@item gsl_sf_bessel_Yn_e @tab Y @tab gsl_sf_bessel_Yn(int_expr,dbl_expr)
@item gsl_sf_bessel_Yn_array @tab Y @tab gsl_sf_bessel_Yn_array
@item gsl_sf_bessel_I0_e @tab Y @tab gsl_sf_bessel_I0(dbl_expr)
@item gsl_sf_bessel_I1_e @tab Y @tab gsl_sf_bessel_I1(dbl_expr)
@item gsl_sf_bessel_In_e @tab Y @tab gsl_sf_bessel_In(int_expr,dbl_expr)
@item gsl_sf_bessel_In_array @tab Y @tab status=gsl_sf_bessel_In_array(int,int,double,&var_out)
@item gsl_sf_bessel_I0_scaled_e @tab Y @tab gsl_sf_bessel_I0_scaled(dbl_expr)
@item gsl_sf_bessel_I1_scaled_e @tab Y @tab gsl_sf_bessel_I1_scaled(dbl_expr)
@item gsl_sf_bessel_In_scaled_e @tab Y @tab gsl_sf_bessel_In_scaled(int_expr,dbl_expr)
@item gsl_sf_bessel_In_scaled_array @tab Y @tab staus=gsl_sf_bessel_In_scaled_array(int,int,double,&var_out)
@item gsl_sf_bessel_K0_e @tab Y @tab gsl_sf_bessel_K0(dbl_expr)
@item gsl_sf_bessel_K1_e @tab Y @tab gsl_sf_bessel_K1(dbl_expr)
@item gsl_sf_bessel_Kn_e @tab Y @tab gsl_sf_bessel_Kn(int_expr,dbl_expr)
@item gsl_sf_bessel_Kn_array @tab Y @tab status=gsl_sf_bessel_Kn_array(int,int,double,&var_out)
@item gsl_sf_bessel_K0_scaled_e @tab Y @tab gsl_sf_bessel_K0_scaled(dbl_expr)
@item gsl_sf_bessel_K1_scaled_e  @tab Y @tab gsl_sf_bessel_K1_scaled(dbl_expr)
@item gsl_sf_bessel_Kn_scaled_e @tab Y @tab gsl_sf_bessel_Kn_scaled(int_expr,dbl_expr)
@item gsl_sf_bessel_Kn_scaled_array @tab Y @tab status=gsl_sf_bessel_Kn_scaled_array(int,int,double,&var_out)
@item gsl_sf_bessel_j0_e @tab Y @tab gsl_sf_bessel_J0(dbl_expr)
@item gsl_sf_bessel_j1_e @tab Y @tab gsl_sf_bessel_J1(dbl_expr)
@item gsl_sf_bessel_j2_e @tab Y @tab gsl_sf_bessel_j2(dbl_expr)
@item gsl_sf_bessel_jl_e @tab Y @tab gsl_sf_bessel_jl(int_expr,dbl_expr)
@item gsl_sf_bessel_jl_array @tab Y @tab status=gsl_sf_bessel_jl_array(int,double,&var_out)
@item gsl_sf_bessel_jl_steed_array @tab Y @tab gsl_sf_bessel_jl_steed_array
@item gsl_sf_bessel_y0_e @tab Y @tab gsl_sf_bessel_Y0(dbl_expr)
@item gsl_sf_bessel_y1_e @tab Y @tab gsl_sf_bessel_Y1(dbl_expr)
@item gsl_sf_bessel_y2_e @tab Y @tab gsl_sf_bessel_y2(dbl_expr)
@item gsl_sf_bessel_yl_e @tab Y @tab gsl_sf_bessel_yl(int_expr,dbl_expr)
@item gsl_sf_bessel_yl_array @tab Y @tab status=gsl_sf_bessel_yl_array(int,double,&var_out)
@item gsl_sf_bessel_i0_scaled_e @tab Y @tab gsl_sf_bessel_I0_scaled(dbl_expr)
@item gsl_sf_bessel_i1_scaled_e @tab Y @tab gsl_sf_bessel_I1_scaled(dbl_expr)
@item gsl_sf_bessel_i2_scaled_e @tab Y @tab gsl_sf_bessel_i2_scaled(dbl_expr)
@item gsl_sf_bessel_il_scaled_e @tab Y @tab gsl_sf_bessel_il_scaled(int_expr,dbl_expr)
@item gsl_sf_bessel_il_scaled_array @tab Y @tab status=gsl_sf_bessel_il_scaled_array(int,double,&var_out)
@item gsl_sf_bessel_k0_scaled_e @tab Y @tab gsl_sf_bessel_K0_scaled(dbl_expr)
@item gsl_sf_bessel_k1_scaled_e @tab Y @tab gsl_sf_bessel_K1_scaled(dbl_expr)
@item gsl_sf_bessel_k2_scaled_e @tab Y @tab gsl_sf_bessel_k2_scaled(dbl_expr)
@item gsl_sf_bessel_kl_scaled_e @tab Y @tab gsl_sf_bessel_kl_scaled(int_expr,dbl_expr)
@item gsl_sf_bessel_kl_scaled_array @tab Y @tab status=gsl_sf_bessel_kl_scaled_array(int,double,&var_out)
@item gsl_sf_bessel_Jnu_e @tab Y @tab gsl_sf_bessel_Jnu(dbl_expr,dbl_expr)
@item gsl_sf_bessel_Ynu_e @tab Y @tab gsl_sf_bessel_Ynu(dbl_expr,dbl_expr)
@item gsl_sf_bessel_sequence_Jnu_e @tab N @tab gsl_sf_bessel_sequence_Jnu
@item gsl_sf_bessel_Inu_scaled_e @tab Y @tab gsl_sf_bessel_Inu_scaled(dbl_expr,dbl_expr)
@item gsl_sf_bessel_Inu_e @tab Y @tab gsl_sf_bessel_Inu(dbl_expr,dbl_expr)
@item gsl_sf_bessel_Knu_scaled_e @tab Y @tab gsl_sf_bessel_Knu_scaled(dbl_expr,dbl_expr)
@item gsl_sf_bessel_Knu_e @tab Y @tab gsl_sf_bessel_Knu(dbl_expr,dbl_expr)
@item gsl_sf_bessel_lnKnu_e @tab Y @tab gsl_sf_bessel_lnKnu(dbl_expr,dbl_expr)
@item gsl_sf_bessel_zero_J0_e @tab Y @tab gsl_sf_bessel_zero_J0(uint_expr)
@item gsl_sf_bessel_zero_J1_e @tab Y @tab gsl_sf_bessel_zero_J1(uint_expr)
@item gsl_sf_bessel_zero_Jnu_e @tab N @tab gsl_sf_bessel_zero_Jnu
@item gsl_sf_clausen_e @tab Y @tab gsl_sf_clausen(dbl_expr)
@item gsl_sf_hydrogenicR_1_e @tab N @tab gsl_sf_hydrogenicR_1
@item gsl_sf_hydrogenicR_e @tab N @tab gsl_sf_hydrogenicR
@item gsl_sf_coulomb_wave_FG_e @tab N @tab gsl_sf_coulomb_wave_FG
@item gsl_sf_coulomb_wave_F_array @tab N @tab gsl_sf_coulomb_wave_F_array
@item gsl_sf_coulomb_wave_FG_array @tab N @tab gsl_sf_coulomb_wave_FG_array
@item gsl_sf_coulomb_wave_FGp_array @tab N @tab gsl_sf_coulomb_wave_FGp_array
@item gsl_sf_coulomb_wave_sphF_array  @tab N @tab gsl_sf_coulomb_wave_sphF_array 
@item gsl_sf_coulomb_CL_e @tab N @tab gsl_sf_coulomb_CL
@item gsl_sf_coulomb_CL_array @tab N @tab gsl_sf_coulomb_CL_array
@item gsl_sf_coupling_3j_e @tab N @tab gsl_sf_coupling_3j
@item gsl_sf_coupling_6j_e @tab N @tab gsl_sf_coupling_6j
@item gsl_sf_coupling_RacahW_e @tab N @tab gsl_sf_coupling_RacahW
@item gsl_sf_coupling_9j_e @tab N @tab gsl_sf_coupling_9j
@item gsl_sf_coupling_6j_INCORRECT_e @tab N  @tab gsl_sf_coupling_6j_INCORRECT
@item gsl_sf_dawson_e @tab Y @tab gsl_sf_dawson(dbl_expr)
@item gsl_sf_debye_1_e @tab Y @tab gsl_sf_debye_1(dbl_expr)
@item gsl_sf_debye_2_e @tab Y @tab gsl_sf_debye_2(dbl_expr)
@item gsl_sf_debye_3_e @tab Y @tab gsl_sf_debye_3(dbl_expr)
@item gsl_sf_debye_4_e @tab Y @tab gsl_sf_debye_4(dbl_expr)
@item gsl_sf_debye_5_e @tab Y @tab gsl_sf_debye_5(dbl_expr)
@item gsl_sf_debye_6_e @tab Y @tab gsl_sf_debye_6(dbl_expr)
@item gsl_sf_dilog_e @tab N @tab gsl_sf_dilog
@item gsl_sf_complex_dilog_xy_e  @tab N @tab gsl_sf_complex_dilog_xy_e 
@item gsl_sf_complex_dilog_e @tab N @tab gsl_sf_complex_dilog
@item gsl_sf_complex_spence_xy_e   @tab N @tab gsl_sf_complex_spence_xy_e  
@item gsl_sf_multiply_e @tab N @tab gsl_sf_multiply
@item gsl_sf_multiply_err_e @tab N @tab gsl_sf_multiply_err
@item gsl_sf_ellint_Kcomp_e @tab Y @tab gsl_sf_ellint_Kcomp(dbl_expr)
@item gsl_sf_ellint_Ecomp_e @tab Y @tab gsl_sf_ellint_Ecomp(dbl_expr)
@item gsl_sf_ellint_Pcomp_e @tab Y @tab gsl_sf_ellint_Pcomp(dbl_expr,dbl_expr)
@item gsl_sf_ellint_Dcomp_e @tab Y @tab gsl_sf_ellint_Dcomp(dbl_expr)
@item gsl_sf_ellint_F_e @tab Y @tab gsl_sf_ellint_F(dbl_expr,dbl_expr)
@item gsl_sf_ellint_E_e @tab Y @tab gsl_sf_ellint_E(dbl_expr,dbl_expr)
@item gsl_sf_ellint_P_e @tab Y @tab gsl_sf_ellint_P(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_ellint_D_e @tab Y @tab gsl_sf_ellint_D(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_ellint_RC_e @tab Y @tab gsl_sf_ellint_RC(dbl_expr,dbl_expr)
@item gsl_sf_ellint_RD_e @tab Y @tab gsl_sf_ellint_RD(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_ellint_RF_e @tab Y @tab gsl_sf_ellint_RF(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_ellint_RJ_e @tab Y @tab gsl_sf_ellint_RJ(dbl_expr,dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_elljac_e @tab N @tab gsl_sf_elljac
@item gsl_sf_erfc_e @tab Y @tab gsl_sf_erfc(dbl_expr)
@item gsl_sf_log_erfc_e @tab Y @tab gsl_sf_log_erfc(dbl_expr)
@item gsl_sf_erf_e @tab Y @tab gsl_sf_erf(dbl_expr)
@item gsl_sf_erf_Z_e @tab Y @tab gsl_sf_erf_Z(dbl_expr)
@item gsl_sf_erf_Q_e @tab Y @tab gsl_sf_erf_Q(dbl_expr)
@item gsl_sf_hazard_e @tab Y @tab gsl_sf_hazard(dbl_expr)
@item gsl_sf_exp_e @tab Y @tab gsl_sf_exp(dbl_expr)
@item gsl_sf_exp_e10_e @tab N @tab gsl_sf_exp_e10
@item gsl_sf_exp_mult_e @tab Y @tab gsl_sf_exp_mult(dbl_expr,dbl_expr)
@item gsl_sf_exp_mult_e10_e @tab N @tab gsl_sf_exp_mult_e10
@item gsl_sf_expm1_e @tab Y @tab gsl_sf_expm1(dbl_expr)
@item gsl_sf_exprel_e @tab Y @tab gsl_sf_exprel(dbl_expr)
@item gsl_sf_exprel_2_e @tab Y @tab gsl_sf_exprel_2(dbl_expr)
@item gsl_sf_exprel_n_e @tab Y @tab gsl_sf_exprel_n(int_expr,dbl_expr)
@item gsl_sf_exp_err_e @tab Y @tab gsl_sf_exp_err(dbl_expr,dbl_expr)
@item gsl_sf_exp_err_e10_e @tab N @tab gsl_sf_exp_err_e10
@item gsl_sf_exp_mult_err_e @tab N @tab gsl_sf_exp_mult_err
@item gsl_sf_exp_mult_err_e10_e @tab N @tab gsl_sf_exp_mult_err_e10
@item gsl_sf_expint_E1_e @tab Y @tab gsl_sf_expint_E1(dbl_expr)
@item gsl_sf_expint_E2_e @tab Y @tab gsl_sf_expint_E2(dbl_expr)
@item gsl_sf_expint_En_e @tab Y @tab gsl_sf_expint_En(int_expr,dbl_expr)
@item gsl_sf_expint_E1_scaled_e @tab Y @tab gsl_sf_expint_E1_scaled(dbl_expr)
@item gsl_sf_expint_E2_scaled_e @tab Y @tab gsl_sf_expint_E2_scaled(dbl_expr)
@item gsl_sf_expint_En_scaled_e @tab Y @tab gsl_sf_expint_En_scaled(int_expr,dbl_expr)
@item gsl_sf_expint_Ei_e @tab Y @tab gsl_sf_expint_Ei(dbl_expr)
@item gsl_sf_expint_Ei_scaled_e @tab Y @tab gsl_sf_expint_Ei_scaled(dbl_expr)
@item gsl_sf_Shi_e @tab Y @tab gsl_sf_Shi(dbl_expr)
@item gsl_sf_Chi_e @tab Y @tab gsl_sf_Chi(dbl_expr)
@item gsl_sf_expint_3_e @tab Y @tab gsl_sf_expint_3(dbl_expr)
@item gsl_sf_Si_e @tab Y @tab gsl_sf_Si(dbl_expr)
@item gsl_sf_Ci_e @tab Y @tab gsl_sf_Ci(dbl_expr)
@item gsl_sf_atanint_e @tab Y @tab gsl_sf_atanint(dbl_expr)
@item gsl_sf_fermi_dirac_m1_e @tab Y @tab gsl_sf_fermi_dirac_m1(dbl_expr)
@item gsl_sf_fermi_dirac_0_e @tab Y @tab gsl_sf_fermi_dirac_0(dbl_expr)
@item gsl_sf_fermi_dirac_1_e @tab Y @tab gsl_sf_fermi_dirac_1(dbl_expr)
@item gsl_sf_fermi_dirac_2_e @tab Y @tab gsl_sf_fermi_dirac_2(dbl_expr)
@item gsl_sf_fermi_dirac_int_e @tab Y @tab gsl_sf_fermi_dirac_int(int_expr,dbl_expr)
@item gsl_sf_fermi_dirac_mhalf_e @tab Y @tab gsl_sf_fermi_dirac_mhalf(dbl_expr)
@item gsl_sf_fermi_dirac_half_e @tab Y @tab gsl_sf_fermi_dirac_half(dbl_expr)
@item gsl_sf_fermi_dirac_3half_e @tab Y @tab gsl_sf_fermi_dirac_3half(dbl_expr)
@item gsl_sf_fermi_dirac_inc_0_e @tab Y @tab gsl_sf_fermi_dirac_inc_0(dbl_expr,dbl_expr)
@item gsl_sf_lngamma_e @tab Y @tab gsl_sf_lngamma(dbl_expr)
@item gsl_sf_lngamma_sgn_e @tab N @tab gsl_sf_lngamma_sgn 
@item gsl_sf_gamma_e @tab Y @tab gsl_sf_gamma(dbl_expr)
@item gsl_sf_gammastar_e @tab Y @tab gsl_sf_gammastar(dbl_expr)
@item gsl_sf_gammainv_e @tab Y @tab gsl_sf_gammainv(dbl_expr)
@item gsl_sf_lngamma_complex_e @tab N @tab gsl_sf_lngamma_complex
@item gsl_sf_taylorcoeff_e @tab Y @tab gsl_sf_taylorcoeff(int_expr,dbl_expr)
@item gsl_sf_fact_e @tab Y @tab gsl_sf_fact(uint_expr)
@item gsl_sf_doublefact_e @tab Y @tab gsl_sf_doublefact(uint_expr)
@item gsl_sf_lnfact_e @tab Y @tab gsl_sf_lnfact(uint_expr)
@item gsl_sf_lndoublefact_e @tab Y @tab gsl_sf_lndoublefact(uint_expr)
@item gsl_sf_lnchoose_e @tab N @tab gsl_sf_lnchoose
@item gsl_sf_choose_e @tab N @tab gsl_sf_choose
@item gsl_sf_lnpoch_e @tab Y @tab gsl_sf_lnpoch(dbl_expr,dbl_expr)
@item gsl_sf_lnpoch_sgn_e @tab N @tab gsl_sf_lnpoch_sgn
@item gsl_sf_poch_e @tab Y @tab gsl_sf_poch(dbl_expr,dbl_expr)
@item gsl_sf_pochrel_e @tab Y @tab gsl_sf_pochrel(dbl_expr,dbl_expr)
@item gsl_sf_gamma_inc_Q_e @tab Y @tab gsl_sf_gamma_inc_Q(dbl_expr,dbl_expr)
@item gsl_sf_gamma_inc_P_e @tab Y @tab gsl_sf_gamma_inc_P(dbl_expr,dbl_expr)
@item gsl_sf_gamma_inc_e @tab Y @tab gsl_sf_gamma_inc(dbl_expr,dbl_expr)
@item gsl_sf_lnbeta_e @tab Y @tab gsl_sf_lnbeta(dbl_expr,dbl_expr)
@item gsl_sf_lnbeta_sgn_e @tab N @tab gsl_sf_lnbeta_sgn
@item gsl_sf_beta_e @tab Y @tab gsl_sf_beta(dbl_expr,dbl_expr)
@item gsl_sf_beta_inc_e @tab N @tab gsl_sf_beta_inc
@item gsl_sf_gegenpoly_1_e @tab Y @tab gsl_sf_gegenpoly_1(dbl_expr,dbl_expr)
@item gsl_sf_gegenpoly_2_e @tab Y @tab gsl_sf_gegenpoly_2(dbl_expr,dbl_expr)
@item gsl_sf_gegenpoly_3_e @tab Y @tab gsl_sf_gegenpoly_3(dbl_expr,dbl_expr)
@item gsl_sf_gegenpoly_n_e @tab N @tab gsl_sf_gegenpoly_n
@item gsl_sf_gegenpoly_array @tab Y @tab gsl_sf_gegenpoly_array
@item gsl_sf_hyperg_0F1_e @tab Y @tab gsl_sf_hyperg_0F1(dbl_expr,dbl_expr)
@item gsl_sf_hyperg_1F1_int_e @tab Y @tab gsl_sf_hyperg_1F1_int(int_expr,int_expr,dbl_expr)
@item gsl_sf_hyperg_1F1_e @tab Y @tab gsl_sf_hyperg_1F1(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_U_int_e @tab Y @tab gsl_sf_hyperg_U_int(int_expr,int_expr,dbl_expr)
@item gsl_sf_hyperg_U_int_e10_e @tab N @tab gsl_sf_hyperg_U_int_e10
@item gsl_sf_hyperg_U_e @tab Y @tab gsl_sf_hyperg_U(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_U_e10_e @tab N @tab gsl_sf_hyperg_U_e10
@item gsl_sf_hyperg_2F1_e @tab Y @tab gsl_sf_hyperg_2F1(dbl_expr,dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_2F1_conj_e @tab Y @tab gsl_sf_hyperg_2F1_conj(dbl_expr,dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_2F1_renorm_e @tab Y @tab gsl_sf_hyperg_2F1_renorm(dbl_expr,dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_2F1_conj_renorm_e @tab Y @tab gsl_sf_hyperg_2F1_conj_renorm(dbl_expr,dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_hyperg_2F0_e @tab Y @tab gsl_sf_hyperg_2F0(dbl_expr,dbl_expr,dbl_expr)
@item gsl_sf_laguerre_1_e @tab Y @tab gsl_sf_laguerre_1(dbl_expr,dbl_expr)
@item gsl_sf_laguerre_2_e @tab Y @tab gsl_sf_laguerre_2(dbl_expr,dbl_expr)
@item gsl_sf_laguerre_3_e @tab Y @tab gsl_sf_laguerre_3(dbl_expr,dbl_expr)
@item gsl_sf_laguerre_n_e @tab Y @tab gsl_sf_laguerre_n(int_expr,dbl_expr,dbl_expr)
@item gsl_sf_lambert_W0_e @tab Y @tab gsl_sf_lambert_W0(dbl_expr)
@item gsl_sf_lambert_Wm1_e @tab Y @tab gsl_sf_lambert_Wm1(dbl_expr)
@item gsl_sf_legendre_Pl_e @tab Y @tab gsl_sf_legendre_Pl(int_expr,dbl_expr)
@item gsl_sf_legendre_Pl_array @tab Y @tab status=gsl_sf_legendre_Pl_array(int,double,&var_out)
@item gsl_sf_legendre_Pl_deriv_array @tab N @tab gsl_sf_legendre_Pl_deriv_array
@item gsl_sf_legendre_P1_e @tab Y @tab gsl_sf_legendre_P1(dbl_expr)
@item gsl_sf_legendre_P2_e @tab Y @tab gsl_sf_legendre_P2(dbl_expr)
@item gsl_sf_legendre_P3_e @tab Y @tab gsl_sf_legendre_P3(dbl_expr)
@item gsl_sf_legendre_Q0_e @tab Y @tab gsl_sf_legendre_Q0(dbl_expr)
@item gsl_sf_legendre_Q1_e @tab Y @tab gsl_sf_legendre_Q1(dbl_expr)
@item gsl_sf_legendre_Ql_e @tab Y @tab gsl_sf_legendre_Ql(int_expr,dbl_expr)
@item gsl_sf_legendre_Plm_e @tab Y @tab gsl_sf_legendre_Plm(int_expr,int_expr,dbl_expr)
@item gsl_sf_legendre_Plm_array  @tab Y @tab status=gsl_sf_legendre_Plm_array(int,int,double,&var_out) 
@item gsl_sf_legendre_Plm_deriv_array @tab N @tab gsl_sf_legendre_Plm_deriv_array
@item gsl_sf_legendre_sphPlm_e @tab Y @tab gsl_sf_legendre_sphPlm(int_expr,int_expr,dbl_expr)
@item gsl_sf_legendre_sphPlm_array @tab Y @tab status=gsl_sf_legendre_sphPlm_array(int,int,double,&var_out)
@item gsl_sf_legendre_sphPlm_deriv_array @tab N @tab gsl_sf_legendre_sphPlm_deriv_array
@item gsl_sf_legendre_array_size @tab N @tab gsl_sf_legendre_array_size
@item gsl_sf_conicalP_half_e @tab Y @tab gsl_sf_conicalP_half(dbl_expr,dbl_expr)
@item gsl_sf_conicalP_mhalf_e @tab Y @tab gsl_sf_conicalP_mhalf(dbl_expr,dbl_expr)
@item gsl_sf_conicalP_0_e @tab Y @tab gsl_sf_conicalP_0(dbl_expr,dbl_expr)
@item gsl_sf_conicalP_1_e @tab Y @tab gsl_sf_conicalP_1(dbl_expr,dbl_expr)
@item gsl_sf_conicalP_sph_reg_e @tab Y @tab gsl_sf_conicalP_sph_reg(int_expr,dbl_expr,dbl_expr)
@item gsl_sf_conicalP_cyl_reg_e @tab Y @tab gsl_sf_conicalP_cyl_reg(int_expr,dbl_expr,dbl_expr)
@item gsl_sf_legendre_H3d_0_e @tab Y @tab gsl_sf_legendre_H3d_0(dbl_expr,dbl_expr)
@item gsl_sf_legendre_H3d_1_e @tab Y @tab gsl_sf_legendre_H3d_1(dbl_expr,dbl_expr)
@item gsl_sf_legendre_H3d_e @tab Y @tab gsl_sf_legendre_H3d(int_expr,dbl_expr,dbl_expr)
@item gsl_sf_legendre_H3d_array @tab N @tab gsl_sf_legendre_H3d_array
@item gsl_sf_legendre_array_size @tab N @tab gsl_sf_legendre_array_size
@item gsl_sf_log_e @tab Y @tab gsl_sf_log(dbl_expr)
@item gsl_sf_log_abs_e @tab Y @tab gsl_sf_log_abs(dbl_expr)
@item gsl_sf_complex_log_e @tab N @tab gsl_sf_complex_log
@item gsl_sf_log_1plusx_e @tab Y @tab gsl_sf_log_1plusx(dbl_expr)
@item gsl_sf_log_1plusx_mx_e @tab Y @tab gsl_sf_log_1plusx_mx(dbl_expr)
@item gsl_sf_mathieu_a_array @tab N @tab gsl_sf_mathieu_a_array
@item gsl_sf_mathieu_b_array @tab N @tab gsl_sf_mathieu_b_array
@item gsl_sf_mathieu_a @tab N @tab gsl_sf_mathieu_a
@item gsl_sf_mathieu_b @tab N @tab gsl_sf_mathieu_b
@item gsl_sf_mathieu_a_coeff @tab N @tab gsl_sf_mathieu_a_coeff
@item gsl_sf_mathieu_b_coeff @tab N @tab gsl_sf_mathieu_b_coeff
@item gsl_sf_mathieu_ce @tab N @tab gsl_sf_mathieu_ce
@item gsl_sf_mathieu_se @tab N @tab gsl_sf_mathieu_se
@item gsl_sf_mathieu_ce_array @tab N @tab gsl_sf_mathieu_ce_array
@item gsl_sf_mathieu_se_array @tab N @tab gsl_sf_mathieu_se_array
@item gsl_sf_mathieu_Mc @tab N @tab gsl_sf_mathieu_Mc
@item gsl_sf_mathieu_Ms @tab N @tab gsl_sf_mathieu_Ms
@item gsl_sf_mathieu_Mc_array @tab N @tab gsl_sf_mathieu_Mc_array
@item gsl_sf_mathieu_Ms_array @tab N @tab gsl_sf_mathieu_Ms_array
@item gsl_sf_pow_int_e @tab N @tab gsl_sf_pow_int
@item gsl_sf_psi_int_e @tab Y @tab gsl_sf_psi_int(int_expr)
@item gsl_sf_psi_e @tab Y @tab gsl_sf_psi(dbl_expr)
@item gsl_sf_psi_1piy_e @tab Y @tab gsl_sf_psi_1piy(dbl_expr)
@item gsl_sf_complex_psi_e @tab N @tab gsl_sf_complex_psi
@item gsl_sf_psi_1_int_e @tab Y @tab gsl_sf_psi_1_int(int_expr)
@item gsl_sf_psi_1_e @tab Y @tab gsl_sf_psi_1(dbl_expr)
@item gsl_sf_psi_n_e @tab Y @tab gsl_sf_psi_n(int_expr,dbl_expr)
@item gsl_sf_synchrotron_1_e @tab Y @tab gsl_sf_synchrotron_1(dbl_expr)
@item gsl_sf_synchrotron_2_e @tab Y @tab gsl_sf_synchrotron_2(dbl_expr)
@item gsl_sf_transport_2_e @tab Y @tab gsl_sf_transport_2(dbl_expr)
@item gsl_sf_transport_3_e @tab Y @tab gsl_sf_transport_3(dbl_expr)
@item gsl_sf_transport_4_e @tab Y @tab gsl_sf_transport_4(dbl_expr)
@item gsl_sf_transport_5_e @tab Y @tab gsl_sf_transport_5(dbl_expr)
@item gsl_sf_sin_e @tab N @tab gsl_sf_sin
@item gsl_sf_cos_e @tab N @tab gsl_sf_cos
@item gsl_sf_hypot_e @tab N @tab gsl_sf_hypot
@item gsl_sf_complex_sin_e @tab N @tab gsl_sf_complex_sin
@item gsl_sf_complex_cos_e @tab N @tab gsl_sf_complex_cos
@item gsl_sf_complex_logsin_e @tab N @tab gsl_sf_complex_logsin
@item gsl_sf_sinc_e @tab N @tab gsl_sf_sinc
@item gsl_sf_lnsinh_e @tab N @tab gsl_sf_lnsinh
@item gsl_sf_lncosh_e @tab N @tab gsl_sf_lncosh
@item gsl_sf_polar_to_rect @tab N @tab gsl_sf_polar_to_rect
@item gsl_sf_rect_to_polar @tab N @tab gsl_sf_rect_to_polar
@item gsl_sf_sin_err_e @tab N @tab gsl_sf_sin_err
@item gsl_sf_cos_err_e @tab N @tab gsl_sf_cos_err
@item gsl_sf_angle_restrict_symm_e @tab N @tab gsl_sf_angle_restrict_symm
@item gsl_sf_angle_restrict_pos_e @tab N @tab gsl_sf_angle_restrict_pos
@item gsl_sf_angle_restrict_symm_err_e @tab N @tab gsl_sf_angle_restrict_symm_err
@item gsl_sf_angle_restrict_pos_err_e @tab N @tab gsl_sf_angle_restrict_pos_err
@item gsl_sf_zeta_int_e @tab Y @tab gsl_sf_zeta_int(int_expr)
@item gsl_sf_zeta_e @tab Y @tab gsl_sf_zeta(dbl_expr)
@item gsl_sf_zetam1_e @tab Y @tab gsl_sf_zetam1(dbl_expr)
@item gsl_sf_zetam1_int_e @tab Y @tab gsl_sf_zetam1_int(int_expr)
@item gsl_sf_hzeta_e @tab Y @tab gsl_sf_hzeta(dbl_expr,dbl_expr)
@item gsl_sf_eta_int_e @tab Y @tab gsl_sf_eta_int(int_expr)
@item gsl_sf_eta_e @tab Y @tab gsl_sf_eta(dbl_expr)
@end multitable

@html
<a name="gsl_int"></a> <!-- http://nco.sf.net/nco.html#gsl_int -->
@end html
@node GSL interpolation, GSL least-squares fitting, GSL special functions, ncap2 netCDF Arithmetic Processor
@subsection GSL interpolation
@cindex @acronym{GSL}
@noindent As of version 3.9.9 (released July, 2009), @acronym{NCO} has wrappers to the @acronym{GSL} interpolation functions.

@noindent  Given a set of data points (x1,y1)...(xn, yn) the @acronym{GSL} functions computes a continuous interpolating function @acronym{Y(x)} such that @acronym{Y(xi) = yi}. The interpolation is piecewise smooth, and its behavior at the end-points is determined by the type of interpolation used. For more information consult the @acronym{GSL} manual. 

@noindent Interpolation with @command{ncap2} is a two stage process. In the first stage, a @acronym{RAM} variable is created from the chosen interpolating function and the data set. This @acronym{RAM} variable holds in memory a @acronym{GSL} interpolation object. In the second stage, points along the interpolating function are calculated. If you have a very large data set or are interpolating many sets then consider deleting the @acronym{RAM} variable when it is redundant. Use the command @command{ram_delete(var_nm)}.   

@noindent A simple example

@example
x_in[$lon]=@{1.0,2.0,3.0,4.0@};
y_in[$lon]=@{1.1,1.2,1.5,1.8@};

// Ram variable is declared and defined here 
gsl_interp_cspline(&ram_sp,x_in,y_in);

x_out[$lon_grd]=@{1.1,2.0,3.0,3.1,3.99@};

y_out=gsl_spline_eval(ram_sp,x_out);
y2=gsl_spline_eval(ram_sp,1.3);
y3=gsl_spline_eval(ram_sp,0.0);
ram_delete(ram_sp);

print(y_out); // 1.10472, 1.2, 1.4, 1.42658, 1.69680002 
print(y2);    // 1.12454 
print(y3);    // '_' 
@end example

@noindent Note in the above example y3 is set to 'missing value' because 0.0 isn't within the input X range.  

@strong{@acronym{GSL} Interpolation Types}@*
@noindent All the interpolation functions have been implemented. These are:@*
gsl_interp_linear() @* gsl_interp_polynomial() @* gsl_interp_cspline()@*
gsl_interp_cspline_periodic()@* gsl_interp_akima() @* gsl_interp_akima_periodic() @*

@* @*
@strong{ Evaluation of Interpolating Types } @*
@noindent @strong{Implemented} @*
gsl_spline_eval() @*
@noindent @strong{Unimplemented} @*
gsl_spline_deriv()@*
gsl_spline_deriv2()@*
gsl_spline_integ()@*

@html
<a name="ncap_lsqf"></a> <!-- http://nco.sf.net/nco.html#ncap_lsqf -->
@end html
@node GSL least-squares fitting, GSL statistics, GSL interpolation, ncap2 netCDF Arithmetic Processor
@subsection  GSL least-squares fitting       
@noindent Least Squares fitting is a method of calculating a straight line through a set of experimental data points in the XY plane. The data maybe weighted or unweighted. For more information please refer to the @acronym{GSL} manual.

@noindent These @acronym{GSL} functions fall into three categories:@*
@strong{A)} Fitting data to Y=c0+c1*X@*
@strong{B)} Fitting data (through the origin) Y=c1*X@*
@strong{C)} Multi-parameter fitting (not yet implemented)@* 

@strong{Section A} @* @*
@code{status=@strong{gsl_fit_linear} (data_x,stride_x,data_y,stride_y,n,&co,&c1,&cov00,&cov01,&cov11,&sumsq) }

@noindent @strong{Input variables}: data_x, stride_x, data_y, stride_y, n @* 
From the above variables an X and Y vector both of length 'n' are derived. 
If data_x or data_y is less than type double then it is converted to type @code{double}. 
It is up to you to do bounds checking on the input data. 
For example if stride_x=3 and n=8 then the size of data_x must be at least 24

@noindent @strong{Output variables}: c0, c1, cov00, cov01, cov11,sumsq @* 
The '&' prefix indicates that these are call-by-reference variables.
If any of the output variables don't exist prior to the call then they are created on the fly as scalar variables of type @code{double}. If they already exist then their existing value is overwritten. If the function call is successful then @code{status=0}. 

@code{status= @strong{gsl_fit_wlinear}(data_x,stride_x,data_w,stride_w,data_y,stride_y,n,&co,&c1,&cov00,&cov01,&cov11,&chisq) }

@noindent Similar to the above call except it creates an additional weighting vector from the variables data_w, stride_w, n  


@code{ data_y_out=@strong{gsl_fit_linear_est}(data_x,c0,c1,cov00,cov01,cov11) }

@noindent This function calculates y values along the line Y=c0+c1*X @* @*



@strong{Section B} @* @*
@code{status=@strong{gsl_fit_mul}(data_x,stride_x,data_y,stride_y,n,&c1,&cov11,&sumsq) }

@noindent @strong{Input variables}: data_x, stride_x, data_y, stride_y, n @* 
From the above variables an X and Y vector both of length 'n' are derived. 
If data_x or data_y is less than type @code{double} then it is converted to type @code{double}. @*

@noindent @strong{Output variables}: c1,cov11,sumsq @* 


@code{status= @strong{gsl_fit_wmul}(data_x,stride_x,data_w,stride_w,data_y,stride_y,n,&c1,&cov11,&sumsq) }

@noindent Similar to the above call except it creates an additional weighting vector from the variables data_w, stride_w, n  


@code{ data_y_out=@strong{gsl_fit_mul_est}(data_x,c0,c1,cov11) }

@noindent This function calculates y values along the line Y=c1*X @* @*

@noindent The below example shows @strong{gsl_fit_linear()} in action

@example
defdim("d1",10);
xin[d1]=@{1,2,3,4,5,6,7,8,9,10.0@};
yin[d1]=@{3.1,6.2,9.1,12.2,15.1,18.2,21.3,24.0,27.0,30.0@};
gsl_fit_linear(xin,1,yin,1,$d1.size,&c0,&c1,&cov00,&cov01,&cov11,&sumsq);
print(c0);  // 0.2
print(c1);  // 2.98545454545


defdim("e1",4);
xout[e1]=@{1.0,3.0,4.0,11@};
yout[e1]=0.0;

yout=gsl_fit_linear_est(xout, c0,c1, cov00,cov01, cov11, sumsq);

print(yout);  // 3.18545454545 ,9.15636363636, ,12.1418181818 ,33.04
@end example
@* @*



@html
<a name="ncap_stat"></a> <!-- http://nco.sf.net/nco.html#ncap_stat -->
@end html

@node GSL statistics, GSL random number generation, GSL least-squares fitting, ncap2 netCDF Arithmetic Processor
@subsection GSL statistics

@noindent Wrappers for most of the @acronym{GSL} Statistical functions have been implemented. The @acronym{GSL} function names include a type specifier (except for type double functions). To obtain the equivalent @acronym{NCO} name simply remove the type specifier; then depending on the data type the appropriate @acronym{GSL} function  is called. The weighed statistical functions e.g., @code{ gsl_stats_wvariance()} are only defined in @acronym{GSL} for floating point types; so your data must of type @code{float} or @code{double} otherwise ncap2 will emit an error message. To view the implemented functions use the shell command @command{ncap2 -f|grep _stats}   

@noindent @acronym{GSL} Functions
@example
short gsl_stats_max (short data[], size_t stride, size_t n);
double gsl_stats_int_mean (int data[], size_t stride, size_t n);
double gsl_stats_short_sd_with_fixed_mean (short data[], size_t stride, size_t n, double mean);
double gsl_stats_wmean (double w[], size_t wstride, double data[], size_t stride, size_t n);
double gsl_stats_quantile_from_sorted_data (double sorted_data[], size_t stride, size_t n, double f) ;
@end example


@noindent Equivalent ncap2 wrapper functions
@example
short gsl_stats_max (var_data, data_stride, n);
double gsl_stats_mean (var_data, data_stride, n);
double gsl_stats_sd_with_fixed_mean (var_data, data_stride, n, var_mean);
double gsl_stats_wmean (var_weight, weight_stride, var_data, data_stride, n, var_mean);
double gsl_stats_quantile_from_sorted_data (var_sorted_data, data_stride, n, var_f) ;
@end example

@noindent @acronym{GSL} has no notion of missing values or dimensionality beyond one. If your data has missing values which you want ignored in the calculations then use the @command{ncap2} built in aggregate functions( @ref{Methods and functions} ). The @acronym{GSL} functions operate on a vector of values created from the var_data/stride/n arguments. The ncap wrappers check that there is no bounding error with regard to the size of the data and the final value in the vector. 

Some examples

@example
a1[time]=@{1,2,3,4,5,6,7,8,9,10 @};

a1_avg=gsl_stats_mean(a1,1,10);
print(a1_avg); // 5.5

a1_var=gsl_stats_variance(a1,4,3);
print(a1_var); // 16.0

// bounding error, vector attempts to access element a1(10)
a1_sd=gsl_stats_sd(a1,5,3); 

@end example

@noindent For functions with the signature 
@strong{func_nm(var_data,data_stride,n)}, 
one may omit the second or third arguments. 
The default value for @var{stride} is @code{1}. 
The default value for @var{n} is @code{1+(data.size()-1)/stride}.

@example
// Following statements are equvalent
n2=gsl_stats_max(a1,1,10)
n2=gsl_stats_max(a1,1);
n2=gsl_stats_max(a1);

// Following statements are equvalent
n3=gsl_stats_median_from_sorted_data(a1,2,5);
n3=gsl_stats_median_from_sorted_data(a1,2);

// Following statements are NOT equvalent
n4=gsl_stats_kurtosis(a1,3,2);
n4=gsl_stats_kurtosis(a1,3); //default n=4
@end example 

The following example illustrates some of the weighted functions.
The data are randomly generated. 
In this case the value of the weight for each datum is either 0.0 or 1.0   
@example
defdim("r1",2000);
data[r1]=1.0;

// Fill with random numbers [0.0,10.0)
data=10.0*gsl_rng_uniform(data);

// Create a weighting variable
weight=(data>4.0);

wmean=gsl_stats_wmean(weight,1,data,1,$r1.size);
print(wmean);

wsd=gsl_stats_wsd(weight,1,data,1,$r1.size);
print(wsd);

// number of values in data that are greater than 4
weight_size=weight.total();
print(weight_size);

// print min/max of data 
dmin=data.gsl_stats_min();
dmax=data.gsl_stats_max();
print(dmin);print(dmax);
@end example

@html
<a name="ncap_rng"></a> <!-- http://nco.sf.net/nco.html#ncap_rng -->
@end html

@node GSL random number generation, Examples ncap2, GSL statistics, ncap2 netCDF Arithmetic Processor
@subsection GSL random number generation
The @acronym{GSL} library has a large number of random number generators. In addition there are a large set of functions for turning uniform random numbers into discrete or continuous probabilty distributions. The random number generator algorithms vary in terms of quality numbers output, speed of execution and maximium number output. For more information see the @acronym{GSL} documentation. The algorithm and seed are set via environment variables, these are picked up by the @code{ncap2} code.

@noindent @strong{Setup} @*  
The number algorithm is set by the environment variable @code{GSL_RNG_TYPE}. If this variable isn't set then the default rng algorithm is gsl_rng_19937. The seed is set with the environment variable @code{GSL_RNG_SEED}. The following wrapper functions in ncap2 provide information about the chosen algorithm. @* 

@table @code
@item gsl_rng_min() 
the minimium value returned by the rng algorithm.
@item gsl_rng_max()
the maximium value returned by the rng algorithm. 
@end table

@noindent @strong{Uniformly Distributed Random Numbers} 
@table @code
@item gsl_rng_get(var_in)
This function returns var_in with integers from the chosen rng algorithm. The min and max values depend uoon the chosen rng algorthm.
@item gsl_rng_uniform_int(var_in)
This function returns var_in with random integers from 0 to n-1. The value n must be less than or equal to the maximium value of the chosen rng algorithm. 
@item gsl_rng_uniform(var_in)
This function returns var_in with double-precision numbers in the range [0.0,1). The range includes 0.0 and excludes 1.0.
@item gsl_rng_uniform_pos(var_in)
This function returns var_in with double-precision numbers in the range (0.0,1), excluding both 0.0 and 1.0.
@end table

@noindent Below are examples of @code{gsl_rng_get()} and @code{gsl_rng_uniform_int()} in action.

@example
export GSL_RNG_TYPE=ranlux
export GSL_RNG_SEED=10
ncap2 -v -O -s 'a1[time]=0;a2=gsl_rng_get(a1);' in.nc foo.nc 
// 10 random numbers from the range 0 - 16777215
// a2=9056646, 12776696, 1011656, 13354708, 5139066, 1388751, 11163902, 7730127, 15531355, 10387694 ;

ncap2 -v -O -s 'a1[time]=21;a2=gsl_rng_uniform_int(a1).sort();' in.nc foo.nc
// 10 random numbers from the range 0 - 20
a2 = 1, 1, 6, 9, 11, 13, 13, 15, 16, 19 ;

@end example

@noindent The following example produces an @code{ncap2} runtime error. This is because the chose rng algorithm has a maximium value greater than @code{ NC_MAX_INT=2147483647 }; the wrapper functions to @code{gsl_rng_get()} and @code{gsl_rng_uniform_int()} return variable of type @code{NC_INT}. Please be aware of this when using random number distribution functions functions from the @acronym{GSL} library which return @code{unsigned int}. Examples of these are @code{gsl_ran_geometric()} and @code{gsl_ran_pascal()}. 

@example
export GSL_RNG_TYPE=mt19937
ncap2 -v -O -s 'a1[time]=0;a2=gsl_rng_get(a1);' in.nc foo.nc 
@end example

@noindent To find the maximium value of the chosen rng algorithm use the following code snippet.
@example
ncap2 -v -O -s 'rng_max=gsl_rng_max();print(rng_max)' in.nc foo.nc
@end example

@noindent @strong{Random Number Distributions} @*
The @acronym{GSL} library has a rich set of random number disribution functions. The library also provides cumulative distribution functions and inverse cumulative distribution functions sometimes referred to a quantile functions. To see whats available on your build use the shell command @code{ncap2 -f|grep -e _ran -e _cdf}.

@noindent The following examples all return variables of type @code{NC_INT} @*
@example
defdim("out",15);
a1[$out]=0.5;
a2=gsl_ran_binomial(a1,30).sort();
//a2 = 10, 11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 16, 16, 17, 22 ;
a3=gsl_ran_geometric(a2).sort();
//a2 = 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 5 ;
a4=gsl_ran_pascal(a2,50);
//a5 = 37, 40, 40, 42, 43, 45, 46, 49, 52, 58, 60, 62, 62, 65, 67 ;
@end example

@noindent The following all return variables of type @code{NC_DOUBLE};
@example
defdim("b1",1000);
b1[$b1]=0.8;
b2=gsl_ran_exponential(b1);
b2_avg=b2.avg();
print(b2_avg);
// b2_avg = 0.756047976787

b3=gsl_ran_gaussian(b1);
b3_avg=b3.avg();
b3_rms=b3.rms();
print(b3_avg);
// b3_avg = -0.00903446534258;
print(b3_rms);
// b3_rms = 0.81162979889;

b4[$b1]=10.0;
b5[$b1]=20.0;
b6=gsl_ran_flat(b4,b5);
b6_avg=b6.avg();
print(b6_avg);
// b6_avg=15.0588129413
@end example

@html
<a name="ncap_emp"></a> <!-- http://nco.sf.net/nco.html#ncap_emp -->
@end html
@node Examples ncap2, Intrinsic mathematical methods, GSL random number generation, ncap2 netCDF Arithmetic Processor
@subsection Examples ncap2

See the @file{ncap.in} and @file{ncap2.in} scripts released with @acronym{NCO} 
for more complete demonstrations of @command{ncap2} functionality
(script available on-line at @url{http://nco.sf.net/ncap2.in}).

Define new attribute @var{new} for existing variable @var{one}
as twice the existing attribute @var{double_att} of variable
@var{att_var}: 
@example
ncap2 -s 'one@@new=2*att_var@@double_att' in.nc out.nc
@end example

Average variables of mixed types (result is of type @code{double}):
@example
ncap2 -s 'average=(var_float+var_double+var_int)/3' in.nc out.nc 
@end example

Multiple commands may be given to @command{ncap2} in three ways.
First, the commands may be placed in a script which is executed, e.g.,
@file{tst.nco}. 
Second, the commands may be individually specified with multiple
@samp{-s} arguments to the same @command{ncap2} invocation.
Third, the commands may be chained into a single @samp{-s}
argument to @command{ncap2}.
Assuming the file @file{tst.nco} contains the commands
@code{a=3;b=4;c=sqrt(a^2+b^2);}, then the following @command{ncap2}
invocations produce identical results:
@example
ncap2 -v -S tst.nco in.nc out.nc
ncap2 -v -s 'a=3' -s 'b=4' -s 'c=sqrt(a^2+b^2)' in.nc out.nc
ncap2 -v -s 'a=3;b=4;c=sqrt(a^2+b^2)' in.nc out.nc
@end example
The second and third examples show that @command{ncap2} does not require
that a trailing semi-colon @samp{;} be placed at the end of a @samp{-s}
argument, although a trailing semi-colon @samp{;} is always allowed.
However, semi-colons are required to separate individual assignment
statements chained together as a single @samp{-s} argument. 

@html
<a name="xmp_grw"></a> <!-- http://nco.sf.net/nco.html#xmp_grw -->
@end html
@cindex growing dimensions
@cindex dimensions, growing
@command{ncap2} may be used to ``grow'' dimensions, i.e., to increase
dimension sizes without altering existing data.
Say @file{in.nc} has @code{ORO(lat,lon)} and the user wishes a new
file with @code{new_ORO(new_lat,new_lon)} that contains zeros in the
undefined portions of the new grid.
@example
defdim("new_lat",$lat.size+1); // Define new dimension sizes
defdim("new_lon",$lon.size+1);
new_ORO[$new_lat,$new_lon]=0.0f; // Initialize to zero
new_ORO(0:$lat.size-1,0:$lon.size-1)=ORO; // Fill valid data
@end example
The commands to define new coordinate variables @code{new_lat}
and @code{new_lon} in the output file follow a similar pattern.
One would might store these commands in a script @file{grow.nco}
and then execute the script with
@example
ncap2 -v -S grow.nco in.nc out.nc
@end example

@html
<a name="flg"></a> <!-- http://nco.sf.net/nco.html#flg -->
@end html
@cindex flags
Imagine you wish to create a binary flag based on the value of 
an array.
The flag should have @w{value 1.0} where the array @w{exceeds 1.0},
and @w{value 0.0} elsewhere.
This example creates the binary flag @code{ORO_flg} in @file{out.nc}
from the continuous array named @code{ORO} in @file{in.nc}.
@example
ncap2 -s 'ORO_flg=(ORO > 1.0)' in.nc out.nc
@end example
Suppose your task is to change all values of @code{ORO} which 
@w{equal 2.0} to the new @w{value 3.0}:
@example
ncap2 -s 'ORO_msk=(ORO==2.0);ORO=ORO_msk*3.0+!ORO_msk*ORO' in.nc out.nc
@end example
@cindex mask
This creates and uses @code{ORO_msk} to mask the subsequent arithmetic
operation.
Values of @code{ORO} are only changed where @code{ORO_msk} is true,
i.e., where @code{ORO} @w{equals 2.0} @*
Using the @code{where} statement the above code simplifies to :
@example
ncap2 -s 'where(ORO==2.0) ORO=3.0;' in.nc foo.nc
@end example

@html
<a name="cvr"></a> <!-- http://nco.sf.net/nco.html#cvr -->
@end html
This example uses @command{ncap2} to compute the covariance of two
variables. 
Let the variables @var{@wndznl{}} and @var{@wndmrd{}} be the horizontal 
wind components. 
@cindex covariance
@c fxm 20030423: texi2html 1.64 has problems with this legal syntax but makeinfo --html does not
The @dfn{covariance} of @var{@wndznl{}} and @var{@wndmrd{}} is defined
as the time mean product of the deviations of @var{@wndznl{}} and
@var{@wndmrd{}} from their respective time means.
Symbolically, the covariance 
@set flg
@tex
$[\wndznl^{\prime} \wndmrd^{\prime}] =
[\wndznl\wndmrd]-[\wndznl][\wndmrd]$ where $[\xxx]$ denotes the
time-average of~$\xxx$, 
$[\xxx] \equiv {1 \over \tau} \int_{\tm=0}^{\tm=\tau} \xxx(\tm) \,\dfr\tm$
and $\xxx^{\prime}$ 
@clear flg 
@end tex
@ifinfo
@math{[@var{@wndznl{}'@wndmrd{}'}] =
[@var{@wndznl{}@wndmrd{}}]-[@var{@wndznl{}}][@var{@wndmrd{}}]} 
where @math{[@var{@xxx{}}]} denotes the time-average of
@math{@var{@xxx{}}} and @math{@var{@xxx{}'}} 
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
[@var{@wndznl{}'@wndmrd{}'}] =
[@var{@wndznl{}@wndmrd{}}]-[@var{@wndznl{}}][@var{@wndmrd{}}] where
[@xxx{}] denotes the time-average of @var{@xxx{}} and @var{@xxx{}'}
@clear flg
@end ifset
denotes the deviation from the time-mean. 
The covariance tells us how much of the correlation of two signals
arises from the signal fluctuations versus the mean signals.
@cindex eddy covariance
Sometimes this is called the @dfn{eddy covariance}.
We will store the covariance in the variable @code{uprmvprm}.
@example
ncwa -O -a time -v u,v in.nc foo.nc # Compute time mean of u,v
ncrename -O -v u,uavg -v v,vavg foo.nc # Rename to avoid conflict
ncks -A -v uavg,vavg foo.nc in.nc # Place time means with originals
ncap2 -O -s 'uprmvprm=u*v-uavg*vavg' in.nc in.nc # Covariance
ncra -O -v uprmvprm in.nc foo.nc # Time-mean covariance
@end example
The mathematically inclined will note that the same covariance would be
obtained by replacing the step involving @command{ncap2} with
@example
ncap2 -O -s 'uprmvprm=(u-uavg)*(v-vavg)' foo.nc foo.nc # Covariance
@end example

As of @acronym{NCO} version 3.1.8 (December, 2006), @command{ncap2}
can compute averages, and thus covariances, by itself:
@example
ncap2 -s 'uavg=u.avg($time);vavg=v.avg($time);uprmvprm=u*v-uavg*vavg' \
      -s 'uprmvrpmavg=uprmvprm.avg($time)' in.nc foo.nc
@end example
We have not seen a simpler method to script and execute powerful
arithmetic than @command{ncap2}.

@cindex globbing
@cindex shell
@cindex quotes
@cindex extended regular expressions
@cindex regular expressions
@command{ncap2} utilizes many meta-characters 
(e.g., @samp{$}, @samp{?}, @samp{;}, @samp{()}, @samp{[]})
that can confuse the command-line shell if not quoted properly.
The issues are the same as those which arise in utilizing extended
regular expressions to subset variables (@pxref{Subsetting Files}).
The example above will fail with no quotes and with double quotes.
This is because shell globbing tries to @dfn{interpolate} the value of
@code{$time} from the shell environment unless it is quoted:
@example
ncap2 -s 'uavg=u.avg($time)'  in.nc foo.nc # Correct (recommended)
ncap2 -s  uavg=u.avg('$time') in.nc foo.nc # Correct (and dangerous)
ncap2 -s  uavg=u.avg($time)   in.nc foo.nc # Fails ($time = '')
ncap2 -s "uavg=u.avg($time)"  in.nc foo.nc # Fails ($time = '')
@end example
Without the single quotes, the shell replaces @code{$time} with an
empty string.
The command @command{ncap2} receives from the shell is
@code{uavg=u.avg()}. 
This causes @command{ncap2} to average over all dimensions rather than
just the @var{time} dimension, and unintended consequence.

We recommend using single quotes to protect @command{ncap2}
command-line scripts from the shell, even when such protection is not
strictly necessary. 
Expert users may violate this rule to exploit the ability to use shell
variables in @command{ncap2} command-line scripts 
(@pxref{CCSM Example}). 
In such cases it may be necessary to use the shell backslash character
@samp{\} to protect the @command{ncap2} meta-character.

@cindex appending data
@cindex time-averaging
@findex ncks
@findex ncwa
@findex ncra
@cindex degenerate dimension
@cindex @samp{-b}
A dimension of size one is said to be @emph{degenerate}.
Whether a degenerate record dimension is desirable or not
depends on the application.
Often a degenerate @var{time} dimension is useful, e.g., for
concatentating, but it may cause problems with arithmetic.
Such is the case in the above example, where the first step employs
@command{ncwa} rather than @command{ncra} for the time-averaging.
Of course the numerical results are the same with both operators.
The difference is that, unless @samp{-b} is specified, @command{ncwa}
writes no @var{time} dimension to the output file, while @command{ncra}
defaults to keeping @var{time} as a degenerate (@w{size 1}) dimension. 
Appending @code{u} and @code{v} to the output file would cause
@command{ncks} to try to expand the degenerate time axis of @code{uavg}
and @code{vavg} to the size of the non-degenerate @var{time} dimension
in the input file.
Thus the append (@command{ncks -A}) command would be undefined (and
should fail) in this case. 
@cindex @code{-C}
Equally important is the @samp{-C} argument 
(@pxref{Subsetting Coordinate Variables}) to @command{ncwa} to prevent
any scalar @var{time} variable from being written to the output file.  
Knowing when to use @command{ncwa -a time} rather than the default
@command{ncra} for time-averaging takes, well, time.

@html
<a name="mth"></a> <!-- http://nco.sf.net/nco.html#mth -->
@end html
@node Intrinsic mathematical methods, Operator precedence and associativity , Examples ncap2, ncap2 netCDF Arithmetic Processor
@subsection Intrinsic mathematical methods
@command{ncap2} supports the standard mathematical functions supplied with
most operating systems.
@cindex addition
@cindex subtraction
@cindex multiplication
@cindex division
@cindex exponentiation
@cindex power
@cindex modulus
@cindex @code{+} (addition)
@cindex @code{-} (subtraction)
@cindex @code{*} (multiplication)
@cindex @code{/} (division)
@cindex @code{^} (power)
@cindex @code{%} (modulus)
Standard calculator notation is used for addition @kbd{+}, subtraction
@kbd{-}, multiplication @kbd{*}, division @kbd{/}, exponentiation
@kbd{^}, and modulus @kbd{%}.
The available elementary mathematical functions are: 
@cindex @var{abs}
@cindex @var{acosh}
@cindex @var{acos}
@cindex @var{asinh}
@cindex @var{asin}
@cindex @var{atanh}
@cindex @var{atan}
@cindex @var{ceil}
@cindex @var{cosh}
@cindex @var{cos}
@cindex @var{erfc}
@cindex @var{erf}
@cindex @var{exp}
@cindex @var{floor}
@cindex @var{gamma}
@cindex @var{ln}
@cindex @var{log10}
@cindex @var{log}
@cindex @var{nearbyint}
@cindex @var{pow}
@cindex @var{rint}
@cindex @var{round}
@cindex @var{sinh}
@cindex @var{sin}
@cindex @var{sqrt}
@cindex @var{tanh}
@cindex @var{tan}
@cindex @var{trunc}
@cindex mathematical functions
@cindex nearest integer function (inexact)
@cindex nearest integer function (exact)
@cindex rounding functions
@cindex truncation function
@cindex absolute value
@cindex arccosine function
@cindex arcsine function
@cindex arctangent function
@cindex ceiling function
@cindex complementary error function
@cindex cosine function
@cindex error function
@cindex exponentiation function
@cindex floor function
@cindex gamma function
@cindex hyperbolic arccosine function
@cindex hyperbolic arcsine function
@cindex hyperbolic arctangent function
@cindex hyperbolic cosine function
@cindex hyperbolic sine function
@cindex hyperbolic tangent
@cindex logarithm, base 10
@cindex logarithm, natural
@cindex power function
@cindex sine function
@cindex square root function
@table @code
@item abs(x)
@dfn{Absolute value}
@tex
Absolute value of $x$, $|x|$.
@end tex
@ifinfo
Absolute value of @var{x}.
@end ifinfo
Example: 
@tex
abs$(-1) = 1$
@end tex
@ifinfo
@math{abs(-1) = 1}
@end ifinfo
@item acos(x)
@dfn{Arc-cosine}
Arc-cosine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
acos$(1.0) = 0.0$
@end tex
@ifinfo
@math{acos(1.0) = 0.0}
@end ifinfo
@item acosh(x)
@dfn{Hyperbolic arc-cosine}
Hyperbolic arc-cosine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
acosh$(1.0) = 0.0$
@end tex
@ifinfo
@math{acosh(1.0) = 0.0}
@end ifinfo
@item asin(x)
@dfn{Arc-sine}
Arc-sine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
asin$(1.0) = 1.57079632679489661922$
@end tex
@ifinfo
@math{asin(1.0) = 1.57079632679489661922}
@end ifinfo
@item asinh(x)
@dfn{Hyperbolic arc-sine}
Hyperbolic arc-sine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
asinh$(1.0) = 0.88137358702$
@end tex
@ifinfo
@math{asinh(1.0) = 0.88137358702}
@end ifinfo
@item atan(x)
@dfn{Arc-tangent}
Arc-tangent of @var{x} where @var{x} is specified in radians between 
@tex
$-\pi/2$ and $\pi/2$.
@end tex
@ifinfo
@math{-pi/2} and @math{pi/2}.
@end ifinfo
Example: 
@tex
atan$(1.0) = 0.78539816339744830961$
@end tex
@ifinfo
@math{atan(1.0) = 0.78539816339744830961}
@end ifinfo

@item atan2(y,x)
@dfn{Arc-tangent2}
Arc-tangent of @var{y/x} 
@ifinfo
@math{:Example atan2(1,3) =  0.321689857}
@end ifinfo

@item atanh(x)
@dfn{Hyperbolic arc-tangent}
Hyperbolic arc-tangent of @var{x} where @var{x} is specified in radians between 
@tex
$-\pi/2$ and $\pi/2$.
@end tex
@ifinfo
@math{-pi/2} and @math{pi/2}.
@end ifinfo
Example:
@tex
atanh$(3.14159265358979323844) = 1.0$
@end tex
@ifinfo
@math{atanh(3.14159265358979323844) = 1.0}
@end ifinfo
@item ceil(x)
@dfn{Ceil}
Ceiling of @var{x}. Smallest integral value not less than argument.
Example: 
@tex
ceil$(0.1) = 1.0$
@end tex
@ifinfo
@math{ceil(0.1) = 1.0}
@end ifinfo
@item cos(x)
@dfn{Cosine}
Cosine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
cos$(0.0) = 1.0$
@end tex
@ifinfo
@math{cos(0.0) = 1.0}
@end ifinfo
@item cosh(x)
@dfn{Hyperbolic cosine}
Hyperbolic cosine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
cosh$(0.0) = 1.0$
@end tex
@ifinfo
@math{cosh(0.0) = 1.0}
@end ifinfo
@item erf(x)
@dfn{Error function}
Error function of @var{x} where @var{x} is specified between
@tex
$-1$ and $1$.
@end tex
@ifinfo
@math{-1} and @math{1}.
@end ifinfo
Example: 
@tex
erf$(1.0) = 0.842701$
@end tex
@ifinfo
@math{erf(1.0) = 0.842701}
@end ifinfo
@item erfc(x)
@dfn{Complementary error function}
Complementary error function of @var{x} where @var{x} is specified between
@tex
$-1$ and $1$.
@end tex
@ifinfo
@math{-1} and @math{1}.
@end ifinfo
Example: 
@tex
erfc$(1.0) = 0.15729920705$
@end tex
@ifinfo
@math{erfc(1.0) = 0.15729920705}
@end ifinfo
@item exp(x)
@dfn{Exponential}
Exponential of @var{x},
@tex
$e^{x}$.
@end tex
@ifinfo
@math{e^x}.
@end ifinfo
Example: 
@tex
exp$(1.0) = 2.71828182845904523536$
@end tex
@ifinfo
@math{exp(1.0) = 2.71828182845904523536}
@end ifinfo
@item floor(x)
@dfn{Floor}
Floor of @var{x}. Largest integral value not greater than argument.
Example: 
@tex
floor$(1.9) = 1$
@end tex
@ifinfo
@math{floor(1.9) = 1}
@end ifinfo
@item gamma(x)
@dfn{Gamma function}
Gamma function of @var{x},
@tex
$\Gamma(x)$.
@end tex
@ifinfo
@math{Gamma(x)}.
@end ifinfo
The well-known and loved continuous factorial function.
Example: 
@tex
gamma$(0.5) = \sqrt{\pi}$
@end tex
@ifinfo
@math{gamma(0.5) = sqrt(pi)}
@end ifinfo
@item gamma_inc_P(x)
@dfn{Incomplete Gamma function}
Incomplete Gamma function of parameter @var{a} and variable @var{x},
@tex
$P(a,x)$.
@end tex
@ifinfo
@math{gamma_inc_P(a,x)}.
@end ifinfo
One of the four incomplete gamma functions.
Example: 
@tex
gamma\_inc\_P$(1,1) = 1-\me^{-1}$
@end tex
@ifinfo
@math{gamma_inc_P(1,1) = 1-1/e}
@end ifinfo
@item ln(x)
@dfn{Natural Logarithm}
Natural logarithm of @var{x},
@tex
$\ln(x)$.
@end tex
@ifinfo
@math{ln(x)}.
@end ifinfo
Example: 
@tex
ln$(2.71828182845904523536) = 1.0$
@end tex
@ifinfo
@math{ln(2.71828182845904523536) = 1.0}
@end ifinfo
@item log(x)
@dfn{Natural Logarithm}
Exact synonym for @code{ln(x)}.
@item log10(x)
@dfn{Base 10 Logarithm}
@w{Base 10} logarithm of @var{x}, 
@tex
$\log_{10}(x)$.
@end tex
@ifinfo
@math{log10(x)}.
@end ifinfo
Example: 
@tex
log$(10.0) = 1.0$
@end tex
@ifinfo
@math{log(10.0) = 1.0}
@end ifinfo
@item nearbyint(x)
@dfn{Round inexactly}
Nearest integer to @var{x} is returned in floating point format.
@cindex inexact conversion
No exceptions are raised for @dfn{inexact conversions}.
Example: 
@tex
nearbyint$(0.1) = 0.0$
@end tex
@ifinfo
@math{nearbyint(0.1) = 0.0}
@end ifinfo
@item pow(x,y)
@dfn{Power}
@cindex promotion
@cindex automatic type conversion
Value of @var{x} is raised to the power of @var{y}.
Exceptions are raised for @dfn{domain errors}.
Due to type-limitations in the @w{C language} @code{pow} function,
integer arguments are promoted (@pxref{Type Conversion}) to type
@code{NC_FLOAT} before evaluation. 
Example: 
@tex
pow$(2,3) = 8$
@end tex
@ifinfo
@math{pow(2,3) = 8}
@end ifinfo
@item rint(x)
@dfn{Round exactly}
Nearest integer to @var{x} is returned in floating point format.
Exceptions are raised for @dfn{inexact conversions}.
Example: 
@tex
rint$(0.1) = 0$
@end tex
@ifinfo
@math{rint(0.1) = 0}
@end ifinfo
@item round(x)
@dfn{Round}
Nearest integer to @var{x} is returned in floating point format.
Round halfway cases away from zero, regardless of current IEEE rounding direction. 
Example: 
@tex
round$(0.5) = 1.0$
@end tex
@ifinfo
@math{round(0.5) = 1.0}
@end ifinfo
@item sin(x)
@dfn{Sine}
Sine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
sin$(1.57079632679489661922) = 1.0$
@end tex
@ifinfo
@math{sin(1.57079632679489661922) = 1.0}
@end ifinfo
@item sinh(x)
@dfn{Hyperbolic sine}
Hyperbolic sine of @var{x} where @var{x} is specified in radians.
Example: 
@tex
sinh$(1.0) = 1.1752$
@end tex
@ifinfo
@math{sinh(1.0) = 1.1752}
@end ifinfo
@item sqrt(x)
@dfn{Square Root}
Square Root of @var{x},
@tex
$\sqrt{x}$.
@end tex
@ifinfo
@math{sqrt(x)}.
@end ifinfo
Example: 
@tex
sqrt$(4.0) = 2.0$
@end tex
@ifinfo
@math{sqrt(4.0) = 2.0}
@end ifinfo
@item tan(x)
@dfn{Tangent}
Tangent of @var{x} where @var{x} is specified in radians.
Example: 
@tex
tan$(0.78539816339744830961) = 1.0$
@end tex
@ifinfo
@math{tan(0.78539816339744830961) = 1.0}
@end ifinfo
@item tanh(x)
@dfn{Hyperbolic tangent}
Hyperbolic tangent of @var{x} where @var{x} is specified in radians.
Example: 
@tex
tanh$(1.0) = 0.761594155956$
@end tex
@ifinfo
@math{tanh(1.0) = 0.761594155956}
@end ifinfo
@item trunc(x)
@dfn{Truncate}
Nearest integer to @var{x} is returned in floating point format.
Round halfway cases toward zero, regardless of current IEEE rounding direction. 
Example: 
@tex
trunc$(0.5) = 0.0$
@end tex
@ifinfo
@math{trunc(0.5) = 0.0}
@end ifinfo
@end table
@noindent
The complete list of mathematical functions supported is
platform-specific.  
Functions mandated by @w{ANSI C} are @emph{guaranteed} to be present
and are indicated with an asterisk 
@c fxm No they're not, not yet
@cindex @code{ANSI C}
@cindex @code{float}
@cindex precision
@cindex quadruple-precision
@cindex single-precision
@cindex double-precision
@cindex @code{long double}
@cindex @code{NC_DOUBLE}
@footnote{
@w{ANSI C} compilers are guaranteed to support double-precision versions
of these functions.
These functions normally operate on netCDF variables of type @code{NC_DOUBLE}
without having to perform intrinsic conversions.
For example, @acronym{ANSI} compilers provide @code{sin} for the sine of C-type
@code{double} variables. 
The @acronym{ANSI} standard does not require, but many compilers provide,
an extended set of mathematical functions that apply to single
(@code{float}) and quadruple (@code{long double}) precision variables. 
Using these functions (e.g., @code{sinf} for @code{float}, 
@code{sinl} for @code{long double}), when available, is (presumably)
more efficient than casting variables to type @code{double},
performing the operation, and then re-casting.
@acronym{NCO} uses the faster intrinsic functions when they are
available, and uses the casting method when they are not.
}.
and are indicated with an asterisk. 
@cindex @code{-f}
@cindex @code{--prn_fnc_tbl}
@cindex @code{--fnc_tbl}
Use the @samp{-f} (or @samp{fnc_tbl} or @samp{prn_fnc_tbl}) switch
to print a complete list of functions supported on your platform.
@cindex Linux
@footnote{Linux supports more of these intrinsic functions than
other OSs.}

@noindent
@html
<a name="xmp_ncap"></a> <!-- http://nco.sf.net/nco.html#xmp_ncap -->
<a name="xmp_ncap2"></a> <!-- http://nco.sf.net/nco.html#xmp_ncap2 -->
@end html

@c Begin HMB documentation

@html
<a name="ncap_opts"></a> <!-- http://nco.sf.net/nco.html#ncap_opts -->
@end html
@node Operator precedence and associativity , ID Quoting, Intrinsic mathematical methods, ncap2 netCDF Arithmetic Processor
@subsection Operator precedence and associativity
This page lists the @command{ncap2} operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

@multitable @columnfractions .18 .62 .20
@headitem Operator @tab Description @tab Associativity
@item @code{++ --} @tab Postfix Increment/Decrement @tab Right to Left
@item @code{()} @tab Parentheses (function call)
@item @code{.}	@tab Method call
@item
@item @code{++ --} @tab Prefix Increment/Decrement @tab Right to Left
@item @code{+ -} @tab  Unary  Plus/Minus
@item @code{!} @tab Logical Not
@item
@item @code{^} @tab Power of Operator @tab Right to Left
@item
@item @code{* / %} @tab Multiply/Divide/Modulus @tab Left To Right
@item
@item @code{+ -} @tab Addition/Subtraction @tab Left To Right
@item
@item @code{>> <<} @tab Fortran style array clipping @tab Left to Right
@item
@item
@item @code{< <=} @tab Less than/Less than or equal to @tab Left to Right
@item @code{> >=} @tab Greater than/Greater than or equal to
@item
@item @code{== !=} @tab Equal to/Not equal to @tab Left to Right
@item 
@item @code{&&}	@tab Logical AND @tab Left to Right
@item
@item @code{||}	@tab Logical OR @tab Left to Right
@item
@item @code{?:} @tab Ternary Operator @tab Right to Left
@item
@item @code{=}	@tab Assignment	@tab Right to Left
@item @code{+= -=} @tab	Addition/subtraction assignment	
@item @code{*= /=} @tab	Multiplication/division assignment
@end multitable

@html
<a name="ncap_nmc"></a> <!-- http://nco.sf.net/nco.html#ncap_nmc -->
@end html
@node ID Quoting,  , Operator precedence and associativity , ncap2 netCDF Arithmetic Processor
@subsection ID Quoting
@cindex ID Quoting
In this section when I refer to a name I mean a variable name, attribute name or a dimension name
The allowed characters in a valid netCDF name vary from release to release. (See end section). If you want to use metacharacters in a name or use a method name as a variable name then the name has to be quoted wherever it occurs. 

@noindent The default @acronym{NCO} name is specified by the regular expressions:

@example
DGT:     ('0'..'9');
LPH:     ( 'a'..'z' | 'A'..'Z' | '_' );
name:    (LPH)(LPH|DGT)+
@end example

@noindent The first character of a valid name must be alphabetic or the underscore. Any subsequent characters must be alphanumeric or underscore. ( e.g., a1,_23, hell_is_666 )

@noindent The valid characters in a quoted name are specified by the regular expressions:
@example
LPHDGT:  ( 'a'..'z' | 'A'..'Z' | '_' | '0'..'9');
name:    (LPHDGT|'-'|'+'|'.'|'('|')'|':' )+  ;      
@end example

@noindent Quote a variable:@*
'avg' , '10_+10','set_miss' '+-90field' , '--test'=10.0d@* @* 
Quote a attribute: @*
'three@@10', 'set_mss@@+10', '666@@hell', 't1@@+units'="kelvin" @* @*
Quote a dimension: @*
'$10', '$t1--', '$--odd', c1['$10','$t1--']=23.0d @* 

@sp 1
The following comments are from the netCDF library definitions and
detail the naming conventions for each release. 
@noindent netcdf-3.5.1 @*
netcdf-3.6.0-p1 @*
netcdf-3.6.1 @*
netcdf-3.6.2 @*
@example
/*
 * ( [a-zA-Z]|[0-9]|'_'|'-'|'+'|'.'|'|':'|'@@'|'('|')' )+
 * Verify that name string is valid CDL syntax, i.e., all characters are
 * alphanumeric, '-', '_', '+', or '.'.
 * Also permit ':', '@@', '(', or ')' in names for chemists currently making 
 * use of these characters, but don't document until ncgen and ncdump can 
 * also handle these characters in names.
 */
@end example

@noindent netcdf-3.6.3@*
netcdf-4.0 Final  2008/08/28@*
@example
/*
 * Verify that a name string is valid syntax.  The allowed name
 * syntax (in RE form) is:
 *
 * ([a-zA-Z_]|@{UTF8@})([^\x00-\x1F\x7F/]|@{UTF8@})*
 *
 * where UTF8 represents a multibyte UTF-8 encoding.  Also, no
 * trailing spaces are permitted in names.  This definition
 * must be consistent with the one in ncgen.l.  We do not allow '/'
 * because HDF5 does not permit slashes in names as slash is used as a
 * group separator.  If UTF-8 is supported, then a multi-byte UTF-8
 * character can occur anywhere within an identifier.  We later
 * normalize UTF-8 strings to NFC to facilitate matching and queries.
 */ 
@end example
@c End HMB documentation

@page
@html
<a name="ncatted"></a> <!-- http://nco.sf.net/nco.html#ncatted -->
@end html
@node ncatted netCDF Attribute Editor, ncbo netCDF Binary Operator, ncap2 netCDF Arithmetic Processor, Operator Reference Manual
@section @command{ncatted} netCDF Attribute Editor
@cindex attributes
@cindex attribute names
@cindex editing attributes
@findex ncatted

@noindent
SYNTAX
@example
ncatted [-a @var{att_dsc}] [-a @dots{}] [-D @var{dbg}] [-h] [--hdr_pad @var{nbr}]
[-l @var{path}] [-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all]
@var{input-file} [[@var{output-file}]]
@end example
 
@noindent
DESCRIPTION

@cindex @command{ncattget}
@command{ncatted} edits attributes in a netCDF file.  
If you are editing attributes then you are spending too much time in the
world of metadata, and @command{ncatted} was written to get you back out as
quickly and painlessly as possible.
@command{ncatted} can @dfn{append}, @dfn{create}, @dfn{delete},
@dfn{modify}, and @dfn{overwrite} attributes (all explained below).  
@command{ncatted} allows each editing operation to be applied
to every variable in a file.
This saves time when changing attribute conventions throughout a file. 
@command{ncatted} is for @emph{writing} attributes.
To @emph{read} attribute values in plain text, use @command{ncks -m -M},
or define something like @command{ncattget} as a shell command
(@pxref{Filters for @command{ncks}}). 

@cindex @code{history}
@cindex @code{-h}
Because repeated use of @command{ncatted} can considerably increase the size
of the @code{history} global attribute (@pxref{History Attribute}), the
@samp{-h} switch is provided to override automatically appending the
command to the @code{history} global attribute in the @var{output-file}.

@cindex missing values
@cindex data, missing 
@cindex @code{_FillValue}
When @command{ncatted} is used to change the @code{_FillValue} attribute,
it changes the associated missing data self-consistently.
If the internal floating point representation of a missing value, 
e.g., 1.0e36, differs between two machines then netCDF files produced 
on those machines will have incompatible missing values.
This allows @command{ncatted} to change the missing values in files from 
different machines to a single value so that the files may then be 
concatenated, e.g., by @command{ncrcat}, without losing information.   
@xref{Missing Values}, for more information.

To master @command{ncatted} one must understand the meaning of the
structure that describes the attribute modification, @var{att_dsc} 
specified by the required option @samp{-a} or @samp{--attribute}. 
Each @var{att_dsc} contains five elements, which makes using
@command{ncatted} somewhat complicated, yet powerful.
The @var{att_dsc} fields are in the following order:@* 

@var{att_dsc} = @var{att_nm}, @var{var_nm}, @var{mode}, @var{att_type},
@var{att_val}@*

@table @var
@item att_nm
Attribute name. 
Example: @code{units}
@item var_nm
Variable name. 
Example: @code{pressure}, @code{'^H2O'}.
@cindex extended regular expressions
@cindex regular expressions
@cindex pattern matching
@cindex wildcards
Regular expressions (@pxref{Subsetting Files}) are accepted and will 
select any matching variable names.
The names @code{global} and @code{group} have special meaning.
@item mode
Edit mode abbreviation. 
Example: @code{a}. 
See below for complete listing of valid values of @var{mode}.
@item att_type
Attribute type abbreviation. 
Example: @code{c}. 
See below for complete listing of valid values of @var{att_type}.
@item att_val
Attribute value. 
Example: @code{pascal}. 
@end table
@noindent
There should be no empty space between these five consecutive
arguments. 
The description of these arguments follows in their order of
appearance. 

The value of @var{att_nm} is the name of the attribute you want to
edit. 
This meaning of this should be clear to all @command{ncatted} users.
Recall, as mentioned above, that @var{var_nm} may be specified as a
regular expression. 
If @var{att_nm} is omitted (i.e., left blank) and @dfn{Delete} mode is 
selected, then all attributes associated with the specified variable
will be deleted. 

@cindex global attributes
@cindex attributes, global
The value of @var{var_nm} is the name of the variable containing the
attribute (named @var{att_nm}) that you want to edit.
There are three very important and useful exceptions to this rule.
The value of @var{var_nm} can also be used to direct @command{ncatted}
to edit global attributes, or to repeat the editing operation for every 
group or variable in a file.
@w{A value} of @var{var_nm} of @code{global} indicates that @var{att_nm}
refers to a global (i.e., root-level) attribute, rather than to a
particular variable's attribute. 
This is the method @command{ncatted} supports for editing global
attributes.
@w{A value} of @var{var_nm} of @code{group} indicates that @var{att_nm}
refers to all groups, rather than to a particular variable's or group's
attribute.  
The operation will proceed to edit group metadata for every group.
Finally, if @var{var_nm} is left blank, then @command{ncatted} 
attempts to perform the editing operation on every variable in the file.
This option may be convenient to use if you decide to change the
conventions you use for describing the data.

@html
<a name="mode"></a> <!-- http://nco.sf.net/nco.html#mode -->
<a name="att_mode"></a> <!-- http://nco.sf.net/nco.html#att_mode -->
@end html
The value of @var{mode} is a single character abbreviation (@code{a},
@code{c}, @code{d}, @code{m}, or @code{o}) standing for one of
five editing modes:@*
@cindex attributes, appending
@cindex attributes, creating
@cindex attributes, deleting
@cindex attributes, modifying
@cindex attributes, editing
@cindex attributes, overwriting
@table @code
@item a 
@dfn{Append}.
Append value @var{att_val} to current @var{var_nm} attribute
@var{att_nm} value @var{att_val}, if any.  
If @var{var_nm} does not have an attribute @var{att_nm}, there is no
effect.
@item c
@dfn{Create}.
Create variable @var{var_nm} attribute @var{att_nm} with @var{att_val}
if @var{att_nm} does not yet exist.  
If @var{var_nm} already has an attribute @var{att_nm}, there is no
effect. 
@item d
@dfn{Delete}.
Delete current @var{var_nm} attribute @var{att_nm}.
If @var{var_nm} does not have an attribute @var{att_nm}, there is no
effect. 
If @var{att_nm} is omitted (left blank), then all attributes associated
with the specified variable are automatically deleted. 
When @dfn{Delete} mode is selected, the @var{att_type} and @var{att_val}
arguments are superfluous and may be left blank.
@item m
@dfn{Modify}.
Change value of current @var{var_nm} attribute @var{att_nm} to value
@var{att_val}. 
If @var{var_nm} does not have an attribute @var{att_nm}, there is no
effect. 
@item o
@dfn{Overwrite}.
Write attribute @var{att_nm} with value @var{att_val} to variable
@var{var_nm}, overwriting existing attribute @var{att_nm}, if any. 
This is the default mode.
@end table

@html
<a name="att_typ"></a> <!-- http://nco.sf.net/nco.html#att_typ -->
@end html
The value of @var{att_type} is a single character abbreviation 
(@code{f}, @code{d}, @code{l}, @code{i}, @code{s}, @code{c}, 
@code{b}, @code{u}) or a short string standing for one of the twelve
primitive netCDF data types:@*  
@table @code
@item f
@dfn{Float}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_FLOAT}. 
@item d
@dfn{Double}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_DOUBLE}.
@item i, l
@dfn{Integer} or @dfn{Long}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_INT}.
@item s
@dfn{Short}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_SHORT}.
@item c
@dfn{Char}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_CHAR}.
@item b
@dfn{Byte}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_BYTE}.
@item ub
@dfn{Unsigned Byte}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_UBYTE}.
@item us
@dfn{Unsigned Short}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_USHORT}.
@item u, ui, ul
@dfn{Unsigned Int}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_UINT}.
@item ll, int64
@dfn{Int64}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_INT64}.
@item ull, uint64
@dfn{Uint64}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_UINT64}.
@item sng, string
@dfn{String}.
Value(s) specified in @var{att_val} will be stored as netCDF intrinsic
type @code{NC_STRING}.
Note that @command{ncatted} handles type @code{NC_STRING} attributes
correctly beginning with version 4.3.3 released in July, 2013. 
Earlier versions fail when asked to handle @code{NC_STRING} attributes.  
@end table
@noindent
In @dfn{Delete} mode the specification of @var{att_type} is optional
(and is ignored if supplied).

The value of @var{att_val} is what you want to change attribute
@var{att_nm} to contain.
The specification of @var{att_val} is optional in @dfn{Delete} (and is
ignored) mode. 
Attribute values for all types besides @code{NC_CHAR} must have an
attribute length of at least one.
Thus @var{att_val} may be a single value or one-dimensional array of
elements of type @code{att_type}.
If the @var{att_val} is not set or is set to empty space,
and the @var{att_type} is @code{NC_CHAR}, e.g., @code{-a units,T,o,c,""}
or @code{-a units,T,o,c,}, then the corresponding attribute is set to 
have zero length.
When specifying an array of values, it is safest to enclose
@var{att_val} in single or double quotes, e.g., 
@code{-a levels,T,o,s,"1,2,3,4"} or   
@code{-a levels,T,o,s,'1,2,3,4'}.
The quotes are strictly unnecessary around @var{att_val} except 
when @var{att_val} contains characters which would confuse the calling
shell, such as spaces, commas, and wildcard characters. 

@cindex Perl
@cindex @acronym{ASCII}
@acronym{NCO} processing of @code{NC_CHAR} attributes is a bit like Perl in
that it attempts to do what you want by default (but this sometimes
causes unexpected results if you want unusual data storage).
@cindex @code{printf()}
@cindex @code{\n} (@acronym{ASCII} LF, linefeed)
@cindex characters, special
@cindex @code{\t} (@acronym{ASCII} HT, horizontal tab)
If the @var{att_type} is @code{NC_CHAR} then the argument is interpreted as a
string and it may contain C-language escape sequences, e.g., @code{\n},
which @acronym{NCO} will interpret before writing anything to disk.
@acronym{NCO} translates valid escape sequences and stores the
appropriate @acronym{ASCII} code instead.
Since two byte escape sequences, e.g., @code{\n}, represent one-byte
@acronym{ASCII} codes, e.g., @acronym{ASCII} 10 (decimal), the stored
string attribute is one byte shorter than the input string length for
each embedded escape sequence. 
The most frequently used C-language escape sequences are @code{\n} (for
linefeed) and @code{\t} (for horizontal tab).
These sequences in particular allow convenient editing of formatted text
attributes. 
@cindex @code{\a} (@acronym{ASCII} BEL, bell)
@cindex @code{\b} (@acronym{ASCII} BS, backspace)
@cindex @code{\f} (@acronym{ASCII} FF, formfeed)
@cindex @code{\r} (@acronym{ASCII} CR, carriage return)
@cindex @code{\v} (@acronym{ASCII} VT, vertical tab)
@cindex @code{\\} (@acronym{ASCII} \, backslash)
The other valid @acronym{ASCII} codes are @code{\a}, @code{\b}, @code{\f},
@code{\r}, @code{\v}, and @code{\\}. 
@xref{ncks netCDF Kitchen Sink}, for more examples of string formatting
(with the @command{ncks} @samp{-s} option) with special characters. 

@cindex @code{\'} (protected end quote)
@cindex @code{\"} (protected double quote)
@cindex @code{\?} (protected question mark)
@cindex @code{\\} (protected backslash)
@cindex @code{'} (end quote)
@cindex @code{"} (double quote)
@cindex @code{?} (question mark)
@cindex @code{\} (backslash)
@cindex special characters
@cindex @acronym{ASCII}
Analogous to @code{printf}, other special characters are also allowed by 
@command{ncatted} if they are "protected" by a backslash.
The characters @code{"}, @code{'}, @code{?}, and @code{\} may be 
input to the shell as @code{\"}, @code{\'}, @code{\?}, and @code{\\}.
@acronym{NCO} simply strips away the leading backslash from these
characters before editing the attribute.
No other characters require protection by a backslash.
Backslashes which precede any other character (e.g., @code{3}, @code{m},
@code{$}, @code{|}, @code{&}, @code{@@}, @code{%}, @code{@{}, and
@code{@}}) will not be filtered and will be included in the attribute.

@cindex strings
@cindex NUL-termination
@cindex NUL
@cindex C language
@cindex @code{0} (NUL)
Note that the NUL character @code{\0} which terminates @w{C language}
strings is assumed and need not be explicitly specified.
@comment If @code{\0} is input, it will not be translated (because it would
@comment terminate the string in an additional location).
@comment 20101007 Before today, \0 was not translated to NUL
@comment 20101007 As of today,  \0 is      translated to NUL
If @code{\0} is input, it is translated to the NUL character.
However, this will make the subsequent portion of the string, if any,
invisible to @w{C standard} library string functions. 
And that may cause unintended consequences.
Because of these context-sensitive rules, one must use @command{ncatted}
with care in order to store data, rather than text strings, in an 
attribute of type @code{NC_CHAR}.

Note that @command{ncatted} interprets character attributes
(i.e., attributes of type @code{NC_CHAR}) as strings.
@noindent
@html
<a name="xmp_ncatted"></a> <!-- http://nco.sf.net/nco.html#xmp_ncatted -->
@end html
EXAMPLES

Append the string "Data version 2.0.\n" to the global attribute
@code{history}: 
@example
ncatted -a history,global,a,c,"Data version 2.0\n" in.nc 
@end example
Note the use of embedded @w{C language} @code{printf()}-style escape 
sequences. 

Change the value of the @code{long_name} attribute for variable @code{T}
from whatever it currently is to "temperature":
@example
ncatted -a long_name,T,o,c,temperature in.nc
@end example

@html
<a name="NaN"></a> <!-- http://nco.sf.net/nco.html#NaN -->
@end html
@cindex NaN
@cindex IEEE NaN
@cindex Not-a-Number
@acronym{NCO} arithmetic operators will not work as expected on IEEE
NaN (short for Not-a-Number) and NaN-like numbers such as positive
infinity and negative infinity.  
One way to work-around this problem is to change IEEE NaNs to normal
missing values. 
As of @acronym{NCO} 4.1.0 (March, 2012), @command{ncatted} works with
NaNs.
First set the missing value (i.e., the value of the @code{_FillValue}
attribute) for the variable(s) in question to the IEEE NaN value. 
@example
ncatted -a _FillValue,,o,f,NaN in.nc
@end example
Then change the missing value from the IEEE NaN value to a normal IEEE
number, like 1.0e36 (or to whatever the original missing value was).
@example
ncatted -a _FillValue,,m,f,1.0e36 in.nc
@end example

Delete all existing @code{units} attributes:
@example
ncatted -a units,,d,, in.nc
@end example
@noindent
The value of @var{var_nm} was left blank in order to select all
variables in the file.
The values of @var{att_type} and @var{att_val} were left blank because
they are superfluous in @dfn{Delete} mode. 

@cindex @code{global} attribute
@cindex global attributes
@cindex attributes, global
Delete all attributes associated with the @code{tpt} variable, and
delete all global attributes
@example
ncatted -a ,tpt,d,, -a ,global,d,, in.nc
@end example
@noindent
The value of @var{att_nm} was left blank in order to select all
attributes associated with the variable.
To delete all global attributes, simply replace @code{tpt} with
@code{global} in the above.

@cindex @code{units}
Modify all existing @code{units} attributes to "meter second-1":
@example
ncatted -a units,,m,c,"meter second-1" in.nc
@end example

@cindex @code{units}
Add a @code{units} attribute of "kilogram kilogram-1" to all variables 
whose first three characters are @samp{H2O}:
@example
ncatted -a units,'^H2O',c,c,"kilogram kilogram-1" in.nc
@end example

Overwrite the @code{quanta} attribute of variable
@code{energy} to an array of four integers. 
@example
ncatted -O -a quanta,energy,o,s,"010,101,111,121" in.nc
@end example

@cindex extended regular expressions
@cindex regular expressions
@cindex pattern matching
@cindex wildcards
As of @acronym{NCO} 3.9.6 (January, 2009), @command{ncatted} accepts
@dfn{extended regular expressions} as arguments for variable names.
Create @code{isotope} attributes for all variables containing @samp{H2O} 
in their names.
@example
ncatted -O -a isotope,'^H2O*',c,s,"18" in.nc
@end example
See @ref{Subsetting Files} for more details.

@cindex groups
As of @acronym{NCO} 4.3.8 (November, 2013), @command{ncatted} 
accepts full and partial group paths in names of attributes,
variables, dimensions, and groups.
@c ncks -m -v lon ~/in_grp.nc
@example
# Overwrite units attribute of specific 'lon' variable
ncatted -O -a units,/g1/lon,o,c,"degrees_west" in_grp.nc
# Overwrite units attribute of all 'lon' variables
ncatted -O -a units,lon,o,c,"degrees_west" in_grp.nc
# Delete units attribute of all 'lon' variables
ncatted -O -a units,lon,d,, in_grp.nc
# Overwrite units attribute with new type for specific 'lon' variable
ncatted -O -a units,/g1/lon,o,sng,"degrees_west" in_grp.nc
# Add new_att attribute to all variables
ncatted -O -a new_att,,c,sng,"new variable attribute" in_grp.nc
# Add new_grp_att group attribute to all groups
ncatted -O -a new_grp_att,group,c,sng,"new group attribute" in_grp.nc
# Add new_grp_att group attribute to single group
ncatted -O -a g1_grp_att,g1,c,sng,"new group attribute" in_grp.nc
# Add new_glb_att global attribute to root group
ncatted -O -a new_glb_att,global,c,sng,"new global attribute" in_grp.nc
@end example

Demonstrate input of C-language escape sequences (e.g., @code{\n}) and
other special characters (e.g., @code{\"}) 
@example
ncatted -h -a special,global,o,c,
'\nDouble quote: \"\nTwo consecutive double quotes: \"\"\n
Single quote: Beyond my shell abilities!\nBackslash: \\\n
Two consecutive backslashes: \\\\\nQuestion mark: \?\n' in.nc
@end example
Note that the entire attribute is protected from the shell by single
quotes. 
These outer single quotes are necessary for interactive use, but may be
omitted in batch scripts.

@page
@html
<a name="ncbo"></a> <!-- http://nco.sf.net/nco.html#ncbo -->
<a name="ncdiff"></a> <!-- http://nco.sf.net/nco.html#ncdiff -->
<a name="ncadd"></a> <!-- http://nco.sf.net/nco.html#ncadd -->
<a name="ncsub"></a> <!-- http://nco.sf.net/nco.html#ncsub -->
<a name="ncsubtract"></a> <!-- http://nco.sf.net/nco.html#ncsubtract -->
<a name="ncmult"></a> <!-- http://nco.sf.net/nco.html#ncmult -->
<a name="ncmultiply"></a> <!-- http://nco.sf.net/nco.html#ncmultiply -->
<a name="ncdivide"></a> <!-- http://nco.sf.net/nco.html#ncdivide -->
@end html
@node ncbo netCDF Binary Operator, nces netCDF Ensemble Statistics, ncatted netCDF Attribute Editor, Operator Reference Manual
@section @command{ncbo} netCDF Binary Operator
@findex ncbo
@findex ncdiff
@findex ncadd
@findex ncsub
@findex ncsubtract
@findex ncmult
@findex ncmultiply
@findex ncdivide
@cindex binary operations
@cindex addition
@cindex subtraction
@cindex multiplication
@cindex adding data
@cindex subtracting data
@cindex multiplying data
@cindex dividing data

@noindent
SYNTAX
@example 
ncbo [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]] [-F] 
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdr_pad @var{nbr}]
[-L @var{dfl_lvl}] [-l @var{path}] [--no_tmp_fl]
[-O] [-o @var{file_3}] [-p @var{path}] [-R] [-r] [--ram_all]
[-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] [-y @var{op_typ}]
@var{file_1} @var{file_2} [@var{file_3}]
@end example

@noindent
DESCRIPTION

@command{ncbo} performs binary operations on variables in @var{file_1}
and the corresponding variables (those with the same name) in
@var{file_2} and stores the results in @var{file_3}. 
The binary operation operates on the entire files (modulo any excluded
variables). 
@xref{Missing Values}, for treatment of missing values.
One of the four standard arithmetic binary operations currently
supported must be selected with the @samp{-y @var{op_typ}} switch (or
long options @samp{--op_typ} or @samp{--operation}).
@cindex @code{add}
@cindex @code{subtract}
@cindex @code{multiply}
@cindex @code{divide}
@cindex @code{+}
@cindex @code{-}
@cindex @code{*}
@cindex @code{/}
@cindex @code{-y @var{op_typ}}
@cindex @code{--operation @var{op_typ}}
@cindex @code{--op_typ @var{op_typ}}
@cindex alternate invocations
The valid binary operations for @command{ncbo}, their definitions, 
corresponding values of the @var{op_typ} key, and alternate invocations
are:  
@table @dfn
@item Addition
@c Internal operation code: @{nco_op_add}@*
Definition: @var{file_3} = @var{file_1} + @var{file_2}@*
Alternate invocation: @command{ncadd}@*
@var{op_typ} key values: @samp{add}, @samp{+}, @samp{addition}@*
Examples: @samp{ncbo --op_typ=add 1.nc 2.nc 3.nc}, @samp{ncadd 1.nc 2.nc 3.nc}@*
@item Subtraction
Definition: @var{file_3} = @var{file_1} - @var{file_2}@*
Alternate invocations: @command{ncdiff}, @command{ncsub}, @command{ncsubtract}@*
@var{op_typ} key values: @samp{sbt}, @samp{-}, @samp{dff}, @samp{diff}, @samp{sub}, @samp{subtract}, @samp{subtraction}@*
Examples: @samp{ncbo --op_typ=- 1.nc 2.nc 3.nc}, @samp{ncdiff 1.nc 2.nc 3.nc}@*
@item Multiplication
Definition: @var{file_3} = @var{file_1} * @var{file_2}@* 
Alternate invocations: @command{ncmult}, @command{ncmultiply}@* 
@var{op_typ} key values: @samp{mlt}, @samp{*}, @samp{mult}, @samp{multiply}, @samp{multiplication}@*
Examples: @samp{ncbo --op_typ=mlt 1.nc 2.nc 3.nc}, @samp{ncmult 1.nc 2.nc 3.nc}@*
@item Division
Definition: @var{file_3} = @var{file_1} / @var{file_2}@* 
Alternate invocation: @command{ncdivide}@*
@var{op_typ} key values: @samp{dvd}, @samp{/}, @samp{divide}, @samp{division}@*
Examples: @samp{ncbo --op_typ=/ 1.nc 2.nc 3.nc}, @samp{ncdivide 1.nc 2.nc 3.nc}@*
@end table
@noindent
Care should be taken when using the shortest form of key values,
i.e., @samp{+}, @samp{-}, @samp{*}, @w{and @samp{/}}.
Some of these single characters may have special meanings to the shell
@cindex naked characters
@footnote{@w{A naked} (i.e., unprotected or unquoted) @samp{*} is a
wildcard character.  
@w{A naked} @samp{-} may confuse the command line parser.
@w{A naked} @samp{+} and @samp{/} are relatively harmless.}.
@cindex Bash shell
Place these characters inside quotes to keep them from being interpreted 
(globbed) by the shell
@footnote{The widely used shell Bash correctly interprets all these
special characters even when they are not quoted. 
That is, Bash does not prevent @acronym{NCO} from correctly interpreting 
the intended arithmetic operation when the following arguments are given
(without quotes) to @command{ncbo}:
@samp{--op_typ=+}, @samp{--op_typ=-}, @samp{--op_typ=*},
and @samp{--op_typ=/}}. 
@cindex globbing
@cindex shell
@cindex quotes
For example, the following commands are equivalent
@example
ncbo --op_typ=* 1.nc 2.nc 3.nc # Dangerous (shell may try to glob)
ncbo --op_typ='*' 1.nc 2.nc 3.nc # Safe ('*' protected from shell)
ncbo --op_typ="*" 1.nc 2.nc 3.nc # Safe ('*' protected from shell)
ncbo --op_typ=mlt 1.nc 2.nc 3.nc
ncbo --op_typ=mult 1.nc 2.nc 3.nc
ncbo --op_typ=multiply 1.nc 2.nc 3.nc
ncbo --op_typ=multiplication 1.nc 2.nc 3.nc
ncmult 1.nc 2.nc 3.nc # First do 'ln -s ncbo ncmult'
ncmultiply 1.nc 2.nc 3.nc # First do 'ln -s ncbo ncmultiply'
@end example
No particular argument or invocation form is preferred.
Users are encouraged to use the forms which are most intuitive to them.

@cindex @command{alias}
@cindex @command{ln -s}
@cindex symbolic links
Normally, @command{ncbo} will fail unless an operation type is specified
with @samp{-y} (equivalent to @samp{--op_typ}).
You may create exceptions to this rule to suit your particular tastes,
in conformance with your site's policy on @dfn{symbolic links} to
executables (files of a different name point to the actual executable).
For many years, @command{ncdiff} was the main binary file operator.
As a result, many users prefer to continue invoking @command{ncdiff}
rather than memorizing a new command (@samp{ncbo -y @var{sbt}}) which
behaves identically to the original @command{ncdiff} command.
However, from a software maintenance standpoint, maintaining a distinct 
executable for each binary operation (e.g., @command{ncadd}) is untenable,
and a single executable, @command{ncbo}, is desirable.
To maintain backward compatibility, therefore, @acronym{NCO}
automatically creates a symbolic link from @command{ncbo} to
@command{ncdiff}.  
Thus @command{ncdiff} is called an @dfn{alternate invocation} of
@command{ncbo}. 
@command{ncbo} supports many additional alternate invocations which must
be manually activated.
Should users or system adminitrators decide to activate them, the
procedure is simple. 
For example, to use @samp{ncadd} instead of @samp{ncbo --op_typ=add}, 
simply create a symbolic link from @command{ncbo} to @command{ncadd}
@footnote{The command to do this is @samp{ln -s -f ncbo ncadd}}.
The alternatate invocations supported for each operation type are listed
above. 
Alternatively, users may always define @samp{ncadd} as an @dfn{alias} to 
@samp{ncbo --op_typ=add}
@footnote{The command to do this is @samp{alias ncadd='ncbo --op_typ=add'}}.

It is important to maintain portability in @acronym{NCO} scripts.
Therefore we recommend that site-specfic invocations (e.g.,
@samp{ncadd}) be used only in interactive sessions from the
command-line.
For scripts, we recommend using the full invocation (e.g., 
@samp{ncbo --op_typ=add}).
This ensures portability of scripts between users and sites.

@html
<a name="brd_var"></a> <!-- http://nco.sf.net/nco.html#brd_var -->
@end html
@cindex broadcasting variables
@cindex rank
@command{ncbo} operates (e.g., adds) variables in @var{file_2} with the
corresponding variables (those with the same name) in @var{file_1} and
stores the results in @var{file_3}. 
@cindex broadcasting variables
Variables in @var{file_1} or @var{file_2} are @dfn{broadcast} to conform
to the corresponding variable in the other input file if
necessary@footnote{
Prior to @acronym{NCO} version 4.3.1 (May, 2013), @command{ncbo}
would only broadcast variables in @var{file_2} to conform to
@var{file_1}. 
Variables in @var{file_1} were @emph{never} broadcast to conform to the 
dimensions in @var{file_2}.}. 
Now @command{ncbo} is completely symmetric with respect to @var{file_1}
and @var{file_2}, i.e., 
@set flg
@tex
$\rm{file}_1 - \rm{file}_2 = -(\rm{file}_2-\rm{file}_1)$.
@clear flg
@end tex
@ifinfo
@math{@var{file_1} - @var{file_2} = - (@var{file_2} - @var{file_1}}.
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
@var{file_1} - @var{file_2} = -(@var{file_2} - @var{file_1}.
@clear flg
@end ifset

Broadcasting a variable means creating data in non-existing dimensions
by copying data in existing dimensions.
For example, a two dimensional variable in @var{file_2} can be
subtracted from a four, three, or two (not one or zero)
dimensional variable (of the same name) in @code{file_1}. 
@cindex anomalies
This functionality allows the user to compute anomalies from the mean.
In the future, we will broadcast variables in @var{file_1}, if necessary
to conform to their counterparts in @var{file_2}.
@c TODO #268
@cindex rank
Thus, presently, the number of dimensions, or @dfn{rank}, of any
processed variable in @var{file_1} must be greater than or equal to the
rank of the same variable in @var{file_2}. 
Of course, the size of all dimensions common to both @var{file_1} and
@var{file_2} must be equal. 

When computing anomalies from the mean it is often the case that
@var{file_2} was created by applying an averaging operator to a file
with initially the same dimensions as @var{file_1} (often @var{file_1}
itself).  
In these cases, creating @var{file_2} with @command{ncra} rather than
@command{ncwa} will cause the @command{ncbo} operation to fail.
For concreteness say the record dimension in @code{file_1} is
@code{time}.  
If @var{file_2} were created by averaging @var{file_1} over the
@code{time} dimension with the @command{ncra} operator rather than with
the @command{ncwa} operator, then @var{file_2} will have a @code{time}
dimension of @w{size 1} rather than having no @code{time} dimension at
all 
@cindex degenerate dimension
@cindex @samp{-b}
@footnote{This is because @command{ncra} collapses the record dimension
to a size @w{of 1} (making it a @dfn{degenerate} dimension), but does
not remove it, while, unless @samp{-b} is given, @command{ncwa} removes
all averaged dimensions.
In other words, by default @command{ncra} changes variable size though
not rank, while, @command{ncwa} changes both variable size and rank.}.   
In this case the input files to @command{ncbo}, @var{file_1} and
@var{file_2}, will have unequally sized @code{time} dimensions which
causes @command{ncbo} to fail.
To prevent this from occuring, use @command{ncwa} to remove the
@code{time} dimension from @var{file_2}.
See the example below.

@cindex coordinate variable 
@cindex @code{NC_CHAR}
@command{ncbo} never operates on coordinate variables or variables
of type @code{NC_CHAR} or @code{NC_STRING}. 
This ensures that coordinates like (e.g., latitude and longitude) are 
physically meaningful in the output file, @var{file_3}. 
This behavior is hardcoded.
@cindex @acronym{CF} conventions
@command{ncbo} applies special rules to some 
@acronym{CF}-defined (and/or @acronym{NCAR CCSM} or @acronym{NCAR CCM} 
fields) such as @code{ORO}.
See @ref{CF Conventions} for a complete description.
Finally, we note that @command{ncflint} (@pxref{ncflint netCDF File
Interpolator}) is designed for file interpolation.
As such, it also performs file subtraction, addition, multiplication,
albeit in a more convoluted way than @command{ncbo}.

@html
<a name="brd_grp"></a> <!-- http://nco.sf.net/nco.html#brd_grp -->
<a name="gb"></a> <!-- http://nco.sf.net/nco.html#gb -->
<a name="GB"></a> <!-- http://nco.sf.net/nco.html#GB -->
@end html
@cindex broadcasting groups
Beginning with @acronym{NCO} version 4.3.1 (May, 2013), @command{ncbo} 
supports @dfn{group broadcasting}.
Group broadcasting means processing data based on group patterns in the
input file(s) and automatically transferring or transforming groups to
the output file. 
Consider the case where @var{file_1} contains multiple groups each with
the variable @var{v1}, while @var{file_2} contains @var{v1} only in its 
top-level (i.e., root) group.
Then @command{ncbo} will replicate the group structure of @var{file_1}
in the output file, @var{file_3}.
Each group in @var{file_3} contains the output of the corresponding
group in @var{file_1} operating on the data in the single group in
@var{file_2}. 
An example is provided below.

@noindent
@html
<a name="xmp_ncbo"></a> <!-- http://nco.sf.net/nco.html#xmp_ncbo -->
<a name="xmp_ncdiff"></a> <!-- http://nco.sf.net/nco.html#xmp_ncdiff -->
@end html
EXAMPLES

Say files @file{85_0112.nc} and @file{86_0112.nc} each contain 12 months
of data.
Compute the change in the monthly averages from 1985 to 1986:
@example
ncbo   86_0112.nc 85_0112.nc 86m85_0112.nc
ncdiff 86_0112.nc 85_0112.nc 86m85_0112.nc
ncbo --op_typ=sub 86_0112.nc 85_0112.nc 86m85_0112.nc
ncbo --op_typ='-' 86_0112.nc 85_0112.nc 86m85_0112.nc
@end example
@noindent
These commands are all different ways of expressing the same thing.

@cindex broadcasting
@cindex rank
The following examples demonstrate the broadcasting feature of
@command{ncbo}.  
Say we wish to compute the monthly anomalies of @code{T} from the yearly
average of @code{T} for the year 1985.
First we create the 1985 average from the monthly data, which is stored
with the record dimension @code{time}.
@example
ncra 85_0112.nc 85.nc
ncwa -O -a time 85.nc 85.nc
@end example
@noindent
The second command, @command{ncwa}, gets rid of the @code{time} dimension
of @w{size 1} that @command{ncra} left in @file{85.nc}. 
Now none of the variables in @file{85.nc} has a @code{time} dimension.
@w{A quicker} way to accomplish this is to use @command{ncwa} from the
beginning:  
@example
ncwa -a time 85_0112.nc 85.nc
@end example
@noindent
We are now ready to use @command{ncbo} to compute the anomalies for 1985:
@example
ncdiff -v T 85_0112.nc 85.nc t_anm_85_0112.nc
@end example
@noindent
Each of the 12 records in @file{t_anm_85_0112.nc} now contains the
monthly deviation of @code{T} from the annual mean of @code{T} for each 
gridpoint. 

Say we wish to compute the monthly gridpoint anomalies from the zonal
annual mean. 
@w{A @dfn{zonal mean}} is a quantity that has been averaged over the
longitudinal (or @var{x}) direction.
First we use @command{ncwa} to average over longitudinal direction
@code{lon}, creating @file{85_x.nc}, the zonal mean of @file{85.nc}. 
Then we use @command{ncbo} to subtract the zonal annual means from the
monthly gridpoint data:
@example
ncwa -a lon 85.nc 85_x.nc
ncdiff 85_0112.nc 85_x.nc tx_anm_85_0112.nc
@end example
@noindent
This examples works assuming @file{85_0112.nc} has dimensions
@code{time} and @code{lon}, and that @file{85_x.nc} has no @code{time}
or @code{lon} dimension.

@cindex broadcasting groups
Group broadcasting simplifies evaluation of multiple models against
observations.
Consider the input file @file{cmip5.nc} which contains multiple
top-level groups @code{cesm}, @code{ecmwf}, and @code{giss}, each of
which contains the surface air temperature field @code{tas}.
We wish to compare these models to observations stored in @file{obs.nc} 
which contains @code{tas} only in its top-level (i.e., root) group.
It is often the case that many models and/or model simulations exist,
whereas only one observational dataset does.
We evaluate the models and obtain the bias (difference) between models
and observations by subtracting @file{obs.nc} from @file{cmip5.nc}.
Then @command{ncbo} ``broadcasts'' (i.e., replicates) the observational
data to match the group structure of @file{cmip5.nc}, subtracts,
and then stores the results in the output file, @file{bias.nc}
which has the same group structure as @file{cmip5.nc}.
@example
% ncbo -O cmip5.nc obs.nc bias.nc
% ncks -H -v tas -d time,3 bias.nc
/cesm/tas
time[3] tas[3]=-1 
/ecmwf/tas
time[3] tas[3]=0 
/giss/tas
time[3] tas[3]=1 
@end example
@noindent

@html
<a name="csn_anm"></a> <!-- http://nco.sf.net/nco.html#csn_anm -->
@end html
As a final example, say we have five years of monthly data (i.e., 
@w{60 months}) stored in @file{8501_8912.nc} and we wish to create a
file which contains the twelve month seasonal cycle of the average
monthly anomaly from the five-year mean of this data. 
The following method is just one permutation of many which will
accomplish the same result.
First use @command{ncwa} to create the five-year mean: 
@example
ncwa -a time 8501_8912.nc 8589.nc
@end example
@noindent
Next use @command{ncbo} to create a file containing the difference of
each month's data from the five-year mean:
@example
ncbo 8501_8912.nc 8589.nc t_anm_8501_8912.nc
@end example
@noindent
Now use @command{ncks} to group together the five January anomalies in
one file, and use @command{ncra} to create the average anomaly for all
five Januarys. 
These commands are embedded in a shell loop so they are repeated for all
twelve months:
@cindex Bash Shell
@cindex Bourne Shell
@cindex C Shell
@example
for idx in @{1..12@}; do # Bash Shell (version 3.0+) 
  idx=`printf "%02d" $@{idx@}` # Zero-pad to preserve order
  ncks -F -d time,$@{idx@},,12 t_anm_8501_8912.nc foo.$@{idx@}
  ncra foo.$@{idx@} t_anm_8589_$@{idx@}.nc
done
for idx in 01 02 03 04 05 06 07 08 09 10 11 12; do # Bourne Shell
  ncks -F -d time,$@{idx@},,12 t_anm_8501_8912.nc foo.$@{idx@}
  ncra foo.$@{idx@} t_anm_8589_$@{idx@}.nc
done
foreach idx (01 02 03 04 05 06 07 08 09 10 11 12) # C Shell
  ncks -F -d time,$@{idx@},,12 t_anm_8501_8912.nc foo.$@{idx@}
  ncra foo.$@{idx@} t_anm_8589_$@{idx@}.nc
end
@end example
@noindent
Note that @command{ncra} understands the @code{stride} argument so the
two commands inside the loop may be combined into the single command 
@example
ncra -F -d time,$@{idx@},,12 t_anm_8501_8912.nc foo.$@{idx@}
@end example
@noindent
Finally, use @command{ncrcat} to concatenate the @w{12 average} monthly  
anomaly files into one twelve-record file which contains the entire
seasonal cycle of the monthly anomalies:
@example
ncrcat t_anm_8589_??.nc t_anm_8589_0112.nc
@end example
@noindent

@page
@html
<a name="nces"></a> <!-- http://nco.sf.net/nco.html#nces -->
<a name="ncea"></a> <!-- http://nco.sf.net/nco.html#ncea -->
@end html
@node nces netCDF Ensemble Statistics, ncecat netCDF Ensemble Concatenator, ncbo netCDF Binary Operator, Operator Reference Manual
@section @command{nces} netCDF Ensemble Statistics
@cindex averaging data
@cindex ensemble average
@findex nces

@noindent
SYNTAX
@example
nces [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]] [-F]
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdf] [--hdr_pad @var{nbr}] 
[-L @var{dfl_lvl}] [-l @var{path}] [-n @var{loop}] [--no_tmp_fl] [--nsm_fl|grp] [--nsm_sfx sfx]
[-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all] [--rth_dbl|flt]
[-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] [-y @var{op_typ}]
[@var{input-files}] [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{nces} performs gridpoint statistics on variables across an
arbitrary number (an @dfn{ensemble}) of @var{input-files} and/or of
input groups within each file.
Each file (or group) receives an equal weight.
@command{nces} was formerly (until @acronym{NCO} version 4.3.9,
released December, 2013) known as @command{ncea} (netCDF Ensemble
Averager)@footnote{
The old ncea command was deprecated in @acronym{NCO} version 4.3.9,  
released December, 2013.
@acronym{NCO} will attempt to maintain back-compatibility and work
as expected with invocations of @command{ncea} for as long as possible.
Please replace @command{ncea} by @command{nces} in all future work.}.
@cindex ensemble
For example, @command{nces} will average a set of files or groups,
weighting each file or group evenly. 
This is distinct from @command{ncra}, which performs statistics only
over the record dimension(s) (e.g., @var{time}), and weights each record 
in each record dimension evenly.

The file or group is the logical unit of organization for the results of
many scientific studies.
Often one wishes to generate a file or group which is the statistical
product (e.g., average) of many separate files or groups. 
This may be to reduce statistical noise by combining the results of a
large number of experiments, or it may simply be a step in a procedure 
whose goal is to compute anomalies from a mean state. 
In any case, when one desires to generate a file whose statistical
properties are equally influenced by all the inputs, then @command{nces}
is the operator to use. 

Variables in the @var{output-file} are the same size as the variable
hyperslab in each input file or group, and each input file or group
must be the same size after hyperslabbing
@footnote{As of @acronym{NCO} version 4.4.2 (released February, 2014)
@command{nces} allows hyperslabs in all dimensions so long as the
hyperslabs resolve to the same size. 
The fixed (i.e., non-record) dimensions should be the same size in
all ensemble members both before and after hyperslabbing, although
the hypserslabs may (and usually do) change the size of the dimensions
from the input to the output files.
Prior to this, @command{nces} was only guaranteed to work on hyperslabs
in the record dimension that resolved to the same size.}
@cindex record dimension
@cindex hyperslab
@command{nces} does allow files to differ in the record dimension size
if the requested record hyperslab (@pxref{Hyperslabs}) resolves to the
same size for all files.  
@command{nces} recomputes the record dimension hyperslab limits for
each input file so that coordinate limits may be used to select equal
length timeseries from unequal length files.
@cindex @acronym{IPCC}
@cindex @acronym{AR4}
@cindex @acronym{CMIP}
This simplifies analysis of unequal length timeseries from simulation
ensembles (e.g., the @acronym{CMIP3} @acronym{IPCC} @acronym{AR4}
archive).   

@html
<a name="nsm_fl"></a> <!-- http://nco.sf.net/nco.html#nsm_fl -->
<a name="nsm_grp"></a> <!-- http://nco.sf.net/nco.html#nsm_grp -->
<a name="nsm_sfx"></a> <!-- http://nco.sf.net/nco.html#nsm_sfx -->
@end html
@cindex @code{--nsm_fl}
@cindex @code{--nsm_grp}
@cindex @code{--ensemble_file}
@cindex @code{--ensemble_group}
@cindex @code{--nsm_sfx}
@cindex @code{--ensemble_suffix}
@command{nces} works in one of two modes, file ensembles 
or group ensembles.
File ensembles are the default (equivalent to the old @command{ncea}) 
and may also be explicitly specified by the @samp{--nsm_fl} or
@samp{--ensemble_file} switches.
To perform statistics on ensembles of groups, a newer feature, use
@samp{--nsm_grp} or @samp{--ensemble_group}.
Members of a group ensemble are groups that share the same structure,
parent group, and nesting level. 
Members must be @dfn{leaf groups}, i.e., not contain any sub-groups.
Their contents usually have different values because they are
realizations of replicated experiments.  
In group ensemble mode @command{nces} computes the statistics across 
the ensemble, which may span multiple input files. 
Files may contain members of multiple, distinct ensembles. 
However, all ensembles must have at least one member in the first input 
file. 
Group ensembles behave as an unlimited dimension of datasets: 
they may contain an arbitrary and extensible number of realizations in
each file, and may be composed from multiple files. 

Output statistics in group ensemble mode are stored in the parent group
by default. 
If the ensemble members are @file{/cesm/cesm_01} and
@file{/cesm/cesm_02}, then the computed statistic will be in
@file{/cesm} in the output file.  
The @samp{--nsm_sfx} option instructs nces to instead store output in  
a new child group of the parent created by attaching the suffix
to the parent group's name, e.g., @samp{--nsm_sfx='_avg'} would store
results in the output group @file{/cesm/cesm_avg}:
@example
nces --nsm_grp                  mdl1.nc mdl2.nc mdl3.nc out.nc
nces --nsm_grp --nsm_sfx='_avg' mdl1.nc mdl2.nc mdl3.nc out.nc
@end example

@xref{Statistics vs. Concatenation}, for a description of the
distinctions between the statistics tools and concatenators. 
@cindex multi-file operators
@cindex standard input
@cindex @code{stdin}
As a multi-file operator, @command{nces} will read the list of
@var{input-files} from @code{stdin} if they are not specified 
as positional arguments on the command line 
(@pxref{Large Numbers of Files}).

Like @command{ncra} and @command{ncwa}, @command{nces} treats coordinate
variables as a special case.
Coordinate variables are assumed to be the same in all ensemble members,
so @command{nces} simply copies the coordinate variables that appear in 
ensemble members directly to the output file.
This has the same effect as averaging the coordinate variable across the
ensemble, yet does not incur the time- or precision- penalties of
actually averaging them.
@command{ncra} and @command{ncwa} allow coordinate variables to be
processed only by the linear average operation, regardless of the
arithmetic operation type performed on the non-coordinate variables
(@pxref{Operation Types}). 
Thus it can be said that the three operators (@command{ncra},
@command{ncwa}, and @command{nces}) all average coordinate variables
(even though @command{nces} simply copies them).
All other requested arithmetic operations (e.g., maximization,
square-root, RMS) are applied only to non-coordinate variables.
In these cases the linear average of the coordinate variable will be
returned.

@noindent
@html
<a name="xmp_ncea"></a> <!-- http://nco.sf.net/nco.html#xmp_ncea -->
<a name="xmp_nces"></a> <!-- http://nco.sf.net/nco.html#xmp_nces -->
@end html
EXAMPLES

Consider a model experiment which generated five realizations of one
year of data, say 1985.
Imagine that the experimenter slightly perturbs the initial conditions
of the problem before generating each new solution.   
Assume each file contains all twelve months (a seasonal cycle) of data
and we want to produce a single file containing the ensemble average
(mean) seasonal cycle.  
Here the numeric filename suffix denotes the realization number
(@emph{not} the month):
@example
nces 85_01.nc 85_02.nc 85_03.nc 85_04.nc 85_05.nc 85.nc
nces 85_0[1-5].nc 85.nc
nces -n 5,2,1 85_01.nc 85.nc
@end example
@noindent
These three commands produce identical answers.
@xref{Specifying Input Files}, for an explanation of the distinctions
between these methods.
The output file, @file{85.nc}, is the same size as the inputs files.
It contains 12 months of data (which might or might not be stored in the 
record dimension, depending on the input files), but each value in the
output file is the average of the five values in the input files.

In the previous example, the user could have obtained the ensemble
average values in a particular spatio-temporal region by adding a 
hyperslab argument to the command, e.g.,
@example
nces -d time,0,2 -d lat,-23.5,23.5 85_??.nc 85.nc
@end example
@noindent
In this case the output file would contain only three slices of data in
the @var{time} dimension. 
These three slices are the average of the first three slices from the
input files.
Additionally, only data inside the tropics is included.

As of @acronym{NCO} version 4.3.9 (released December, 2013)
@command{nces} also works with groups (rather than files) as the
fundamental unit of the ensemble.
Consider two ensembles, @code{/ecmwf} and @code{/cesm} stored across
three input files @file{mdl1.nc}, @file{mdl2.nc}, and @file{mdl3.nc}.
Ensemble members would be leaf groups with names like @code{/ecmwf/01},
@code{/ecmwf/02} etc. and @code{/cesm/01}, @code{/cesm/02}, etc.
These commands average both ensembles: 
@example
nces --nsm_grp mdl1.nc mdl2.nc mdl3.nc out.nc
nces --nsm_grp --nsm_sfx='_min' --op_typ=min -n 3,1,1 mdl1.nc out.nc
nces --nsm_grp -g cesm -v tas -d time,0,3 -n 3,1,1 mdl1.nc out.nc
@end example
The first command stores averages in the output groups @file{/cesm} and 
@file{/ecmwf}, while the second stores minima in the output groups
@file{/cesm/cesm_min} and @file{/ecmwf/ecmwf_min}:
The third command demonstrates that sub-setting and hyperslabbing work
as expected.
Note that each input file may contain different numbers of members
of each ensemble, as long as all distinct ensembles contain at least one
member in the first file.

@page
@html
<a name="ncecat"></a> <!-- http://nco.sf.net/nco.html#ncecat -->
@end html
@node ncecat netCDF Ensemble Concatenator, ncflint netCDF File Interpolator, nces netCDF Ensemble Statistics, Operator Reference Manual
@section @command{ncecat} netCDF Ensemble Concatenator
@cindex concatenation
@cindex ensemble concatenation
@findex ncecat

@noindent
SYNTAX
@example
ncecat [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]] [-F]
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [--gag] [-h] [--hdf] [--hdr_pad @var{nbr}]
[-L @var{dfl_lvl}] [-l @var{path}] [-M] [--md5_digest] [--mrd] [-n @var{loop}] [--no_tmp_fl] 
[-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all] 
[-t @var{thr_nbr}] [-u @var{ulm_nm}] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] 
[@var{input-files}] [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{ncecat} aggregates an arbitrary number of input files into a 
single output file using using one of two methods.
@dfn{Record AGgregation} (@acronym{RAG}), the traditional method employed on
netCDF3 files and still the default method, stores @var{input-files} as
consecutive records in the @var{output-file}.
@dfn{Group AGgregation} (@acronym{GAG}) stores @var{input-files} as top-level
groups in the netCDF4 @var{output-file}.
Record Aggregation (@acronym{RAG}) makes numerous assumptions about the structure
of input files and Group Aggregation (@acronym{GAG}) makes none.
Both methods are described in detail below.
Since @command{ncecat} aggregates all the contents of the input files,
it can easily produce large output files so it is often helpful to invoke
subsetting simultaneously (@pxref{Subsetting Files}).

@html
<a name="rag"></a> <!-- http://nco.sf.net/nco.html#rag -->
@end html
@cindex record aggregation
@cindex @acronym{RAG}
@acronym{RAG} makes each variable (except coordinate variables) in each
input file into a single record of the same variable in the output file.  
Coordinate variables are not concatenated, they are instead simply
copied from the first input file to the @var{output-file}.
All @var{input-files} must contain all extracted variables (or else
there would be "gaps" in the output file).

A new record dimension is the glue which binds together the input file
data.
The new record dimension is defined in the root group of the output file
so it is visible to all sub-groups.
Its name is, by default, ``record''.
@cindex unlimited dimension
@cindex record dimension
@cindex @samp{-u @var{ulm_nm}}
@cindex @samp{--ulm_nm @var{ulm_nm}}
@cindex @samp{--rcd_nm @var{ulm_nm}}
This default name can be overridden with the @samp{-u @var{ulm_nm}}
short option (or the @samp{--ulm_nm} or @samp{rcd_nm} long options).

Each extracted variable must be constant in size and rank across all
@var{input-files}. 
@cindex record dimension
@cindex hyperslab
The only exception is that @command{ncecat} allows files to differ in
the record dimension size if the requested record hyperslab
(@pxref{Hyperslabs}) resolves to the same size for all files. 
@cindex @acronym{CMIP}
This allows easier gluing/averaging of unequal length timeseries from 
simulation ensembles (e.g., the @acronym{CMIP} rchive). 

@cindex fixed dimension
@cindex fix record dimension
Classic (i.e., all netCDF3 and @code{NETCDF4_CLASSIC}) output files
can contain only one record dimension.
@command{ncecat} makes room for the new glue record dimension by
changing the pre-existing record dimension, if any, in the input files
into a fixed dimension in the output file. 
netCDF4 output files may contain any number of record dimensions, so
@command{ncecat} need not and does not alter the record dimensions,
if any, of the input files as it copies them to the output file. 

@html
<a name="gag"></a> <!-- http://nco.sf.net/nco.html#gag -->
@end html
@cindex group aggregation
@cindex @acronym{GAG}
@dfn{Group AGgregation} (@acronym{GAG}) stores @var{input-files} as
top-level groups in the @var{output-file}.
No assumption is made about the size or shape or type of a given 
object (variable or dimension or group) in the input file.
The entire contents of the extracted portion of each input file
is placed in its own top-level group in @var{output-file}, which
is automatically made as a netCDF4-format file.

@cindex @option{--gag}
@acronym{GAG} has two methods to specify group names for the
@var{output-file}.    
The @samp{-G} option, or its long-option equivalent @samp{--gpe},
takes as argument a group path editing description @var{gpe_dsc} of
where to place the results.
Each input file needs a distinct output group name to avoid namespace
conflicts in the @var{output-file}. 
Hence @command{ncecat} automatically creates unique output group names
based on either the input filenames or the @var{gpe_dsc} arguments.
When the user provides @var{gpe_dsc} (i.e., with @samp{-G}), then the
output groups are formed by enumerating sequential two-digit numeric
suffixes starting with zero, and appending them to the specified group
path (@pxref{Group Path Editing}).
When @var{gpe_dsc} is not provided (i.e., user requests @acronym{GAG} with
@samp{--gag} instead of @samp{-G}), then @command{ncecat} forms the
output groups by stripping the input file name of any type-suffix
(e.g., @code{.nc}), and all but the final component of the full
filename. 
@example
ncecat --gag 85.nc 86.nc 87.nc 8587.nc # Output groups 85, 86, 87
ncecat -G 85_ a.nc b.nc c.nc 8589.nc # Output groups 85_00, 85_01, 85_02
ncecat -G 85/ a.nc b.nc c.nc 8589.nc # Output groups 85/00, 85/01, 85/02
@end example

With both @acronym{RAG} and @acronym{GAG} the @var{output-file} size is
the sum of the sizes of the extracted variables in the input files. 
@xref{Statistics vs. Concatenation}, for a description of the
distinctions between the various statistics tools and concatenators. 
@cindex multi-file operators
@cindex standard input
@cindex @code{stdin}
As a multi-file operator, @command{ncecat} will read the list of
@var{input-files} from @code{stdin} if they are not specified 
as positional arguments on the command line 
(@pxref{Large Numbers of Files}).

@cindex @code{-M}
@cindex @code{--glb_mtd_spp}
@cindex metadata, global 
Suppress global metadata copying.
By default @acronym{NCO}'s multi-file operators copy the global metadata
from the first input file into @var{output-file}.  
This helps to preserve the provenance of the output data.
However, the use of metadata is burgeoning and is not uncommon to
encounter files with excessive amounts of extraneous metadata.
Extracting small bits of data from such files leads to output files
which are much larger than necessary due to the automatically copied
metadata.
@command{ncecat} supports turning off the default copying of global
metadata via the @samp{-M} switch (or its long option equivalents,
@samp{--glb_mtd_spp} and @samp{--global_metadata_suppress}). 

@cindex climate model
Consider five realizations, @file{85a.nc}, @file{85b.nc}, 
@w{@dots{} @file{85e.nc}} of 1985 predictions from the same climate
model. 
Then @code{ncecat 85?.nc 85_ens.nc} glues together the individual
realizations into the single file, @file{85_ens.nc}. 
If an input variable was dimensioned [@code{lat},@code{lon}], it will
by default have dimensions [@code{record},@code{lat},@code{lon}] in
the output file. 
@w{A restriction} of @command{ncecat} is that the hyperslabs of the
processed variables must be the same from file to file.
Normally this means all the input files are the same size, and contain 
data on different realizations of the same variables.

@findex ncpdq
@cindex packing
@cindex unpacking
@cindex @code{add_offset}
@cindex @code{scale_factor}
Concatenating a variable packed with different scales across multiple
datasets is beyond the capabilities of @command{ncecat} (and
@command{ncrcat}, the other concatenator (@ref{Concatenation}).
@command{ncecat} does not unpack data, it simply @emph{copies} the data
from the @var{input-files}, and the metadata from the @emph{first}
@var{input-file}, to the @var{output-file}. 
This means that data compressed with a packing convention must use
the identical packing parameters (e.g., @code{scale_factor} and
@code{add_offset}) for a given variable across @emph{all} input files.
Otherwise the concatenated dataset will not unpack correctly.
The workaround for cases where the packing parameters differ across
@var{input-files} requires three steps:
First, unpack the data using @command{ncpdq}.
Second, concatenate the unpacked data using @command{ncecat}, 
Third, re-pack the result with @command{ncpdq}.

@noindent
@html
<a name="xmp_ncecat"></a> <!-- http://nco.sf.net/nco.html#xmp_ncecat -->
@end html
EXAMPLES

Consider a model experiment which generated five realizations of one
year of data, say 1985.
You can imagine that the experimenter slightly perturbs the
initial conditions of the problem before generating each new solution.  
Assume each file contains all twelve months (a seasonal cycle) of data
and we want to produce a single file containing all the seasonal
cycles. 
Here the numeric filename suffix denotes the experiment number
(@emph{not} the month):
@example
ncecat 85_01.nc 85_02.nc 85_03.nc 85_04.nc 85_05.nc 85.nc
ncecat 85_0[1-5].nc 85.nc
ncecat -n 5,2,1 85_01.nc 85.nc
@end example
@noindent
These three commands produce identical answers.
@xref{Specifying Input Files}, for an explanation of the distinctions
between these methods.
The output file, @file{85.nc}, is five times the size as a single
@var{input-file}. 
It contains @w{60 months} of data.

@html
<a name="ncecat_rnm"></a> <!-- http://nco.sf.net/nco.html#ncecat_rnm -->
@end html
One often prefers that the (new) record dimension have a more
descriptive, context-based name than simply ``record''. 
This is easily accomplished with the @samp{-u @var{ulm_nm}} switch:
@example
ncecat -u realization 85_0[1-5].nc 85.nc
@end example
@noindent
Users are more likely to understand the data processing history when
such descriptive coordinates are used. 

@html
<a name="dmn_rcd_rm"></a> <!-- http://nco.sf.net/nco.html#dmn_rcd_rm -->
@end html
@cindex record dimension
@cindex fixed dimension
@cindex fix record dimension
@cindex @code{--mk_rec_dmn @var{dim}}
Consider a file with an existing record dimension named @code{time}. 
and suppose the user wishes to convert @code{time} from a record
dimension to a non-record dimension.
This may be useful, for example, when the user has another use for the
record variable.
The simplest method is to use @samp{ncks --fix_rec_dmn} but another
possibility is to use @command{ncecat} followed by 
@command{ncwa}: 
@cindex degenerate dimension
@example
ncecat in.nc out.nc # Convert time to non-record dimension
ncwa -a record in.nc out.nc # Remove new degenerate record dimension
@end example
@noindent
The second step removes the degenerate record dimension.
See @ref{ncpdq netCDF Permute Dimensions Quickly} and
@ref{ncks netCDF Kitchen Sink} for other methods of
of changing variable dimensionality, including the record dimension.

@page
@html
<a name="ncflint"></a> <!-- http://nco.sf.net/nco.html#ncflint -->
@end html
@node ncflint netCDF File Interpolator, ncks netCDF Kitchen Sink, ncecat netCDF Ensemble Concatenator, Operator Reference Manual
@section @command{ncflint} netCDF File Interpolator
@cindex interpolation
@cindex adding data
@cindex multiplying data
@cindex addition
@findex ncflint

@noindent
SYNTAX
@example
ncflint [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]
[-F] [--fix_rec_crd] [-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdr_pad @var{nbr}]
[-i @var{var},@var{val3}] [-L @var{dfl_lvl}] [-l @var{path}] [--no_tmp_fl] 
[-O] [-o @var{file_3}] [-p @var{path}] [-R] [-r] [--ram_all] 
[-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-w @var{wgt1}[,@var{wgt2}]] [-X ...] [-x]
@var{file_1} @var{file_2} [@var{file_3}]
@end example

@noindent
DESCRIPTION

@command{ncflint} creates an output file that is a linear combination of 
the input files.
This linear combination is a weighted average, a normalized weighted
average, or an interpolation of the input files.
Coordinate variables are not acted upon in any case, they are simply
copied from @var{file_1}.

There are two conceptually distinct methods of using @command{ncflint}.
The first method is to specify the weight each input file contributes to 
the output file.
In this method, the value @var{val3} of a variable in the output file
@var{file_3} is determined from its values @var{val1} and @var{val2} in
the two input files according to 
@set flg
@tex
$val3 = wgt1 \times val1 + wgt2 \times val2$
@clear flg
@end tex
@ifinfo
@math{@var{val3} = @var{wgt1}*@var{val1} + @var{wgt2}*@var{val2}} 
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
@var{val3} = @var{wgt1}*@var{val1} + @var{wgt2}*@var{val2} 
@clear flg
@end ifset
.
Here at least @var{wgt1}, and, optionally, @var{wgt2}, are specified on 
the command line with the @samp{-w} (or @samp{--weight} or
@samp{--wgt_var}) switch.
@cindex @code{-w @var{wgt1}[,@var{wgt2}]}
@cindex @code{--weight @var{wgt1}[,@var{wgt2}]}
@cindex @code{--wgt_var @var{wgt1}[,@var{wgt2}]}
If only @var{wgt1} is specified then @var{wgt2} is automatically
computed as @math{@var{wgt2} = 1 @minus{} @var{wgt1}}.
Note that weights larger @w{than 1} are allowed. 
Thus it is possible to specify @math{@var{wgt1} = 2} and
@math{@var{wgt2} = -3}.
One can use this functionality to multiply all the values in a given
file by a constant.

The second method of using @command{ncflint} is to specify the
interpolation option @w{with @samp{-i}} (or with the @samp{--ntp} or 
@samp{--interpolate} long options). 
This is the inverse of the first method in the following sense: 
When the user specifies the weights directly, @command{ncflint} has no
work to do besides multiplying the input values by their respective
weights and adding together the results to produce the output values.  
It makes sense to use this when the weights are known 
@emph{@w{a priori}}.

@cindex arrival value 
Another class of problems has the @dfn{arrival value} (i.e., @var{val3})
of a particular variable @var{var} known @emph{@w{a priori}}. 
In this case, the implied weights can always be inferred by examining
the values of @var{var} in the input files. 
This results in one equation in two unknowns, @var{wgt1} and @var{wgt2}:  
@set flg
@tex
$val3 = wgt1 \times val1 + wgt2 \times val2$
@clear flg
@end tex
@ifinfo
@math{@var{val3} = @var{wgt1}*@var{val1} + @var{wgt2}*@var{val2}} 
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
@var{val3} = @var{wgt1}*@var{val1} + @var{wgt2}*@var{val2} 
@clear flg
@end ifset
.
Unique determination of the weights requires imposing the additional
constraint of normalization on the weights:
@math{@var{wgt1} + @var{wgt2} = 1}.
Thus, to use the interpolation option, the user specifies @var{var}
and @var{val3} with the @samp{-i} option.
@command{ncflint} then computes @var{wgt1} and @var{wgt2}, and uses these
weights on all variables to generate the output file.
Although @var{var} may have any number of dimensions in the input
files, it must represent a single, scalar value.  
@cindex degenerate dimension
Thus any dimensions associated with @var{var} must be @dfn{degenerate},
i.e., of size one.

If neither @samp{-i} nor @samp{-w} is specified on the command line,
@command{ncflint} defaults to weighting each input file equally in the
output file.
This is equivalent to specifying @samp{-w 0.5} or @samp{-w 0.5,0.5}.
Attempting to specify both @samp{-i} and @samp{-w} methods in the same
command is an error. 

@command{ncflint} does not interpolate variables of type @code{NC_CHAR}
and @code{NC_STRING}. 
This behavior is hardcoded.

By default @command{ncflint} interpolates or multiplies record
coordinate variables (e.g., time is often stored as a record coordinate) 
not other coordinate variables (e.g., latitude and longitude). 
This is because @command{ncflint} is often used to time-interpolate
between existing files, but is rarely used to spatially interpolate.
Sometimes however, users wish to multiply entire files by a constant
that does not multiply any coordinate variables.
The @samp{--fix_rec_crd} switch was implemented for this purpose
in @acronym{NCO} version 4.2.6 (March, 2013).
It prevents @command{ncflint} from multiplying or interpolating any
coordinate variables, including record coordinate variables. 

@cindex missing values
@cindex @code{_FillValue}
Depending on your intuition, @command{ncflint} may treat missing values
unexpectedly.
Consider a point where the value in one input file, say @var{val1},
equals the missing value @var{mss_val_1} and, at the same point,
the corresponding value in the other input file @var{val2} is not
misssing (i.e., does not equal @var{mss_val_2}).
There are three plausible answers, and this creates ambiguity.

@w{Option one} is to set @math{@var{val3} = @var{mss_val_1}}.
The rationale is that @command{ncflint} is, at heart, an interpolator
and interpolation involving a missing value is intrinsically undefined.
@command{ncflint} currently implements this behavior since it is the
most conservative and least likely to lead to misinterpretation.

@w{Option two} is to output the weighted valid data point, i.e.,
@set flg
@tex
$val3 = wgt2 \times val2$
@clear flg
@end tex
@ifinfo
@math{@var{val3} = @var{wgt2}*@var{val2}} 
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
@var{val3} = @var{wgt2}*@var{val2} 
@clear flg
@end ifset
.
The rationale for this behavior is that interpolation is really a
weighted average of known points, so @command{ncflint} should weight the
valid point. 

@w{Option three} is to return the @emph{unweighted} valid point, i.e.,
@math{@var{val3} = @var{val2}}.
This behavior would appeal to those who use @command{ncflint} to
estimate data using the closest available data. 
When a point is not bracketed by valid data on both sides, it is better
to return the known datum than no datum at all.

The current implementation uses the first approach, @w{Option one}.
If you have strong opinions on this matter, let us know, since we are
willing to implement the other approaches as options if there is enough
interest. 

@noindent
@html
<a name="xmp_ncflint"></a> <!-- http://nco.sf.net/nco.html#xmp_ncflint -->
@end html
EXAMPLES

Although it has other uses, the interpolation feature was designed 
to interpolate @var{file_3} to a time between existing files.
Consider input files @file{85.nc} and @file{87.nc} containing variables 
describing the state of a physical system at times @math{@code{time} =
85} and @math{@code{time} = 87}.
Assume each file contains its timestamp in the scalar variable
@code{time}.  
Then, to linearly interpolate to a file @file{86.nc} which describes
the state of the system at time at @code{time} = 86, we would use
@example
ncflint -i time,86 85.nc 87.nc 86.nc
@end example

Say you have observational data covering January and April 1985 in two
files named @file{85_01.nc} and @file{85_04.nc}, respectively.
Then you can estimate the values for February and March by interpolating
the existing data as follows.
Combine @file{85_01.nc} and @file{85_04.nc} in a 2:1 ratio to make
@file{85_02.nc}:  
@example
ncflint -w 0.667 85_01.nc 85_04.nc 85_02.nc
ncflint -w 0.667,0.333 85_01.nc 85_04.nc 85_02.nc
@end example

Multiply @file{85.nc} @w{by 3} and @w{by @minus{}2} and add them
together to make @file{tst.nc}: 
@example
ncflint -w 3,-2 85.nc 85.nc tst.nc
@end example
@noindent
@cindex null operation
This is an example of a null operation, so @file{tst.nc} should be
identical (within machine precision) to @file{85.nc}.

@cindex multiplication
@cindex file multiplication
@cindex scaling
Multiply all the variables except the coordinate variables in the file
@file{emissions.nc} by @w{by 0.8}:
@example
ncflint --fix_rec_crd -w 0.8,0.0 emissions.nc emissions.nc scaled_emissions.nc
@end example
@noindent
The use of @samp{--fix_rec_crd} ensures, e.g., that the @code{time}
coordinate, if any, is not scaled (i.e., multiplied).

Add @file{85.nc} to @file{86.nc} to obtain @file{85p86.nc},
then subtract @file{86.nc} from @file{85.nc} to obtain @file{85m86.nc} 
@example
ncflint -w 1,1 85.nc 86.nc 85p86.nc
ncflint -w 1,-1 85.nc 86.nc 85m86.nc
ncdiff 85.nc 86.nc 85m86.nc
@end example
@noindent
Thus @command{ncflint} can be used to mimic some @command{ncbo}
operations. 
@cindex broadcasting variables
However this is not a good idea in practice because @command{ncflint}
does not broadcast (@pxref{ncbo netCDF Binary Operator}) conforming
variables during arithmetic. 
Thus the final two commands would produce identical results except that    
@command{ncflint} would fail if any variables needed to be broadcast.

@cindex @code{units}
Rescale the dimensional units of the surface pressure @code{prs_sfc}
from Pascals to hectopascals (millibars)
@example
ncflint -C -v prs_sfc -w 0.01,0.0 in.nc in.nc out.nc
ncatted -a units,prs_sfc,o,c,millibar out.nc
@end example
@noindent

@page
@html
<a name="ncks"></a> <!-- http://nco.sf.net/nco.html#ncks -->
@end html
@node ncks netCDF Kitchen Sink, ncpdq netCDF Permute Dimensions Quickly, ncflint netCDF File Interpolator, Operator Reference Manual
@section @command{ncks} netCDF Kitchen Sink
@cindex kitchen sink
@cindex printing files contents
@cindex printing variables
@findex ncks

@noindent
SYNTAX
@example
ncks [-3] [-4] [-5] [-6] [-7] [-A] [-a] [-b @var{binary-file}] [-C] [-c] [--cdl]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]] [-F] [--fix_rec_dmn @var{dim}] 
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-H] [-h] [--hdn] [--hdr_pad @var{nbr}]
[-L @var{dfl_lvl}] [-l @var{path}] [-M] [-m] [--mk_rec_dmn @var{dim}] [--md5_digest]
[--no_blank] [--no_tmp_fl] [-O] [-o @var{output-file}] [-P] [-p @var{path}] 
[-Q] [-q] [-R] [-r] [--ram_all] [-s @var{format}] 
[-u] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] [--xml]
@var{input-file} [[@var{output-file}]]
@end example

@noindent
DESCRIPTION

@cindex @command{ncextr}
The nickname ``kitchen sink'' is a catch-all because @command{ncks}
combines most features of @command{ncdump} and @command{nccopy} with
extra features to extract, hyperslab, multi-slab, sub-set, and translate  
into one versatile utility. 
@command{ncks} extracts (a subset of the) data from @var{input-file} and 
and writes (or pastes) it in netCDF format to @var{output-file}, and 
optionally writes it in flat binary format to @file{binary-file}, and
optionally prints it to screen.

@command{ncks} prints netCDF input data in @acronym{ASCII},
@acronym{CDL}, or @acronym{NcML} text formats @code{stdout}, like (an
extended version of) @command{ncdump}.
By default @command{ncks} prints data in a tabular format intended to be
easy to search for the data you want, one datum per screen line, with
all dimension subscripts and coordinate values (if any) preceding the
datum. 
Option @samp{-s} (or long options @samp{--sng_fmt} and @samp{--string}) 
permits the user to format data using C-style format strings, while
option @samp{--cdl} outputs @acronym{CDL} and option @samp{--xml}
outputs @acronym{NcML}. 
@command{ncks} exposes many flexible controls over printed output,
including @acronym{CDL} and @acronym{NcML}.

Options @samp{-5}, @samp{-a}, @samp{--cdl}, @samp{-F} , @samp{-H},
@samp{--hdn}, @samp{-M}, @samp{-m}, @samp{-P}, @samp{-Q}, @samp{-q},
@samp{-s}, @samp{-u}, @samp{--xml} (and their long option counterparts)
control the formatted appearance of the data.

@cindex global attributes
@cindex attributes, global
@command{ncks} extracts (and optionally creates a new netCDF file
comprised of) only selected variables from the input file
(similar to the old @command{ncextr} specification).
Only variables and coordinates may be specifically included or
excluded---all global attributes and any attribute associated with an
extracted variable are copied to the screen and/or output netCDF file. 
Options @samp{-c}, @samp{-C}, @samp{-v}, and @samp{-x} (and their long 
option synonyms) control which variables are extracted.

@command{ncks} extracts hyperslabs from the specified variables
(@command{ncks} implements the original @command{nccut} specification). 
Option @samp{-d} controls the hyperslab specification.
Input dimensions that are not associated with any output variable do
not appear in the output netCDF.
This feature removes superfluous dimensions from netCDF files. 

@cindex appending data
@cindex merging files
@command{ncks} will append variables and attributes from the
@var{input-file} to @var{output-file} if @var{output-file} is a
pre-existing netCDF file whose relevant dimensions conform to dimension
sizes of @var{input-file}. 
The append features of @command{ncks} are intended to provide a
rudimentary means of adding data from one netCDF file to another,
conforming, netCDF file. 
If naming conflicts exist between the two files, data in
@var{output-file} is usually overwritten by the corresponding data from 
@var{input-file}.  
Thus, when appending, the user should backup @var{output-file} in case 
valuable data are inadvertantly overwritten.

If @var{output-file} exists, the user will be queried whether to
@dfn{overwrite}, @dfn{append}, or @dfn{exit} the @command{ncks} call
completely.  
Choosing @dfn{overwrite} destroys the existing @var{output-file} and
create an entirely new one from the output of the @command{ncks} call.  
Append has differing effects depending on the uniqueness of the
variables and attributes output by @command{ncks}: If a variable or
attribute extracted from @var{input-file} does not have a name conflict
with the members of @var{output-file} then it will be added to
@var{output-file} without overwriting any of the existing contents of
@var{output-file}.  
In this case the relevant dimensions must agree (conform) between the
two files; new dimensions are created in @var{output-file} as required. 
@cindex global attributes
@cindex attributes, global
When a name conflict occurs, a global attribute from @var{input-file}
will overwrite the corresponding global attribute from
@var{output-file}.  
If the name conflict occurs for a non-record variable, then the
dimensions and type of the variable (and of its coordinate dimensions,
if any) must agree (conform) in both files. 
Then the variable values (and any coordinate dimension values)
from @var{input-file} will overwrite the corresponding variable values
(and coordinate dimension values, if any) in @var{output-file} 
@footnote{
Those familiar with netCDF mechanics might wish to know what is
happening here: @command{ncks} does not attempt to redefine the variable
in @var{output-file} to match its definition in @var{input-file},
@command{ncks} merely copies the values of the variable and its
coordinate dimensions, if any, from @var{input-file} to
@var{output-file}. 
}.

Since there can only be one record dimension in a file, the record
dimension must have the same name (though not necessarily the same size) in 
both files if a record dimension variable is to be appended. 
If the record dimensions are of differing sizes, the record dimension of
@var{output-file} will become the greater of the two record dimension
sizes, the record variable from @var{input-file} will overwrite any
counterpart in @var{output-file} and fill values will be written to any
gaps left in the rest of the record variables (I think). 
In all cases variable attributes in @var{output-file} are superseded by
attributes of the same name from @var{input-file}, and left alone if
there is no name conflict. 

Some users may wish to avoid interactive @command{ncks} queries about
whether to overwrite existing data.
For example, batch scripts will fail if @command{ncks} does not receive 
responses to its queries. 
Options @samp{-O} and @samp{-A} are available to force overwriting
existing files and variables, respectively. 

@unnumberedsubsec Options specific to @command{ncks}

The following list provides a short summary of the features unique to
@command{ncks}.  
Features common to many operators are described in 
@ref{Common features}. 

@table @samp

@html
<a name="-5"></a> <!-- http://nco.sf.net/nco.html#-5 -->
@end html
@cindex @code{-5}
@item -5 
Print data to screen alphabetically by group, and alphabetically by
variable within each group.
This ordering here is used by default in @acronym{CDL}-mode printing,
and may be selected for traditional mode printing with @samp{-5}
(The switch for invocation may change to something more descriptive in
the future). 

@cindex alphabetization
@cindex sort alphabetically
@cindex @code{-a}
@cindex @code{--abc}
@cindex @code{--alphabetize}
@item -a
Do not alphabetize extracted fields. 
By default, the specified output variables are extracted, printed, and
written to disk in alphabetical order.
This tends to make long output lists easier to search for particular
variables. 
Specifying @code{-a} results in the variables being extracted, printed,
and written to disk in the order in which they were saved in the input
file.
Thus @code{-a} retains the original ordering of the variables.
Also @samp{--abc} and @samp{--alphabetize}.

@cindex binary format
@cindex @code{-b}
@cindex @code{--fl_bnr}
@cindex @code{--bnr}
@cindex @code{--binary}
@item -b @file{file}
Activate native machine binary output writing to binary file
@file{file}.
Also @samp{--fl_bnr} and @samp{--binary-file}.
Writing packed variables in binary format is not supported.

@html
<a name="dmn_fix_mk"></a> <!-- http://nco.sf.net/nco.html#dmn_fix_mk -->
<a name="fix_rec_dmn"></a> <!-- http://nco.sf.net/nco.html#fix_rec_dmn -->
@end html
@cindex record dimension
@cindex fixed dimension
@cindex @code{--fix_rec_dmn @var{dim}}
@cindex @code{--no_rec_dmn @var{dim}}
@item --fix_rec_dmn
Change record dimension @var{dim} in the input file into a fixed
dimension in the output file. 
Also @samp{--no_rec_dmn}.
Before @acronym{NCO} version 4.2.5 (January, 2013), the syntax for 
@code{--fix_rec_dmn} did not permit or require the specification of
the dimension name @var{dim}. 
This is because the feature only worked on netCDF3 files, which support
only one record dimension, so specifying its name was not necessary.
netCDF4 files allow an arbitrary number of record dimensions, so the
user must specify which record dimension to fix.
The decision was made that starting with @acronym{NCO} version 4.2.5
(January, 2013), it is always required to specify the dimension name to
fix regardless of the netCDF file type.
This keeps the code simple, and is symmetric with the syntax for
@code{--mk_rec_dmn}, described next.

As of @acronym{NCO} version 4.4.0 (January, 2014), the argument
@code{all} may be given to @samp{--fix_rec_dmn} to convert @emph{all} 
record dimensions to fixed dimensions in the output file. 
Previously, @samp{--fix_rec_dmn} only allowed one option, the name of a
single record dimension to be fixed. 
Now it is simple to simultaneously fix all record dimensions.
This is useful (and nearly mandatory) when flattening netCDF4 files that
have multiple record dimensions per group into netCDF3 files (which are
limited to at most one record dimension) (@pxref{Group Path Editing}). 

@html
<a name="hdn"></a> <!-- http://nco.sf.net/nco.html#hdn -->
<a name="hidden"></a> <!-- http://nco.sf.net/nco.html#hidden -->
@end html
@cindex hidden attributes
@cindex special attributes
@cindex @code{--hdn}
@cindex @code{--hidden}
@cindex @code{_Format}
@cindex @code{_DeflateLevel}
@cindex @code{_Shuffle}
@cindex @code{_Storage}
@cindex @code{_ChunkSizes}
@cindex @code{_Endianness}
@cindex @code{_Fletcher32}
@cindex @code{_NOFILL}
As of @acronym{NCO} version 4.4.0 (January, 2014), the @samp{--hdn}
or @samp{--hidden} options print hidden (aka special) attributes.
This is equivalent to @samp{ncdump -s}.
Hidden attributes include: @code{_Format}, @code{_DeflateLevel},
@code{_Shuffle}, @code{_Storage}, @code{_ChunkSizes},
@code{_Endianness}, @code{_Fletcher32}, and @code{_NOFILL}. 
Previously @command{ncks} ignored all these attributes in
@acronym{CDL}/@acronym{XML} modes. 
Now it prints these attributes as appropriate. 
Users are referred to the
@uref{http://www.unidata.ucar.edu/software/netcdf/docs, Unidata netCDF Documentation},
or the man pages for @command{ncgen} or @command{ncdump}, for
detailed descriptions of the meanings of these attributes. 

@html
<a name="cdl"></a> <!-- http://nco.sf.net/nco.html#cdl -->
<a name="hdp"></a> <!-- http://nco.sf.net/nco.html#hdp -->
<a name="hncgen"></a> <!-- http://nco.sf.net/nco.html#hncgen -->
<a name="ncgen-hdf"></a> <!-- http://nco.sf.net/nco.html#ncgen-hdf -->
@end html
@cindex @command{hdp}
@cindex @command{ncgen}
@cindex @command{ncgen-hdf}
@cindex @command{hncgen}
@cindex @command{ncdump}
@cindex @code{--cdl}
@cindex @acronym{CDL}
@cindex @acronym{HDF}
@cindex @acronym{HDF4}
@item --cdl 
As of @acronym{NCO} version 4.3.3 (July, 2013), @command{ncks} can
print extracted data and metadata to screen (i.e., @code{stdout}) as
valid @acronym{CDL} (network Common data form Description Language). 
@acronym{CDL} is the human-readable ``lingua franca'' of netCDF ingested by
@command{ncgen} and excreted by @command{ncdump}.
Compare @command{ncks} ``traditional'' with @acronym{CDL} printing:
@example
zender@@roulee:~$ ncks -v one ~/nco/data/in.nc
one: type NC_FLOAT, 0 dimensions, 1 attribute, chunked? no, compressed? no, packed? no
one size (RAM) = 1*sizeof(NC_FLOAT) = 1*4 = 4 bytes
one attribute 0: long_name, size = 3 NC_CHAR, value = one

one = 1 

zender@@roulee:~$ ncks --cdl -v one ~/nco/data/in.nc
netcdf in @{

  variables:
    float one ;
    one:long_name = "one" ;

  data:
    one = 1 ;

@} // group /
@end example
@command{ncgen} converts @acronym{CDL}-mode output into a netCDF file:
@example
ncks --cdl -v one ~/nco/data/in.nc > ~/in.cdl
ncgen -k netCDF-4 -b -o ~/in.nc ~/in.cdl
ncks -v one ~/in.nc
@end example
The @acronym{HDF} version of @command{ncgen}, often named
@command{hncgen} or @command{ncgen-hdf}, converts netCDF3 @acronym{CDL}
into an @acronym{HDF} file:  
@example
/usr/hdf4/bin/ncgen -b -o ~/in.hdf ~/in.cdl # HDF ncgen (local builds)
/usr/bin/hncgen     -b -o ~/in.hdf ~/in.cdl # Same as HDF ncgen (RPM packages?)
/usr/bin/ncgen-hdf  -b -o ~/in.hdf ~/in.cdl # Same as HDF ncgen (Debian packages?)
hdp dumpsds ~/in.hdf                        # ncdump-equivalent for HDF4 files
@end example
Note that @acronym{HDF4} does not support netCDF-style groups, so the
above commands fail when the input file contains groups.
Only netCDF4 and @acronym{HDF5} support groups.
In our experience the @acronym{HDF} @command{ncgen} command, by whatever 
name installed, is not robust and can fail on valid netCDF3
@acronym{CDL}.  

@html
<a name="dmn_rec_mk"></a> <!-- http://nco.sf.net/nco.html#dmn_rec_mk -->
<a name="mk_rec_dmn"></a> <!-- http://nco.sf.net/nco.html#mk_rec_dmn -->
@end html
@cindex record dimension
@cindex fixed dimension
@cindex fix record dimension
@cindex @code{--mk_rec_dmn @var{dim}}
@item --mk_rec_dmn @var{dim}
Change existing dimension @var{dim} to a record dimension in the output file.
This is the most straightforward way of changing a dimension to a/the
record dimension, and works fine in most cases.
See @ref{ncecat netCDF Ensemble Concatenator} and 
@ref{ncpdq netCDF Permute Dimensions Quickly} for other methods of
changing variable dimensionality, including the record dimension. 

@html
<a name="prn"></a> <!-- http://nco.sf.net/nco.html#prn -->
@end html
@cindex @code{-H}
@cindex @code{--data}
@cindex @code{--hieronymus}
@item -H 
Turn-on printing to screen or turn-off copying data (not metadata).
Also activated using @samp{--print} or @samp{--prn}.
By default @command{ncks} prints all metadata and data to screen if
no netCDF output file is specified.
Use @samp{-H} to print data to screen if a netCDF output is specified,
or to restrict printing to data (no metadata) when no netCDF output is 
specified.
Also use @samp{-H} to turn-off copying data (not metadata) to an output
file. 
Unless otherwise specified (with @code{-s}), each element of the data
hyperslab prints on a separate line containing the names, indices,
and, values, if any, of all of the variables dimensions.
The dimension and variable indices refer to the location of the
corresponding data element with respect to the variable as stored on
disk (i.e., not the hyperslab).
@example
% ncks -C -v three_dmn_var in.nc
lat[0]=-90 lev[0]=100 lon[0]=0 three_dmn_var[0]=0 
lat[0]=-90 lev[0]=100 lon[1]=90 three_dmn_var[1]=1 
lat[0]=-90 lev[0]=100 lon[2]=180 three_dmn_var[2]=2 
...
lat[1]=90 lev[2]=1000 lon[1]=90 three_dmn_var[21]=21 
lat[1]=90 lev[2]=1000 lon[2]=180 three_dmn_var[22]=22 
lat[1]=90 lev[2]=1000 lon[3]=270 three_dmn_var[23]=23 
@end example
Printing the same variable with the @samp{-F} option shows the same
variable indexed with Fortran conventions
@example
% ncks -F -C -v three_dmn_var in.nc
lon(1)=0 lev(1)=100 lat(1)=-90 three_dmn_var(1)=0 
lon(2)=90 lev(1)=100 lat(1)=-90 three_dmn_var(2)=1 
lon(3)=180 lev(1)=100 lat(1)=-90 three_dmn_var(3)=2 
...
@end example
Printing a hyperslab does not affect the variable or dimension indices
since these indices are relative to the full variable (as stored in the
input file), and the input file has not changed.
However, if the hyperslab is saved to an output file and those values
are printed, the indices will change:
@c fxm: replace with new MSA output style
@example
% ncks -H -d lat,90.0 -d lev,1000.0 -v three_dmn_var in.nc out.nc
...
lat[1]=90 lev[2]=1000 lon[0]=0 three_dmn_var[20]=20 
lat[1]=90 lev[2]=1000 lon[1]=90 three_dmn_var[21]=21 
lat[1]=90 lev[2]=1000 lon[2]=180 three_dmn_var[22]=22 
lat[1]=90 lev[2]=1000 lon[3]=270 three_dmn_var[23]=23 
% ncks -C -v three_dmn_var out.nc
lat[0]=90 lev[0]=1000 lon[0]=0 three_dmn_var[0]=20 
lat[0]=90 lev[0]=1000 lon[1]=90 three_dmn_var[1]=21 
lat[0]=90 lev[0]=1000 lon[2]=180 three_dmn_var[2]=22 
lat[0]=90 lev[0]=1000 lon[3]=270 three_dmn_var[3]=23 
@end example

@cindex @code{-M}
@cindex @code{--Mtd}
@cindex @code{--Metadata}
@cindex metadata, global 
@item -M
Turn-on printing to screen or turn-off copying global and group metadata.
This includes file summary information and global and group attributes.
Also @samp{--Mtd} and @samp{--Metadata}.
By default @command{ncks} prints global metadata to screen if no netCDF
output file and no variable extraction list is specified (with @samp{-v}).  
Use @samp{-M} to print global metadata to screen if a netCDF output is 
specified, or if a variable extraction list is specified (with @samp{-v}). 
Use @samp{-M} to turn-off copying of global and group metadata when
copying, subsetting, or appending to an output file.

@html
<a name="prn_tbl"></a> <!-- http://nco.sf.net/nco.html#prn_tbl -->
@end html
The various combinations of printing switches can be confusing.
In an attempt to anticipate what most users want to do, @command{ncks}
uses context-sensitive defaults for printing.
Our goal is to minimize the use of switches required to accomplish the
common operations.
We assume that users creating a new file or overwriting (e.g., with
@samp{-O}) an existing file usually wish to copy all global and
variable-specific attributes to the new file.
In contrast, we assume that users appending (e.g., with @samp{-A} an
explicit variable list from one file to another usually wish to copy
only the variable-specific attributes to the output file.
The switches @samp{-H}, @samp{-M}, and @samp{-m} switches are
implemented as toggles which reverse the default behavior.
The most confusing aspect of this is that @samp{-M} inhibits copying
global metadata in overwrite mode and causes copying of global
metadata in append mode.
@example
ncks                 in.nc        # Print  VAs and GAs
ncks          -v one in.nc        # Print  VAs not GAs
ncks    -M    -v one in.nc        # Print  GAs only
ncks       -m -v one in.nc        # Print  VAs only
ncks    -M -m -v one in.nc        # Print  VAs and GAs
ncks -O              in.nc out.nc # Copy   VAs and GAs
ncks -O       -v one in.nc out.nc # Copy   VAs and GAs
ncks -O -M    -v one in.nc out.nc # Copy   VAs not GAs
ncks -O    -m -v one in.nc out.nc # Copy   GAs not VAs
ncks -O -M -m -v one in.nc out.nc # Copy   only data (no atts)
ncks -A              in.nc out.nc # Append VAs and GAs
ncks -A       -v one in.nc out.nc # Append VAs not GAs
ncks -A -M    -v one in.nc out.nc # Append VAs and GAs
ncks -A    -m -v one in.nc out.nc # Append only data (no atts)
ncks -A -M -m -v one in.nc out.nc # Append GAs not VAs
@end example
where @code{VAs} and @code{GAs} denote variable and group/global
attributes, respectively. 

@cindex @command{ncdump}
@cindex @code{-m}
@cindex @code{--mtd}
@cindex @code{--metadata}
@cindex metadata
@item -m
Turn-on printing to screen or turn-off copying variable metadata.
Using @samp{-m} will print variable metadata to screen (similar to
@kbd{ncdump -h}).  
This displays all metadata pertaining to each variable, one variable
at a time.
@cindex chunking
@cindex compression
@cindex deflation
This includes information on the storage properties of the variable,
such as whether it employs chunking, compression, or packing.
Also activated using @samp{--mtd} and @samp{--metadata}.
The @command{ncks} default behavior is to print variable metadata to
screen if no netCDF output file is specified.
Use @samp{-m} to print variable metadata to screen if a netCDF output is  
specified. 
Also use @samp{-m} to turn-off copying of variable metadata to an output
file.

@cindex @code{--no_blank}
@cindex @code{--noblank}
@cindex @code{--no-blank}
@cindex blank
@cindex missing values
@item --no_blank
Print numeric representation of missing values.
As of @acronym{NCO}
As of @acronym{NCO} version 4.2.2 (October, 2012), @acronym{NCO} prints
missing values as blanks (i.e., the underscore character @samp{_}) by default.
To enable the old behavior of printing the numeric representation of
missing values (e.g., @code{1.0e36}), use the @samp{--no_blank} switch.
Also activated using @samp{--noblank} or @samp{--no-blank}.

@cindex @code{-P}
@cindex @code{--print}
@cindex @code{--prn}
@item -P 
Print data, metadata, and units to screen.
The @samp{-P} switch is a convenience abbreviation for 
@samp{-C -H -M -m -u}.
Also activated using @samp{--print} or @samp{--prn}.
This set of switches is useful for exploring file contents.

@cindex @code{-Q}
@item -Q 
Toggle printing of dimension indices and coordinate values when printing
arrays. 
Each variable's name appears flush left in the output.
This helps locate specific variables in lists with many variables and 
different dimensions. 

@cindex @code{-q}
@cindex @code{--quiet}
@cindex quiet
@item -q 
Turn off all printing to screen.
This overrides the setting of all print-related switches, equivalent to
@kbd{-H -M -m} when in single-file printing mode. 
When invoked with @code{-R} (@pxref{Retaining Retrieved Files}), @command{ncks}
automatically sets @code{-q}. 
This allows @command{ncks} to retrieve remote files without
automatically trying to print them.
Also @samp{--quiet}.

@cindex @code{-s}
@cindex @code{--string}
@cindex @code{--sng_fmt}
@cindex @code{printf()}
@cindex C language
@item -s @var{format}
String format for text output. 
Accepts @w{C language} escape sequences and @code{printf()} formats. 
Also @samp{--string}  and @samp{--sng_fmt}. 

@cindex @code{-u}
@cindex @code{--units}
@item -u 
Toggle the printing of a variable's @code{units} attribute, if any, 
with its values.
Also @samp{--units}.

@html
<a name="xml"></a> <!-- http://nco.sf.net/nco.html#xml -->
<a name="ncmnl"></a> <!-- http://nco.sf.net/nco.html#ncml -->
@end html
@cindex @code{--xml}
@cindex @code{--ncml}
@cindex @command{ncdump}
@cindex @acronym{XML}
@cindex @acronym{NcML}
@item --xml, --ncml
As of @acronym{NCO} version 4.3.3 (July, 2013), @command{ncks} can
print extracted metadata to screen (i.e., @code{stdout}) as
@acronym{XML} in @acronym{NcML}, the netCDF Markup Language.  
@command{ncks} supports for @acronym{XML} more completely than 
of @samp{ncdump -x}.
With @command{ncks} one can translate entire netCDF3 and netCDF4 files
into @acronym{NcML}, including metadata and data, using all 
@acronym{NCO}'s subsetting and hyperslabbing capabilities.
Compare @command{ncks} ``traditional'' with @acronym{XML} printing:
@example
@verbatim
zender@@roulee:~$ ncks -v one ~/nco/data/in.nc
one: type NC_FLOAT, 0 dimensions, 1 attribute, chunked? no, compressed? no, packed? no
one size (RAM) = 1*sizeof(NC_FLOAT) = 1*4 = 4 bytes
one attribute 0: long_name, size = 3 NC_CHAR, value = one

one = 1 

zender@roulee:~$ ncks --xml -v one ~/nco/data/in.nc
<?xml version="1.0" encoding="UTF-8"?>
<netcdf xmlns="http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2" location="/home/zender/nco/data/in.nc">
  <variable name="one" type="float" shape="">
    <attribute name="long_name" separator="*" value="one" />
    <values>1.</values>
  </variable>
</netcdf>
@end verbatim
@end example
@acronym{XML}-mode prints variable metadata and, as of 
@acronym{NCO} version 4.3.7 (October, 2013), variable data and, as of
@acronym{NCO} version 4.4.0 (January, 2014), hidden attributes.
That @acronym{ncks} produces correct @acronym{NcML} translations of
@acronym{CDM} files for all supported datatypes is verified by
comparison to output from Unidata's @command{toolsUI} Java program.
Please let us know how to improve @acronym{XML}/@acronym{NcML}
features. 

@cindex @code{--xml_no_location}
@cindex @code{--xml_spr_chr}
@cindex @code{--xml_spr_nmr}
@cindex separator
@command{ncks} provides additional options to configure @acronym{NcML}
output: @samp{--xml_no_location}, @samp{--xml_spr_chr}, and
@samp{--xml_spr_nmr}. 
Every @acronym{NcML} configuration option automatically triggers
@acronym{NcML} printing, so that specifying @samp{--xml} in addition
to a configuration option is redundant and unnecessary.
The @samp{--xml_no_location} switch prevents output of the
@acronym{NcML} @code{location} element.
By default the location element is printed with a value equal to the
location of the input dataset, e.g.,
@code{location="/home/zender/in.nc"}.
The @samp{--xml_spr_chr} and @samp{--xml_spr_nmr} options customize
the strings used as @acronym{NcML} separators for attributes and
variables of character-type and numeric-type, respectively.
Their default separators are "*" and " ":
@example
@verbatim
zender@@roulee:~$ ncks --xml -d time,0,3 -v two_dmn_rec_var_sng in.nc
...
   <values separator="*">abc*bcd*cde*def</values>
 ...
 zender@@roulee:~$ ncks --xml_spr_chr=', ' -v two_dmn_rec_var_sng in.nc
...
<values separator=", ">abc, bcd, cde, def, efg, fgh, ghi, hij, jkl, klm</values>
...
zender@@roulee:~$ ncks --xml -v one_dmn_rec_var in.nc
...
<values>1 2 3 4 5 6 7 8 9 10</values>
...
zender@@roulee:~$ ncks --xml_spr_nmr=', ' -v one_dmn_rec_var in.nc
...
<values separator=", ">1, 2, 3, 4, 5, 6, 7, 8, 9, 10</values>
...
@end verbatim
@end example
Separator elements for strings are a thorny issue.
One must be sure that the separator element is not mistaken as a portion
of the string. 
@acronym{NCO} attempts to produce valid @acronym{NcML} and supplies the
@samp{--xml_spr_chr} option to work around any difficulties.
@acronym{NCO} performs precautionary checks with
@code{strstr(@var{val},@var{spr})} to identify presence of the separator
string (@var{spr}) in data (@var{val}) and, when it detects a match,
automatically switches to a backup separator string (@code{*|*}). 
However limitations of @code{strstr()} may lead to false negatives 
when the separator string occurs in data beyond the first string in
multi-dimensional @code{NC_CHAR} arrays. 
Hence, results may be ambiguous to NcML parsers. 
If problems arise, use @samp{--xml_spr_chr} to specify a multi-character
separator that does not appear in the string array and that does not
include an NcML formatting characters (e.g., commas, angles, quotes).
@end table

@html
<a name="ncattget"></a> <!-- http://nco.sf.net/nco.html#ncattget -->
<a name="nclist"></a> <!-- http://nco.sf.net/nco.html#nclist -->
<a name="ncdmnsz"></a> <!-- http://nco.sf.net/nco.html#ncdmnsz -->
<a name="ncrecsz"></a> <!-- http://nco.sf.net/nco.html#ncrecsz -->
<a name="ncmax"></a> <!-- http://nco.sf.net/nco.html#ncmax -->
<a name="ncmdn"></a> <!-- http://nco.sf.net/nco.html#ncmdn -->
<a name="ncavg"></a> <!-- http://nco.sf.net/nco.html#ncavg -->
<a name="ncrng"></a> <!-- http://nco.sf.net/nco.html#ncrng -->
<a name="ncunits"></a> <!-- http://nco.sf.net/nco.html#ncunits -->
<a name="alias"></a> <!-- http://nco.sf.net/nco.html#alias -->
<a name="filters"></a> <!-- http://nco.sf.net/nco.html#filters -->
<a name="filter"></a> <!-- http://nco.sf.net/nco.html#filter -->
<a name="flt"></a> <!-- http://nco.sf.net/nco.html#flt -->
@end html
@menu
* Filters for @command{ncks}::
@end menu

@node Filters for @command{ncks},  , ncks netCDF Kitchen Sink, ncks netCDF Kitchen Sink
@subsection Filters for @command{ncks}
@cindex @acronym{UNIX}
@cindex @command{ncattget}
@cindex @command{ncavg}
@cindex @command{ncdmnsz}
@cindex @command{nclist}
@cindex @command{ncmax}
@cindex @command{ncmdn}
@cindex @command{ncmin}
@cindex @command{ncrecsz}
@cindex @command{ncrng}
@cindex @command{ncunits}
@cindex @file{.bashrc}
@cindex filters
@cindex alias
@cindex shell
@cindex Bash shell
@cindex Csh shell
@cindex Sh shell
@cindex @command{bash}
We encourage the use of standard @acronym{UNIX} pipes and filters to
narrow the verbose output of @command{ncks} into more precise targets.
For example, to obtain an uncluttered listing of the variables in a file
try 
@example
ncks -m in.nc | grep -E ': type' | cut -f 1 -d ' ' | sed 's/://' | sort
@end example
A Bash user could alias the previous filter to the shell command
@command{nclist} as shown below.
More complex examples could involve command line arguments.
For example, a user may frequently be interested in obtaining the value
of an attribute, e.g., for textual file examination or for passing to
another shell command.
Say the attribute is @code{purpose}, the variable is @code{z}, and the
file is @code{in.nc}.
In this example, @command{ncks -m -v z} is too verbose so a robust
@command{grep} and @command{cut} filter is desirable, such as
@example
ncks -M -m in.nc | grep -E -i "^z attribute [0-9]+: purpose" | cut -f 11- -d ' ' | sort
@end example
The filters are clearly too complex to remember on-the-fly so the entire 
procedure could be implemented as a shell command or function called,
say, @command{ncattget}
@example
function ncattget @{ ncks -M -m $@{3@} | grep -E -i "^$@{2@} attribute [0-9]+: $@{1@}" | cut -f 11- -d ' ' | sort ; @}
@end example
The shell @command{ncattget} is invoked with three arugments that are,
in order, the names of the attribute, variable, and file to examine.
Global attributes are indicated by using a variable name of @code{global}.
This definition yields the following results
@example
% ncattget purpose z in.nc
Height stored with a monotonically increasing coordinate
% ncattget Purpose Z in.nc
Height stored with a monotonically increasing coordinate
% ncattget history z in.nc
% ncattget history global in.nc
History global attribute.
@end example
Note that case sensitivity has been turned off for the variable and
attribute names (and could be turned on by removing the @samp{-i} switch
to @command{grep}).
Furthermore, extended regular expressions may be used for both the
variable and attribute names.
The next two commands illustrate this by searching for the values
of attribute @code{purpose} in all variables, and then for all
attributes of the variable @code{z}:
@example
% ncattget purpose .+ in.nc
1-D latitude coordinate referred to by geodesic grid variables
1-D longitude coordinate referred to by geodesic grid variables
...
% ncattget .+ Z in.nc
Height
Height stored with a monotonically increasing coordinate
meter
@end example

Extended filters are best stored as shell commands if they are
used frequently.
Shell commands may be re-used when they are defined in shell
configuration files.
These files are usually named @file{.bashrc}, @file{.cshrc}, and
@file{.profile} for the Bash, Csh, and Sh shells, respectively.
@example
@verbatim
# NB: Untested on Csh, Ksh, Sh, Zsh! Send us feedback!
# Bash shell (/bin/bash) users place these in .bashrc
# ncattget $att_nm $var_nm $fl_nm : What attributes does variable have?
function ncattget { ncks -M -m ${3} | grep -E -i "^${2} attribute [0-9]+: ${1}" | cut -f 11- -d ' ' | sort ; }
# ncunits $att_val $fl_nm : Which variables have given units?
function ncunits { ncks -M -m ${2} | grep -E -i " attribute [0-9]+: units.+ ${1}" | cut -f 1 -d ' ' | sort ; }
# ncavg $var_nm $fl_nm : What is mean of variable?
function ncavg { ncwa -y avg -O -C -v ${1} ${2} ~/foo.nc ; ncks -H -C -v ${1} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncavg $var_nm $fl_nm : What is mean of variable?
function ncavg { ncap2 -O -C -v -s "foo=${1}.avg();print(foo)" ${2} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncdmnsz $dmn_nm $fl_nm : What is dimension size?
function ncdmnsz { ncks -m -M ${2} | grep -E -i ": ${1}, size =" | cut -f 7 -d ' ' | uniq ; }
# nclist $fl_nm : What variables are in file?
function nclist { ncks -m ${1} | grep -E ': type' | cut -f 1 -d ' ' | sed 's/://' | sort ; }
# ncmax $var_nm $fl_nm : What is maximum of variable?
function ncmax { ncwa -y max -O -C -v ${1} ${2} ~/foo.nc ; ncks -H -C -v ${1} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncmax $var_nm $fl_nm : What is maximum of variable?
function ncmax { ncap2 -O -C -v -s "foo=${1}.max();print(foo)" ${2} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncmdn $var_nm $fl_nm : What is median of variable?
function ncmdn { ncap2 -O -C -v -s "foo=gsl_stats_median_from_sorted_data(${1}.sort());print(foo)" ${2} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncrng $var_nm $fl_nm : What is range of variable?
function ncrng { ncap2 -O -C -v -s "foo_min=${1}.min();foo_max=${1}.max();print(foo_min,\"%f\");print(\" to \");print(foo_max,\"%f\")" ${2} ~/foo.nc ; }
# ncmode $var_nm $fl_nm : What is mode of variable?
function ncmode { ncap2 -O -C -v -s "foo=gsl_stats_median_from_sorted_data(${1}.sort());print(foo)" ${2} ~/foo.nc | cut -f 3- -d ' ' ; }
# ncrecsz $fl_nm : What is record dimension size?
function ncrecsz { ncks -M ${1} | grep -E -i "^Record dimension:" | cut -f 8- -d ' ' ; }
# Csh shell (/bin/csh) users place these in .cshrc
ncattget() { ncks -M -m ${3} | grep -E -i "^${2} attribute [0-9]+: ${1}" | cut -f 11- -d ' ' | sort ; }
ncdmnsz() { ncks -m -M ${2} | grep -E -i ": ${1}, size =" | cut -f 7 -d ' ' | uniq ; }
nclist() { ncks -m ${1} | grep -E ': type' | cut -f 1 -d ' ' | sed 's/://' | sort ; }
ncrecsz() { ncks -M ${1} | grep -E -i "^Record dimension:" | cut -f 8- -d ' ' ; }
# Sh shell (/bin/sh) users place these in .profile
ncattget() { ncks -M -m ${3} | grep -E -i "^${2} attribute [0-9]+: ${1}" | cut -f 11- -d ' ' | sort ; }
ncdmnsz() { ncks -m -M ${2} | grep -E -i ": ${1}, size =" | cut -f 7 -d ' ' | uniq ; }
nclist() { ncks -m ${1} | grep -E ': type' | cut -f 1 -d ' ' | sed 's/://' | sort ; }
ncrecsz() { ncks -M ${1} | grep -E -i "^Record dimension:" | cut -f 8- -d ' ' ; }
@end verbatim
@end example

@noindent
@html
<a name="xmp_ncks"></a> <!-- http://nco.sf.net/nco.html#xmp_ncks -->
@end html
EXAMPLES

View all data in netCDF @file{in.nc}, printed with Fortran indexing
conventions: 
@example
ncks -F in.nc
@end example

Copy the netCDF file @file{in.nc} to file @file{out.nc}.
@example
ncks in.nc out.nc
@end example
Now the file @file{out.nc} contains all the data from @file{in.nc}.
There are, however, two differences between @file{in.nc} and
@file{out.nc}.
@cindex @code{history}
First, the @code{history} global attribute (@pxref{History Attribute})
will contain the command used to create @file{out.nc}.
@cindex alphabetize output
@cindex sort alphabetically
@cindex @code{-a}
Second, the variables in @file{out.nc} will be defined in alphabetical
order.
Of course the internal storage of variable in a netCDF file should be
transparent to the user, but there are cases when alphabetizing a file 
is useful (see description of @code{-a} switch).

@html
<a name="xmp_att_glb_cpy"></a> <!-- http://nco.sf.net/nco.html#xmp_att_glb_cpy -->
@end html
@cindex global attributes
@cindex attributes, global
@cindex subsetting
@cindex exclusion
@cindex extraction
@cindex @code{-v @var{var}}
@cindex @code{--variable @var{var}}
@cindex @code{-x}
@cindex @code{--exclude}
@cindex @code{--xcl}
Copy all global attributes (and no variables) from @file{in.nc} to
@file{out.nc}: 
@example
ncks -A -x ~/nco/data/in.nc ~/out.nc
@end example
The @samp{-x} switch tells @acronym{NCO} to use the complement of the extraction
list (@pxref{Subsetting Files}). 
Since no extraction list is explicitly specified (with @samp{-v}),
the default is to extract all variables.
The complement of all variables is no variables.
@cindex @code{-A}
@cindex @code{--apn}
@cindex @code{--append}
@cindex appending to files
Without any variables to extract, the append (@samp{-A}) command
(@pxref{Appending Variables}) has only to extract and copy
(i.e., append) global attributes to the output file.

@html
<a name="xmp_att_glb_cpy"></a> <!-- http://nco.sf.net/nco.html#xmp_att_var_cpy -->
@end html
Copy/append metadata (not data) from variables in one file to
variables in a second file.
When copying/subsetting/appending files (as opposed to printing them),
the copying of data, variable metadata, and global/group metadata are
now turned OFF by @samp{-H}, @samp{-m}, and @samp{-M}, respectively. 
This is the opposite sense in which these switches work when
@emph{printing} a file. 
One can use these switches to easily replace data or metadata in one
file with data or metadata from another:
@example
# Extract naked (data-only) copies of two variables
ncks -h -M -m -O -C -v one,three_dmn_rec_var ~/nco/data/in.nc ~/out.nc
# Change values to be sure original values are not copied in following step
ncap2 -O -v -s 'one*=2;three_dmn_rec_var*=0' ~/nco/data/in.nc ~/in2.nc
# Append in2.nc metadata (not data!) to out.nc
ncks -A -C -H -v one,three_dmn_rec_var ~/in2.nc ~/out.nc
@end example
Variables in @file{out.nc} now contain data (not metadata) from
@file{in.nc} and metadata (not data) from @file{in2.nc}.

@cindex @code{printf()}
@cindex @code{\n} (linefeed)
@cindex @code{\t} (horizontal tab)
Print variable @code{three_dmn_var} from file @file{in.nc} with
default notations. 
Next print @code{three_dmn_var} as an un-annotated text column.
Then print @code{three_dmn_var} signed with very high precision.
Finally, print @code{three_dmn_var} as a comma-separated list.
@example
% ncks -C -v three_dmn_var in.nc
lat[0]=-90 lev[0]=100 lon[0]=0 three_dmn_var[0]=0 
lat[0]=-90 lev[0]=100 lon[1]=90 three_dmn_var[1]=1 
...
lat[1]=90 lev[2]=1000 lon[3]=270 three_dmn_var[23]=23 
% ncks -s '%f\n' -C -v three_dmn_var in.nc
0.000000
1.000000
...
23.000000
% ncks -s '%+16.10f\n' -C -v three_dmn_var in.nc
   +0.0000000000
   +1.0000000000
...
  +23.0000000000
% ncks -s '%f, ' -C -v three_dmn_var in.nc
0.000000, 1.000000, ..., 23.000000,
@end example
@noindent
Programmers will recognize these as the venerable @w{C language} 
@code{printf()} formatting strings. 
The second and third options are useful when pasting data into text
files like reports or papers.  
@xref{ncatted netCDF Attribute Editor}, for more details on string
formatting and special characters. 

As of @acronym{NCO} version 4.2.2 (October, 2012), @acronym{NCO} prints
missing values as blanks (i.e., the underscore character @samp{_}) by
default: 
@example
% ncks -C -H -v mss_val in.nc
lon[0]=0 mss_val[0]=73 
lon[1]=90 mss_val[1]=_ 
lon[2]=180 mss_val[2]=73 
lon[3]=270 mss_val[3]=_ 
% ncks -s '%+5.1f, ' -H -C -v mss_val in.nc
+73.0, _, +73.0, _, 
@end example

One dimensional arrays of characters stored as netCDF variables are 
automatically printed as strings, whether or not they are
NUL-terminated, e.g.,
@example
ncks -v fl_nm in.nc
@end example
@noindent
The @code{%c} formatting code is useful for printing 
multidimensional arrays of characters representing fixed length strings
@example
ncks -s '%c' -v fl_nm_arr in.nc
@end example
@noindent
@cindex @code{core dump}
Using the @code{%s} format code on strings which are not NUL-terminated 
(and thus not technically strings) is likely to result in a core dump.

@cindex subsetting
@cindex exclusion
@cindex extraction
Create netCDF @file{out.nc} containing all variables, and any associated 
coordinates, except variable @code{time}, from netCDF @file{in.nc}:
@example
ncks -x -v time in.nc out.nc
@end example
As a special case of this, consider how to remove a 
@acronym{CF} Convention comliant @code{bounds} or @code{coordinates}
variable (@pxref{CF Conventions}) such as @code{time_bounds}.
@acronym{NCO} subsetting assumes the user wants all coordinates 
and bounds and axes associated with all extracted variables 
(@pxref{Subsetting Coordinate Variables}).
Hence to exclude a @code{bounds} or @code{coordinates} variable while
retaining the ``parent'' variable (here @code{time}), one must use the
@samp{-C} switch: 
@example
ncks -C -x -v time_bounds in.nc out.nc
@end example
The @samp{-C} switch tells the operator @emph{NOT} to necessarily
include all the @acronym{CF} coordinates and bounds and axes.
Hence the output file will contain @code{time} and not
@code{time_bounds}. 

Extract variables @code{time} and @code{pressure} from netCDF
@file{in.nc}.  
If @file{out.nc} does not exist it will be created.
Otherwise the you will be prompted whether to append to or to
overwrite @file{out.nc}: 
@example
ncks -v time,pressure in.nc out.nc
ncks -C -v time,pressure in.nc out.nc
@end example
@noindent
The first version of the command creates an @file{out.nc} which contains
@code{time}, @code{pressure}, and any coordinate variables associated
with @var{pressure}. 
The @file{out.nc} from the second version is guaranteed to contain only 
two variables @code{time} and @code{pressure}.  

Create netCDF @file{out.nc} containing all variables from file
@file{in.nc}.  
Restrict the dimensions of these variables to a hyperslab. 
Print (with @code{-H}) the hyperslabs to the screen for good measure.  
The specified hyperslab is: the fifth value in dimension @code{time};
the 
half-open range @math{@var{lat} > 0.} in coordinate @code{lat}; the
half-open range @math{@var{lon} < 330.} in coordinate @code{lon}; the
closed interval @math{0.3 < @var{band} < 0.5} in coordinate @code{band};
and cross-section closest to 1000.@: in coordinate @code{lev}.  
Note that limits applied to coordinate values are specified with a
decimal point, and limits applied to dimension indices do not have a 
decimal point @xref{Hyperslabs}.
@example
ncks -H -d time,5 -d lat,,0.0 -d lon,330.0, -d band,0.3,0.5 
-d lev,1000.0 in.nc out.nc 
@end example

@cindex wrapped coordinates
Assume the domain of the monotonically increasing longitude coordinate
@code{lon} is @math{0 < @var{lon} < 360}. 
Here, @code{lon} is an example of a wrapped coordinate.
@command{ncks} will extract a hyperslab which crosses the Greenwich
meridian simply by specifying the westernmost longitude as @var{min} and 
the easternmost longitude as @var{max}, as follows:
@example
ncks -d lon,260.0,45.0 in.nc out.nc
@end example
For more details @xref{Wrapped Coordinates}.

@page
@html
<a name="ncpdq"></a> <!-- http://nco.sf.net/nco.html#ncpdq -->
<a name="ncpack"></a> <!-- http://nco.sf.net/nco.html#ncpack -->
<a name="ncunpack"></a> <!-- http://nco.sf.net/nco.html#ncunpack -->
@end html
@node ncpdq netCDF Permute Dimensions Quickly, ncra netCDF Record Averager, ncks netCDF Kitchen Sink, Operator Reference Manual
@section @command{ncpdq} netCDF Permute Dimensions Quickly
@findex ncpdq
@findex ncpack
@findex ncunpack
@cindex reshape variables
@cindex permute dimensions
@cindex reverse dimensions
@cindex re-order dimensions
@cindex re-dimension
@cindex packing
@cindex unpacking

@noindent
SYNTAX
@example
ncpdq [-3] [-4] [-6] [-7] [-A] [-a [-]@var{dim}[,@dots{}]] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]]
[-F] [-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdf] [--hdr_pad @var{nbr}]
[-L @var{dfl_lvl}] [-l @var{path}] [-M @var{pck_map}] [--mrd] [--no_tmp_fl] 
[-O] [-o @var{output-file}] [-P @var{pck_plc}] [-p @var{path}] 
[-R] [-r] [--ram_all] [-t @var{thr_nbr}] [-U] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x]
@var{input-file} [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{ncpdq} performs one (not both) of two distinct functions:
packing or dimension permutation.
@command{ncpdq} is optimized to perform these actions in a parallel
fashion with a minimum of time and memory.
The @dfn{pdq} may stand for ``Permute Dimensions Quickly'', 
``Pack Data Quietly'', ``Pillory Dan Quayle'', or other silly uses.

@cindex @code{add_offset}
@cindex @code{scale_factor}
@cindex @command{ncap2}
@cindex packing policy
@unnumberedsubsec Packing and Unpacking Functions
The @command{ncpdq} packing (and unpacking) algorithms are described 
in @ref{Methods and functions}, and are also implemented in
@command{ncap2}. 
@command{ncpdq} extends the functionality of these algorithms by 
providing high level control of the @dfn{packing policy} so that
users can consistently pack (and unpack) entire files with one command. 
@cindex @var{pck_plc}
@cindex @code{-P @var{pck_plc}}
@cindex @code{--pck_plc @var{pck_plc}}
@cindex @code{--pack_policy @var{pck_plc}}
The user specifies the desired packing policy with the @samp{-P} switch
(or its long option equivalents, @samp{--pck_plc} and
@samp{--pack_policy}) and its @var{pck_plc} argument.
Four packing policies are currently implemented:@*   
@table @dfn
@item Packing (and Re-Packing) Variables [@emph{default}]
Definition: Pack unpacked variables, re-pack packed variables@*
Alternate invocation: @code{ncpack}@*
@var{pck_plc} key values: @samp{all_new}, @samp{pck_all_new_att}@*
@item Packing (and not Re-Packing) Variables
Definition: Pack unpacked variables, copy packed variables@*
Alternate invocation: none@*
@var{pck_plc} key values: @samp{all_xst}, @samp{pck_all_xst_att}@*
@item Re-Packing Variables
Definition: Re-pack packed variables, copy unpacked variables@*
Alternate invocation: none@*
@var{pck_plc} key values: @samp{xst_new}, @samp{pck_xst_new_att}@*
@item Unpacking
Definition: Unpack packed variables, copy unpacked variables@*
Alternate invocation: @code{ncunpack}@*
@var{pck_plc} key values: @samp{upk}, @samp{unpack}, @samp{pck_upk}@*
@end table
@noindent
Equivalent key values are fully interchangeable.
Multiple equivalent options are provided to satisfy disparate needs
and tastes of @acronym{NCO} users working with scripts and from the
command line.

Regardless of the packing policy selected, @command{ncpdq} 
no longer (as of @acronym{NCO} version 4.0.4 in October, 2010)
packs coordinate variables, or the special variables, weights, 
and other grid properties described in @ref{CF Conventions}.
Prior @command{ncpdq} versions treated coordinate variables and
grid properties no differently from other variables.
However, coordinate variables are one-dimensional, so packing saves
little space on large files, and the resulting files are difficult for
humans to read. 
@command{ncpdq} will, of course, @emph{unpack} coordinate variables and
weights, for example, in case some other, non-@acronym{NCO} software
packed them in the first place.

Concurrently, Gaussian and area weights and other grid properties are
often used to derive fields in re-inflated (unpacked) files, so packing
such grid properties causes a considerable loss of precision in 
downstream data processing.
If users express strong wishes to pack grid properties, we will
implement new packing policies.
An immediate workaround for those needing to pack grid properties
now, is to use the @command{ncap2} packing functions or to rename the
grid properties prior to calling @command{ncpdq}. 
We welcome your feedback. 

To reduce required memorization of these complex policy switches, 
@command{ncpdq} may also be invoked via a synonym or with switches
that imply a particular policy.
@command{ncpack} is a synonym for @command{ncpdq} and behaves the same 
in all respects.
Both @command{ncpdq} and @command{ncpack} assume a default packing
policy request of @samp{all_new}.
Hence @command{ncpack} may be invoked without any @samp{-P} switch,
unlike @command{ncpdq}.
Similarly, @command{ncunpack} is a synonym for @command{ncpdq} 
except that @command{ncpack} implicitly assumes a request to unpack, 
i.e., @samp{-P pck_upk}.
@cindex @code{-U}
@cindex @code{--upk}
@cindex @code{--unpack}
Finally, the @command{ncpdq} @samp{-U} switch (or its long option
equivalents, @samp{--upk} and @samp{--unpack}) requires no argument.
It simply requests unpacking.

Given the menagerie of synonyms, equivalent options, and implied
options, a short list of some equivalent commands is appropriate.
The following commands are equivalent for packing:
@code{ncpdq -P all_new}, @code{ncpdq --pck_plc=all_new}, and
@code{ncpack}.
The following commands are equivalent for unpacking:
@code{ncpdq -P upk}, @code{ncpdq -U}, @code{ncpdq --pck_plc=unpack}, 
and @code{ncunpack}.
Equivalent commands for other packing policies, e.g., @samp{all_xst}, 
follow by analogy. 
@cindex @command{alias}
@cindex @command{ln -s}
@cindex symbolic links
Note that @command{ncpdq} synonyms are subject to the same constraints 
and recommendations discussed in the secion on @command{ncbo} synonyms
(@pxref{ncbo netCDF Binary Operator}).
That is, symbolic links must exist from the synonym to @command{ncpdq},
or else the user must define an @command{alias}.

@cindex packing map
@cindex @var{pck_map}
@cindex @code{-M @var{pck_map}}
@cindex @code{--pck_map @var{pck_map}}
@cindex @code{--map @var{pck_map}}
The @command{ncpdq} packing algorithms must know to which type
particular types of input variables are to be packed.
The correspondence between the input variable type and the output,
packed type, is called the @dfn{packing map}.
The user specifies the desired packing map with the @samp{-M} switch
(or its long option equivalents, @samp{--pck_map} and
@samp{--map}) and its @var{pck_map} argument.
Five packing maps are currently implemented:@*
@cindex @samp{hgh_sht}
@cindex @samp{hgh_byt}
@cindex @samp{flt_sht}
@cindex @samp{flt_byt}
@cindex @samp{nxt_lsr}
@cindex @code{NC_DOUBLE}
@cindex @code{NC_FLOAT}
@cindex @code{NC_INT64}
@cindex @code{NC_UINT64}
@cindex @code{NC_INT}
@cindex @code{NC_UINT}
@cindex @code{NC_SHORT}
@cindex @code{NC_USHORT}
@cindex @code{NC_CHAR}
@cindex @code{NC_BYTE}
@cindex @code{NC_UBYTE}
@table @dfn
@item Pack Floating Precisions to @code{NC_SHORT} [@emph{default}]
Definition: Pack floating precision types to @code{NC_SHORT}@*
Map: Pack [@code{NC_DOUBLE},@code{NC_FLOAT}] to @code{NC_SHORT}@*
Types copied instead of packed: [@code{NC_INT64},@code{NC_UINT64},@code{NC_INT},@code{NC_UINT},@code{NC_SHORT},@code{NC_USHORT},@code{NC_CHAR},@code{NC_BYTE},@code{NC_UBYTE}]@*
@var{pck_map} key values: @samp{flt_sht}, @samp{pck_map_flt_sht}@*
@item Pack Floating Precisions to @code{NC_BYTE}
Definition: Pack floating precision types to @code{NC_BYTE}@*
Map: Pack [@code{NC_DOUBLE},@code{NC_FLOAT}] to @code{NC_BYTE}@* 
Types copied instead of packed: [@code{NC_INT64},@code{NC_UINT64},@code{NC_INT},@code{NC_UINT},@code{NC_SHORT},@code{NC_USHORT},@code{NC_CHAR},@code{NC_BYTE},@code{NC_UBYTE}]@*
@var{pck_map} key values: @samp{flt_byt}, @samp{pck_map_flt_byt}@*
@item Pack Higher Precisions to @code{NC_SHORT}
Definition: Pack higher precision types to @code{NC_SHORT}@*
Map: 
Pack [@code{NC_DOUBLE},@code{NC_FLOAT},@code{NC_INT64},@code{NC_UINT64},@code{NC_INT},@code{NC_UINT}] to @code{NC_SHORT}@*
Types copied instead of packed: [@code{NC_SHORT},@code{NC_USHORT},@code{NC_CHAR},@code{NC_BYTE},@code{NC_UBYTE}]@*
@var{pck_map} key values: @samp{hgh_sht}, @samp{pck_map_hgh_sht}@*
@item Pack Higher Precisions to @code{NC_BYTE}
Definition: Pack higher precision types to @code{NC_BYTE}@*
Map: 
Pack [@code{NC_DOUBLE},@code{NC_FLOAT},@code{NC_INT64},@code{NC_UINT64},@code{NC_INT},@code{NC_UINT},@code{NC_SHORT},@code{NC_USHORT}] to @code{NC_BYTE}@*
Types copied instead of packed: [@code{NC_CHAR},@code{NC_BYTE},@code{NC_UBYTE}]@*
@var{pck_map} key values: @samp{hgh_byt}, @samp{pck_map_hgh_byt}@*
@item Pack to Next Lesser Precision
Definition: Pack each type to type of next lesser size@*
Map: Pack [@code{NC_DOUBLE},@code{NC_INT64},@code{NC_UINT64}], to @code{NC_INT}. 
Pack [@code{NC_FLOAT},@code{NC_INT},@code{NC_UINT}] to @code{NC_SHORT}.
Pack [@code{NC_SHORT},@code{NC_USHORT}] to @code{NC_BYTE}.@*
Types copied instead of packed: [@code{NC_CHAR},@code{NC_BYTE},@code{NC_UBYTE}]@*
@var{pck_map} key values: @samp{nxt_lsr}, @samp{pck_map_nxt_lsr}@*
@end table
@noindent
The default @samp{all_new} packing policy with the default
@samp{flt_sht} packing map reduces the typical @code{NC_FLOAT}-dominated
file size by @w{about 50%.}
@samp{flt_byt} packing reduces an @code{NC_DOUBLE}-dominated file by
@w{about 87%.} 

@cindex @var{_FillValue}
@cindex @code{_FillValue}
@cindex @code{NUL}
The netCDF packing algorithm (@pxref{Methods and functions}) is
lossy---once packed, the exact original data cannot be recovered without
a full backup. 
Hence users should be aware of some packing caveats:
First, the interaction of packing and data equal to the
@var{_FillValue} is complex.
Test the @code{_FillValue} behavior by performing a pack/unpack cycle 
to ensure data that are missing @emph{stay} missing and data that are
not misssing do not join the Air National Guard and go missing.
This may lead you to elect a new @var{_FillValue}.
Second, @code{ncpdq} actually allows packing into @code{NC_CHAR} (with,
e.g., @samp{flt_chr}).
However, the intrinsic conversion of @code{signed char} to higher
precision types is tricky for values equal to zero, i.e., for
@code{NUL}.  
Hence packing to @code{NC_CHAR} is not documented or advertised.  
Pack into @code{NC_BYTE} (with, e.g., @samp{flt_byt}) instead.

@html
<a name="rvr"></a> <!-- http://nco.sf.net/nco.html#rvr -->
@end html
@unnumberedsubsec Dimension Permutation
@command{ncpdq} re-shapes variables in @var{input-file} by re-ordering
and/or reversing dimensions specified in the dimension list.
The dimension list is a whitespace-free, comma separated list of
dimension names, optionally prefixed by negative signs, that follows the 
@samp{-a} (or long options @samp{--arrange}, @samp{--permute},
@samp{--re-order}, or @samp{--rdr}) switch.  
To re-order variables by a subset of their dimensions, specify
these dimensions in a comma-separated list following @samp{-a}, e.g., 
@samp{-a lon,lat}. 
To reverse a dimension, prefix its name with a negative sign in the
dimension list, e.g., @samp{-a -lat}. 
Re-ordering and reversal may be performed simultaneously, e.g.,
@samp{-a lon,-lat,time,-lev}. 

@cindex record dimension
Users may specify any permutation of dimensions, including
permutations which change the record dimension identity.
The record dimension is re-ordered like any other dimension.
@cindex concatenation
@cindex record dimension
This unique @command{ncpdq} capability makes it possible to concatenate
files along any dimension.
See @ref{Concatenation} for a detailed example.
@cindex record variable
The record dimension is always the most slowly varying dimension in a
record variable (@pxref{C and Fortran Index Conventions}).
The specified re-ordering fails if it requires creating more than
one record dimension amongst all the output variables
@footnote{This limitation, imposed by the netCDF storage layer,
may be relaxed in the future with netCDF4.}.

Two special cases of dimension re-ordering and reversal deserve special
mention. 
First, it may be desirable to completely reverse the storage order of a
variable. 
To do this, include all the variable's dimensions in the dimension
re-order list in their original order, and prefix each dimension name
with the negative sign.  
@cindex transpose
Second, it may useful to transpose a variable's storage order, e.g.,
@w{from C} to Fortran data storage order 
(@pxref{C and Fortran Index Conventions}).
To do this, include all the variable's dimensions in the dimension
re-order list in reversed order.
Explicit examples of these two techniques appear below.

@tex
NB: fxm ncpdq documentation will evolve through Fall 2004.
I will upload updates to documentation linked to by the NCO homepage.
ncpdq is a powerful operator, and 
I am unfamiliar with the terminology needed to describe what ncpdq does.
Sequences, sets, sheesh!
I just know that it does "The right thing" according to my gut feelings.
Now do you feel more comfortable using it?

Let $\dmnvct(\xxx)$ represent the dimensionality of the variable $\xxx$. 
Dimensionality describes the order and sizes of dimensions.
If $\xxx$ has rank $\dmnnbr$, then we may write $\dmnvct(\xxx)$ as the
$\dmnnbr$-element vector 
$$
\dmnvct(\xxx) = [ \dmn_{1}, \dmn_{2}, \dmn_{3}, \ldots, 
\dmn_{\dmnidx-1}, \dmn_{\dmnidx}, \dmn_{\dmnidx+1}, 
\ldots, \dmn_{\dmnnbr-2}, \dmn_{\dmnnbr-1}, \dmn_{\dmnnbr} ] 
$$
where $\dmn_{\dmnidx}$ is the size of the $\dmnidx$'th dimension.

The dimension re-order list specified with @samp{-a} is the
$\rdrnbr$-element vector 
$$
\rdrvct = [ \rdr_{1}, \rdr_{2}, \rdr_{3}, \ldots, 
\rdr_{\rdridx-1}, \rdr_{\rdridx}, \rdr_{\rdridx+1}, 
\ldots, \rdr_{\rdrnbr-2}, \rdr_{\rdrnbr-1}, \rdr_{\rdrnbr} ] 
$$
There need be no relation between $\dmnnbr$ and $\rdrnbr$.
Let the $\shrnbr$-element vector $\shrvct$ be the intersection
(i.e., the ordered set of unique shared dimensions) of $\dmnvct$ and 
$\rdrvct$
Then
$$
\eqalign{{\shrvct} &= \rdrvct \cap \dmnvct \cr
&= [ \shr_{1}, \shr_{2}, \shr_{3}, \ldots, 
\shr_{\shridx-1}, \shr_{\shridx}, \shr_{\shridx+1}, 
\ldots, \shr_{\shrnbr-2}, \shr_{\shrnbr-1}, \shr_{\shrnbr} ]} 
$$
$\shrvct$ is empty if $\rdrvct \notin \dmnvct$.

Re-ordering (or re-shaping) a variable means mapping the input state
with dimensionality $\dmnvct(\xxx)$ to the output state with
dimensionality $\dmnvctprm(\xxxprm)$.  
In practice, mapping occurs in three logically distinct steps.
First, we tranlate the user input to a one-to-one mapping $\mpp$ 
between input and output dimensions, 
$\dmnvct \mapsto \dmnvctprm$.
This tentative map is final unless external constraints (typically
netCDF restrictions) impose themselves.   
Second, we check and, if necessary, refine the tentative mapping so that
the re-shaped variables will co-exist in the same file without violating 
netCDF-imposed storage restrictions. 
This refined map specifies the final (output) dimensionality.
Third, we translate the output dimensionality into one-dimensional  
memory offsets for each datum according to the @w{C language} convention 
for multi-dimensional array storage.
Dimension reversal changes the ordering of data, though not the
rank or dimensionality, and so is part of the third step. 

Dimensions $\rdr$ disjoint from $\dmnvct$ play no role in re-ordering.
The first step taken to re-order a variable is to determine $\shrvct$. 
$\rdrvct$ is constant for all variables, whereas $\dmnvct$, and hence
$\shrvct$, is variable-specific.
$\shrvct$ is empty if $\rdrvct \notin \dmnvct$.
This may be the case for some extracted variables.
The user may explicitly specify the one-to-one mapping of input
to output dimension order by supplying (with @samp{-a}) a re-order list
$\rdrvct$ such that $\shrnbr = \dmnnbr$. 
In this case $\dmnsubnnnprm = \shrsubnnn$.  
The degenerate case occurs when $\dmnvct = \shrvct$.
This produces the identity mapping $\dmnsubnnnprm = \dmnsubnnn$.  

The mapping of input to output dimension order is more complex
when $\shrnbr \ne \dmnnbr$. 
In this case $\dmnsubnnnprm = \dmnsubnnn$ for the $\dmnnbr-\shrnbr$
dimensions $\dmnsubnnnprm \notin \shrvct$.
For the $\shrnbr$ dimensions $\dmnsubnnnprm \in \shrvct$, 
$\dmnsubnnnprm = \shrsubsss$.  
@end tex

@c fxm: discuss netCDF-imposed constraints here

@noindent
@html
<a name="xmp_ncpdq"></a> <!-- http://nco.sf.net/nco.html#xmp_ncpdq -->
@end html
EXAMPLES

Pack and unpack all variables in file @file{in.nc} and store the results
in @file{out.nc}:  
@example
ncpdq in.nc out.nc # Same as ncpack in.nc out.nc
ncpdq -P all_new -M flt_sht in.nc out.nc # Defaults
ncpdq -P all_xst in.nc out.nc
ncpdq -P upk in.nc out.nc # Same as ncunpack in.nc out.nc
ncpdq -U in.nc out.nc # Same as ncunpack in.nc out.nc
@end example
The first two commands pack any unpacked variable in the input file.
They also unpack and then re-pack every packed variable.
The third command only packs unpacked variables in the input file.
If a variable is already packed, the third command copies it unchanged
to the output file. 
The fourth and fifth commands unpack any packed variables.
If a variable is not packed, the third command copies it unchanged.

The previous examples all utilized the default packing map.
Suppose you wish to archive all data that are currently unpacked 
into a form which only preserves 256 distinct values.
Then you could specify the packing map @var{pck_map} as @samp{hgh_byt}
and the packing policy @var{pck_plc} as @samp{all_xst}:
@example
ncpdq -P all_xst -M hgh_byt in.nc out.nc
@end example
@cindex appending variables
@cindex @samp{-A}
@cindex @samp{-v}
Many different packing maps may be used to construct a given file 
by performing the packing on subsets of variables (e.g., with @samp{-v}) 
and using the append feature with @samp{-A} (@pxref{Appending Variables}).

Users may wish to unpack data packed with the @acronym{HDF} convention,
and then re-pack it with the netCDF convention so that all their
datasets use the same packing convention prior to intercomparison.
@cindex @command{ncl_convert2nc}
@cindex @acronym{NCL}
@example
# One-step procedure: For NCO 4.4.0+, netCDF 4.3.1+
# 1. Convert, unpack, and repack HDF file into netCDF file
ncpdq --hdf_upk -P xst_new modis.hdf modis.nc # HDF4 files
ncpdq --hdf_upk -P xst_new modis.h5  modis.nc # HDF5 files

# One-step procedure: For NCO 4.3.7--4.3.9
# 1. Convert, unpack, and repack HDF file into netCDF file
ncpdq --hdf4 --hdf_upk -P xst_new modis.hdf modis.nc # HDF4
ncpdq        --hdf_upk -P xst_new modis.h5  modis.nc # HDF5

# Two-step procedure: For NCO 4.3.6 and earlier
# 1. Convert HDF file to netCDF file
ncl_convert2nc modis.hdf
# 2. Unpack using HDF convention and repack using netCDF convention
ncpdq --hdf_upk -P xst_new modis.nc modis.nc
@end example
@acronym{NCO} now
@footnote{
Prior to @acronym{NCO} 4.4.0 and netCDF 4.3.1 (January, 2014),
@acronym{NCO} requires the @samp{--hdf4} switch to correctly read
HDF4 input files.
For example, @samp{ncpdq --hdf4 --hdf_upk -P xst_new modis.hdf modis.nc}.
That switch is now obsolete, though harmless for backwards compatibility.
Prior to version 4.3.7 (October, 2013), @acronym{NCO} lacked the
software necessary to workaround netCDF library flaws handling
@acronym{HDF4} files, and thus @acronym{NCO} failed to convert
@acronym{HDF4} files to netCDF files.
In those cases, use the @command{ncl_convert2nc} command distributed
with @acronym{NCL} to convert @acronym{HDF4} files to netCDF.}
automatically detects @acronym{HDF4} files.  
In this case it produces an output file @file{modis.nc} which preserves
the @acronym{HDF} packing used in the input file.
The @command{ncpdq} command first unpacks all packed variables using the
@acronym{HDF} unpacking algorithm (as specified by @samp{--hdf_upk}), 
and then repacks those same variables using the netCDF algorithm
(because that is the only algorithm @acronym{NCO} packs with).
As described above the @samp{--P xst_new} packing policy only repacks
variables that are already packed. 
Not-packed variables are copied directly without loss of precision
@footnote{@command{ncpdq} does not support packing data using the
@acronym{HDF} convention.
Although it is now straightforward to support this, we think it might
sow more confusion than it reaps. 
Let us know if you disagree and would like @acronym{NCO} to support
packing data with @acronym{HDF} algorithm.}.

Re-order file @file{in.nc} so that the dimension @code{lon} always
precedes the dimension @code{lat} and store the results in
@file{out.nc}:  
@example
ncpdq -a lon,lat in.nc out.nc
ncpdq -v three_dmn_var -a lon,lat in.nc out.nc
@end example
The first command re-orders every variable in the input file.
The second command extracts and re-orders only the variable
@code{three_dmn_var}. 

@cindex reverse dimensions
Suppose the dimension @code{lat} represents latitude and monotonically 
increases increases from south to north. 
Reversing the @code{lat} dimension means re-ordering the data so that
latitude values decrease monotonically from north to south.
Accomplish this with
@example
% ncpdq -a -lat in.nc out.nc
% ncks -C -v lat in.nc
lat[0]=-90
lat[1]=90
% ncks -C -v lat out.nc
lat[0]=90
lat[1]=-90
@end example
This operation reversed the latitude dimension of all variables.
Whitespace immediately preceding the negative sign that specifies
dimension reversal may be dangerous.
@cindex long options
@cindex quotes
Quotes and long options can help protect negative signs that should
indicate dimension reversal from being interpreted by the shell as
dashes that indicate new command line switches.
@example
ncpdq -a -lat in.nc out.nc # Dangerous? Whitespace before "-lat"
ncpdq -a '-lat' in.nc out.nc # OK. Quotes protect "-" in "-lat"
ncpdq -a lon,-lat in.nc out.nc # OK. No whitespace before "-"
ncpdq --rdr=-lat in.nc out.nc # Preferred. Uses "=" not whitespace
@end example

@cindex reverse dimensions
To create the mathematical transpose of a variable, place all its
dimensions in the dimension re-order list in reversed order.
This example creates the transpose of @code{three_dmn_var}: 
@example
% ncpdq -a lon,lev,lat -v three_dmn_var in.nc out.nc
% ncks -C -v three_dmn_var in.nc
lat[0]=-90 lev[0]=100 lon[0]=0 three_dmn_var[0]=0 
lat[0]=-90 lev[0]=100 lon[1]=90 three_dmn_var[1]=1 
lat[0]=-90 lev[0]=100 lon[2]=180 three_dmn_var[2]=2 
...
lat[1]=90 lev[2]=1000 lon[1]=90 three_dmn_var[21]=21 
lat[1]=90 lev[2]=1000 lon[2]=180 three_dmn_var[22]=22 
lat[1]=90 lev[2]=1000 lon[3]=270 three_dmn_var[23]=23 
% ncks -C -v three_dmn_var out.nc
lon[0]=0 lev[0]=100 lat[0]=-90 three_dmn_var[0]=0
lon[0]=0 lev[0]=100 lat[1]=90 three_dmn_var[1]=12
lon[0]=0 lev[1]=500 lat[0]=-90 three_dmn_var[2]=4
...
lon[3]=270 lev[1]=500 lat[1]=90 three_dmn_var[21]=19
lon[3]=270 lev[2]=1000 lat[0]=-90 three_dmn_var[22]=11
lon[3]=270 lev[2]=1000 lat[1]=90 three_dmn_var[23]=23
@end example

@cindex reverse data
To completely reverse the storage order of a variable, include
all its dimensions in the re-order list, each prefixed by a negative
sign. 
This example reverses the storage order of @code{three_dmn_var}: 
@example
% ncpdq -a -lat,-lev,-lon -v three_dmn_var in.nc out.nc
% ncks -C -v three_dmn_var in.nc
lat[0]=-90 lev[0]=100 lon[0]=0 three_dmn_var[0]=0 
lat[0]=-90 lev[0]=100 lon[1]=90 three_dmn_var[1]=1 
lat[0]=-90 lev[0]=100 lon[2]=180 three_dmn_var[2]=2 
...
lat[1]=90 lev[2]=1000 lon[1]=90 three_dmn_var[21]=21 
lat[1]=90 lev[2]=1000 lon[2]=180 three_dmn_var[22]=22 
lat[1]=90 lev[2]=1000 lon[3]=270 three_dmn_var[23]=23 
% ncks -C -v three_dmn_var out.nc
lat[0]=90 lev[0]=1000 lon[0]=270 three_dmn_var[0]=23
lat[0]=90 lev[0]=1000 lon[1]=180 three_dmn_var[1]=22
lat[0]=90 lev[0]=1000 lon[2]=90 three_dmn_var[2]=21
...
lat[1]=-90 lev[2]=100 lon[1]=180 three_dmn_var[21]=2
lat[1]=-90 lev[2]=100 lon[2]=90 three_dmn_var[22]=1
lat[1]=-90 lev[2]=100 lon[3]=0 three_dmn_var[23]=0
@end example

@html
<a name="dmn_rcd_mk"></a> <!-- http://nco.sf.net/nco.html#dmn_rcd_mk -->
<a name="mk_rcd_dmn"></a> <!-- http://nco.sf.net/nco.html#mk_rcd_dmn -->
@end html
Creating a record dimension named, e.g., @code{time}, in a file which
has no existing record dimension is simple with @command{ncecat}:
@example
ncecat -O -u time in.nc out.nc # Create degenerate record dimension named "time"
@end example

@cindex record dimension
Now consider a file with all dimensions, including @code{time}, fixed
(non-record).
Suppose the user wishes to convert @code{time} from a fixed dimension to  
a record dimension. 
This may be useful, for example, when the user wishes to append
additional time slices to the data.
As of @acronym{NCO} version 4.0.1 (April, 2010) the preferred method for
doing this is with @command{ncks}:
@example
ncks -O --mk_rec_dmn time in.nc out.nc # Change "time" to record dimension
@end example

Prior to 4.0.1, the procedure to change an existing fixed dimension into
a record dimension required three separate commands,
@command{ncecat} followed by @command{ncpdq}, and then @command{ncwa}.
The recommended method is now to use @samp{ncks --fix_rec_dmn}, yet it
is still instructive to present the original procedure, as it shows how
multiple operators can achieve the same ends by different means: 
@cindex degenerate dimension
@example
ncecat -O in.nc out.nc # Add degenerate record dimension named "record"
ncpdq -O -a time,record out.nc out.nc # Switch "record" and "time"
ncwa -O -a record out.nc out.nc # Remove (degenerate) "record"
@end example
@noindent
The first step creates a degenerate (size equals one) record dimension
named (by default) @code{record}. 
The second step swaps the ordering of the dimensions named @code{time}
and @code{record}.
Since @code{time} now occupies the position of the first (least rapidly
varying) dimension, it becomes the record dimension.
The dimension named @code{record} is no longer a record dimension.
The third step averages over this degenerate @code{record} dimension.
Averaging over a degenerate dimension does not alter the data.
The ordering of other dimensions in the file (@code{lat}, @code{lon},
etc.) is immaterial to this procedure. 
See @ref{ncecat netCDF Ensemble Concatenator} and 
@ref{ncks netCDF Kitchen Sink} for other methods of
changing variable dimensionality, including the record dimension. 

@page
@html
<a name="ncra"></a> <!-- http://nco.sf.net/nco.html#ncra -->
@end html
@node ncra netCDF Record Averager, ncrcat netCDF Record Concatenator, ncpdq netCDF Permute Dimensions Quickly, Operator Reference Manual
@section @command{ncra} netCDF Record Averager
@cindex averaging data
@cindex record average
@cindex record dimension
@cindex running average
@findex ncra

@noindent
SYNTAX
@example
ncra [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}][,[@var{subcycle}]]]] [-F]
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdf] [--hdr_pad @var{nbr}] 
[-L @var{dfl_lvl}] [-l @var{path}] [--mro] [-n @var{loop}] [--no_tmp_fl]
[-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all] [--rec_apn] [--rth_dbl|flt]
[-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] [-y @var{op_typ}]
[@var{input-files}] [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{ncra} averages record variables across an arbitrary number of 
@var{input-files}.
@cindex degenerate dimension
@cindex record dimension
The record dimension is, by default, retained as a degenerate 
@w{(size 1)} dimension in the output variables.
@xref{Statistics vs. Concatenation}, for a description of the
distinctions between the various statistics tools and concatenators. 
@cindex multi-file operators
@cindex standard input
@cindex @code{stdin}
As a multi-file operator, @command{ncra} will read the list of
@var{input-files} from @code{stdin} if they are not specified 
as positional arguments on the command line 
(@pxref{Large Numbers of Files}).

Input files may vary in size, but each must have a record dimension.
The record coordinate, if any, should be monotonic (or else non-fatal
warnings may be generated). 
@cindex hyperslab
Hyperslabs of the record dimension which include more than one file 
work correctly.
@cindex stride
@command{ncra} supports the @var{stride} argument to the @samp{-d}
hyperslab option (@pxref{Hyperslabs}) for the record dimension only,
@var{stride} is not supported for non-record dimensions.

@command{ncra} weights each record (e.g., time slice) in the
@var{input-files} equally.
@command{ncra} does not attempt to see if, say, the @code{time}
coordinate is irregularly spaced and thus would require a weighted
average in order to be a true time average.
@cindex operation types
@command{ncra} @emph{always averages} coordinate variables regardless of 
the arithmetic operation type performed on the non-coordinate variables. 
(@pxref{Operation Types}). 

@noindent
@html
<a name="xmp_ncra"></a> <!-- http://nco.sf.net/nco.html#xmp_ncra -->
@end html
EXAMPLES

Average files @file{85.nc}, @file{86.nc}, @w{@dots{} @file{89.nc}}
along the record dimension, and store the results in @file{8589.nc}: 
@cindex globbing
@cindex @code{NINTAP}
@cindex Processor
@cindex @acronym{CCM} Processor
@example
ncra 85.nc 86.nc 87.nc 88.nc 89.nc 8589.nc
ncra 8[56789].nc 8589.nc
ncra -n 5,2,1 85.nc 8589.nc
@end example
These three methods produce identical answers.
@xref{Specifying Input Files}, for an explanation of the distinctions
between these methods.

@cindex Fortran
Assume the files @file{85.nc}, @file{86.nc}, @w{@dots{} @file{89.nc}}
each contain a record coordinate @var{time} of length 12 defined such
that the third record in @file{86.nc} contains data from March 1986,
etc. 
@acronym{NCO} knows how to hyperslab the record dimension across files.
Thus, to average data from December, 1985 through February, 1986:
@example
ncra -d time,11,13 85.nc 86.nc 87.nc 8512_8602.nc
ncra -F -d time,12,14 85.nc 86.nc 87.nc 8512_8602.nc
@end example
@noindent
The file @file{87.nc} is superfluous, but does not cause an error.
The @samp{-F} turns on the Fortran (1-based) indexing convention.
@cindex stride
The following uses the @var{stride} option to average all the March
temperature data from multiple input files into a single output file
@example
ncra -F -d time,3,,12 -v temperature 85.nc 86.nc 87.nc 858687_03.nc
@end example
@xref{Stride}, for a description of the @var{stride} argument.

Assume the @var{time} coordinate is incrementally numbered such that
January, @w{@math{1985 = 1}} and December, @w{@math{1989 = 60}}.
Assuming @samp{??} only expands to the five desired files, the following 
averages June, 1985--June, 1989: 
@example
ncra -d time,6.,54. ??.nc 8506_8906.nc
@end example

@page
@html
<a name="ncrcat"></a> <!-- http://nco.sf.net/nco.html#ncrcat -->
@end html
@node ncrcat netCDF Record Concatenator, ncrename netCDF Renamer, ncra netCDF Record Averager, Operator Reference Manual
@section @command{ncrcat} netCDF Record Concatenator
@cindex concatenation
@cindex record concatenation
@findex ncrcat

@noindent
SYNTAX
@example
ncrcat [-3] [-4] [-6] [-7] [-A] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}][,[@var{subcycle}]]]] [-F]
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdr_pad @var{nbr}]
[-L @var{dfl_lvl}] [-l @var{path}] [--md5_digest] [-n @var{loop}] [--no_tmp_fl]
[-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all] [--rec_apn]
[-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-X ...] [-x] 
[@var{input-files}] [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{ncrcat} concatenates record variables across an arbitrary
number of @var{input-files}.
@cindex record dimension
The final record dimension is by default the sum of the lengths of the 
record dimensions in the input files.
@xref{Statistics vs. Concatenation}, for a description of the
distinctions between the various statistics tools and concatenators. 
@cindex multi-file operators
@cindex standard input
@cindex @code{stdin}
As a multi-file operator, @command{ncrcat} will read the list of
@var{input-files} from @code{stdin} if they are not specified 
as positional arguments on the command line 
(@pxref{Large Numbers of Files}).

Input files may vary in size, but each must have a record dimension.
The record coordinate, if any, should be monotonic (or else non-fatal
warnings may be generated).
@cindex hyperslab
Hyperslabs along the record dimension that span more than one file are  
handled correctly.
@cindex stride
@command{ncra} supports the @var{stride} argument to the @samp{-d}
hyperslab option for the record dimension only, @var{stride} is not
supported for non-record dimensions.

@findex ncpdq
@cindex packing
@cindex unpacking
@cindex @code{add_offset}
@cindex @code{scale_factor}
Concatenating a variable packed with different scales multiple datasets  
is beyond the capabilities of @command{ncrcat} (and @command{ncecat},
the other concatenator (@ref{Concatenation}).
@command{ncrcat} does not unpack data, it simply @emph{copies} the data
from the @var{input-files}, and the metadata from the @emph{first}
@var{input-file}, to the @var{output-file}. 
This means that data compressed with a packing convention must use
the identical packing parameters (e.g., @code{scale_factor} and
@code{add_offset}) for a given variable across @emph{all} input files.
Otherwise the concatenated dataset will not unpack correctly.
The workaround for cases where the packing parameters differ across
@var{input-files} requires three steps:
First, unpack the data using @command{ncpdq}.
Second, concatenate the unpacked data using @command{ncrcat}, 
Third, re-pack the result with @command{ncpdq}.

@cindex ARM conventions
@command{ncrcat} applies special rules to @acronym{ARM} convention time
fields (e.g., @code{time_offset}).
See @ref{ARM Conventions} for a complete description.

@noindent
@html
<a name="xmp_ncrcat"></a> <!-- http://nco.sf.net/nco.html#xmp_ncrcat -->
@end html
EXAMPLES

Concatenate files @file{85.nc}, @file{86.nc}, @w{@dots{} @file{89.nc}}
along the record dimension, and store the results in @file{8589.nc}: 
@cindex globbing
@cindex @code{NINTAP}
@cindex Processor
@cindex @acronym{CCM} Processor
@example
ncrcat 85.nc 86.nc 87.nc 88.nc 89.nc 8589.nc
ncrcat 8[56789].nc 8589.nc
ncrcat -n 5,2,1 85.nc 8589.nc
@end example
@noindent
These three methods produce identical answers.
@xref{Specifying Input Files}, for an explanation of the distinctions
between these methods.

@cindex Fortran
Assume the files @file{85.nc}, @file{86.nc}, @w{@dots{} @file{89.nc}}
each contain a record coordinate @var{time} of @w{length 12} defined
such that the third record in @file{86.nc} contains data from March
1986, etc. 
@acronym{NCO} knows how to hyperslab the record dimension across files. 
Thus, to concatenate data from December, 1985--February, 1986:
@example
ncrcat -d time,11,13 85.nc 86.nc 87.nc 8512_8602.nc
ncrcat -F -d time,12,14 85.nc 86.nc 87.nc 8512_8602.nc
@end example
@noindent
The file @file{87.nc} is superfluous, but does not cause an error.
When @command{ncra} and @command{ncrcat} encounter a file which does 
contain any records that meet the specified hyperslab criteria, they
disregard the file and proceed to the next file without failing.
The @samp{-F} turns on the Fortran (1-based) indexing convention.
@cindex stride

The following uses the @var{stride} option to concatenate all the March 
temperature data from multiple input files into a single output file
@example
ncrcat -F -d time,3,,12 -v temperature 85.nc 86.nc 87.nc 858687_03.nc
@end example
@xref{Stride}, for a description of the @var{stride} argument.

Assume the @var{time} coordinate is incrementally numbered such that
January, @w{1985 = 1} and December, @w{1989 = 60.}
Assuming @code{??} only expands to the five desired files, the following 
concatenates June, 1985--June, 1989: 
@example
ncrcat -d time,6.,54. ??.nc 8506_8906.nc
@end example

@page
@html
<a name="ncrename"></a> <!-- http://nco.sf.net/nco.html#ncrename -->
@end html
@node ncrename netCDF Renamer, ncwa netCDF Weighted Averager, ncrcat netCDF Record Concatenator, Operator Reference Manual
@section @command{ncrename} netCDF Renamer
@cindex renaming variables
@cindex renaming groups
@cindex renaming dimensions
@cindex renaming attributes
@cindex variable names
@cindex dimension names
@cindex attribute names
@cindex group names
@findex ncrename

@noindent
SYNTAX
@example
ncrename [-a @var{old_name},@var{new_name}] [-a @dots{}] [-D @var{dbg}] 
[-d @var{old_name},@var{new_name}] [-d @dots{}] [-g @var{old_name},@var{new_name}] [-g @dots{}] 
[-h] [--hdf] [--hdr_pad @var{nbr}] [-l @var{path}] [-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] 
[-v @var{old_name},@var{new_name}] [-v @dots{}]
@var{input-file} [[@var{output-file}]]
@end example
 
@noindent
DESCRIPTION

@cindex @kbd{.}
@command{ncrename} renames netCDF dimensions, variables, attributes, and
groups. 
Each object that has a name in the list of old names is renamed using
the corresponding name in the list of new names. 
All the new names must be unique. 
Every old name must exist in the input file, unless the old name is
preceded by the period (or ``dot'') character @samp{.}. 
The validity of @var{old_name} is not checked prior to the renaming. 
Thus, if @var{old_name} is specified without the the @samp{.} prefix and
is not present in @var{input-file}, @command{ncrename} will abort. 
The @var{new_name} should never be prefixed by a @samp{.} (or else the
period will be included as part of the new name).
The OPTIONS and EXAMPLES show how to select specific variables
whose attributes are to be renamed.

Although @command{ncrename} supports full pathnames for both
@var{old_name} and @var{new_name}, this is really ``window dressing''.
The full-path to @var{new_name} must be identical to the full-path to 
@var{old_name} in all classes of objects (attributes, variables,
dimensions, or groups).
In other words, @command{ncrename} can change only the local names
of objects, it cannot change the location of the object in the group
hierarchy within the file.
Hence using a full-path in @var{new_name} is redundant. 
The object name is the terminal path component of @var{new_name} and
this object must already exist in the group specified by the 
@var{old_name} path.

@cindex data safety
@cindex safeguards
@cindex temporary output files
@command{ncrename} is an exception to the normal @acronym{NCO} rule that
the user will be interactively prompted before an existing file is
changed, and that a temporary copy of an output file is constructed
during the operation. 
If only @var{input-file} is specified, then @command{ncrename} changes
the names of the @var{input-file} in place without prompting and without
creating a temporary copy of @code{input-file}.
This is because the renaming operation is considered reversible if the
user makes a mistake.
The @var{new_name} can easily be changed back to @var{old_name} by using 
@command{ncrename} one more time.

Note that renaming a dimension to the name of a dependent variable can
be used to invert the relationship between an independent coordinate
variable and a dependent variable. 
In this case, the named dependent variable must be one-dimensional and
should have no missing values. 
Such a variable will become a coordinate variable.

@cindex performance
@cindex operator speed
@cindex speed
@cindex execution time
According to the @cite{netCDF User Guide}, renaming properties in
netCDF files does not incur the penalty of recopying the entire file
when the @var{new_name} is shorter than the @var{old_name}.

@noindent
OPTIONS

@table @samp
@item -a @var{old_name},@var{new_name}
Attribute renaming. 
The old and new names of the attribute are specified with @samp{-a}
(or @samp{--attribute}) by the associated @var{old_name} and
@var{new_name} values.  
@cindex @code{global} attribute
@cindex global attributes
@cindex attributes, global
Global attributes are treated no differently than variable attributes.
This option may be specified more than once.
As mentioned above, all occurrences of the attribute of a given name
will be renamed unless the @samp{.} form is used, with one exception.
To change the attribute name for a particular variable, specify 
the @var{old_name} in the format @var{old_var_name@@old_att_name}.
The @samp{@@} symbol delimits the variable from the attribute name.
If the attribute is uniquely named (no other variables contain the
attribute) then the @var{old_var_name@@old_att_name} syntax is
redundant. 
The @var{var_nm} @code{global} has special significance---it indicates
that @var{att_nm} refers to a global or group attribute, and not to a
variable named @code{global}.
In other words, a @var{var_nm} of @code{global} is syntactically
equivalent to a @var{var_nm} that is empty.
The @var{var_name@@att_name} syntax is accepted, though not required,
for the @var{new_name}.

@item -d @var{old_name},@var{new_name}
Dimension renaming. 
The old and new names of the dimension are specified with @samp{-d}
(or @samp{--dmn}, @samp{--dimension}) by the associated @var{old_name}
and @var{new_name} values.  
This option may be specified more than once.
 
@item -g @var{old_name},@var{new_name}
Group renaming. 
The old and new names of the group are specified with @samp{-g}
(or @samp{--grp}, @samp{--group}) by the associated @var{old_name}
and @var{new_name} values.  
This option may be specified more than once.
This functionality is only available in @acronym{NCO} version 4.3.7
(October, 2013) or later, and only when built on netCDF library version
4.3.1-rc1 (August, 2013) or later. 
 
@item -v @var{old_name},@var{new_name}
Variable renaming. 
The old and new names of the variable are specified with @samp{-v}
(or @samp{--variable}) by the associated @var{old_name} and
@var{new_name} values.  
This option may be specified more than once.
@end table

@noindent
@html
<a name="xmp_ncrename"></a> <!-- http://nco.sf.net/nco.html#xmp_ncrename -->
@end html
EXAMPLES

Rename the variable @code{p} to @code{pressure} and @code{t} to
@code{temperature} in netCDF @file{in.nc}. 
In this case @code{p} must exist in the input file (or
@command{ncrename} will abort), but the presence of @code{t} is optional:
@example
ncrename -v p,pressure -v .t,temperature in.nc
@end example

Rename the attribute @code{long_name} to @code{largo_nombre} in the
variable @code{u}, and no other variables in netCDF @file{in.nc}. 
@example
ncrename -a u@@long_name,largo_nombre in.nc
@end example
 
Rename the group @code{g8} to @code{g20} in netCDF4 file
@file{in_grp.nc}:   
@example
ncrename -g g8,g20 in_grp.nc
@end example
 
Rename the variable @code{/g1/lon} to @code{longitude} in netCDF4
@file{in_grp.nc}:
@example
ncrename -v /g1/lon,longitude in_grp.nc
ncrename -v /g1/lon,/g1/longitude in_grp.nc # Alternate
@end example
 
@html
<a name="ncrename_crd"></a> <!-- http://nco.sf.net/nco.html#ncrename_crd -->
@end html
@cindex coordinate variables
@command{ncrename} does not automatically attach dimensions to variables of
the same name.
This is done to make renaming an easy way to change whether a variable
is a coordinate.
If you want to rename a coordinate variable so that it remains a
coordinate variable, you must separately rename both the dimension and
the variable: 
@example
ncrename -d lon,longitude -v lon,longitude in.nc
@end example
Unfortunately, the netCDF4 library has a longstanding bug (all versions
until 4.3.1-rc5 released in December, 2013) that causes @acronym{NCO} to
crash when performing this operation. 
Simultaneously renaming variables and dimensions in netCDF4 files with
earlier versions of netCDF is impossible; it must instead be done in two
separate @command{ncrename} invocations (e.g., first rename the
variable, then the dimension) to avoid triggering the libary bug.

A related bug causes unintended side-effects with @command{ncrename} 
also built with all versions of the netCDF4 library until 4.3.1-rc5
released in December, 2013):
Renaming @emph{either} a dimension @emph{or} its assosiated
coordinate variable (not both, which would fail as above) in a netCDF4 
file inadvertently @emph{does} rename both:
@example
# Demonstate bug in netCDF4/HDF5 library prior to netCDF-4.3.1-rc5
ncks -O -h -m -M -4 -v lat_T42 ~/nco/data/in.nc ~/foo.nc
ncrename -O -v lat_T42,lat ~/foo.nc ~/foo2.nc # Also renames dimension
ncrename -O -d lat_T42,lat ~/foo.nc ~/foo2.nc # Also renames variable
@end example
To avoid this faulty behavior, either build @acronym{NCO} with netCDF
version 4.3.1-rc5 or later, or convert the file to netCDF3 first,
then rename as intended, then convert back.

@cindex global attributes
@cindex attributes, global
@cindex @code{_FillValue}
@cindex @code{missing_value}
Create netCDF @file{out.nc} identical to @file{in.nc} except the
attribute @code{_FillValue} is changed to @code{missing_value}, 
the attribute @code{units} is changed to @code{CGS_units} (but only in
those variables which possess it), the attribute @code{hieght} is
changed to @code{height} in the variable @code{tpt}, and in the
variable @code{prs_sfc}, if it exists.
@example
ncrename -a _FillValue,missing_value -a .units,CGS_units \
  -a tpt@@hieght,height -a prs_sfc@@.hieght,height in.nc out.nc 
@end example
The presence and absence of the @samp{.} and @samp{@@} features
cause this command to execute successfully only if a number of 
conditions are met. 
All variables @emph{must} have a @code{_FillValue} attribute @emph{and} 
@code{_FillValue} must also be a global attribute.
The @code{units} attribute, on the other hand, will be renamed to
@code{CGS_units} wherever it is found but need not be present in
the file at all (either as a global or a variable attribute).
The variable @code{tpt} must contain the @code{hieght} attribute.
The variable @code{prs_sfc} need not exist, and need not contain the
@code{hieght} attribute.

Rename the global or group attribute @code{Convention} to
@code{Conventions}
@example
ncrename -a Convention,Conventions  in.nc # Variable and global atts.
ncrename -a .Convention,Conventions in.nc # Variable and global atts.
ncrename -a @@Convention,Conventions  in.nc # Global atts. only
ncrename -a @@.Convention,Conventions in.nc # Global atts. only
ncrename -a global@@Convention,Conventions   in.nc # Global atts. only
ncrename -a .global@@.Convention,Conventions in.nc # Global atts. only
@end example
The examples without the @code{@@} character attempt to change the
attribute name in both Global or Group and variable attributes.
The examples with the @code{@@} character attempt to change only 
global and group @code{Convention} attributes, and leave unchanged any
@code{Convention} attributes attached directly to variables.
Attributes prefixed with a period (@code{.Convention}) need not be
present. 
Attributes not prefixed with a period (@code{Convention}) must be
present. 
Variables prefixed with a period (@code{.} or @code{.global}) need not 
be present.  
Variables not prefixed with a period (@code{global}) must be present.  

@page
@html
<a name="ncwa"></a> <!-- http://nco.sf.net/nco.html#ncwa -->
@end html
@node ncwa netCDF Weighted Averager,  , ncrename netCDF Renamer, Operator Reference Manual
@section @command{ncwa} netCDF Weighted Averager
@cindex averaging data
@cindex weighted average
@cindex masked average
@cindex broadcasting variables
@findex ncwa

@noindent
SYNTAX
@example
ncwa [-3] [-4] [-6] [-7] [-A] [-a @var{dim}[,@dots{}]] [-B @var{mask_cond}] [-b] [-C] [-c]
[--cnk_dmn nm,sz] [--cnk_map map] [--cnk_plc plc] [--cnk_scl sz]
[-D @var{dbg}] [-d @var{dim},[@var{min}][,[@var{max}][,[@var{stride}]]] [-F]
[-G @var{gpe_dsc}] [-g @var{grp}[,@dots{}]] [-h] [--hdr_pad @var{nbr}] [-I]
[-L @var{dfl_lvl}] [-l @var{path}] [-M @var{mask_val}] [-m @var{mask_var}] [-N] [--no_tmp_fl]
[-O] [-o @var{output-file}] [-p @var{path}] [-R] [-r] [--ram_all] [--rth_dbl|flt]
[-T @var{mask_comp}] [-t @var{thr_nbr}] [--unn] [-v @var{var}[,@dots{}]] [-w @var{weight}]
[-X ...] [-x] [-y @var{op_typ}]
@var{input-file} [@var{output-file}]
@end example

@noindent
DESCRIPTION

@command{ncwa} averages variables in a single file over arbitrary
dimensions, with options to specify weights, masks, and normalization.   
@xref{Statistics vs. Concatenation}, for a description of the
distinctions between the various statistics tools and concatenators. 
The default behavior of @command{ncwa} is to arithmetically average
every numerical variable over all dimensions and to produce a scalar 
result for each. 

@cindex degenerate dimension
Averaged dimensions are, by default, eliminated as dimensions.
Their corresponding coordinates, if any, are output as scalar
variables. 
The @samp{-b} switch (and its long option equivalents @samp{--rdd} and 
@samp{--retain-degenerate-dimensions}) causes @command{ncwa} to retain
averaged dimensions as degenerate (@w{size 1}) dimensions.
This maintains the association between a dimension (or coordinate) and
variables after averaging and simplifies, for instance, later
concatenation along the degenerate dimension. 

To average variables over only a subset of their dimensions, specify
these dimensions in a comma-separated list following @samp{-a}, e.g.,
@samp{-a time,lat,lon}. 
@cindex arithmetic operators
@cindex hyperslab
@cindex @code{-d @var{dim},[@var{min}][,[@var{max}]]}
As with all arithmetic operators, the operation may be restricted to
an arbitrary hypserslab by employing the @samp{-d} option
(@pxref{Hyperslabs}). 
@command{ncwa} also handles values matching the variable's
@code{_FillValue} attribute correctly. 
Moreover, @command{ncwa} understands how to manipulate user-specified
weights, masks, and normalization options.
With these options, @command{ncwa} can compute sophisticated averages
(and integrals) from the command line. 

@html
<a name="-w"></a> <!-- http://nco.sf.net/nco.html#-w -->
<a name="wgt"></a> <!-- http://nco.sf.net/nco.html#wgt -->
@end html
@cindex @code{-w @var{weight}}
@cindex @code{--weight @var{weight}}
@cindex @code{--wgt_var @var{weight}}
@cindex @code{-m @var{mask_var}}
@cindex @code{--mask-variable @var{mask_var}}
@cindex @code{--mask_variable @var{mask_var}}
@cindex @code{--msk_nm @var{mask_var}}
@cindex @code{--msk_var @var{mask_var}}
@cindex @code{-B @var{mask_cond}}
@cindex @code{--msk_cnd @var{mask_cond}}
@cindex @code{--mask_condition @var{mask_cond}}
@var{mask_var} and @var{weight}, if specified, are broadcast to conform
to the variables being averaged. 
@cindex rank
The rank of variables is reduced by the number of dimensions which they
are averaged over.  
Thus arrays which are one dimensional in the @var{input-file} and are
averaged by @command{ncwa} appear in the @var{output-file} as scalars.
This allows the user to infer which dimensions may have been averaged.
Note that that it is impossible for @command{ncwa} to make make a
@var{weight} or @var{mask_var} of rank @var{W} conform to a @var{var} of
rank @var{V} if @var{W > V}.
This situation often arises when coordinate variables (which, by
definition, are one dimensional) are weighted and averaged.
@command{ncwa} assumes you know this is impossible and so @command{ncwa}
does not attempt to broadcast @var{weight} or @var{mask_var} to conform
to @var{var} in this case, nor does @command{ncwa} print a warning
message telling you this, because it is so common.  
Specifying @var{dbg > 2} does cause @command{ncwa} to emit warnings in
these situations, however.

Non-coordinate variables are always masked and weighted if specified.
Coordinate variables, however, may be treated specially.
By default, an averaged coordinate variable, e.g., @code{latitude},
appears in @var{output-file} averaged the same way as any other variable 
containing an averaged dimension.
In other words, by default @command{ncwa} weights and masks
coordinate variables like all other variables.  
This design decision was intended to be helpful but for some
applications it may be preferable not to weight or mask coordinate
variables just like all other variables.   
Consider the following arguments to @command{ncwa}: 
@code{-a latitude -w lat_wgt -d latitude,0.,90.} where @code{lat_wgt} is
a weight in the @code{latitude} dimension.
Since, by default @command{ncwa} weights coordinate variables, the
value of @code{latitude} in the @var{output-file} depends on the weights 
in @var{lat_wgt} and is not likely to @w{be 45.0}, the midpoint latitude
of the hyperslab.
@cindex coordinate variable
@cindex @code{-I}
Option @samp{-I} overrides this default behavior and causes
@command{ncwa} not to weight or mask coordinate variables
@footnote{The default behavior of (@samp{-I}) changed on
19981201---before this date the default was not to weight or mask
coordinate variables.}.
In the above case, this causes the value of @code{latitude} in the
@var{output-file} to @w{be 45.0}, an appealing result.
Thus, @samp{-I} specifies simple arithmetic averages for the coordinate
variables. 
In the case of latitude, @samp{-I} specifies that you prefer to archive
the arithmetic mean latitude of the averaged hyperslabs rather than the 
area-weighted mean latitude.
@footnote{If @code{lat_wgt} contains Gaussian weights then the value of 
@code{latitude} in the @var{output-file} will be the area-weighted
centroid of the hyperslab. 
For the example given, this is about @w{30 degrees.}}.  

@cindex average
@cindex operation types
As explained in @xref{Operation Types}, @command{ncwa} 
@emph{always averages} coordinate variables regardless of the arithmetic
operation type performed on the non-coordinate variables. 
This is independent of the setting of the @samp{-I} option.
The mathematical definition of operations involving rank reduction 
is given above (@pxref{Operation Types}).

@menu
* Mask condition::
* Normalization and Integration::
@end menu

@html
<a name="mask"></a> <!-- http://nco.sf.net/nco.html#mask -->
<a name="msk"></a> <!-- http://nco.sf.net/nco.html#msk -->
<a name="-m"></a> <!-- http://nco.sf.net/nco.html#-m -->
@end html
@node Mask condition, Normalization and Integration, ncwa netCDF Weighted Averager, ncwa netCDF Weighted Averager
@subsection Mask condition
@cindex mask condition
@cindex truth condition
@tex
Each $\xxx_{\idx}$ also has an associated masking
weight~$\mskflg_{\idx}$ whose value is~0 or~1 (false or true).
The value of~$\mskflg_{\idx}$ is always~1 unless a @var{mask\_var} is
specified (with 
@samp{-m}).
As noted above, @var{mask\_var} is broadcast, if possible, to conform 
to the variable being averaged.  
In this case, the value of~$\mskflg_{\idx}$ depends on the 
@dfn{mask condition} also known as the @dfn{truth condition}.
As expected, $\mskflg_{\idx} = 1$ when the mask condition is
@dfn{true} and $\mskflg_{\idx} = 0$ otherwise.   
@end tex

@cindex @code{--op_rlt @var{mask_comp}}
@cindex @code{--mask_comparator @var{mask_comp}}
@cindex @code{--msk_cmp_typ @var{mask_comp}}
@cindex @code{--msk_cnd_sng @var{mask_cond}}
@cindex @code{--mask_condition @var{mask_cond}}
@cindex @code{-B @var{mask_cond}}
The mask condition has the syntax @math{@var{mask_var}}
@math{@var{mask_comp}} @math{@var{mask_val}}. 
The preferred method to specify the mask condition is in one string with  
the @samp{-B} or @samp{--mask_condition} switches.
The older method is to use the three switches @samp{-m}, @samp{-T}, and
@samp{-M} to specify the @var{mask_var}, @var{mask_comp}, and 
@var{mask_val}, respectively.  
@footnote{The three switches @samp{-m}, @samp{-T}, and @samp{-M} are
maintained for backward compatibility and may be deprecated in the
future.
It is safest to write scripts using @samp{--mask_condition}.}.
The @var{mask_condition} string is automatically parsed into its three
constituents @var{mask_var}, @var{mask_comp}, and @var{mask_val}.

@cindex comparator
Here @var{mask_var} is the name of the masking variable (specified with 
@samp{-m}, @samp{--mask-variable}, @samp{--mask_variable},
@samp{--msk_nm}, or @samp{--msk_var}).  
The truth @var{mask_comp} argument (specified with @samp{-T},
@samp{--mask_comparator}, @samp{--msk_cmp_typ}, or @samp{--op_rlt} may 
be any one of the six arithmetic comparators: @kbd{eq}, @kbd{ne},
@kbd{gt}, @kbd{lt}, @kbd{ge}, @kbd{le}. 
@set flg
@tex
These are the Fortran-style character abbreviations for the logical 
comparisons $=$, $\neq$, $>$, $<$, $\ge$, $\le$. 
@clear flg
@end tex
@ifinfo
These are the Fortran-style character abbreviations for the logical 
comparisons @math{==}, @math{!=}, @math{>}, @math{<}, @math{>=},
@math{<=}. 
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
These are the Fortran-style character abbreviations for the logical 
comparisons @kbd{==}, @kbd{!=}, @kbd{>}, @kbd{<}, @kbd{>=},
@clear flg
@end ifset
The mask comparator defaults to @kbd{eq} (equality).
@cindex @code{--mask-value @var{mask_val}}
@cindex @code{--mask_value @var{mask_val}}
@cindex @code{--msk_val @var{mask_val}}
The @var{mask_val} argument to @samp{-M} (or @samp{--mask-value}, or
@samp{--msk_val}) is the right hand side of the
@dfn{mask condition}.
Thus for the @var{i}'th element of the hyperslab to be averaged,
the mask condition is 
@set flg
@tex
{\it mask$_{\idx}$ mask\_comp mask\_val}.
@clear flg
@end tex
@ifinfo
@math{mask(i)} @var{mask_comp} @var{mask_val}.
@clear flg
@end ifinfo
@ifset flg
@c texi2html does not like @math{}
@var{mask}(@var{i}) @var{mask_comp} @var{mask_val}.
@clear flg
@end ifset

@tex
Each~$\xxx_{\idx}$ is also associated with an additional
weight~$\wgt_{\idx}$ whose value may be user-specified.
The value of~$\wgt_{\idx}$ is identically~1 unless the user specifies a 
weighting variable @var{weight} (with @samp{-w}, @samp{--weight}, or
@samp{--wgt\_var}). 
In this case, the value of~$\wgt_{\idx}$ is determined by the
@var{weight} variable in the @var{input-file}. 
As noted above, @var{weight} is broadcast, if possible, to conform 
to the variable being averaged.  

$\tllnbr$ is the number of input elements $\xxx_{\idx}$ which actually
contribute to output element $\xxx_{\jjj}$.
$\tllnbr$ is also known as the @dfn{tally} and is defined as 
$$
\tllnbr = \sum_{\idx=1}^{\idx=\lmnnbr} \mssflg_{\idx} \mskflg_{\idx} 
$$
$\tllnbr$ is identical to the denominator of the generic averaging
expression except for the omission of the weight $\wgt_{\idx}$.
Thus $\tllnbr = \lmnnbr$ whenever no input points are missing values or
are masked.  
Whether an element contributes to the output, and thus increments
$\tllnbr$ by one, has more to do with the above two criteria (missing
value and masking) than with the numeric value of the element per se.
For example, $\xxx_{\idx}=0.0$ does contribute to $\xxx_{\jjj}$
(assuming the @code{_FillValue} attribute is not~0.0 and location
$\idx$ is not masked). 
The value $\xxx_{\idx}=0.0$ will not change the numerator of the generic 
averaging expression, but it will change the denominator (unless its
weight $\wgt_{\idx}=0.0$ as well).
@end tex

@html
<a name="nrm"></a> <!-- http://nco.sf.net/nco.html#nrm -->
<a name="ntg"></a> <!-- http://nco.sf.net/nco.html#ntg -->
@end html
@node Normalization and Integration,  , Mask condition, ncwa netCDF Weighted Averager
@subsection Normalization and Integration
@cindex normalization
@cindex @code{-N}
@cindex @code{numerator}
@cindex integration
@cindex dot product
@command{ncwa} has one switch which controls the normalization of the
averages appearing in the @var{output-file}.
Short option @samp{-N} (or long options @samp{--nmr} or
@samp{--numerator}) prevents @command{ncwa} from dividing the weighted
sum of the variable (the numerator in the averaging expression) by the
weighted sum of the weights (the denominator in the averaging
expression).   
Thus @samp{-N} tells @command{ncwa} to return just the numerator of the
arithmetic expression defining the operation (@pxref{Operation Types}). 

With this normalization option, @command{ncwa} can integrate variables.
Averages are first computed as sums, and then normalized to obtain the
average. 
The original sum (i.e., the numerator of the expression in
@ref{Operation Types}) is output if default normalization is turned off
(@w{with @samp{-N}}). 
This sum is the integral (not the average) over the specified 
(@w{with @samp{-a}}, or all, if none are specified) dimensions.
The weighting variable, if specified (@w{with @samp{-w}}), plays the
role of the differential increment and thus permits more sophisticated 
integrals (i.e., weighted sums) to be output.
For example, consider the variable 
@code{lev} where @math{@var{lev} = [100,500,1000]} weighted by
the weight @code{lev_wgt} where @math{@var{lev_wgt} = [10,2,1]}.
@cindex dot product
The vertical integral of @code{lev}, weighted by @code{lev_wgt}, 
is the dot product of @var{lev} and @var{lev_wgt}. 
That this is @w{is 3000.0} can be seen by inspection and verified with 
the integration command
@example
ncwa -N -a lev -v lev -w lev_wgt in.nc foo.nc;ncks foo.nc
@end example

@ignore
fxm TODO nco702
As explained in @xref{Operation Types}, @command{ncwa} 
@emph{always averages} coordinate variables regardless of the arithmetic 
operation type performed on the non-coordinate variables. 
The single exception is shown in the above example.
The @samp{-N} switch turns off normalization so variables which are to be
averaged, including coordinate variables, are not normalized.
This is equivalent to summation or integration.
@end ignore

@ignore
@c NB: these masking features are deprecated
The second normalization option tells @command{ncwa} to multiply the
weighted average the variable (given by the averaging expression)
by the @w{tally, @var{M}}.
Thus this option is similar to integration---multiplying the mean value
of a quantity by the number of gridpoints to which it applies.

The third normalization option is equivalent to specifying the first two
options simultaneously. 
In other words this option causes @command{ncwa} to return 
@w{@var{M} times} the numerator of the generic averaging expression.  
With these normalization options, @command{ncwa} can compute
sophisticated averages (and integrals) from the command line.
@end ignore

@noindent
@html
<a name="xmp_ncwa"></a> <!-- http://nco.sf.net/nco.html#xmp_ncwa -->
@end html
EXAMPLES

Given file @file{85_0112.nc}:
@example
netcdf 85_0112 @{
dimensions:
        lat = 64 ;
        lev = 18 ;
        lon = 128 ;
        time = UNLIMITED ; // (12 currently)
variables:
        float lat(lat) ;
        float lev(lev) ;
        float lon(lon) ;
        float time(time) ;
        float scalar_var ;
        float three_dmn_var(lat, lev, lon) ;
        float two_dmn_var(lat, lev) ;
        float mask(lat, lon) ;
        float gw(lat) ;
@} 
@end example

Average all variables in @file{in.nc} over all dimensions and store
results in @file{out.nc}:
@example
ncwa in.nc out.nc
@end example
@noindent
All variables in @file{in.nc} are reduced to scalars in @file{out.nc} 
since @command{ncwa} averages over all dimensions unless otherwise
specified (with @samp{-a}).

Store the zonal (longitudinal) mean of @file{in.nc} in @file{out.nc}:
@example
ncwa -a lon in.nc out1.nc
ncwa -a lon -b in.nc out2.nc
@end example
@noindent
@cindex degenerate dimension
The first command turns @code{lon} into a scalar and the second retains 
@code{lon} as a degenerate dimension in all variables.
@example
% ncks -C -H -v lon out1.nc
lon = 135
% ncks -C -H -v lon out2.nc
lon[0] = 135
@end example
In either case the tally is simply the size of @code{lon}, i.e., 180
for the @file{85_0112.nc} file described by the sample header above.

@cindex @code{gw}
@cindex Gaussian weights
@cindex climate model
Compute the meridional (latitudinal) mean, with values weighted by
the corresponding element of @var{gw}
@footnote{@code{gw} stands for @dfn{Gaussian weight} in many
climate models.}: 
@example
ncwa -w gw -a lat in.nc out.nc
@end example
@noindent
Here the tally is simply the size of @code{lat}, @w{or 64.}
The sum of the Gaussian weights @w{is 2.0.}

Compute the area mean over the tropical Pacific:
@example
ncwa -w gw -a lat,lon -d lat,-20.,20. -d lon,120.,270. in.nc out.nc
@end example
@noindent
Here the tally is 
@set flg
@tex
$64 \times 128 = 8192$.
@clear flg
@end tex
@ifset flg
64 times 128 = 8192.
@clear flg
@end ifset

@cindex @code{ORO}
@cindex climate model
Compute the area-mean over the globe using only points for which 
@set flg
@tex
$ORO < 0.5$
@clear flg
@end tex
@ifset flg
@var{ORO} < 0.5
@clear flg
@end ifset
@footnote{@code{ORO} stands for @dfn{Orography} in some climate models
and in those models @math{@var{ORO} < 0.5} selects ocean gridpoints.}: 
@example
ncwa -B 'ORO < 0.5'      -w gw -a lat,lon in.nc out.nc
ncwa -m ORO -M 0.5 -T lt -w gw -a lat,lon in.nc out.nc
@end example
@noindent
It is considerably simpler to specify the complete @var{mask_cond} with
the single string argument to @samp{-B} than with the three separate
switches @samp{-m}, @samp{-T}, and @samp{-M}
@footnote{Unfortunately the @samp{-B} and @samp{--mask_condition}
options are unsupported on Windows (with the @acronym{MVS} compiler),
which lacks a free, standard parser and lexer.}. 
If in doubt, enclose the @var{mask_cond} within quotes since some
of the comparators have special meanings to the shell.

Assuming 70% of the gridpoints are maritime, then here the tally is
@set flg
@tex
$0.70 \times 8192 \approx 5734$.
@clear flg
@end tex
@ifset flg
0.70 times 8192 = 5734.
@clear flg
@end ifset

Compute the global annual mean over the maritime tropical Pacific:
@example
ncwa -B 'ORO < 0.5'      -w gw -a lat,lon,time \
  -d lat,-20.0,20.0 -d lon,120.0,270.0 in.nc out.nc
ncwa -m ORO -M 0.5 -T lt -w gw -a lat,lon,time \
  -d lat,-20.0,20.0 -d lon,120.0,270.0 in.nc out.nc
@end example
Further examples will use the one-switch specification of
@var{mask_cond}.  

Determine the total area of the maritime tropical Pacific, assuming
the variable @var{area} contains the area of each gridcell
@example
ncwa -N -v area -B 'ORO < 0.5' -a lat,lon \
  -d lat,-20.0,20.0 -d lon,120.0,270.0 in.nc out.nc
@end example
Weighting @var{area} (e.g., by @var{gw}) is not appropriate because
@var{area} is @emph{already} area-weighted by definition.
Thus the @samp{-N} switch, or, equivalently, the @samp{-y ttl} switch, 
correctly integrate the cell areas into a total regional area.

@cindex mask condition
@cindex truth condition
Mask a file to contain @var{_FillValue} everywhere except where
@math{@var{thr_min} <= @var{msk_var} <= @var{thr_max}}:
@example
# Set masking variable and its scalar thresholds
export msk_var='three_dmn_var_dbl' # Masking variable
export thr_max='20' # Maximum allowed value
export thr_min='10' # Minimum allowed value
ncecat -O in.nc out.nc # Wrap out.nc in degenerate "record" dimension
ncwa -O -a record -B "$@{msk_var@} <= $@{thr_max@}" out.nc out.nc
ncecat -O out.nc out.nc # Wrap out.nc in degenerate "record" dimension
ncwa -O -a record -B "$@{msk_var@} >= $@{thr_min@}" out.nc out.nc
@end example
After the first use of @command{ncwa}, @file{out.nc} contains
@var{_FillValue} where @code{$@{msk_var@} >= $@{thr_max@}}.
The process is then repeated on the remaining data to filter out 
points where @code{$@{msk_var@} <= $@{thr_min@}}.
The resulting @file{out.nc} contains valid data only
where @math{@var{thr_min} <= @var{msk_var} <= @var{thr_max}}.

@html
<a name="ctr"></a> <!-- http://nco.sf.net/nco.html#ctr -->
@end html
@node Contributing, Quick Start, Operator Reference Manual, Top
@chapter Contributing
@cindex contributing
We welcome contributions from anyone.
The project homepage at @uref{https://sf.net/projects/nco}
contains more information on how to contribute. 

@cindex PayPal
Financial contributions to @acronym{NCO} development may be made through  
@uref{https://www.paypal.com/xclick/business=zender%40uci.edu&item_name=NCO+development&item_number=nco_dnt_dvl&no_note=1&tax=0&currency_code=USD, PayPal}.
@acronym{NCO} has been shared for over @w{10 years} yet only two 
users have contributed any money to the developers
@footnote{
@cindex chocolate
Happy users have sent me a few gifts, though.
This includes a box of imported chocolate.
Mmm.
Appreciation and gifts are definitely better than money.
Naturally, I'm too lazy to split and send gifts to the other developers.
However, unlike some @acronym{NCO} developers, I have a steady "real job".
My intent is to split monetary donations among the active developers
and to send them their shares via PayPal.}. 
So you could be the third!

@html
<a name="dvl"></a> <!-- http://nco.sf.net/nco.html#dvl -->
<a name="cnt"></a> <!-- http://nco.sf.net/nco.html#cnt -->
<a name="ppl"></a> <!-- http://nco.sf.net/nco.html#ppl -->
@end html
@menu
* Contributors::
* Proposals for Institutional Funding::
@end menu

@node Contributors, Proposals for Institutional Funding, Contributing, Contributing
@section Contributors
@acronym{NCO} would not exist without the dedicated efforts of the
remarkable software engineers who conceive, develop, and
maintain netCDF, UDUnits, and OPeNDAP.
@cindex Russ Rew
@cindex John Caron
@cindex Glenn Davis
@cindex Steve Emmerson
@cindex James Gallagher
@cindex Ed Hartnett
@cindex Dennis Heimbigner
Since 1995 @acronym{NCO} has received support from, I believe, the
entire staff of all these projects, including 
Russ Rew, 
John Caron,
Glenn Davis, 
Steve Emmerson, 
James Gallagher, 
Ed Hartnett, 
and Dennis Heimbigner.
In addition to their roles in maintaining the software stack on which
@acronym{NCO} perches, Yertl-like, some of these gentlemen have advised
or contributed to @acronym{NCO} specifically. That support is
acknowledged separately below. 

@cindex contributors
The primary contributors to @acronym{NCO} development have been:
@table @asis
@cindex Charlie Zender
@item Charlie Zender
All concept, design and implementation from 1995-2000.
Since then autotools, bug-squashing, @acronym{CDL}, chunking,
documentation, anchoring, recursion, @acronym{GPE}, packing,
@acronym{NCO} library redesign, @command{ncap2} features,
@command{ncbo}, @command{ncpdq}, SMP threading and MPI parallelization,
netCDF4 integration, external funding, project management, science
research, releases. 
@cindex Henry Butowsky
@item Henry Butowsky
Non-linear operations and @code{min()}, @code{max()}, @code{total()}
support in @command{ncra} and @command{ncwa}. 
Type conversion for arithmetic.
Migration to netCDF3 API.
@command{ncap2} parser, lexer, @acronym{GSL}-support, @w{and I/O}.
Multislabbing algorithm.
Variable wildcarding.
Numerous hacks.
@command{ncap2} language.
@cindex Rorik Peterson
@item Rorik Peterson
Original autotool build support. 
Long command-line options.
Original UDUnits support.
Debianization.
Numerous bug-fixes.
@cindex Daniel Wang
@item Daniel Wang
Script Workflow Analysis for MultiProcessing (SWAMP).
RPM support.
@cindex Harry Mangalam
@item Harry Mangalam
Benchmarking.
OPeNDAP configuration.
@cindex Pedro Vicente
@item Pedro Vicente
Windows Visual Studio support.
netCDF4 groups.
@cindex Russ Rew
@item Russ Rew
Advice on NCO structural algorithms
@cindex Brian Mays
@item Brian Mays
Original packaging for Debian @acronym{GNU}/Linux, @command{nroff} man pages.
@cindex George Shapovalov
@item George Shapovalov
Packaging for Gentoo @acronym{GNU}/Linux.
@cindex Bill Kocik
@item Bill Kocik
Memory management.
@cindex Len Makin
@item Len Makin
NEC SX architecture support.
@cindex Jim Edwards
@item Jim Edwards
AIX architecture support.
@cindex Juliana Rew
@item Juliana Rew
Compatibility with large @acronym{PID}s.
@cindex Karen Schuchardt
@item Karen Schuchardt
Auxiliary coordinate support.
@cindex Gayathri Venkitachalam
@item Gayathri Venkitachalam
@acronym{MPI} implementation.
@cindex Scott Capps
@item Scott Capps
Large work-load testing
@cindex Peter Campbell
@cindex Martin Dix
@cindex Mark Flanner
@cindex Markus Liebig
@cindex Keith Lindsay
@cindex Stu Muller
@cindex Mike Page
@cindex Martin Schmidt
@cindex Lori Sentman
@cindex Michael Schulz
@cindex Gary Strand
@cindex Andrew Wittenberg
@cindex George White
@cindex Remik Ziemlinski
@item Peter Campbell, Martin Dix, Mark Flanner, Markus Liebig, Keith Lindsay, Mike Page, Martin Schmidt, Michael Schulz, Lori Sentman, Gary Strand, George White Andrew Wittenberg, Remik Ziemlinski
Excellent bug reports and feature requests.
@cindex Daniel Baumann
@cindex Nick Bower
@cindex Luk Claes
@cindex Barry deFreese
@cindex Aleksandar Jelenak
@cindex Francesco Lovergine
@cindex Matej Vela
@item Daniel Baumann, Nick Bower, Luk Claebs, Barry deFreese, Aleksandar Jelenak, Francesco Lovergine, Matej Vela
Debian packaging
@cindex Patrice Dumas
@cindex Ed Hill
@cindex Orion Powlawski
@item Patrice Dumas, Ed Hill, Orion Poplawski
RedHat packaging
@cindex George Shapavalov
@cindex Patrick Kursawe
@item George Shapavalov, Patrick Kursawe
Gentoo packaging
@cindex Filipe Fernandes
@item Filipe Fernandes
OpenSuse packaging
@cindex Alexander Hansen
@cindex Takeshi Enomoto
@item Takeshi Enomoto, Alexander Hansen
Mac OS packaging
@cindex Eric Blake
@item Eric Blake
Autoconf/M4 help
@cindex Gavin Burris
@cindex Kyle Wilcox
@item Gavin Burris, Kyle Wilcox
RHEL and CentOS build scripts and bug reports.
@cindex Andrea Cimatoribus
@item Andrea Cimatoribus
@acronym{NCO} Spiral Logo
@cindex Martin Otte
@cindex Etienne Tourigny
@item Martin Otte, Etienne Tourigny
Single bug reports and fixes
@cindex Wenshan Wang
@item Wenshan Wang
@acronym{CMIP5} and @acronym{MODIS} processing documentation.
@end table
Please let me know if your name was omitted!

@html
<a name="prp"></a> <!-- http://nco.sf.net/nco.html#prp -->
<a name="prp_sei"></a> <!-- http://nco.sf.net/nco.html#prp_sei -->
<a name="fnd"></a> <!-- http://nco.sf.net/nco.html#fnd -->
@end html
@menu
* Proposals for Institutional Funding::  
@end menu

@node Proposals for Institutional Funding,  , Contributors, Contributing
@section Proposals for Institutional Funding
@cindex funding
@cindex proposals
@cindex @acronym{NSF}
@cindex server-side processing
@cindex Distributed Data Reduction & Analysis
@cindex Scientific Data Operators
@cindex @acronym{DDRA}
@cindex Server-Side Distributed Data Reduction & Analysis
@cindex @acronym{SSDDRA}
@cindex @acronym{CCSM}
@cindex @acronym{IPCC}
@cindex @acronym{NSF}
@cindex @acronym{SDO}
@cindex @acronym{SEIII}
@cindex OptIPuter
@acronym{NSF} has funded a
@uref{http://nco.sf.net#prp_sei, project}
to improve Distributed Data Reduction & Analysis (@acronym{DDRA}) by
evolving @acronym{NCO} into a suite of Scientific Data Operators called 
@acronym{SDO}.
@cindex parallelism
The two main components of this project are @acronym{NCO} parallelism
(OpenMP, @acronym{MPI}) and Server-Side @acronym{DDRA}
(@acronym{SSDDRA}) implemented through extensions to @acronym{OPeNDAP} 
and netCDF4. 
This project will dramatically reduce bandwidth usage for @acronym{NCO}
@acronym{DDRA}. 

@cindex @acronym{NASA}
@cindex @acronym{NRA}
@cindex @acronym{HDF}
With this first @acronym{NCO} proposal funded, the content of the
next @acronym{NCO} proposal is clear.
We are interested in obtaining @acronym{NASA} support for
@acronym{HDF}-specific enhancements to @acronym{NCO}. 
We plan to submit a proposal to the next suitable @acronym{NASA}
@acronym{NRA} or @acronym{NSF} opportunity. 

We are considering other interesting ideas for still more proposals.
Please contact us if you wish to be involved with any future
@acronym{NCO}-related proposals.  
Comments on the proposals and letters of support are also very welcome.

@html
<a name="quicksrt"></a> <!-- http://nco.sf.net/nco.html#quicksrt -->
@end html
@node Quick Start, CMIP5 Example, Contributing, Top
@chapter Quick Start
@cindex Quick Start
Simple examples in Bash shell scripts showing how to average data with
different file structures.  
Here we include monthly, seasonal and annual average with daily or
monthly data in either one file or multiple files. 

@menu
* Daily data in one file::
* Monthly data in one file::
* One time point one file::
* Multiple files with multiple time points::
@end menu

@node Daily data in one file, Monthly data in one file, Quick Start, Quick Start
@section Daily data in one file
@cindex daily data
Suppose we have daily data from Jan 1st, 1990 to Dec. 31, 2005 in the
file of @file{in.nc} with the record dimension as @code{time}.

@noindent
@strong{Monthly average:}
@cindex monthly average
@cindex average
@cindex time-averaging
@example
for yyyy in @{1990..2005@}; do      # Loop over years
  for moy in @{1..12@}; do          # Loop over months
    mm=$( printf "%02d" $@{moy@} )  # Change to 2-digit format

    # Average specific month yyyy-mm
    ncra -O -d time,"$@{yyyy@}-$@{mm@}-01","$@{yyyy@}-$@{mm@}-31" \
         in.nc in_$@{yyyy@}$@{mm@}.nc
  done
done

# Concatenate monthly files together
ncrcat -O in_??????.nc out.nc
@end example

@noindent
@strong{Annual average:}
@cindex annual average from daily data
@cindex average
@cindex time-averaging
@example
for yyyy in @{1990..2005@}; do      # Loop over years
  ncra -O -d time,"$@{yyyy@}-01-01","$@{yyyy@}-12-31" in.nc in_$@{yyyy@}.nc
done

# Concatenate annual files together
ncrcat -O in_????.nc out.nc
@end example
The @option{-O} switch means to overwrite the pre-existing files (@pxref{Batch Mode}).
The @option{-d} option is to specify the range of hyperslabs (@pxref{Hyperslabs}).
There are detailed instructions on @command{ncra} (@pxref{ncra netCDF Record Averager} and @command{ncrcat} (@pxref{ncrcat netCDF Record Concatenator}).
@acronym{NCO} supports UDUnits so that we can use readable dates as time dimension (@pxref{UDUnits Support}).

@node Monthly data in one file, One time point one file, Daily data in one file, Quick Start
@section Monthly data in one file
@cindex monthly data
Inside the input file @file{in.nc}, the record dimension @code{time} is from Jan 1990 to Dec 2005.

@noindent
@strong{Seasonal average (e.g., DJF):}
@cindex seasonal average
@cindex average
@cindex time-averaging
@example
ncra -O --mro -d time,"1990-12-01",,12,3 in.nc out.nc
@end example

@noindent
@strong{Annual average:}
@cindex annual average from monthly data
@cindex average
@cindex time-averaging
@example
ncra -O --mro -d time,,,12,12 in.nc out.nc
@end example
Here we use the subcycle feature (i.e., the number after the fourth comma: @samp{3} in the seasonal example and the second @samp{12} in the annual example) 
to retrieve groups of records separated by regular intervals (@pxref{Subcycle}).
The option @option{--mro} switches @command{ncra} to produce a Multi-Record Output instead of a single-record output.
For example, assume @var{snd} is a 3D array with dimensions @code{time} * @code{latitude} * @code{longitude} 
and @code{time} includes every month from Jan. 1990 to Dec. 2005, 192 months as total, which are 16 years.
Let's look at the following two command lines.
@example
ncra --mro -v snd -d time,"1990-12-01",,12,3 in.nc out_mro.nc
ncra -v snd -d time,"1990-12-01",,12,3 in.nc out_sro.nc
@end example
In the first output file, @file{out_mro.nc}, @var{snd} is still a 3D array with dimensions @code{time} * @code{latitude} * @code{longitude},
but the length of @code{time} now is 16, meaning 16 winters.
In the second output file, @file{out_sro.nc}, the length of @code{time} is @w{only 1}.
It is now the average of all the 16 winters.

when using @samp{-d @var{dim},min[,max]} to specify the hyperslabs,
you can leave it blank if you want to include the minimum or the maximum of the data, like we did above.

@node One time point one file, Multiple files with multiple time points, Monthly data in one file, Quick Start
@section One time point one file
@cindex daily data
@cindex monthly data
@cindex average
@cindex time-averaging
This means if you have daily data of 30 days, there will be 30 data files.
Or if you have monthly data of 12 months, there will be 12 data files.
Dealing with this kind of files, you need to specify the file names in shell scripts and pass them to NCO operators.
For example, your daily data files may look like @file{snd_19900101.nc}, @file{snd_19900102.nc}, @file{snd_19900103.nc} ...
If you want to know the monthly average of Jan 1990, you can write like,
@example
ncra -O snd_199001??.nc out.nc
@end example
You might want to use loop if you need the average of each month.
@example
for moy in @{1..12@}; do          # Loop over months
  mm=$( printf "%02d" $@{moy@} )  # Change to 2-digit format

  ncra -O snd_????$@{mm@}??.nc out_$@{mm@}.nc
done
@end example

@node Multiple files with multiple time points,  , One time point one file, Quick Start
@section Multiple files with multiple time points
@cindex daily data
@cindex monthly data
Similar as the last one, it's more about shell scripts.
Suppose you have daily data with one month of them in one data file.
The monthly average is simply to apply @command{ncra} on the specific data file.
And for seasonal averages, you can specify the three months by shell scripts.

@html
<a name="cmip5"></a> <!-- http://nco.sf.net/nco.html#cmip5 -->
@end html
@node CMIP5 Example, Parallel, Quick Start, Top
@chapter @acronym{CMIP5} Example
@cindex @acronym{CMIP5}
@ignore
This @uref{http://nco.sf.net/xmp_cesm.html,Wonderful CMIP5 Documentation}
shows complete processing of the @acronym{CMIP5} dataset.
@end ignore

The fifth phase of the Coupled Model Intercomparison Project 
(@uref{http://cmip-pcmdi.llnl.gov/cmip5/index.html?submenuheader=0, @acronym{CMIP5}}) 
provides a multi-model framework for comparing the mechanisms and
responses of climate models from around the world.   
However, it is a tremendous workload to retrieve a single climate
statistic from all these models, each of which includes several ensemble 
members.  
Not only that, it is too often a repetitive process which impedes new
research and hypothesis testing.  
Our @acronym{NASA} @acronym{ACCESS} project is designed to simplify and
accelerate this process.  
To begin, we document below a prototypical example of @acronym{CMIP5}
analysis and evaluation using traditional @acronym{NCO} commands on
netCDF3-format model and @acronym{HDF-EOS} format observational
(@acronym{NASA} @acronym{MODIS} satellite instrument) datasets.
These examples complement the @acronym{NCO} User Guide by detailing
in-depth data analysis in a frequently encountered ``real world''
context.   
Graphical representations of the results (@acronym{NCL} scripts
available upon request) are provided to illustrate physical meaning of
the analysis.
@ignore
In 2013 we added scripts which make use of new @acronym{NCO} features
that combine all the loops in the analysis into single commands by
exploiting @acronym{NCO}'s new group aggregation and arithmetic
features.   
@end ignore
Since @acronym{NCO} can process hierarchical datasets, i.e., datasets
stored with netCDF4 groups, we present sample scripts illustrating
group-based processing as well. 

@menu
* Combine Files::
* Global Distribution of Long-term Average::
* Annual Average over Regions::
* Monthly Cycle::
* Regrid MODIS Data::
* Add Coordinates to MODIS Data::
* Permute MODIS Coordinates::
@end menu

@node Combine Files, Global Distribution of Long-term Average, CMIP5 Example, CMIP5 Example
@section Combine Files
@cindex file combination
Sometimes, the data of one ensemble member will be stored in several
files to reduce single file size.
But it is not convenient to process in a batch mode.
The following script illustrates how to concatenate these files into one.
Key steps include: 
@enumerate
@item Obtain number and names (or partial names) of files in a directory
@item Concatenate files along the record dimension (usually time) using 
@command{ncrcat} (@pxref{ncrcat netCDF Record Concatenator}).
@end enumerate
@example
@verbatiminclude xmp/cmb_fl.sh
@end example

Right now, @acronym{CMIP5} model data downloaded from Earth System Grid
Federation (@uref{http://pcmdi9.llnl.gov/esgf-web-fe/, @acronym{ESGF}}) 
will not contain @key{group} features yet. 
Therefore users can aggregate the flat files into groups themselves.
The following script shows how to aggregate models to one file.
Each dataset becomes a group in the output file.
There can be several levels of groups.
In this example, we employ two experiments as the top-level.
The second-level comprises different models.
Some models have more than one ensemble member.
These ensemble members are on the third level.
In each sub-group of ensemble members, we appended two variables,
@var{snc} and @var{snd} (these stand for snow cover and snow depth, by
the way).
@cindex @option{--gag}
@cindex aggregation
@cindex group aggregation
@cindex groups, creating
@example
@verbatiminclude xmp/cmb_fl_grp.sh
@end example

@node Global Distribution of Long-term Average, Annual Average over Regions, Combine Files, CMIP5 Example
@section Global Distribution of Long-term Average
@cindex spatial distribution
@cindex long-term average
@cindex average
@cindex time-averaging
@float Figure,fgr:glb
@image{xmp/fgr1,3.5in} 
@caption{Global Distribution of Long-term Average.}
@end float
@noindent
This section illustrates how to calculate the global distribution of
long-term average (@pxref{fgr:glb}) with either flat files or 
@uref{http://nco.sourceforge.net/nco.html#index-groups, group file}.
Key steps include: 
@enumerate
@item Average ensemble members of each model using @command{nces} (@pxref{nces netCDF Ensemble Statistics})
@item Average the record dimension using @command{ncra} (@pxref{ncra netCDF Record Averager})
@item Store results of each model as a distinct group in a single output file using @command{ncecat} (@pxref{ncrcat netCDF Record Concatenator}) with the @option{--gag} option
@end enumerate
The first example shows how to process flat files.
@example
@verbatiminclude xmp/glb_avg.sh
@end example

With the use of @key{group}, the above script
will be shortened to just @w{TWO LINES}.
@cindex groups, averaging
@ignore
Isn't it amazing or what?!
@end ignore
@example
# Data from cmb_fl_grp.sh
# ensemble averaging
nces -O --nsm_grp --nsm_sfx='_avg' \
sn_LImon_all-mdl_all-xpt_all-nsm_200001-200512.nc \
  sn_LImon_all-mdl_all-xpt_nsm-avg.nc
ncra -O -g 'avg$' sn_LImon_all-mdl_all-xpt_nsm-avg.nc \
  sn_LImon_all-mdl_all-xpt_nsm-avg_tm-avg.nc
@end example
The input file, @file{sn_LImon_all-mdl_all-xpt_all-nsm_200001-200512.nc}, produced by @file{cmb_fl_grp.sh}, 
includes all the ensemble members as groups.
The option @samp{--nsm_grp} denotes 
that we are using @uref{http://nco.sf.net/nco.html#nsm_grp, group ensembles mode} of @command{nces},
instead of @uref{http://nco.sf.net/nco.html#nsm_fl, file ensembles mode}, @samp{--nsm_fl}.
The option @samp{--nsm_sfx='_avg'} instructs @command{nces} 
to store the output as a new child group @file{/[model]/[model name]_avg},
instead of in the parent group @file{/[model]}. 
In the final output file, @file{sn_LImon_all-mdl_all-xpt_nsm-avg_tm-avg.nc}, 
sub-groups with a suffix of `avg' are the long-term averages of each model.
Here, @samp{-g 'avg$'} is used to retrieve groups having 'avg' at the end of their names,
i.e., the long-term average groups.

@node Annual Average over Regions, Monthly Cycle, Global Distribution of Long-term Average, CMIP5 Example
@section Annual Average over Regions
@cindex annual average
@cindex average
@cindex time-averaging
@cindex area-averaging
@cindex dimension order
@cindex anomalies
@cindex standard deviation
@cindex renaming variables
@cindex attributes, editing
@cindex	attributes, modifying
@cindex	attributes, overwriting
@cindex regression
@cindex nco script file
@cindex variables, appending
@float Figure,fgr:anl
@image{xmp/fgr2,4in}
@caption{Annual Average over Regions.}
@end float
@noindent
This section illustrates how to calculate the annual average over
specific regions (@pxref{fgr:anl}).
Key steps include: 
@enumerate
@item Spatial average using @command{ncap2} (@pxref{ncap2 netCDF Arithmetic Processor}) and @command{ncwa} (@pxref{ncwa netCDF Weighted Averager}); 
@item Change dimension order using @command{ncpdq} (@pxref{ncpdq netCDF Permute Dimensions Quickly});
@item Annual average using @command{ncra} (@pxref{ncra netCDF Record Averager});
@item Anomaly from long-term average using @command{ncbo} (@pxref{ncbo netCDF Binary Operator});
@item Standard deviation using @command{ncbo} (@pxref{ncbo netCDF Binary Operator}) and @command{nces} (@pxref{nces netCDF Ensemble Statistics});
@item Rename variables using @command{ncrename} (@pxref{ncrename netCDF Renamer});
@item Edit attributions using @command{ncatted} (@pxref{ncatted netCDF Attribute Editor});
@item Linear regression using @command{ncap2} (@pxref{ncap2 netCDF Arithmetic Processor});
@item Use @command{ncap2} (@pxref{ncap2 netCDF Arithmetic Processor}) with nco script file (i.e., @file{.nco} file);
@item Move variables around using @command{ncks} (@pxref{ncks netCDF Kitchen Sink}).
@end enumerate
@strong{Flat files example}
@example
@verbatiminclude xmp/ann_avg.sh
@end example
@strong{gsl_rgr.nco}
@example
@verbatiminclude xmp/gsl_rgr.nco
@end example

With the @key{group} feature, 
all the loops over experiments, models and ensemble members can be omitted.
As we are working on implementing @key{group} feature in all @acronym{NCO} operators,
some functions (e.g., regression and standard deviation over ensemble members) 
may have to wait until the new versions.
@cindex group, spatial averaging
@cindex group, temporal averaging
@cindex group, anomaly
@cindex group, standard deviation
@cindex group, aggregation
@cindex group, dimension permutation
@example
@verbatiminclude xmp/ann_avg_grp.sh
@end example

@node Monthly Cycle, Regrid MODIS Data, Annual Average over Regions, CMIP5 Example
@section Monthly Cycle
@cindex monthly average
@cindex average
@cindex time-averaging
@cindex anomalies
@cindex geographical weight
@cindex weighted average
@float Figure,fgr:mon
@image{xmp/fgr3,4in}
@caption{Monthly Cycle.}
@end float
@noindent
This script illustrates how to calculate the monthly anomaly from the
annual average (@pxref{fgr:mon}). 
In order to keep only the monthly cycle,
we will subtract the annual average of each year from the monthly data,
instead of subtracting the long-term average.
This is a little more complicated in coding since we need to loop over years. 

@strong{Flat files example}
@example
@verbatiminclude xmp/mcc.sh
@end example
Using @key{group} feature and @uref{http://nco.sourceforge.net/nco.html#Hyperslabs, hyperslabs} of @command{ncbo},
the script will be shortened.
@example
@verbatiminclude xmp/mcc_grp.sh
@end example

@node Regrid MODIS Data, Add Coordinates to MODIS Data, Monthly Cycle, CMIP5 Example
@section Regrid @acronym{MODIS} Data
@cindex regrid
@cindex MODIS
@cindex bilinear interpolation
@cindex interpolation
@cindex renaming variables
@cindex renaming attributes
@cindex renaming dimensions
@cindex attributes, editing
@cindex	attributes, modifying
@cindex	attributes, overwriting
In order to compare the results between @acronym{MODIS} and
@acronym{CMIP5} models, one usually regrids one or both datasets so 
that the spatial resolutions match. 
Here, the script illustrates how to regrid @acronym{MODIS} data.
Key steps include:
@enumerate
@item Regrid using bilinear interpolation (@pxref{Bilinear interpolation})
@item Rename variables, dimensions and attributions using @command{ncrename} (@pxref{ncrename netCDF Renamer}).
@end enumerate
@strong{Main Script}
@example
@verbatiminclude xmp/rgr.sh
@end example
@strong{bi_interp.nco}
@example
@verbatiminclude xmp/bi_interp.nco
@end example

@node Add Coordinates to MODIS Data, Permute MODIS Coordinates, Regrid MODIS Data, CMIP5 Example
@section Add Coordinates to @acronym{MODIS} Data
@cindex MODIS
@cindex coordinates
@strong{Main Script}
@example
@verbatiminclude xmp/add_crd.sh
@end example
@strong{crd.nco}
@example
@verbatiminclude xmp/crd.nco
@end example

@node Permute MODIS Coordinates,  , Add Coordinates to MODIS Data, CMIP5 Example
@section Permute @acronym{MODIS} Coordinates
@cindex coordinates, modifying
@c NB: 20140130: @textdegree is in TeXInfo 4.12 but Mac OS X 10.8 ships with 4.8
@acronym{MODIS} orders latitude data from 90@textdegree{}N to
-90@textdegree{}N, and longitude from -180@textdegree{}E to
180@textdegree{}E.   
However, @acronym{CMIP5} orders latitude from -90@textdegree{}N to
90@textdegree{}N, and longitude from 0@textdegree{}E to
360@textdegree{}E.  
This script changes the @acronym{MODIS} coordinates to follow the
@acronym{CMIP5} convention.
@example
@verbatiminclude xmp/pmt_crd.sh
@end example

@ignore
@node Hierarchical Data Files, Parallel, CMIP5 Example, Top
section Hierarchical Data Files
@cindex hierarchical data
@cindex groups
Hierarchical Data Files support arbitrarily nested groups.
The following @acronym{NCO} operators now can work recursively through all groups:
@itemize @bullet
@item @command{ncbo} (@pxref{ncbo netCDF Binary Operator})
@item @command{ncecat} (@pxref{ncecat netCDF Ensemble Concatenator})
@item @command{ncks} (@pxref{ncks netCDF Kitchen Sink})
@item @command{ncpdq} (@pxref{ncpdq netCDF Permute Dimensions Quickly})
@item @command{ncwa} (@pxref{ncwa netCDF Weighted Averager})
@end itemize
Here is an example showing:
@enumerate
@item How to create a hierarchical data file from multiple files using @command{ncecat} (@pxref{ncecat netCDF Ensemble Concatenator}) or @command{ncks} (@pxref{ncks netCDF Kitchen Sink});
@item Hyperslabs using @command{ncks} (@pxref{ncks netCDF Kitchen Sink});
@item Spatial average and time average using @command{ncwa} (@pxref{ncwa netCDF Weighted Averager});
@item Anomaly from average using @command{ncbo} (@pxref{ncbo netCDF Binary Operator}).
@end enumerate
@example
@verbatiminclude xmp/grp.sh
@end example
@end ignore

@html
<a name="parallel"></a> <!-- http://nco.sf.net/nco.html#parallel -->
@end html
@node Parallel, CCSM Example, CMIP5 Example, Top
@chapter Parallel
@cindex @command{parallel}
This section will describe scripting strategies, including the use of
@acronym{GNU} Parallel, to @acronym{NCO}.
@example
ls *historical*.nc | parallel ncks -O -d time,"1950-01-01","2000-01-01" @{@} 50y/@{@}
@end example

@html
<a name="ccsm"></a> <!-- http://nco.sf.net/nco.html#ccsm -->
@end html
@node CCSM Example, mybibnode, Parallel, Top
@chapter CCSM Example
@cindex CCSM

This chapter illustrates how to use @acronym{NCO} to
process and analyze the results of a @acronym{CCSM} climate simulation.
@example
************************************************************************
Task 0: Finding input files
************************************************************************
The CCSM model outputs files to a local directory like:

/ptmp/zender/archive/T42x1_40

Each component model has its own subdirectory, e.g., 

/ptmp/zender/archive/T42x1_40/atm
/ptmp/zender/archive/T42x1_40/cpl
/ptmp/zender/archive/T42x1_40/ice
/ptmp/zender/archive/T42x1_40/lnd
/ptmp/zender/archive/T42x1_40/ocn

within which model output is tagged with the particular model name

/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0001-01.nc
/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0001-02.nc
/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0001-03.nc
...
/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0001-12.nc
/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0002-01.nc
/ptmp/zender/archive/T42x1_40/atm/T42x1_40.cam2.h0.0002-02.nc
...

or 

/ptmp/zender/archive/T42x1_40/lnd/T42x1_40.clm2.h0.0001-01.nc
/ptmp/zender/archive/T42x1_40/lnd/T42x1_40.clm2.h0.0001-02.nc
/ptmp/zender/archive/T42x1_40/lnd/T42x1_40.clm2.h0.0001-03.nc
...

************************************************************************
Task 1: Regional processing
************************************************************************
The first task in data processing is often creating seasonal cycles.
Imagine a 100-year simulation with its 1200 monthly mean files.
Our goal is to create a single file containing 12 months of data.
Each month in the output file is the mean of 100 input files.

Normally, we store the "reduced" data in a smaller, local directory.

caseid='T42x1_40'
#drc_in="$@{DATA@}/archive/$@{caseid@}/atm"
drc_in="$@{DATA@}/$@{caseid@}"
drc_out="$@{DATA@}/$@{caseid@}"
mkdir -p $@{drc_out@}
cd $@{drc_out@}

Method 1: Assume all data in directory applies
for mth in @{1..12@}; do
  mm=`printf "%02d" $mth`
  ncra -O -D 1 -o $@{drc_out@}/$@{caseid@}_clm$@{mm@}.nc \
    $@{drc_in@}/$@{caseid@}.cam2.h0.*-$@{mm@}.nc 
done # end loop over mth

Method 2: Use shell 'globbing' to construct input filenames
for mth in @{1..12@}; do
  mm=`printf "%02d" $mth`
  ncra -O -D 1 -o $@{drc_out@}/$@{caseid@}_clm$@{mm@}.nc \
    $@{drc_in@}/$@{caseid@}.cam2.h0.00??-$@{mm@}.nc \
    $@{drc_in@}/$@{caseid@}.cam2.h0.0100-$@{mm@}.nc
done # end loop over mth

Method 3: Construct input filename list explicitly
for mth in @{1..12@}; do
  mm=`printf "%02d" $mth`
  fl_lst_in=''
  for yr in @{1..100@}; do
    yyyy=`printf "%04d" $yr`
    fl_in=$@{caseid@}.cam2.h0.$@{yyyy@}-$@{mm@}.nc
    fl_lst_in="$@{fl_lst_in@} $@{caseid@}.cam2.h0.$@{yyyy@}-$@{mm@}.nc"
  done # end loop over yr
  ncra -O -D 1 -o $@{drc_out@}/$@{caseid@}_clm$@{mm@}.nc -p $@{drc_in@} \
    $@{fl_lst_in@}
done # end loop over mth

Make sure the output file averages correct input files!
ncks -M prints global metadata: 

  ncks -M $@{drc_out@}/$@{caseid@}_clm01.nc

The input files ncra used to create the climatological monthly mean
will appear in the global attribute named 'history'.

Use ncrcat to aggregate the climatological monthly means

  ncrcat -O -D 1 \
    $@{drc_out@}/$@{caseid@}_clm??.nc $@{drc_out@}/$@{caseid@}_clm_0112.nc

Finally, create climatological means for reference.
The climatological time-mean:

  ncra -O -D 1 \
    $@{drc_out@}/$@{caseid@}_clm_0112.nc $@{drc_out@}/$@{caseid@}_clm.nc

The climatological zonal-mean:

  ncwa -O -D 1 -a lon \
    $@{drc_out@}/$@{caseid@}_clm.nc $@{drc_out@}/$@{caseid@}_clm_x.nc

The climatological time- and spatial-mean:

  ncwa -O -D 1 -a lon,lat,time -w gw \
    $@{drc_out@}/$@{caseid@}_clm.nc $@{drc_out@}/$@{caseid@}_clm_xyt.nc

This file contains only scalars, e.g., "global mean temperature",
used for summarizing global results of a climate experiment.

Climatological monthly anomalies = Annual Cycle: 
Subtract climatological mean from climatological monthly means. 
Result is annual cycle, i.e., climate-mean has been removed.

  ncbo -O -D 1 -o $@{drc_out@}/$@{caseid@}_clm_0112_anm.nc \
    $@{drc_out@}/$@{caseid@}_clm_0112.nc $@{drc_out@}/$@{caseid@}_clm_xyt.nc

************************************************************************
Task 2: Correcting monthly averages
************************************************************************
The previous step appoximates all months as being equal, so, e.g.,
February weighs slightly too much in the climatological mean.
This approximation can be removed by weighting months appropriately.
We must add the number of days per month to the monthly mean files.
First, create a shell variable dpm:

unset dpm # Days per month
declare -a dpm
dpm=(0 31 28.25 31 30 31 30 31 31 30 31 30 31) # Allows 1-based indexing

Method 1: Create dpm directly in climatological monthly means
for mth in @{1..12@}; do
  mm=`printf "%02d" $@{mth@}`
  ncap2 -O -s "dpm=0.0*date+$@{dpm[$@{mth@}]@}" \
    $@{drc_out@}/$@{caseid@}_clm$@{mm@}.nc $@{drc_out@}/$@{caseid@}_clm$@{mm@}.nc
done # end loop over mth

Method 2: Create dpm by aggregating small files
for mth in @{1..12@}; do
  mm=`printf "%02d" $@{mth@}`
  ncap2 -O -v -s "dpm=$@{dpm[$@{mth@}]@}" ~/nco/data/in.nc \
    $@{drc_out@}/foo_$@{mm@}.nc
done # end loop over mth
ncecat -O -D 1 -p $@{drc_out@} -n 12,2,2 foo_$@{mm@}.nc foo.nc
ncrename -O -D 1 -d record,time $@{drc_out@}/foo.nc
ncatted -O -h \
  -a long_name,dpm,o,c,"Days per month" \
  -a units,dpm,o,c,"days" \
  $@{drc_out@}/$@{caseid@}_clm_0112.nc
ncks -A -v dpm $@{drc_out@}/foo.nc $@{drc_out@}/$@{caseid@}_clm_0112.nc

Method 3: Create small netCDF file using ncgen
cat > foo.cdl << 'EOF'
netcdf foo @{ 
dimensions:
	time=unlimited;
variables:
	float dpm(time);
	dpm:long_name="Days per month";
	dpm:units="days";
data:
	dpm=31,28.25,31,30,31,30,31,31,30,31,30,31;
@}
EOF
ncgen -b -o foo.nc foo.cdl
ncks -A -v dpm $@{drc_out@}/foo.nc $@{drc_out@}/$@{caseid@}_clm_0112.nc

Another way to get correct monthly weighting is to average daily
output files, if available.  

************************************************************************
Task 3: Regional processing
************************************************************************
Let's say you are interested in examining the California region.
Hyperslab your dataset to isolate the appropriate latitude/longitudes.

ncks -O -D 1 -d lat,30.0,37.0 -d lon,240.0,270.0 \ 
    $@{drc_out@}/$@{caseid@}_clm_0112.nc \
    $@{drc_out@}/$@{caseid@}_clm_0112_Cal.nc

The dataset is now much smaller!
To examine particular metrics.

************************************************************************
Task 4: Accessing data stored remotely
************************************************************************
OPeNDAP server examples:

UCI DAP servers:
ncks -M -p http://dust.ess.uci.edu/cgi-bin/dods/nph-dods/dodsdata in.nc
ncrcat -O -C -D 3 \
  -p http://dust.ess.uci.edu/cgi-bin/dods/nph-dods/dodsdata \
  -l /tmp in.nc in.nc ~/foo.nc

Unidata DAP servers:
ncks -M -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in.nc
ncrcat -O -C -D 3 \
  -p http://thredds-test.ucar.edu/thredds/dodsC/testdods \
  -l /tmp in.nc in.nc ~/foo.nc

NOAA DAP servers:
ncwa -O -C -a lat,lon,time -d lon,-10.,10. -d lat,-10.,10. -l /tmp -p \
http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.dailyavgs/surface \
pres.sfc.1969.nc ~/foo.nc

LLNL PCMDI IPCC OPeNDAP Data Portal: 
ncks -M -p http://username:password@@esgcet.llnl.gov/cgi-bin/dap-cgi.py/ipcc4/sresa1b/ncar_ccsm3_0 pcmdi.ipcc4.ncar_ccsm3_0.sresa1b.run1.atm.mo.xml

Earth System Grid (ESG): http://www.earthsystemgrid.org

caseid='b30.025.ES01' 
CCSM3.0 1% increasing CO2 run, T42_gx1v3, 200 years starting in year 400
Atmospheric post-processed data, monthly averages, e.g.,
/data/zender/tmp/b30.025.ES01.cam2.h0.TREFHT.0400-01_cat_0449-12.nc
/data/zender/tmp/b30.025.ES01.cam2.h0.TREFHT.0400-01_cat_0599-12.nc

ESG supports password-protected FTP access by registered users
NCO uses the .netrc file, if present, for password-protected FTP access 
Syntax for accessing single file is, e.g.,
ncks -O -D 3 \
  -p ftp://climate.llnl.gov/sresa1b/atm/mo/tas/ncar_ccsm3_0/run1 \
  -l /tmp tas_A1.SRESA1B_1.CCSM.atmm.2000-01_cat_2099-12.nc ~/foo.nc 

# Average surface air temperature tas for SRESA1B scenario
# This loop is illustrative and will not work until NCO correctly
# translates '*' to FTP 'mget' all remote files
for var in 'tas'; do
for scn in 'sresa1b'; do
for mdl in 'cccma_cgcm3_1 cccma_cgcm3_1_t63 cnrm_cm3 csiro_mk3_0 \
gfdl_cm2_0 gfdl_cm2_1 giss_aom giss_model_e_h giss_model_e_r \
iap_fgoals1_0_g inmcm3_0 ipsl_cm4 miroc3_2_hires miroc3_2_medres \
miub_echo_g mpi_echam5 mri_cgcm2_3_2a ncar_ccsm3_0 ncar_pcm1 \
ukmo_hadcm3 ukmo_hadgem1'; do
for run in '1'; do
        ncks -R -O -D 3 -p ftp://climate.llnl.gov/$@{scn@}/atm/mo/$@{var@}/$@{mdl@}/run$@{run@} -l $@{DATA@}/$@{scn@}/atm/mo/$@{var@}/$@{mdl@}/run$@{run@} '*' $@{scn@}_$@{mdl@}_$@{run@}_$@{var@}_$@{yyyymm@}_$@{yyyymm@}.nc
done # end loop over run
done # end loop over mdl
done # end loop over scn
done # end loop over var

cd sresa1b/atm/mo/tas/ukmo_hadcm3/run1/
ncks -H -m -v lat,lon,lat_bnds,lon_bnds -M tas_A1.nc | m
bds -x 096 -y 073 -m 33 -o $@{DATA@}/data/dst_3.75x2.5.nc # ukmo_hadcm3
ncview $@{DATA@}/data/dst_3.75x2.5.nc

# msk_rgn is California mask on ukmo_hadcm3 grid
# area is correct area weight on ukmo_hadcm3 grid
ncks -A -v area,msk_rgn $@{DATA@}/data/dst_3.75x2.5.nc \
$@{DATA@}/sresa1b/atm/mo/tas/ukmo_hadcm3/run1/area_msk_ukmo_hadcm3.nc 

Template for standardized data:
$@{scn@}_$@{mdl@}_$@{run@}_$@{var@}_$@{yyyymm@}_$@{yyyymm@}.nc

e.g., raw data
$@{DATA@}/sresa1b/atm/mo/tas/ukmo_hadcm3/run1/tas_A1.nc
becomes standardized data

Level 0: raw from IPCC site--no changes except for name 
         Make symbolic link name match raw data
Template: $@{scn@}_$@{mdl@}_$@{run@}_$@{var@}_$@{yyyymm@}_$@{yyyymm@}.nc

ln -s -f tas_A1.nc sresa1b_ukmo_hadcm3_run1_tas_200101_209911.nc
area_msk_ukmo_hadcm3.nc

Level I: Add all variables (not standardized in time)
         to file containing msk_rgn and area
Template: $@{scn@}_$@{mdl@}_$@{run@}_$@{yyyymm@}_$@{yyyymm@}.nc

/bin/cp area_msk_ukmo_hadcm3.nc sresa1b_ukmo_hadcm3_run1_200101_209911.nc
ncks -A -v tas sresa1b_ukmo_hadcm3_run1_tas_200101_209911.nc \
               sresa1b_ukmo_hadcm3_run1_200101_209911.nc
ncks -A -v pr  sresa1b_ukmo_hadcm3_run1_pr_200101_209911.nc \
               sresa1b_ukmo_hadcm3_run1_200101_209911.nc

If already have file then:
mv sresa1b_ukmo_hadcm3_run1_200101_209911.nc foo.nc
/bin/cp area_msk_ukmo_hadcm3.nc sresa1b_ukmo_hadcm3_run1_200101_209911.nc
ncks -A -v tas,pr foo.nc sresa1b_ukmo_hadcm3_run1_200101_209911.nc

Level II: Correct # years, months
Template: $@{scn@}_$@{mdl@}_$@{run@}_$@{var@}_$@{yyyymm@}_$@{yyyymm@}.nc

ncks -d time,....... file1.nc file2.nc 
ncrcat file2.nc file3.nc sresa1b_ukmo_hadcm3_run1_200001_209912.nc

Level III: Many derived products from level II, e.g., 

      A. Global mean timeseries
      ncwa -w area -a lat,lon \
           sresa1b_ukmo_hadcm3_run1_200001_209912.nc \
	   sresa1b_ukmo_hadcm3_run1_200001_209912_xy.nc

      B. Califoria average timeseries
      ncwa -m msk_rgn -w area -a lat,lon \
           sresa1b_ukmo_hadcm3_run1_200001_209912.nc \
	   sresa1b_ukmo_hadcm3_run1_200001_209912_xy_Cal.nc
@end example

@html
<a name="bibliography"></a> <!-- http://nco.sf.net/nco.html#bibliography -->
<a name="bib"></a> <!-- http://nco.sf.net/nco.html#bib -->
@end html
@node mybibnode, General Index, CCSM Example, Top
@chapter References
@itemize
@mybibitem{ZeM07} Zender, C. S., and H. J. Mangalam (2007), Scaling Properties of Common Statistical Operators for Gridded Datasets, Int. J. High Perform. Comput. Appl., 21(4), 485-498, doi:10.1177/1094342007083802.
@mybibitem{Zen08} Zender, C. S. (2008), Analysis of Self-describing Gridded Geoscience Data with netCDF Operators (NCO), Environ. Modell. Softw., 23(10), 1338-1342, doi:10.1016/j.envsoft.2008.03.004.
@mybibitem{WZJ07} Wang, D. L., C. S. Zender, and S. F. Jenks (2007), DAP-enabled Server-side Data Reduction and Analysis, Proceedings of the 23rd AMS Conference on Interactive Information and Processing Systems (IIPS) for Meteorology, Oceanography, and Hydrology, Paper 3B.2, January 14-18, San Antonio, TX. American Meteorological Society, AMS Press, Boston, MA.
@mybibitem{ZMW06} Zender, C. S., H. Mangalam, and D. L. Wang (2006), Improving Scaling Properties of Common Statistical Operators for Gridded Geoscience Datasets, Eos Trans. AGU, 87(52), Fall Meet. Suppl., Abstract IN53B-0827.
@mybibitem{ZeW07} Zender, C. S., and D. L. Wang (2007), High performance distributed data reduction and analysis with the netCDF Operators (NCO), Proceedings of the 23rd AMS Conference on Interactive Information and Processing Systems (IIPS) for Meteorology, Oceanography, and Hydrology, Paper 3B.4, January 14-18, San Antonio, TX. American Meteorological Society, AMS Press, Boston, MA.
@mybibitem{WZJ06} Wang, D. L., C. S. Zender, and S. F. Jenks (2006), Server-side netCDF Data Reduction and Analysis, Eos Trans. AGU, 87(52), Fall Meet. Suppl., Abstract IN53B-0826.
@mybibitem{WZJ073} Wang, D. L., C. S. Zender, and S. F. Jenks (2007), Server-side parallel data reduction and analysis, in Advances in Grid and Pervasive Computing, Second International Conference, GPC 2007, Paris, France, May 2-4, 2007, Proceedings. IEEE Lecture Notes in Computer Science, vol. 4459, edited by C. Cerin and K.-C. Li, pp. 744-750, Springer-Verlag, Berlin/Heidelberg, doi:10.1007/978-3-540-72360-8_67.
@mybibitem{WZJ074} Wang, D. L., C. S. Zender and S. F. Jenks (2007), A System for Scripted Data Analysis at Remote Data Centers, Eos Trans. AGU, 88(52), Fall Meet. Suppl., Abstract IN11B-0469.
@mybibitem{WZJ081} Wang, D. L., C. S. Zender and S. F. Jenks (2008), Cluster Workflow Execution of Retargeted Data Analysis Scripts, Proceedings of the 8th IEEE Int'l Symposium on Cluster Computing and the Grid (IEEE CCGRID '08), pp. 449-458, Lyon, France, May 2008.
@mybibitem{WZJ091} Wang, D. L., C. S. Zender, and S. F. Jenks (2009), Efficient Clustered Server-side Data Analysis Workflows using SWAMP, Earth Sci. Inform., 2(3), 141-155, doi:10.1007/s12145-009-0021-z.
@mybibitem{PFT88} Press, Flannery, Teukolsky, and Vetterling (1988), Numerical Recipes in C, Cambridge Univ. Press, New York, NY.
@end itemize

@c @node Name Index, General Index, Operators, Top
@c @unnumbered Function and Variable Index

@c @printindex fn

@html
<a name="index"></a> <!-- http://nco.sf.net/nco.html#index -->
<a name="idx"></a> <!-- http://nco.sf.net/nco.html#idx -->
@end html
@node General Index,  , mybibnode, Top
@unnumbered General Index

@syncodeindex fn cp
@printindex cp

@c TTFN (Ta ta for now)
@bye
