找到离散数据点的切线向量

时间:2012-11-15 04:10:53

标签: python vector numpy scipy

我有一个在空间中最少有两个点的向量,例如:

A = np.array([-1452.18133319  3285.44737438 -7075.49516676])
B = np.array([-1452.20175668  3285.29632734 -7075.49110863])

我想在曲线的离散点找到矢量的切线,g.g是曲线的起点和终点。我知道如何在Matlab中做到这一点,但我想用Python做。这是Matlab中的代码:

A = [-1452.18133319  3285.44737438 -7075.49516676];
B = [-1452.20175668  3285.29632734 -7075.49110863];
points = [A; B];
distance = [0.; 0.1667];
pp = interp1(distance, points,'pchip','pp');
[breaks,coefs,l,k,d] = unmkpp(pp);
dpp = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
ntangent=zeros(length(distance),3);
for j=1:length(distance)
    ntangent(j,:) = ppval(dpp, distance(j));
end

%The solution would be at beginning and end:
%ntangent =
%   -0.1225   -0.9061    0.0243
%   -0.1225   -0.9061    0.0243    

有什么想法吗?我尝试使用numpy和scipy使用多种方法找到解决方案,例如

tck, u= scipy.interpolate.splprep(data)

但是这些方法似乎都不符合我的要求。

2 个答案:

答案 0 :(得分:5)

der=1赋予splev以获取样条曲线的导数:

from scipy import interpolate
import numpy as np
t=np.linspace(0,1,200)
x=np.cos(5*t)
y=np.sin(7*t)
tck, u = interpolate.splprep([x,y])

ti = np.linspace(0, 1, 200)
dxdt, dydt = interpolate.splev(ti,tck,der=1)

答案 1 :(得分:0)

好吧,我发现解决方案是上面“pv”的一点修改(请注意,splev仅适用于1D向量) 我最初使用“tck,u = scipy.interpolate.splprep(data)”时遇到的一个问题是它需要最少4个点才能工作(Matlab可以使用两个点)。我用了两点。增加数据点后,它可以正常工作。

以下是完整性的解决方案:

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
data = np.array([[-1452.18133319 , 3285.44737438, -7075.49516676],
                 [-1452.20175668 , 3285.29632734, -7075.49110863],
                 [-1452.32645025 , 3284.37412457, -7075.46633213],
                 [-1452.38226151 , 3283.96135828, -7075.45524248]])

distance=np.array([0., 0.15247556, 1.0834, 1.50007])

data = data.T
tck,u = interpolate.splprep(data, u=distance, s=0)
yderv = interpolate.splev(u,tck,der=1)

和切线(如果使用相同的数据,则匹配Matlab结果):

(-0.13394599723751408, -0.99063114953803189, 0.026614957159932656)
(-0.13394598523149195, -0.99063115868512985, 0.026614950816003666)
(-0.13394595055068903, -0.99063117647357712, 0.026614941718878599)
(-0.13394595652952143, -0.9906311632471152, 0.026614954146007865)