---
title: "FROGS Phyloseq: Import Data (version 4.1.0)"
output: 
  html_notebook:
    code_folding: hide
params:
  # Path ASV abundance biom file
  biomfile: 
    value: x
  # Path to sample metadata TSV file
  samplefile:
    value: x
  # (optional) Path to ASVs tree NWK file
  treefile:
    value: x
  # (optional) normalisation string option : TRUE or FALSE
  normalisation:
    value: x
  # Path to phyloseq object store in Rdata file
  outputRdata:
    value: x
  # List of taxonomic ranks names
  ranks : 
    value: x
  # Path to the phyloseq-extend R functions : https://github.com/mahendra-mariadassou/phyloseq-extended, typically stored in FROGS/lib/external-lib
  libdir:
    value: x
---
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
.button {
    background-color: #2a7ecc; /* Blue */
    border          : none;
    color           : white;
    padding         : 5px 10px;
    text-align      : center;
    text-decoration : none;
    display         : inline-block;
    font-size       : 12px;
    margin          : 4px 2px;
    cursor          : pointer;
    border-radius   : 8px;
}
h4 { 
    display      : block;
    font-size    : 1em;
    margin-top   : 1.33em;
    margin-bottom: 1.33em;
    margin-left  : 0;
    margin-right : 0;
    font-weight  : bold;
    color        : #2a7ecc;
}
</style>


```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Phyloseq `r packageVersion("phyloseq")`
 
```{r package_import, message=FALSE, warning=FALSE}

## Import packages
library(phyloseq)
library(ggplot2)
library(ape)

## Settin variables
  ## The ASV abundance matrix with taxonomy annotation file (biom format)
  # biomfile <- ""

  ## The sample metadata file(TSV format)
  # samplefile <- ""

  ## (optional) the ASV tree file (nwk format). Write "None" if you do not have any tree
  # treefile <- ""

  ## The ordered taxonomic levels stored in BIOM. Each level is separated by one space.
  ## default : "Kingdom Phylum Class Order Family Genus Species"
  # ranks <- ""

  ## Do you want to normalise your data ? "True" or "False"
  # normalisation <- ""

## Create input and parameters dataframe
  # params <- data.frame( "biomfile" = biomfile, "samplefile" = samplefile, "tree" = tree, "ranks" = ranks, "normalisation" = normalisation)


## Import data
biomfile <- params$biomfile
data     <- import_biom(biomfile)
sampledata <- read.csv(params$samplefile, sep = "\t", row.names = 1)

# if taxonomy starts with k__ it means that its Greengenes like format
# import need to be done using parse_taxonomy_greengenes function
# in this case user taxonomic rank names are ignored
tax      <- tax_table(data)[[1]]
if ((gregexpr('k__', tax))[[1]][1]>0) { 
  cat("Warning : Taxonomic affiliations come from Greengenes database, user specified ranks names are ignored.")
  data <- import_biom(biomfile, parseFunction = parse_taxonomy_greengenes)
} else {
## else, custumize rank name with the user specified ranks variable
  new_rank <- as.list(strsplit(params$ranks, " ")[[1]])
  colnames(tax_table(data)) <- new_rank
}

## add sample name to metadata, as SampleID variable
sampledata$SampleID <- rownames(sampledata)
sample_data(data) <- sampledata

## add tree metadata if available
if (params$treefile != "None"){
  treefile <- read.tree(params$treefile)
  phy_tree(data) <- treefile
}

## change de sample metadata order as in input samplefile
for ( variable in sample_variables(data)){
  variable.order = as.vector(unique(sampledata[,variable]))
  sample_data(data)[,variable] <- factor(get_variable(data, variable),levels=variable.order)
}

## remove empty samples
empty_samples <- sample_names(data)[which(sample_sums(data)==0)]
sample_to_keep <- sample_names(data)[which(sample_sums(data)>0)]
data <- prune_samples(sample_to_keep, data)

## abundance normalisation
if(params$normalisation){ data <- rarefy_even_depth(data, rngseed = 1121983)}

## save phyloseq object in Rdata file
save(data, file=params$outputRdata)
```

# {.tabset .tabset-fade .tabset-pills}
## Summary
```{r summary}
data
if(length(empty_samples) > 0) {cat(paste('Remove empty samples: ', paste(empty_samples, collapse=",")))}
if(params$normalisation){cat(paste('Number of sequences in each sample after normalisation: ', head(sample_sums(data))[[1]]))}
```

## Ranks Names
```{r ranks}
cat(paste('Rank names : ',paste(rank_names(data),collapse=', ')))
```

## Sample metadata
```{r sample}
variables <- sample_variables(data)
cat(paste('Sample variables: ', paste(variables, collapse=', ' )))

for (var in variables){
  cat(paste(var,': ',paste(levels(factor(get_variable(data, varName = var))),collapse=', '), '\n\n'))
}
```

## Plot tree
```{r tree, fig.width=10, fig.height=8}

if(params$treefile!="None"){
  p <- plot_tree(data, color=rank_names(data)[2]) + 
          ggtitle(paste("Phylogenetic tree colored by", rank_names(data)[2])) + 
          theme(plot.title = element_text(hjust = 0.5))
  plot(p)
}

if(params$treefile=="None"){
  cat("There is no phylogenetic tree in the object you have provided.")
}
```
