""" Vectorized NumPy utilities for geographic distance calculations. """ import numpy as np import logging logger = logging.getLogger(__name__) def calculate_haversine_matrix_vectorized(lats: np.ndarray, lons: np.ndarray) -> np.ndarray: """ Calculate an N x N distance matrix using the Haversine formula. Fully vectorized using NumPy for O(N^2) speed improvement over Python loops. """ # Earth's radius in kilometers R = 6371.0 # Convert degrees to radians lats_rad = np.radians(lats) lons_rad = np.radians(lons) # Create meshgrids for pairwise differences # lats.reshape(-1, 1) creates a column vector # lats.reshape(1, -1) creates a row vector # Subtracting them creates an N x N matrix of differences dlat = lats_rad.reshape(-1, 1) - lats_rad.reshape(1, -1) dlon = lons_rad.reshape(-1, 1) - lons_rad.reshape(1, -1) # Haversine formula a = np.sin(dlat / 2)**2 + np.cos(lats_rad.reshape(-1, 1)) * np.cos(lats_rad.reshape(1, -1)) * np.sin(dlon / 2)**2 c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) return R * c