示例#1
0
 def getting_it_all(my, dt, beta, N, S0, I0,
                    R0):  #since im doing it twice, I made a function
     p = SIR_class(my, dt, beta, N)
     solver = RungeKutta4(p)
     solver.set_initial_condition([S0, I0, R0])
     t = np.linspace(0, N * dt, N + 1)
     u, t = solver.solve(t)
     S = u[:, 0]
     I = u[:, 1]
     R = u[:, 2]
     #unpacking u with the variables I need
     plot_SIR(S, I, R, t)  #plotting this S
示例#2
0
def solve_SEIR(T, dt, S_0, E2_0):
    """Solves the differential equation given initial conditions and time"""
    # Initial conditions and time
    initial_conditions = [S_0, 0, E2_0, 0, 0, 0]
    times = np.linspace(0, T, int(T / dt) + 1)

    # Uses RungeKutta4 to solve
    solver = RungeKutta4(SEIR)
    solver.set_initial_condition(initial_conditions)
    u, t = solver.solve(times)

    return u, t
示例#3
0
def test_asymptotic_limit():
    U0 = [1, 1]

    f = Problem(tau_A=8, tau_B=40)
    from ODESolver import RungeKutta4
    solver = RungeKutta4(f)
    solver.set_initial_condition(U0)
    dt = 10 / 60.0  # minutes
    T = 50  # 50 min
    n = int(round(T / float(dt)))
    import numpy as np
    time_points = np.linspace(0, T, n + 1)
    u, t = solver.solve(time_points)

    # Plot
    u_A = u[:, 0]
    u_B = u[:, 1]
    assert f.test_asymptotic_limit(u_A, u_B, tol=0.001)

    from matplotlib.pyplot import plot, show, legend
    plot(t, u_A, t, u_B)
    legend(['u_A', 'u_B'], loc='lower left')
    show()
        S, I, R, V = u
        new_S = -self.beta * S * I - self.p(t, self.vt) * S
        new_I = self.beta * S * I - self.my * I
        new_R = self.my * I
        new_V = self.p(t, self.vt) * S
        return new_S, new_I, new_R, new_V


if __name__ == "__main__":
    max_infected = np.zeros(32)
    qq = 0
    a = False
    for i in range(32):
        plt.clf()
        problem = SIRV2(0.1, 0.5, 0.0005, 120, p, i)
        solver = RungeKutta4(problem)
        solver.set_initial_condition([1500, 1, 0, 0])
        t = np.linspace(0, 60, 121)
        u, t = solver.solve(t)
        S = u[:, 0]
        I = u[:, 1]
        R = u[:, 2]
        V = u[:, 3]

        max_infected[i] = np.amax(I)

        q = np.amax(I)
        tol = 0.5
        if abs(qq - q) < tol and a == False:
            ii = i
            print "when we have vacinated %d days, from day 6, to day %d, we have the most effective vaccination period" % (
示例#5
0
文件: bjorgvin.py 项目: MrMelk/IN1900
    u_k = u[k, :]
    u_k_minus_1 = u[k - 1, :]
    test = np.abs(np.sum(u_k_minus_1) - np.sum(u_k))
    tol = 1e-9

    msg = "They aint the same bro. THEY AINT THE SAME"
    if test < tol:
        return False
    else:
        print(msg)
        return True


U0 = (7000, 30, 0, 0)

swaggyboi = RungeKutta4(solvelolve)
swaggyboi.set_initial_condition(U0)

u, t = swaggyboi.solve(t, terminate=terminate)


def plottelott(u, t):
    S = []
    I = []
    R = []
    D = []
    for i in range(len(u)):
        S.append(u[i][0])
        I.append(u[i][1])
        R.append(u[i][2])
        D.append(u[i][3])
示例#6
0
if __name__ == "__main__":
    n = 240 #number of points
    alpha = 0.0016#chance that a human kills a zmobie
    sigma = 2.0 #number of new people
    gammaS = 0.014#chance that a susceptible human dies
    gamma1 = 0.014#chance that an infected human dies
    p = 1#chance that an human zombie turns into a zombie
    beta = 0.0012 #chance of human turning zombie
    T = 24 #time in hours
    S0 = 10 #start humans
    I0 = 0 #start infected
    Z0 = 100 #start zombies
    R0 = 0 #start removed

    p = SIZR_class(alpha, sigma, gamma1, gammaS, p, beta, n)
    solver = RungeKutta4(p)
    solver.set_initial_condition([S0, I0, Z0, R0])
    t = np.linspace(0, T, n+1)
    u, t = solver.solve(t)
    #using ODESolver and RungeKutta to get the values I need
    S = u[:, 0]
    I = u[:, 1]
    Z = u[:, 2]
    R = u[:, 3]
    #unpacking the values

    plot4zombie(t, S, I, Z, R)
    #plotting the thing

"""
terminal > python SIZR.py
示例#7
0
from ODESolver import ODESolver, ForwardEuler, RungeKutta4


def f(u, t):
    M = 1  # SolarMasses
    G = 4 * pi**2  # AU^3/(yr^2*SM)
    x, y, vx, vy = u
    dx = vx
    dy = vy
    radius = sqrt(x**2 + y**2)
    dvx = -G * M * x / radius**2
    dvy = -G * M * y / radius**2
    return [dx, dy, dvx, dvy]


planet = RungeKutta4(f)
x = 1
y = 0  # AU
vx = 0
vy = 2 * pi  # AU/yr
U0 = [x, y, vx, vy]
planet.set_initial_condition(U0)

time_points = linspace(0, 10, 1001)
u, t = planet.solve(time_points)

x, y, vx, vy = u[:, 0], u[:, 1], u[:, 2], u[:, 3]

plt.plot(x, y)
plt.axis('equal')
plt.show()

class SIR:
    def __init__(self, beta, nu):
        self.beta = beta
        self.nu = nu

    def __call__(self, u, t):
        S, I, R = u[0], u[1], u[2]
        dS = -self.beta * S * I
        dI = self.beta * S * I - self.nu * I
        dR = self.nu * I
        return [dS, dI, dR]


S0 = 1000
I0 = 1
R0 = 0

model = SIR(beta=0.001, nu=1 / 7.0)
solver = RungeKutta4(model)
solver.set_initial_condition([S0, I0, R0])
time_points = np.linspace(0, 100, 101)
u, t = solver.solve(time_points)
S = u[:, 0]
I = u[:, 1]
R = u[:, 2]

plt.plot(t, S, t, I, t, R)
plt.show()
示例#9
0
class Decay:
    def __init__(self, a):
        self.a = a

    def __call__(self, u, t):
        return -self.a * u


#b
decay_inst = Decay(a)

#c
T = 20000
tp = np.linspace(1, T, T / 500)
RK = RungeKutta4(decay_inst)
RK.set_initial_condition(u0)

u, t = RK.solve(tp)


def exact(t):
    return np.exp(-a * t)


print(
    f"Difference between exact, {exact(T):.5f}, and approxiamate {u[len(u)-1]:.5f}, is {np.abs(exact(T) - u[len(u)-1]):.5f} after {T} years. limited to  decimals"
)

plt.plot(t, u, label="approximate fraction of particals that remain")
plt.plot(t, exact(t), label="Exact fraction of particals that remain", ls="--")
示例#10
0
plt.subplot(4, 1, 1)
plt.title("RungeKutta2")
for i in n:
    t = np.linspace(-17, 17, i)
    RK2 = RungeKutta2(f)
    RK2.set_initial_condition(y0)
    u, t = RK2.solve(t)
    plt.plot(t, u, label=f"n = {i} steps")
plt.legend()

plt.subplot(4, 1, 2)
plt.title("RungeKutta4")
for i in n:
    t = np.linspace(-17, 17, i)
    RK4 = RungeKutta4(f)
    RK4.set_initial_condition(y0)
    u, t = RK4.solve(t)
    plt.plot(t, u, label=f"n = {i} steps")
plt.legend()

plt.subplot(4, 1, 3)
plt.title("Heun")
for i in n:
    t = np.linspace(-17, 17, i)
    H = Heun(f)
    H.set_initial_condition(y0)
    u, t = H.solve(t)
    plt.plot(t, u, label=f"n = {i} steps")
plt.legend()
示例#11
0
test_Cooling()

#c)
T0 = 95 #temperature when t=0 in C
t1 = 15; T1 = 92 #temperature after 15 seconds in C
U0 = T0

dt = t1; tstop = 3600
N = int (tstop/dt)
timepoints = np.linspace(0, tstop, N)

for color, Ts in zip([ "slateblue", "darkorange"], [20,25]):
    h = estimate_h(t1, Ts, T0, T1)
    cool = Cooling(h, Ts)
    dTdt = RungeKutta4(cool)
    dTdt.set_initial_condition(U0)
    u, t = dTdt.solve(timepoints, cool.terminate)
    print(f"Surrounding temperature: {Ts}. Coffee temperature when poured into the cup: {u[0]}◦C. After 15 sec: {u[1]}")
    plt.plot(t, u, f"{color}", label = f"Ts = {Ts}")


plt.legend()
plt.xlabel("time (seconds)")
plt.ylabel("Temperature (◦C)")
plt.title("Solutions-Newton’s law of cooling")
plt.show()


"""
(plot)
示例#12
0
from ODESolver import RungeKutta4
import numpy as np
import matplotlib.pyplot as plt


def SIR_model(u, t):
    beta = 0.001
    nu = 1 / 7.0
    S, I, R = u[0], u[1], u[2]
    dS = -beta * S * I
    dI = beta * S * I - nu * I
    dR = nu * I
    return [dS, dI, dR]


S0 = 1000
I0 = 1
R0 = 0

solver = RungeKutta4(SIR_model)
solver.set_initial_condition([S0, I0, R0])
time_points = np.linspace(0, 100, 101)
u, t = solver.solve(time_points)
S = u[:, 0]
I = u[:, 1]
R = u[:, 2]

plt.plot(t, S, t, I, t, R)
plt.show()
示例#13
0
seconds = 10
time_array = linspace(0, seconds, timepoints)
V0 = 8  # Voltage of battery when on

def Q_der(Q,t):  # Definition of Q'(t)
    return (V0 - Q/C)/R

# __Exercise a__
def Q_exact(t):  # Q(t) exact (only for charge-up).
    return (Q0 - C*V0)*exp(-t/(R*C)) + C*V0

circuit_FE = ForwardEuler(Q_der)
circuit_FE.set_initial_condition(Q0)
Q_FE, t = circuit_FE.solve(time_array)

circuit_RK4 = RungeKutta4(Q_der)
circuit_RK4.set_initial_condition(Q0)
Q_RK4, t = circuit_RK4.solve(time_array)

plt.plot(t, Q_FE, label='$Q(t)$, Forward Euler')
plt.plot(t, Q_RK4, label='$Q(t)$, Runge Kutta 4')
many_time_steps = linspace(0, seconds, 1001)  # For analytical solution.
plt.plot(many_time_steps, Q_exact(many_time_steps), label='$Q(t)$, exact')
plt.xlabel('Time [seconds]')
plt.ylabel('Electric charge [colomb]')
plt.title('Charging capasitor')
plt.legend()
plt.savefig('fig_E2.1.pdf')
plt.clf()

# __Exercise b__