# run R in /home/mgoleb/Dokumenty/mycovir/all_clean/mapped on ptg1 (158.75.106.101)
library(ballgown)
library(genefilter)
library(dplyr)
library(RSkittleBrewer)
library(rtracklayer)

sampledata <- read.table("../mycovir_sampledata.csv", header=T, sep=",") # The file needs to be comma separated and read in with
rownames(sampledata) <- sampledata$ids
sampledata$Virus <- sub("pvy-", "", sampledata$Virus)


# Reading in stringtie GTF
mapped.gtf <- import("mycovir_soltu_stringtie.gtf")
mapped.gtf <- as.data.frame(mapped.gtf)

# Reading in functional annotation
func_annot <- read.table("DM_1-3_516_R44_potato.v6.1.working_models.func_anno.txt", header=F, sep="\t", col.names=c('transcript_id', 'annotation'))

# Reading in GO terms
# GO-Slim
go_terms <- read.table("DM_1-3_516_R44_potato.v6.1.working_models.goslim.txt", header=F, sep="", col.names=c('source', 'transcript_id', 'transcript_id1', 'go_term', 'tair', 'iea', 'level', 'feature_type', 'taxon', 'date', 'source1'))
go_terms$source <- NULL
go_terms$source1 <- NULL
go_terms$transcript_id1 <- NULL
go_terms$tair <- NULL
go_terms$iea <- NULL
go_terms$level <- NULL
go_terms$taxon <- NULL
go_terms$date <- NULL
go_terms_collapsed <- as.data.frame(go_terms %>% group_by(transcript_id) %>% summarise(go_terms_slim = paste(go_term, collapse=", ")))

# InterProScan
go_terms_iproscan <- read.table("DM_1-3_516_R44_potato.v6.1.working_models.iprscan_go_terms.txt", header=F, sep="\t", col.names=c("transcript_id", "go_terms_iproscan"))

# merging GO-Slim and InterProScan data
go_terms_final <- merge(go_terms_collapsed, go_terms_iproscan, by="transcript_id", all=T)

# Reading in potato genome GTF as GRangesList
annotated_gtf <- gffReadGR("potato_ref.gtf", splitByTranscript=T)

annot_final <- merge(go_terms_final, func_annot, by="transcript_id", all=T)


soltu_bg <- ballgown(dataDir=".", samplePattern="ballgown_")
sampledata <- sampledata[ sampleNames(soltu_bg), ]
identical( rownames(sampledata), sampleNames(soltu_bg)) # must be TRUE!
pData(soltu_bg) <- sampledata
soltu_bg_clean <- subset( soltu_bg, "!sampleNames(soltu_bg) %in% c('ballgown_A50_1', 'ballgown_P0_Fm_L1', 'ballgown_P0_C_L3', 'ballgown_P0_C_L1')", genomesubset=F)
soltu_texpr <- texpr(soltu_bg_clean, meas='FPKM')
soltu_texpr <- as.data.frame(t(soltu_texpr))
soltu_texpr_nonzero <- soltu_texpr[, colSums(soltu_texpr) > 0 ]
soltu_texpr_nonzero.nzv <- nearZeroVar(soltu_texpr_nonzero)
soltu_texpr_nonzero.lv <- soltu_texpr_nonzero[ , -soltu_texpr_nonzero.nzv$Position ] # large variance transcripts
rownames(soltu_texpr_nonzero.lv) <- sub('FPKM\\.', "", rownames(soltu_texpr_nonzero.lv))
sampledata <- sampledata[ rownames(sampledata) %in% sampleNames(soltu_bg_clean), ]

# mapping Stringtie-assembled transcripts to the reference ones
soltu_stringtie_to_potatoref <- annotate_assembly(assembled=structure(soltu_bg)$trans, annotated=annotated_gtf)


rownames(soltu_texpr) <- sub("FPKM.ballgown_", "", rownames(soltu_texpr))
soltu_texpr_t <- as.data.frame(t(soltu_texpr))
soltu_texpr_t$transcript_id <- rownames(soltu_texpr_t)
soltu_annot_texpr_t <- merge(soltu_texpr_t, annot_final, by="transcript_id")


soltu.bray.nmds <- metaMDS( soltu_texpr_nonzero.lv, k=2, dist='bray', try=100, trymax=500 )
palette(default);
svg("soltu.bray.nmds.svg", width=3.5, height=3.5, point=6)
par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
ordiplot(soltu.bray.nmds, type='none', main=""); 
points( soltu.bray.nmds, pch=21+as.numeric(as.factor(sampledata$Cultivar)), col=as.numeric(as.factor(sampledata$Virus)), bg=as.numeric(as.factor(sampledata$Organ)) ); 
ordiellipse(soltu.bray.nmds, display='sites', groups=as.factor(sampledata$Cultivar), label=T); 
legend('topright', legend=levels(as.factor(sampledata$Cultivar)), pch=21+sort(unique(as.numeric(as.factor(sampledata$Cultivar))))); 
dev.off(); 

sampledata <- sampledata[ rownames(soltu_texpr_nonzero.lv), ]
identical( rownames(sampledata), rownames(soltu_texpr_nonzero.lv) )

for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){ 
		for( infection in c('neg', 'pos') ){
			otutable <- paste0('soltu.', cultivar, '.', organ, '.', infection );
			envdata <- paste0('sdata.', cultivar, '.', organ, '.', infection );
#			assign(otutable, soltu_texpr_nonzero.lv[ sampledata$Cultivar == cultivar & sampledata$Organ == organ & sampledata$Virus == infection, ] );
#			assign(envdata, sampledata[ sampledata$Cultivar == cultivar & sampledata$Organ == organ & sampledata$Virus == infection, ] );
			for( distance in c('horn') ){
				ord <- paste0('soltu.', cultivar, '.', organ, '.', infection, '.', distance, '.nmds');
				file <- paste0('soltu.', cultivar, '.', organ,  '.', infection, '.', distance, '.nmds.svg');
				permanova <- paste0('soltu.', cultivar, '.', organ, '.', infection, '.', distance,'.adonis');
#				assign(ord, metaMDS(get(otutable), k=2, dist=distance, try=100, trymax=500));
				assign(permanova, adonis(get(otutable) ~ Inoculation, data=get(envdata), permu=999, method=distance));
				title <- paste0("NMDS on ", distance,  " distance matrix of ", cultivar," ", organ, " ", infection, " community", "\nPERMANOVA: p=", round(get(permanova)$aov.tab$"Pr(>F)"[1], 4));
				print( title );
				palette("default"); 
				svg( file, width=3.5, height=3.5, pointsize=6); 
				par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
				ordiplot(get(ord), type='none', main=title); 
				points( get(ord), pch=19+as.numeric(as.factor(get(envdata)$Inoculation)), col='black', bg=as.numeric(as.factor(get(envdata)$Inoculation)) ); 
				ordiellipse(get(ord), display='sites', groups=as.factor(get(envdata)$Inoculation), label=T); 
				legend('topright', legend=levels(as.factor(get(envdata)$Inoculation)), pch=19+sort(unique(as.numeric(as.factor(get(envdata)$Inoculation))))); 
				dev.off(); 
			}
		}
	}
}


for( organ in c('L', 'R') ){ 
	for( inoculation in c('C', 'Fm', 'Ri') ){
		otutable <- paste0('soltu.', organ, '.', inoculation );
		envdata <- paste0('sdata.', organ, '.', inoculation);
		assign(otutable, soltu_texpr_nonzero.lv[ sampledata$Organ == organ & sampledata$Inoculation == inoculation, ] );
		assign(envdata, sampledata[ sampledata$Organ == organ & sampledata$Inoculation == inoculation, ] );
		for( distance in c('horn') ){
			ord <- paste0('soltu.', organ, '.', inoculation, '.', distance, '.nmds');
			permanova <- paste0('soltu.', '.', organ, '.', inoculation, '.', distance, '.adonis');
			file <- paste0('soltu.', organ,  '.', inoculation, '.', distance, '.nmds.svg');
			title <- paste0("NMDS on ", distance,  " distance matrix of ", organ, " ", inoculation, " community", "\nPERMANOVA: p=", round(get(permanova)$aov.table$"Pr(>F)"[1], 4) );
			print( title );
			assign(ord, metaMDS(get(otutable), k=2, dist=distance, try=100, trymax=500));
			palette("default"); 
			svg( file, width=3.5, height=3.5, pointsize=6); 
			par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
			ordiplot(get(ord), type='none', main=title); 
			points( get(ord), pch=19+as.numeric(as.factor(get(envdata)$Virus)), col='black', bg=as.numeric(as.factor(get(envdata)$Virus)) ); 
			ordiellipse(get(ord), display='sites', groups=as.factor(get(envdata)$Virus), label=T); 
			legend('topright', legend=levels(as.factor(get(envdata)$Virus)), pch=19+sort(unique(as.numeric(as.factor(get(envdata)$Virus))))); 
			dev.off(); 
		}
	}
}


for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){ 
		for( inoculation in c('C', 'Fm', 'Ri') ){
			envdata <- paste0('sdata.', cultivar, ".", organ, '.', inoculation);
			otutable <- paste0('soltu.', cultivar, ".", organ, '.', inoculation );
#			assign(otutable, soltu_texpr_nonzero.lv[ sampledata$Cultivar == cultivar & sampledata$Organ == organ & sampledata$Inoculation == inoculation, ] );
#			assign(envdata, sampledata[ sampledata$Cultivar == cultivar & sampledata$Organ == organ & sampledata$Inoculation == inoculation, ] );			
			for( distance in c('horn') ){
				ord <- paste0('soltu.', cultivar, ".", organ, '.', inoculation, '.', distance, '.nmds');
				permanova <- paste0("soltu.", cultivar, ".", organ, ".", inoculation, ".", distance, ".adonis");
				file <- paste0('soltu.', cultivar, ".", organ,  '.', inoculation, '.', distance, '.nmds.svg');
#				assign(ord, metaMDS(get(otutable), k=2, dist=distance, try=100, trymax=500));
#				assign(permanova, adonis(get(otutable) ~ Virus, data=get(envdata), permu=999, method=distance));
				title <- paste0("NMDS on ", distance,  " distance matrix of ", cultivar, " ", organ, " ", inoculation, " community", "\nPERMANOVA: p=", round(get(permanova)$aov.tab$"Pr(>F)"[1], 4) );				
				palette("default"); 
				svg( file, width=3.5, height=3.5, pointsize=6); 
				par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
				ordiplot(get(ord), type='none', main=title); 
				points( get(ord), pch=19+as.numeric(as.factor(get(envdata)$Virus)), col='black', bg=as.numeric(as.factor(get(envdata)$Virus)) ); 
				ordiellipse(get(ord), display='sites', groups=as.factor(get(envdata)$Virus), label=T); 
				legend('topright', legend=levels(as.factor(get(envdata)$Virus)), pch=19+sort(unique(as.numeric(as.factor(get(envdata)$Virus))))); 
				dev.off(); 
			}
		}
	}
}



#### Differentially expressed transcripts identification

soltu_bg_highvar <- subset(soltu_bg_clean, "rowVars(texpr(soltu_bg)) > 1", genomesubset=T) # only transcripts with variance > 1


# Fungi influence
soltu_bg.Delikat.L.neg <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-neg'", genomesubset=F)
soltu_bg.Delikat.L.pos <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-pos'", genomesubset=F)
soltu_bg.Delikat.R.neg <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-neg'", genomesubset=F)
soltu_bg.Delikat.R.pos <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-pos'", genomesubset=F)
soltu_bg.Pirol.L.neg <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-neg'", genomesubset=F)
soltu_bg.Pirol.L.pos <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-pos'", genomesubset=F)
soltu_bg.Pirol.R.neg <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-neg'", genomesubset=F)
soltu_bg.Pirol.R.pos <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-pos'", genomesubset=F)

for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){ 
		for( inoculation in c('neg', 'pos') ){
			bg <- paste0("soltu_bg.", cultivar, '.', organ, ".", inoculation);
			file_t <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, ".Inoculation.DEtranscripts.significant.csv");
			file_g <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, ".Inoculation.DEgenes.significant.csv");
			result <- stattest(get(bg), feature='transcript', meas='FPKM', getFC=T, covariate="Inoculation");
			resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05, ];	
			write.table(resultsignificant, file_t, sep="\t");
			result <- stattest(get(bg), feature='gene', meas='FPKM', getFC=T, covariate="Inoculation");
			resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05 & (result$fc > 2 | result$fc < 0.5), ];	
			write.table(resultsignificant, file_g, sep="\t");
		}
	}
}

soltu_bg.Delikat.L.neg.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.L.neg.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Delikat.L.neg.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.L.pos.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.L.pos.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Delikat.L.pos.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.R.neg.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.R.neg.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Delikat.R.neg.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.R.pos.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Delikat.R.pos.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Delikat.R.pos.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.L.neg.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.L.neg.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Pirol.L.neg.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-neg' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.L.pos.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.L.pos.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Pirol.L.pos.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Virus == 'pvy-pos' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.R.neg.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.R.neg.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Pirol.R.neg.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-neg' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.R.pos.C_Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Fm')", genomesubset=F)
soltu_bg.Pirol.R.pos.C_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'C' | Inoculation == 'Ri')", genomesubset=F)
soltu_bg.Pirol.R.pos.Fm_Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Virus == 'pvy-pos' & (Inoculation == 'Ri' | Inoculation == 'Fm')", genomesubset=F)

soltu_transcripts <- data.frame( t_id = transcriptIDs(soltu_bg), t_name = transcriptNames(soltu_bg) )
soltu_transcripts <- merge(soltu_transcripts, soltu_stringtie_to_potatoref_filtered, by.x='t_id', by.y='assembledInd', all.x=T)
ref_transcript_id <- data.frame( ref_t_id = unlist(lapply(annotated_gtf, FUN= function(x) as.character(mcols(x)$transcript_id[1])) ), id=seq(1:length(annotated_gtf)) )
ref_transcript_id <- merge( ref_transcript_id, annot_final, by.x='ref_t_id', by.y='transcript_id', all.x=T)
soltu_stringtie_annot_transcripts <- merge(soltu_transcripts, soltu_stringtie_to_potatoref, by.x='t_id', by.y='assembledInd', all.x=T)




for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){ 
		for( inoculation in c('neg', 'pos') ){
			for( comp in c( 'C_Fm', 'C_Ri', 'Fm_Ri' ) ){
				cult1 <- strsplit(comp, '_')[[1]][1];
				cult2 <- strsplit(comp, '_')[[1]][2];
				bg <- paste0("soltu_bg.", cultivar, '.', organ, ".", inoculation, '.', comp);
				file_t <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, '.', comp, ".Inoculation.DEtranscripts.significant.csv");
				file_g <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, '.', comp, ".Inoculation.DEgenes.significant.csv");
				transDE <- paste0("soltu.", cultivar, ".", organ, ".", inoculation, ".", comp, "Inoculation.DEtranscripts");
				result <- stattest(get(bg), feature='transcript', meas='FPKM', getFC=T, covariate="Inoculation");
				print( transDE );
				result <- merge( result, soltu_stringtie_annot_transcripts, by.x='id', by.y='t_id', all.x=T)
				assign(transDE, merge( result, soltu_stringtie_annot_transcripts, by.x='id', by.y='t_id', all.x=T));
				resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05, ];	
				write.table(resultsignificant, file_t, sep="\t");
				result <- stattest(get(bg), feature='gene', meas='FPKM', getFC=T, covariate="Inoculation");
				resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05 & (result$fc > 2 | result$fc < 0.5),  ];	
				print( "geny" );
				write.table(resultsignificant, file_g, sep="\t");
			}
		}
	}
}


# Virus influence
soltu_bg.Delikat.L.C <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Inoculation == 'C'", genomesubset=F)
soltu_bg.Delikat.L.Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Inoculation == 'Fm'", genomesubset=F)
soltu_bg.Delikat.L.Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'L' & Inoculation == 'Ri'", genomesubset=F)
soltu_bg.Delikat.R.C <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Inoculation == 'C'", genomesubset=F)
soltu_bg.Delikat.R.Fm <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Inoculation == 'Fm'", genomesubset=F)
soltu_bg.Delikat.R.Ri <- subset(soltu_bg_highvar, "Cultivar == 'Delikat' & Organ == 'R' & Inoculation == 'Ri'", genomesubset=F)
soltu_bg.Pirol.L.C <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Inoculation == 'C'", genomesubset=F)
soltu_bg.Pirol.L.Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Inoculation == 'Fm'", genomesubset=F)
soltu_bg.Pirol.L.Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'L' & Inoculation == 'Ri'", genomesubset=F)
soltu_bg.Pirol.R.C <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Inoculation == 'C'", genomesubset=F)
soltu_bg.Pirol.R.Fm <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Inoculation == 'Fm'", genomesubset=F)
soltu_bg.Pirol.R.Ri <- subset(soltu_bg_highvar, "Cultivar == 'Pirol' & Organ == 'R' & Inoculation == 'Ri'", genomesubset=F)

for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){ 
		for( inoculation in c('C', 'Fm', 'Ri') ){
			bg <- paste0("soltu_bg.", cultivar, '.', organ, ".", inoculation);
			file_t <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, ".Virus.DEtranscripts.significant.csv");
			file_g <- paste0("soltu.", cultivar, '.', organ, ".", inoculation, ".Virus.DEgenes.significant.csv");
			result <- stattest(get(bg), feature='transcript', meas='FPKM', getFC=T, covariate="Virus");
			resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05, ];	
			write.table(resultsignificant, file_t, sep="\t");
			result <- stattest(get(bg), feature='gene', meas='FPKM', getFC=T, covariate="Virus");
			resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05 & ( result$fc > 2 | result$fc < 0.5), ];	
			write.table(resultsignificant, file_g, sep="\t");
		}
	}
}


###################### GO enrichment ########################
library(topGO)

# preparation of a gene universe (all genes names vector)
geneUniverse <- soltu_stringtie_annot_transcripts$t_name # all transcripts names

# preparation of GO data
GOannot <- data.frame(id=soltu_stringtie_annot_transcripts$t_name, GO=soltu_stringtie_annot_transcripts$go_terms_slim)
write.table(GOannot, "GOannot.csv", sep="\t", row.names=F, col.names=F, quote=F)
gene2GO <- readMappings("GOannot.csv", sep="\t", IDsep=",")

for( cultivar in c('Delikat', 'Pirol') ){
	for( organ in c('L', 'R') ){
		for( infection in c('neg', 'pos') ){
			for( inoculation in c("C_Fm", "C_Ri", "Fm_Ri") ){
				DEresult <- paste0('soltu.', cultivar, '.', organ, '.', infection, '.', inoculation, 'Inoculation.DEtranscripts');
				significant <- get(DEresult)[ !is.na(get(DEresult)$qval) & get(DEresult)$qval < 0.05 & (get(DEresult)$fc >= 2 | get(DEresult)$fc <= 0.5), ]
 				geneList <- factor(as.integer( geneUniverse %in% significant$t_name.x ))
				names(geneList) <- geneUniverse
				if( nrow(significant) > 3 ){
					for( ontology in c("MF", "BP", "CC") ){
						results <- paste0("soltu.", cultivar, ".", organ, ".", infection, ".", inoculation, ".", ontology);
						file <- paste0(results, ".csv");
						top_go_data <- new( "topGOdata", ontology=ontology, allGenes = geneList, annot = annFUN.gene2GO, gene2GO = gene2GO );
						allGO <- usedGO(top_go_data);
						results_weight01 <- runTest(top_go_data, algorithm="weight01", statistic="fisher");
						results_classic <- runTest(top_go_data, algorithm="classic", statistic="fisher");
						results_elim <- runTest(top_go_data, algorithm="elim", statistic="fisher");
						assign( results, GenTable(top_go_data, weight01=results_weight01, classic=results_classic, elim=results_elim, orderBy="weight01", topNodes=length(allGO), numChar=1000) );
						write.table(get(results), file, sep="\t")
					}
				}
			}
		}
	}
}


##### Analysis without PVY transcripts ###################

batch1_bg_nopvy <- subset(soltu_bg_highvar, "gene_id != 'MSTRG.2'", genomesubset=T) # PVY removed
batch1_bg_nopvy <- subset(batch1_bg_nopvy, "gene_id != 'MSTRG.1'", genomesubset=T) # PVY removed
batch1_bg_nopvy <- subset(batch1_bg_nopvy, "sampleNames(batch1_bg_nopvy) != 'ballgown_P0_C_L1'", genomesubset=F) # outlier removed
batch1_bg_nopvy <- subset(batch1_bg_nopvy, "sampleNames(batch1_bg_nopvy) != 'ballgown_P1_Ri_R3'", genomesubset=F)
sampledata_noP0_C_L1 <- sampledata[ rownames(sampledata) !="ballgown_P0_C_L1", ]
sampledata_noP0_C_L1 <- sampledata_noP0_C_L1[ rownames(sampledata_noP0_C_L1) !="ballgown_P1_Ri_R3", ]
rownames(sampledata_noP0_C_L1) <- sub("ballgown_", "", rownames(sampledata_noP0_C_L1))
batch1_nopvy_texpr <- texpr(batch1_bg_nopvy)
batch1_nopvy_texpr <- as.data.frame(t(batch1_nopvy_texpr))
rownames(batch1_nopvy_texpr) <- sub("FPKM.ballgown_", "", rownames(batch1_nopvy_texpr))
batch1_nopvy_texpr_nonzero <- batch1_nopvy_texpr[, colSums(batch1_nopvy_texpr) > 0 ]
identical(rownames(batch1_nopvy_texpr_nonzero), rownames(sampledata_noP0_C_L1)) # must be TRUE

for( organ in c('L', 'R') ){ 
	for( inoculation in c('C', 'Fm', 'Ri') ){
	otutable <- paste0("batch1_nopvy.", organ, ".", inoculation );
	print( otutable );
	sdata <- paste0("sdata.", organ, ".", inoculation);
	print( sdata );
	assign(otutable, batch1_nopvy_texpr_nonzero[ sampledata_noP0_C_L1$Organ == organ & sampledata_noP0_C_L1$Type == inoculation, ]); 
	assign(sdata, sampledata_noP0_C_L1[ sampledata_noP0_C_L1$Organ == organ & sampledata_noP0_C_L1$Type == inoculation, ]);
	}
}


for( organ in c('L', 'R') ){ 
	for( inoculation in c('C', 'Fm', 'Ri') ){
		for( distance in c('horn', 'bray') ){
			otutable <- paste0('batch1_nopvy.', organ, '.', inoculation );
			ord <- paste0('batch1_nopvy.', organ, '.', inoculation, '.', distance, '.nmds');
			permanova <- paste0('batch1_nopvy.', organ, '.', inoculation, '.', distance, '.adonis');
			file <- paste0('batch1_nopvy.', organ,  '.', inoculation, '.', distance, '.nmds.svg');
			envdata <- paste0('sdata.', organ, '.', inoculation);
			assign(ord, metaMDS(get(otutable), k=2, dist=distance, try=100, trymax=500));
			assign(permanova, adonis(get(otutable) ~ P, data=get(envdata), dist=distance, permu=999));
			title <- paste0("Metric: ", distance,  "; PERMANOVA p=", round(get(permanova)$aov.tab$"Pr(>F)"[1], digits=4), ", F=", round(get(permanova)$aov.tab$F.Model[1], digits=4), ", df=", get(permanova)$aov.tab$Df[1]);
			print( title );
			palette("default"); 
			svg( file, width=3.5, height=3.5, pointsize=6); 
			par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
			ordiplot(get(ord), type='none', main=title); 
			points( get(ord), pch=19+as.numeric(as.factor(get(envdata)$P)), col='black', bg=as.numeric(as.factor(get(envdata)$P)) ); 
			ordiellipse(get(ord), display='sites', groups=as.factor(get(envdata)$P), label=T); 
			legend('topright', legend=levels(as.factor(get(envdata)$P)), pch=19+sort(unique(as.numeric(as.factor(get(envdata)$P))))); 
			dev.off(); 
		}
	}
}

for( organ in c('L', 'R') ){ 
	for( inoculation in c('P0', 'P1') ){
	otutable <- paste0("batch1_nopvy.", organ, ".", inoculation );
	print( otutable );
	sdata <- paste0("sdata.", organ, ".", inoculation);
	print( sdata );
	assign(otutable, batch1_nopvy_texpr_nonzero[ sampledata_noP0_C_L1$Organ == organ & sampledata_noP0_C_L1$P == inoculation, ]); 
	assign(sdata, sampledata_noP0_C_L1[ sampledata_noP0_C_L1$Organ == organ & sampledata_noP0_C_L1$P == inoculation, ]);
	}
}


for( organ in c('L', 'R') ){ 
	for( inoculation in c('P0', 'P1') ){
		for( distance in c('horn', 'bray') ){
			otutable <- paste0('batch1_nopvy.', organ, '.', inoculation );
			ord <- paste0('batch1_nopvy.', organ, '.', inoculation, '.', distance, '.nmds');
			permanova <- paste0('batch1_nopvy.', organ, '.', inoculation, '.', distance, '.adonis');
			file <- paste0('batch1_nopvy.', organ,  '.', inoculation, '.', distance, '.nmds.svg');
			envdata <- paste0('sdata.', organ, '.', inoculation);
			assign(ord, metaMDS(get(otutable), k=2, dist=distance, try=100, trymax=500));
			assign(permanova, adonis(get(otutable) ~ Type, data=get(envdata), dist=distance, permu=999));
			title <- paste0("Metric: ", distance,  "; PERMANOVA p=", round(get(permanova)$aov.tab$"Pr(>F)"[1], digits=4), ", F=", round(get(permanova)$aov.tab$F.Model[1], digits=4), " df=", get(permanova)$aov.tab$Df[1]);
			print( title );
			palette("default"); 
			svg( file, width=3.5, height=3.5, pointsize=6); 
			par(mar=c(4,4,2,4)+0.1, mfrow=c(1,1), las=2); 
			ordiplot(get(ord), type='none', main=title); 
			points( get(ord), pch=19+as.numeric(as.factor(get(envdata)$P)), col='black', bg=as.numeric(as.factor(get(envdata)$Type)) ); 
			ordiellipse(get(ord), display='sites', groups=as.factor(get(envdata)$Type), label=T); 
			legend('topright', legend=levels(as.factor(get(envdata)$Type)), pch=19+sort(unique(as.numeric(as.factor(get(envdata)$Type))))); 
			dev.off(); 
		}
	}
}





################### Differentially expressed transcripts identification ####################################

batch1_bg_nopvy.L.P0 <- subset(batch1_bg_nopvy, "Organ == 'L' & P == 'P0'", genomesubset=F)
batch1_bg_nopvy.L.P1 <- subset(batch1_bg_nopvy, "Organ == 'L' & P == 'P1'", genomesubset=F)
batch1_bg_nopvy.R.P0 <- subset(batch1_bg_nopvy, "Organ == 'R' & P == 'P0'", genomesubset=F)
batch1_bg_nopvy.R.P1 <- subset(batch1_bg_nopvy, "Organ == 'R' & P == 'P1'", genomesubset=F)

for( organ in c('L', 'R') ){ 
	for( inoculation in c('P0', 'P1') ){
		bg <- paste0("batch1_bg_nopvy.", organ, ".", inoculation);
		file_t <- paste0("batch1_nopvy", organ, ".", inoculation, "DEtranscripts.significant.csv");
		file_g <- paste0("batch1_nopvy", organ, ".", inoculation, "DEgenes.significant.csv");
		result <- stattest(get(bg), feature='transcript', meas='FPKM', getFC=T, covariate="Type");
		resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05, ];	
		write.table(resultsignificant, file_t, sep="\t");
		result <- stattest(get(bg), feature='gene', meas='FPKM', getFC=T, covariate="Type");
		resultsignificant <- result[ !(is.na(result$qval)) & result$qval < 0.05, ];	
		write.table(resultsignificant, file_g, sep="\t");
	}
}


################## plotting genes of interest ##############################################################33

stress_genes <- read.table("stress_proteins.csv", header=F, sep="\t")
susceptibility_genes <- read.table("susceptibility_proteins.csv", header=F, sep="\t")
resistance_genes <- read.table("resistance_proteins.csv", header=F, sep="\t")

for( g in stress_genes$V1 ){
	gene1 <- sub("..$", "", g);
	file <- paste0(gene1, "stress_plotMeans.svg");
	if( nrow(transcript_to_gene.df[transcript_to_gene.df$g_id == gene1, ]) > 0 ){
		print(gene1);
		svg(file, width=5, height=3.5, points=6);
		plotMeans(gown=batch1_bg, gene=gene1, meas='FPKM', groupvar='P', colorby='transcript', legend=T, labelTranscripts=T);
		dev.off()
	}
}

for( g in susceptibility_genes$V1 ){
	gene1 <- sub("..$", "", g);
	file <- paste0(gene1, "susceptibility_plotMeans.svg");
	if( nrow(transcript_to_gene.df[transcript_to_gene.df$g_id == gene1, ]) > 0 ){
		print(gene1);
		svg(file, width=5, height=3.5, points=6);
		plotMeans(gown=batch1_bg, gene=gene1, meas='FPKM', groupvar='P', colorby='transcript', legend=T, labelTranscripts=T);
		dev.off()
	}
}

for( g in resistance_genes$V1 ){
	gene1 <- sub("..$", "", g);
	file <- paste0(gene1, "resistance_plotMeans.svg");
	if( nrow(transcript_to_gene.df[transcript_to_gene.df$g_id == gene1, ]) > 0 ){
		print(gene1);
		svg(file, width=5, height=3.5, points=6);
		plotMeans(gown=batch1_bg, gene=gene1, meas='FPKM', groupvar='P', colorby='transcript', legend=T, labelTranscripts=T);
		dev.off()
	}
}


