# Evaluation and calculation of curves to match Fourier coefficinets
# Erdas IMG rasters are uploaded and curves are calculated for each single pair of coordinates
# This script importas images in Erdas propietary format (but can easily adapted to importa other formats, read the help for th epackage "raster")
# and exports as ".asc" images.
# Concept and programming by A. Estrada-Pe??a (2013)
#
library(sp)
library(raster)
library(maptools)
library(TSA)
library(SDMTools)
library(matlab)
library(rgdal)
library(zoo)

x1 <- "~/Documents/Cosas/MODIS_Fourier/Todas/TDia/" # the directory where images downloaded from MODIS repository are
capas1 <- stack()
for (intervalo in seq(2002,2010,by=1)) # In this example, the interval to calculate the coefficients is between the years 2002 to 2010
{
  print(intervalo)
  for (mes in 1:12)
  {
    x <- paste(x1,intervalo,mes,"td.img",sep="")
    Textra <- raster(x); NAvalue(Textra) <- 99999
    capas1 <- addLayer(capas1,Textra)
  }
}
matriz1 <- as.data.frame(capas1)
x.model <- matrix(data=0,nc=17,nr=nrow(matriz1))
z <- which(is.na(matriz1[,1]))     ### filling the sea water masses; just a way to imrpove the time of computations
x.model[z,] <- -9999               ###
for (i in 1:6480000) ### filling the rest of the pixels of the images; change the maximum value according to dimensions of your images
{
  if (i%%500==0)
  {
    print(i*100/5364000)
  }
  if (x.model[i,1]!=-9999)
  {
    if (length(which(is.na(matriz1[i,])))<3)
    {
    previo <- as.vector(matriz1[i,1:108],mode="numeric")
    previo <- append(previo,previo,after=length(previo))
    narigon <- (na.approx(previo[1:23]))
    narigon <- t(matriz1[i,])
    mipolla <- ts(narigon[1:108],start=c(2001,1),frequency=108) # obviously the frequency depends on the number of time intervals; change as necessary
    har <- harmonic(mipolla,8)
    x.model[i,] <- coef(lm(mipolla~har))
    }
    else
      x.model[i,] <- -9999
  }
}
setwd("~/Desktop") ## point to the directory to write the results (replace as necessary)
for (i in 1:17)
{
  nombre <- c(paste("ParamTDay_",i,".asc",sep="")) # each image is stored in the directory as the number of coefficient ("i") for TDay (day temperature)
  matriz <- matrix(x.model[,i],3600,1800)
  matriz2 <- fliplr(matriz)
  imagen <- as.asc(matriz2,xll=-179.75,yll=-89.75,cellsize=0.1)
  write.asc(imagen,nombre,gz=FALSE)
}