Skip to content

coral-li/searoute-python

Repository files navigation

SeaRoute Python

A Python implementation of the SeaRoute maritime distance calculation software, originally developed in Java by Eurostat. This package provides accurate sea-based distances and routes between any two points on Earth, maintaining full compatibility with the original Java implementation while offering enhanced performance and usability.

Python 3.8+ License

✨ Features

  • 🚢 Accurate Maritime Routes: Calculate shortest sea paths using Eurostat's proven algorithm
  • 🗺️ Multiple Resolutions: 5km to 100km network detail options
  • 🌊 Canal Controls: Control usage of major waterways (Suez, Panama, etc.)
  • 📊 Multiple Interfaces: Command-line tool, Python API, and REST API server
  • 🚀 Enhanced Performance: Improved geodesic calculations and comprehensive benchmarking
  • 📍 GeoJSON Output: Compatible with all major mapping tools
  • 🔄 Batch Processing: Handle multiple routes efficiently

🚀 Quick Start

Installation

# Install from GitHub (recommended)
pip install git+https://github.com/coral-li/searoute-python.git

Calculate Your First Route

from searoute_python import SeaRouting

# Initialize routing engine
sr = SeaRouting(resolution_km=20)

# Calculate route from Marseille to Shanghai
route = sr.get_route(
    origin_lon=5.3, origin_lat=43.3,      # Marseille
    dest_lon=121.8, dest_lat=31.2,        # Shanghai
    allow_suez=True, allow_panama=True
)

print(f"Maritime distance: {route['properties']['distance_km']:.2f} km")

Result: Maritime distance: 16,367.37 km

📦 Installation

Standard Installation

# Latest version from GitHub
pip install git+https://github.com/coral-li/searoute-python.git

# Specific version
pip install git+https://github.com/coral-li/searoute-python.git@v1.0.0

# For users with permission issues
pip install --user git+https://github.com/coral-li/searoute-python.git

Development Installation

git clone https://github.com/coral-li/searoute-python.git
cd searoute-python
pip install -e ".[dev]"

Verify Installation

python -c "from searoute_python import SeaRouting; print('✅ Installation successful!')"

📖 Usage Guide

Command Line Interface

# Single route calculation
searoute-py --origin-lon 5.3 --origin-lat 43.3 --dest-lon 121.8 --dest-lat 31.2 -o route.geojson

# Batch processing from CSV
searoute-py -i routes.csv -o output.geojson

# Custom settings
searoute-py -i routes.csv --res 10 --panama 0 --suez 1 -o output.geojson

CSV Input Format:

route name,olon,olat,dlon,dlat
Marseille-Shanghai,5.3,43.3,121.8,31.2
Hamburg-NewYork,9.993,53.551,-74.006,40.713

Python API

Basic Route Calculation

from searoute_python import SeaRouting

# Initialize with desired resolution
sr = SeaRouting(resolution_km=20)

# Calculate single route
route = sr.get_route(
    origin_lon=5.3, origin_lat=43.3,
    dest_lon=121.8, dest_lat=31.2,
    allow_suez=True,
    allow_panama=True
)

# Extract information
distance = route['properties']['distance_km']
geometry = route['geometry']  # GeoJSON LineString

Batch Processing

import pandas as pd

# Load routes from CSV
df = pd.read_csv('routes.csv')
routes_data = df.to_dict('records')

# Calculate all routes
sr = SeaRouting(resolution_km=20)
routes = sr.get_routes_from_csv(routes_data)

# Process results
for i, route in enumerate(routes):
    distance = route['properties']['distance_km']
    print(f"Route {i+1}: {distance:.2f} km")

🌐 REST API Server

Starting the Server

# Using console script (recommended) 
searoute-api

# Using Python module
python -m searoute_python.api

# Custom configuration
uvicorn searoute_python.api:app --host 127.0.0.1 --port 4242

Server runs at: http://127.0.0.1:4242

API Endpoints

Calculate Route

POST /route

curl -X POST "http://127.0.0.1:4242/route" \
  -H "Content-Type: application/json" \
  -d '{
    "origin": {"longitude": 5.3, "latitude": 43.3},
    "destination": {"longitude": 121.8, "latitude": 31.2},
    "resolution_km": 20,
    "canal_options": {
      "allow_suez": true,
      "allow_panama": true
    }
  }'

Health Check

GET /health - Check API status

Documentation

  • Swagger UI: http://127.0.0.1:4242/docs
  • ReDoc: http://127.0.0.1:4242/redoc

Python Client Example

import requests

def calculate_route(origin_lon, origin_lat, dest_lon, dest_lat):
    response = requests.post('http://127.0.0.1:4242/route', json={
        'origin': {'longitude': origin_lon, 'latitude': origin_lat},
        'destination': {'longitude': dest_lon, 'latitude': dest_lat},
        'resolution_km': 20
    })
    
    if response.status_code == 200:
        route = response.json()
        return route['properties']['distance_km']
    else:
        raise Exception(f"API Error: {response.text}")

# Calculate Marseille to Shanghai
distance = calculate_route(5.3, 43.3, 121.8, 31.2)
print(f"Distance: {distance:.2f} km")

⚙️ Configuration Options

Network Resolution

Resolution Detail Performance Use Case
5 km Highest Slowest Precision routing
10 km High Slow Detailed analysis
20 km Balanced Good Default/Recommended
50 km Medium Fast Quick calculations
100 km Lowest Fastest Bulk processing

Canal and Strait Controls

route = sr.get_route(
    origin_lon=..., origin_lat=...,
    dest_lon=..., dest_lat=...,
    # Major waterways (default: enabled)
    allow_suez=True,        # Suez Canal
    allow_panama=True,      # Panama Canal
    allow_gibraltar=True,   # Gibraltar Strait
    allow_malacca=True,     # Malacca Strait
    allow_dover=True,       # Dover Strait
    allow_bering=True,      # Bering Strait
    allow_magellan=True,    # Magellan Strait
    allow_babelmandeb=True, # Bab-el-Mandeb Strait
    
    # Specialized waterways (default: disabled)
    allow_kiel=False,       # Kiel Canal
    allow_corinth=False,    # Corinth Canal
    allow_northwest=False,  # Northwest Passage
    allow_northeast=False,  # Northeast Passage
)

📊 Performance & Benchmarking

Expected Performance (20km resolution)

  • Short routes (<5,000 km): 5-20ms
  • Medium routes (5,000-15,000 km): 15-40ms
  • Long routes (>15,000 km): 30-100ms
  • Network initialization: 100-500ms

Running Benchmarks

# Quick benchmark
./run_benchmarks.sh

# Full benchmark suite
./run_benchmarks.sh full

# Benchmark specific CSV routes
./run_benchmarks.sh csv

# Custom benchmark
python benchmark.py --quick -r 20 -r 50 -i 10

Benchmark Tools

  • benchmark.py - Comprehensive performance testing with predefined routes
  • benchmark_csv.py - Analyze performance of routes from CSV
  • run_benchmarks.sh - Easy-to-use benchmark runner script

🏗️ Integration Examples

Docker Deployment

FROM python:3.11-slim

# Install system dependencies
RUN apt-get update && apt-get install -y git gdal-bin libgdal-dev

# Install SeaRoute
RUN pip install git+https://github.com/coral-li/searoute-python.git

# Install production server
RUN pip install gunicorn

EXPOSE 8000
CMD ["gunicorn", "searoute_python.api:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]

Requirements.txt

# Add to your requirements.txt
git+https://github.com/coral-li/searoute-python.git

Conda Environment

# environment.yml
name: my-project
dependencies:
  - python>=3.8
  - pip
  - pip:
    - git+https://github.com/coral-li/searoute-python.git

🗺️ Major Port Coordinates

Port Longitude Latitude
New York, USA -74.0059 40.7128
Rotterdam, Netherlands 4.4777 51.9244
Singapore 103.8198 1.3521
Shanghai, China 121.4737 31.2304
Los Angeles, USA -118.2437 34.0522
Hamburg, Germany 9.9937 53.5511
Tokyo, Japan 139.6917 35.6895
Dubai, UAE 55.2708 25.2048

🔧 Advanced Topics

Distance Calculation Method

This implementation uses geodesic distance by default for finding nearest network nodes, which provides more accurate distance calculations on Earth's surface. This differs from the original Eurostat Java implementation which uses Euclidean distance in degrees.

# Default: Accurate geodesic distance
sr = SeaRouting(resolution_km=20)  # use_geodesic_distance=True

# Java compatibility mode
sr = SeaRouting(resolution_km=20, use_geodesic_distance=False)

Production Deployment

Using Gunicorn

pip install gunicorn
gunicorn searoute_python.api:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

Environment Variables

export SEAROUTE_HOST=0.0.0.0
export SEAROUTE_PORT=8000
export SEAROUTE_WORKERS=4

🐛 Troubleshooting

Common Issues

Installation Issues:

# Missing git
sudo apt-get install git  # Ubuntu/Debian
brew install git         # macOS

# Missing geospatial dependencies
sudo apt-get install gdal-bin libgdal-dev libproj-dev libgeos-dev  # Ubuntu
brew install gdal proj geos  # macOS

Runtime Issues:

  • Import Error: Ensure package is properly installed with pip list | grep searoute-python
  • No route found: Verify coordinates are in water-accessible locations
  • Performance: Use higher resolution values (50km/100km) for faster processing

Error Handling

The API returns meaningful error messages:

  • 400: Invalid coordinates or parameters
  • 404: No maritime route found
  • 422: Request format validation error
  • 500: Internal server error

📝 Output Format

All route calculations return GeoJSON features:

{
  "type": "Feature",
  "properties": {
    "distance_km": 16367.37,
    "origin_lon": 5.3,
    "origin_lat": 43.3,
    "dest_lon": 121.8,
    "dest_lat": 31.2,
    "origin_approx_dist_km": 4.85,
    "dest_approx_dist_km": 3.21,
    "resolution_km": 20,
    "path_nodes": 142
  },
  "geometry": {
    "type": "LineString",
    "coordinates": [[5.3, 43.3], [5.4, 43.4], ...]
  }
}

🤝 Contributing

We welcome contributions! To get started:

  1. Fork the repository
  2. Install development dependencies: pip install -e ".[dev]"
  3. Run tests: pytest
  4. Run benchmarks: ./run_benchmarks.sh
  5. Submit a pull request

📄 License

This Python implementation is based on the original SeaRoute software developed by Eurostat (European Commission's statistical office). This package maintains full compatibility with the original Java implementation while extending it with additional features and performance improvements.

Original Java SeaRoute: https://github.com/eurostat/searoute - Developed by Eurostat for calculating maritime distances and routes
Python Implementation: Enhanced port with additional APIs, better performance, and modern tooling

🙋 Support

  • Issues: Create an issue on GitHub for bugs or feature requests
  • Documentation: This README contains comprehensive usage information
  • Performance: Run benchmarks to verify expected performance on your system

SeaRoute Python - Accurate maritime routing for the modern world 🌊

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published