PyTorch implementation of the Gibbs SeaWater (GSW) Oceanographic Toolbox
Project description
GSW PyTorch
PyTorch implementation of the Gibbs SeaWater (GSW) Oceanographic Toolbox.
This package provides a PyTorch-based reimplementation of the GSW Python package, enabling:
- Automatic differentiation via PyTorch's autograd
- GPU acceleration for large-scale oceanographic computations
- Numerical parity with the reference numpy-based GSW implementation (within 1e-8 tolerance)
- Same API as the original GSW-Python package
Installation
Development Installation
This package uses uv for environment management:
# Create virtual environment
uv venv
# Activate environment (Linux/Mac)
source .venv/bin/activate
# Windows: .venv\Scripts\activate
# Install package in development mode
uv pip install -e .
# Install development dependencies
uv pip install -e ".[dev]"
Future: PyPI Installation
pip install gsw-torch
Usage
The API is designed to match the original GSW-Python package:
import torch
import gsw_torch
# Create input tensors
SA = torch.tensor([35.0], dtype=torch.float64) # Absolute Salinity, g/kg
CT = torch.tensor([15.0], dtype=torch.float64) # Conservative Temperature, °C
p = torch.tensor([100.0], dtype=torch.float64) # Pressure, dbar
# Calculate density
rho = gsw_torch.rho(SA, CT, p)
# Calculate specific volume and expansion coefficients
specvol, alpha, beta = gsw_torch.specvol_alpha_beta(SA, CT, p)
# Functions support automatic differentiation
SA.requires_grad = True
rho = gsw_torch.rho(SA, CT, p)
rho.backward()
print(SA.grad) # Gradient of density with respect to salinity
Differences from NumPy GSW
- Input/Output Types: Functions accept and return
torch.Tensorobjects instead of numpy arrays - Automatic Conversion: Numpy arrays are automatically converted to tensors
- Scalar Returns: Scalar results are returned as 0-dimensional tensors (use
.item()to get Python scalars) - GPU Support: All operations can run on GPU by using CUDA tensors
- Gradient Computation: All differentiable operations support automatic differentiation
Implementation Status
Version 0.1.0 - Beta Release
The package includes 118+ functions with full PyTorch implementations:
- ✅ Conversions - Temperature, salinity, entropy, pressure conversions (30+ functions)
- ✅ Density - Density, specific volume, expansion coefficients (25+ functions)
- ✅ Energy - Enthalpy, internal energy, latent heat (10+ functions)
- ✅ Freezing - Freezing point calculations (5+ functions)
- ✅ Ice - Ice thermodynamics and melting functions (15+ functions)
- ✅ Stability - Buoyancy frequency, Turner angle, stability analysis (5+ functions)
- ✅ Geostrophy - Geostrophic velocity calculations (4+ functions)
- ✅ Interpolation - Vertical interpolation using Reiniger-Ross method (2+ functions)
- ✅ Utility - Oxygen solubility, chemical potential, PCHIP interpolation (5+ functions)
All functions support:
- Automatic differentiation (autograd)
- GPU acceleration
- Numerical parity with reference GSW (within 1e-8 tolerance)
See IMPLEMENTATION_STATUS.md for detailed status and known limitations.
Development History
This package was autonomously translated from the reference GSW-Python implementation to PyTorch using Cursor AI agents. The translation process followed strict guardrails to ensure correctness:
Core Principles:
- Exact numeric parity: All functions maintain numerical accuracy within 1e-8 tolerance compared to the reference implementation (float64, CPU)
- Pure PyTorch: No NumPy dependencies in core library code; all operations use PyTorch tensors exclusively
- Autograd compatibility: All differentiable functions support automatic differentiation without breaking gradients
- Reference as oracle: The original GSW implementation served as a read-only reference; no modifications were made to the oracle
Translation Constraints:
- Preserved evaluation order to maintain rounding behavior
- Used
torch.float64as default dtype throughout - Avoided
.item()calls and Python branching on tensor values to maintain autograd compatibility - Replaced NumPy operations with equivalent PyTorch operations (
np.where→torch.where, etc.) - Implemented iterative solvers with deterministic, fixed iteration counts matching the reference
Quality Assurance:
- Comprehensive parity testing against reference GSW for all 118+ functions
- Gradient checking for all differentiable functions
- Continuous integration with automated testing, linting, and type checking
Testing
Run tests with pytest:
# Run all tests
pytest
# Run with coverage
pytest --cov=gsw_torch
# Run parity tests against reference implementation
pytest --run-parity
# Run gradient checks
pytest tests/test_gradcheck.py
Development
Code Quality
- Linting: Uses
rufffor code formatting and linting - Type Checking: Uses
mypyfor static type checking - Testing: Uses
pytestwith coverage reporting
# Format code
ruff format gsw_torch tests
# Lint code
ruff check gsw_torch tests
# Type check
mypy gsw_torch
Adding New Functions
- Implement the function in the appropriate
_coremodule (e.g.,_core/density.py) - Export it from the module's
__init__.pyor module file - Add tests in
tests/test_*.py - Add gradient checks if the function is differentiable
- Add parity tests against reference implementation
Documentation
- Quick Start: See
QUICKSTART.mdfor examples and common patterns - Implementation Status: See
IMPLEMENTATION_STATUS.mdfor detailed function status - Contributing: See
CONTRIBUTING.mdfor contribution guidelines - Release Notes: See
CHANGELOG.mdfor version history
Known Limitations
Some functions have minor precision limitations or edge case issues:
enthalpy_second_derivatives.h_SA_SA: Precision errors at high pressure (~4e-3)entropy_from_CT: Minor precision errors (~8.9e-8)spiciness0/1/2: Polynomial fitting precision (~5-10e-6)CT_freezing,t_freezing: Non-finite gradients when SA=0
See IMPLEMENTATION_STATUS.md for complete details and workarounds.
Citation
If you use GSW PyTorch in your research, please cite:
@software{gsw_torch,
title = {GSW PyTorch: PyTorch Implementation of the Gibbs SeaWater Oceanographic Toolbox},
authors = {Miranda, Jose R.; Zavala-Romero, Olmo},
year = {2026},
version = {0.1.0},
url = {https://github.com/0jrm/gsw-torch},
note = {Autonomously translated from GSW-Python using Cursor AI agents}
}
References
- TEOS-10 - The international thermodynamic equation of seawater
- GSW-Python - Reference numpy-based implementation
- GSW-Matlab - Original MATLAB implementation
- GSW-C - C implementation
License
This project is licensed under the BSD 3-Clause License - see the LICENSE file for details.
The software is based on the TEOS-10 GSW Toolbox, which is licensed under a BSD 3-clause license by SCOR/IAPSO WG127.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gsw_torch-0.1.1.tar.gz.
File metadata
- Download URL: gsw_torch-0.1.1.tar.gz
- Upload date:
- Size: 2.3 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4ee2db80fdb2f0eface78de87bafadf01d59d44384b8d5bc39cb76a680e1397d
|
|
| MD5 |
83be54ab4d922c64edec8cb85c5825db
|
|
| BLAKE2b-256 |
c3059c963291f601021710a744abd2090f7f0d85cd288923906ff41a61a25dbb
|
File details
Details for the file gsw_torch-0.1.1-py3-none-any.whl.
File metadata
- Download URL: gsw_torch-0.1.1-py3-none-any.whl
- Upload date:
- Size: 2.3 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cf7a7b3fa643acc980f3454b735a34577d27e462804835d534e97bb3e59f02a7
|
|
| MD5 |
e8206ee1962161b6b3ea4bb31a56c503
|
|
| BLAKE2b-256 |
bb3f51fa42ccd9e4c2064c884c3ecd49f00c3bb84fa14c62f16645e5ebd5012e
|