I have an assignment to plot two consecutive first order reactions, then find the maximum concentration for reaction B.
I've managed to plot a graph of the three functions, i'm struggling with
finding the maximum value. My teacher told me to use optimize.fmin()
(I figure he wants me to create a negative of the function for reaction B,
and find the minimum for that function, which should be the maximum.),
only trouble is it's not working!
here's what I have so far, I have tried other value other than 0.75 for the second argument in the optimize.fmin()
function.
Where am I going wrong here ? I see the error is saying it is expecting an array but getting a sequence ? is this in relation to the t=linspace(0,tmax,20)
line
of code where I create 20 evenly spaced points of to a total runtime of 20 minutes for the experiment
%pylab inline
from matplotlib import *
from scipy import *
k1 = 0.15
k2 = 0.10
A0 = 2
tmax = 21
t = linspace(0,tmax,20)
e1= e**(-k1*t)
e2= e**(-k2*t)
def conc_A(t):
A = A0 * e1
return A
def conc_B(t):
B = A0 *(k1 / (k2-k1)) * (e1 - e2)
return B
def conc_C(t):
C = (A0/ (k2-k1)) * (k2 * ((1 - e1 ))* - (k1 *(1-e2)))
return C
pylab.plot(t,conc_A(t),label ='[A]')
plot(t,conc_B(t),label= '[B]')
plot(t,conc_C(t),label= '[C]')
pylab.legend(loc='upper right')
plt.xlabel("Time (minutes)" )
plt.ylabel("Concentration Mol $Dm^{-3}$")
plt.title("Rates of reaction of two consecutive first order reactions")
def neg_B(t):
return -conc_B(t)
optimize.fmin(neg_B,0.75)
The error I get is
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-88-f481d0e274f9> in <module>()
48
49
---> 50 optimize.fmin(neg_B,0.75)
51
52
C:\Users\gsandle1\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy\optimize\optimize.py in fmin(func, x0, args, xtol, ftol, maxiter, maxfun, full_output, disp, retall, callback, initial_simplex)
391 'initial_simplex': initial_simplex}
392
--> 393 res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
394 if full_output:
395 retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']
C:\Users\gsandle1\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy\optimize\optimize.py in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, **unknown_options)
515
516 for k in range(N + 1):
--> 517 fsim[k] = func(sim[k])
518
519 ind = numpy.argsort(fsim)
ValueError: setting an array element with a sequence.