我试图将数据拟合成一个由两个方程组成的系统,如下所示:

enter image description here

enter image description here

这里有gamma与C_s的关系,其余的gamma_0、gamma_inf、a和K是拟合参数.

我没有看到任何错误,但拟合不起作用,每个参数不可能是负的,但其中一些是负的.

enter image description here

import numpy as np
from scipy.optimize import curve_fit, fsolve
import matplotlib.pyplot as plt
import pandas as pd

# Prompt the user for the CSV file location
csv_file = input("Enter the path to your CSV file: ")

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file,header=None)

# Alternatively, select each column by index
# Remember that indices start from 0
Cs_data = df.iloc[:, 0]
gamma_data = df.iloc[:, 1]

# Define the Frumkin equilibrium function to solve for x
def frumkin_x(C_s, a, K, x_guess=0.5):
    # Function to find the root of
    func = lambda x: x - C_s / (C_s + a * np.exp(K * x))
    x_solution, = fsolve(func, x_guess)
    return x_solution

# Define the equilibrium isotherm function
def equilibrium_isotherm(C_s, gamma_0, Gamma_inf, a, K):
    x = np.array([frumkin_x(cs, a, K) for cs in C_s])
    return gamma_0 + Gamma_inf * R * T * (np.log(1 - x) - 0.5 * K * x**2)

# Constants
R = 8.314  # Universal gas constant, J/(mol*K)
T = 298    # Temperature, K

# Initial parameter guesses for curve_fit
# gamma_0, Gamma_inf, a, K
initial_guesses = [72, 0.0000000004, 0.00000007, 0]

params_opt, params_cov = curve_fit(lambda Cs, gamma_0, Gamma_inf, a, K: equilibrium_isotherm(Cs, gamma_0, Gamma_inf, a, K), Cs_data, gamma_data, p0=initial_guesses)

# Print optimized parameters
print("Optimized Parameters:")
print("gamma_0:", params_opt[0])
print("Gamma_inf:", params_opt[1])
print("a (alpha_0/beta_0):", params_opt[2])
print("K:", params_opt[3])

# Plot the original data and fitted curve for visualization
Cs_fit = np.linspace(min(Cs_data), max(Cs_data), 100)
gamma_fit = equilibrium_isotherm(Cs_fit, *params_opt)

plt.scatter(Cs_data, gamma_data, label='Data')
plt.plot(Cs_fit, gamma_fit, label='Fitted Curve', color='red')
plt.xlabel('Sublayer Concentration (Cs)')
plt.ylabel('Surface Tension (gamma)')
plt.legend()
plt.show()

我没有看到任何错误,所以我不知道问题是什么.

上面的链接包含我的脚本和数据.

推荐答案

在一些帮助下,本质上是边界和初始猜测(fsolve和curve_fit),你可以回归你的参数:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import optimize

data = pd.read_csv("frumkin.csv", header=None, names=["Cs", "gamma"])

def system(x, Cs, a, K):
    return x - Cs / (Cs + a * np.exp(K * x))

R = 8.314
T = 298.

def model(Cs, g0, Ginf, a, K):
    x = np.array([optimize.fsolve(system, x0=0.05, args=(c, a, K))[0] for c in Cs])
    return g0 + Ginf * R * T * (np.log(1. - x) - 0.5 * K * x ** 2)

popt, pcov = optimize.curve_fit(
    model, data.Cs, data.gamma,
    p0=[100., 1e-5, 1e-5, 1.],
    bounds=[(0., 0., 0., 0.), (np.inf, np.inf, np.inf, np.inf)]
)
# array([7.28040792e+01, 3.58127986e-01, 1.43487197e-08, 3.72400451e+02])

它返回:

enter image description here

关于解的唯一性,人们可以证明它是一个在参数范围内的有效假设.以下算盘显示不同设置下Csx之间的关系:

@np.vectorize
def solution(Cs, a, K):
    return optimize.fsolve(system, x0=0.05, args=(Cs, a, K))[0]

Cs = np.logspace(-12, -6, 100, base=10)
As = np.logspace(-12, -6, 10, base=10)
Ks = np.logspace(-5, +5, 10, base=10)
C, A, K = np.meshgrid(Cs, As, Ks, indexing="ij")

s = solution(C, A, K)

enter image description here enter image description here

Python相关问答推荐

将HLS纳入媒体包

如何使用SubProcess/Shell从Python脚本中调用具有几个带有html标签的参数的Perl脚本?

使用mySQL的SQlalchemy过滤重叠时间段

TARete错误:类型对象任务没有属性模型'

重新匹配{ }中包含的文本,其中文本可能包含{{var}

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

如何让剧作家等待Python中出现特定cookie(然后返回它)?

从numpy数组和参数创建收件箱

如何在Raspberry Pi上检测USB并使用Python访问它?

在极性中创建条件累积和

使用groupby方法移除公共子字符串

用砂箱开发Web统计分析

启动带有参数的Python NTFS会导致文件路径混乱

Flash只从html表单中获取一个值

剪切间隔以添加特定日期

如何过滤组s最大和最小行使用`transform`'

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

如何在Python中将超链接添加到PDF中每个页面的顶部?

如何将一个文件的多列导入到Python中的同一数组中?

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名