def get_linear_equations_solution_numerically(eqs, dt): # Otherwise assumes it is given in functional form n = len(eqs._diffeq_names) # number of state variables dynamicvars = eqs._diffeq_names # Calculate B AB = zeros((n, 1)) d = dict.fromkeys(dynamicvars) for j in range(n): d[dynamicvars[j]] = 0. * eqs._units[dynamicvars[j]] for var, i in zip(dynamicvars, count()): AB[i] = -eqs.apply(var, d) # Calculate A M = zeros((n, n)) for i in range(n): for j in range(n): d[dynamicvars[j]] = 0. * eqs._units[dynamicvars[j]] if isinstance(eqs._units[dynamicvars[i]], Quantity): d[dynamicvars[i]] = Quantity.with_dimensions(1., eqs._units[dynamicvars[i]].get_dimensions()) else: d[dynamicvars[i]] = 1. for var, j in zip(dynamicvars, count()): M[j, i] = eqs.apply(var, d) + AB[j] #B=linalg.solve(M,AB) numeulersteps = 100 deltat = dt / numeulersteps E = eye(n) + deltat * M C = eye(n) D = zeros((n, 1)) for step in xrange(numeulersteps): C, D = dot(E, C), dot(E, D) - AB * deltat return C, D
def get_linear_equations(eqs): ''' Returns the matrices M and B for the linear model dX/dt = M(X-B), where eqs is an Equations object. ''' # Otherwise assumes it is given in functional form n = len(eqs._diffeq_names) # number of state variables dynamicvars = eqs._diffeq_names # Calculate B AB = zeros((n, 1)) d = dict.fromkeys(dynamicvars) for j in range(n): d[dynamicvars[j]] = 0. * eqs._units[dynamicvars[j]] for var, i in zip(dynamicvars, count()): AB[i] = -eqs.apply(var, d) # Calculate A M = zeros((n, n)) for i in range(n): for j in range(n): d[dynamicvars[j]] = 0. * eqs._units[dynamicvars[j]] if isinstance(eqs._units[dynamicvars[i]], Quantity): d[dynamicvars[i]] = Quantity.with_dimensions(1., eqs._units[dynamicvars[i]].get_dimensions()) else: d[dynamicvars[i]] = 1. for var, j in zip(dynamicvars, count()): M[j, i] = eqs.apply(var, d) + AB[j] #M-=eye(n)*1e-10 # quick dirty fix for problem of constant derivatives; dimension = Hz #B=linalg.lstsq(M,AB)[0] # We use this instead of solve in case M is degenerate B = linalg.solve(M, AB) # We use this instead of solve in case M is degenerate return M, B