Learning Objectives
By the end of this lab, you should be able to
Find and download sea surface salinity (SSS) data from the NASA SMAP satellite
Utilize the NASA/JPL Physical Oceanography DAAC Data Subscriber tools for data access
Read in multiple files to generate a time series using a loop
Convert date string to
numpydatetimetypesWrite a function in Python to consolidate code used iteratively
Motivation¶
In the previous lab on sea surface temperature, we obtained data provided in a single, convenient netCDF file. However, we often receive data spread across many files that may not always be formatted consistently. For example, the data could be provided on different grids corresponding to the satellite swath along its orbit. In this lab, we will see how to obtain a collection of files for sea surface salinity (SSS) data and generate a time series from this set.
Sticking with the theme of the previous lab, we will consider salinity variations in the coastal ocean near Monterey Bay region. Because coastal upwelling can bring relatively salty subsurface water toward the surface, we might expect higher SSS during periods of stronger upwelling. However, the salinity signal may also reflect precipitation, evaporation, freshwater input, horizontal transport, and mixing. Let’s have a look.
Getting Started¶
Import modules for this notebook¶
To begin this lab, we’ll import the modules used in this notebook:
# import the numpy, matplotlib, netcdf4 and os modules
import numpy as np
import matplotlib.pyplot as plt
import netCDF4 as nc4
import os
# import the PO.DAAC access tools
from subscriber import podaac_data_downloader as pddNote that this notebook provides the functionality to download a set of files from JPL’s Physical Oceanography DAAC (PO.DAAC) using their podaac-data-subscriber package which we downloaded with the notes in the Getting Started section.
Info detailing how these scripts work can be found on the github page here: https://
Set paths to your local and external folders¶
In this lab, we will access a non-negligible volume of data. In the previous lab, we stored our data in the same directory as our notebook. It is good practice to maintain an organized local data repository of data obtained from online databases, so we will demo that here - and continue this practice in subsequent notebooks.
# define the path to your data folder where you will store your data
data_folder = '../data/labs/lab06'Part 1: Download SSS files¶
To begin this lab, we will obtain sea surface salinity data estimated from the NASA Surface Moisture Active Passive (SMAP) satellite obtained with the PO.DAAC tools.
User Inputs¶
Here, we will define the query parameters for our search of SSS data:
# define a start time
# must be in this format: 'YYYY-MM-DDThh:mm:ssZ:
start_date_time = '2018-01-01T00:00:00Z'
# define an end time
end_date_time = '2020-12-31T00:00:00Z'
# define a collection:
short_name = 'SMAP_JPL_L3_SSS_CAP_MONTHLY_V5'Note that the short name is identified on the PO.DAAC landing page for the data product of interest. In this lab, the SSS data is provided HERE.
Creating the Download Arguments¶
Next, we’ll organize our query using the PO.DAAC tools:
# create a parser object from the downloader package
parser = pdd.create_parser()
args = parser.parse_args(['-c',short_name, '-d',data_folder,
'-sd',start_date_time, '-ed',end_date_time, "--verbose"])Run the downloading script¶
The run method will download the files found in PO.DAAC. Nothing will print in the Jupyter notebook but the files will show up in the download folder you created above.
# run the downloading script
pdd.run(args)After this code has finished running, you will find all of the SSS data for the years corresponding to your query in your data folder.
Part 2: Generating a time series¶
Formulate a list of files¶
In the subsequent sections, we’re going to write a loop to iterate through each of the files we’ve obtained and extract the salinity data at a location of interest. In anticipation of this larger loop, here will use a shorter example of a loop to make a list of the files that we have downloaded:
# create an empty list to store the files
nc_files = []
# write a for loop to loop through the files
for file_name in os.listdir(data_folder):
# if the file is a SMAP nc file
if 'SMAP' in file_name and file_name.endswith('.nc'):
nc_files.append(file_name)
# sort the file list
nc_files.sort()
# print the number of files that are found
print('Found '+str(len(nc_files))+' files')Found 37 files
Make an array of dates¶
Now that we’ve identified our list of files, next we will construct an array of dates that will be used for our independent data (i.e. the x-axis of our time series plot). For reference, this is equivalent to the dates object we constructed for our time series of SST in the previous lab. However, the format will be slightly different. Here, we will see another date format included with the numpy package called datetime64 whereas the previous lab used a datetime object from the datetime package. As we will see in the coming labs, there are many different ways that time can be defined for computations and visualization.
To construct our date array, we will leverage the fact that each file contains the year, month, and day in the file name. When formatted as a string of the form YYYY-MM-DD, these values can be easily converted to a datetime64 object in numpy.
# make an empty list for strings storing the date
date_list = []
# loop through the file name
for file_name in nc_files:
# split the file name and retrieve the year and month strings
year_str = file_name.split('_')[3][:4]
month_str = file_name.split('_')[3][4:6]
# make a string for the middle day of the month (15)
day_str = '15'
# join the year, month, and day strings with dashes
# and add the date string to the date_list
date_list.append(year_str+'-'+month_str+'-'+day_str)
# convert the date list to array
date_array = np.array(date_list, dtype='datetime64')Make an array of SSS values¶
Now that we’ve got our time data, we’ll turn our attention to the salinity data. Below, we will loop through each of the files but before we begin, its helpful to get familiar with a single file to examine the format.
Open a single file and read in the data¶
Begin by opening one of the files in Panoply, similar to the steps we completed in the previous lab. Note the structure of the file and the names of the variables. Your view in Panoply should look like the following screenshot:

Figure 1:SMAP SSS data in Panoply
After you’ve inspected the file, use the netCDF package to read in the longitude, latitude, and SSS variables, following the steps used in the previous lab:
# create a path to the first SSS file
file_path = os.path.join(data_folder, nc_files[0])
print(file_path)
# open the netCDF file with the nc4.Dataset() method
ds = nc4.Dataset(file_path)
# read in the longitude and latitude variables
lon = ds.variables['longitude'][:]
lat = ds.variables['latitude'][:]
# read in the sss field
SSS = ds.variables['smap_sss'][:, :]
# close the netCDF file
ds.close()../data/labs/lab06/SMAP_L3_SSS_201712_MONTHLY_V5.0.nc
Find an SSS value at the location closest to Monterey Bay¶
Now that you’ve got the data read in, let’s identify a location near to Monterey Bay. As in the previous lab, we’ll define one pair of longitude and latitude values corresponding to this location:
# set the longitude and latitude of the location
site_longitude = -123
site_latitude = 37Note that this location is further offshore of Monterey than the location used in our previous lab due to issues with coastal resolution and contamination.
Then, we’ll find the closest row and column to this point, and extract the SSS value at this location:
# find the closest indices to the site longitude and latitude
lon_index = np.argmin(np.abs(lon-site_longitude))
lat_index = np.argmin(np.abs(lat-site_latitude))
# compute the closest lon and lat
closest_lon = lon[lon_index]
closest_lat = lat[lat_index]
# print the closest lon and lat to the site and
# compare with the site lons as a sanity check
print('Longitude sanity check:',site_longitude, closest_lon)
print('Latitude sanity check:',site_latitude, closest_lat)
# print the SSS value at this location
closest_sss = SSS[lat_index, lon_index]
print('Closest salinity estimate:',closest_sss)Longitude sanity check: -123 -123.125
Latitude sanity check: 37 37.125
Closest salinity estimate: 33.390404
Generalize the reading and extraction to a function¶
In the previous step, we opened a single file to get the SSS value. You could imagine copying and pasting this code for each of the files we downloaded above. However, that would be pretty inefficient. Luckily, a loop is designed precisely to run the same code over and over again - we just need to bundle our code up into a function.
Here, we will write a function that will take in a file path (a given data file) along with a location and return an SSS value based on the location:
def read_SSS_from_file(file_path, site_longitude, site_latitude):
ds = nc4.Dataset(file_path)
# read in the longitude and latiude variables
lon = ds.variables['longitude'][:]
lat = ds.variables['latitude'][:]
# read in the sss field
SSS = ds.variables['smap_sss'][:, :]
# close the netCDF file
ds.close()
# find the closest indices to the site longitude and latitude
lon_index = np.argmin(np.abs(lon-site_longitude))
lat_index = np.argmin(np.abs(lat-site_latitude))
# find the SSS value at this location
closest_sss = SSS[lat_index, lon_index]
# return the closest SSS at the location
return(closest_sss)Note that this is the exact same code from above - just written under the defined read_SSS_from_file function definition.
Make a list of SSS values¶
With our list of files in hand and our SSS function written, we’re prepared to extract the SSS values corresponding to each of our files. This loop will look quite similar to the one above for dates:
# make an empty list for the sss values
sss_values = []
# loop through the file names
for file_name in nc_files:
# define a file path
file_path = os.path.join(data_folder,file_name)
# use the SSS function to find the sss value for this file
sss_value = read_SSS_from_file(file_path, site_longitude, site_latitude)
# add the sss value to the list
sss_values.append(sss_value)Part 3: Make a plot¶
After collecting all of the salinity values in the Monterey Bay location, now we’re ready to make a plot!
Make the plot of the SSS time series¶
Using code similar to the plotting of the time series in the previous lab, make a plot of the monthly salinity values:
# make a figure of width 10 and height 4
plt.figure(figsize=(10,4))
# plot the time series
plt.plot(date_array,sss_values,'b-')
# label the y axis with the units
plt.ylabel('Salinity (psu)')
# add a title
plt.title('SMAP Sea Surface Salinity outside of Monterey Bay')
# add grid lines
plt.grid(linestyle='--',alpha=0.5,linewidth=0.5)
There is substantial seasonal and interannual variability observed in the plot above. Explain some key features and provide a hypothesis for what might contribute to this variability.
🤔 Try it for yourself!¶
In the example above, we looked at SSS in the Monterey Bay region during 2018-2020. Consider another process in the ocean that you expect to have a significant SSS signal - think about regions with strong seasonal precipitation, upwelling, ice melt, etc. Then, using the steps above, obtain some data from the SMAP SSS product and use it to examine your process of interest. Be sure to visualize a time series and consider what contributes to the observed variability.