python-3.x - 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'
有人可以帮我弄清楚我的代码发生了什么吗?非常感谢大家
解决方案
假设您的代码中的缩进是正确的,并且 ODE 求解器没有在类级别上调用,那么您忽略了odeint
其 ODE 函数所期望的参数格式。格式是
ode_func(y,t)
状态向量后跟时间。在您的情况下,传递的空间和时间参数进入self
and 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)
.
推荐阅读
- python - 在 Python 中将多个 CSV 文件合并到电子表格的单独选项卡中
- wordpress - WordPress 编辑器中的最少字符数
- php - 返回在哪个表中找到该项目
- php - 在 woocommerce 管理产品列表中为产品标签添加过滤器下拉列表
- git - TortoiseGit 到 Gitlab 存储库 HTTP 基本访问被拒绝
- react-native - 什么是类App中的道具
- python - 将大型 DataFrame 从 Pandas 加载到 Postgresql
- postgresql - 哪个查询更快?
- php - 如何检查 URL 是否包含数字范围并使用 PHP 重定向页面
- java - 将 Spring Boot 和 Angular 项目部署到 weblogic 12c