Python 中的跳跃角度计算

问题描述 投票:0回答:1

我无法理解如何在 Python 中精确计算我所说的“跳跃角度”。所以基本上,我有一个由位置(x 和 y,所以在 2D 中)组成的几个轨迹(转录因子)的地图跟踪,并且我有兴趣找到轨迹的两个连续片段之间的跳跃角度(参见以下内容)数字)。编辑:我改变了图像,所以我真正想要的表示。
jump angles

我尝试了很多方法,包括使用atan2,但这会导致错误的角度表示,至少是我这样做的方式。因此,我尝试手动计算它,但这也没有给出任何好的表示。您会在下面找到我的计算方法

def calculate_jump_angles(x_coords, y_coords):
    """Calculate the jump angles between consecutive segments in a track."""
    angles = []
    for i in range(len(x_coords) - 2):
        vec1 = (x_coords[i+1] - x_coords[i], y_coords[i+1] - y_coords[i])
        vec2 = (x_coords[i+2] - x_coords[i+1], y_coords[i+2] - y_coords[i+1])
        dot_product = vec1[0] * vec2[0] + vec1[1] * vec2[1]
        mag1 = np.sqrt(vec1[0]**2 + vec1[1]**2)
        mag2 = np.sqrt(vec2[0]**2 + vec2[1]**2)
        cos_theta = dot_product / (mag1 * mag2)
        
        cos_theta = np.clip(cos_theta, -1.0, 1.0)
        angle = np.arccos(cos_theta)
        cross_product = vec1[0] * vec2[1] - vec1[1] * vec2[0]
        angle = angle if cross_product >= 0 else -angle
        angles.append(angle)
    return angles

其中

x_coords
y_coords
分别是一个轨道的 x 和 y 坐标。

python coordinates angle
1个回答
0
投票

如果您只想要 0 到 180 度之间的角度,那么您的图表给出以下内容。

import numpy as np

def calculate_jump_angles(x_coords, y_coords):
    angles = []
    dx = x_coords[1:] - x_coords[0:-1]
    dy = y_coords[1:] - y_coords[0:-1]
    firstx = dx[0:-1];   secondx = dx[1:]
    firsty = dy[0:-1];   secondy = dy[1:]
    costheta = ( firstx * secondx + firsty * secondy ) / np.sqrt( ( firstx ** 2 + firsty ** 2 ) * ( secondx ** 2 + secondy ** 2 ) )
    costheta = np.clip( costheta, -1.0, 1.0 )
    angles = np.arccos( costheta )
    return angles

x = np.array( [ 0.0, 2.0, 3.5, 5.5, 4.0, 3.5, 5.5 ] )
y = np.array( [ 0.0, 0.0, 1.0, 0.0,-1.5,-2.7,-2.0 ] )
A = calculate_jump_angles( x, y ) * 180.0 / np.pi
print( "Angles (deg) = ", A )

输出:

Angles (deg) =  [ 33.69006753  60.2551187  108.43494882  22.38013505 131.90991117]
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.