2013-10-16 68 views
3

numpy array data has .... data。 Numpy數組z有距離。數據和z具有相同的形狀,z的每個點是測量相應數據點的距離。使問題複雜化的是,用戶將提供具有3,4或5維度的數據/ z陣列。1D numpy/scipy插值不完全是1D

我想插入數據到一維numpy數組dists中的一組距離。由於數據結構的原因,插值軸始終是兩個軸,即如果數組有三維,則插值軸爲0;如果數組有4維,則插值軸爲1等。由於AFAICT,所有numpy/scipy插值例程都希望在1D數組中給出原始距離,插值數據和z在dists上看起來有點複雜。這是我有:

def dist_interp(data, z, dists): 
    # construct array to hold interpolation results 
    num_dims = len(data.shape) 
    interp_axis = num_dims-3 
    interp_shape = list(data.shape) 
    interp_shape[interp_axis] = dists.shape[0] 
    interp_res = np.zeros(shape=interp_shape) 
    # depending on usage, data could have between 3 and five dimensions. 
    # add dims to generalize. I hate doing it this way. Must be 
    # some other way. 
    for n in range(num_dims, 5) : 
     data = np.expand_dims(data, axis=0) 
     z = np.expand_dims(z, axis=0) 
     interp_res = np.expand_dims(interp_res, axis=0) 
    for m in range(data.shape[0]): 
     for l in range(data.shape[1]): 
      for j in range(data.shape[3]): 
       for i in range(data.shape[4]): 
        interp_res[m,l,:,j,i]=(
            np.interp(dists,z[m,l,:,j,i], 
              data[m,l,:,j,i])) 
    # now remove extra "wrapping" dimensions 
    for n in range(0,5-num_dims): 
     interp_res = interp_res[0] 
    return(interp_res) 

我認爲這會工作,但添加和刪除額外的「包裹」虛擬維度是極其不雅併爲代碼,是不是在所有緊湊。任何更好的想法?謝謝。

+0

你可以添加一些示例輸入數據到你的文章?如果您願意,您可以生成與輸入相同形狀的隨機數據。 – YXD

回答

4

根據經驗,對於這種情況一般規則:

  1. 將您想要做的形狀元組
  2. 重塑年底的東西軸所產生的陣列是2D
  3. 從這個二維一個
  4. 撤消創建新的數組新陣列

對於你的情況在步驟2和1,它可能看起來索姆就像:

# Create some random test data 
axis = -2 
shape = np.random.randint(10, size=(5,)) 
data = np.random.rand(*shape) 
data = np.sort(data, axis=axis) 
z = np.random.rand(*shape) 
dists = np.linspace(0,1, num=100) 

data = np.rollaxis(data, axis, data.ndim) 
new_shape = data.shape 
data = data.reshape(-1, data.shape[-1]) 
z = np.rollaxis(z, axis, z.ndim) 
z = z.reshape(-1, z.shape[-1]) 

out = np.empty(z.shape[:1]+dists.shape) 
for o, x, f in zip(out, data, z): 
    o[:] = np.interp(dists, x, f) 

out = out.reshape(new_shape[:-1]+dists.shape) 
out = np.rollaxis(out, -1, axis) 
+0

謝謝。看起來正是我需要的! –