0

I'm trying to solve decay equations using scipy.integrate.odeint. I'm trying to have initial values from a dictionary, but it isn't working and I'm not sure if it can work. Here is the code I'm working with:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    f0 = - init['a']/.5
    f1 = init['a']/.5 - init['b']/.2
    f2 = init['b']/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = {'a':5, 'b':0, 'c':0}
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

It works as expected if instead of a dictionary I use a list like this:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def decay(init,t):
    a,b,c = init
    f0 = - a/.5
    f1 = a/.5 - b/.2
    f2 = b/.2
    return [f0,f1,f2]

if __name__ == '__main__':
    init = [5,0,0]
    time = np.linspace(0, 10, 101)
    soln  = odeint(decay, init ,time)
    a = soln[:,0]
    b = soln[:,1]
    c = soln[:,2]
    print a
    print b
    print c
    plt.plot(time, a, color = 'g')
    plt.plot(time, b, color = 'r')
    plt.plot(time, c, color = 'b')
    plt.show()

However, I need to be using a dictionary for my purposes. Is there a way to use a dictionary to call the initial values?

2
  • According to the docs, the second parameter is supposed to be an array -- numpy converts list to array just fine, but it won't convert a dict to an array ... So what you're asking for probably isn't possible... Commented Jun 9, 2016 at 22:16
  • Oh, yeah I see that now. Good eye Commented Jun 9, 2016 at 22:22

1 Answer 1

1

If this works:

init = [5,0,0]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

then this should as well:

adict = {'a':5, 'b':0, 'c':0}
init = [adict['a'],adict['b'],adict['c']]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

In other words, regardless of where you are getting this dictionary from, you need to convert its values to a list.

init = adict.values() (or list(adict.values()) in Py3) won't work since a dictionary orders the keys in its own way:

In [306]: list({'a':5, 'b':0, 'c':0}.values())
Out[306]: [0, 0, 5]

or for a longer list of keys, this might be simpler:

In [307]: adict = {'a':5, 'b':0, 'c':0}
In [308]: init = [adict[k] for k in ['a','b','c']]
In [309]: init
Out[309]: [5, 0, 0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.