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

\documentclass{article}

% \VignetteIndexEntry{Introduction to oce}
% \VignetteDepends{oce}
% \VignetteKeyword{oceanography}

\usepackage{url}
\usepackage{fullpage}
\usepackage{boxedminipage}
\usepackage{hyperref}
\usepackage{makeidx}
\usepackage{titlesec}
\makeindex

\parskip=1.5ex plus 1.5ex minus 1.25ex

\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{\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.}
}


\usepackage{Sweave}
\begin{document}

\title{The OCE package}
\author{Dan E. Kelley}
\maketitle


\begin{abstract}

The \verb@oce@ package makes it easy to read, summarize and plot data from a
variety of Oceanographic instruments, isolating the researcher from the quirky
data formats that are common in this field. It also provides functions for
working with basic seawater properties such as the equation of state, and with
derived quantities such as the buoyancy frequency.  Although simple enough to be
used in a teaching context, \verb@oce@ is powerful enough for a research
setting.  These things are illustrated here, in the context of some practical
examples.  Worked examples are provided, in order to help readers take early
steps towards using the \verb@oce@ package in their research.

\end{abstract}

\section{Introduction}

Oceanographers must deal with measurements made by a wide variety of
instruments, a task that is complicated by the delight instrument manufacturers
seem to take in inventing new data formats. The manufacturers often provide
software for scanning the data files and producing some standard plots, but this
software is of limited use to researchers who work with several instrument types
at the same time, and who need to carry the analysis beyond the first steps,
e.g. moving beyond engineering plots to scientific plots and to statistical
analysis.

\begin{figure}[ht]
  \begin{center}
    \includegraphics[width=0.5\hsize]{ctd-object}
  \end{center}
  \caption{\label{f:ctdobject}Sketch of the contents of a \texttt{ctd}
    object. The elements \texttt{data}, \texttt{metadata}, and
    \texttt{history} are shared by all \texttt{oce} objects, although
    their contents vary from object to object.}
\end{figure}

The need to scan diverse data files was one motivation for the creation of
\verb@oce@, but an equal goal was to make it easy to work with the data once
they are in the system.  This was accomplished partly by the provision of
functions to work with the data, and partly by developing a uniform object
design that lets users reach inside without guesswork.

At the core of the \verb@oce@ design process is a policy of adding features
according to the priorities of practical research. As a result, \verb@oce@ is a
fairly comfortable tool today, and it should remain so as it grows.


\section{Object design}

As illustrated in Figure~\ref{f:ctdobject}, each \texttt{oce} object is a list
containing three elements: (a) \texttt{data}, a list or a data frame containing
the actual data (e.g., for a CTD object, this will contain pressure,
temperature, etc.), (b) \texttt{metadata}, a list containing data such things as
file headers, the location of a CTD cast, etc., and (c) \texttt{history},
a list that documents how the file was created (often by a \texttt{read} or
\texttt{as} method) and how it was changed thereafter (e.g. by decimating a CTD
cast).

The uniformity of the various \texttt{oce} objects makes it easy to build skill
in examining and modifying objects.  A simple S3-based object inheritance scheme
permits somewhat generic processing of \texttt{oce} objects, e.g. \verb@plot(x)@
produces different sorts of plots for different sorts of \verb@x@ objects.


\section{Calculations of seawater properties}

\index{calculation!seawater properties}
\index{seawater properties, calculations of}

The \verb@oce@ package provides many functions for dealing with
seawater properties. Perhaps the most used is \verb@swRho(S,T,p)@,
which computes seawater density $\rho=\rho(salinity, temperature,
pressure)$, where salinity follows the practical salinity scale,
$temperature$ is \emph{in-situ} temperature in $^\circ$C, and
$pressure$ is seawater pressure, i.e. the excess over atmospheric
pressure, in dbar.  (This and similar functions starts with the
letters \verb@sw@ to designate that they relate to seawater
properties; a future version of \verb@oce@ may provide air properties,
with functions names starting with \verb@air.@) The result is a number
in the order of $1000$\,kg/m$^3$.  For many purposes, Oceanographers
prefer to use the density anomaly $\sigma=\rho-1000$\,kg/m$^3$,
provided with \verb@swSigma(salinity,temperature,pressure)@, or its
adiabatic cousin $\sigma_\theta$, provided with
\verb@swSigmaTheta(salinity,temperature,pressure)@.

\looseness=1
\index{dynamic height}
Most of the functions use the UNESCO formulations of seawater properties, but new formulations
may be added as they come into use in the literature.
A partial list of seawater functions is as follows:
\verb@swDynamicHeight@ (dynamic height),
\verb@swN2@ (buoyancy frequency),
\verb@swSCTp@ (salinity from conductivity, temperature and pressure),
\verb@swSTrho@ (salinity from temperature and density),
\verb@swTSrho@ (temperature from salinity and density),
\verb@swTFreeze@ (freezing temperature),
\verb@swAlpha@ (thermal expansion coefficient $\alpha=-\rho_0^{-1}\partial\rho/\partial T$),
\verb@swBeta@ (haline compression coefficient $\beta=\rho_0^{-1}\partial\rho/\partial S$),
\verb@swAlphaOverBeta@ ($\alpha/\beta$),
\verb@swConductivity@ (conductivity from $S$, $T$ and $p$),
\verb@swDepth@ (depth from $p$ and latitude),
\verb@swLapseRate@ (adiabatic lapse rate),
\verb@swRho@ (density $\rho$ from $S$, $T$ and $p$),
\verb@swSigma@ ($\rho-1000$\,kg/m$^3$),
\verb@swSigmaT@ ($\sigma$ with $p$ set to zero and temperature unaltered),
\verb@swSigmaTheta@ ($\sigma$ with $p$ set to zero and temperature altered adiabatically),
\verb@swSoundSpeed@ (speed of sound),
\verb@swSpecificHeat@ (specific heat),
\verb@swSpice@ (a quantity used in double-diffusive research),
\verb@swTheta@ (potential temperature $\theta$),
and
\verb@swViscosity@ (viscosity).
Details and examples are provided in the documentation of these functions.


\workedexercise{1}{(a) What is the density of a seawater parcel at pressure
$100$\,dbar, with salinity $34$\,PSU and temperature 10$^\circ$C?
(b) What temperature would the parcel have if raised adiabatically to the surface?
(c) What density would it have if raised adiabatically to the surface?
(d) What density would it have if lowered about 100m, increasing the pressure to $200$dbar?
(e) Draw a blank $T$-$S$ diagram with $S$ from $30$ to $40$\,PSU and $T$ from $-2$ to 20$^\circ$C.
(Answers are provided at the end of this document.)
}


\section{CTD data}
\subsection{Example with pre-trimmed data}

\index{data!ctd profile \verb@ctd@}

To get you started with CTD data, \verb@oce@ provides a sample data set that has
been trimmed to just the downcast portion of the sampling.  (See the next
section to learn how to do this trimming.).  The commands
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(ctd)
> plot(ctd)
\end{Sinput}
\end{Schunk}
produce Figure~\ref{fig:ctd}. You may also get a summary of the data with
\begin{Schunk}
\begin{Sinput}
> summary(ctd)
\end{Sinput}
\end{Schunk}

The object used to hold CTD data stores not just the data, but also the raw
header sequence, and whatever has been discovered about the dataset by parsing
the header, use
\begin{Schunk}
\begin{Sinput}
> names(ctd)
\end{Sinput}
\end{Schunk}
etc.

Of course, you may apply any \verb@R@ techniques to the data in \verb@oce@
objects, e.g. \verb@hist(ctd$data$temperature)@ would produce a histogram of
temperature for the \verb@ctd@ object.  It is always worth checking, though, to
see if \verb@oce@ has already defined a function that you may be applying,
e.g. \verb@plot.TS@ will produce a lovely temperature-salinity diagram, with
isopycnals and proper units on the axes.

The package provides facilities for some common operations with oceanographic
data, such as trimming CTD profiles with \verb@ctdTrim()@, but of course you
may do that sort of work by acting on the data directly, if necessary.  Just
make sure you realize that the metadata will not be altered if you do that.
Also, it is a good idea to add log entries to any objects that you change, by
using the \verb@historyAdd()@ function.  (You can see an example of
this in action with \verb@?section@.)

\begin{figure}
\begin{center}
\setkeys{Gin}{width=\textwidth}
\includegraphics{-ctdfig}
\end{center}
\caption{Overview graph of the sample CTD dataset \texttt{ctd}, acquired in
the St Lawrence Estuary Internal Wave Experiment.  (This dataset has been
trimmed to the downcast; see the text and Figure~\ref{fig:ctdraw}.)}
\label{fig:ctd}
\end{figure}

\workedexercise{2}{Plot a profile of $\sigma_\theta$ and $N^2$, for the data in the pycnocline.}

\subsection{Example with raw data}

Practicing Oceanographers may be wondering how the CTD cast used in the
preceding section was trimmed of equilibration-phase and upcast-phase data. Data
from these sections are spurious and must be trimmed as a first step in
processing. For example, consider the following code.
\begin{Schunk}
\begin{Sinput}
> data(ctd.raw)
> plot.ctd.scan(ctd.raw)
\end{Sinput}
\end{Schunk}
\begin{figure}
\begin{center}
\setkeys{Gin}{width=0.55\textwidth}
\includegraphics{-ctdrawfig}
\end{center}
\caption{Scanwise plot of the \texttt{ctd.raw} sample data set.  Note the wild
spike at the start, the equilibration phase before the downcast, and the
spurious freshening signal near the start of the upcast.  See the text for a
discussion of how inspection of such graphs can help in trimming CTD data.}
\label{fig:ctdraw}
\end{figure}

\noindent This produces a two-panel plot (Figure~\ref{fig:ctdraw}) of the data
as a time-series, revealing not just the (useful) downcast, but also the
subsequent upcast sequence.  The x-axis in this plot is the scan number, which
is a convenient index for extraction of the downcast portion of the profile by
an essentially manual method, e.g. proceeding with a sequence of commands such
as
\begin{Schunk}
\begin{Sinput}
> plot.ctd.scan(ctdTrim(ctd.raw, "range", parameters = list(item = "scan", 
+     from = 140, to = 250)))
> plot.ctd.scan(ctdTrim(ctd.raw, "range", parameters = list(item = "scan", 
+     from = 150, to = 250)))
\end{Sinput}
\end{Schunk}
This is the ``gold standard'' method, which is recommended for detailed
work. However, for quick work, you may find that the automatic downcast
detection scheme works adequately, e.g.
\begin{Schunk}
\begin{Sinput}
> ctdTrimmed <- ctdTrim(ctd.raw)
\end{Sinput}
\end{Schunk}

It should be noted that \verb@ctdTrim@ inserts entries into the object's log
file, so that you (or anyone else with whom you share the object) will be able to
see the details of how the trimming was done.

\index{reading!ctd profile}

Once the profile has been trimmed, you may wish to use \texttt{ctd.decimate()}
to smooth the data and interpolate the smoothed results to uniformly-spaced
pressure values. For example, a quick examination of a file might be done by the
following:
\begin{Schunk}
\begin{Sinput}
> plot(ctd.decimate(ctdTrim(read.ctd("stn123.cnv"))))
\end{Sinput}
\end{Schunk}

\subsection{Example with WOCE archive data}

The package has a harder time scanning the headers of data files in the WOCE
archive format than it does in the Seabird format illustrated in the previous
examples. This is mainly because front-line researchers tend to work in the
Seabird format, and partly because the WOCE format is odd. For example, the
first line of a WOCE file is of the form \texttt{CTD,20060609WHPOSIODAM} (or
\texttt{BOTTLE,...}).  Scanning the item to the left of the comma is not
difficult (although there are variants to the two shown, e.g. \texttt{CTDO}
sometimes occurs).  The part to the right of the comma is more difficult.  The
first part is a date (yyyymmdd) so that's no problem.  But then things start to
get tricky.  In the example provided, this text contains the division of the
institute (WHPO), the institute itself (SIO), and initial of the investigator
(DAM). The problem is that no dividers separate these items, and that there seem
to be no standards for the item lengths. Rather than spend a great deal of time
coding special cases (e.g. scanning to see if the string \texttt{WHOI} occurs in
the header line), the approach taken with \verb@oce@ is to ignore such issues
relating to quirky headers.  This frees up time to work on more important
things, such as plotting the data.

Of course, R provides access to object constituents, so that you are
free to do such things as
\begin{Schunk}
\begin{Sinput}
> x <- read.ctd("nnsa_00934_00001_ct1.csv", type = "WOCE")
> x$metadata$institute <- "SIO"
> x$metadata$scientist <- "DAM"
\end{Sinput}
\end{Schunk}
but it is \emph{bad practice} to alter metadata in such a way, because
doing so alters the object without altering its documentation.  The
preferred scheme is to do as follows.
\index{changelogs in oce objects}
\index{oce object changelog}
\index{logged changes to oce objects}
\index{editing oce objects}
\index{oce.edit}
\begin{Schunk}
\begin{Sinput}
> x <- read.ctd("nnsa_00934_00001_ct1.csv", type = "WOCE")
> x <- oce.edit(x, "institute", "SIO")
> x <- oce.edit(x, "scientist", "DAM")
\end{Sinput}
\end{Schunk}
which will store a note about the changes in the object's log.  Even
better, provide a reason for the change, and sign the change with your
name:
\begin{Schunk}
\begin{Sinput}
> x <- read.ctd("nnsa_00934_00001_ct1.csv", type = "WOCE")
> x <- oce.edit(x, "institute", "SIO", "human-parsed", "Dan Kelley")
> x <- oce.edit(x, "scientist", "DAM", "human-parsed", "Dan Kelley")
\end{Sinput}
\end{Schunk}

For a real-world example (with warts!), visit
\url{http://cchdo.ucsd.edu/data_access?ExpoCode=58JH199410} and download the zip
file containing the Arctic section called ``CARINA'', measured in 1994. Expand
the zip file, enter the directory, and run the code below.
\begin{Schunk}
\begin{Sinput}
> library(oce)
> files <- system("ls *.csv", intern = TRUE)
> for (i in 1:length(files)) {
+     cat(files[i], "\n")
+     x <- read.ctd(files[i])
+     if (i == 1) {
+         plot.TS(x, xlim = c(31, 35.5), ylim = c(-1, 10), type = "l", 
+             col = "red")
+     }
+     else {
+         lines(x$data$salinity, x$data$temperature, col = "red")
+     }
+ }
\end{Sinput}
\end{Schunk}

What you'll see is an overall $T$-$S$ diagram for the entire dataset. It may take
a while, since the dataset contains over 90,000 observations. You may note that,
even though this is an official, quality-controlled dataset, it is not without
problems. The graph that is produced by this code has several spurious lines
oriented horizontally (indicating spurious salinity) and vertically (indicating
spurious temperature). One way to find such values is to put the lines
\begin{Schunk}
\begin{Sinput}
> print(range(x$data$temperature))
> print(range(x$data$salinity))
\end{Sinput}
\end{Schunk}
after the \verb@read.ctd()@ command. One thing you'll find is that station 987
has a minimum salinity range of 0.0009 to 987. These values are clearly in
error, as are the temperatures at this spot in the file. (It is perhaps
revealing that the spurious salinity is equal to the station number.) Indeed, at
this spot in the file it can be seen that the pressure jumps from 1342 to 0, and
then starts increasing again; the file contains two profiles, or the same
profile twice. This is not the only flaw that is revealed by the graph, and by
\verb@range@ commands; a generous user would spend a week tracking down such
issues, and would then contact the data provider (or the chief scientist of the
field work) with specific suggestions for correcting the files. The point here
is to highlight how this package can be used with real-world data.

\subsection{Section plots}
The commands
\begin{Schunk}
\begin{Sinput}
> data(section)
> data(coastlineHalifax)
> plot(section, coastline = coastlineHalifax)
\end{Sinput}
\end{Schunk}
will plot a summary diagram containing sections of
$T$, $S$, and $\sigma_\theta$, along with a chart indicating station
locations. In addition to such overview diagrams, \verb@plot@ can also create
individual plots of individual properties.

\workedexercise{3}{Draw a $T$-$S$ diagram for the section data, colour-coded by station}

\index{reading!ctd section}
\index{data!section \verb@a03@, North Atlantic along 36$^\circ$N}

\index{Gulf Stream}

The Halifax section is supplied in a pre-gridded format, but some datasets have
different pressure levels at each station.  For such cases, the
\verb@sectionGrid@ function may be used, e.g.
\begin{Schunk}
\begin{Sinput}
> data(a03)
> GS <- subset(a03, indices = 124:102)
> GSg <- sectionGrid(GS, p = seq(0, 1600, 25))
> data(coastlineWorld)
> plot(GSg, coastline = coastlineWorld, map.xlim = c(-85, -(64 + 
+     13/60)))
\end{Sinput}
\end{Schunk}
produces Figure~\ref{fig:sectiona03}.  The ship doing the sampling was
travelling westward from the Mediterranean towards North America, taking 124
stations in total; the \verb@indices@ value selects the last few
stations of the section, during which the ship heading was changed to run in a
northwesterly direction, to cross isobaths (and perhaps, the Gulf Stream) at
right angles.

\begin{figure}
\begin{center}
\setkeys{Gin}{width=1\textwidth}
\includegraphics{-sectionfiga03}
\end{center}
\caption{\label{fig:sectiona03}
  Portion of the CTD section designated A03, showing the Gulf Sream region.  The
  square on the cruise track corresponds to zero distance on the sections.
}
\end{figure}

\workedexercise{4}{Plot dynamic height and geostrophic velocity across the Gulf Stream.}

\section{Coastline and topographic data}

\index{data!coastline}
\index{data!topography}

Coastline data are available from a variety of sources. The NOAA site
\url{http://www.ngdc.noaa.gov/mgg_coastline/} is particularly popular, and it
has the advantage of providing data in Splus format.  The function
\verb@read.coastline@ can handle reading that format (plus some other formats),
and \verb@plot@ on the resulting object will produce a simple coastline map.
The only real advantage over plotting things yourself is that latitude and
longitude are scaled to give natural shapes near the centre of the plot.

Bathymetric charts, or more generally topographic maps, can be produced easily, e.g. (Figure~\ref{fig:topo})
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(topoMaritimes)
> plot(topoMaritimes, xlim = c(-66, -58), ylim = c(44, 50), water.z = c(-50, 
+     -100, -150, -200, -300, -400, -500, -1000, -2000), lwd.water = c(1, 
+     1, 1, 1, 1, 1, 1.5, 1.5, 1.5))
\end{Sinput}
\end{Schunk}
\begin{figure}
\begin{center}
\setkeys{Gin}{width=0.7\textwidth}
\includegraphics{-topofig}
\end{center}
\caption{Topography of eastern Canada, centred on Les \^{i}les de la Madeleine.}
\label{fig:topo}
\end{figure}

\section{Sea-level data}

\subsection{Time-domain analysis}

\index{sea level!during Hurricane Juan}
\index{Hurricane Juan!surge seen in time-series of sea level}

The commands
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(sealevelHalifax)
> plot(sealevelHalifax)
\end{Sinput}
\end{Schunk}
load and graph a build-in dataset of sea-level timeseries. The result, shown in
Figure~\ref{fig:sealevel}, is a four-panel plot. The top panel is a timeseries
view that provides an overview of the entire data set. The second panel is
narrowed to the most recent month, which should reveal spring-neap cycles if the
tide is mixed. The third panel is a spectrum, with a few tidal constituents
indicated. At the bottom is a cumulative spectrum, which makes these
narrow-banded constituents quite visible.

\begin{figure}
\begin{center}
\setkeys{Gin}{width=0.8\textwidth}
\includegraphics{-sealevelfig}
\end{center}
\caption{Sea-level timeseries measured in 2003 in Halifax Harbour.  (The spike
in September is the storm surge associated with Hurricane Juan, regarded by the
Canadian Hurricane Centre to be one of the most powerful and damaging hurricanes
to ever hit Canada.)}
\label{fig:sealevel}
\end{figure}

\workedexercise{5}{Illustrate Halifax sealevel variations during Hurricane Juan.}

\workedexercise{6}{Draw a spectrum of sea-level variation, with the M2 tidal component indicated.}

\subsection{Tidal analysis}

In a future version, tidal analysis will be provided, along the lines of the
t-tide package in Matlab.  A preliminary version of tidal analysis is provided
by the \verb@tidem@ function provided in this version of the package, but
readers are cautioned that the results are certain to change in a future
version.  (The problems involve phase, and the inference of satellite nodes.)

%%% \index{sea level!storm surge during Hurricane Juan}
%%% \index{Hurricane Juan!surge detection by detiding}
%%%
%%% <<label=tideplot,eval=FALSE>>=
%%% library(oce)
%%% data(sealevelHalifax)
%%% tide <- tidem(sealevelHalifax)
%%% days <- 15 # focus on these days at end of series
%%% n <- length(sealevelHalifax$data$elevation)
%%% i <- seq(n-24*days, n)
%%% t   <- sealevelHalifax$data$t[i]
%%% eta <- sealevelHalifax$data$elevation[i]
%%% eta.pred <- predict(tide)[i]
%%% plot(t, eta, type="l", ylim=c(-0.5,3))
%%% abline(h=0, col="pink")
%%% lines(t, eta - eta.pred, col="red")
%%% @
%%% produce Figure~\ref{fig:tide}, illustrating the use of tidal analysis to detect
%%% storm surges.  Note the use of the \verb@model@ that is returned by the tide
%%% analysis.
%%%
%%% (It should be noted that the tidal analysis portion of \verb@oce@ is still in
%%% active development, and the features are subject to change.  Use
%%% \verb@?tidem@ to learn more about this.)
%%%
%%% \begin{figure}
%%% 	\begin{center}
%%% \setkeys{Gin}{width=0.8\textwidth}
%%% <<label=tidefig,fig=TRUE,width=8,height=5,echo=FALSE>>=
%%% <<tideplot>>
%%% @
%%% \end{center}
%%% \caption{Sea-level variation in Halifax Harbour in 2003 (black line) and the residual
%%% after removal of tides using \texttt{tidem()}.  The spike on September 28th
%%% is a storm surge caused by Hurricane Juan, which caused a great deal of damage
%%% to the region.}
%%% \label{fig:tide}
%%% \end{figure}
%%%
%%% \goodbreak

\section{Temperature-Depth Recorder data}
The commands
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(ptr)
> plot(ptr)
\end{Sinput}
\end{Schunk}
produce a plot (Figure~\ref{fig:pt}) of pressure-temperature recorder (pt)
measurements made during St Lawrence Estuary Internal Wave Experiment, a
CFCAS-funded research program in which the \texttt{oce} author was a principal
investigator.  The device was mounted on a mooring that tilted significantly
with the tide, yielding strong tidal signals in pressure as well as temperature,
thus providing a rough indication of the temperature profile.  Note that this
graph contains in-air as well as in-water data.
\begin{figure}
\begin{center}
\setkeys{Gin}{width=0.66\textwidth}
\includegraphics{-ptfig}
\end{center}
\caption{Measurements made with a pressure-temperature recorder in the
  St Lawrence Estuary.  Note that the record contains in-air
  measurements made during an hour prior to lowering into the water,
  and during several days of transit from the field site back to
  Dalhousie University.  The text suggests a procedure for isolating
  in-water data, and removing the approximately 10 dbar atmospheric
  component of pressure.}
\label{fig:pt}
\end{figure}

\workedexercise{7}{Trim the in-air measurements from this \texttt{pt} record, and
then remove the atmospheric pressure from the signal.}


\section{Acoustic Doppler Current Profiler data}
\index{ADP}
The commands
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(adp)
> plot(adp, which = 1:2, adorn = expression({
+     lines(x$data$ts$time, x$data$ts$pressure, col = "green", 
+         lwd = 2)
+ }))
\end{Sinput}
\end{Schunk}
produce Figure~\ref{fig:adp}, showing currents made
in the St Lawrence Estuary Internal Wave Experiment.
\begin{figure}
\begin{center}
\setkeys{Gin}{width=\textwidth}
\includegraphics{-adpfig}
\end{center}
\caption{Measurements made with an ADP in the
  St Lawrence Estuary.  The data were recorded in beam format, so a two-step
  process is used to convert to enu coordinates.  The green curve indicates
  the water surface, inferred from the pressure measured by the ADP.}
\label{fig:adp}
\end{figure}



\section{The future of oce}

The present version of \verb@oce@ can only handle data types that the author has
been using lately in his research. New data types will be added as the need
arises in that work, but the author would also be happy to add other data types
that are likely to prove useful to the Oceanographic community.  (The data types
need not be restricted to Physical Oceanography, but the author will need some
help in dealing with other types of data, given his research focus.)
Two principles will guide the addition of data types and functions:
(a) the need, as perceived by the author or by other contributors and
(b) the ease with which the additions can be made.

% As for algorithms, there are plenty of gaps in \verb@oce@.  Dealing
% with measurements of turbulence is a high priority for the author, for
% example, as is improving the functions for processing data from
% pressure-temperature sensors and acoustic Doppler current profilers.


\section{Development website}

The site \url{http://github.com/dankelley/oce} provides a window on the
development that goes on between the CRAN releases of the package. Please visit
the site to report bugs, to suggest new features, or just to see how \verb@oce@
development is coming along.  Note that the \verb@development@ branch is used by
the author in his work, and is updated so frequently that it must be considered
unstable, at least in those spots being changed on a given day.  Every week or
so, as the \verb@development@ branch stabilizes, the changes are merged back
into the \verb@master@ branch.  Official CRAN releases derive from the
\verb@master@ branch, and are done when the code is considered to be of
reasonable stability and quality.  This is all in a common pattern for
open-source software.

%\begin{center}
%\vspace{2cm}
%
%------
%
%\vspace{2cm}
%
%See the end of the document for answers to exercises.
%
%\end{center}
%
%\newpage


\vspace{2cm plus 2cm minus 2cm}
\section*{Answers to exercises}
\workedanswer{1}{Seawater properties}
\begin{Schunk}
\begin{Sinput}
> library(oce)
> swRho(34, 10, 100)
\end{Sinput}
\begin{Soutput}
[1] 1026.624
\end{Soutput}
\begin{Sinput}
> swTheta(34, 10, 100)
\end{Sinput}
\begin{Soutput}
[1] 9.988598
\end{Soutput}
\begin{Sinput}
> swRho(34, swTheta(34, 10, 100), 0)
\end{Sinput}
\begin{Soutput}
[1] 1026.173
\end{Soutput}
\begin{Sinput}
> swRho(34, swTheta(34, 10, 100, 200), 200)
\end{Sinput}
\begin{Soutput}
[1] 1027.074
\end{Soutput}
\begin{Sinput}
> plot.TS(as.ctd(c(30, 40), c(-2, 20), rep(0, 2)), grid = TRUE, 
+     col = "white")
\end{Sinput}
\end{Schunk}

\workedanswer{2}{Profile plots}
Although one may argue as to the limits of the pycnocline, for illustration let us say it is in 5bar to 12dbar range.  One way to do this is
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(ctd)
> pycnocline <- ctdTrim(ctd, "range", parameters = list(item = "pressure", 
+     from = 5, to = 12))
> plot.profile(pycnocline, type = "density+N2")
\end{Sinput}
\end{Schunk}
and another is
\index{subset!extracting a portion of a profile}
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(ctd)
> pycnocline <- subset(ctd, 5 <= pressure & pressure <= 12)
> plot.profile(pycnocline, type = "density+N2")
\end{Sinput}
\end{Schunk}

\index{section!extracting profile data from}
\workedanswer{3}{TS diagram for section data}
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(section)
> SS <- TT <- pp <- id <- NULL
> n <- length(section$data$station)
> for (i in 1:n) {
+     stn <- section$data$station[[i]]
+     SS <- c(SS, stn$data$salinity)
+     TT <- c(TT, stn$data$temperature)
+     pp <- c(pp, stn$data$pressure)
+     id <- c(id, rep(i, length(stn$data$pressure)))
+ }
> ctd <- as.ctd(SS, TT, pp)
> plot.TS(ctd, col = hsv(0.7 * id/n), cex = 2, pch = 21)
\end{Sinput}
\end{Schunk}

\workedanswer{4}{Gulf Stream}
(Try \verb@?swDynamicHeight@ for hints on smoothing.)
\index{Gulf Stream!geostrophic calculation}
\index{subset!extracting stations from a section}
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(a03)
> GS <- subset(a03, indices = 124:102)
> dh <- swDynamicHeight(GS)
> par(mfrow = c(2, 1))
> plot(dh$distance, dh$height, type = "b", xlab = "", ylab = "Dyn. Height [m]")
> grid()
> f <- coriolis(GS$data$station[[1]]$metadata$latitude)
> g <- gravity(GS$data$station[[1]]$metadata$latitude)
> v <- diff(dh$height)/diff(dh$distance) * g/f/1000
> plot(dh$distance[-1], v, type = "l", col = "blue", xlab = "Distance [km]", 
+     ylab = "Velocity [m/s]")
> grid()
> abline(h = 0)
\end{Sinput}
\end{Schunk}
\workedanswer{5}{Halifax sealevel during Hurricane Juan.}
\index{Hurricane Juan!worked example of sea-level plot}
\index{sea level!during Hurricane Juan}
A web search will tell you that Hurricane Juan hit about midnight, 2003-sep-28.
The author can verify that the strongest winds occurred a bit after midnight -- that was the time
he moved to a room without windows, in fear of flying glass.
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(sealevelHalifax)
> plot(sealevelHalifax, which = 1, xlim = as.POSIXct(c("2003-09-24", 
+     "2003-10-05"), tz = "UTC"))
> abline(v = as.POSIXct("2003-09-29 04:00:00", tz = "UTC"), col = "red")
> mtext("Hurricane\nJuan", at = as.POSIXct("2003-09-29 04:00:00", 
+     tz = "UTC"), col = "red")
\end{Sinput}
\end{Schunk}

\workedanswer{6}{Sealevel spectrum}
Notice the use of \verb@(object)$data$(item)@ here.  All \verb@oce@ objects are lists,
and all of them contain a \verb@data@ element of a similar form to this.
\begin{Schunk}
\begin{Sinput}
> library(oce)
> data(sealevelHalifax)
> spectrum(sealevelHalifax$data$elevation, spans = c(3, 7))
> abline(v = 1/12.42)
> mtext("M2", at = 1/12.42, side = 3)
\end{Sinput}
\end{Schunk}

\workedanswer{7}{Pressure-temperature Recorder plot}
\index{subset!using with pt data}
\index{data!tdr}

The accuracy of automatic removal of the atmospheric component done
with \verb@pt.trim()@ can be quite good if the instrument has recorded
in the air at the start and end of the record.  Even so, it always
makes sense to investigate the data by eye, in order to select a time
window.  Manual selection of a time window is also important when a
researcher is dealing with a set of instruments whose measuremnts are
to be combined and so need a uniform time base (e.g. to make a matrix
to be contoured).

The best plan is simply to plot the data interactively, and then to
narrow in on start and end times by plotting trial values, e.g.
\begin{Schunk}
\begin{Sinput}
> abline(v = as.POSIXct("2008-06-25 00:00:00"), col = "red")
\end{Sinput}
\end{Schunk}
with arrow keys being used to repeat commands that get edited as the
key times are located.


\printindex
\end{document}
