Source code for cruiseplan.output.kml_generator

"""
KML Generation System for Cruise Planning.

Generates Google Earth compatible KML files from cruise configuration catalogs.
Creates geospatial visualizations of all cruise entities (stations, moorings,
transits, ports, areas) for geographic analysis and planning.

This module provides two generation modes:
1. Catalog-based: Generate KML from YAML configuration entities (recommended)
2. Timeline-based: Generate KML from scheduled timeline activities (legacy)

Notes
-----
KML files can be opened directly in Google Earth or other GIS applications.
Each entity type is styled differently for visual distinction. Point features
include detailed metadata in popups. Catalog-based generation shows each
location once regardless of visitation frequency.
"""

import logging
from pathlib import Path

from cruiseplan.config.cruise_config import CruiseConfig
from cruiseplan.output.output_utils import round_time_to_minute
from cruiseplan.timeline.record import ActivityRecord

logger = logging.getLogger(__name__)

# KML styles for different operation types
# TODO: Refactor to use centralized PLOT_STYLES from utils/plot_config.py
KML_STYLES = """
        <Style id="stationStyle">
            <IconStyle>
                <color>ff0000ff</color>
                <scale>1.2</scale>
                <Icon>
                    <href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href>
                </Icon>
            </IconStyle>
        </Style>

        <Style id="mooringStyle">
            <IconStyle>
                <color>ff00ff00</color>
                <scale>1.2</scale>
                <Icon>
                    <href>http://maps.google.com/mapfiles/kml/shapes/placemark_square.png</href>
                </Icon>
            </IconStyle>
        </Style>

        <Style id="lineOpStyle">
            <LineStyle>
                <color>ff0066FF</color>
                <width>3</width>
            </LineStyle>
        </Style>

        <Style id="areaStyle">
            <LineStyle>
                <color>ffFFD700</color>
                <width>2</width>
            </LineStyle>
            <PolyStyle>
                <color>66FFD700</color>
            </PolyStyle>
        </Style>
"""


[docs] class KMLGenerator: """ Manages KML generation for cruise schedules showing only scientific operations. This class generates Google Earth compatible KML files containing geospatial representations of scientific cruise activities. Only scientific operations are included, with different styling for each operation type. """
[docs] def __init__(self) -> None: """Initialize the KML generator."""
[docs] def generate_schedule_kml( self, config: CruiseConfig, timeline: list[ActivityRecord], output_file: Path ) -> Path: """ Generate KML schedule output with only scientific operations. Parameters ---------- config : CruiseConfig The cruise configuration object timeline : List[ActivityRecord] Timeline generated by the scheduler output_file : Path Path to output KML file Returns ------- Path Path to generated KML file """ # Define KML styles for different operation types kml_content = f"""<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name>{config.cruise_name} - Schedule</name> <description>{config.description or "Cruise schedule"}</description> <!-- Styles for different operation types --> <Style id="stationStyle"> <IconStyle> <color>ff0000ff</color> <scale>1.2</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href> </Icon> </IconStyle> </Style> <Style id="mooringStyle"> <IconStyle> <color>ff00ff00</color> <scale>1.2</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/shapes/placemark_square.png</href> </Icon> </IconStyle> </Style> <Style id="lineOpStyle"> <LineStyle> <color>ff0066FF</color> <width>3</width> </LineStyle> </Style> """ # Scientific operations and ports; a line runs from its entry to its # exit, an area is shown at its entry point (records carry no corners) for activity in timeline: if activity.kind not in {"station", "mooring", "port", "line", "area"}: continue if activity.kind == "line": kml_content += f""" <Placemark> <name>{activity.label}</name> <description> Activity: {activity.activity} (Line) Start: {round_time_to_minute(activity.start_time):%Y-%m-%d %H:%M} Duration: {activity.duration_minutes:.1f} min </description> <styleUrl>#lineOpStyle</styleUrl> <LineString> <coordinates> {activity.entry_lon},{activity.entry_lat},0 {activity.exit_lon},{activity.exit_lat},0 </coordinates> </LineString> </Placemark> """ elif activity.kind == "area": kml_content += f""" <Placemark> <name>{activity.label}</name> <description> Activity: {activity.activity} (Area - no corners defined) Start: {round_time_to_minute(activity.start_time):%Y-%m-%d %H:%M} Duration: {activity.duration_minutes:.1f} min </description> <styleUrl>#stationStyle</styleUrl> <Point> <coordinates>{activity.entry_lon},{activity.entry_lat},0</coordinates> </Point> </Placemark> """ else: style_id = ( "mooringStyle" if activity.kind == "mooring" else "stationStyle" ) kml_content += f""" <Placemark> <name>{activity.label}</name> <description> Activity: {activity.activity} Start: {round_time_to_minute(activity.start_time):%Y-%m-%d %H:%M} Duration: {activity.duration_minutes:.1f} min </description> <styleUrl>#{style_id}</styleUrl> <Point> <coordinates>{activity.entry_lon},{activity.entry_lat},0</coordinates> </Point> </Placemark> """ kml_content += """ </Document> </kml> """ # Write to file output_file.parent.mkdir(parents=True, exist_ok=True) with Path(output_file).open("w", encoding="utf-8") as f: f.write(kml_content) return output_file
[docs] def generate_kml_catalog(config: CruiseConfig, output_file: Path) -> Path: """ Generate KML file from YAML configuration catalog entities. Creates a KML file containing all entities defined in the cruise configuration (stations, moorings, transits, ports, areas) without timeline duplication. Each location appears once regardless of how many times it's visited. Parameters ---------- config : CruiseConfig The cruise configuration object containing all catalog entities output_file : Path Path to output KML file Returns ------- Path Path to generated KML file """ # Define KML styles for different entity types kml_content = f"""<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name>{config.cruise_name} - Catalog</name> <description>Cruise configuration catalog including all stations, moorings, transits, ports, and areas</description> <!-- Styles for different entity types --> <Style id="stationStyle"> <IconStyle> <color>ff0000ff</color> <scale>1.2</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href> </Icon> </IconStyle> </Style> <Style id="mooringStyle"> <IconStyle> <color>ff00ff00</color> <scale>1.2</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/shapes/placemark_square.png</href> </Icon> </IconStyle> </Style> <Style id="portStyle"> <IconStyle> <color>ff0080ff</color> <scale>1.5</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/shapes/marina.png</href> </Icon> </IconStyle> </Style> <Style id="transitStyle"> <LineStyle> <color>800066FF</color> <width>3</width> </LineStyle> </Style> <Style id="areaStyle"> <LineStyle> <color>ff00ffff</color> <width>2</width> </LineStyle> <PolyStyle> <color>4000ffff</color> <fill>1</fill> </PolyStyle> </Style> <!-- Ports -->""" # Add ports from cruise configuration if hasattr(config, "departure_port") and config.departure_port: port = config.departure_port kml_content += f""" <Placemark> <name>Departure: {port.name}</name> <description> Port: {port.name} Type: Departure Port Location: {port.latitude:.6f}°N, {port.longitude:.6f}°W Timezone: {getattr(port, "timezone", "N/A")} </description> <styleUrl>#portStyle</styleUrl> <Point> <coordinates>{port.longitude},{port.latitude},0</coordinates> </Point> </Placemark>""" if hasattr(config, "arrival_port") and config.arrival_port: port = config.arrival_port kml_content += f""" <Placemark> <name>Arrival: {port.name}</name> <description> Port: {port.name} Type: Arrival Port Location: {port.latitude:.6f}°N, {port.longitude:.6f}°W Timezone: {getattr(port, "timezone", "N/A")} </description> <styleUrl>#portStyle</styleUrl> <Point> <coordinates>{port.longitude},{port.latitude},0</coordinates> </Point> </Placemark>""" # Add ports from configuration catalog if hasattr(config, "ports") and config.ports: for port in config.ports: timezone_str = getattr(port, "timezone", "N/A") kml_content += f""" <Placemark> <name>{port.name}</name> <description> Port: {port.name} Type: Catalog Port Location: {port.latitude:.6f}°N, {port.longitude:.6f}°W Timezone: {timezone_str} </description> <styleUrl>#portStyle</styleUrl> <Point> <coordinates>{port.longitude},{port.latitude},0</coordinates> </Point> </Placemark>""" kml_content += """ <!-- Stations -->""" # Add stations from configuration if hasattr(config, "points") and config.points: for station in config.points: # Convert enum values to strings operation_type = getattr(station, "operation_type", "station") if hasattr(operation_type, "value"): operation_type = operation_type.value if operation_type is None: operation_type = "station" action = getattr(station, "action", "profile") if hasattr(action, "value"): action = action.value if action is None: action = "profile" # Use water_depth field (added by enrichment) with fallback depth = getattr(station, "water_depth_m", None) or getattr( station, "depth", None ) depth_str = f"{depth:.0f}" if depth is not None else "N/A" kml_content += f""" <Placemark> <name>{station.name}</name> <description> Type: {operation_type.upper()} Action: {action.upper()} Location: {station.latitude:.6f}°N, {station.longitude:.6f}°W Depth: {depth_str} m </description> <styleUrl>#stationStyle</styleUrl> <Point> <coordinates>{station.longitude},{station.latitude},0</coordinates> </Point> </Placemark>""" kml_content += """ <!-- Moorings -->""" # Add moorings from configuration if hasattr(config, "moorings") and config.moorings: for mooring in config.moorings: # Convert enum values to strings operation_type = getattr(mooring, "operation_type", "mooring") if hasattr(operation_type, "value"): operation_type = operation_type.value if operation_type is None: operation_type = "mooring" action = getattr(mooring, "action", "deployment") if hasattr(action, "value"): action = action.value if action is None: action = "deployment" # Use water_depth field (added by enrichment) with fallback depth = getattr(mooring, "water_depth_m", None) or getattr( mooring, "depth", None ) depth_str = f"{depth:.0f}" if depth is not None else "N/A" kml_content += f""" <Placemark> <name>{mooring.name}</name> <description> Type: {operation_type.upper()} Action: {action.upper()} Location: {mooring.latitude:.6f}°N, {mooring.longitude:.6f}°W Depth: {depth_str} m </description> <styleUrl>#mooringStyle</styleUrl> <Point> <coordinates>{mooring.longitude},{mooring.latitude},0</coordinates> </Point> </Placemark>""" kml_content += """ <!-- Transits -->""" # Add lines from configuration if hasattr(config, "lines") and config.lines: for line in config.lines: # Extract start and end coordinates from route waypoints if line.route and len(line.route) >= 2: start_lat = line.route[0].latitude start_lon = line.route[0].longitude end_lat = line.route[-1].latitude end_lon = line.route[-1].longitude # Calculate route distance if available route_distance = getattr(line, "distance", None) if route_distance is None or route_distance == "calculated": # Calculate distance if not provided from cruiseplan.utils.coordinates import distance_nm route_distance = distance_nm( (start_lat, start_lon), (end_lat, end_lon) ) route_distance = f"{route_distance:.1f}" # Get the actual operation type from the config operation_type = getattr(line, "operation_type", "line") if hasattr(operation_type, "value"): operation_type = operation_type.value kml_content += f""" <Placemark> <name>{line.name}</name> <description> Type: {operation_type} Start: {start_lat:.6f}°N, {start_lon:.6f}°W End: {end_lat:.6f}°N, {end_lon:.6f}°W Distance: {route_distance} nm </description> <styleUrl>#transitStyle</styleUrl> <LineString> <coordinates> {start_lon},{start_lat},0 {end_lon},{end_lat},0 </coordinates> </LineString> </Placemark>""" kml_content += """ <!-- Areas -->""" # Add areas from configuration if hasattr(config, "areas") and config.areas: for area in config.areas: if hasattr(area, "corners") and area.corners: # Create coordinate list for polygon coord_list = [ f"{corner.longitude},{corner.latitude},0" for corner in area.corners ] # Close the polygon if area.corners: coord_list.append( f"{area.corners[0].longitude},{area.corners[0].latitude},0" ) coordinates_str = " ".join(coord_list) # Convert enum to string for display operation_type = getattr(area, "operation_type", "survey") if hasattr(operation_type, "value"): operation_type = operation_type.value kml_content += f""" <Placemark> <name>{area.name}</name> <description> Type: Area Corners: {len(area.corners)} Operation: {operation_type} </description> <styleUrl>#areaStyle</styleUrl> <Polygon> <outerBoundaryIs> <LinearRing> <coordinates>{coordinates_str}</coordinates> </LinearRing> </outerBoundaryIs> </Polygon> </Placemark>""" # Close KML document kml_content += """ </Document> </kml> """ # Write to file output_file.parent.mkdir(parents=True, exist_ok=True) with Path(output_file).open("w", encoding="utf-8") as f: f.write(kml_content) return output_file
[docs] def generate_kml_schedule( config: CruiseConfig, timeline: list[ActivityRecord], output_file: Path ) -> Path: """ Generate a KML schedule from the scheduler timeline. Parameters ---------- config : CruiseConfig The cruise configuration object timeline : List[ActivityRecord] Timeline generated by the scheduler output_file : Path Path to output KML file Returns ------- Path Path to generated KML file """ generator = KMLGenerator() return generator.generate_schedule_kml(config, timeline, output_file)