2017-08-28 56 views
0

我想在NumPy數組中存儲時間間隔(使用它的特定算術)。如果我使用我自己的Interval類,它可以工作,但是我的課很差,我的Python知識有限。我知道pyInterval這是非常完整的。它涵蓋了我的問題。唯一不起作用的是將PyInterval對象存儲在NumPy數組中。爲什麼NumPy將對象轉換爲浮動對象?

class Interval(object): 

    def __init__(self, lower, upper = None): 
     if upper is None: 
      self.upper = self.lower = lower 
     elif lower <= upper: 
      self.lower = lower 
      self.upper = upper 
     else: 
      raise ValueError(f"Lower is bigger than upper! {lower},{upper}") 

    def __repr__(self): 
     return "Interval " + str((self.lower,self.upper)) 

    def __mul__(self,another): 
     values = (self.lower * another.lower, 
         self.upper * another.upper, 
         self.lower * another.upper, 
         self.upper * another.lower) 
     return Interval(min(values), max(values)) 

import numpy as np 
from interval import interval 

i = np.array([Interval(2,3), Interval(-3,6)], dtype=object) # My class 
ix = np.array([interval([2,3]), interval([-3,6])], dtype=object) # pyInterval 

這些結果

In [30]: i 
Out[30]: array([Interval (2, 3), Interval (-3, 6)], dtype=object) 

In [31]: ix 
Out[31]: 
array([[[2.0, 3.0]], 

     [[-3.0, 6.0]]], dtype=object) 

從pyInterval的間隔已經鑄成花車的名單列表。它不會是一個問題,如果他們保持區間算術......

In [33]: i[0] * i[1] 
Out[33]: Interval (-9, 18) 

In [34]: ix[0] * ix[1] 
Out[34]: array([[-6.0, 18.0]], dtype=object) 

Out[33]是希望輸出。使用pyInterval的輸出不正確。顯然,使用原始pyInterval它就像一個魅力

In [35]: interval([2,3]) * interval([-3,6]) 
Out[35]: interval([-9.0, 18.0]) 

Here是pyInterval源代碼。我不明白爲什麼使用這個對象NumPy不能像我期望的那樣工作。

+0

快速的猜測是,它繼承了元組,因而是一個迭代器。 'np.array'嘗試從可迭代元素中構建數組。你可以間接地創建一個像列表或元組這樣的迭代對象數組。 – hpaulj

回答

2

說句公道話,真的很辛苦構造函數來推斷哪種數據應該進入它。它接收類似元組列表的對象,並且處理它。

你可以,但是,幫助你的構造受了一點沒有它猜你的數據的形狀:

a = interval([2,3]) 
b = interval([-3,6]) 
ll = [a,b] 
ix = np.empty((len(ll),), dtype=object) 
ix[:] = [*ll] 
ix[0]*ix[1] #interval([-9.0, 18.0]) 
1

NumPy將每個間隔視爲兩個數字的數組,並且它執行不需要的元素乘法。試試這個:

interval.__mul__(ix[0], ix[1]) 

這是直接調用你想調用的函數。它應該給你你需要的答案,即使它不是很漂亮。爲了把它變成的東西,對整個陣列的作品,你可以這樣做:

itvmul = np.vectorize(interval.__mul__) 

這將允許你這樣做間隔的陣列的elementwise乘法:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.vectorize.html