Exercise 2 - Bathymetry Mapping#

📅 Due Date: November 24, 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: Setup Your Environment#

Important

If you completed Exercise 1 successfully, your environment should already be set up! Just clone this new assignment and install its requirements.

Quick Setup (For Students Who Completed Exercise 1)#

  1. Clone your assignment repository (get URL from GitHub Classroom)

  2. Navigate to the folder and activate your virtual environment

  3. Install new packages: pip install -r requirements.txt (includes cartopy, cmocean)

  4. Open in VS Code: File Open Folder → Select assignment folder

  5. Start working: Open src/assignment.ipynb

First-Time Setup or Troubleshooting#

For complete setup instructions, troubleshooting, and help, see:

Having issues? The troubleshooting section in Exercise 1 covers all common problems:

  • Virtual environment issues

  • Package installation failures (especially cartopy/netCDF4)

  • Git problems

  • VS Code kernel selection

Tip

New packages in this exercise: This assignment includes cartopy (mapping) and cmocean (oceanographic colors). These can be tricky to install - see the Exercise 1 troubleshooting if you encounter package installation issues.

Step 3: Complete the Exercise#

Work through the assignment notebook systematically. Look for # YOUR CODE HERE sections and fill them in.

What You’ll Do#

  1. Update your information (name, date, student ID)

  2. Write your first function - get_depth_at_location() to extract depths at coordinates

  3. Create 3 bathymetric maps:

    • Figure 1: Basic matplotlib contour plot

    • Figure 2: Cartopy map with projections

    • Figure 3: Enhanced map with DS2 mooring and annotations

  4. Answer analysis questions about bathymetric features

New in This Exercise: Function Writing#

def get_depth_at_location(bathymetry_dataset, target_lat, target_lon):
    """Extract water depth at a specific location"""
    # Your code here - use .sel() with method='nearest'
    return depth_value

Quick Reference for Bathymetry Data#

print(bathymetry_subset)              # Overview of dataset
print(bathymetry_subset.z.shape)     # Depth array dimensions  
bathymetry_subset.z.plot()           # Quick visualization

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

Need Help?#

💡 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#

Important

GitHub Classroom automatically collects your submission when you push to your repository. No separate submission step required - just commit and push your changes!

Option A: VS Code Source Control (Recommended) Note: Requires git to be installed - see troubleshooting section if git commands don’t work

  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)

Option B: Command Line

git add src/assignment.ipynb figures/
git commit -m "Complete Exercise 2"
git push origin main

Option C: 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”

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.

Troubleshooting Common Issues#

1. Package Installation Issues (cartopy, netCDF4)#

These packages need system libraries and can be difficult to install with pip.

Problem: pip install -r requirements.txt fails on cartopy or netCDF4

Solution 1: Hybrid conda + pip approach Create a conda environment that handles the tricky packages, then uses pip for the rest:

  1. Create environment.yml file in your assignment folder:

    name: exercise2
    channels:
      - conda-forge
      - defaults
    dependencies:
      - python=3.12
      - cartopy      # Install via conda (avoids compilation issues)
      - netcdf4      # Install via conda (avoids compilation issues)
      - cmocean      # Install via conda (oceanographic colormaps)
      - pip
      - pip:
        - matplotlib
        - numpy
        - scipy
        - pandas
        - xarray
        - tqdm
        - gsw
        - seasenselib
        - jupyterlab
        - ipywidgets
    
  2. Create the environment:

    conda env create -f environment.yml
    conda activate exercise2
    
  3. Open VS Code and select the conda environment as your interpreter

Solution 2: Use GitHub Codespaces These packages are pre-configured and work reliably in Codespaces.

For other setup issues: See Exercise 1 troubleshooting section.

2. Module Import Errors#

If you get ModuleNotFoundError for custom modules:

# Check if sys.path.append('..') is in your notebook
import sys
print(sys.path)  # Should show parent directory

3. Function Writing Issues#

If your get_depth_at_location() function isn’t working:

  • Check function indentation (Python is strict about spaces)

  • Verify you’re returning a value with return

  • Test with simple coordinates first

4. Map/Plotting Problems#

See Python Tips & Troubleshooting for plotting issues, or:

plt.clf()        # Clear current figure
plt.close('all') # Close all figures and restart

5. General Setup Issues#

For all other problems (git, virtual environments, VS Code), see the Exercise 1 troubleshooting section.

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.