首页 > 解决方案 > AttributeError:使用python中的类求解方程组时

问题描述

我有两个耦合 ODE [dXdt,dVdt] 的模型,其中包含一些参数(rho,F1,...),我想在类中使用 Scipy 中的 odeint 来解决这些参数。当我尝试时,我得到了一个 AttributeError ,你可以在这里看到:

  File "C:/Users/Asus/Desktop/Mixer_model.py", line 20, in Mixer_model
    dXdt = (1/(self.rho*Z[1]))*(self.F1*(self.x1-Z[0]) + self.F2*(self.x2-Z[0]))

AttributeError: 'numpy.ndarray' object has no attribute 'rho'
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
class Mixer_class:
    def __init__(self, rho, F1, F2, F, x1,x2):
        self.rho = rho
        self.F1 = F1
        self.F2 = F2
        self.F = F
        self.x1 = x1
        self.x2 = x2
    def Mixer_model(self, Z):
        dXdt = (1/(self.rho*Z[1]))*(self.F1*(self.x1-Z[0]) + self.F2*(self.x2-Z[0]))
        dVdt = (1/self.rho)*(self.F1 + self.F2 - self.F)
        return [dXdt, dVdt]
    t = np.arange(0,650, 22.5)
    # initial condition
    V0 = 0.75  # m^3
    x0 = 0.95
    Z0 = [x0, V0]
    # ODE solve
    Vx = odeint(Mixer_model,Z0,t)
    plt.plot(t,Vx[:,0],'ko--',linewidth = 1.5)
    plt.plot(t,Vx[:,1],'cs-',linewidth = 1.5)
    plt.ylabel('V(t) and X(t)')
    plt.xlabel('Time(sec)')
    plt.show()
Mix = Mixer_class(1000, 12.5, 6.7, 3.87, 0.42, 0.58)

当我运行代码时,我得到以下属性错误:

  File "C:/Users/Asus/Desktop/Mixer_model.py", line 20, in Mixer_model
    dXdt = (1/(self.rho*Z[1]))*(self.F1*(self.x1-Z[0]) + self.F2*(self.x2-Z[0]))

AttributeError: 'numpy.ndarray' object has no attribute 'rho'

有人可以帮我弄清楚我的代码发生了什么吗?非常感谢大家

标签: python-3.xclasssystemodenumpy-ndarray

解决方案


假设您的代码中的缩进是正确的,并且 ODE 求解器没有在类级别上调用,那么您忽略了odeint其 ODE 函数所期望的参数格式。格式是

ode_func(y,t)

状态向量后跟时间。在您的情况下,传递的空间和时间参数进入selfand time。因此错误消息。

您需要先实例化该类,然后将实例函数的包装变体传递给集成器。

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
class Mixer_class:
    def __init__(self, rho, F1, F2, F, x1,x2):
        self.rho = rho
        self.F1 = F1
        self.F2 = F2
        self.F = F
        self.x1 = x1
        self.x2 = x2
    def Mixer_model(self, Z):
        dXdt = (1/(self.rho*Z[1]))*(self.F1*(self.x1-Z[0]) + self.F2*(self.x2-Z[0]))
        dVdt = (1/self.rho)*(self.F1 + self.F2 - self.F)
        return [dXdt, dVdt]

Mix = Mixer_class(1000, 12.5, 6.7, 3.87, 0.42, 0.58)
t = np.arange(0,650, 22.5)
# initial condition
V0 = 0.75  # m^3
x0 = 0.95
Z0 = [x0, V0]
# ODE solve
Vx = odeint(lambda Z,t: Mix.Mixer_model(Z), Z0,t)
plt.plot(t,Vx[:,0],'ko--',linewidth = 1.5)
plt.plot(t,Vx[:,1],'cs-',linewidth = 1.5)
plt.ylabel('V(t) and X(t)')
plt.xlabel('Time(sec)')
plt.show()

在此处输入图像描述

或者,您可以将求解器放入--正确声明的--类方法中。然后包装看起来像lambda Z,t: self.Mixer_model(Z).


推荐阅读