[SciPy-User] Notification when array is modified
David Baddeley
david_baddeley@yahoo.com...
Mon Aug 20 04:12:12 CDT 2012
I'd make a proxy class to hold your array and implement the __getitem__ and __setitem__ methods. Something like (your actual implementation might need to be a bit more complex - numpy arrays seem to override __setslice__ as well as __setitem__):
class ChangeTrackingArray(object):
def __init__(self, mask, callback):
self.mask = mask
self.data = np.zeros(mask.shape)
self.callback = callback
def __getitem__(self, keys):
return self.data.__getitem__(keys)
def __setitem__(self, keys, values):
self.data.__setitem__(keys, values)
self.mask.__setitem__(keys, 1)
self.callback()
________________________________
From: John Jumper <jumper@uchicago.edu>
To: scipy-user@scipy.org
Sent: Monday, 20 August 2012 7:00 PM
Subject: [SciPy-User] Notification when array is modified
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
_______________________________________________
SciPy-User mailing list
SciPy-User@scipy.org
http://mail.scipy.org/mailman/listinfo/scipy-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120820/ecfbc892/attachment.html
More information about the SciPy-User
mailing list