[SciPy-User] Notification when array is modified

Christian K. ckkart at hoc.net
Mon Aug 20 20:44:43 EDT 2012


For that purpose I use a subclass of ndarray. See the attached sample.
Hope it helps.

Christian

Am 20.08.12 04:00, schrieb John Jumper:
> I am looking for a method so that I can be notified when the contents
> of a numpy array change.
> 
> A simplified class that illustrates the desired functionality is below.
> 
> class ComputeDerived(object):
>     def __init__(self, n):
>         self.A = np.zeros(n)
>         self.B = np.zeros(n)
>         self.change_mask = np.ones(n, dtype=np.bool)
>         self._Derived = expensive(self.A,self.B)
> 
>     def set_A(self, i, x):
>         self.A[i] = x
>         self.change_mask[i] = True
> 
>     def set_B(self, i, x):
>         self.B[i] = x
>         self.change_mask[i] = True
> 
>     def Derived(self):
>         if np.any(self.change_mask):
>             for i in np.nonzero(self.change_mask)[0]:
>                 self._Derived[i] = expensive(A[i],B[i])
>             self.change_mask[:] = False
>         return self._Derived
> 
> This class works, but I lack the power of numpy's indexing syntax to
> change A or B.  I would like to be able to write
> compute_derived.A[(3,5,6)] = 1 and then be notified that A has
> changed.  Otherwise, if I want to use a numpy interface for A and B, I
> would have to store old copies of A and B and traverse these copies
> every time Derived is called.
> 
> Is there any interface in numpy so that I could expose A and B
> directly as writeable numpy arrays but be notified when they are
> modified?  Alternatively, if I subclass ndarray, is there some
> exhaustive list of methods that can change the underlying data (I
> would be worried about view objects here)?
> 
> In case it makes a difference, my actual use case is a C++ class
> wrapped using Boost::Python.  The numpy arrays A and B would point at
> aligned float* members of my C++ class.
> 
> Thank you,
> John Jumper
> 

-------------- next part --------------
A non-text attachment was scrubbed...
Name: callback_array.py
Type: text/x-python-script
Size: 1357 bytes
Desc: not available
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20120820/db989794/attachment.bin>


More information about the SciPy-User mailing list