# Script developed by HU GUANGAN and modified by SOURAV NAYAK
# 
# This R script is to calculate the gene periodicities of Rodent malaria transcriptomes using Fast Fourier Transform (FFT) technology
#
# In the R GUI, make sure that the Working Directory is set to the folder in which this script and the "infile.txt" are located
# [change the Working Directory via 'File'-'Change dir...']
#
# !!!!!!!!!! YOU HAVE TO ADJUST THE VALUES dd and id BELOW !!!!!!!!!
#
# !!!!!!!!!! Make sure in the input file MISSING DATA are represented by "NA" !!!!!!!!!
#
# THE OUTPUT of this script:
# - the 1st column contains consecutive serial numbers
# - the 2nd column contains the geneIDs
# - the next n columns contain some sort of data (with n being the number of data columns present in the infile)
# - the next 1 column contains ??
# - the next 1 column does contain the Fourier phase!!!!!!!!!!!!!!!!
#       (e.g. when you have 24 data columns, the Fourier phase will be in column #28 labeled "V28",
#       i.e. in Excel-sheet-column AB when the whole output is pasted into an Excel-sheet starting in column A)
#
# To be able to sort sensibly according to this phase you still have to:
#       - add pi to any negative values
#       - subtract pi from any positive value
#       - use e.g. this Excel formula: (=IF(AB2<0,AB2+3.14159,AB2-3.14159)  [to be pasted into cell AC2 with the Fourier phase being in cell AB2]
# Then sort according to the Fourier phase (typically in ASCENDING order = early upregulated genes/proteins first)
# Comments by Bernardo FOTH
#read original data; remember to change file name; include file with header and geneid data




#-------------------------------------
d <- read.table("Archna_all data_for_FFT.txt",header=TRUE,sep="\t",na.string="NA")
ni <- nrow(d)
nj <- ncol(d)



#starting column 1; dd represents 1st and last column data is read; id is column where geneid is 
data <- d[,2:nj]
id<-d[,1]
nh = (nj-1)/12
tt = names(data)



for(i in 1:nh)
{
  
  sp = (i-1) * 12 +1
  ep = sp + 12 - 1
  
  
  otfile = paste(tt[sp],"_phase.txt",sep="");
  subdata = data[,sp:ep]
  na_or_not = as.numeric(is.na(subdata[,1]))
  
  
  #center genes
  dcent = t(apply(subdata,1,function(y) (y-mean(y))))
  
  
  phase <- matrix(data=NA,nr=ni,nc=nj)
  phase = matrix(rep(0,ni*12),ncol=12,nrow=ni)
  dcent.fft = dcent[na_or_not==0,]
  
  
  #FFT analysis
  phase[na_or_not==0,] = t(apply(dcent.fft,1,function(y){ y.fft = fft(y); atan2(-Im(y.fft),Re(y.fft))}))
  
  
  ph = as.numeric(phase[,2])
  raw = ph
  ph[raw<0] = raw[raw<0]+pi
  ph[raw>0] = raw[raw>0]-pi
  # combine columns and output files; only extract 2nd phase & delete the rest
  d.out <-cbind(as.character(id),subdata,dcent,ph)
  write.table(d.out,file=otfile,sep="\t",dec=".",row.names=F)
  
  
}
