Create a reproducible computing starter kit for grad courses: environment pinning, data…
- User
Create a reproducible computing starter kit for grad courses: environment pinning, data versioning, CI for notebooks, and grading hooks.
Assistant
Create a reproducible computing starter kit for grad courses: environment pinning, data versioning, CI for notebooks, and grading hooks.
The user wants a "reproducible computing starter kit for grad courses." This starter kit needs to cover four specific areas:
Target Audience: Graduate students and instructors in computational courses (data science, ML, scientific computing). They need something practical, relatively easy to adopt, and standard-compliant (git, conda/docker, etc.).
Component 1: Environment Pinning
environment.yml), pip (requirements.txt), Docker (Dockerfile).conda env export).Component 2: Data Versioning
.dvc/.gitignore, .gitignore.Component 3: CI for Notebooks (Continuous Integration)
nbdev or jupyter nbconvert: Execute the notebook to ensure it runs without errors.black / isort / flake8 (via nbqa): Lint code inside notebooks.nbstripout): Essential to keep git diffs readable..github/workflows/ci.yml.Component 4: Grading Hooks
nbgrader is the heavy lifter here. It handles assignment creation, release, collection, and autograding.nbgrader as the robust solution. I'll focus on a "git-based" submission workflow script for simplicity, as nbgrader requires JupyterHub infrastructure often.Structure of the Response:
environment.yml and Dockerfile.Refining the Content:
jupyter nbconvert --to notebook --execute. This is the "does it crash?" test. Use nbstripout for clean diffs.unittest to test functions inside a student's notebook. This mimics the autograding logic without the infrastructure overhead.Drafting the Code Snippets:
dvc init, dvc add data/raw.csv.importnb or similar) or runs a specific cell. Actually, unittest against a notebook file is best handled by extracting the code or running it. Let's stick to a script that executes the notebook and checks for specific output variables or simply verifying it runs top-to-bottom without error as the primary "grading" hook in CI. For specific assignment grading, I'll include a template for pytest that scans notebooks.Self-Correction/Review during drafting:
Final Plan:
environment.yml (pinned).Let's write the response. This is a complete starter kit designed for a graduate-level computational course (e.g., Data Science, ML, Econometrics, or Quantitative Biology).
It uses standard, robust tools:
conda (industry standard for data science).DVC (Data Version Control).nbgrader logic implemented via scripts.First, create a repository with this exact structure.
course-repro-starter/
├── .dvc/ # DVC internal config
├── .github/
│ └── workflows/
│ └── ci.yml # CI pipeline
├── data/
│ ├── raw/ # Immutable raw data (tracked by DVC)
│ └── processed/ # Cleaned data (tracked by DVC)
├── notebooks/
│ └── student_lab.ipynb # The assignment
├── src/
│ ├── __init__.py
│ └── utils.py # Helper functions
├── tests/
│ ├── test_environment.py # Checks if libs are installed
│ └── test_notebook.py # Executes notebook programmatically
├── environment.yml # Conda environment definition
├── README.md
└── .gitignore
We use Conda to ensure every student has the exact same Python version and library versions.
File: environment.yml
name: course-env
channels:
- conda-forge
- defaults
dependencies:
- python=3.10
- pip
# Core Data Science Stack
- numpy=1.23
- pandas=1.5
- scikit-learn=1.2
- matplotlib
- seaborn
# Tooling
- jupyterlab
- dvc
- nbstripout
- pytest
- pytest-notebook # Useful for testing notebooks
- pip:
- otter-grader # Optional: specialized grading tool
Setup Instructions for Students:
# Create the environment
conda env create -f environment.yml
conda activate course-env
Git is bad at large files. DVC acts like Git for data.
Setup (Run once by Instructor):
# Initialize dvc
dvc init
# Track a large dataset file
dvc add data/raw/big_dataset.csv
# This creates data/raw/big_dataset.csv.dvc and updates .gitignore
# Commit the .dvc file to git, NOT the .csv
git add data/raw/big_dataset.csv.dvc data/raw/.gitignore
git commit -m "Track raw data with DVC"
Remote Storage (Instructor): You need a place to store the actual data files.
# Example: Using a local server or cloud bucket (S3/GDrive)
dvc remote add -d myremote /path/to/shared/drive
git commit .dvc/config -m "Configure remote storage"
Student Instructions:
When students clone the repo, they get the code (Git) and the pointer files (.dvc). They run:
dvc pull
This CI pipeline does three things:
environment.yml is valid.File: .github/workflows/ci.yml
name: Course CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Miniconda
uses: conda-incubator/setup-miniconda@v2
with:
environment-file: environment.yml
activate-environment: course-env
auto-activate-base: false
- name: Pull Data (DVC)
# In a real repo, you need auth secrets for DVC remote
run: |
dvc pull
shell: bash -l {0}
- name: Check Environment Reproducibility
run: |
python --version
pip list
shell: bash -l {0}
- name: Lint Notebooks (Check for outputs)
# Ensure students didn't commit huge output blobs
run: |
pip install nbstripout
nbstripout --check notebooks/*.ipynb
shell: bash -l {0}
- name: Execute Notebook (Integration Test)
# Runs the notebook top-to-bottom. Fails if a cell errors out.
run: |
jupyter nbconvert --to notebook --execute notebooks/student_lab.ipynb --output test_run.ipynb
shell: bash -l {0}
The best way to grade notebooks programmatically is to inject "Assertion" tests into the student notebook or run an external test suite against it.
pytest (Simple)Create a test script that runs the student's notebook logic.
File: tests/test_student_work.py
import subprocess
import os
def test_notebook_execution():
"""
Ensures the notebook runs from top to bottom without errors.
This prevents students from submitting notebooks that rely on
variables defined in previously run (but now deleted) cells.
"""
notebook_path = "notebooks/student_lab.ipynb"
# Use nbconvert to execute
result = subprocess.run([
"jupyter", "nbconvert",
"--to", "notebook",
"--execute", notebook_path,
"--output", "temp_executed.ipynb"
], capture_output=True, text=True)
# Clean up
if os.path.exists("temp_executed.ipynb"):
os.remove("temp_executed.ipynb")
# Check return code
assert result.returncode == 0, f"Notebook execution failed:\n{result.stderr}"
For actual grading (checking if model.accuracy > 0.8), use Otter Grader.
Instructor creates: notebooks/student_lab.ipynb with hidden test cells.
# In a student visible cell:
def square(x):
return x * x
# In a hidden cell (or referenced via otter):
# >>> ANSWER CHECK
assert square(2) == 4
CI/Grading Hook: Add a step in your CI (or a separate grading workflow) to run the grader.
# Install otter-grader first
otter grade notebooks/student_lab.ipynb -o grades/
conda env create -> dvc pull.student_lab.ipynb -> git push.otter grade (or inspects manually) knowing the environment matches perfectly because of environment.yml.