#########################################
# u_t - u_xx = 0,      x \in (0,1), t>0
# u(x,0) = (1/2)*x*(1-x),    x \in [0,1]
# u(0,t) = u(1,t) = 0, t>0
#########################################

# install.packages("animation")
library(animation)

# 1) Definicia funkcie u

u <- function(x,t,N){     # N clenov z nekonecnej sumy
  k <- 1:N
  alfa0 <- (2-2*(-1)^k)/(k^3 * pi^3)  # rozvoj zaciatocnej podmienky
  u <- rep(NA, times=length(x))
  for (i in 1:length(x)){
    alfa <- alfa0*exp(-k^2 * pi^2 * t)
    u[i] <- sum(alfa * sin(k * pi * x[i]))
  }
  return(u)
}

# 2) Priklad grafu

x <- seq(from=0,to=1,by=0.01)
plot(x, u(x,0,20), type="l")  # t=0
plot(x, u(x,1,20), type="l")  # t=1

# 3) Animacia

cas <- seq(from=0, to=0.2, by=0.01)
x <- seq(from=0,to=1,by=0.01)

ani.record(reset = TRUE)

for (i in 1:length(cas)) {
  plot(x, u(x,cas[i],20),col="blue",type="l",
       xlim=c(0,1),ylim=c(0,0.13),
       xlab="x", ylab="u(x,t)")
  ani.record()  
}

ani.options(interval = 0.25)
ani.replay()

# 4) Ulozenie animacie ako html 

saveHTML(ani.replay(), 
         img.name = "priklad1",       # ako sa ulozia obrazky
         htmlfile = "nuloveOP.html")  # nazov html suboru s animaciou
