Exercise 1 - Plot profiles in python#

Attention

Known Issue with Automated Tests: The automated tests for this exercise may fail due to a template configuration issue, not necessarily because of problems with your code. If you see test failures, please check that your figures are generated correctly and your code runs without errors. We are working to fix this issue.

📅 Due Date: November 10, 2025 at 18:00

Aim: To work with vertical profile data and make standard oceanographic calculations.

Context: This exercise uses CTD data from R/V Maria S. Merian (MSM121 near 47°N in the Atlantic in 2023) to demonstrate using oceanographic profile data.

Goals: At the end of this exercise, you will be able to:

  • Run python with jupyter notebooks and automated testing

  • Convert Sea-Bird CNV files to netCDF format using seasenselib

  • Calculate TEOS-10 parameters (Absolute Salinity, Conservative Temperature) using gsw

  • Create oceanographic profile plots

  • Generate Temperature-Salinity diagrams with density contours

Required Outputs: Four figures showing oceanographic data.


Step 1: Accept GitHub Classroom Assignment#

📝 Accept Assignment: Exercise 1 - CTD Profile Data

V2 link Exercise 1 CTD v2

–> V3 link Exercise 1 CTD v3 – tests here should pass. There are problems with the tests for the previous versions. You should be able to simply add your completed assignment.ipynb into a new version of the repository generated when you click this link. Due date if you use this link is 17 November 2025 at 18:00

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:

your-assignment-folder/          ← Assignment root directory
├── src/
│   └── assignment.ipynb         ← Main exercise notebook  
├── data/
│   └── MSM121_054_1db.cnv      ← CTD data file
├── tests/
│   └── test_exercise.py         ← Automated tests
├── requirements.txt             ← Python packages to install
├── .devcontainer/               ← Codespaces configuration
└── figures/                     ← Created automatically for your plots

Warning

If the data directory is missing, see troubleshooting section for download instructions.

Path References: The notebook (src/assignment.ipynb) uses relative paths:

  • ../data/ to access data files (goes up one level from src/)

  • ../figures/ to save your plots (goes up one level from src/)

Step 2: Choose where to work on the assignment#

Important

Our goal is to get Python working on your own computer. This will serve you throughout the course and your career. Codespaces is only a temporary backup if you encounter setup issues.

Option 2: GitHub Codespaces (Temporary Backup Only)#

Warning

Use this only if local setup fails. The goal is to get Python working on your computer. If you use Codespaces for this exercise, please still work on setting up Python locally for future assignments.

No local installation required! Work directly in your browser if local setup isn’t working.

  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

Step 3: Complete the Exercise#

The assignment notebook is structured with both instructional information and coding tasks.

📝 Markdown cells contain instructions and explanations using Markdown syntax.

💻 Code cells contain Python code. You’ll encounter two types:

  • Completed examples - Run these to understand the workflow

  • Tasks for you Fill in code where you see:

    # YOUR CODE HERE
    raise NotImplementedError()
    
  • 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

Test your code

The assignment has two types of tests:

  1. Embedded test cells (in the notebook) - Run automatically as you work through each section

    • These check that each step completed correctly

    • You’ll see “✓ Test passed!” messages when successful

  2. External test suite - Run from terminal to check overall completion:

    python -m pytest tests/ -v
    

    Run this in your VS Code terminal (with virtual environment activated) to verify everything works together.

Tip

Automatic Testing: When you commit and push changes, GitHub Actions will automatically run tests and provide feedback in the “Actions” tab.

Completion Steps#

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

  2. Complete each coding section:

    • File Setup: Configure figure output directory

    • Data Loading: Convert CNV to netCDF using seasenselib

    • TEOS-10 Calculations: Compute Absolute Salinity and Conservative Temperature

    • Figure Creation: Generate 4 oceanographic plots

    • Analysis Questions: Read and reflect (for class discussion, not graded)

  3. Key Python concepts you’ll learn:

    • Import statements: Loading packages (import matplotlib.pyplot as plt)

    • Variables: Storing data and file paths (figdir = '../figures/')

    • Functions: Calling oceanographic tools (gsw.conversions.SA_from_SP(...))

    • Plotting: Creating figures with matplotlib

  4. Oceanographic workflow:

    • Convert Sea-Bird sensor data to standard format

    • Calculate modern oceanographic parameters using TEOS-10

    • Visualize vertical profiles and water mass properties

    • Interpret T-S diagrams with density contours

Tip

Testing as you go: Each major section has test cells that verify your work automatically. Use these to check progress before moving on.

Need Help While Working?#

For debugging, data exploration, and troubleshooting help, see the Python Tips & Troubleshooting guide. It includes:

  • 🔍 Getting help in Python (help(), ?, dir())

  • 📊 Understanding your data (xarray datasets, checking data ranges)

  • 🐛 Debugging & troubleshooting (import problems, file paths, plotting issues)

  • 🆘 Common error messages and their solutions

  • 💡 Best practices for code organization and workflow

Bookmark that page - you’ll use it throughout the course!

💡 First Exercise Tips#

🎯 Before You Start:

  • Make sure pip install -r requirements.txt completed successfully

  • Run the setup test above - if it works, you’re ready!

  • Don’t worry if you don’t understand everything - focus on completing the tasks first

🔬 While Working:

  • Read each cell carefully before running it

  • Look at the outputs - they tell you if things worked

  • Don’t skip the test cells - they catch problems early

  • Ask for help if you’re stuck for more than 15 minutes

🆘 Got an error? Check the Python Tips & Troubleshooting guide for solutions to common problems.

Step 4: Submission and Grading#

Automatic Testing#

Your work is tested automatically when you submit! The assignment includes:

  • File creation checks - All 4 required figures generated

  • Code functionality - CNV conversion, TEOS-10 calculations working

  • Data validation - Proper variable creation and data loading

  • Template completion - No placeholder text remaining

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! You can submit as many times as you like.

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 – this looks like 3 circles connected by 2 lines, one straight and one wiggly)

  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 1”

  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 1"
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 1”

  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 (NetCDF files, 4 figures)

  • All automated tests pass (data valid, figures contain content)

  • Personal information completed

  • Code executes without errors

🌟 PASS PLUS (Professional Quality): All PASS requirements PLUS:

  • Sensible legends and titles on all figures

  • Good choices for figure plotting (appropriate aspect ratios, professional color scales, clear line styles)

  • All axes have proper labels with units (e.g., “Temperature (°C)”, “Pressure (dbar)”, “Salinity (g/kg)”)

  • Thoughtful formatting (readable fonts, appropriate figure sizes)

  • Professional T-S diagram styling with proper density contour labels

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. Seasenselib Import Errors#

If you get import errors with seasenselib, try these solutions:

Problem: ModuleNotFoundError or import structure issues

# If this doesn't work:
from seasenselib.readers import SbeCnvReader, NetCdfReader
from seasenselib.writers import NetCdfWriter

# Try this instead:
from seasenselib.modules.reader import CnvReader as SbeCnvReader, NetCdfReader
from seasenselib.modules.writer import NetCdfWriter

Solution: Make sure you have the correct virtual environment activated and run:

pip install --upgrade seasenselib

2. Python Version Mismatch in VS Code#

If your notebook kernel doesn’t match your terminal Python:

  1. Press Ctrl+Shift+P (Windows) or Cmd+Shift+P (Mac)

  2. Type “Python: Select Interpreter”

  3. Choose the Python from your venv folder

  4. For notebooks: Ctrl+Shift+P → “Jupyter: Select Interpreter” → Choose venv Python

3. Git Not Installed#

See the Python Installation Guide for detailed git installation instructions for all platforms.

4. Missing Data Files#

If the data/ directory is missing or empty, download the data files (or anything else missing) from the template repository: ifmeo-courses/mf-ex1-template

Copy the data/ folder to your project directory.

5. Virtual Environment Not Working#

If venv commands fail, see the Python Installation Guide for platform-specific setup instructions, or try these alternatives:

# Try using python3 instead of python
python3 -m venv .venv

# Or use conda if you have it installed
conda create -n exercise1 python=3.12
conda activate exercise1
pip install -r requirements.txt

Still having issues? Check the Python Installation Guide troubleshooting section for package installation problems and environment setup help.

6. Python Version Mismatch in Codespaces#

If packages aren’t found in Codespaces even after installing them:

  1. Check .devcontainer/devcontainer.json - ensure Python version matches your requirements

  2. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac)

  3. Type “Dev Containers: Rebuild Container”

  4. Wait for the rebuild to complete

  5. Reinstall packages: pip install -r requirements.txt

This happens when the terminal Python version doesn’t match the Jupyter kernel version.

Frequently Asked Questions (FAQ)#

Q: Where can I find more detailed documentation for seasenselib?#

A: For detailed seasenselib documentation, including usage examples and API reference, visit the seasenselib documentation and check the User Guide section. This resource contains:

  • Complete installation instructions

  • Detailed examples for reading CNV files

  • NetCDF conversion workflows

  • API documentation for all functions

  • Common use cases and troubleshooting

The User Guide is especially helpful for understanding the different reader and writer classes and their options.

Q: Why is my test_exercise.py passing but test_outputs.py failing?#

A: The two test files check different things:

  • test_exercise.py - Tests your Python code and functions (can pass even if you haven’t run the notebook)

  • test_outputs.py - Tests the actual output files you generate when completing the exercise

In v3 of the Github assignment (see links above) the test suite has been updated. There were issues with the paths (where the file is looking to find your solutions – thanks Aysegul for flagging this). This should be fixed now in the v3 tests.

Solution: Add the v3 assignment, and copy your completed notebook assignment.ipynb to this new repository. Run the notebook (which requires setting up the environment) and then run the tests pytest tests/* from the root directory. This should have fewer failures.

Q: My code works in the notebook but tests still fail. What’s wrong?#

A: Check these common issues:

  1. File paths: Make sure you’re saving figures to ../figures/ (relative to the notebook location)

  2. File naming: Figures should be named ex1fig1-YourName-Messfern.png (replace “YourName” with your actual name)

  3. Complete execution: Run all notebook cells from top to bottom in order

  4. Virtual environment: Ensure you’re using the same Python environment for both the notebook and tests

Test the workflow:

# From your assignment directory with venv activated:
python -m pytest tests/test_exercise.py -v     # Test your code
python -m pytest tests/test_outputs.py -v     # Test your outputs

See also the note about submitting as v3 of the github assignment (find the link at the top of the page).

Q: I’m getting import errors with seasenselib. What should I do?#

A: Try these solutions in order:

  1. Update seasenselib:

    pip install --upgrade seasenselib
    
  2. Check the import structure: Different versions might have different import paths. See seasenselib documentation for the correct import statements for your version.

  3. Verify your virtual environment: Make sure you’re using the same environment in your notebook as in your terminal.

Q: I’m getting errors when trying to write the NetCDF file. What should I do?#

A: If you encounter errors when writing the NetCDF file (especially metadata or attribute-related errors), try dropping the attributes first before writing:

# After loading your data with:
ctd_data = reader.get_data()

# Drop attributes before writing to NetCDF:
ctd_data = ctd_data.drop_attrs()

# Then proceed with writing the NetCDF file
writer.write_data(ctd_data)

This removes potentially problematic metadata that can cause write errors while preserving the actual data.

Q: My tests expect temperature but my NetCDF file has temperature_1. How do I fix this?#

A: The seasenselib output uses numbered variable names (temperature_1, temperature_2, etc.) but the tests expect simplified names. Add variable renaming after loading your NetCDF file:

# After loading data:
ctd_ds = xr.open_dataset(netcdf_file_with_path)

# Rename variables to match test expectations
ctd_ds = ctd_ds.rename({
    'temperature_1': 'temperature',
    'salinity': 'salinity'  # Keep salinity the same
})

This ensures your variable names match what the automated tests expect.

OR: This has been fixed in the v3 of the tests. See the link at the top to accept the v3 assignment.

Q: Can I modify the test files if they’re not working?#

A: No, don’t modify the test files - they’re designed to match the autograder. BUT if you want to use a previous version of the assignment and see whether it’s just the tests which are a problem, download the tests from ifmeo-courses/mf-ex1-template and replace the tests in your repository with these files.

Q: How do I know if I’ve completed everything correctly?#

A: You’ve completed the exercise successfully when:

  • ✅ All notebook cells run without errors

  • ✅ Your figures/ directory contains 4 PNG files with your name

  • ✅ Your data/ directory contains the converted NetCDF files

  • ✅ All placeholder text has been replaced with your information

  • ✅ Both test_exercise.py AND test_outputs.py pass completely

Run python -m pytest tests/ -v to check everything at once.