Exercise 2 - Bathymetry Mapping#
📅 Due Date: November 17, 2025 at 18:00
Aim: To work with bathymetry data and create professional oceanographic maps using matplotlib and cartopy.
Context: This exercise uses ETOPO bathymetry data from the North Atlantic region to teach cartographic visualization and function writing skills in Python.
Goals: At the end of this exercise, you will be able to:
Load and work with bathymetry data using xarray
Write your first Python function to extract depth at specific locations
Create contour plots using matplotlib
Generate maps using cartopy and map projections
Add geographic annotations, legends, and features to maps
Apply appropriate color scales for oceanographic data visualization
Identify oceanographic features
Required Outputs: Three figures showing bathymetric data and a working depth extraction function.
Step 1: Accept GitHub Classroom Assignment#
📝 Accept Assignment: Exercise 2 - Bathymetry Mapping
Click the link above to start the assignment. You may need to create a GitHub account or link your existing account to your name.
Your assignment repository will be automatically created with:
src/assignment.ipynb- Main exercise notebook with automated testingmodules/bathymetry.py- Data loading utilities for bathymetrytests/- Automated tests that run when you submitrequirements.txt- All required Python packages including cartopy and cmocean
Step 2: Choose where to work on the assignment#
Note: The instructions below are a quick reminder. For more complete setup instructions, see the Python Exercise Setup Guide.
Option 1: Work on your own computer#
Prerequisites: Python 3.12 with VS Code setup complete (see Python Installation Guide).
For detailed instructions on cloning, installing dependencies, and setting up VS Code, refer to the Python Exercise Setup Guide. The basic steps are:
Navigate to your messfern folder and activate virtual environment
Clone your assignment repository (see detailed git clone instructions in the Python exercise guide)
Install dependencies from the assignment’s requirements.txt file
Open assignment folder in VS Code:
Launch VS Code
Go to File → Open Folder
Select your cloned assignment folder (inside
~/messfern/your-assignment-repo)Open
src/assignment.ipynbin VS Code
Complete the exercise by filling in code where you see:
# YOUR CODE HERE raise NotImplementedError()
Test your work locally:
python -m pytest tests/ -v
Option 2: GitHub Codespaces#
No local installation required! Work directly in your browser.
Open Codespace:
Go to your assignment repository on GitHub
Click the green
<> CodebuttonSelect “Codespaces” tab → “Create codespace on main”
Setup environment:
Wait for Codespace to initialize
Open terminal and install dependencies:
pip install -r requirements.txt
Start working:
Navigate to
src/assignment.ipynbSelect Python kernel when prompted
Complete the exercise by filling in
# YOUR CODE HEREsections
Test your work:
python -m pytest tests/ -v
Tip
Automatic Testing: When you commit and push changes, GitHub Actions will automatically run tests and provide feedback in the “Actions” tab.
Step 3: Understanding Jupyter Notebooks#
Before diving into the exercise, it’s important to understand how Jupyter notebooks work, especially if this is your second Python experience.
Notebook Structure#
A Jupyter notebook (*.ipynb) is organized in cells. Each cell is either:
📝 Markdown cells contain explanations and use Markdown syntax:
#creates headers,##creates subheaders-creates bullet points**bold text**for bold,*italic text*for italicDouble-click a markdown cell to edit it
💻 Code cells contain Python instructions that tell the computer what to do:
Syntax matters! Missing punctuation, wrong capitalization, incorrect brackets, or wrong indentation will cause errors
Python is like other programming languages (Matlab, Julia) but has its own rules
We provide starter code to edit rather than coding from scratch - this gets you to “real oceanography” faster, but be aware you may have gaps in basic programming understanding
Working Through the Exercise#
You’ll encounter two types of code cells:
Completed examples - Run these to understand the workflow
Tasks for you - Look for
# YOUR CODE HEREandraise NotImplementedError()
Key Python Concepts You’ll Use#
As you work through the notebook, you’ll see these important Python patterns:
1. Importing packages: Loading tools into Python
import matplotlib.pyplot as plt # Plotting tools (shortened to 'plt')
import xarray as xr # NetCDF data handling (shortened to 'xr')
2. Loading data: Using xarray to read NetCDF files
dataset = xr.open_dataset('filename.nc') # Opens a data file
print(dataset) # Shows what's in the dataset
3. File paths: Telling Python where to find and save files
figdir = '../figures/' # Where to save figures
sys.path.append('..') # Where to find custom modules
4. Making plots: Creating figures with matplotlib
plt.figure(figsize=(10, 8)) # Create a figure of specific size
plt.contourf(x, y, data) # Make filled contours
plt.savefig('figure.png') # Save the figure
5. Writing functions: Creating reusable code (NEW in this exercise!)
def function_name(parameter1, parameter2):
"""What the function does"""
result = parameter1 + parameter2
return result
Quick Python Reference for This Exercise#
🔍 Exploring bathymetry data:
print(bathymetry_subset) # Overview of your dataset
print(bathymetry_subset.z.shape) # Dimensions of depth array
bathymetry_subset.z.plot() # Quick visualization
🛠️ Function writing (NEW!):
def my_function(parameter):
"""What this function does"""
result = parameter * 2
return result
# Test your function:
test_result = my_function(5)
print(f"Result: {test_result}")
🗺️ Working with coordinates:
print(f"Lat range: {lats.min():.2f}°N to {lats.max():.2f}°N")
print(f"Lon range: {lons.min():.2f}°E to {lons.max():.2f}°E")
Tip
Need more Python help? Check out the Python Tips & Troubleshooting guide with debugging strategies, data exploration techniques, and solutions to common errors.
Step 4: Complete the Exercise#
The assignment notebook is structured with both instructional content and coding tasks.
Completion Steps#
Update student information (first cell) with your name, date, and student ID.
You may need to double-click the cell to edit it
Complete each coding section by working through the notebook systematically:
a. Import packages: You’ll import packages like
netCDF4,cmocean, andcartopy. We also use a custom modulebathymetry.pythat handles data downloading.b. File Setup: Configure paths telling Python where to find data and save figures. The
sys.path.append('..')line is crucial - it tells Python where to find our custom modules.c. Data Loading: Load bathymetry data using
xarray.open_dataset(). Theprint()command shows you what’s in the dataset - this is very helpful for understanding your data!d. Function Writing (NEW!): Create your first Python function
get_depth_at_location()that extracts depth at any lat/lon coordinate. This introduces you to writing reusable code.e. Figure Creation: Generate 3 professional bathymetric maps:
Figure 1: Simple matplotlib contour plot
Figure 2: Cartopy map with geographic projections
Figure 3: Enhanced map with DS2 mooring location and deepest point marked
f. Analysis Questions: Interpret the bathymetric features you observe
Key Python concepts you’ll learn:
Module imports: Using
sys.path.append()for local modulesFunction definition: Writing reusable code with parameters and return values
xarray data selection: Using
.sel()withmethod='nearest'Map projections: Understanding coordinate reference systems with cartopy
Color scales: Applying appropriate colormaps for oceanographic data
Oceanographic workflow:
Work with ETOPO bathymetry data
Extract depths at specific locations (DS2 mooring)
Visualize seafloor topography with appropriate depth contours
Identify oceanographic features like continental shelf, slope, and abyssal plains
Tip
Testing as you go: Each major section has test cells that verify your work automatically. Use these to check progress before moving on.
💡 Pro Tips for Success#
🎯 Before You Start:
Run the first few cells to make sure everything imports correctly
Check that the
bathymetry_subset.ncfile downloads successfullyIf imports fail, check your
requirements.txtinstallation
🔬 While Working:
Read error messages carefully - Python tells you exactly what’s wrong and where
Test your function with simple values before using it in plots
Save your work frequently (Ctrl+S on Windows/Linux, Cmd+S on macOS)
Run cells one at a time rather than “Run All” to catch errors early
🎨 For Better Figures:
Try different colormaps:
'viridis','Blues',cmocean.cm.deepExperiment with figure sizes:
figsize=(12, 8)vsfigsize=(8, 6)Add meaningful titles that describe what you’re showing
🆘 When Things Go Wrong:
# Common fixes:
# If module not found:
import sys
print(sys.path) # Check if your path is correct
# If plot looks weird:
plt.clf() # Clear the current figure
plt.close('all') # Close all figures and start fresh
# If coordinates seem wrong:
print(f"Lat range: {lats.min():.2f} to {lats.max():.2f}")
print(f"Lon range: {lons.min():.2f} to {lons.max():.2f}")
Step 4: Submission and Grading#
Automatic Testing#
Your work is tested automatically when you submit! The assignment includes:
✅ Function creation checks -
get_depth_at_location()function working correctly✅ Figure creation checks - All 3 required figures generated with proper naming
✅ Data validation - Proper bathymetry data loading and processing
✅ Template completion - No placeholder text remaining
✅ Code functionality - Module imports and depth extraction working
Submit Your Work#
Option A: GitHub Codespaces
Stage your changes in the Source Control panel (Ctrl+Shift+G)
Add a commit message: “Complete Exercise 2”
Click “Commit” → “Sync Changes”
Option B: Local Computer
git add src/assignment.ipynb
git commit -m "Complete Exercise 2"
git push origin main
Option C: VS Code Source Control
Open the Source Control panel (Ctrl+Shift+G or click the source control icon on the left sidebar)
Review your changes by clicking on
src/assignment.ipynbin the Changes sectionStage your changes by clicking the + button next to
src/assignment.ipynbAdd a commit message in the text box: “Complete Exercise 2”
Click Commit button
Click Sync Changes to push to GitHub (or click the sync icon in the status bar)
Check Your Results#
Go to your repository on GitHub.com
Click the “Actions” tab to see automated test results
Green checkmark = All tests passed!
Red X = Review failed tests and fix issues
Grading#
This assignment uses a tiered PASS system:
✅ PASS (Basic Requirements):
All required files created (bathymetry data, 3 figures)
All automated tests pass (data valid, figures contain content)
Personal information completed
Code executes without errors
🌟 PASS PLUS (Professional!): All PASS requirements PLUS:
Sensible legends and titles on all figures
Good choices for figure plotting (appropriate aspect ratios, color scales, clear line styles)
All axes have proper labels with units and geographic coordinates
Thoughtful formatting (readable fonts, appropriate figure sizes)
Map styling with proper geographic features and annotations
❌ FAIL Conditions:
Missing required outputs
Test failures (invalid data, empty figures)
Code execution errors
Template placeholders not replaced
Tip
Multiple attempts allowed! You can revise and resubmit until the deadline. Each commit triggers new automated tests.
Advanced: Working with Real Bathymetry Data (Optional)#
If you want to explore beyond the provided dataset:
Navigate to the ETOPO bathymetry website
Launch the grid extract tool
Choose the ETOPO_2022 dataset (Bedrock; 60 arcseconds)
Select your area of interest, for example: 66°N, 63°N, 35°W (-35) and 25°W (-25)
Download the data file to your local machine
Save the downloaded file to the data directory as
ETOPO_2022_bathymetry.ncLoad and use this real data instead of the provided dataset
This exercise demonstrates essential skills for visualizing and interpreting bathymetric data in oceanographic research, including proper use of map projections, geographic coordinate systems, and professional cartographic presentation.