
# MATA271 Tietokoneharjoitus 2
# Lasse Leskelä 2011-10-14
#
# Skripti ajetaan komennolla source('EpidemicExample.R')
#
# Tarvittaessa R:n muuttujat voi nollata komennolla
# rm(list = ls())
#

# Aikahorisontti
T <- 10

# Verkko
m <- 10
source('SquareLatticeGraph.R')
L <- SquareLatticeGraph(m)
n <- m^2

# Tartunta-tn
p <- .9

# Tilamuuttujien alustus
S <- 2:n
I <- c(1)
R <- integer(0)

# Epidemian dynamiikka
for (t in 1:T) {

  # Tartunta: Lasketaan I_new eli tartuttavat t:nnen vaiheen lopussa
  I_new <- integer(0)
  for (i in I) {
    N <- which(L[i,] == 1)
    Targets <- intersect(N,S);
    count_Targets <- length(Targets)
    if (count_Targets == 1) {
      count_C <- rbinom(1,count_Targets,p)
      if (count_C == 1) {
        I_new <- union(I_new,Targets);
      }
    }
    if (count_Targets > 1) {
      count_C <- rbinom(1,count_Targets,p);
      C <- sample(Targets, count_C);
      I_new <- union(I_new,C);
    }
  }

  # Tartunta: Lasketaan S_new eli alttiit t:nnen vaiheen lopussa
  S_new <- setdiff(S,I_new)

  # Paraneminen: Lasketaan R_new eli parantuneet t:nnen vaiheen lopussa.
  R_new <- union(R,I)

  # Päivitetään tilamuuttujat uusiin arvoihinsa.
  S <- S_new
  I <- I_new
  R <- R_new
}
