如何用scipy拟合两个实验数据的导数方程?

sqyvllje  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(131)

我试图同时拟合2个实验数据,因为它有一些共享参数。这是一个化学React,我希望得到如所附图片所示的拟合。我已经设法使用symfit软件包拟合我的数据,但我需要使用scipy/numpy来进一步处理数据(使用蒙特卡罗模拟)。我尝试使用scipy的代码是:
GL conversion to GM and fitting
Dataset for download

import matplotlib.pyplot as plt
import numpy as np
import scipy as sp

# Open dataset from txt file after extraction from brute data:

with open("ydata.txt", "r") as csv_file:
    ydata = np.loadtxt(csv_file, delimiter = ',')

with open("ydata2.txt", "r") as csv_file:
    ydata2 = np.loadtxt(csv_file, delimiter = ',')

xdata = np.arange(0, len(ydata))
fulldata = np.column_stack([ydata,ydata2])

# Define the equation considering the enzymatic reaction Gl -> Gm with the HP decay.

def f(C, t, k, a, b):
    GL = ydata
    GM = ydata2

    dGLdt = -k*GL - GL/a
    dGMdt = k*GL - GM/b

    return [dGLdt, dGMdt] 

guess = (1e-3, 10, 10,1 )

popt, pcov = sp.optimize.curve_fit(f, xdata, fulldata, guess)

我得到的错误是:

File "/Users/karensantos/Desktop/Codes/Stack_question.py", line 52, in <module>
    popt, pcov = sp.optimize.curve_fit(f, xdata, fulldata, guess)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 784, in curve_fit
    res = leastsq(func, p0, Dfun=jac, full_output=1,**kwargs)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 410, in leastsq
    shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 24, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))

  File "/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py", line 484, in func_wrapped
    return func(xdata, *params) - ydata

ValueError: operands could not be broadcast together with shapes (2,98) (98,2)

我可以用curve_fit一次求解一个方程,但我需要一起拟合以找到所有正确的共享参数(k),因为GM依赖于GL(分别为产品和底物)。
如何使用scipy优化来拟合两个实验数据?
先谢谢你,

u2nhd7ah

u2nhd7ah1#

您可以在1D数组中连接数组,以使用curve_fit运行
我不能运行你的例子,所以我会做一个

import numpy as np
from scipy.optimize import curve_fit
def cost(x, a, b):
    return np.hstack(f(a, b, x))
def f(a,b,x):
    return a * x**3, a**2*np.exp(-(x-b/a)**2/a)
x = np.linspace(-2, 2)
y1, y2 = f(4.5, 2.3, x)
initial_guess = (1,1)
params, _ = curve_fit(cost, x, np.hstack([y1, y2]),initial_guess)
print(params)

在这个例子中,有一个函数f,它有两个参数和x数据,我用它来计算(y1,y2),然后我用curve_fit来确定哪些参数生成了(y1,y2)。

编辑1

使用OP提供的数据,拟合可能是这样的

def f(params, xdata, ydata, ydata2):
    C = xdata
    t, k, a, b = params
    GL = ydata
    GM = ydata2

    dGLdt = -k*GL - GL/a
    dGMdt = k*GL - GM/b

    return np.hstack([dGLdt, dGMdt])

guess = (1e-3, 10, 10,1)

popt, pcov = scipy.optimize.leastsq(f, guess, args=(xdata, ydata, ydata2))

参数的选择是[ 1.00000000e-03, -1.71943255e-69, 1.60693865e+61, 1.60694078e+60],一个平凡解,(ab)增长到无穷大,而k趋于零。t不变,因为目标函数不随t而变化。
我觉得你应该重新考虑一下你的模型方程。

相关问题