Skip to content

Commit 3301288

Browse files
committed
Make notebooks standalone
1 parent 7e7635c commit 3301288

23 files changed

Lines changed: 3574 additions & 2937 deletions

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,5 +160,4 @@ cython_debug/
160160
.idea/
161161

162162
# Custom
163-
/output
164-
/data
163+
output

CATALOG.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Notebook Catalog
2+
3+
## Workflows
4+
5+
### workflows/vertical-profiling/
6+
7+
- **[bacvp_ctd_up_profiles.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/vertical-profiling/bacvp_ctd_up_profiles.ipynb)**
8+
Demonstrates vertical profile plotting for potential density from CTD data.
9+
*Keywords:* gsw
10+
11+
- **[bacvp_videocam_opencv.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/vertical-profiling/bacvp_videocam_opencv.ipynb)**
12+
Illustrates video processing and frame extraction from videocam sources.
13+
*Keywords:* opencv-python, video
14+
15+
### workflows/transit-analysis/
16+
17+
- **[distance_from_terminals.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/transit-analysis/distance_from_terminals.ipynb)**
18+
Computes and visualizes time series for ferry-to-terminal distance.
19+
*Keywords:* geopy, xarray
20+
21+
- **[grid_transit.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/transit-analysis/grid_transit.ipynb)**
22+
Analyzes ferry transit grid patterns and routing.
23+
*Keywords:* xarray
24+
25+
- **[system_sampling_state.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/transit-analysis/system_sampling_state.ipynb)**
26+
Examines sampling state and temporal coverage of ferry measurements.
27+
28+
- **[transit_identifier.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/transit-analysis/transit_identifier.ipynb)**
29+
Identifies and classifies distinct transit events.
30+
31+
- **[twsb_tsg_clean_no_gaps.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/workflows/transit-analysis/twsb_tsg_clean_no_gaps.ipynb)**
32+
Performs TSG data quality and gap-filling workflows.
33+
*Keywords:* xarray
34+
35+
## Case Studies
36+
37+
### case-studies/multi-source-analysis/
38+
39+
- **[fraser_river_plume.ipynb](https://github.com/OceanNetworksCanada/python-community-notebooks/blob/main/case-studies/multi-source-analysis/fraser_river_plume.ipynb)**
40+
Analyzes the Fraser River plume using multiple oceanographic datasets.
41+
*Keywords:* hypercoast, xarray, cartopy, gsw, plume

CONTRIBUTING.md

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Contributing
2+
3+
Thank you for contributing to Python Community Notebooks.
4+
5+
## Where To Place Content
6+
7+
Place your work under the best matching top-level category:
8+
9+
- `tutorials`: Entry-level learning notebooks.
10+
- `workflows`: Reusable, method-focused notebooks.
11+
- `case-studies`: End-to-end, question-driven analyses.
12+
- `data-pipelines`: Script-first acquisition/processing workflows with optional notebooks.
13+
- `shared`: Common helper code, schemas, and templates used across notebooks and scripts.
14+
15+
## Colab-compatible notebooks
16+
17+
We encourage contributors to create notebooks that are compatible with Google Colab whenever possible.
18+
19+
- Include an **"Open in Colab"** badge in the first cell of the notebook. The markdown link is `[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/OceanNetworksCanada/python-community-notebooks/blob/main/AAA/BBB/CCC.ipynb)`.
20+
- Handle dependencies in the notebook.
21+
- Add the bootstrap cell for token initialization and sys.path update before importing libraries.
22+
- You can open/test notebooks in Colab using any of the following:
23+
- Open the notebook in GitHub, then replace `github.com` with [githubtocolab.com](https://githubtocolab.com/) in the URL.
24+
- Open [Google Colab](https://colab.research.google.com/), choose **GitHub**, and paste the notebook GitHub URL.
25+
- Build a direct Colab URL in this format: `https://colab.research.google.com/github/OceanNetworksCanada/python-community-notebooks/blob/<branch-or-main>/AAA/BBB/CCC.ipynb`.
26+
- Click the **Open in Colab** badge in the first cell and update the branch name in the url for non-main branches.
27+
28+
## Dependency Management
29+
30+
- Prefer local dependency files inside related notebooks/scripts. Common libraries like `matplotlib`, `numpy`, and `pandas` do not need to be listed per notebook, as they are included in the root requirements.txt and Google Colab.
31+
- Non-versioned dependencies are easier to maintain and usually better for simple notebooks that rely on stable, common packages.
32+
- Versioned dependencies are better when reproducibility matters or when a notebook depends on fragile scientific/geospatial stacks.
33+
- Recommended default: avoid strict pinning for simple community notebooks, but pin versions when a notebook is known to break across package releases or when results must be reproducible.
34+
35+
Recommended dependency initialization cell (**always** install onc library because Google Colab does not have it by default):
36+
37+
```python
38+
!uv pip install -q onc xxx yyy
39+
```
40+
41+
## Bootstrap
42+
### Token Initialization
43+
44+
- Use `ONC_TOKEN` from Colab secrets (the "key" icon in the left sidebar) or local `.env`.
45+
- Do not hardcode API tokens in notebooks or scripts.
46+
47+
### Helper Files In Colab
48+
49+
If a notebook depends on helper scripts or shared modules in this repository, put them in the `shared` folder, and use a bootstrap cell in the notebooks. This keeps local runs clean while enabling imports in Colab.
50+
51+
### Recommended bootstrap cell
52+
53+
```python
54+
# Bootstrap cell
55+
import sys
56+
from pathlib import Path
57+
import os
58+
59+
def in_colab() -> bool:
60+
try:
61+
import google.colab
62+
return True
63+
except ImportError:
64+
return False
65+
66+
def setup_repo_for_shared_imports():
67+
"""
68+
Locate (or clone, in Colab) the notebook repository and add it to ``sys.path``.
69+
Assume that only the root directory has the ``shared`` directory.
70+
71+
Notes:
72+
- In Colab, this ensures the repository exists at
73+
``/content/python-community-notebooks`` by cloning it if needed.
74+
- In local environments, this searches upward from the current working
75+
directory for ``shared`` to identify the repo root.
76+
- If a repo root is found, it is prepended to ``sys.path`` to enable
77+
imports from the repository (e.g., ``shared`` modules).
78+
"""
79+
repo_dir: Path | None = None
80+
81+
if in_colab():
82+
repo_dir = Path('/content/python-community-notebooks')
83+
if not repo_dir.exists():
84+
!git clone --depth 1 https://github.com/OceanNetworksCanada/python-community-notebooks.git /content/python-community-notebooks
85+
else:
86+
cwd = Path.cwd().resolve()
87+
for candidate in [cwd, *cwd.parents]:
88+
if (candidate / 'shared').exists():
89+
repo_dir = candidate
90+
break
91+
92+
if repo_dir is not None and str(repo_dir) not in sys.path:
93+
sys.path.insert(0, str(repo_dir))
94+
95+
96+
97+
def init_token():
98+
"""
99+
Initialize the ONC_TOKEN environment variable.
100+
101+
Notes:
102+
- If in Colab, add your ONC_TOKEN secrets by clicking the key icon on the left sidebar
103+
- If in local, create .env file in the root directory, and add ONC_TOKEN=XXX in your .env file
104+
"""
105+
if in_colab():
106+
from google.colab import userdata
107+
os.environ['ONC_TOKEN'] = userdata.get('ONC_TOKEN')
108+
else:
109+
from dotenv import load_dotenv
110+
load_dotenv()
111+
112+
init_token()
113+
setup_repo_for_shared_imports()
114+
```
115+
116+
If helper files are not needed, remove `setup_repo_for_shared_imports()` definition and usage from the cell.
117+
118+
## Catalog Updates
119+
120+
When adding or moving notebooks, update [CATALOG.md](CATALOG.md):
121+
122+
- Add a short description.
123+
- Add keywords (optional but recommended).
124+

README.md

Lines changed: 32 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -2,166 +2,61 @@
22

33
## Overview
44

5-
The **Python Community Notebooks** repository contains a curated collection of Jupyter notebooks demonstrating practical applications of the [onc](https://github.com/OceanNetworksCanada/api-python-client) Python client library. These notebooks showcase practices for data manipulation, analysis, and visualization using Ocean Networks Canada (ONC) datasets.
5+
This repository contains community-maintained notebooks and scripts demonstrating practical use of the [onc](https://github.com/OceanNetworksCanada/api-python-client) Python client and ONC datasets.
66

7-
This repository serves as a learning resource for users at all levels seeking to deepen their understanding of oceanographic data processing and analysis techniques.
7+
The repository is organized by analysis purpose (not by contributor).
88

99
### Disclaimer
1010

11-
Community notebooks are provided as-is and are not regulated, endorsed, developed, or maintained by Ocean Networks Canada. All feature requests and bug reports must be directed to the original notebook author.
11+
Community content is provided as-is and is not regulated, endorsed, developed, or maintained by Ocean Networks Canada. Feature requests and bug reports should be directed to the original notebook or script author.
12+
13+
## Repository Structure
14+
15+
Folders are organized by purpose:
16+
17+
- `tutorials/`: Entry-level guided notebooks for learning core ONC and analysis concepts.
18+
- `workflows/`: Reusable method notebooks. They teach repeatable techniques that can be applied to many datasets.
19+
- `case-studies/`: End-to-end, question-driven analyses focused on a specific oceanographic story.
20+
- `data-pipelines/`: Script-first data acquisition and processing workflows, with optional companion notebooks.
21+
- `shared/`: Common helper code, schemas, and templates used across notebooks and scripts.
22+
23+
Notebook listings are maintained in [CATALOG.md](CATALOG.md).
1224

1325
## Quick Start
1426

1527
### Prerequisites
1628

1729
- Python 3.10+
18-
- An ONC API token (see [Token Configuration](#token-configuration))
19-
- Virtual environment (recommended)
30+
- [uv](https://docs.astral.sh/uv/)
31+
- ONC API token
32+
- Google account (optional, for running notebooks in Google Colab)
2033

2134
### Setup
2235

36+
For direct Google Colab usage (optional):
37+
38+
- Some notebooks support running in Colab before any local setup.
39+
- Use the notebook links in [CATALOG.md](CATALOG.md) to open the notebook on GitHub, then click the **Open in Colab** badge in the first cell (if present).
40+
- In Colab, set `ONC_TOKEN` using **Secrets** (key icon in the left sidebar): add a secret named `ONC_TOKEN`, then run the notebook token initialization cell. Adding a secret in Google Colab is a one-time effort, but you might need to toggle the notebook access for each new notebook to grant the access.
41+
2342
1. **Clone the repository**
2443
```bash
2544
git clone https://github.com/OceanNetworksCanada/python-community-notebooks.git
2645
cd python-community-notebooks
2746
```
2847

29-
2. **Create and activate a virtual environment**
30-
```bash
31-
python -m venv .venv
32-
source .venv/bin/activate # On Windows: .venv\Scripts\activate
33-
```
34-
35-
3. **Install dependencies**
36-
```bash
37-
pip install -r XXX/requirements.txt # Adjust the path as needed
38-
```
48+
2. **Install common dependencies**
49+
```bash
50+
uv pip install -r requirements.txt
51+
```
3952

40-
4. **Configure your ONC token** (see [Token Configuration](#token-configuration))
41-
42-
5. **Launch Jupyter in the terminal or using your favorite IDE**
53+
3. **Create a `.env` file for your token**
4354
```bash
44-
jupyter notebook
55+
echo "ONC_TOKEN=your_token_here" > .env
4556
```
4657

47-
## Notebook Catalog
48-
49-
### IanTBlack
50-
51-
#### barkley_canyon_vertical_profiler/
52-
53-
- **bacvp_ctd_up_profiles.ipynb**
54-
Demonstrates the creation of vertical profile plots for sea water potential density using CTD data.
55-
*Keywords:* gsw
56-
57-
- **bacvp_videocam_opencv.ipynb**
58-
Illustrates video processing and frame extraction from videocam sources.
59-
*Keywords:* opencv-python, video
60-
61-
62-
#### british_columbia_ferries/
63-
64-
- **distance_from_terminals.ipynb**
65-
Computes and visualizes time series data for ferry-to-terminal distances using geospatial calculations.
66-
*Keywords:* geopy, xarray
67-
68-
- **grid_transit.ipynb**
69-
Analyzes transit grid patterns and routing through ferry data.
70-
*Keywords:* xarray
71-
72-
- **system_sampling_state.ipynb**
73-
Examines sampling state and temporal coverage of ferry system measurements.
74-
*Keywords:*
75-
76-
- **transit_identifier.ipynb**
77-
Identifies and classifies distinct transit events within ferry operational data.
78-
*Keywords:*
79-
80-
- **twsb_tsg_clean_no_gaps.ipynb**
81-
Performs data quality assurance and gap-filling for TSG (Thermosalinograph) measurements.
82-
*Keywords:* xarray
83-
84-
85-
#### multiple_datasets/
86-
87-
- **fraser_river_plume.ipynb**
88-
Analyzes and visualizes the transport and evolution of the Fraser River plume using multi-source oceanographic data.
89-
*Keywords:* hypercoast, xarray, cartopy, gsw, plume
90-
91-
## Guidelines and Best Practices
92-
93-
The following guidelines are recommended for consistency across contributed notebooks. Individual contributors may maintain their own conventions; consult their notebook documentation for specific implementation details.
94-
95-
### Token Configuration
96-
97-
Authentication to the ONC API requires a personal token. For instructions on obtaining a token, refer to the [api-python-client documentation](https://github.com/OceanNetworksCanada/api-python-client#obtaining-a-token).
98-
99-
#### Recommended: Environment Variable Storage
100-
101-
Store your token as an environment variable rather than hardcoding it in notebooks. The `onc` library (version 2.6.0+) automatically reads the `ONC_TOKEN` environment variable when instantiating the `ONC` class.
102-
103-
**Configuration Steps:**
104-
105-
1. Create a `.env` file in the repository root:
106-
```
107-
ONC_TOKEN=your_token_here
108-
```
109-
110-
2. Add the initialization code to your notebook:
111-
```python
112-
from dotenv import load_dotenv
113-
from onc import ONC
114-
115-
load_dotenv()
116-
onc = ONC() # Automatically uses ONC_TOKEN from environment
117-
```
118-
119-
The `load_dotenv()` function searches for the `.env` file in the current directory and parent directories, allowing all notebooks to share a single configuration file.
120-
121-
### Dependency Management
122-
123-
#### Virtual Environments
124-
125-
Since different notebooks may require conflicting library versions, **always use virtual environments** to isolate dependencies. You can also use [uv](https://docs.astral.sh/uv/pip/environments/) or IDEs like [VS Code](https://code.visualstudio.com/docs/python/environments) and [PyCharm](https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html) to manage virtual environments.
126-
127-
You may create multiple virtual environments for different notebook sets if needed.
128-
129-
#### Requirements Files
130-
131-
Each contributor should maintain a `requirements.txt` file documenting all external library dependencies. You may maintain:
132-
- A single `requirements.txt` covering all your notebooks
133-
- Multiple `requirements.txt` files for notebook-specific dependencies
134-
135-
#### Installation in Notebooks
136-
137-
Optionally include an initialization cell to install dependencies within a notebook:
138-
```python
139-
!pip install -r ./requirements.txt # Adjust path as needed
140-
```
58+
4. **Open any notebook** in Jupyter or VS Code, and run the cells in the notebook.
14159

14260
## Contributing
14361

144-
Contributions are welcome! When adding new notebooks, please follow these standards:
145-
146-
### Notebook Structure
147-
148-
- Include a descriptive title and markdown cells explaining the analysis objective
149-
- Optionally add a brief overview of the data sources and processing steps
150-
- Document all external dependencies in a `requirements.txt` file
151-
- Use clear variable names and include inline comments for complex calculations
152-
- Add your notebook description to this README under the appropriate category. Common dependency libraries like `numpy`, `pandas`, `matplotlib` and `onc` can be omitted in the keywords.
153-
154-
### Code Organization
155-
156-
Helper functions and shared utilities could be organized in separate Python modules. To import modules from parent directories within notebooks, use the standard `sys` library, or the notebooks magic command `%cd`:
157-
158-
```python
159-
import sys
160-
sys.path.append('..')
161-
import module_name
162-
```
163-
164-
```python
165-
%cd ..
166-
import module_name
167-
```
62+
Contribution guidelines are in [CONTRIBUTING.md](CONTRIBUTING.md).

0 commit comments

Comments
 (0)