2016-10-24 39 views
0

我有一个简单Point类如下插值类对象

class Point(object): 
    def __init__(self, x=0.0, y=0.0, z=0.0): 
     self.x = x 
     self.y = y 
     self.z = z 

我想用scipy.interpolate.interp1d作为时间的函数,例如内插这些点

x,y,z = f(t) 

然而,当我尝试以下小例子

import numpy as np 
from scipy.interpolate import interp1d 

times = np.array([0.0, 0.1, 0.2]) 
points = np.array([Point(0.0, 0.0, 0.0), 
        Point(1.0, 1.0, 1.0), 
        Point(2.0, 2.0, 2.0)]) 

function = interp1d(times, points) 

new_point = function(0.05) 

我收到以下错误

Traceback (most recent call last): 
    File "D:/example.py", line 31, in <module> 
    function = interp1d(times, points) 
    File "C:\long_path\scipy\interpolate\interpolate.py", line 439, in __init__ 
    y = y.astype(np.float_) 
TypeError: float() argument must be a string or a number, not 'Point' 

我也试着重载算术运算符的Point类(如__add____sub__,__truediv__)虽然这似乎没有帮助。

有没有一种方法可以在我的课堂上使用scipy.interpolate.interp1d

+0

为什么不把所有的点放在'Nx3' float64数组中? – Kh40tiK

回答

3

因为python对象是内部的dicts而不是连续的缓冲区,所以当自定义类型对象位于numpy.ndarray的内部时,numpy/scipy将无法使用某些方法。

一个简单的解决办法是把所有Point内一个单一的ndarray带内置型:

from __future__ import print_function 
import numpy as np 
import scipy.interpolate as sp_interp 
points = np.array([[0.0, 0.0, 0.0], 
        [1.0, 1.0, 1.0], 
        [2.0, 2.0, 2.0]], dtype='float64') 
times = np.linspace(0.,.2, len(points)) 

fn_interp = sp_interp.interp1d(times, points, axis=0) 
print(fn_interp(0.05)) 

如果你致力于基于类的方法,你可能想定制定义dtype或使ndarray子,如答案here