Exercise 1 - Profile data#

Aim: To work with vertical profile data and make some standard calculations.

Learning outcomes: At the end of this lab, you will be able to:

  1. Calculate buoyancy frequency

  2. Calculate dynamic height

  3. Gain basic familiarity with Python xarray data arrays, and reading and writing *.nc files using xarray.

Data: You will work with the CNV files from the MSM121 cruise off of 47°N.

Directions: Answer the questions, create an *.ipynb and 5 figures. Make sure you follow the file naming convention.

Measure of success: You will have created a python notebook, a netCDF file (not added to the git repository) and the 5 figures exported as *.png format into your folder; these will be “commited” and “pushed” to the shared repository, and viewable by everyone. Additionally, copy your 2 best figures to the shared_figures/ folder for discussion.


Create a notebook#

Create an *.ipynb containing the commands for this assignment, or copy this file.

File naming convention

Name your python notebook something useful ex<X>-<slug>-<Lastname>-seaocn.ipynb where you replace <X> with the exercise number and <slug> with the short slug to name the topic, and <Lastname> with your last name.

Figures should be named something like ex<X>fig<Y>-<Lastname>-<slug>-seaocn.png where you replace <X> with the exercise number, <Y> with the figure number, and <Lastname> with your last name.

Import necessary packages.#

For example, matplotlib and pandas and numpy and xarray. You may also need

import matplotlib.pyplot as plt
import pandas as pd
import gsw 
import numpy as np
import xarray as xr
from datetime import datetime

Here you have two options (there may be more) for working with *.cnv files. They are pycnv and seabird, as

You may try either of these. Note that pycnv will create its own data type which you will need to conver to xarray. seabird can be used to create a netCDF file (*.nc) which is a format that xarray can handle.

Both of these packages are designed to run on *.cnv files. Normally, the data will first need to be converted from *.hex to *.cnv using the Seabird processing. There is a “wrapper” written to call Seabird processing from within python, but it does require the Seabird software to already be installed on the computer (therefore the computer needs to be running Windows). See Seabird-processing (link).

If you are missing any of the packages that you decide you need, please refer to Resources: Python.

For processing directly from *.hex, there is some python code available here by Jody Klymak. It was written for a specific set of SeaCat files, and so may not be generalised to all the possible (especially header) formats for Seabird instruments.

# Importing required packages here
import matplotlib.pyplot as plt
import numpy as np

Using pycnv#

Load the data with pycnv#

The data are in a *.cnv file. This is text file in the format from the Seabird Electronics manufacturer. The package pycnv has been developed to read Seabird data into python, but functionality is limited.

Note

You will want to convert the pycnv format to xarray for later labs.

For data located in the directory msm121_profiles, you need to provide the filename with full path as an input to pycnv.

file_path1 = '../msm121_profiles/MSM121_015_1db.cnv'
cnv1 = pycnv.pycnv(file_path1)

# Print some info to the screen
print('Test if we are in the Baltic Sea (usage of different equation of state): ' + str(cnv1.baltic))
print('Position of cast is: Longitude:', cnv1.lon,'Latitude:',cnv1.lat)
print('Time of cast was:', cnv1.date)
print('Number of sensor entries (len(cnv.data.keys())):',len(cnv1.data.keys()))
print('Names of sensor entries (cnv.data.keys()):',cnv1.data.keys())

Write your version of this code below. If successful, you’ll see output like

INFO:pycnv: Opening file: ../msm121_profiles/MSM121_015_1db.cnv
Test if we are in the Baltic Sea (usage of different equation of state): False
Position of cast is: Longitude: nan Latitude: nan
Time of cast was: 2024-03-12 13:06:47+00:00
Number of sensor entries (len(cnv.data.keys())): 8
Names of sensor entries (cnv.data.keys()): dict_keys(['scan', 'timeK', 'tv290C', 'cond0mS/cm', 'sal00', 'prdM', 'p', 'flag'])

Note that the dict_keys tells you what your variable names were in the file, and gives you an idea of how to access them.

# Loading the data

Display parameters#

You can see in the example code previously or here:

key0 = list(cnv1.data.keys())[0]
data0 = cnv1.data[key0]
print(cnv1.data)

various ways to interact with the pycnv data type.

# Try printing to see what is in your data

Fig. 1 Make a profile plot#

Plot standard parameters#

pl.figure(1)
pl.clf()
pl.subplot(1,2,1)

Note that pycnv already did the TEOS-10 conversion to SA for you using gsw#

pl.plot(cnv.SA,cnv.p)
pl.xlabel('Absolute salinity [' + cnv.SA_unit + ']')
pl.ylabel('Pressure [' + cnv.p_unit + ']')
pl.gca().invert_yaxis()  # Question: What happens if you comment out this line?

Modify your plot:

  1. Add grid lines

  2. Limit the top of the plot to the surface (p=0)

  3. Add a second plot for temperature, to the right of the salinity plot

  4. Add a title to your figure, perhaps the station number, latitude and longitude

  5. Print the figure to a *.png file in the subdirectory figures/

Note

Naming convention should be ex<X>fig<Y>_<Lastname>-seaocn.png where you replace <X> with the exercise number, <Y> with the figure number, and <Lastname> with your last name.

# Make your plot

Convert to netCDF and load with xarray#

  • First, on your computer (after installing the seabird (link) package, run it on one *.cnv file to create a *.nc file.

    seabird cnv2nc MSM121_054_1db.cnv
    
  • xarray is a python package commonly used for ocean and climate science. While you could continue working with the pycnv format, it will become a hindrance later.

See also

Read the docs: xarray.DataArray

Alternative

You can instead convert your pycnv format data into an xarray dataArray, but I suspect this may be slightly more complicated.

# Load your *.nc file

Work with data in xarray#

Use the print command to see what is in your data array. A data array is a bit like a file folder, with different variable types in it.

# Print your data

Calculate TEOS-10 parameters#

  • Calculate absolute salinity and conservative temperature

  • Repeat for both primary and secondary channels

# Calculate TEOS-10 parameters

Add these data to your xarray data array#

  • Name them ‘SA’ and ‘CT’ for absolute salinity and conservative temperature

  • And ‘SA2’ and ‘CT2’ for secondary

See also

Some functions to get you started reading the xarray docs: https://docs.xarray.dev/en/latest/generated/xarray.Dataset.assign.html

# Add additional data fields

Save an xr.da to *.netCDF file#

Now that your data are in xarray.DataArray format, you can use tools within xarray to write a netCDF file.

See also

Function help for xarray.Dataset.to_netcdf


Fig 2. Repeat the profile plot#

As above, but with the data in xarray format.

Modify your plot:

  1. Add grid lines

  2. Limit the top of the plot to the surface (p=0)

  3. Add a second plot for temperature, to the right of the salinity plot

  4. Add a title to your figure, perhaps the station number, latitude and longitude

  5. Export the figure using the figure naming convention, to the subfolder figures/.

# Plot the data

Fig 3. Make a T-S diagram#

A T-S diagram has salinity on the x-axis and temperature on the y-axis, and contours of density (sigma_0) added.

Modify your plot by

  1. Add contours of potential density

    • Hint, you will need to create a vector of temperature and salinity spanning at least the ranges in the profile

    • You will then need to use these gridded vectors to calculate potential density using the gsw toolbox

  2. Add contour labels for the density

  3. Add a title

  4. Export the figure using the figure-naming convention, to the subfolder figures/

# Plot a T-S diagram

Clean up the plots#

Go back and clean up the plots if needed. This means, add a legend, axes labels, fix the time axis annotations if needed, and fix the fontsize to be legible even if the figure is small.

Note

In future exercises, you will be expected to clean up all plots without reminders. All plots should have axes labelled (with units!), legible font size (bigger than you think) and appropriate axis ranges. Legends should be used whenever more than one quantity is plotted.

  • Re-export the figures with the same names as before.


Further calculations#

Calculate buoyancy frequency#

Buoyancy frequency is a measure of how strongly a vertical profile is stratified. It is calculated as

\[ N^2 = \partial b/\partial z \]

where buoyancy \(b\) is

\[ b(z) = -g\frac{\rho(z)}{\rho_0} \]

and \(g\) is gravitational acceleration, \(\rho(z)\) the profile of density, and \(\rho_0\) a background mean value of density. (The exact value of \(\rho_0\) doesn’t matter much. Something like 1023 or 1025 kg/m\(^3\) will do fine.)

You can do this two ways.

  1. Calculate density using the Gibb’s seawater toolbox GSW density, and

  2. Use the GSW function for buoyancy frequency under GSW stability.

Fig 4. Plot buoyancy frequency#

Try and plot both ways on the same axes.

Note

The convention in oceanography is that the N\(^2\) axis is a log10 axis. Do you have a noisy plot? (Optional:) The way we calculate buoyancy frequency in practice is to use one of a few possible techniques to smooth the data.

  1. Export your figure.

# Calculate buoyancy frequency
# Plot buoyancy frequency

Calculate dynamic height#

Small variations in seawater density affect both ocean circulation and sea level. According to the hydrostatic approximation, the vertical gradient of pressure is a function of density \(\rho\) and gravitational acceleration \(g\) as

\[ \frac{\partial p}{\partial z} = -\rho g \]

if we want to integrate to find the height of the surface above a profile of given density, we can calculate

\[ h = \int_{p_r}^p\frac{dp}{-\rho g} \]

which has units of meters.

Dynamic height is a similar quantity, but accounts for gravity already (has units of m\(^2\)/s\(^s\) and is used in the geostrophic velocity/transport calculation.

See also

See dynamic height calculations in the GSW toolbox

Fig 5. Plot dynamic height#

  1. Plot dynamic height against depth or pressure

  2. In a separate plot in the same figure, convert dynamic height to steric height (units of m) and plot it.

  3. Extra (optional): Calculate dynamic height manually by using the specific volume anomaly.

# Calculate dynamic height
# Calculate steric height
# Plot dynamic height + steric height