In this notebook, you’ll learn to assess trends in time series in passive microwave sea ice data available from the National Snow and Ice Data Center.
This notebook has four components:
Download sea ice concentration data from the National Snow and Ice Data Center
Generate a monthly time series of sea ice area from 1979 to 2025
Analyze trends of sea ice area during the September sea ice minimum
Compute the trend in sea ice in a given area
Import the modules for this notebook
import numpy as np
import matplotlib.pyplot as plt
import netCDF4 as nc4
import os
import datetime as dt
import requestsPart 1: Downloading Sea Ice Data from NSIDC¶
This notebook is designed to download sea ice concentration data, available at https://data_folder where you will download the sea ice data.
# define a path to your raster files folder
data_folder = '../data/labs/lab07'Make a list of file paths¶
Next, we’ll make a list of download links to the monthly sea ice files. The code below will generate a list of all files from 1979 through 2025:
# hemisphere and hemisphere code
hemisphere = 'north'
# initial satellite code
sat_code = 'n07'
# define the base url
base_url = 'https://noaadata.apps.nsidc.org/NOAA/G02202_V6/'+hemisphere+'/monthly/'
# make a list of URls corresponding to the file date
file_urls = []
for year in range(1979,2026):
for month in range(1,13):
# update satellite code when different satellites are used
if year==1987 and month==8:
sat_code = 'F08'
if year==1992 and month==1:
sat_code = 'F11'
if year==1995 and month==10:
sat_code = 'F13'
if year==2008 and month==1:
sat_code = 'F17'
if year==2025 and month==1:
sat_code = 'am2'
# format a file path and add it to the url list
yr = str(year)
mo = '{:02d}'.format(month)
file_name = 'sic_psn25_'+yr+mo+'_'+sat_code+'_v06r00.nc'
file_urls.append(base_url+'/'+file_name)Download the data¶
With all of the links in hand, we can download these files to our data folder using simple get requests with the requests package:
# loop through all of the files
for i in range(len(file_urls)):
url = file_urls[i]
file_name = url.split('/')[-1]
# check that the file needs to be downloaded
if file_name not in os.listdir(data_folder):
print('Downloading '+file_name+
' (file '+str(i+1)+' of '+str(len(file_urls))+')')
# download the file using a get request
output_file = os.path.join(data_folder,file_name)
with requests.get(url, stream=True, allow_redirects=True) as r:
r.raise_for_status()
with open(output_file, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print('All '+str(len(file_urls))+' have been downloaded')All 564 have been downloaded
Part 2: Generating a time series of sea ice area¶
Before reading in all of the data in a loop, it’s helpful to open up a single file and see what’s inside. Use the Panoply program to get a list of the variables and determine the name of the sea ice variable:

Figure 1:Passive microwave sea ice data in Panoply
We’ll use this information when looping through each file and generating a time series of sea ice area.
Explore a monthly sea ice file¶
After determining which variable will be used for the sea ice area calculation, read in the grid into an array using the netcdf4 package and examine the range of sea ice data values:
# make a file path to one of the nc files
file_path = os.path.join(data_folder,'sic_psn25_197901_n07_v06r00.nc')
# open the file and read in the sea ice variable to a 2D numpy grid
ds = nc4.Dataset(file_path)
seaice_grid = np.array(ds.variables['cdr_seaice_conc_monthly'])
ds.close()
# print the minimum and maximum of the grid
print('minimum:',np.min(seaice_grid))
print('maximum:',np.max(seaice_grid))minimum: 0.0
maximum: 255.0
Hmm... sea ice concentration is supposed to be in the range 0-1. What’s going on here? To get a sense of this data, it helps to have a visual.
Make a histogram¶
A histogram will give us a sense of the range of datain this file.
# ravel the seaice data - the histogram plotting function needs a 1D array
seaice_grid = seaice_grid.ravel()
# make a figure object
fig = plt.figure(figsize=(10,4))
# plot a histogram of the data and add a title
plt.subplot(1,2,1)
plt.hist(seaice_grid)
plt.title('Histogram of sea ice conc.')
# create a filtered version of the data
seaice_values_filtered = seaice_grid[seaice_grid<2]
# plot a histogram of the filtered data and add a title
plt.subplot(1,2,2)
plt.hist(seaice_values_filtered)
plt.title('Histogram of filtered sea ice conc.')
# show the figure
plt.show()
As we can see, the sea ice data contains a lot of values assigned 255 - these are “fill” values to represent land in the regularly-gridded data and are designed to be easily filtered or masked.
Compute the total sea ice area for the test file¶
To compute sea ice area, we’ll convert the concentration into an area using the information that each grid cell is sized 25 km by 25 km:
# Define the grid cell size in km
grid_cell_size = 25
# Convert to area (in km^2) using the grid resolution
seaice_area = np.sum(seaice_values_filtered*grid_cell_size**2)
# print the sea ice area
print('seaice area:',seaice_area,'km^2')seaice area: 14647320.0 km^2
Make a time series from the sea ice area¶
Using all of the information above, we can loop through each of the sea ice fields and generate a time series of the area through time. This calculation follows the approach introduced in the previous Sea Surface Salinity lab - the only difference is that the here, we compute the total area of sea ice rather than sampling the field at a given point.
# make a sorted file list of all the sea ice nc files
file_list = []
for file_name in os.listdir(data_folder):
if file_name[-3:]=='.nc':
file_list.append(file_name)
# sort the file list
file_list.sort()
# make empty lists called date_list and seaice_values
# to store data from all of the files
date_list = []
seaice_values = []
# loop through all of the files in the file list
for file_name in file_list:
# make a date string for the file
date_str = file_name.split('_')[2][:4]+'-'+file_name.split('_')[2][4:6]+'-15'
# open the file to get the seaice grid
file_path = os.path.join(data_folder,file_name)
ds = nc4.Dataset(file_path)
seaice_grid = np.array(ds.variables['cdr_seaice_conc_monthly'])
ds.close()
# compute the total area of seaice in this grid
seaice_grid = seaice_grid.ravel()
seaice_values_filtered = seaice_grid[seaice_grid<2]
seaice_area = np.sum(seaice_values_filtered*grid_cell_size**2)
# if the sea ice area value is valid (>0), add the date to the date list
# and the value to the value list
if seaice_area>0:
date_list.append(date_str)
seaice_values.append(seaice_area)
# make a date_array from the date_list
date_array = np.array(date_list, dtype = 'datetime64')Plot the sea ice time series¶
With our date array and associated sea ice time series in hand, we can now plot the time series to assess the seasonal and interannual variability in northern hemisphere sea ice:
# make a figure object with a width of 10 and a height of 4
fig = plt.figure(figsize=(10,4))
# make a plot of the sea ice values vs the date array
plt.plot(date_array, seaice_values)
# label the y axis
plt.ylabel('Sea Ice Area (km$^2$)')
# make a grid
plt.grid(linestyle='--', linewidth=0.5, alpha=0.5)
# show the figure
plt.show()
🤔 What do you observe?¶
The time series shows some interesting changes seasonally and through the years. What are 2-3 features of the time series above?
Part 3: Analyze Northern Hemisphere September sea ice area trends¶
The extent of sea ice at the September sea ice minimum is the an important metric of overall sea ice health. It is also becoming increasingly important for commerce as more ships are beginning to use the Arctic Ocean as a shipping lane.
To assess changes in the September sea ice area, we will compute the trends in area since 1979. However, before computing this, we’ll need to filter the sea ice to extract only the values pertaining to September and we’ll need to convert our dates to format which can be represented in years.
Filtering the sea ice data by month¶
To filter the sea ice data for the month of September, we’ll loop through all of our data and keep only those dates which have a month equal to 9.
# make empty arrays to store the values
sept_date_list = []
sept_seaice_values = []
# loop through each value
for i in range(len(date_array)):
date = date_array[i].astype(dt.datetime)
# add values to the september lists if they month is equal to 9
if date.month == 9:
sept_date_list.append(date)
sept_seaice_values.append(seaice_values[i])Plot the filtered time series¶
Let’s have a look at what the September time series looks like now that we have our filtered values in hand:
# make a figure object with a width of 10 and a height of 4
fig = plt.figure(figsize=(10,4))
# plot the september values
plt.plot(sept_date_list, sept_seaice_values)
# label the y axis
plt.ylabel('Sea Ice Area (km$^2$)')
# make a grid
plt.grid(linestyle='--', linewidth=0.5, alpha=0.5)
# show the figure
plt.show()
🤔 What do you observe?¶
How does the September time series compare to the full monthly time series? Are there any new features observable in this time series that were not visible before?
Define a function for decimal years¶
If we’d like to compute trends in units of area change per year, we’ll need to express our time in units of years. Here, we’ll introduce yet another time called “decimal years” which can be computed with the following function:
# define a function to turn a date, given by year, month, and day, into a decimal year
def YMD_to_DecYr(year,month,day):
# define a date object using the datetime module
date = dt.datetime(year,month,day)
# define the start in ordinal units (days since ...)
start = dt.date(date.year, 1, 1).toordinal()
# compute the year_length in ordinal units (365 or 366)
year_length = dt.date(date.year+1, 1, 1).toordinal() - start
# compute the fraction based on the date
decimal_fraction = float(date.toordinal() - start) / year_length
# compute the decimal year
dec_yr = year+decimal_fraction
return(dec_yr)We can see how this function works by considering the decimal year as a few dates:
# test your function below:
print(YMD_to_DecYr(2000,1,1)) # January 1, 2000
print(YMD_to_DecYr(2000,6,8)) # June 8, 2000
print(YMD_to_DecYr(2000,12,7)) # December 7, 20002000.0
2000.4344262295083
2000.931693989071
As we can see, the decimal part of the decimal year expresses the time elapsed through the year (between 0 and 1).
Make a decimal year array for the September values¶
Now that we’ve got a function to convert our data to decimal years, let’s generate a new time array with the dates expressed in decimal years:
# make an empty list for the decimal years
sept_decyr_values = []
for date in sept_date_list:
dec_yr = YMD_to_DecYr(date.year,date.month,date.day)
sept_decyr_values.append(dec_yr)Compute the best fit line¶
Now that our date units are appropriate for our goal, we can compute trends by fitting a line to the data. The numpy package provides an easy way to fit a polynomial to a collection of data - we’ll leverage this tool for a linear fit:
# use numpy's polyfit function to compute the best fit line
p = np.polyfit(sept_decyr_values, sept_seaice_values, 1)
# the slope value is the first value
slope = p[0]
# the intercept is the second value
intercept = p[1]
# compute the values of the best fit line
# for the september decyr values
best_fit = slope*np.array(sept_decyr_values)+interceptCreate the plot with the line of best fit¶
With our best fit line in hand, let’s regenerate our plot now with the line of best fit:
# make a figure object with a width of 10 and a height of 4
fig = plt.figure(figsize=(10,4))
# plot the september values
plt.plot(sept_decyr_values, sept_seaice_values)
# plot the line of best fit
# add a label which includes the trend
plt.plot(sept_decyr_values, best_fit, 'k--',
label='Trend: '+'{:.1f}'.format(p[0])+' km$^2$/yr')
# label the y axis
plt.ylabel('Sea Ice Area (km$^2$)')
# make a grid
plt.grid(linestyle='--', linewidth=0.5, alpha=0.5)
# make a legend
plt.legend()
# show the figure
plt.show()
🤔 What do you observe?¶
What is the average loss in sea ice area in September of each year? How does this area compare to the, say, the total area of the state of California?
Part 4: Computing regional sea ice trends¶
In the above example, we computed changes in sea ice in the entire northern hemisphere. Next, we’ll consider computing these trends in a regional area. As an example, we’ll consider Fram Strait - the region between northeast Greenland and Svalbard which is an important sea ice export region.
To subsample the sea ice data regionally, we’ll need to identify where our location of interest is in the data grid. In the last two labs, the SST and SSS data was provided in geographic (longitude-latitude) coordinates. Since the sea ice data is centered around the north (or south) pole, this data set is projected into a different coordinate system. Open up Panoply and examine the file one more time. The projection for this data is stored in the crs variable (short for Coordinate Reference System). This is a text variable (rather than a variable with coordinate or data information) which has a lot of details about the projection:

Figure 2:A snapshot of the coordinate reference system for the sea ice data.
As we can see, the EPSG code for this data is 3411 - the National Snow and Ice Data Center polar stereographic projection. We can use this information in QGIS to define our area of interest.
Identify the coordinates of the area of interest using QGIS¶
Open QGIS and add the global coastline from our first lab. Then, change the projection using the information identified in the sea ice data file.

Figure 3:A snapshot of the global coastline in the polar stereographic projection.
Using the map in QGIS, find the bounds of the region of interest in the projected coordinates and add them below. You can use the approximate locations of a box around Fram Strait:
# define the bounds of the box north of the Fram Strait near Greenland and Svalbard
min_x = 654320
min_y = -1151585
max_x = 906998
max_y = -658495Compute the regional area with one file¶
To test out the regional calculation, we’ll again explore the steps using a single file. Let’s read in the grid for the first file here as well as the geographic information:
# make a file path to one of the nc files
file_path = os.path.join(data_folder,'sic_psn25_197901_n07_v06r00.nc')
# open the file and read in the sea ice variable to a 2D numpy grid
ds = nc4.Dataset(file_path)
seaice_grid = np.array(ds.variables['cdr_seaice_conc_monthly'])
x = np.array(ds.variables['x'])
y = np.array(ds.variables['y'])
ds.close()Next, we’ll find where our region of interest is located inside the grid for the full northern hemisphere. Similar to our identification of locations in the previous labs for SST and SSS time series, we will identify the indices of our location within the broader grid:
# find the indices of the box bounds in the x and y grids
min_x_index = np.argmin(np.abs(x-min_x))
max_y_index = np.argmin(np.abs(y-min_y))
max_x_index = np.argmin(np.abs(x-max_x))
min_y_index = np.argmin(np.abs(y-max_y))
# print the indices to be sure these are ordered correctly
print('x indices:',min_x_index,max_x_index)
print('y indices:',min_y_index,max_y_index)x indices: 180 190
y indices: 260 280
Using these indices, we can next subset our grid to our location of interest. It helps to print out the shapes of the grid to ensure the indices are applied in the correct locations:
# print the shape of the seaice grid
print('Shape of sea ice grid:',np.shape(seaice_grid))
# take only the "first timestep" of the seaice grid
seaice_grid = seaice_grid[0, :, :]
# subset the grid and find the area of sea ice in the subset
seaice_grid_subset = seaice_grid[min_y_index:max_y_index, min_x_index:max_x_index]
# print the shape of the seaice grid
print('Shape of sea ice grid subset:',np.shape(seaice_grid_subset))Shape of sea ice grid: (1, 448, 304)
Shape of sea ice grid subset: (20, 10)
As we can see, there is a time array that only has a single dimension. As a final sanity check before running calculations, we can also plot our sea ice grid to ensure we are identifying the correct region within the broader grid:
# make figure
plt.figure(figsize=(7,6))
# plot the sea ice using the pcolormesh command
seaice_grid_masked = np.ma.masked_where(seaice_grid>2,seaice_grid)
C = plt.pcolormesh(seaice_grid_masked,cmap='Blues_r',vmin=0,vmax=1)
# plot a land mask using the pcolormesh command
land_mask = seaice_grid>2
land_mask = np.ma.masked_where(land_mask==0, land_mask)
plt.pcolormesh(land_mask,cmap='Greys',vmin=0,vmax=2)
# plot the box of the sample location
plt.plot([min_x_index, max_x_index], [min_y_index, min_y_index] ,'k-')
plt.plot([min_x_index, max_x_index], [max_y_index, max_y_index] ,'k-')
plt.plot([min_x_index, min_x_index], [min_y_index, max_y_index] ,'k-')
plt.plot([max_x_index, max_x_index], [min_y_index, max_y_index] ,'k-')
# label the axes and show the plot
plt.colorbar(C, label='Sea Ice Concentration (m$^2$/m$^2$)')
plt.xlabel('Grid Column Indices')
plt.ylabel('Grid Row Indices')
plt.show()
Generate a time series in the region of interest¶
Now that we’ve got our region of interest defined and verified, we can generate a time series in this region. The coding block below is almost identical to the time series code above - the only difference is that now we compute our statistics in the subsetted grid rather than whole northern hemisphere:
# make a sorted file list of all the sea ice nc files
file_list = []
for file_name in os.listdir(data_folder):
if file_name[-3:]=='.nc':
file_list.append(file_name)
# sort the file list
file_list.sort()
# make empty lists called date_list and seaice_values
# to store data from all of the files
date_list = []
seaice_values = []
# loop through all of the files in the file list
for file_name in file_list:
# make a date string for the file
date_str = file_name.split('_')[2][:4]+'-'+file_name.split('_')[2][4:6]+'-15'
# open the file to get the seaice grid
file_path = os.path.join(data_folder,file_name)
ds = nc4.Dataset(file_path)
seaice_grid = np.array(ds.variables['cdr_seaice_conc_monthly'])
ds.close()
# take only the "first timestep" of the seaice grid
seaice_grid = seaice_grid[0, :, :]
# subset the grid and find the area of sea ice in the subset
seaice_grid_subset = seaice_grid[min_y_index:max_y_index, min_x_index:max_x_index]
# compute the total area of seaice in this grid
seaice_grid = seaice_grid_subset.ravel()
seaice_values_filtered = seaice_grid[seaice_grid<2]
seaice_area = np.sum(seaice_values_filtered*grid_cell_size**2)
# if the sea ice area value is valid (>0), add the date to the date list
# and the value to the value list
if seaice_area>0:
date_list.append(date_str)
seaice_values.append(seaice_area)
# make a date_array from the date_list
date_array = np.array(date_list, dtype = 'datetime64')Plot the regional time series¶
After generating our time series, we can plot it and compare it to the time series above:
# make a figure object with a width of 10 and a height of 4
fig = plt.figure(figsize=(10,4))
# make a plot of the sea ice values vs the date array
plt.plot(date_array, seaice_values)
# label the y axis
plt.ylabel('Sea Ice Area (km$^2$)')
# make a grid
plt.grid(linestyle='--', linewidth=0.5, alpha=0.5)
# show the figure
plt.show()
Filter the time series to only include values in September¶
Finally, just like our previous assessment, let’s take a look at trends during the September sea ice minimum. First, make a subsetted time series:
# subset the data to september
sept_date_list = []
sept_seaice_values = []
for i in range(len(date_array)):
date = date_array[i].astype(dt.datetime)
if date.month == 9:
sept_date_list.append(date)
sept_seaice_values.append(seaice_values[i])
# make an empty list for the decimal years
sept_decyr_values = []
for date in sept_date_list:
dec_yr = YMD_to_DecYr(date.year,date.month,date.day)
sept_decyr_values.append(dec_yr)Then, compute trends:
# use numpy's polyfit function to compute the best fit line
p = np.polyfit(sept_decyr_values, sept_seaice_values, 1)
# the slope value is the first value
slope = p[0]
# the intercept is the second value
intercept = p[1]
# compute the values of the best fit line
# for the september decyr values
best_fit = slope*np.array(sept_decyr_values)+interceptFinally, visualize the time series:
# make a figure object with a width of 10 and a height of 4
fig = plt.figure(figsize=(10,4))
# plot the september values
plt.plot(sept_decyr_values, sept_seaice_values)
# plot the line of best fit
# add a label which includes the trend
plt.plot(sept_decyr_values, best_fit, 'k--',
label='Trend: '+'{:.1f}'.format(p[0])+' km$^2$/yr')
# label the y axis
plt.ylabel('Sea Ice Area (km$^2$)')
# make a grid
plt.grid(linestyle='--', linewidth=0.5, alpha=0.5)
plt.legend()
# show the figure
plt.show()
🤔 What do you observe?¶
How does this regional trend compare to the hemisphere-wide trend? What might be different in this regional location?