2016-06-09 11 views
0

Ich versuche, Zerfallsgleichungen mit scipy.integrate.odeint zu lösen. Ich versuche, Anfangswerte aus einem Wörterbuch zu haben, aber es funktioniert nicht und ich bin nicht sicher, ob es funktionieren kann. Hier ist der Code Ich arbeite mit:Verwenden von scipy.integrate.odeint mit Wörterbuch [Python]

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() 

Es funktioniert wie erwartet, wenn anstelle eines Wörterbuchs verwende ich eine Liste wie folgt aus:

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() 

Ich brauche aber ein Wörterbuch verwenden für meine Absichten. Gibt es eine Möglichkeit, ein Wörterbuch zu verwenden, um die Anfangswerte aufzurufen?

+0

Laut der Dokumentation soll der zweite Parameter ein Array sein - 'numpy' konvertiert Liste in Array, aber es wird kein dict in ein Array konvertieren ... Also, was Sie wahrscheinlich fragen ist nicht möglich ... – mgilson

+0

Oh, ja, ich sehe das jetzt. Gutes Auge – greenthumbtack

Antwort

1

Wenn dies funktioniert:

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

dann soll dies auch:

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) 

Mit anderen Worten, unabhängig davon, wo Sie das Wörterbuch aus bekommen, müssen Sie die Werte in einem umwandeln Liste.

init = adict.values() (oder list(adict.values()) in PY3) wird nicht funktionieren, da ein Wörterbuch die Schlüssel in seiner eigenen Art und Weise anordnet:

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

oder für eine längere Liste von Schlüsseln, könnte dies einfacher sein:

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]