【问题标题】:Method without arguments or parenthesis for Scipy odeintScipy odeint 没有参数或括号的方法
【发布时间】:2020-12-03 17:49:56
【问题描述】:

请帮助 - 我无法理解我自己的代码!哈哈 我是 python 的新手,经过多次试验和错误,我的代码可以正常工作,但其中有一个特定部分我不明白。

在下面的代码中,我通过 scipy 的 odeint 函数解决了一个相当基本的 ODE。我的目标是在此蓝图的基础上构建更复杂的系统。

我的问题:如何在没有任何参数且没有右括号的情况下调用方法.reaction_rate_simple?这在 python 中是什么意思?我应该在某处使用静态方法吗?

如果有人对此有任何反馈 - 也许这是一段糟糕的代码,但有更好的解决方法!

非常感谢任何回复和帮助!

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

class batch_reator:

    def __init__(self, C_init, volume_reactor, time_init, time_end):
        self.C_init = C_init
        self.volume = volume_reactor
        self.time_init = time_init
        self.time_end = time_end
        self.operation_time = (time_end - time_init)
    
    def reaction_rate_simple(self, concentration_t, t, stoch_factor, order, rate_constant):
        reaction_rate = stoch_factor * rate_constant * (concentration_t ** order)
        return reaction_rate

    def equations_system(self, kinetics):
        dCdt = kinetics
        return dCdt


C_init = 200
time_init, time_end = 0, 1000 
rate_constant, volume_reactor, order, stoch_factor = 0.0001, 10, 1, -1
time_span = np.linspace(time_init, time_end, 100)
 
Batch_basic = batch_reator(C_init, volume_reactor, time_init, time_end)       
kinetics = Batch_basic.reaction_rate_simple

sol = odeint(Batch_basic.equations_system(kinetics), Batch_basic.C_init, time_span, args=(stoch_factor, order, rate_constant))

plt.plot(time_span, sol)
plt.show() 

【问题讨论】:

    标签: python numpy math scipy chemistry


    【解决方案1】:

    我假设你指的是这条线

    kinetics = Batch_basic.reaction_rate_simple
    

    您不是在调用它,而是将方法保存为变量,然后将该方法传递给equations_system(...),它只是返回它。我不熟悉 odeint,但根据文档,它接受一个可调用对象,这就是你给它的。

    在python函数中,lambdas、类都是可调用的,可以赋值给变量,传递给函数,根据需要调用。

    在这种特殊情况下,来自odeint docs 的回调定义说

    func callable(y, t, ...) 或 callable(t, y, ...) 计算 y 在 t 处的导数。如果签名是可调用的(t, y, ...),则参数 tfirst 必须设置为 True。

    所以前两个参数是由 odeint 传入的,另外三个来自你指定的参数。

    【讨论】:

    • 是的,我指的是这一行!我以前从未见过将方法保存为变量,这就是为什么我不太明白的原因。谢谢!我仍然对之后的行感到困惑-持有方法reaction_rate_simple的变量kinetics从哪里获取所有参数? 3 来自args,我假设其他两个在使用 odeint 时被“忽略”......无论如何,这是一个不同的问题,我可以尝试找出!非常感谢您花时间帮助我,非常感谢!
    • 更新了解决该问题的答案。
    猜你喜欢
    • 2019-07-02
    • 2013-10-01
    • 2014-11-26
    • 1970-01-01
    • 2016-08-20
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多