2014-07-10 3 views
2

numpy 재 배열을 서브 클래스 화하고 그 클래스에서 뷰를 생성 할 수 있습니다. 예 :recarray 서브 클래스 뷰 만들기

_Theta = np.dtype([('v', '<f8'), ('a', '<f8'), ('w', '<f8')]) 

class Theta(np.recarray): 
    ''' Defines a class for the parameters of a DDM model. ''' 

    def __new__(clc, shape=1): 

     return np.recarray.__new__(clc, shape, _Theta) 

인스턴스를 만들면 원하는 결과가 생성됩니다.

In [12]: r = Theta() 

In [13]: r 
Out[13]: 
Theta([(6.91957786449907e-310, 2.9958354e-316, 2.0922526e-316)], 
     dtype=[('v', '<f8'), ('a', '<f8'), ('w', '<f8')]) 

그러나, 나는 다음과 같은 얻을 내 클래스의보기 만들려고하면 :

In [11]: np.zeros(3).view(Theta).a 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-11-b9bdab6cd66c> in <module>() 
----> 1 np.zeros(3).view(Theta).a 

/usr/lib/python2.7/dist-packages/numpy/core/records.pyc in __getattribute__(self, attr) 
    414    res = fielddict[attr][:2] 
    415   except (TypeError, KeyError): 
--> 416    raise AttributeError("record array has no attribute %s" % attr) 
    417   obj = self.getfield(*res) 
    418   # if it has fields return a recarray, otherwise return 

AttributeError: record array has no attribute a 

그것은 내가 속성과이를 해결 할 수 있도록 배열의 뷰를 만들 수를 그 나는 Theta를 정의 했는가? (이 방법은 array_finalize 메서드를 통해 어떻게 든 완료되어야한다고 생각하지만, 방법을 모르겠습니다.)

답변

0

당신은이 같은 구현을 할 수있는 :

import numpy as np 

class Theta(np.recarray): 
    ''' Defines a class for the parameters of a DDM model. 

    ''' 
    def __new__(clc, *args, **kwargs): 
     a = np.atleast_2d(np.array(*args, **kwargs)) 
     dtype = np.dtype([('v', '<f8'), ('a', '<f8'), ('w', '<f8')]) 
     r = np.recarray(shape=a.shape[0], dtype=dtype) 
     r.v = a[:,0] 
     r.a = a[:,1] 
     r.w = a[:,2] 
     return r.view(Theta) 

r = Theta([[1,2,3],[1,2,3]]) 

있도록 :

a = Theta(np.zeros(3)) 

당신이하고 싶었던 일을 할 것입니다 ... 이것은 아마도 같은 추가 검사 필요 :

assert a.shape[1] % 3 == 0 
관련 문제