我对Scipy很新,我已经印象深刻了。我希望使用ODEint和曲线拟合来进行一些简单的化学动力学建模。基本上我正在整合一个方程来获得y值,然后将其拟合到我从excel读取的一些数据。对于下面的简单过程,它是完美的
这有效:
data = pd.read_excel('C:\Spreadsheet', header = 0, parse_cols = 5)
data.head()
SM_CONC = 0.1176
def fitfuncSM(t, k1):
def myode(SM, t):
return -k1 * SM
SM0 = SM_CONC
SMt = odeint(myode, SM0, t)
return SMt[:,0]
SM_fit, SMcov = curve_fit(fitfuncSM, data['Time'], data['A'], p0 = 1)
问题
我希望通过同时对多个图进行曲线拟合来增加复杂性(见下文)。这是A转换为B转换为C的反应。我期待曲线拟合并提取值k1和k2。我有Ca和Cb的ydata。要集成的功能运行良好(mytest - 见下文)。但是我不知道如何导入ydata以适应。如果我导入一个ydata数组:SM_f, SMc = curve_fit(SM, data['Time'], ydata (array of the Ca and Cb), p0 = (1, 1)
。它给了我一个错误:操作数不能与形状(10,3)(3,10)“
def SM(t, k1, k2):
def mytest(C, t):
Ca = C[0]
Cb = C[1]
Cc = C[2]
dAdt = -k1 * Ca
dBdt = k1 * Ca - (k2 * Cb)
dCdt = k2 * Cb
dydt = [dAdt, dBdt, dCdt]
return dydt
init = [0.117, 0, 0]
value = odeint(mytest, init, t)
return value
以下更新 - 我使用您建议的转换更新了我的代码(见下文)我感觉我遗漏了一些非常简单的事情。有任何想法吗?这是曲线拟合的限制吗?我应该使用其他东西吗?
xdata = (data['Time'])
ydata = np.array([data['A'], data['B'], data['C']])
SM_CONC = 0.1176
def SM(t, k1, k2):
def mytest(C, t):
Ca = C[0]
Cb = C[1]
Cc = C[2]
dAdt = -k1 * Ca
dBdt = k1 * Ca - (k2 * Cb)
dCdt = k2 * Cb
dydt = np.array([dAdt, dBdt, dCdt])
return dydt
init = [SM_CONC, 0, 0]
value = odeint(mytest, init, t)
return value[:,:]
SM_f, SMc = curve_fit(SM, xdata, ydata.T, p0 = (1, 1))
错误消息
ValueError Traceback (most recent call last)
ValueError: object too deep for desired array
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-58-d09497ebe5ae> in <module>()
30 return value[:,:]
31
---> 32 SM_f, SMc = curve_fit(SM, xdata, ydata.T, p0 = (1, 1))
33
34
C:\Users\Family\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata,
553 # Remove full_output from kw, otherwise we're passing it in twice.
554 return_full = kw.pop('full_output', False)
--> 555 res = leastsq(func, p0, args=args, full_output=1, **kw)
556 (popt, pcov, infodict, errmsg, ier) = res
557
C:\Users\Family\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
377 maxfev = 200*(n + 1)
378 retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
--> 379 gtol, maxfev, epsfcn, factor, diag)
380 else:
381 if col_deriv:
error: Result from function call is not a proper array of floats.