#Zakladna normalizacia

# Vygeneruj 1000 permutovanych matic, permutaciu robi funkcia sample()
require("gplots")

#Osativa_323_v7.0_fragments_toHiC_All.tab
#Athaliana_167_fragments_toHiC_All2.tab

path_to_tab<-"/Users/biomonika/Desktop/VYZKUM/normalize_families/Osativa_323_v7.0_fragments_toHiC_All.tab"
tab<-as.data.frame(read.table(path_to_tab, sep="\t", header=TRUE))

filename<-basename(path_to_tab)
print(colnames(tab))

tab <- tab[which((tab$chr1 == tab$chr2) & ((as.numeric(tab$pos1)-as.numeric(tab$pos2)) > 1000000) | (tab$chr1 != tab$chr2)),]

tab_sample <- table(sample(tab$family1),sample(tab$family2))
num <- 1000
list_of_samples <-list()
for(i in 1:num) {
  list_of_samples[[i]] <- table(sample(tab$family1),sample(tab$family2))
}


data_for_heatmap<-table(tab$family1,tab$family2) #Tabulka z realnych dat
control_for_heatmap<-Reduce(`+`, list_of_samples) / length(list_of_samples) #Priemerne hodnoty spocitane pre 1000 matic vytvorenych pomocou sample

#find shared columns and rows
shared_families_columns<-intersect(colnames(data_for_heatmap),colnames(control_for_heatmap))
shared_families_rows<-intersect(rownames(data_for_heatmap),rownames(control_for_heatmap))
shared_families<-intersect(shared_families_columns,shared_families_rows)

#subset to shared columns and rows
data_for_heatmap<-data_for_heatmap[shared_families,shared_families]
control_for_heatmap<-control_for_heatmap[shared_families,shared_families]
list_of_samples_subsetted<-lapply(list_of_samples,function(x) {x[shared_families,shared_families]})

#create an empty matrix and fill it with calculated p-values for each pair of families
m<-matrix(, nrow = length(rownames(data_for_heatmap)), ncol = length(colnames(data_for_heatmap)))

for(col in 1:length(colnames(data_for_heatmap))) { 
  for(row in 1:length(rownames(data_for_heatmap))) { 
  simulated_values<-sapply(list_of_samples_subsetted,function(x) {x[row,col]})
  obtained_value<-data_for_heatmap[row,col]
  p_value<-t.test(simulated_values,mu=obtained_value,alternative="less")$p.value
  m[row,col]<-round(p_value,4)
  }
}

#our alpha threshold needs to be adjusted to account for multiple testing
alpha_adjusted<-0.05/length(as.numeric(m))
m_significant<-m<alpha_adjusted
print(table(m_significant))

print(dim(data_for_heatmap))
print(dim(control_for_heatmap))

#the dimensions between the data and control must match
stopifnot(colnames(data_for_heatmap)==colnames(control_for_heatmap))
stopifnot(rownames(data_for_heatmap)==rownames(control_for_heatmap))

data_to_plot<-log(data_for_heatmap+0.01)-log(control_for_heatmap+0.01) #compare real values with the controls

png(file = paste0(filename,".sample.","heatmap.png"), units="in", width=5, height=5, res=300)
stopifnot(colnames(data_to_plot)==rownames(data_to_plot))
alphabetical_order<-sort(colnames(data_to_plot))
par(cex.main=0.55)
heatmap.2(data_to_plot[,alphabetical_order],dendrogram="none", na.color="black", cexRow=0.1,cexCol=0.1, Colv=FALSE, Rowv=FALSE, scale="none", trace="none", symm=TRUE, margins=c(8,8), main=paste0("\nNormalized HiC contact frequency\nbetween families (DIST)\n",filename), xlab="Repeat family", ylab="Repeat family")
dev.off()  ## file in the current dir

#indices at which the p-values were significant
significant_indices<-which(m_significant==TRUE,arr.ind=TRUE)

#for indices with significant pairs, format the information about them
formatSignificantFamily<-function(coordinates) {
  row_Index<-coordinates[1]
  col_Index<-coordinates[2]
  row_name<-rownames(data_to_plot)[row_Index]
  col_name<-colnames(data_to_plot)[col_Index]
  entry<-data_to_plot[row_Index,col_Index]
  pval<-m[row_Index,col_Index]
  return(list(row_name,col_name,entry,pval))
}

#create a table with names of significant families, their normalized contact frequency, and their p-values
significant_families_and_their_pvalues<-as.data.frame(do.call(rbind, apply(significant_indices, 1, function(x) {formatSignificantFamily(x)})))
colnames(significant_families_and_their_pvalues)<-c("family1","family2","contact_freq","p-value")

#order based on the contact frequency
significant_families_and_their_pvalues<-as.data.frame(apply(significant_families_and_their_pvalues, 2, unlist))
significant_families_and_their_pvalues<-significant_families_and_their_pvalues[order(significant_families_and_their_pvalues$contact_freq,decreasing=TRUE),]

significant_families_and_their_pvalues<-apply(significant_families_and_their_pvalues,2,as.character)
write.table(significant_families_and_their_pvalues, file = paste0(filename,".sample.","significant_families_and_their_pvalues.txt"), sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE)


