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 filesconstants: Default values and constants used throughout the applicationcoordinates: 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:
objectSimple 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') None[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.
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:
objectUtility class for coordinate unit conversions.
This class provides static methods for converting between different coordinate representations commonly used in maritime and scientific contexts.
- static decmin_to_decimal_degrees(decmin_str: str) float[source]
Convert degrees decimal minutes format to decimal degrees.
- Parameters:
decmin_str (str) – Coordinate in “DD MM.MMM N/S” or “DDD MM.MMM E/W” format.
- Returns:
Coordinate in decimal degrees.
- Return type:
float
Examples
>>> CoordConverter.decmin_to_decimal_degrees("65 14.640 N") 65.244 >>> CoordConverter.decmin_to_decimal_degrees("031 19.062 W") -31.3177 >>> CoordConverter.decmin_to_decimal_degrees("65 31.316 N") 65.521933...
- static format_latitude_decmin(decimal_degrees: float) str[source]
Convert latitude to decimal minutes format.
- Parameters:
decimal_degrees (float) – Latitude in decimal degrees format.
- Returns:
Latitude in “DD MM.MMM N/S” format.
- Return type:
str
Examples
>>> CoordConverter.format_latitude_decmin(65.244) "65 14.640 N" >>> CoordConverter.format_latitude_decmin(-65.244) "65 14.640 S"
- static format_longitude_decmin(decimal_degrees: float) str[source]
Convert longitude to decimal minutes format.
- Parameters:
decimal_degrees (float) – Longitude in decimal degrees format.
- Returns:
Longitude in “DDD MM.MMM E/W” format.
- Return type:
str
Examples
>>> CoordConverter.format_longitude_decmin(-31.3177) "031 19.062 W" >>> CoordConverter.format_longitude_decmin(31.3177) "031 19.062 E"
- 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.ddm_parts(decimal_degrees: float, decimals: int = 2) tuple[int, float][source]
Split a coordinate into whole degrees and rounded decimal minutes.
Minutes are rounded to
decimalsplaces first; when they round to 60 the degree is carried, so 59.99999 gives(60, 0.0)and never(59, 60.0). The sign is dropped: usedecimal_degrees >= 0for the hemisphere.- Parameters:
decimal_degrees (float) – Latitude or longitude in decimal degrees.
decimals (int, optional) – Decimal places kept in the minutes (default: 2).
- Returns:
Absolute whole degrees and minutes in
[0, 60), rounded todecimalsplaces.- Return type:
tuple of (int, float)
Examples
>>> ddm_parts(65.7458) (65, 44.75) >>> ddm_parts(-0.99999) (1, 0.0)
- cruiseplan.utils.coordinates.distance_nm(start: tuple[float, float], end: tuple[float, float]) float[source]
Great-circle (haversine) distance between two positions in nautical miles.
- Parameters:
start (tuple of float) – (latitude, longitude) of the first position in decimal degrees.
end (tuple of float) – (latitude, longitude) of the second position in decimal degrees.
- Returns:
Distance in nautical miles on a sphere of radius
EARTH_RADIUS_KM.- Return type:
float
- cruiseplan.utils.coordinates.extract_coordinates_from_cruise(cruise: CruiseInstance) tuple[list[float], list[float], list[str], tuple[float, ...] | None, tuple[float, ...] | None][source]
Extract coordinates from cruise configuration.
- Parameters:
cruise (CruiseInstance) – 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.config.yaml_io: YAML file format reading/writing with comment preservation - cruiseplan.runtime.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.config.yaml_io - For converting CruiseInstance objects to YAML: cruiseplan.runtime.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]
Set up the output directory and base filename from the config file and parameters.
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
Logging helpers for the cruiseplan package.
The library never configures logging handlers: modules log through
logging.getLogger(__name__) and the application (the cruiseplan
command line, a script or a notebook) decides where messages go. The
API functions’ verbose= parameter only lowers the level of the
cruiseplan logger for the duration of the call.
- cruiseplan.utils.logging.debug_logging(enabled: bool = True) Iterator[None][source]
Set the
cruiseplanlogger to DEBUG inside the block, then restore it.Handlers are left alone, so the messages reach whatever handlers the application configured.
- Parameters:
enabled (bool, optional) – If False, the block runs with the logger unchanged (default True).
- cruiseplan.utils.logging.honors_verbose(func: Callable[[P], R]) Callable[[P], R][source]
Run func under
debug_logging()when it is called withverbose=True.- Parameters:
func (callable) – A function with a
verboseparameter.- Returns:
The wrapped function, with the same signature and docstring.
- Return type:
callable
cruiseplan.utils.plot_config module
Centralized plotting configuration for consistent visualization across cruiseplan.
This module provides: 1. Colormaps for bathymetry and oceanographic data 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(max_depth: int | None = None) 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.
- Parameters:
max_depth (int, optional) – Maximum water depth in metres (positive integer). When provided, the colour scale spans from
-max_depthto +200 m instead of -8000 to +200 m, spreading full colour contrast across shallower water. For example,max_depth=1000makes the range -1000 to +200 m. Default is None (full -8000 to +200 m range).- 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.round_to_minutes(dt: datetime, step: int = 10) datetime[source]
Round a time to the nearest
stepminutes, carrying into the date.The whole time is rounded, seconds included, and a time exactly halfway rounds up, as MATLAB
rounddoes in letsgo.m: withstep=10, 12:05 gives 12:10, 12:04:59 gives 12:00, 12:05:40 gives 12:10, and 23:55 gives 00:00 on the next day.- Parameters:
dt (datetime) – Time to round.
step (int, optional) – Rounding step in minutes (default: 10).
- Returns:
Rounded time, with seconds and microseconds set to zero.
- Return type:
datetime