python - 沿坐标列表给定的路径矢量化 haversine 距离计算

标签 python numpy vectorization distance haversine

我有一个坐标列表,可以使用 haversine distance 计算所有点之间的距离矩阵公制。

坐标来自 numpy.array 形状 (n, 2)(latitude, longitude) 对:

[[  16.34576887 -107.90942116]
 [  12.49474931 -107.76030036]
 [  27.79461514 -107.98607881]
 ...
 [  12.90258404 -107.96786569]
 [  -6.29109889 -107.88681145]
 [  -2.68531605 -107.72796034]]

我还可以像这样提取沿坐标序列隐含的路径的距离:

coordinates = np.deg2rad(coordinates)
lat, lng = coordinates[:, 0], coordinates[:, 1]
diff_lat = lat[:, None] - lat
diff_lng = lng[:, None] - lng

d = np.sin(diff_lat / 2) ** 2 + np.cos(lat[:, None]) * np.cos(lat) * np.sin(diff_lng / 2) ** 2
dist_matrix = 2 * 6371 * np.arcsin(np.sqrt(d))
np.diagonal(dist_matrix, offset=1)

[   428.51472359   1701.42935402   1849.52714339  12707.47743385
  13723.9087041    4521.8250695    2134.258953      401.33113696
   4571.69119707     73.82631307   6078.48898641   9870.17140175
                               ...
   2109.57319898  12959.56540448  16680.64546196   3050.96912506
   3419.95053226   4209.71641445   9467.85523888   2805.65191129
   4120.18701177]

我只想计算距离向量而不是整个矩阵,然后选择相关的对角线。

最佳答案

这是一种无需创建大矩阵即可对该计算进行矢量化的方法。 coslat 是纬度的余弦数组,coslat[:-1]*coslat[1:] 是表达式 cos(ϕ 1)cos(ϕ2)在Haversine公式中。

from __future__ import division, print_function

import numpy as np


def hav(theta):
    return np.sin(theta/2)**2


coords = [[  16.34576887, -107.90942116],
          [  12.49474931, -107.76030036],
          [  27.79461514, -107.98607881],
          [  12.90258404, -107.96786569],
          [  -6.29109889, -107.88681145],
          [  -2.68531605, -107.72796034]]
r = 6371

coordinates = np.deg2rad(coords)
lat = coordinates[:, 0]
lng = coordinates[:, 1]
coslat = np.cos(lat)
t = hav(np.diff(lat)) + coslat[:-1]*coslat[1:]*hav(np.diff(lng))
d = 2*r*np.arcsin(np.sqrt(t))

print(d)

输出:

[  428.51472353  1701.42935412  1655.91938575  2134.25895299   401.33113696]

关于python - 沿坐标列表给定的路径矢量化 haversine 距离计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552284/

相关文章:

python - 制作聊天客户端窗口

python - 有没有办法用 numpy 有效地反转矩阵数组?

performance - 为什么reshape这么快? (剧透 : Copy-on-Write)

sql - Postgres 中的向量(数组)加法

python - 如何用BeautifulSoup获取Python中的具体内容?

python - 如何使用 GPT-3 API 提取所需信息

python - 如何使用 pcolormesh 在二维网格中绘制特定正方形的轮廓?

python - Numpy 切片函数 : Dynamically create slice indices np. r_[a :b, c :d, ...] 来自形状为 (X, 2) 的数组,用于在数组中进行选择

python - 在类级别跟踪 Python 2.7.x 对象属性以快速构造 numpy 数组

python - 洗牌数组中每一行的非零元素 - Python/NumPy