python scipy interpolate.BSpline用法及代码示例
英文原版链接:https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.interpolate.BSpline.html
本文转自:https://vimsky.com/examples/usage/python-scipy.interpolate.BSpline.html
用法:
class scipy.interpolate.BSpline(t, c, k, extrapolate=True, axis=0)
以B-spline为基础的单变量样条。
其中是度k和结t的B-spline个基函数。
参数:
t:ndarray, shape (n+k+1,)
结
c:ndarray, shape (>=n, …)
样条系数
k:int
B-spline订单
extrapolate:bool 或 ‘periodic’, 可选参数
是否推断超出基本区间,t[k] … t[n],或返回nans。如果为True,则推断在基本间隔上处于活动状态的b-spline函数的第一个和最后一个多项式。如果为‘periodic’,则使用定期外推。默认值为True。
axis:int, 可选参数
插补轴。默认值为零。
注意:
B-spline个基本元素通过
实施细节
至少k+1k阶样条需要系数,因此n >= k+1。附加系数,c[j]与j > n,将被忽略。
度为k的B-spline个基本元素在基本间隔上形成一个单位分区,t[k] <= x <= t[n]。
参考文献:
Ra9694dbe14e1-1
Tom Lyche和Knut Morken,样条方法,http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
Ra9694dbe14e1-2
Carl de Boor,《样条曲线实用指南》,Springer,2001年。
例子:
将B-splines的递归定义转换为Python代码,我们有:
def B(x, k, i, t):
… if k == 0:
… return 1.0 if t[i] <= x < t[i+1] else 0.0
… if t[i+k] == t[i]:
… c1 = 0.0
… else:
… c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
… if t[i+k+1] == t[i+1]:
… c2 = 0.0
… else:
… c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
… return c1 + c2def bspline(x, t, c, k):
… n = len(t) - k - 1
… assert (n >= k+1) and (len© >= n)
… return sum(c[i] * B(x, k, i, t) for i in range(n))
请注意,这是评估B-splines的效率低下的方法(如果很简单),该样条类以等效但更有效的方式来进行评估。
这里我们在基本区间上构造一个二次样条函数2 <= x <= 4并与评估样条曲线的幼稚方式进行比较:
from scipy.interpolate import BSpline
k = 2
t = [0, 1, 2, 3, 4, 5, 6]
c = [-1, 2, 0, -1]
spl = BSpline(t, c, k)
spl(2.5)
array(1.375)bspline(2.5, t, c, k)
1.375
注意,超出基本间隔的结果有所不同。这是因为BSpline推断在基本间隔上活动的b-spline函数的第一个和最后一个多项式。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xx = np.linspace(1.5, 4.5, 50)
ax.plot(xx, [bspline(x, t, c ,k) for x in xx], ‘r-’, lw=3, label=‘naive’)
ax.plot(xx, spl(xx), ‘b-’, lw=4, alpha=0.7, label=‘BSpline’)
ax.grid(True)
ax.legend(loc=‘best’)
plt.show()
…/_images/scipy-interpolate-BSpline-1.png
属性
t:ndarray
结矢量图
c:ndarray
样条系数
k:int
样条度
extrapolate:bool
如果为True,则推断在基本间隔上处于活动状态的b-spline函数的第一个和最后一个多项式。
axis:int
插补轴。
tcktuple
相当于(self.t, self.c, self.k)(只读)。
方法:
call(self, x[, nu, extrapolate])
评估样条函数。
basis_element(t[, extrapolate])
返回一个B-spline基本元素B(x | t[0], …, t[k+1])。
derivative(self[, nu])
返回代表导数的b-spline。
antiderivative(self[, nu])
返回代表反导数的b-spline。
integrate(self, a, b[, extrapolate])
计算样条的定积分。
construct_fast(t, c, k[, extrapolate, axis])
构造样条而不进行检查。
源码:
scipy.interpolate.BSpline的API实现见:[源代码]
注:本文由纯净天空筛选整理自 scipy.interpolate.BSpline。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。