Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. library(dplyr)
  2. library(cowplot)
  3. library(deSolve)
  4. set.seed(1234)
  5. SIRsim <- function(beta,gamma){
  6. mat <- matrix(0,12,12)
  7. mat[sample(2:11,1),sample(2:11,1)] <- 1
  8. out <- vector("list",100)
  9. out[[1]] <- mat[2:11,2:11]
  10. for(t in 2:100){
  11. for(i in 2:11){
  12. for(j in 2:11){
  13. #I ->R
  14. if(mat[i,j]==1){mat[i,j] <- rbinom(1,1,gamma)+1}
  15. #S -> I
  16. if(mat[i-1,j]==1 & mat[i,j]==0){mat[i,j] <- rbinom(1,1,beta)}
  17. if(mat[i+1,j]==1 & mat[i,j]==0){mat[i,j] <- rbinom(1,1,beta)}
  18. if(mat[i,j-1]==1 & mat[i,j]==0){mat[i,j] <- rbinom(1,1,beta)}
  19. if(mat[i,j+1]==1 & mat[i,j]==0){mat[i,j] <- rbinom(1,1,beta)}
  20. }
  21. }
  22. out[[t]] <- mat[2:11,2:11]
  23. }
  24. SIR <-data.frame(time=1:100,
  25. S =sapply(out,function(x)sum(x==0)),
  26. I =sapply(out,function(x)sum(x==1)),
  27. R =sapply(out,function(x)sum(x==2))) %>%
  28. tidyr::gather(state,populations,-time) %>%
  29. mutate(state=factor(state,levels=c("S","I","R")))
  30. return(list(matlist=out,SIR=SIR))
  31. }
  32.  
  33. res_sim <- SIRsim(0.1,0.01)
  34.  
  35. p2 <-ggplot(res_sim$SIR,aes(x=time,y=populations,colour=state))+
  36. geom_line(size=1)
  37.  
  38. ggsave("SIRsim.png",p2)
  39. # dat <-res_sim$SIR %>%
  40. # tidyr::spread(state,populations)
  41.  
  42. cols = c("white","grey30","grey70")
  43.  
  44. #i <-which.max(dat$S==0)
  45. library(animation)
  46. saveGIF({
  47. for(i in 1:100){
  48. tmp <-res_sim$matlist[[i]] %>%
  49. as.data.frame() %>%
  50. data.table::setnames(LETTERS[1:10]) %>%
  51. mutate(col=factor(1:10)) %>%
  52. tidyr::gather(row,state,-col)
  53.  
  54. if(all(tmp$state!=2)){
  55. tmp_col= cols[1:2]
  56. }else if(all(tmp$state!=0)){
  57. tmp_col = cols[2:3]
  58. }else{
  59. tmp_col = cols[1:3]
  60. }
  61.  
  62. p1<-ggplot(tmp,aes(x=factor(col),y=factor(row),fill=factor(state)))+
  63. geom_tile()+
  64. scale_fill_manual(values = tmp_col)+
  65. theme(legend.position = "none")+
  66. xlab("")+ylab("")
  67. print(p1)
  68. }},interval=0.3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement