scipy - Avoiding hard coding a lot of coupled ODEs in python -


first of, i'm sorry if title not entirely fitting, had hard time finding appropriate 1 (which might have effect searching efficiency asked questions :/ ).

the problem following. while comparably easy solve coupled ode's in python scipy, still have write down ode in form explicitly. example coupled ode of form

d/dt(c_0)=a(c_0)+b(c_1) , d/dt(c_1)=c(c_0)

i set sth like:

import numpy np scipy.integrate import ode  a=1 b=2 c=3 val=[]  def dc_dt(t, c):     return [a*c[0]+b*c[1],             c*c[0]]  c0, t0 = [1.0,0.0], 0 r = ode(dc_dt).set_integrator('zvode', method='bdf',with_jacobian=false) r.set_initial_value(c0, t0) t1 = 0.001 dt = 0.000005 while r.successful() , r.t < t1:     r.integrate(r.t+dt) val.append(r.y) 

however, have coupled ode's of rough form

d/dt(c_{m,n})=a(c_{m,n})+b(c_{m+1,n-1})+k(c_{m-1,n+1})

with c_{0,0}=1 , have include orders m^2+n^2-mn smaller max value. small max, did, using dictionary use notation 2 indices , map on 1d list

dict_in={'0,0':0,'-1,0':2,...} 

and entered ode each order

def dc_dt(t,c):     return[a*c[dict_in['0,0']]+b*c[dict_in['1,-1']]... 

now have 100 coupled equations, ofc not want hard code, trying figure out way, realize ode's loop or sth. couldn't yet find way around fact of having 2 indices in coefficients condition of including orders m^2+n^2-mn smaller max value. running in deadlines, figured time ask smarter people help.

thanks reading question!

i had similar problem. if fill dictionary can redeclare function more times inside loop. silly example of how works:

dict_in={'0,0':0,'-1,0':2}  elem in dict_in:     def dc_dt(t,c):         #return[a*c[dict_in['0,0']]+b*c[dict_in['1,-1']]         return dict_in[elem]      t, c = 0, 0     print(dc_dt(t,c))     #r = ode(dc_dt).set_integrator('zvode', method='bdf',with_jacobian=false) 

if need use more functions can use anonymous functions , store them in memory. example:

functions_list = list() in range(4):     f = lambda n = i:  n     functions_list.append(f)  j in range(4):     print(functions_list[j]()) 

you can use list or generator too. example can write down value on txt file , read readline function each time.

as pointed in comments below, if use lamda functions should pay attention references. see https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -