[SciPy-User] odeint and subclassed ndarrays
Joscha Schmiedt
joscha.schmiedt@googlemail....
Wed Nov 3 07:53:38 CDT 2010
Dear SciPy community,
I have to solve a dynamical system with several differential equations
belonging to different units, which requires a relatively complex drawing of
variables out of a long state vector. Therefore I thought it might be a good
idea to write a subclass of the ndarray according to
http://docs.scipy.org/doc/numpy/user/basics.subclassing.html and bind a
function for this drawing.
When running odeint (see attached example), however, i get an
AttributeError:
AttributeError: 'numpy.ndarray' object has no attribute 'some_method'
indicating that the type of the array passed to the model function is not an
instance of my class anymore.
Am I doing something wrong or is this not possible in general? As a
workaround I wrote my own integrator, but this is a rather slow
alternative.
Looking forward to any enlightening comments I send you all the best,
Joscha
import numpy as np
import pylab as pl
from scipy.integrate import odeint
class StateVector(np.ndarray):
def __new__(cls, inputArray, someAttribute=1):
obj = np.asarray(inputArray).view(cls)
obj.someAttribute = someAttribute
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.someAttribute = getattr(obj, 'someAttribute', 1)
def some_method(self):
print('Hello world!')
def some_model(y, t, p):
y.some_method()
print(y.someAttribute)
return -p['someParameter'] * y
y0 = StateVector(pl.array([5.0]))
time = pl.arange(0, 1, 0.01)
print('Attribute of state vector = ', y0.someAttribute)
p = {'someParameter': 0.5}
y = odeint(some_model, y0, time, args=(p,))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20101103/ce45c8b0/attachment.html
More information about the SciPy-User
mailing list