General Utilities

cruiseplan.utils package.

This package contains utility modules and helper functions for cruise planning:

  • config: Utilities for loading, saving, and managing cruise configuration files

  • constants: Default values and constants used throughout the application

  • coordinates: Coordinate formatting and conversion utilities for maritime applications

These utilities provide shared functionality across different parts of the cruiseplan system, including data processing, configuration management, and coordinate handling.

cruiseplan.utils.cache module

Data caching utilities for CruisePlan.

This module provides caching functionality for storing and retrieving expensive computations and external data.

class cruiseplan.utils.cache.CacheManager(cache_dir: str = '.cache')[source]

Bases: object

Simple file-based cache using Pickle.

Provides basic caching functionality with automatic serialization using Python’s pickle module. Cache files are stored as .pkl files in the specified cache directory.

cache_dir

Directory where cache files are stored.

Type:

Path

__init__(cache_dir: str = '.cache')[source]

Initialize cache manager.

Parameters:

cache_dir (str, optional) – Directory path for cache storage (default: “.cache”). Will be created if it doesn’t exist.

clear(key: str) None[source]

Remove specific item from cache.

Parameters:

key (str) – Cache key identifier to remove.

get(key: str) Any | None[source]

Retrieve item from cache if it exists.

Parameters:

key (str) – Cache key identifier.

Returns:

Cached data if found and successfully loaded, None otherwise.

Return type:

Optional[Any]

set(key: str, data: Any) None[source]

Save item to cache.

Parameters:
  • key (str) – Cache key identifier.

  • data (Any) – Data to cache. Must be pickle-serializable.

cruiseplan.utils.coordinates module

Coordinate formatting utilities for scientific and maritime applications.

This module provides functions to format coordinates in various standard formats used in oceanographic and maritime contexts, including decimal degrees, degrees and decimal minutes (DDM), and LaTeX-formatted output. Also includes utilities for extracting coordinates from cruise configurations and calculating map bounds.

Notes

All coordinate functions expect input in decimal degrees and handle both northern/eastern (positive) and southern/western (negative) coordinates. The CoordConverter class provides static methods for coordinate conversions.

class cruiseplan.utils.coordinates.CoordConverter[source]

Bases: object

Utility class for coordinate unit conversions.

This class provides static methods for converting between different coordinate representations commonly used in maritime and scientific contexts.

static decimal_degrees_to_ddm(decimal_degrees: float) tuple[float, float][source]

Convert decimal degrees to degrees and decimal minutes.

Parameters:

decimal_degrees (float) – Coordinate in decimal degrees format.

Returns:

Tuple of (degrees, decimal_minutes).

Return type:

tuple of float

Examples

>>> CoordConverter.decimal_degrees_to_ddm(65.7458)
(65.0, 44.75)
cruiseplan.utils.coordinates.calculate_map_bounds(all_lats: list[float], all_lons: list[float], padding_percent: float = 0.05, padding_degrees: float | None = None, apply_aspect_ratio: bool = True, round_to_degrees: bool = True) tuple[float, float, float, float][source]

Calculate map bounds with flexible padding and aspect ratio correction.

Parameters:
  • all_lats (list of float) – All latitude values to include

  • all_lons (list of float) – All longitude values to include

  • padding_percent (float, optional) – Padding as fraction of range (default 0.05 = 5%). Ignored if padding_degrees is set.

  • padding_degrees (float, optional) – Fixed padding in degrees. If set, overrides padding_percent.

  • apply_aspect_ratio (bool, optional) – Whether to apply geographic aspect ratio correction (default True)

  • round_to_degrees (bool, optional) – Whether to round bounds outward to whole degrees (default True)

Returns:

(final_min_lon, final_max_lon, final_min_lat, final_max_lat)

Return type:

tuple

cruiseplan.utils.coordinates.compute_final_limits(lon_min: float, lon_max: float, lat_min: float, lat_max: float) tuple[float, float, float, float][source]

Compute final map limits accounting for geographic aspect ratio.

Parameters:
  • lon_min (float) – Initial longitude bounds

  • lon_max (float) – Initial longitude bounds

  • lat_min (float) – Initial latitude bounds

  • lat_max (float) – Initial latitude bounds

Returns:

(final_lon_min, final_lon_max, final_lat_min, final_lat_max)

Return type:

tuple

cruiseplan.utils.coordinates.extract_coordinates_from_cruise(cruise: Any) tuple[list[float], list[float], list[str], tuple[float, ...] | None, tuple[float, ...] | None][source]

Extract coordinates from cruise configuration.

Parameters:

cruise (Cruise) – Cruise object with station registry and configuration

Returns:

(all_lats, all_lons, station_names, departure_port, arrival_port) departure_port and arrival_port are tuples of (lat, lon, name) or None

Return type:

tuple

cruiseplan.utils.coordinates.format_ddm_comment(lat: float, lon: float) str[source]

Format coordinates as degrees/decimal minutes comment for validator compliance.

This function generates ddm format that passes the strict validator requirements: - DD MM.MM’N, DDD MM.MM’W format (degrees and decimal minutes) - No degree symbols (°) - 2-digit latitude degrees, 3-digit longitude degrees with leading zeros - Exactly 2 decimal places for minutes

Parameters:
  • lat (float) – Latitude in decimal degrees.

  • lon (float) – Longitude in decimal degrees.

Returns:

ddm comment like “65 44.75’N, 024 28.75’W”.

Return type:

str

Examples

>>> format_ddm_comment(65.7458, -24.4792)
"65 44.75'N, 024 28.75'W"
cruiseplan.utils.coordinates.format_position_latex(lat: float, lon: float) str[source]

Format coordinates for LaTeX output with proper symbols.

Parameters:
  • lat (float) – Latitude in decimal degrees.

  • lon (float) – Longitude in decimal degrees.

Returns:

LaTeX-formatted position string.

Return type:

str

Examples

>>> format_position_latex(65.7458, -24.4792)
"65$^\\circ$44.75'N, 024$^\\circ$28.75'W"

cruiseplan.utils.io module

General file I/O utilities for the cruiseplan package.

This module provides low-level file system validation and path handling utilities used by API functions to ensure consistent error handling across the package.

I/O Module Architecture: - cruiseplan.utils.io (this module): File system validation, path handling, directory creation - cruiseplan.schema.yaml_io: YAML file format reading/writing with comment preservation - cruiseplan.core.serialization: High-level CruiseInstance object serialization to YAML - cruiseplan.output.*_generator: Specialized output format generators (HTML, LaTeX, CSV, etc.)

Dependencies: This is the lowest layer - other I/O modules may use these utilities.

See Also: - For YAML file operations: cruiseplan.schema.yaml_io - For converting CruiseInstance objects to YAML: cruiseplan.core.serialization - For generating specific output formats: cruiseplan.output.html_generator, cruiseplan.output.latex_generator, etc.

cruiseplan.utils.io.generate_output_filename(input_path: str | Path, suffix: str, extension: str | None = None) str[source]

Generate output filename by adding suffix to input filename.

# NOTE: Used by stations_api.py and other API modules for consistent filename generation

This utility creates output filenames by taking an input path, extracting its stem, and adding a suffix and optional new extension.

Parameters:
  • input_path (Union[str, Path]) – Input file path to base the output name on

  • suffix (str) – Suffix to add (e.g., “_processed”, “_with_depths”)

  • extension (str, optional) – New file extension including the dot (e.g., “.yaml”, “.json”). If None, uses the original file’s extension.

Returns:

Generated filename with suffix and extension

Return type:

str

Examples

>>> generate_output_filename("cruise.yaml", "_enriched")
"cruise_enriched.yaml"
>>> generate_output_filename("data.csv", "_processed", ".json")
"data_processed.json"
cruiseplan.utils.io.setup_output_paths(config_file: str | Path, output_dir: str = 'data', output: str | None = None) tuple[Path, str][source]

Helper function to set up output directory and base filename from config file and parameters.

This is the consolidated output path utility, migrated from utils/config.py. It handles both explicit output naming and automatic name derivation from config files with YAML cruise_name extraction.

Parameters:
  • config_file (Union[str, Path]) – Input YAML configuration file

  • output_dir (str, optional) – Output directory (default: “data”)

  • output (str, optional) – Base filename for outputs (default: use cruise name from YAML)

Returns:

(output_dir_path, base_name) where output_dir_path is resolved Path and base_name is the filename stem to use for outputs

Return type:

tuple[Path, str]

Examples

>>> setup_output_paths("cruise.yaml", "results")
(Path("/path/to/results"), "cruise_name_from_yaml")
>>> setup_output_paths("cruise.yaml", output="custom_name")
(Path("/path/to/data"), "custom_name")
cruiseplan.utils.io.validate_input_file(file_path: str | Path, must_exist: bool = True) Path[source]

Validate and resolve an input file path for API operations.

This is the centralized file validation used by all API functions to ensure consistent error handling and messaging across the package.

Parameters:
  • file_path (Union[str, Path]) – Path to validate

  • must_exist (bool, optional) – Whether the file must exist (default: True)

Returns:

Resolved and validated Path object

Return type:

Path

Raises:

ValueError – If file validation fails (will be caught and re-raised as FileError by API)

cruiseplan.utils.io.validate_output_directory(directory_path: str | Path, create_if_missing: bool = True) Path[source]

Validate and optionally create an output directory.

Parameters:
  • directory_path (Union[str, Path]) – Directory path to validate

  • create_if_missing (bool, optional) – Whether to create the directory if it doesn’t exist (default: True)

Returns:

Resolved and validated directory Path object

Return type:

Path

Raises:

ValueError – If directory validation fails (will be caught and re-raised as FileError by API)

cruiseplan.utils.logging module

Centralized logging configuration utilities.

This module provides common logging setup functions used across multiple CLI commands and API modules for consistent logging behavior.

cruiseplan.utils.logging.configure_logging(verbose: bool = False) None[source]

Configure logging level and format for cruiseplan operations.

This standardizes logging configuration across all API modules, replacing multiple inconsistent basicConfig calls.

Parameters:

verbose (bool, optional) – Enable verbose (DEBUG) logging. If False, uses INFO level.

Notes

Uses a consistent format: “%(levelname)s: %(message)s” Forces reconfiguration with force=True to override any existing config.

cruiseplan.utils.logging.get_logger(name: str) Logger[source]

Get a logger with consistent naming convention.

Parameters:

name (str) – Logger name, typically __name__

Returns:

Configured logger instance

Return type:

logging.Logger

cruiseplan.utils.plot_config module

Centralized plotting configuration for consistent visualization across cruiseplan.

This module provides: 1. Colormaps for bathymetry and oceanographic data (moved from interactive/colormaps.py) 2. Centralized styling configuration for all plot elements 3. Symbol definitions for consistent plotting across PNG, KML, and interactive maps

cruiseplan.utils.plot_config.check_matplotlib_available() None[source]

Check that matplotlib is available for interactive plotting.

Raises:

ImportError – If matplotlib is not available with installation instructions

cruiseplan.utils.plot_config.create_bathymetry_colormap() LinearSegmentedColormap[source]

Create the Flemish Cap bathymetry colormap matching the CPT specification.

This creates a colormap with constant colors within each depth range, exactly matching the CPT specification.

Returns:

Bathymetry colormap with proper depth-color mapping

Return type:

matplotlib.colors.LinearSegmentedColormap

cruiseplan.utils.plot_config.get_colormap(name: str) Colormap[source]

Get a colormap by name.

Parameters:

name (str) – Name of the colormap (‘bathymetry’ or ‘blues_r’)

Returns:

The requested colormap

Return type:

matplotlib.colors.Colormap

Raises:

ValueError – If the colormap name is not recognized

cruiseplan.utils.plot_config.get_legend_entries() dict[str, dict[str, Any]][source]

Get legend entries for all plot styles.

Returns:

Dictionary mapping labels to style dictionaries for legend creation

Return type:

Dict[str, Dict[str, Any]]

cruiseplan.utils.plot_config.get_plot_style(entity_type: str, operation_type: str | None = None, action: str | None = None) dict[str, Any][source]

Get plot styling for a specific entity type.

Parameters:
  • entity_type (str) – Type of entity (‘station’, ‘mooring’, ‘transit’, ‘area’, ‘departure_port’, ‘arrival_port’)

  • operation_type (str, optional) – Operation type (e.g., ‘CTD’, ‘mooring’, ‘underway’, ‘survey’)

  • action (str, optional) – Specific action (e.g., ‘profile’, ‘deployment’, ‘ADCP’, ‘bathymetry’)

Returns:

Dictionary of matplotlib styling parameters

Return type:

Dict[str, Any]

cruiseplan.utils.plot_config.interpolate_great_circle_position(start_lat: float, start_lon: float, end_lat: float, end_lon: float, fraction: float) tuple[float, float][source]

Interpolate position along great circle route using spherical geometry.

This function is useful for generating smooth great circle routes for map visualization, which provides more accurate geographic representation than straight line interpolation.

Parameters:
  • start_lat (float) – Starting latitude in decimal degrees.

  • start_lon (float) – Starting longitude in decimal degrees.

  • end_lat (float) – Ending latitude in decimal degrees.

  • end_lon (float) – Ending longitude in decimal degrees.

  • fraction (float) – Interpolation fraction (0.0 = start, 1.0 = end).

Returns:

Interpolated (latitude, longitude) in decimal degrees.

Return type:

Tuple[float, float]

cruiseplan.utils.units module

Unit conversion constants and functions.

This module provides immutable physical constants and unit conversion functions for time, distance, and other measurements. These are mathematical constants that do not change based on cruise configuration.

cruiseplan.utils.units.hours_to_days(hours: float) float[source]

Convert hours to days.

Parameters:

hours (float) – Time duration in hours.

Returns:

Time duration in days.

Return type:

float

cruiseplan.utils.units.hours_to_minutes(hours: float) float[source]

Convert hours to minutes.

Parameters:

hours (float) – Time duration in hours.

Returns:

Time duration in minutes.

Return type:

float

cruiseplan.utils.units.km_to_nm(km: float) float[source]

Convert kilometers to nautical miles.

Parameters:

km (float) – Distance in kilometers.

Returns:

Distance in nautical miles.

Return type:

float

cruiseplan.utils.units.minutes_to_days(minutes: float) float[source]

Convert minutes to days.

Parameters:

minutes (float) – Time duration in minutes.

Returns:

Time duration in days.

Return type:

float

cruiseplan.utils.units.minutes_to_hours(minutes: float) float[source]

Convert minutes to hours.

Parameters:

minutes (float) – Time duration in minutes.

Returns:

Time duration in hours.

Return type:

float

cruiseplan.utils.units.nm_to_km(nm: float) float[source]

Convert nautical miles to kilometers.

Parameters:

nm (float) – Distance in nautical miles.

Returns:

Distance in kilometers.

Return type:

float

cruiseplan.utils.units.rate_per_second_to_rate_per_minute(rate_per_sec: float) float[source]

Convert rate per second to rate per minute.

For example: meters per second → meters per minute

Parameters:

rate_per_sec (float) – Rate value per second (e.g., m/s).

Returns:

Rate value per minute (e.g., m/min).

Return type:

float

cruiseplan.utils.units.seconds_to_minutes(seconds: float) float[source]

Convert seconds to minutes.

Parameters:

seconds (float) – Time duration in seconds.

Returns:

Time duration in minutes.

Return type:

float