All Inone Code
All Inone Code
All Inone Code
import numpy as np
import matplotlib.pyplot as plt
for i in range(1,steps):
k1S,k1I,k1R = SIR_model(S[i-1],I[i-1],R[i-1], beta, gamma, N)
k2S,k2I,k2R = SIR_model(S[i-1] + 0.5 * dt * k1S, I[i-1] + 0.5 * dt *␣
↪k1I, R[i-1] + 0.5 * dt * k1R, beta, gamma,N)
1
k4S,k4I,k4R = SIR_model(S[i-1] + dt * k3S, I[i-1] + dt * k3I, R[i-1] +␣
↪dt * k3R, beta, gamma,N)
# Time parameters
tf = 365
t0 = 0
dt = 1
#Model parameters
beta = 0.1
gamma = 1/22
t,S,I,R = rk4(SIR_model, S_values, I_values, R_values, t0, tf, dt, beta, gamma,␣
↪N)
plt.xlabel("Time")
plt.ylabel("Population")
plt.legend() # This will display the legend
plt.title("SIR Model Dynamics") # Optional: Add a title for clarity
plt.grid(True) # Optional: Add a grid for better readability
plt.show()
2
[9]: # SIR -- Stochastic model I
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import KDTree
# Model Parameters
CITY_RADIUS = 2.0 # Radius of the circular city
INFECTION_RADIUS = 0.1 # Infection radius
SIGMA = 0.03 # Standard deviation for Gaussian displacement
ALPHA = 0.5 # Probability of S -> I upon contact
BETA = 0.007 # Probability of I -> R
GAMMA = 0.0 # Probability of R -> S (0 means immunity is␣
↪permanent)
# Simulation Parameters
NUM_AGENTS = 200 # Total number of agents
TIME_STEPS = 1000 # Total number of days to simulate
S0, I0, R0 = 198, 2, 0 # Initial counts of S, I, R
3
# State Encoding
SUSCEPTIBLE = 0
INFECTED = 1
RECOVERED = 2
"""
# Generate uniform distribution within a circle
r = city_radius * np.sqrt(np.random.uniform(0, 1, num_agents))
theta = np.random.uniform(0, 2 * np.pi, num_agents)
x = r * np.cos(theta)
y = r * np.sin(theta)
positions = np.array((x, y)).T
# Assign states
states = np.array([SUSCEPTIBLE]*S0 + [INFECTED]*I0 + [RECOVERED]*R0)
np.random.shuffle(states) # Shuffle to randomize initial infected
return positions, states
return new_positions
4
recovered_indices = np.where(states == RECOVERED)[0]
neighbors = tree.query_ball_point(positions[susceptible_indices],␣
↪infection_radius)
# Update states
states[new_infections] = INFECTED
states[recoveries] = RECOVERED
states[lose_immunity] = SUSCEPTIBLE
return states
def simulate():
# Initialize agents
positions, states = initialize_agents(NUM_AGENTS, CITY_RADIUS, S0, I0, R0)
for t in range(TIME_STEPS):
# Move agents
positions = move_agents(positions, SIGMA, CITY_RADIUS)
5
states = update_states(positions, states, ALPHA, BETA, GAMMA,␣
↪INFECTION_RADIUS)
# counts
S_counts.append(np.sum(states == SUSCEPTIBLE))
I_counts.append(np.sum(states == INFECTED))
R_counts.append(np.sum(states == RECOVERED))
# Plot
plt.figure(figsize=(12, 6))
plt.plot(S_counts, label='Susceptible', color='blue')
plt.plot(I_counts, label='Infected', color='red')
plt.plot(R_counts, label='Recovered', color='green')
plt.xlabel('Day')
plt.ylabel('Number of Agents')
plt.title('SIR Model Simulation with Random Movement in a Circular City')
plt.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
simulate()
import numpy as np
import matplotlib.pyplot as plt
6
def simulate_epidemic(N, T, alpha, beta, gamma, initial_state=None):
"""
Simulate epidemic spread using probabilistic model
Parameters:
N: number of agents
T: time steps
alpha: probability of S->I transition
beta: probability of I->R transition
gamma: probability of R->S transition
initial_state: initial state distribution (optional)
"""
# Set parameters
N = 1000 # number of agents
T = 500 # time steps
7
alpha = 0.05 # infection probability
beta = 0.01 # recovery probability
gamma = 0.001 # immunity loss probability
# Run simulation
S, I, R = simulate_epidemic(N, T, alpha, beta, gamma)
# Plot results
plt.figure(figsize=(10, 6))
plt.plot(S, label='Susceptible', color='blue')
plt.plot(I, label='Infected', color='red')
plt.plot(R, label='Recovered', color='green')
plt.xlabel('Time')
plt.ylabel('Estimated Probability')
plt.title(f'Probabilistic SIR Model (alpha={alpha}, Beta={beta}, gamma={gamma},␣
↪N={N})')
plt.legend()
plt.grid(True)
plt.show()
#-----------------------
# Computing proportions ------------------------------------################
#-----------------------
'''
Pt+1(S) = gamma*Pt(R) + (1 - alpha)*Pt(S)
Pt+1(I) = alpha*Pt(S) + (1 - Beta)*Pt(I)
Pt+1(R) = beta*Pt(I) + (1 - gamma)*Pt(R)
Try interpreting these equations in terms of proportions instead of
probabilities
'''
"""
Simulate the SIR model in terms of proportions.
8
Parameters:
N: total population (not used directly in proportions calculation)
T: number of time steps
alpha: probability of S -> I transition
beta: probability of I -> R transition
gamma: probability of R -> S transition
initial_proportions: initial proportions of S, I, R (optional)
Returns:
Proportions of S, I, R over time.
"""
# Initialize proportions
if initial_proportions is None:
a = 0.99 # Initial proportion of Susceptible
b = 0.01 # Initial proportion of Infected
c = 0.0 # Initial proportion of Recovered
else:
a, b, c = initial_proportions
S_proportions[t] = a
I_proportions[t] = b
R_proportions[t] = c
# Set parameters
N = 1000 # Total population (not directly used)
T = 500 # Number of time steps
alpha = 0.05 # Infection probability
9
beta = 0.01 # Recovery probability
gamma = 0.001 # Immunity loss probability
# Run simulation
S, I, R = simulate_sir_proportions(N, T, alpha, beta, gamma)
# Plot results
plt.figure(figsize=(10, 6))
plt.plot(S, label='Susceptible', color='blue')
plt.plot(I, label='Infected', color='red')
plt.plot(R, label='Recovered', color='green')
plt.xlabel('Time Steps')
plt.ylabel('Proportion of Population')
plt.title(f'Probabilistic SIR Model (alpha={alpha}, Beta={beta},␣
↪gamma={gamma})')
plt.legend()
plt.grid(True)
plt.ylim(0, 1)
plt.show()
10
Recovered (c): 0.893
[ ]:
11