Skip to content

Instantly share code, notes, and snippets.

@JHoogink
Forked from chengjun/network_diffusion.R
Last active November 25, 2015 09:28
Show Gist options
  • Save JHoogink/d532f9c519a2ba97b100 to your computer and use it in GitHub Desktop.
Save JHoogink/d532f9c519a2ba97b100 to your computer and use it in GitHub Desktop.
require(igraph)
# generate a social graph
node_number = 100
g = barabasi.game(node_number) ; plot(g)
seeds_num = 1
set.seed(2014); diffusers = sample(V(g),seeds_num) ; diffusers
infected =list()
infected[[1]]= diffusers
# for example, set percolation probability
transmission_rate = 0.4
coins = c(1, 0)
probabilities = c(transmission_rate, 1-transmission_rate )
# sample(coins, 1, rep=TRUE, prob=probabilities) # Generate a sequence
# toss the coins
toss = function(freq) {
tossing = NULL
for (i in 1:freq ) tossing[i] = sample(coins, 1, rep=TRUE, prob=probabilities)
tossing = sum(tossing)
return (tossing)
}
update_diffusers = function(diffusers){
nearest_neighbors = data.frame(table(unlist(neighborhood(g, 1, diffusers))))
nearest_neighbors = subset(nearest_neighbors, !(nearest_neighbors[,1]%in%diffusers))
keep = unlist(lapply(nearest_neighbors[,2], toss))
new_infected = as.numeric(as.character(nearest_neighbors[,1][keep >= 1]))
class(new_infected) <- "igraph.vs" #### this is add to the code of chengjun
diffusers = unique(c(diffusers, new_infected))
return(diffusers)
}
total_time = 1
while(length(infected[[total_time]]) < node_number){
infected[[total_time+1]] = sort(update_diffusers(infected[[total_time]]))
cat(length(infected[[total_time+1]]), "-->")
total_time = total_time + 1
}
plot_time_series = function(infected, m){
num_cum = unlist(lapply(1:m,
function(x) length(infected[[x]]) ))
p_cum = num_cum/node_number
p = diff(c(0, p_cum))
time = 1:m
plot(p_cum~time, type = "b",
ylab = "CDF", xlab = "Time",
xlim = c(0,total_time), ylim =c(0,1))
}
plot_time_series(infected, length(infected))
@JHoogink
Copy link
Author

Modified the version of chengjun's

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment