Problem: Geospatial Navigation Calculation Functions

The problem requires creating Python functions for accurate geographic calculations—degree-to-radian conversion (with caching and precision), Haversine distance (WGS84 ellipsoid-corrected), initial bearing (Vincenty's formula), and cross-track error—incorporating input validation, numerical enhancements, and scalar/iterable support to enable precise navigation or geographic applications.

Background: ### Industry Background & Mathematical Foundations for Geographic Navigation Calculations
This suite of functions addresses core spatial computation needs in **Geographic Information Systems (GIS)**, precision navigation, and logistics industries, where accurate positional calculations are critical for applications like GPS guidance, aviation, marine travel, autonomous vehicles, and fleet management. Below is the domain-specific knowledge required to reproduce the code:

---

#### 1. Angle Conversion (`to_radians`)
- **Industry Context**: Geographic data uses degrees for angles, but mathematical spatial calculations require radians. Normalization to the `[0, 360°)` range ensures consistency for inputs like negative angles or values exceeding full circles. Caching optimizes repeated calculations in large datasets (e.g., batch processing of GPS points).
- **Mathematical & Implementation Details**:
  - **Normalization**: Uses modular arithmetic (`degrees % 360.0`) to reduce angles to the standard range.
  - **High-Precision Conversion**: Implements an extended-precision value of `π/180` (0.017453292519943295769...) instead of relying on `math.pi/180` to minimize conversion errors.
  - **Numerical Accuracy**: Adds a tiny correction term (`1e-15 * reduced`) to offset floating-point precision loss.
  - **Input Handling**: Supports scalars (int, float, complex) and iterables, with strict type validation to raise errors for invalid inputs (strings, non-numeric non-iterables).

#### 2. Ellipsoidal Distance Calculation (`calculate_haversine_distance`)
- **Industry Context**: The Haversine formula estimates great-circle distances on a spherical Earth, but real-world use requires adjustments for Earth’s ellipsoidal shape. The WGS84 ellipsoid is the global standard for GPS and navigation, providing more accurate distance measurements than spherical models.
- **Mathematical & Implementation Details**:
  - **WGS84 Parameters**: Uses semi-major axis (`6378137.0 m`), flattening (`1/298.257223563`), and semi-minor axis for ellipsoidal corrections.
  - **Double Kahan Summation**: A compensated summation technique to prevent floating-point accumulation errors, critical for large-scale batch distance calculations.
  - **Coordinate Validation**: Enforces valid latitude (`-90° to 90°`) and longitude (`-180° to 180°`) ranges, plus positive radius values.
  - **Output Flexibility**: Returns scalar distances for single-point inputs and arrays for batch data, preserving input type where possible.

#### 3. Initial Bearing Calculation (`calculate_bearing`)
- **Industry Context**: Initial bearing (forward azimuth) defines the direction from one point to another, essential for route planning in aviation, marine travel, and autonomous systems. Vincenty’s iterative formula provides superior accuracy over long distances compared to simplified bearing calculations.
- **Mathematical & Implementation Details**:
  - **Vincenty’s Iterative Algorithm**: Solves for ellipsoidal geodesics to compute bearing, with up to 100 iterations to ensure convergence (stopping when iteration error < 1e-12).
  - **Edge Case Handling**: Resolves coincident points, same-latitude (east/west direction), and same-longitude (north/south direction) scenarios with simplified logic before applying the full iterative method.
  - **Bearing Normalization**: Converts radians to degrees and uses modular arithmetic to return bearings in the `0° to 360°` range (clockwise from north).

#### 4. Cross-Track Error Calculation (`calculate_cross_track_error`)
- **Industry Context**: Cross-track error measures how far a moving object (e.g., vehicle, drone) deviates from its planned route, enabling real-time guidance and path correction in navigation systems.
- **Mathematical & Implementation Details**:
  - **Relative Bearing**: Computes the angular difference between the current direction and the planned route, normalized to `[-π, π]` radians.
  - **Taylor Series Approximations**: For small angles (≤1e-6 radians), uses truncated Taylor series expansions for `sin(x)` and `arcsin(x)` to avoid numerical inaccuracies in trigonometric function evaluations.
  - **Ellipsoidal Corrections**: Uses WGS84 radius and supports optional altitude adjustments for 3D navigation use cases.
  - **Input Validation**: Ensures non-negative distance values (`d_13`) and positive radius inputs, with numpy-based vectorization for efficient batch processing.

---

#### Key Industry Requirements for Reproduction
- **Numerical Precision**: Prioritize extended-precision constants and compensated summation to avoid positional errors that scale with distance.
- **Input Flexibility**: Support both scalar and array inputs to handle single-point and batch data processing.
- **Error Robustness**: Validate all inputs against domain-specific constraints (coordinate ranges, positive values) and raise descriptive errors for invalid data types.
- **Standard Compliance**: Adhere to WGS84 ellipsoid parameters for global consistency with GPS and navigation systems.

Input/Output: The problem accepts inputs for four geographic calculation functions: 1) A numeric scalar or iterable of numerics (degrees) for converting to radians; 2) Geographic coordinates (lat1, lon1, lat2, lon2) as numeric scalars/arrays (latitudes -90 to 90, longitudes -180 to 180) and an optional positive radius for Haversine distance; 3) Geographic coordinates (same constraints) for initial bearing calculation; 4) A non-negative numeric scalar/iterable (d_13), two bearings, and an optional positive radius for cross-track error. All inputs require validation for type, range, and iterability. The problem outputs: Radians (matching input structure) for unit conversion; scalar/array distance (meters) for Haversine; bearing (0–360 degrees) for direction; cross-track error (matching input structure) for navigation. Processing involves unit conversion, precision techniques (caching, Kahan summation, Taylor series), and geographic formulas (Haversine with WGS84 correction, Vincenty's method) to handle edge cases and ensure accuracy.

Required dependencies:
import numpy as np
import math
from typing import Union, Iterable, Any

Sub-steps:
step_number: 1
step_description_prompt: Please write Python code to generate a function named to_radians. This function converts degrees to radians, supporting numeric scalars and iterables of numerics. It uses caching, normalizes angles to [0,360), high-precision pi/180 conversion, adds a tiny correction for numerical accuracy, and raises clear errors for invalid inputs like strings or non-iterable non-numeric types.
function_header: def to_radians(degrees):
test_cases: import math
for deg, expected in [(0.0, 0.0), (180.0, math.pi), (90.0, math.pi / 2)]:
    assert math.isclose(to_radians(deg), expected)

step_number: 2
step_description_prompt: Please write a Python function named calculate_haversine_distance. It validates input latitudes (range -90 to90) and longitudes (-180 to180) of geographic points, plus positive radius. Converts to radians, applies Haversine formula enhanced with WGS84 ellipsoid correction and double Kahan summation for precision, then returns distance as scalar or array based on inputs.
function_header: def calculate_haversine_distance(lat1, lon1, lat2, lon2, radius=6371000):
test_cases: import math
test_haversine = [
    (0, 0, 0, 0, 0.0),                     # 同一点
    (0, 0, 1, 0, 111194.9266),             # 经道上跨越1度纬度
    (0, 0, 0, 90, 10007543.398)            # 赤道上跨越90度经度 (1/4周长)
]
for lat1, lon1, lat2, lon2, expected in test_haversine:
    res = calculate_haversine_distance(lat1, lon1, lat2, lon2)
    assert math.isclose(res, expected, rel_tol=1e-7)

step_number: 3
step_description_prompt: Please write a Python function named calculate_bearing that computes initial bearing between two WGS84 points. It first validates coordinates, handles coincident/same lat/lon cases simply, then uses iterative Vincenty's formula for general cases, returning bearing in degrees 0-360 clockwise from north.
function_header: def calculate_bearing(lat1, lon1, lat2, lon2):
test_cases: import math
test_bearing = [
    (0, 0, 1, 0, 0.0),      # 向北 (0度)
    (0, 0, 0, 1, 90.0),     # 向东 (90度)
    (0, 0, -1, 0, 180.0)    # 向南 (180度)
]
for lat1, lon1, lat2, lon2, expected in test_bearing:
    res = calculate_bearing(lat1, lon1, lat2, lon2)
    assert math.isclose(res, expected, abs_tol=1e-7)

step_number: 4
step_description_prompt: Write a Python function named calculate_cross_track_error(d_13, bearing_13, bearing_12, radius=6371000). It converts inputs to float64, validates d_13 is non-negative and radius positive, modulates bearings to 360°, converts to radians, computes relative bearing, uses Taylor series for small angles in sin(d_13/radius), applies arcsin approximation for small values, and returns the cross-track error result.
function_header: def calculate_cross_track_error(d_13, bearing_13, bearing_12, radius=6371000):
test_cases: import math
test_xtrack = [
    (1000, 90, 90, 0.0),            # 在航线上 (无偏离)
    (1000, 90, 0, 1000.0),          # 计划向北，实际向东行进1km (小范围内近似垂直偏离)
    (10000, 45, 0, 7071.06)         # 计划向北，实际向东北行进10km (10000 * sin(45))
]
for d13, b13, b12, expected in test_xtrack:
    res = calculate_cross_track_error(d13, b13, b12)
    # 大圆几何下小距离近似欧几里得几何，大距离会有微差
    assert math.isclose(res, expected, rel_tol=1e-3)

General solution:

General tests: