library(vegan)
library(GUniFrac)
library(phangorn)
library(DESeq2)
library(BiocParallel)
library(mixOmics)
library(ggpubr)
library(patchwork)
library(mgmisc1)
as.list(as.data.frame(combn(levels(as.factor(sampledata[[grouping.variable]])), 2)))
analyze_all <- function( asvtab, sampledata, tree, taxonomy, grouping.variable, color.variable, varpart.variable, asvname="olsza_donice_its" ) {

		basename <- paste0(asvname, "_", grouping.variable);
		print(basename)
		res_alpha <- plotAlphaDiversity(asvtab=asvtab, sampledata=sampledata, variable=grouping.variable, basename=basename, comps=NULL)
		res_beta <- plotBetaDiversity(featuretab=asvtab, sampledata=sampledata, featureannot=taxonomy, shape.variable=grouping.variable, sample.color.variable=color.variable, feature.color.variable="Order", biplot=T, varpart.variable=varpart.variable, basename=basename, dists=c( 'GUniFrac'), unifrac_types=c('d_0.5'), tree=tree, statistics=T)
		diff_asvs <- findDifferentiallyAbundantFeatures(as.formula(paste("~",  grouping.variable)), asvtab=asvtab, sampledata=sampledata, basename=basename, annot=taxonomy, processors=4, write.final=T )
		if( !is.null(taxonomy) ){
			taxlist <- plotTaxonomy(asvtab=asvtab, sampledata=sampledata, taxonomy=taxonomy, variable=grouping.variable, basename=basename )
			resdf <- data.frame(matrix(nrow=0, ncol=14))
			difftaxa_fname <- paste0(basename, ".difftaxa.csv")
			for( tl in names(taxlist) ){
				atab <- taxlist[[tl]]
				nbasename <- paste0(basename, ".", tl)
				cus <- findDifferentiallyAbundantFeatures(as.formula(paste("~",  grouping.variable)), asvtab=atab, annot=taxonomy, sampledata=sampledata, basename=nbasename, processors=4 )
				row <- rep( tl, 14 )
				names(row) <- colnames(cus)
				colnames(resdf) <- colnames(cus)
				resdf <- rbind( resdf, row )
				colnames(resdf) <- colnames(cus)
				resdf <- rbind( resdf, cus )
			}
			write.table( resdf, difftaxa_fname, sep="\t", col.names=NA )	
		}
		return(taxlist)
}


set.seed(667)


olsza.its <- as.data.frame(seqtab.nochim)
colnames(olsza.its) <- paste("ASV", seq(1, dim(seqtab.nochim)[2], 1), sep="")
olsza.its <- olsza.its[ ,colSums(olsza.its) > 1 ] # singletons and doubletons removed
temp <- Rarefy(otu.tab=olsza.its, depth=5000)$otu.tab.rff
for( i in 1:99 ){ print( i ); temp <- temp + Rarefy(otu.tab=olsza.its, depth=5000)$otu.tab.rff }
olsza.its <- round( temp/100 )



olsza.tax <- as.data.frame(taxa)
rownames(olsza.tax) <- paste("ASV", seq(1, dim(seqtab.nochim)[2], 1), sep="")
olsza.tax <- olsza.tax[ rownames(olsza.tax) %in% colnames(olsza.its), ]


olsza.tree <- read.tree("seqs.phylip.tre")
olsza.tree <- midpoint(olsza.tree)
olsza.tree$edge.length[which(is.na(olsza.tree$edge.length))] <- 0


olsza.design <- read.table("../olsza_donice_design.csv", header=T, sep=",", dec=".")
rownames(olsza.design) <- olsza.design$name
olsza.design <- olsza.design[ olsza.design$name %in% rownames(olsza.its), ]
olsza.its <- olsza.its[ rownames(olsza.its) %in% rownames(olsza.design), ]
olsza.design <- olsza.design[ order(rownames(olsza.design)), ]
olsza.its <- olsza.its[ order(rownames(olsza.its)), ]
identical(rownames(olsza.its), rownames(olsza.design)) # must be TRUE!

		

### Experiment 1 - long-term salinity (LT), alder trees from nursery at NS1 were transferred to S1 and S2 and inoculated/non-inoculated


### Does microbiome differ in roots and soils at different locations (NS1, S1, S2)?
for( location in c('NS1', 'S1', 'S2') ){
	for( inoculation in c('no', 'AM', 'EM') ){
		bname <- paste0('olsza_donica.exp1', location, '.', inoculation)
		asvtab <- olsza.its[ olsza.design$experiment == 'exp1' & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$inoculum) & olsza.design$inoculum == inoculation & !is.na(olsza.design$salinity) & olsza.design$salinity == 'no' & !is.na(olsza.design$time) & olsza.design$time == 'after', ]
		asvtab <- asvtab[ , colSums(asvtab) > 1 ]
		sampledata <- olsza.design[ olsza.design$experiment == 'exp1' & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$inoculum) & olsza.design$inoculum == inoculation & !is.na(olsza.design$salinity) & olsza.design$salinity == 'no' & !is.na(olsza.design$time) & olsza.design$time == 'after', ]
		taxonomy <- olsza.tax[ rownames(olsza.tax) %in% colnames(asvtab), ]
		group <- "source"
		cvar <- "time"
		analyze_all(asvtab=asvtab, sampledata=sampledata, tree=olsza.tree, taxonomy=taxonomy, grouping.variable=group, color.variable=cvar, varpart.variable="replicate", asvname=bname)	
	}
}


### Does inoculation influence roots and soils microbiome at various locations (NS1, S1, S2)?
for( material in c('soil', 'root') ){
	for( location in c('NS1', 'S1', 'S2') ){
		bname <- paste0('olsza_donice.exp1', material, '.', location)
		asvtab <- olsza.its[ olsza.design$experiment == 'exp1' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$salinity) & olsza.design$salinity == 'no' & !is.na(olsza.design$time) & olsza.design$time == 'after', ]
		asvtab <- asvtab[ , colSums(asvtab) > 1 ]
		taxonomy <- olsza.tax[ rownames(olsza.tax) %in% colnames(asvtab), ]
		sampledata <- olsza.design[ olsza.design$experiment == 'exp1' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$salinity) & olsza.design$salinity == 'no' & !is.na(olsza.design$time) & olsza.design$time == 'after', ]
		group <- paste0("inoculum");
		cvar <- "replicate"
		analyze_all(asvtab=asvtab, sampledata=sampledata, tree=olsza.tree, taxonomy=taxonomy, grouping.variable=group, color.variable=cvar, varpart.variable="replicate", asvname=bname)		
	}
}



##### Experiment 2 - short-term salinity (ST), NaCl added to pots with growing seedlings in NS2 soil 

### Does salinization influence micobiome in NS2 soils and roots?
for( material in c('soil', 'root') ){
	for( location in c('NS2') ){
		for( inoculation in c('no', 'AM', 'EM') ){
			bname <- paste0('olsza_donice.exp2', material, '.', location, '.', inoculation)
			asvtab <- olsza.its[ olsza.design$experiment == 'exp2' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$inoculum) & olsza.design$inoculum == inoculation, ]
			asvtab <- asvtab[ , colSums(asvtab) > 1 ]
			taxonomy <- olsza.tax[ rownames(olsza.tax) %in% colnames(asvtab), ]
			sampledata <- olsza.design[ olsza.design$experiment == 'exp2' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$inoculum) & olsza.design$inoculum == inoculation, ]
			group <- paste0("salinity");
			cvar <- "time"
			analyze_all(asvtab=asvtab, sampledata=sampledata, tree=olsza.tree, taxonomy=taxonomy, grouping.variable=group, color.variable=cvar, varpart.variable="replicate", asvname=bname)	
		}	
	}
}


### Does inoculation influence microbiome in NS2 soils and roots under differing salinity?
for( material in c('soil', 'root') ){
	for( location in c('NS2') ){
		for( salinity in c('no', '10x', '20x') ){
			bname <- paste0('olsza_donice.exp2', material, '.', location, '.', salinity)
			asvtab <- olsza.its[ olsza.design$experiment == 'exp2' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$salinity) & olsza.design$salinity == salinity & olsza.design$time == 'after', ]
			asvtab <- asvtab[ , colSums(asvtab) > 1 ]
			taxonomy <- olsza.tax[ rownames(olsza.tax) %in% colnames(asvtab), ]
			sampledata <- olsza.design[ olsza.design$experiment == 'exp2' & !is.na(olsza.design$source) & olsza.design$source == material & !is.na(olsza.design$location) & olsza.design$location == location & !is.na(olsza.design$salinity) & olsza.design$salinity == salinity & olsza.design$time == 'after', ]
			group <- paste0("inoculum");
			cvar <- "replicate"
			analyze_all(asvtab=asvtab, sampledata=sampledata, tree=olsza.tree, taxonomy=taxonomy, grouping.variable=group, color.variable=cvar, varpart.variable="replicate", asvname=bname)	
		}	
	}
}


### Does inoculation influence beta-diversity?

olsza.donice.R.d05GUnifrac <- 
olsza_donice.R_inoculum_x_location.dbrda



unloadNamespace("mgmisc1")
remove.packages("mgmisc1")
install.packages("~/software/mgmisc1_0.1.0_R_x86_64-pc-linux-gnu.tar.gz")
library(mgmisc1)

######## PERMANOVA and dbRDA on data divided to experiments
library(mgmisc1)

## LT

at_LT_R <- olsza.its[ olsza.design$experiment == "exp1" & olsza.design$time == "after" & olsza.design$source == "root", ]
at_LT_R <- at_LT_R[ , colSums(at_LT_R) > 0 ]
sd_LT_R <- olsza.design[ olsza.design$experiment == "exp1" & olsza.design$time == "after" & olsza.design$source == "root", ]
tax_LT_R <- olsza.tax[ rownames(olsza.tax) %in% colnames(at_LT_R), ]
tree_LT_R <- ape::drop.tip(olsza.tree, olsza.tree$tip.label[!(olsza.tree$tip.label %in% colnames(at_LT_R))])

at_LT_R.unifracs <- GUniFrac(at_LT_R, tree_LT_R, alpha = c(0.5))
at_LT_R.d05unifrac <- as.dist(at_LT_R.unifracs$unifracs[ , , 'd_0.5' ])


at_LT_S <- olsza.its[ olsza.design$experiment == "exp1" & olsza.design$time == "after" & olsza.design$source == "soil", ]
at_LT_S <- at_LT_S[ , colSums(at_LT_S) > 0 ]
sd_LT_S <- olsza.design[ olsza.design$experiment == "exp1" & olsza.design$time == "after" & olsza.design$source == "soil", ]
tax_LT_S <- olsza.tax[ rownames(olsza.tax) %in% colnames(at_LT_S), ]
tree_LT_S <- ape::drop.tip(olsza.tree, olsza.tree$tip.label[!(olsza.tree$tip.label %in% colnames(at_LT_S))])

at_LT_S.unifracs <- GUniFrac(at_LT_S, tree_LT_S, alpha = c(0.5))
at_LT_S.d05unifrac <- as.dist(at_LT_S.unifracs$unifracs[ , , 'd_0.5' ])


res <- plotdbRDA(	d = at_LT_R.d05unifrac, 
			distname="d05unifrac", 
			featuretab=at_LT_R,
			sampledata=sd_LT_R, 
			featureannot=tax_LT_R, 
			shape.variable="inoculum", 
			sample.color.variable="location",
			varpart.variable="replicate", 
			feature.color.variable="Class", 
			biplot=T, 
			basename="olsza.ITS.LT_R", 
			type="ggplot", 
			sqrt.dist=T,
			permu=9999)



res <- plotdbRDA(	d = at_LT_S.d05unifrac, 
			distname="d05unifrac", 
			featuretab=at_LT_S,
			sampledata=sd_LT_S, 
			featureannot=tax_LT_S, 
			shape.variable="inoculum", 
			sample.color.variable="location",
			varpart.variable="replicate", 
			feature.color.variable="Class", 
			biplot=T, 
			basename="olsza.ITS.LT_S", 
			type="ggplot", 
			sqrt.dist=T,
			permu=9999)



## ST

at_ST_R <- olsza.its[ olsza.design$experiment == "exp2" & olsza.design$time == "after" & olsza.design$source == "root", ]
at_ST_R <- at_ST_R[ , colSums(at_ST_R) > 0 ]
sd_ST_R <- olsza.design[ olsza.design$experiment == "exp2" & olsza.design$time == "after" & olsza.design$source == "root", ]
tax_ST_R <- olsza.tax[ rownames(olsza.tax) %in% colnames(at_ST_R), ]
tree_ST_R <- ape::drop.tip(olsza.tree, olsza.tree$tip.label[!(olsza.tree$tip.label %in% colnames(at_ST_R))])

at_ST_R.unifracs <- GUniFrac(at_ST_R, tree_ST_R, alpha = c(0.5))
at_ST_R.d05unifrac <- as.dist(at_ST_R.unifracs$unifracs[ , , 'd_0.5' ])


at_ST_S <- olsza.its[ olsza.design$experiment == "exp2" & olsza.design$time == "after" & olsza.design$source == "soil", ]
at_ST_S <- at_ST_S[ , colSums(at_ST_S) > 0 ]
sd_ST_S <- olsza.design[ olsza.design$experiment == "exp2" & olsza.design$time == "after" & olsza.design$source == "soil", ]
tax_ST_S <- olsza.tax[ rownames(olsza.tax) %in% colnames(at_ST_S), ]
tree_ST_S <- ape::drop.tip(olsza.tree, olsza.tree$tip.label[!(olsza.tree$tip.label %in% colnames(at_ST_S))])

at_ST_S.unifracs <- GUniFrac(at_ST_S, tree_ST_S, alpha = c(0.5))
at_ST_S.d05unifrac <- as.dist(at_ST_S.unifracs$unifracs[ , , 'd_0.5' ])


res <- plotdbRDA(	d = at_ST_R.d05unifrac, 
			distname="d05unifrac", 
			featuretab=at_ST_R,
			sampledata=sd_ST_R, 
			featureannot=tax_ST_R, 
			shape.variable="inoculum", 
			sample.color.variable="salinity",
			varpart.variable="replicate", 
			feature.color.variable="Class", 
			biplot=T, 
			basename="olsza.ITS.ST_R", 
			type="ggplot", 
			sqrt.dist=T,
			permu=9999)



res <- plotdbRDA(	d = at_ST_S.d05unifrac, 
			distname="d05unifrac", 
			featuretab=at_ST_S,
			sampledata=sd_ST_S, 
			featureannot=tax_ST_S, 
			shape.variable="inoculum", 
			sample.color.variable="salinity",
			varpart.variable="replicate", 
			feature.color.variable="Class", 
			biplot=T, 
			basename="olsza.ITS.ST_S", 
			type="ggplot", 
			sqrt.dist=T,
			permu=9999)

### Which fungal genera are present in initial root and soil material?

olsza.before.sd <- olsza.design[ olsza.design$time == 'before' &
olsza.design$source != 'inoculum', ]
olsza.before.ft <- olsza.its[ rownames(olsza.its) %in%
rownames(olsza.before.sd), ]
olsza.before.ft <- olsza.before.ft[ , colSums(olsza.before.ft) > 0 ]
olsza.before.fa <- olsza.tax[ rownames(olsza.tax) %in%
colnames(olsza.before.ft), ]
tx <- plotTaxonomy(featuretab=olsza.before.ft,
sapledata=olsza.before.sd, taxonomy=olsza.before.fa,
variable="location", facetting.variables=c("source"),
rare.threshold=0.02)
tx <- plotTaxonomy(featuretab=olsza.before.ft,
sampledata=olsza.before.sd, taxonomy=olsza.before.fa,
variable="location", facetting.variables=c("source"),
rare.threshold=0.02)























