% vim: spell tw=80 shiftwidth=4 softtabstop=4 expandtab

% NOTE: to avoid circular dependency in packages, this cannot use either 
% the oce or ocedata package.  That's why the <<>>= blocks are not
% evaluated.  However, there are still some commented-out blocks
% before these, that set up and end PDF and PNG devices. The idea of
% that is to provide a skeleton for creation of the various PDF and
% PNG files used in this vignette.  These PDF and PNG files are
% in the git repository and they get built into the package.

\documentclass{article}

% \VignetteIndexEntry{Introduction to gsw}
% \VignetteKeyword{oceanography}

\usepackage{url}
\usepackage{boxedminipage}
\usepackage{hyperref}
\usepackage{makeidx}
\usepackage{titlesec}
\usepackage{color}
\usepackage{natbib}
\usepackage{xspace}
\usepackage[font=small,skip=0pt]{caption}


%\newcommand\CT{$\textTheta$\xspace} % conservative temperature
\newcommand\CT{$\Theta$\xspace} % conservative temperature
\newcommand\SA{$S_\textrm{A}$\xspace} % absolute salinity


\bibliographystyle{gsw}

\makeindex

\topmargin 0pt
\advance \topmargin by -\headheight
\advance \topmargin by -\headsep
\textheight 8.9in
\oddsidemargin 0pt
\evensidemargin \oddsidemargin
\marginparwidth 0.5in
\textwidth 6.5in
     

%\parskip=1.2ex plus 0.25ex minus 0.5ex

\titleformat{\section}[block]{\normalfont\large\bfseries}{\thesection}{1em}{}
\titlespacing{\section}{0em}{2em plus 0.5em minus 2em}{0.15em plus 0.15em minus 0.125em}
\titleformat{\subsection}[block]{\normalfont\itshape}{\thesubsection}{1em}{}
\titlespacing{\subsection}{0em}{1em plus 0.25em minus 1em}{-0.15em plus 0.15em minus 0.125em}

\newcommand{\di}[1]{#1\index{#1}}
\newcommand{\fixme}[1]{\textbf{$<$ #1 $>$}}


\newcommand\code[1]{\texttt{#1}\xspace}
\newcommand\oce{\texttt{oce}\xspace}
\newcommand\gsw{\texttt{gsw}\xspace}
\newcommand\UNESCO{\textsc{unesco-80}\xspace}
%\newcommand\TEOS{\textsc{teos-10}\xspace}
\newcommand\GSW{\textsc{gsw}\xspace}

\newcommand{\workedexercise}[2]{
	\vspace{2ex plus 2ex minus 1ex}
	\begin{boxedminipage}[c]{0.95\linewidth}
		{\textbf{Exercise #1}.\hspace{1em}#2}
	\end{boxedminipage}
	\vspace{2ex plus 2ex minus 1ex}
}
\newcommand{\workedanswer}[2]{
\goodbreak
\vskip 1.5ex plus 0.5ex minus 0.5ex
\noindent\textbf{Exercise #1 -- #2.}
}


\begin{document}

\title{The \gsw package}
\author{Dan E. Kelley and Clark Richards}
\maketitle


\begin{abstract}

    The \verb@gsw@ package provides an R implementation of the Gibbs SeaWater
    toolbox for the calculation of seawater properties.  This vignette outlines
    how to use \gsw alone or as part of the \oce package.

\end{abstract}

\section{Introduction}

In recent years, thermodynamic considerations have led to improved formulae for
the calculation of seawater properties
\cite[]{ioc2010tite,millero2010hote}, an important component of
which is the Gibbs-SeaWater (\GSW) toolbox
\cite[]{mcdougall2011gswt,pawlowicz2012ahpo}. The \gsw package is an R version
of \GSW, which may be used independently or within the more general \oce package
\cite[]{kelley2014oaoo}.  

This vignette sketches how to use \gsw.  Readers are assumed to be familiar with
oceanographic processing, and at least somewhat familiar with \GSW.  A good
resource for learning more about \GSW is \url{http://www.teos-10.org}, which
provides technical manuals for the Matlab version of \GSW
(\url{http://www.teos-10.org/pubs/gsw/html/gsw_contents.html}), along with white
papers and links to the growing peer-reviewed literature on the topic.

The \gsw framework involves a series of wrappers that connect R with the C
version of the Gibbs Seawater library. This yields high processing speed and the
minimization of transliteration errors increases reliability\footnote{The
incorporation of \GSW check values into the package-building process is an
additional measure taken to achieve reliability.}.

By design, the documentation of \gsw functions is spare, amounting mainly to an
explanation of function arguments and return values, with most other details
being provided through hyperlinks to the \GSW reference documentation. The idea
is to avoid duplication and to encourage users to consult the technical 
materials linked to the \GSW functions mimicked in \gsw.  The \GSW system is
somewhat complex, and analysts owe it to themselves to learn how it works, and
also to develop an appreciation for its scientific context by consulting various
documents provided on \url{http://www.teos-10.org}, including expansive white
papers and pointers to the growing peer-reviewed literature, including
treatments by \cite{wright2011asds}, \cite{mcdougall2012agaf},
\cite{graham2013qtnp}, and others.

%\section{Development status}
% 
%As of late 2014, the package is still in development, with about half of the
%common functions having been coded. All functions needed by the \oce package are
%working, however, and the development version of \oce now prefers to use the
%present package for calculations, if it is installed.

\section{Using gsw independent of oce}

<<echo=false,eval=true>>=
options(keep.source=TRUE, width=60, prompt=' ', continue=' ', oceEOS="unesco")
@

Suppose a water sample taken at pressure\footnote{For practical reasons, \gsw
goes beyond SI to incorporate oceanographic units, such as decibars for
pressure.} 100\,dbar, longitude 188E and latitude 4N, reveals \di{Practical
Salinity} 35 and \di{in-situ temperature} 10\,$^\circ$C (ITS-90).  Then the
\di{Absolute Salinity} may be calculated with

<<>>=
library(gsw)
SA <- gsw_SA_from_SP(SP=35, p=100, longitude=188, latitude=4)
@
yielding \code{SA}=\Sexpr{sprintf("%.4f", SA)} [g/kg], which can then be used to 
calculate \di{Conservative temperature} with
<<>>=
CT <- gsw_CT_from_t(SA=SA, t=10, p=100)
@
yielding \code{CT}=\Sexpr{sprintf("%.4f", CT)} [$^\circ$C]. Readers familiar
with \GSW will recognize the function and argument names, and are likely to find
the other functions needed for their work among the roughly 60 that 
\gsw provides.

\section{Using gsw within oce}

\begin{figure}[t]
    \begin{center}
        \includegraphics[width=0.4\hsize]{TS_unesco}
        \includegraphics[width=0.4\hsize]{TS_gsw}
    \end{center}
    \caption{\label{figure:TS}Hydrographic diagram of a CTD cast made in
    4\,km of water, south of Cape Cod. Left: using the \code{unesco}
    formulation; right: using the \code{gsw} formulation.}
\end{figure}


Many \oce plotting functions have an argument named \code{eos} that can be set
to the string \code{"unesco"} to get the older seawater formulation, or to
\code{"gsw"} to get the newer one. For example, the \code{section} dataset
provided by \oce holds a sequence of \di{CTD} casts in the North Atlantic.
Individual casts may be selected by index, so a \di{TS diagram} of the station
at index 100 (south of Cape Cod in 4000\,m of water) can be plotted as follows
(yielding the left-hand panel of Figure~\ref{figure:TS}).

<<eval=false, echo=false, results=hide>>=
pdf('TS_unesco.pdf', pointsize=18)
@
<<eval=false>>=
library(oce)
data(section)
ctd <- section[["station", 100]]
Slim <- c(34.8, 37.0)
Tlim <- c(0, 25)
plotTS(ctd, Slim=Slim, Tlim=Tlim, eos="unesco")
@
<<eval=false, echo=false, results=hide>>=
dev.off()
pdf('TS_gsw.pdf', pointsize=18)
@
where plot limits are used to match axes for a plot using
\code{gsw} (right-hand panel of Figure~\ref{figure:TS}):
<<eval=false>>=
plotTS(ctd, Slim=Slim, Tlim=Tlim, eos="gsw")
@
<<eval=false, echo=false, results=hide>>=
dev.off()
@


\begin{figure}[t]
    \begin{center}
        \includegraphics[width=0.4\hsize]{temperature_comparison}
        \includegraphics[width=0.4\hsize]{salinity_comparison}
    \end{center}
    \caption{\label{figure:comparison}Comparison of \code{unesco} and \code{gsw}
    formulations for a CTD section crossing the Atlantic at 36$^\circ$N.}
\end{figure}

Most hydrography-related functions of \oce provide this \code{eos} argument for
selecting the seawater formulation. This includes functions for plotting and for
calculating.  In addition, most of the objects within \oce have accessors that
can return temperature and salinity in either the \UNESCO or \GSW scheme. For
example, the ratio of Conservative Temperature to \UNESCO-formulated potential
temperature $\theta$ for all the CTD profiles in \code{section} is constructed
as follows (left panel of Figure~\ref{figure:comparison}).

<<eval=false, echo=false, results=hide>>=
pdf('temperature_comparison.pdf', height=5, pointsize=18)
par(mar=c(3.2, 3, 1, 1/2), mgp=c(2, 0.85, 0))
@
<<eval=false>>=
hist(section[["theta"]] / section[["CT"]], main="")
@
while the corresponding panel comparing Practical Salinity to Absolute Salinity
is constructed with
<<eval=false, echo=false, results=hide>>=
dev.off()
pdf('salinity_comparison.pdf', height=5, pointsize=18)
par(mar=c(3.2, 3, 1, 1/2), mgp=c(2, 0.85, 0))
@
<<eval=false>>=
hist(section[["salinity"]] / section[["SA"]], main="")
@
<<eval=false, echo=false, results=hide>>=
dev.off()
@

\begin{figure}[t]
    \begin{center}
        \includegraphics[width=.65\hsize]{SSS_1}
        \includegraphics[width=.65\hsize]{SSS_2}
    \end{center}
    \caption{\label{figure:SSS}Sea surface Practical Salinity (SP) from the
    \code{levitus} dataset and the percent difference between this and Absolute
    Salinity (SA). In the bottom panel colours are limited to a quantile range,
    to avoid the scale being set mainly by a contrast between the Baltic and the
    other salty waters of the planet.}
\end{figure}

\newpage
Maps are another way to compare \UNESCO and \GSW values, e.g.
Figure~\ref{figure:SSS} is generated by:

% Next causes build problems so just run it manually and
<<eval=false, echo=false, results=hide>>=
png('SSS_%d.png', width=7, height=4, unit="in", res=150, pointsize=14)
@
<<eval=false>>=
data("levitus", package="ocedata")
SSS <- levitus$SSS
dim <- dim(SSS)
ll <- expand.grid(lon=levitus$longitude, lat=levitus$latitude)
SA <- gsw_SA_from_SP(levitus$SSS, 0, ll$lon, ll$lat)
imagep(levitus$longitude, levitus$latitude, levitus$SSS, col=oceColorsJet)
title("Surface SP")
per <- 100 * (1 - levitus$SSS / SA)
imagep(levitus$longitude, levitus$latitude, per, col=oceColorsJet,
       zlim=quantile(per, c(0.001, 0.999), na.rm=TRUE))
title("Surface SA-SP, percent")
@
<<eval=false, echo=false, results=hide>>=
dev.off()
@
Note the use of quantile-specified scales for the images, the colour mappings of
which would otherwise be controlled by isolated low-saline waters, yielding
little to see in the wider expanses of the world ocean; see e.g.
\cite{mcdougall2012agaf} for a broader context.



\newpage

\bibliography{gsw}

\end{document}

