---
title: "gsw"
author: "Dan Kelley and Clark Richards"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
    number_sections: true
    fig_caption: yes
    fig_width: 5
    fig_height: 5
    dpi: 72
    dev.args: list(pointsize=11)
vignette: >
  %\VignetteIndexEntry{gsw}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
<!-- There is a problem in running this vignette in the normal way, because ``oce'' is -->
<!-- used to create the figures, but oce depends on gsw! There is no way to break the circle -->
<!-- for building on CRAN, but the developer can handle this easily because he has both oce -->
<!-- and gsw on his machine. His steps in updating the vignette (which is done infrequently) -->
<!-- are as follows, 2 and 3 being most important. ->
<!-- 1. Edit this file to update the content -->
<!-- 2. Edit this file with '%s/ eval=FALSE/ eval=TRUE/gc' in vim (keep this line and line 33, through) -->
<!-- 3. In a console centred in this directory, do -->
<!--     knitr::purl("gsw.Rmd") -->
<!-- to create a new gsw.R file -->
<!-- 4. Run this gsw.R file to update the figures.-->
<!-- 5. Return here, open a console, and do-->
<!--     devtools::build_vignettes() -->
<!-- to update the vignette. -->
<!-- 6. Edit this file with '%s/ eval=TRUE/ eval=FALSE/gc' in vim (keep this line and line 25, though) -->
<!-- 7. Build package in normal way -->

**Abstract.** The `gsw` package provides an R implementation of the Gibbs
SeaWater toolbox for the calculation of seawater properties (version 3.05).
This vignette outlines how to use `gsw` alone or as part of the `oce` package.

# Introduction

In recent years, thermodynamic considerations have led to improved formulae for
the calculation of seawater properties (IOC, 2010; Millero et al 2010), an
important component of which is the Gibbs-SeaWater (GSW) toolbox (McDougall
2011; Pawlowicz et al 2012). The `gsw` package is an R version of GSW, which
may be used independently or within the more general `oce` package (Kelley and
Richards 2016).

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
[http://www.teos-10.org](http://www.teos-10.org), which provides technical
manuals for the Matlab version of GSW
[http://www.teos-10.org/pubs/gsw/html/gsw_contents.html](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. 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 at [http://www.teos-10.org](http://www.teos-10.org),
including expansive white papers and pointers to the growing peer-reviewed
literature (Wright et al.  2011; McDougall et al. 2012; Graham et al. 2013)


# Using gsw independent of oce

```{r echo=FALSE, results="hide"}
options(keep.source=TRUE, width=60, prompt=' ', continue=' ', oceEOS="unesco")
```

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

```{r}
library(gsw)
SA <- gsw_SA_from_SP(SP=35, p=100, longitude=188, latitude=4)
```

This yields 
`SA`=`r SA` [g/kg], which can then be used to 
calculate Conservative Temperature as follows.

```{r}
CT <- gsw_CT_from_t(SA=SA, t=10, p=100)
```

The above yields `CT`=`r 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 sixty functions that
`gsw` provides.

# Using gsw within oce

![**Figure 1.** TS diagram with UNESCO formulation](TS_unesco.png)

![**Figure 2.** TS diagram with GSW formulation](TS_gsw.png)


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

```{r eval=FALSE, echo=FALSE}
png("TS_unesco.png", width=353, height=353, pointsize=12)
```

```{r 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")
```

```{r eval=FALSE, echo=FALSE}
dev.off()
png("TS_gsw.png", width=353, height=353, pointsize=12)
```

For comparison, it helps to plot a `gsw` equivalent with the same plot limits (Figure 2).
```{r eval=FALSE}
plotTS(ctd, Slim=Slim, Tlim=Tlim, eos="gsw")
```

```{r eval=FALSE, echo=FALSE}
dev.off()
png("TS_gsw.png", width=353, height=353, pointsize=12)
```


Most hydrography-related functions of `oce` provide this `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 `section` is
constructed as Figure 3 with

```{r eval=FALSE, echo=FALSE}
png('temperature_comparison.png', width=353, height=252, pointsize=12)
par(mar=c(3.2, 3, 1, 1/2), mgp=c(2, 0.85, 0))
```

```{r eval=FALSE}
f <- (section[["CT"]] - section[["theta"]]) / section[["CT"]]
hist(f, main="", xlab="(CT-theta)/CT")
```

A salinity comparison (Figure 4) is constructed with

```{r eval=FALSE, echo=FALSE}
dev.off()
png('salinity_comparison.png', width=353, height=252, pointsize=12)
par(mar=c(3.2, 3, 1, 1/2), mgp=c(2, 0.85, 0))
```

```{r eval=FALSE}
f <- (section[["SA"]] - section[["salinity"]]) / section[["SA"]]
hist(f, main="", xlab="(SA-SP)/SA")
```

![**Figure 3.** Comparison of GSW Conservative Temperature and UNESCO potential temperature for the `section` dataset, spanning the mid-latitude North Atlantic.](temperature_comparison.png)

![**Figure 4.** Comparison of Absolute Salinity and Practical salinity for the `section` dataset.](salinity_comparison.png)


```{r eval=FALSE, echo=FALSE}
dev.off()
png("SSS_2.png", width=588, height=336)
```

An examination of worldwide spatial patterns is also informative. Figure 5, for example,
is produced as follows.

```{r eval=FALSE}
library(oce)
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)
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(expression("Percent difference between " * S[A] * " and " * S[P]))
```

```{r eval=FALSE, echo=FALSE}
dev.off()
```

![**Figure 5.** Percent difference between surface Absolute Salinity and Practical Salinity, for Levitus dataset.](SSS_2.png)

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; a broader context has
been detailed in the literature (McDougall et al. 2012).

# References

Graham, F. S. and T. J. McDougall, 2012.  Quantifying the Nonconservative
Production of Conservative Temperature, Potential Temperature, and Entropy.
Journal of Physical Oceanography, 43(5):838-862.
[http://dx.doi.org/10.1175/JPO-D-11-0188.1](http://dx.doi.org/10.1175/JPO-D-11-0188.1)

IOC and SCOR and IAPSO, 2010.  Intergovernmental Oceanographic Commission,
Manuals and Guide, 56, UNESCO.
[http://www.teos-10.org/pubs/TEOS-10_Manual.pdf](http://www.teos-10.org/pubs/TEOS-10_Manual.pdf)

Kelley, D. and C. Richards, 2016.  oce: Analysis of Oceanographic data, R
package version 0.9-18.  Comprehensive R Archive Network.
[http://dankelley.github.com/oce](http://dankelley.github.com/oce)

McDougall, T. J. and P. M. Barker,2011.  Getting started with TEOS-10 and the
Gibbs Seawater (GSW) Oceanographic Toolbox.  SCOR/IAPSO WG127.
978-0-646-55621-5.

McDougall, T. J., D. R. Jackett, F. J. Millero, R. Pawlowicz and P. M.  Barker, 
2012.  A global algorithm for estimating Absolute Salinity.  Ocean Science,
       8:1123-1134.
       [http://www.ocean-sci.net/8/1123/2012/os-8-1123-2012.pdf](http://www.ocean-sci.net/8/1123/2012/os-8-1123-2012.pdf)

Millero, F. J. 2010.  History of the equation of state of seawater.
Oceanography, 23:18-33.
[http://www.tos.org/oceanography/article/history-of-the-equation-of-state-of-seawater](http://www.tos.org/oceanography/article/history-of-the-equation-of-state-of-seawater)

Pawlowicz, R., T. McDougall, R. Feistel and R. Tailleux, 2012.  Preface ``An
historical perspective on the development of the Thermodynamic Equation of
Seawater--2010''}.  Ocean Science, 8:161-174.
[http://www.ocean-sci.net/8/161/2012/os-8-161-2012.pdf](http://www.ocean-sci.net/8/161/2012/os-8-161-2012.pdf)

Wright, D. G., R. Pawlowicz, T. J. McDougall, R. Feistel and G. M.  Marion,
2011.  Absolute Salinity, Density Salinity and the Reference-Composition
   Salinity Scale: present and future use in the seawater standard TEOS-10.
   Ocean Science, 7:1-26.
   [http://www.ocean-sci.net/7/1/2011/os-7-1-2011.pdf](http://www.ocean-sci.net/7/1/2011/os-7-1-2011.pdf)

```{r results="hide", echo=FALSE}
options(prompt='> ', continue='+ ', oceEOS="unesco")
```

