import ODESolver
import matplotlib.pyplot as plt
import numpy as np
class Region:
def __init__(self, region, S0, I0, R0, D0):
self.S0 = S0
self.I0 = I0
self.R0 = R0
self.D0 = D0
self.region = region
def set_SIRD_values(self, u, t):
self.S = u[:,0]
self.I = u[:,1]
self.R = u[:,2]
self.D = u[:,3]
self.t = t
def plot(self, x_label):
plt.plot(self.t, self.S, label="Susceptible", color="blue")
plt.plot(self.t, self.I, label="Susceptible", color="yellow")
plt.plot(self.t, self.R, label="Susceptible", color="red")
plt.plot(self.t, self.D, label="Susceptible", color="green")
class ProblemSIRD:
def __init__(self, region, alpha, beta, gamma):
self.region = region
if isinstance(alpha, (float, int)):
self.alpha = lambda t: alpha
elif callable(alpha):
self.alpha = alpha
self.beta = beta
self.gamma = gamma
def set_initial_condition(self):
self.initial_condition = [self.region.S0, self.region.I0, self.region.R0, self.region.D0]
def get_population(self):
return self.region.S0 + self.region.I0 + self.region.R0 + self.region.D0
def solution(self, u, t):
return self.region.set_SIRD_values()
def __call__(self, u, t):
S, I, R, D = u
return [-self.alpha * S * I,self.alpha * S * I - self.beta * I - self.gamma * I,self.beta * I,self.gamma * I]
class SolverSIRD:
def __init__(self, problem, T, dt):
self.problem = problem
self.T = T
self.dt = dt
self.total_population = ProblemSIRD.get_population(problem)
def terminate(self,U,t,time_step):
tol = 1e-10
msg = 'Error in numerical method'
assert abs(sum(U[time_step]) - self.total_population()) < tol, msg
def solve(self, method=RungeKutta4):
solver = method(self.problem)
problem.set_initial_condition()
t = np.linspace(0, self.T, self.dt)
u, t = solver.solve(t, self.terminate)
self.problem.solution(u, t)
U0 = [7000.0, 30.0, 0.0, 0.0]
initialP = 63
alpha = 6.5e-5
beta = 0.1/4
gamma = 0.9/4
bjorgvin = Region('Bjorgvin', U0[0], U0[1], U0[2], U0[3])
problem = ProblemSIRD(alpha, beta, gamma, bjorgvin)
solver = SolverSIRD(problem,63,64)
solver.solve(method = ODESolver.RungeKutta4)
Region.plot(x_label = bjorgvin)
plt.legend()
plt.show()
错误:
第50行,在get_population中 返回self.region.S0 + self.region.I0 + self.region.R0 + self.region.D0
AttributeError:“浮动”对象没有属性“ S0”
这里可能有多个错误,但是如果您能帮助我解决这个问题,我将不胜感激。我在“ set_initial_condition”功能中遇到了同样的问题。为什么我不能使用Region类中的属性?
答案 0 :(得分:0)
看看代码中的以下几行:
class ProblemSIRD:
def __init__(self, region, alpha, beta, gamma):
...
您的类__init__
的{{1}}方法期望将ProblemSIRD
对象作为 first 参数传递。但是,在实例化该类时,您将其作为 last 参数传递。
Region
将行重写为bjorgvin = Region('Bjorgvin', U0[0], U0[1], U0[2], U0[3])
problem = ProblemSIRD(alpha, beta, gamma, bjorgvin)
应该可以解决此问题。