All Inone Code

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

All inone code

October 30, 2024

[8]: # SIR -- Deterministic model

import numpy as np
import matplotlib.pyplot as plt

def SIR_model(S, I, R, beta, gamma, N):


'''
The simple SIR model :
S = Susceptible
I = Infected
R = Recovered
N = total population
beta, gamma = infection rate, recovery rate respectively
'''
dSdt = -beta*S*I / N
dIdt = beta*S*I / N - gamma*I
dRdt = gamma*I
return dSdt, dIdt, dRdt

# Runge kutta method for simple SIR model.


def rk4(SIR_model, S_values, I_values, R_values, t0, tf, dt, beta, gamma, N):
steps = int((tf - t0) / dt) + 1

t = np.linspace(t0, tf, steps)


S = np.zeros(steps)
I = np.zeros(steps)
R = np.zeros(steps)
S[0]=S_values
I[0]=I_values
R[0]=R_values

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)

k3S,k3I,k3R = SIR_model(S[i-1] + 0.5 * dt * k2S, I[i-1] + 0.5 * dt *␣


↪k2I, R[i-1] + 0.5 * dt * k2R, 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)

S[i] = S[i-1] + (dt / 6) * (k1S + 2 * k2S + 2 * k3S + k4S)


I[i] = I[i-1] + (dt / 6) * (k1I + 2 * k2I + 2 * k3I + k4I)
R[i] = R[i-1] + (dt / 6) * (k1R + 2 * k2R + 2 * k3R + k4R)
return t,S,I,R

S_values = 198 # 90% susceptible


I_values = 2 # 10% infected
R_values = 0 # initially - 0 recovery
N = S_values+I_values

# 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.plot(t, S, "blue", label="Susceptible")


plt.plot(t, I, "red", label="Infected")
plt.plot(t, R, "green", label="Recovered")

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

def initialize_agents(num_agents, city_radius, S0, I0, R0):


"""
Initialize agents uniformly within the circular city and assign initial␣
↪states.

"""
# 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

def move_agents(positions, sigma, city_radius):


# Gaussian displacement
displacements = np.random.normal(0, sigma, positions.shape)
new_positions = positions + displacements

# Compute distances from center


distances = np.linalg.norm(new_positions, axis=1)

# Find agents outside the city


outside = distances > city_radius
num_outside = np.sum(outside)
if num_outside > 0:
# Teleport outside agents to random positions inside the city
r = city_radius * np.sqrt(np.random.uniform(0, 1, num_outside))
theta = np.random.uniform(0, 2 * np.pi, num_outside)
new_x = r * np.cos(theta)
new_y = r * np.sin(theta)
new_positions[outside] = np.array((new_x, new_y)).T

return new_positions

def update_states(positions, states, alpha, beta, gamma, infection_radius):


# Separate indices by state
susceptible_indices = np.where(states == SUSCEPTIBLE)[0]
infected_indices = np.where(states == INFECTED)[0]

4
recovered_indices = np.where(states == RECOVERED)[0]

# Build KDTree for efficient neighbor search


if len(infected_indices) > 0 and len(susceptible_indices) > 0:
tree = KDTree(positions[infected_indices])
# For each susceptible agent, find if any infected agent is within␣
↪infection_radius

neighbors = tree.query_ball_point(positions[susceptible_indices],␣
↪infection_radius)

# Determine which susceptible agents have at least one neighbor


potentially_infected = np.array([len(n) > 0 for n in neighbors])
# Susceptible agents that are close to at least one infected agent
susceptible_close = susceptible_indices[potentially_infected]
# Determine which of these become infected based on probability alpha
new_infections = susceptible_close[np.random.uniform(0, 1,␣
↪len(susceptible_close)) < alpha]

# Update states
states[new_infections] = INFECTED

# Infected agents recover with probability beta


if len(infected_indices) > 0:
recoveries = infected_indices[np.random.uniform(0, 1,␣
↪len(infected_indices)) < beta]

states[recoveries] = RECOVERED

# Recovered agents lose immunity with probability gamma


if gamma > 0 and len(recovered_indices) > 0:
lose_immunity = recovered_indices[ np.random.uniform(0, 1,␣
↪len(recovered_indices)) < gamma]

states[lose_immunity] = SUSCEPTIBLE

return states

def simulate():
# Initialize agents
positions, states = initialize_agents(NUM_AGENTS, CITY_RADIUS, S0, I0, R0)

# Lists to record daily counts


S_counts = []
I_counts = []
R_counts = []

for t in range(TIME_STEPS):
# Move agents
positions = move_agents(positions, SIGMA, CITY_RADIUS)

# Update states based on interactions and transitions

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()

[11]: # SIR model -- Stochastic model II

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)
"""

# Define transition probability matrix


P = np.array([
[1-alpha, alpha, 0], # S -> S, I, R
[0, 1-beta, beta], # I -> S, I, R
[gamma, 0, 1-gamma] # R -> S, I, R
])

# Initialize states (0=S, 1=I, 2=R)


states = np.zeros((N, T), dtype=int)

# Set initial states randomly if not provided


if initial_state is None:
states[:, 0] = np.random.choice([0, 1, 2], size=N)
else:
states[:, 0] = initial_state

# Simulate for each time step


for t in range(1, T):
for agent in range(N):
current_state = states[agent, t-1]
# Sample next state based on transition probabilities
states[agent, t] = np.random.choice(3, p=P[current_state])

# Calculate proportions for each time step


S_prop = np.mean(states == 0, axis=0)
I_prop = np.mean(states == 1, axis=0)
R_prop = np.mean(states == 2, axis=0)

return S_prop, I_prop, R_prop

# 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()

# Calculate theoretical steady state values


denominator = (1/gamma + 1/beta + 1/alpha)
a = (1/alpha) / denominator # Susceptible
b = (1/beta) / denominator # Infected
c = (1/gamma) / denominator # Recovered

print("\nTheoretical steady state values:")


print(f"Susceptible (a): {a:.3f}")
print(f"Infected (b): {b:.3f}")
print(f"Recovered (c): {c:.3f}")

#-----------------------
# 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
'''

def simulate_sir_proportions(N, T, alpha, beta, gamma,␣


↪initial_proportions=None):

"""
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

# Arrays to store proportions over time


S_proportions = np.zeros(T)
I_proportions = np.zeros(T)
R_proportions = np.zeros(T)

# Set initial proportions


S_proportions[0] = a
I_proportions[0] = b
R_proportions[0] = c

# Simulate over T time steps


for t in range(1, T):
a = gamma * R_proportions[t-1] + (1 - alpha) * S_proportions[t-1]
b = alpha * S_proportions[t-1] + (1 - beta) * I_proportions[t-1]
c = beta * I_proportions[t-1] + (1 - gamma) * R_proportions[t-1]

S_proportions[t] = a
I_proportions[t] = b
R_proportions[t] = c

return S_proportions, I_proportions, R_proportions

# 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()

Theoretical steady state values:


Susceptible (a): 0.018
Infected (b): 0.089

10
Recovered (c): 0.893

[ ]:

11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy