install.packages("igraph")
install.packages("animation")
library(igraph)
library(animation)

NodeSize = 1000
rho = 0.3
I2Rtime = 5

pal = c("gray80","black","gray50")
pal = c("gray80","red","blue")
#ga <- sample_smallworld(dim=1, size=NodeSize, nei=2, p=0.01)
#ga <- sample_smallworld(dim=1, size=NodeSize, nei=2, p=0)
#ga <- sample_pa(n=NodeSize, power=1, m=1, directed=F)
ga <- sample_pa(n=NodeSize, power=1, m=2, directed=F)

el <- as_edgelist(ga)
NS_now <- numeric(NodeSize)
NS_time <- numeric(NodeSize)
NS_now[1] <- 1
NS_time[1] <- I2Rtime
pd <- NULL


#l <- layout_in_circle(ga)
l <- layout_with_fr(ga)
plot(ga, layout=l, vertex.label.color="black", vertex.label=NA, vertex.size=5, vertex.frame.color=NA, vertex.color=pal[NS_now+1],main=as.character(t))

ani.record(reset = TRUE)

for (t in 1:500) {
  plot(ga, layout=l, vertex.label.color="black", vertex.label=NA, vertex.size=5, vertex.frame.color=NA, vertex.color=pal[NS_now+1],main=as.character(t))
  ani.record()
  
  n0 <- length(which(NS_now==0))
  n1 <- length(which(NS_now==1))
  n2 <- length(which(NS_now==2))
  
  pd1 <- c(t,n0/NodeSize,n1/NodeSize,n2/NodeSize)
  pd <- rbind(pd,pd1)
  print(pd1)
  
  if(n1==0){
    break
  }

    for (i in 1:NodeSize) {
    if(NS_time[i]>0){
      NS_time[i] <- NS_time[i] -1
      if(NS_time[i]==0){
        NS_now[i] <- 2
      }
    }
    }
  
  NS_next <- NS_now
  for (i in 1:nrow(el)) {
    id1 <- el[i,1]
    id2 <- el[i,2]
    if(NS_now[id1]==1 && NS_now[id2]==0){
        if(runif(1)<rho){
        NS_next[id2]<- 1
        NS_time[id2] <- I2Rtime
      }
    }
    if(NS_now[id2]==1 && NS_now[id1]==0){
      if(runif(1)<rho){
        NS_next[id1]<- 1
        NS_time[id1] <- I2Rtime
      }
    }
  }
  NS_now <- NS_next

  
}
matplot(pd[,1],pd[,2:4],pch=1:3,ylim=c(0,1),xlim=c(0,50),col="black")
save(pd, file="data.rda")
#load("data.rda")
oopts = ani.options(interval = 0.1)
saveHTML(ani.replay(), img.name = "record_plot")
saveGIF(ani.replay(), img.name = "record_plot")


