简体   繁体   English

如何在2.7中使用带有化学反应动力学的optimize.fmin函数

[英]How to use the optimize.fmin function in python 2.7 with chemical reaction kinetics

I have an assignment to plot two consecutive first order reactions, then find the maximum concentration for reaction B. 我有一个任务要绘制两个连续的一级反应,然后找到反应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! 我的老师告诉我使用optimize.fmin() (我想他想让我为反应B创建一个负数的函数,并找到该函数的最小值,应该是最大值。),唯一的麻烦是它不起作用!

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. 到目前为止,这是我为optimize.fmin()函数尝试的第二个参数,除0.75以外的其他值。 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 这是与代码的t=linspace(0,tmax,20)行有关的,在该行中,我创建了20个均匀间隔的点,实验的总运行时间为20分钟

%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.

Taking a lot more points in t , eg 2000, you may find the time of the maximum by finding the index of the array at which the numerical maximum occurs. t花费更多点,例如2000,您可以通过找到数值最大值出现的数组的索引来找到最大值的时间。

t = np.linspace(0,tmax,2000)
#... rest of code
print t[np.argmax(conc_B(t))] # prints 8.11

If you want to use optimize.fmin , I would suggest you first read the documentation . 如果要使用optimize.fmin ,建议您先阅读文档 It states that the first argument needs to be a function. 它指出第一个参数必须是一个函数。 So you need to provide a function that should be minimized. 因此,您需要提供一个应该最小化的功能。

import numpy as np
import scipy.optimize as optimize

k1 = 0.15
k2 = 0.10
A0 = 2.
tmax = 21

e1= lambda t: np.exp(-k1*t)
e2= lambda t: np.exp(-k2*t)

conc_A = lambda t: A0 * e1(t)
conc_B= lambda t: A0 *(k1 / (k2-k1)) * (e1(t) - e2(t))
conc_C = lambda t: (A0/ (k2-k1)) * (k2 * ((1. - e1(t) ))* -(k1 *(1.-e2(t))))

print optimize.fmin(lambda t: -conc_B(t),0.75)

# Optimization terminated successfully.
#         Current function value: -0.888889
#         Iterations: 23
#         Function evaluations: 46
# [ 8.10930176]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM