I am a physical oceanographer interested in how ocean water is mixed and transformed. I am currently working as Research Scientist at the Bedford Institute of Oceanography in Halifax, Nova Scotia.

Recent Posts:

A perfect CTD profile

I love the function. A lot. It’s such a perfect model for a density interface in the ocean, that it is commonly used in theoretical and numerical models and I regularly used it for both research and demonstration/example purposes. Behold, a interface:

T <- function(z, T0=10, dT=5, z0=-25, dz=5) T0 + dT*tanh((z - z0)/dz)
z <- seq(0, -60)
plot(T(z), z)

plot of chunk unnamed-chunk-1

But whenever I use it, especially for teaching, I’m always saying how it’s idealized and really doesn’t represent what an ocean interface actually looks like. UNTIL NOW.

ctd <- read.oce('../assets/D19002034.ODF')
## Warning in read.odf(file = file, columns = columns, debug = debug -
## 1): "CRAT_01" should be unitless, but the file states the unit as "S/
## m" so that is retained in the object metadata. This will likely cause
## problems. See ?read.odf for an example of rectifying this unit error.
par(mfrow=c(1, 2))
plot(ctd, which=1, type='l')
plot(ctd, which=5)

plot of chunk unnamed-chunk-2

Yes, this is real data.

Just how close to a is it?1

z <- -ctd[["depth"]]
T <- ctd[["temperature"]]
m <- nls(T~a+b*tanh((z-z0)/dz), start=list(a=3, b=1, z0=-10, dz=5))
## Nonlinear regression model
##   model: T ~ a + b * tanh((z - z0)/dz)
##    data: parent.frame()
##        a        b       z0       dz 
##   3.7251   0.9516 -25.0448  -2.7648 
##  residual sum-of-squares: 0.05222
## Number of iterations to convergence: 16 
## Achieved convergence tolerance: 4.394e-06
plot((T-predict(m))/T * 100, z, type="o", xlab='Percent error')

plot of chunk unnamed-chunk-3

  1. My PhD advisor, who also taught me introductory physical oceanography, once said to a class of students while using tanh to describe an idealized interface: “tanh – it’s like ‘lunch’, only better!” 

Negating functions and function definitions: an 'opposite' function to the wonderful `%in%` operator


R has some neat functions, and even some weird quirks, that you aren’t likely to discover on your own but can either be immensely helpful or horribly confounding.

For example, the “+” operator (i.e. addition) is actually a function, and can even be called using the typical “bracket” notation:

1 + 2
## [1] 3

We can use backticks to evaluate the function as a “regular” function:

## function (e1, e2)  .Primitive("+")

And can therefore call it as a “regular” function, using brackets to pass the arguments:

`+`(1, 2)
## [1] 3

One consequence of this is that it is possible to redefine how “+” works:

`+` <- function(x1, x2) x1 - x2
1 + 2
## [1] -1

Ok … admittedly that’s confusing. Why would you want to redefine “+”? Well, one example is given by the syntax of the ggplot2 package, which defines it’s own version of “+” that lets you string plotting functions together to build up a plot (e.g. see my post about plotting here).

The %in% function

The %in% function is one of those functions that just clicked when I started using R. It’s an elegant way to write conditional statements – it checks whether the object to the left of the operator occurs anywhere in the object on the right of the operator. An example:

Does the number 5 occur in the vector of 1 through 10?

5 %in% 1:10
## [1] TRUE

Yes, it does (obviously).

One thing that I often find myself doing however, is wanting to know if something doesn’t occur in another object. To make that work, I usually wrap the whole statement in brackets and then precede with an ! operator (logical negation). Like this:

!(11 %in% 1:10)
## [1] TRUE

This evaluates to TRUE because 11 is not in the vector 1:10. While this works, it’s always bugged me because it just looks inelegant.

Well, while browsing Twitter recently, I came across this post from @groundwalkergmb:

First, note the (confusing) syntax that you don’t actually have to negate the entire expression. It is equivalent to write:

!11 %in% 1:10
## [1] TRUE

Ew. Gross! (@groundwalkergmb agrees with me about this)

But reading through the comments led me to this one:

Basically, you can use the Negate() function (never knew about this before) to create a new function which returns the logical negation of the output of the original.

`%nin%`<- Negate(`%in%`)
11 %nin% 1:10
## [1] TRUE

A Shiny app that uses 'reactive' data


A powerful, and increasingly useful, tool available to users of R, is the interactive app package known as Shiny. Shiny provides a framework for building interactive web apps that can be used for visualization, exploratory data analysis, data quality control – really anything that could benefit from an interactive environment.

This post will not go into the basics of Shiny. There are many resources on the web for getting started, and of particular value is the RStudio Shiny gallery.

The purpose of this post is two-fold: to test the embedding of a Shiny app within a jekyll blog post, and to document a test app that I made that uses “reactive data”.

Using Shiny apps with jekyll

In order to run a Shiny app, a “shiny server” is required. The easiest way to do this is to install the necessary R packages (e.g. install.packages('shiny')) on your computer, and run a “local” server. This is very easy to do within RStudio, but it can also be done from the system command line, e.g. using a command something like:

$ Rscript -e "library(shiny); runApp(port=4321)"

Then, opening a web browser to the url will display and run the app. However, the app is only available on the machine that it is being run, and not as a distributed web app that other users can connect to.

For webs that are hosted and made available to others, a proper Shiny server environment must be installed on a properly configured web server. Thankfully Shiny Server is free (and open source), however the configuration of a proper server is not a task for the uninitiated.

Another option is to use the ShinyApps.io service that is provided by RStudio. The free option allows for 5 applications, with a limited amount of server time available (25 hours per month at the time of writing).

For a Github-pages hosted site (like this one), the lack of an R environment and a shiny server on Github means that any apps to be included in posts must be hosted somewhere else. For this example, I will use my shinyapps.io account.

Reactive data

The premise of “reactive data” (actually, the concept of “reactive” in the context of Shiny apps is really a fundamental principle) is one where the data being used in the app may change from time to time. In a regular R script, loading data using commands like load(), read.csv(), etc is easy and will occur every time the script is run. However, in a shiny app, using such commands may result in the data being loaded only when the server is started, but then not updating with time as the data being loaded is changed (e.g. if more data is downloaded).

To get around this, we use the shiny function reactiveFileReader(), which allows the data reading to occur as a “reactive” object, meaning that it can be updated (at prescribed intervals) even while the app is running.

The example code below is a simple app I made to demonstrate the principle. In it, the user clicks the action button to generate new data, which is saved as a .rds object in the server file system. That rds object is then read by the file reader, which checks for changes every 1000 milliseconds (1 second) and only re-reads the file if the data has changed when it checks. It’s a silly way to make an interactive plot that updates with new data, but demonstrates the principle of reactive data well.


new_data <- function() {
    d <- list(a=1:100, b=rnorm(100))
    saveRDS(file='data.rds', d)

server <- function(input, output, session) {
    data <- reactiveFileReader(1000,

    observeEvent(input$newdata, {
    output$plot1 <- renderPlot({

ui <- fluidPage(    
    ## Give the page a title
    ## Generate a row with a sidebar
        ## Define the sidebar with one input
            actionButton(inputId = 'newdata',
                         label = 'Generate new data')
        ## Create a spot for the barplot

shinyApp(ui = ui, server = server)

The app

To include the app in the post, we upload it to shinyapps.io, and then include it as an iframe object, with (note the html comment tags around the iframe code chunk to keep it from evaluating in HTML):

<!-- <iframe id="example1" src="https://clarkrichards.shinyapps.io/reactiveData/" 
style="border: non; width: 100%; height: 500px" 
</iframe> -->

Using the oce package to make nice maps


Making maps is a pretty important part of doing, and presenting, ocean data analyses. Except for very small domains, using map projections is crucial to ensure that the map is not distorted. This is particularly true for polar and high latitude regions, such as the Arctic (where I do much of my work).

In this post I will give a brief introduction to making projected maps with the oce package, including not just the land/coastline but also various ways of plotting the bathymetry. For the latter I will discuss the handy marmap package.

Making a polar stereographic map of the Canadian Arctic

To make “projected” maps with oce, you can use the mapPlot() function. The easiest way is to use mapPlot() with a coastline object, to set the projection you want, and then add other elements (such as bathymetry, etc) using functions like mapLines(), mapPoints(), mapImage(), etc. You may need to redo the coastline at the end to clean up anything that might have plotted over land that you don’t want.

The coastlineWorldFine dataset from the ocedata package is pretty good for sub-regions such as the Canadian Arctic.

## Loading required package: testthat
## Loading required package: gsw
library(ocedata) #for the coastlineWorldFine data

To get the projection you want, it must be passed in the projection= argument using “proj4” syntax as a character string. You can read up on the syntax and available projection in the help – i.e. ?mapPlot, or have a look at:


For polar maps, the most commonly used is the stereoraphic projection:

## Save it to a function to make it easy to re-run
mp <- function() {
    mapPlot(coastlineWorldFine, projection="+proj=stere +lon_0=-90 +lat_0=90",
            longitudelim = c(-120, -60),
            latitudelim = c(60, 85), col='grey')

plot of chunk unnamed-chunk-2

In this example, the +lon_0 parameter defines the longitude at the center of the projection, and the +lat_0 is the latitude at the center of the projection. The mapPlot() arguments longitudelim and latitudelim are used to control the extent of the map.

As for adding bathymetry, there are a few options:

  1. oce includes a low-res version of the etopo dataset, called topoWorld that can be used, either as a contour plot or as an image plot.

  2. The marmap package allows easy downloading of subsets of the full resolution etopo data, which can be used to make nicer plots. One downside is that because of the “triangle” nature of a polar stereoraphic projection you have to download a lot more data than you really need.

Using topoWorld

A quick way of adding bathymetry is to simply use the mapContour() function (analogous to the base-R contour()).

mapContour(topoWorld, levels=-c(500, 1000, 2000, 4000),

plot of chunk unnamed-chunk-3

Contour plots can be tricky, because of the labeling etc, and choosing which contours to plot. Another option is to use the mapImage() function:

mapImage(topoWorld, col=oceColorsGebco, breaks=seq(-4000, 0, 500))
mapPolygon(coastlineWorldFine, col='grey')

plot of chunk unnamed-chunk-4

But sometimes using mapImage() shows off the “blockiness” of the low-res topoWorld dataset – especially near the poles where the shape of the cells (evenly divided in lon/lat space) gets really skinny.

One fix is to use a higher res data set (so the “boxes” are smaller – see next section). Another is to use the fillContour argument in mapImage() to plot filled contours rather than the individual grid cells.

mapImage(topoWorld, col=oceColorsGebco, breaks=seq(-4000, 0, 500), filledContour = TRUE)
mapPolygon(coastlineWorldFine, col='grey')

plot of chunk unnamed-chunk-5

Using marmap

Here we load the marmap package and download the bathymetry. Note that because we have the North Pole in view, we basically have to download an entire half hemisphere. It takes a little while to download, but if you use the keep=TRUE argument then it will just reload it from the file each time.

However, because there is so much more data, the plotting can be quite a bit slower.

## Attaching package: 'marmap'
## The following object is masked from 'package:oce':
##     plotProfile
## The following object is masked from 'package:grDevices':
##     as.raster
b <- as.topo(getNOAA.bathy(-180, 0, 55, 90, keep=TRUE))
## File already exists ; loading 'marmap_coord_-180;55;0;90_res_4.csv'
mapImage(b, col=oceColorsGebco, breaks=seq(-4000, 0, 500))
mapPolygon(coastlineWorldFine, col='grey')

plot of chunk unnamed-chunk-6

Looks pretty good, though!

The (ocean) physics of The Ocean Cleanup's System 001


The Ocean Cleanup, brainchild of Dutch inventor Boyan Slat, was in the news again this past week after announcing that in addition to the fact that their system is unable to collect plastic as intended, it suffered a mechanical failure. “Wilson” is currently being towed to Hawaii, where it will undergo repairs and upgrades, presumably to be towed back out to the garbage patch for a second trial.

I am not a mechanical engineer, so I don’t intend to comment on the details of their mechanical failure. I am, however, a sea-going oceanographer. Which means that I am used to the sorts of situations with scientific research equipment that was so succinctly paraphrased by Dr. Miriam Goldstein:

“The ocean is strong and powerful, and likes to rip things up.”

Dr. Miriam Goldstein. Prescient oceanographer

In short – the ocean is a difficult place to work. There are literally CONFERENCES dedicated to the engineering of putting thing out to sea and having them survive (see the MTS Buoy Workshop, which I have participated in). There is a saying in oceanographic fieldwork: if you get your gear back, it was a successful program. If it recorded data – that’s icing on the cake.

Designing for physics

But beyond the engineering, there are the questions of what the physics are that TOC are relying on for their system to be successful. Some of you may recall that the original design was to moor (i.e. anchor) their device in 6000m (20000 feet) of water, and let existing ocean currents sweep garbage into the U-shaped structure. Thankfully, they realized the challenges associated with deep-ocean moorings, and abandoned that idea.

The latest design iteration (misleadingly called “System 001”, as though they haven’t built and tested any other previous to it), is to have a freely-drifting system, avoiding the use of anchors. TOC claim that under the influence of current, wind, and waves, their design will drift faster than the plastic – causing it to accumulate in the U, making for easy pickup. They summarize the concept with a little explainer video on their website, with a representative screen shot below:

Nice how the wind, waves, and current all are going in the same direction!!!

Based on a quick Twitter rant that I had after thinking about all this for a few minutes (see here), I wanted to explain out the various points that have either a) been missed by TOC design team, or b) deliberately excluded from their rosy assessment of how they expect their system to actually collect garbage. What follows is a “first stab” at a physical oceanographic assessment of the basic idea behind “System001”, and what TOC would need to address to convince the community (i.e. scientists, conservationists, etc) that their system is actually worth the millions of dollars going into development and testing.

The premise

As outlined in the video, the premise of System001 as a garbage collection system is that through the combined action of wind, waves, and currents, the U-shaped boom will travel faster through the water than the floating plastic, thereby collecting and concentrating it for eventual removal. This appears to be based on the idea that while both the boom and the plastic will drift with the current, because the boom protrudes from the water (like a sail), it will actually move faster than the surface water by catching wind.

There are some issues with this premise. Or, at least, there are some real aspects of oceanography that have either been ignored or missed in thinking that such a system will behave in the predictable way described by TOC. I’ll try and outline them here.

Stokes drift

Any of you who may have had an introduction to ocean waves may have heard that during the passage of a wave, the water particles move in little circles (often called wave orbital motion). While not a bad “first-order” description, it turns out that for real ocean waves there is also some drift in the direction of wave propagation. This drift is named after Gabriel Stokes, who first described it mathematically in 1847 (see wikipedia article here).

Stokes drift, from https://www.researchgate.net/publication/315739116_Breaching_of_Coastal_Barriers_under_Extreme_Storm_Surges_and_Implications_for_Groundwater_Contamination_Application_of_XBeach_in_Coastal_Flood_Propagation/figures?lo=1

The amount of drift depends nonlinearly on both the amplitude and the wavelength of the wave. For example, for a 0.5m amplitude wave with a wavelength of 10m and period of 10s (something like typical ocean swell), the drift velocity is about 10 cm/s right at the surface.

Of course, the Stokes’ solution describes the motion of the water parcels being moved by the wave. For those water parcels to then have an effect on anything in the water, one would need to consider the various components of force/impulse/momentum (i.e. our buddy Sir Isaac Newton). Needless to say, it seems obvious that a smallish piece of neutrally buoyant plastic will respond to the Stokes drift much more readily than a 600m long floating cylinder with a large mass (and therefore large inertia).

This alone could be enough to quash the idea of a passive propagating collection system.

Ekman currents

While we’re talking about long-dead European fluid mechanics pioneers, any study of the effect of winds and currents wouldn’t be complete without a foray into the theories proposed by Swedish oceanographer Vagn Walfrid Ekman in 1905. What Ekman found was that when the wind blew over the surface of the ocean, the resulting current (forced by friction between the air and the water) didn’t actually move in the same direction as the wind. The reason for this is because of the so-called “Coriolis effect”, whereby objects moving on the surface of the Earth experience an “acceleration” orthogonal to their direction of motion that appears to make them follow a curved path (for those who want to go down the rabbit hole, the Coriolis acceleration is essentially a “fix” for the fact that the surface of the Earth is non-inertial reference frame, and therefore doesn’t satisfy the conditions for Newton’s laws to apply without modification).

Anyway – the consequence is that in an ideal ocean, with a steady wind blowing over the surface, the surface currents actually move at an angle of 45 degrees to the wind direction! Whether it’s to the left or right of the wind depends on which hemisphere you are in – I’ll leave it as an exercise to determine which is which. And what’s cooler, is that the surface current then acts like a frictional layer to the water just below it, causing it to move at an angle, and so on, with the effect being that the wind-forced flow actually makes a SPIRAL that gets smaller with depth. This is known as the Ekman spiral.

Ekman spiral, from http://oceanmotion.org/html/background/ocean-in-motion.htm

The actual depth that the spiral penetrates to depends on a mysterious ocean parameter called Az, which describes the vertical mixing of momentum between the layers – kind of like the friction between them. What is clear though, is that a small particle of plastic floating close to the surface and a 3m deep floating structure will likely not experience the same wind-forced current, and therefore won’t move in the same direction. Hmmm … that’s going to make it hard to pick up pieces of plastic.

What is a “Gyre” anyway?

The final point I wanted to make in this article (I have more, which I’ll summarize at the end for a possible future article), is to try and give a sense of what currents in the ocean (including in the “gyre” or in the region often referred to as the “Great Pacific Garbage Patch”) actually look like. The conception that there is a great swirling current 1000’s of km across is true only when the currents are averaged for a very long time. At any given instant, however, the ocean current field is a mess of flows at various space and time scales. An appropriate term for describing typical ocean flow fields is “turbulent”, as in an oft-viewed video made by NASA from satellite ocean current data.

To illustrate this, I took some screenshots of current conditions from the wonderful atmosphere/ocean visualization tool at earth.nullschool.net showing: ocean currents, surface waves, and wind.

Ocean currents

Ocean waves


These images illustrate the potential problem with TOC idea, by highlighting the fact that the wind, wave, and current fields of the ocean (including even in the “quiet” garbage patch) are highly variable spatially and temporally, and are almost never aligned at the same period in time. What’s more, is that the currents and waves at a given time and location are not always a result of the wind at that location. Eddies in the ocean are generated through all kinds of different processes, and can propagate across ocean basins before finally dissipating.

Similarly, surface waves have been measured to cross oceans (i.e. the famous “Waves across the Pacific” study pioneered by the transformative oceanographer Walter Munk).

Other issues

Following the “rule of three”, I tried to hit what I consider to be the biggest concerns with TOC system design and principle, from my perspective as a physical oceanographer. However, there are other issues that should be addressed, if the system as designed is really believed by the TOC team to be capable of doing what they say. And really, it seems like a crazy waste of time on behalf of everyone involved to have spent this much time on something if they aren’t sure it will even work theoretically … not to mention the money spent thus far. So, part of me has to believe that all the dozens of people involved care deeply about making something that might actually work, and they have studied and considered all the effects and potential issues I (and others) have raised.

Anyway, the other issues are:

  • What is the actual response of the system to a rapid change in wind/wave direction? Wind can change direction pretty quickly, especially compared to ocean currents. What’s to prevent a bunch of accumulated plastic getting blown out the open end of the U after a 180 degree shift in wind but before the system can re-orient?

  • What about wave reflection from the boom structure itself? It is a well-known fact that objects (even floating ones) can reflect and “scatter” waves (scattering is when the reflected waves have a shorter wavelength than the original ones), and it seems like this could create a wave field in the U that might actually cause drift out of the system.

  • The idea that all wildlife can just “swim under” the skirt (because it’s impermeable) is not supported by anything that I consider to be rigorous fluid mechanics, aside from the fact that much of what actually lives in the open ocean are non-motile or “planktonic” species. There are a lot of communities in the open ocean that float and drift at the surface, and I see no way that if the System collects floating plastic as it is designed that it won’t just sweep up all those species too. The latest EIA brushed off the effect of the System on planktonic organisms by stating that they “are ubiquitous in the world’s oceans and any deaths that occur as a result of the plastic extraction process will not have any population level effects”. But that doesn’t take into account that the stated mission is to deploy 60 such systems, which are estimated to clean the garbage patch of surface material at a rate of 50% reduction every 5 years. It stands to reason that they would also clean the Pacific of its planktonic communities by the same amount.