2016-10-24 35 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