"""Pure geometric helpers - haversine, polyline math, bezier sampling.""" from __future__ import annotations import math from typing import List, Tuple Coord = Tuple[float, float] # (lat, lng) EARTH_RADIUS_KM = 6371.0088 def haversine_km(a: Coord, b: Coord) -> float: """Great-circle distance between two (lat, lng) points in km.""" lat1, lon1 = map(math.radians, a) lat2, lon2 = map(math.radians, b) dlat = lat2 - lat1 dlon = lon2 - lon1 h = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 return 2 * EARTH_RADIUS_KM * math.asin(math.sqrt(h)) def polyline_length_km(coords: List[Coord]) -> float: """Cumulative haversine length of a polyline.""" if len(coords) < 2: return 0.0 return sum(haversine_km(coords[i], coords[i + 1]) for i in range(len(coords) - 1)) def bearing_deg(a: Coord, b: Coord) -> float: """Initial compass bearing from a to b, in degrees [0, 360).""" lat1, lat2 = math.radians(a[0]), math.radians(b[0]) dlon = math.radians(b[1] - a[1]) x = math.sin(dlon) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dlon) return (math.degrees(math.atan2(x, y)) + 360) % 360 def turn_count(coords: List[Coord], threshold_deg: float = 25.0) -> int: """Approximate number of meaningful turns in a polyline.""" if len(coords) < 3: return 0 turns = 0 for i in range(1, len(coords) - 1): b1 = bearing_deg(coords[i - 1], coords[i]) b2 = bearing_deg(coords[i], coords[i + 1]) diff = abs(b2 - b1) if diff > 180: diff = 360 - diff if diff >= threshold_deg: turns += 1 return turns def bbox(coords: List[Coord]) -> Tuple[float, float, float, float]: """Return (min_lat, min_lng, max_lat, max_lng).""" lats = [c[0] for c in coords] lngs = [c[1] for c in coords] return min(lats), min(lngs), max(lats), max(lngs)