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 testing

  • modules/bathymetry.py - Data loading utilities for bathymetry

  • tests/ - Automated tests that run when you submit

  • requirements.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:

  1. Navigate to your messfern folder and activate virtual environment

  2. Clone your assignment repository (see detailed git clone instructions in the Python exercise guide)

  3. Install dependencies from the assignment’s requirements.txt file

  4. 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.ipynb in VS Code

  5. Complete the exercise by filling in code where you see:

    # YOUR CODE HERE
    raise NotImplementedError()
    
  6. Test your work locally:

    python -m pytest tests/ -v
    

Option 2: GitHub Codespaces#

No local installation required! Work directly in your browser.

  1. Open Codespace:

    • Go to your assignment repository on GitHub

    • Click the green <> Code button

    • Select “Codespaces” tab → “Create codespace on main”

  2. Setup environment:

    • Wait for Codespace to initialize

    • Open terminal and install dependencies:

    pip install -r requirements.txt
    
  3. Start working:

    • Navigate to src/assignment.ipynb

    • Select Python kernel when prompted

    • Complete the exercise by filling in # YOUR CODE HERE sections

  4. 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 italic

  • Double-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 HERE and raise 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#

  1. Update student information (first cell) with your name, date, and student ID.

    • You may need to double-click the cell to edit it

  2. Complete each coding section by working through the notebook systematically:

    a. Import packages: You’ll import packages like netCDF4, cmocean, and cartopy. We also use a custom module bathymetry.py that 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(). The print() 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

  3. Key Python concepts you’ll learn:

    • Module imports: Using sys.path.append() for local modules

    • Function definition: Writing reusable code with parameters and return values

    • xarray data selection: Using .sel() with method='nearest'

    • Map projections: Understanding coordinate reference systems with cartopy

    • Color scales: Applying appropriate colormaps for oceanographic data

  4. 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.nc file downloads successfully

  • If imports fail, check your requirements.txt installation

🔬 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.deep

  • Experiment with figure sizes: figsize=(12, 8) vs figsize=(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

  1. Stage your changes in the Source Control panel (Ctrl+Shift+G)

  2. Add a commit message: “Complete Exercise 2”

  3. 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

  1. Open the Source Control panel (Ctrl+Shift+G or click the source control icon on the left sidebar)

  2. Review your changes by clicking on src/assignment.ipynb in the Changes section

  3. Stage your changes by clicking the + button next to src/assignment.ipynb

  4. Add a commit message in the text box: “Complete Exercise 2”

  5. Click Commit button

  6. Click Sync Changes to push to GitHub (or click the sync icon in the status bar)

Check Your Results#

  1. Go to your repository on GitHub.com

  2. Click the “Actions” tab to see automated test results

  3. Green checkmark = All tests passed!

  4. 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:

  1. Navigate to the ETOPO bathymetry website

  2. Launch the grid extract tool

  3. Choose the ETOPO_2022 dataset (Bedrock; 60 arcseconds)

  4. Select your area of interest, for example: 66°N, 63°N, 35°W (-35) and 25°W (-25)

  5. Download the data file to your local machine

  6. Save the downloaded file to the data directory as ETOPO_2022_bathymetry.nc

  7. Load 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.