Certainly! If you want to plot the final number of infections for each beta value using your existing simulation function sim_sir, you can modify the code to correctly count the number of unique nodes that got infected during the simulation. Here’s the corrected code:
# Load necessary libraries
library(tidyverse)
library(igraph)
# Assuming 'graph_undirected' is already defined
# graph_undirected <- ...
# SIR simulation function
sim_sir <- function(g, beta, mu, seeds) {
state <- rep(0, vcount(g))
state[seeds] <- 1
t <- 0
table <- data.frame(t = 0, inf = seeds)
while(sum(state == 1) > 0) {
t <- t + 1
new_inf <- c()
for(i in which(state == 1)) {
neighbors <- neighbors(g, i, mode = "out")
for(j in neighbors) {
if(state[j] == 0 && runif(1) < beta) {
new_inf <- c(new_inf, j)
}
}
if(runif(1) < mu) {
state[i] <- 2
}
}
state[new_inf] <- 1
if(length(new_inf) > 0) {
table <- rbind(table, data.frame(t = t, inf = new_inf))
}
}
table
}
# Parameters
mu <- 0.1
beta_values <- seq(0.01, 0.2, 0.01)
set.seed(123)
num_seeds <- ceiling(0.01 * vcount(graph_undirected))
# Run simulations for multiple beta values and count unique infections
results <- map_dfr(beta_values, ~{
beta <- .x
seeds <- sample(1:vcount(graph_undirected), num_seeds)
realization <- sim_sir(graph_undirected, beta, mu, seeds)
unique_infected <- unique(realization$inf)
data.frame(beta = beta, ninf = length(unique_infected))
})
# Plot the final number of infections for each beta value
results %>%
ggplot(aes(x = beta, y = ninf)) +
geom_point() +
labs(title = "Final Number of Infections for Different Beta Values",
x = "Beta Value",
y = "Number of Unique Infected Nodes") +
theme_minimal()
Explanation:
-
Simulation Function (sim_sir):
- This function remains the same as your original function. It simulates the SIR model and returns a data frame with the time and node ID when each node gets infected.
-
Running Simulations for Multiple Beta Values:
- The
map_dfr function is used to iterate over the beta values.
- For each beta value, seeds are sampled, and the simulation is run.
- The unique infected nodes are extracted using
unique(realization$inf), and their count is stored in ninf.
-
Plotting:
- The results are plotted using
ggplot2 to show the number of unique infected nodes (ninf) against each beta value.
This code will generate a scatter plot showing the final number of unique infections for each beta value in your SIR model.