python - 使用 numpy 计算多条轨迹的成对距离
问题描述
给定任意数量的 3D 轨迹,每个轨迹有 N 个点(时间步长),我想计算给定时间步长的每个点之间的距离。
假设我们将查看时间步 3,并有四个轨迹 t_0 ... t_3。轨迹 0 的第三个时间步长的点为 t_0(3)。我想计算距离如下:
d_0 = norm(t_0(3) - t_1(3))
d_1 = norm(t_1(3) - t_2(3))
d_2 = norm(t_2(3) - t_3(3))
d_3 = norm(t_3(3) - t_0(3))
如您所见,其中有一种循环行为(最后一个计算到第一个的距离),但这并不是绝对必要的。
我知道如何编写一些 for 循环并计算我想要的。我正在寻找的是一个概念,或者可能是 numpy(或 np 函数的组合)中的一个实现,它可以仅使用右轴和其他 numpy 魔法来执行此逻辑。
这里有一些示例轨迹
import numpy as np
TIMESTEP_COUNT = 70
origin = np.array([0, 0, 0])
run1_direction = np.array([1, 0, 0]) / np.linalg.norm([1, 0 ,0])
run2_direction = np.array([0, 1, 0]) / np.linalg.norm([0, 1, 0])
run3_direction = np.array([0, 0, 1]) / np.linalg.norm([0, 0, 1])
run4_direction = np.array([1, 1, 0]) / np.linalg.norm([1, 1, 0])
run1_trajectory = [origin]
run2_trajectory = [origin]
run3_trajectory = [origin]
run4_trajectory = [origin]
for t in range(TIMESTEP_COUNT - 1):
run1_trajectory.append(run1_trajectory[-1] + run1_direction)
run2_trajectory.append(run2_trajectory[-1] + run2_direction)
run3_trajectory.append(run3_trajectory[-1] + run3_direction)
run4_trajectory.append(run4_trajectory[-1] + run4_direction)
run1_trajectory = np.array(run1_trajectory)
run2_trajectory = np.array(run2_trajectory)
run3_trajectory = np.array(run3_trajectory)
run4_trajectory = np.array(run4_trajectory)
先感谢您!!
编辑:我的问题与下面建议的答案不同,因为我不想计算全距离矩阵。我的算法应该只适用于连续运行之间的距离。
解决方案
我认为您可以将它们垂直堆叠以获得 shape 数组4 x n_timesteps
,然后用于np.roll
在每个时间步中进行差异,即:
r = np.vstack([t0,t1,t2,t3])
r - np.roll(r,shift=-1,axis=0)
数字示例:
t0,t1,t2,t3 = np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5)
r = np.vstack([t0,t1,t2,t3])
r
array([[1, 7, 7, 6, 2],
[9, 1, 2, 3, 6],
[1, 1, 6, 8, 1],
[2, 9, 5, 9, 3]])
r - np.roll(r,shift=-1,axis=0)
array([[-8, 6, 5, 3, -4],
[ 8, 0, -4, -5, 5],
[-1, -8, 1, -1, -2],
[ 1, 2, -2, 3, 1]])
推荐阅读
- node.js - 找不到 vrrp_instance VI_1 的接口 eth0
- html - 多选器批量重命名加号
- swift - Swift CSVImporter 无法读取 CSV 文件
- python - 如何将带有元数据的 Dendropy 对象传递给 python3 中的 ete3?
- javascript - 在nodejs中将字符串转换为日期时间时,时刻js中的意外行为
- sql - 多行选择一行数据
- android - 任何用户都可以访问包文件的内部 java 文件吗?
- java - Spring自定义转换器异常抛出
- google-chrome - Chrome 扩展程序:出现错误:无法识别的清单键“start_url”
- php - 深层链接无法正常工作