---
title: "`r head(tail(unlist(strsplit(getwd(), '/')), 1), 1)`"
subtitle: "Assemblycomparator2 Report"
date: "`r Sys.time()`"
output:
  html_document:
    toc: true
    toc_depth: 2
  #prettydoc::html_pretty:
    #theme: cayman
    #highlight: github
editor_options: 
  chunk_output_type: console
#css: "max-width: 5000px; margin: auto; padding: 1em; line-height: 20px"
---

`r paste("This report was generated in", getwd())`

```{r global-setup echo=FALSE, message=F, warning=F}

# Version: "v2.2.0"
# Authors: Carl M. Kobel, Oliver Kjærlund Hansen


# This is useful for debugging the markdown script.
# Depends on a local run of the tests/E.faecium_plasmids assemblies.
# setwd("~/GenomeDK/assemblycomparator2/tests/E._faecium_plasmids/results_ac2/")    

#setwd("/cluster/projects/nn9864k/cmkobel/assemblycomparator2/tests/E._faecium")     # Development
#setwd("/cluster/home/cmkobel/memokobel/15_bio326/synthetic_rumen/output/metabat2/06_compare_best_with_lives")     # Development

# axodines
# /home/axodines/assemblycomparator2/conda_base/7747644331801b571bf2c3eb25e862b1_
#setwd("/cluster/home/cmkobel/axodines/assemblycomparator2/tests/MAGs")     # Development
#getwd()






#Dependencies
library(tidyverse)
#library(prettydoc)
library(DT)
#library(phytools)
library(ape)
#library(phangorn)



# A function that returns a new table number for each run
tableno_var = 0
tableno = function() {
    tableno_var <<- tableno_var + 1
    tableno_var
}

figno_var = 0
figno = function() {
    figno_var <<- figno_var + 1
    figno_var
}


```

## Sample overview

```{r sample-overview echo=FALSE, message=F, warning=F}



# Import the metadata table
# This table makes it easy for us later to convert the long paths to short and simple sample names
metadata_file = "results_ac2/metadata.tsv"

if (file.exists(metadata_file)) {
    metadata_df = read_tsv(metadata_file)
    
    
    # Generate a very simple table which can be used to convert long paths to sample names
    metadata_translate = metadata_df %>% 
        select(sample, filename = input_file_fasta)
    
    # Present the metadata in the report
    metadata_df %>%
        select(-index) %>% 
        arrange(sample) %>% 
        
        datatable(class = 'cell-border stripe')
    
    
    
} else {
    stop(paste("The metadata file", metadata_file, "is not accessible.")) # Should stop the script completely
}


```

*Table `r tableno()`: Overview of the samples analysed in this run.*

## Assembly statistics

```{r echo=FALSE, message=F, warning=F}

tryCatch({
    assembly_stats_file = "results_ac2/assembly-stats/assembly-stats.tsv"
    gc_summary_file = "results_ac2/collected_results/GC_summary.tsv"
    
    if (file.exists(assembly_stats_file) & file.exists(gc_summary_file) ) {
        paste("both") # debug
        assembly_stats_df = read_tsv(assembly_stats_file)
        gc_summary_df = read_tsv(gc_summary_file) %>% rename(filename = sample)
        
        
        # Put ALL PARTS GC and non-ALL PARTS sd(GC) together
        assembly_stats_GC = gc_summary_df %>% 
            filter(part == "ALL PARTS") %>% 
            select(filename, GC) %>%
            left_join(
                gc_summary_df %>% 
                    filter(part != "ALL PARTS") %>% 
                    group_by(filename) %>% 
                    summarize(sd(GC)),
                by = "filename") %>% 
            mutate_at(vars(GC, `sd(GC)`), signif, digits = 4)
            
        
        
        
        #assembly_stats_df %>% left_join(metadata_translate) %>% 
        assembly_stats_df %>%
            left_join(assembly_stats_GC) %>% 
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename, -N50n, -N70, -N70n, -N90n) %>%
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
          
            
    
        
        
        
    
    } else if (file.exists(assembly_stats_file)) { # Only assembly_stats_file exists
        assembly_stats_df = read_tsv(assembly_stats_file) 
        
        assembly_stats_df %>% left_join(metadata_translate) %>% 
            select(sample, everything(), -filename, -N50n, -N70, -N70n, -N90n) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
                
        
        
    } else {
        paste("Warning: The file", assembly_stats_file, "and/or", gc_summary_file, "is not accessible.")
    }
    
})

```

*Table `r tableno()`: Assembly statistics is provided by [assembly-stats](https://github.com/sanger-pathogens/assembly-stats#assembly-stats). N50 indicates the length of the smallest contig that (together with the longer contigs) covers at least half of the genome. sd(GC) shows variation between each fasta record.*


#### Lengths of contigs:

```{r echo=FALSE, message=F, warning=F}


try({
    # This chunk is needed for setting the size of sequence length comparison plot

    fig_height = max(1.6,
                     (metadata_df$sample %>% length) *0.2)
    
    knitr::opts_chunk$set(fig.height = fig_height,
                          fig.width = 9)

})
```

```{r echo=FALSE, message=F, warning=F}
try({
    # Now when the figure height has been set, we can generate the figure
    sequence_lengths_file = "results_ac2/collected_results/sequence_lengths.tsv"
    
    if (file.exists(sequence_lengths_file)) {
        sequence_lengths_df = read_tsv(sequence_lengths_file)
        sequence_lengths_df %>%
            group_by(sample) %>% 
            #arrange(length) %>% 
            
            #mutate(col = row_number(-length)) %>% 
            mutate(col = 1:length(sample)) %>%
            mutate(init = lag(length, default = 0),
                   start = cumsum(init),
                   stop = start + length - 1) %>%
    
            
            #mutate(sample = fct_reorder(sample, desc(sample))) %>% 
            #mutate(sample = fct_reorder(sample, desc(sample))) %>% 
            
            
            
        
            # Gammel figur
            # ggplot(aes(x=length, y=sample, fill=factor(col))) + 
            # geom_bar(position = position_dodge2(width = 0.9, preserve = "single", reverse = T),
            #          #position = "dodge2",
            #          stat="identity") +
            # theme_classic() +
            # theme(legend.position = "none") +
            # theme(panel.grid.major.x = element_line(colour = "grey92")) 
    
            #View
            #ungroup() %>% 
            #mutate(col = fct_reorder(col, desc(col))) %>% 

        
            ggplot(aes(length, reorder(sample, desc(sample)), fill=reorder(col, desc(col)))) + 
            #geom_bar(stat = "identity", color = "black", size = 0.3, fill = "grey50") +
            
            # The best way to set the colors is to use the default colorramping, because it highlights the relative of contigs.

            geom_bar(stat = "identity", color = "black", size = 0.3) + 
            theme_classic() +
            theme(legend.position = "none") +
            theme(panel.grid.major.x = element_line(colour = "grey92")) + 
            labs(y = "sample") #+
            #scale_fill_brewer(palette = "Dark2", direction = -1) +
            
            # Paired has 12 colors
            #scale_fill_brewer(palette = "Paired", direction = -1) #+
            
            
            #scale_x_log10()

            
        
                
        
        
    } else {
        paste("Warning: The file", sequence_lengths_file, "is not accessible.")
    }
})
```

*Fig. `r figno()`: Lengths of fasta records for each sample. The colors have no intrinsic meaning, other than highlighting the varying sizes and number of records in each assembly.*

## Genome annotation

```{r echo=FALSE, message=F, warning=F}

try({
    # Now when the figure height has been set, we can generate the figure
    prokka_summarized_file = "results_ac2/collected_results/prokka_summarized.txt"
    if (file.exists(prokka_summarized_file)) {
        prokka_summarized_df = read_delim(prokka_summarized_file, delim = " ")
        
        prokka_summarized_df %>% pivot_wider(id_cols = sample, names_from = name, values_from = value) %>% 
            select(sample, CDS, `unique /gene codes` = unique, tRNAs, rRNAs, CRISPRs) %>% 
            arrange(sample) %>% 
            datatable()
            
            
        
                
        
        
    } else {
        paste("Warning: The file", prokka_summarized_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Overview of the number of different gene types. Called using the [Prokka](https://github.com/tseemann/prokka) genome annotator.*



## BUSCO

```{r echo=FALSE, message=F, warning=F}
try({
    busco_extract_file = "results_ac2/collected_results/busco.tsv"
    if (file.exists(busco_extract_file)) {

        
        busco_raw = read_delim(busco_extract_file, delim = ": ", col_names = c("name", "value"))

        busco_df = busco_raw %>% 
            mutate(id = (name == "in") %>% as.integer() %>% cumsum()) %>% 
            mutate(value = str_remove(value, ",$")) %>% 
            
            pivot_wider(id_cols = id)  %>% 
            select(-id)  %>% 
            rename(file = `in`, lineage = name) %>% 
            mutate(file = basename(file)) %>% 

            separate(one_line_summary, c("pre_CS", "D", "F", "M", "n"), sep = ",", extra = "drop") %>% 
            separate(pre_CS, c("C", "S"), "\\[") %>% 
            mutate(D = str_remove(D, "\\]")) %>% 
            
            mutate(
                C = str_extract(C, "\\d+.\\d+") %>% as.numeric,
                S = str_extract(S, "\\d+.\\d+") %>% as.numeric,
                D = str_extract(D, "\\d+.\\d+") %>% as.numeric,
                F = str_extract(F, "\\d+.\\d+") %>% as.numeric,
                M = str_extract(M, "\\d+.\\d+") %>% as.numeric,
                n = str_extract(n, "\\d+") %>% as.numeric
            ) %>% 
            group_by(file) %>% 
            arrange(desc(C)) %>% 
            mutate(rank = 1:n()) %>% 
            ungroup()



        # Present table
        busco_df_meta = metadata_translate %>%
            mutate(file = basename(filename)) %>%
            left_join(busco_df %>% filter(rank == 1), by = "file") %>%
            select(-file, -filename, -rank) %>%
            arrange(lineage)
        busco_df_meta

        busco_df_meta %>% 
            write_tsv("results_ac2/collected_results/export_busco.tsv")
        
        busco_df_meta %>% 
            datatable(class = 'cell-border stripe', options = list(dom = 'ltpi'))





    } else {
        paste("Warning: The file", busco_extract_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Table of [BUSCO](https://busco.ezlab.org/) "BUSCO estimates the completeness and redundancy of processed genomic data based on universal single-copy orthologs.". The following columns are printed as percents [%]: C: Complete, S: Complete and single-copy, D: Complete and duplicated, F: Fragmented, M: Missing, n: Total BUSCO groups searched. For each sample, only the best lineage match (in terms of completeness) is shown.*

```{r echo=FALSE, message=F, warning=F, fig.height = 4.8, fig.width = 8}
try({
    if (file.exists(busco_extract_file)) {

        busco_df_meta %>% 

            ggplot(aes(C, F, color = lineage, label = sample)) + 
            geom_point() +
            geom_text(color = "black", alpha = 0.5, check_overlap = T, hjust = 0, vjust = 0, size = 2.5) +
            labs(
                x = "Complete (C) [%]",
                y = "Fragmented (F) [%]") +
            theme_bw()



    } else {
        paste("Warning: The file", busco_extract_file, "is not accessible.")
    }
})
```

*Fig. `r figno()`: BUSCO Completeness VS Fragmentation. Axes are in percents. Colored by lineage. For each sample, only the best lineage match (in terms of completeness) is shown. Samples in the lower right corner are relatively better.*




## Checkm2

```{r echo=FALSE, message=F, warning=F}
try({
    checkm2_file = "results_ac2/checkm2/quality_report.tsv"
    if (file.exists(checkm2_file)) {

        # Read raw input
        checkm2_raw = read_tsv(checkm2_file)


        checkm2_presentable = metadata_translate %>%
            select(sample) %>%
            left_join(checkm2_raw, by = c("sample" = "Name")) %>%
            
            mutate(
                Completeness_Model_Used = str_replace(Completeness_Model_Used, "Neural Network", "NN"),
                Average_Gene_Length = round(Average_Gene_Length, 1)
            ) %>%
            rename_with(str_replace_all, pattern = "_", replacement = " ")

            


        
        checkm2_presentable %>%
            datatable(class = 'cell-border stripe')

    } else {
        paste("Warning: The file", checkm2_file, "is not accessible.")
    }


})

```

*Table `r tableno()`: [Checkm2](https://github.com/chklovski/CheckM2) results. *



```{r echo=FALSE, message=F, warning=F, fig.height = 4.8, fig.width = 8}
try({
    if (file.exists(checkm2_file)) {

        checkm2_presentable %>%
            ggplot(aes(Completeness, Contamination, color = `Coding Density`, label = sample)) +
            geom_point() +
            geom_text(color = "black", alpha = 0.5, check_overlap = T, hjust = 0, vjust = 0, size = 2.5) +
            labs(
                x = "Completeness [%]",
                y = "Contamination [%]") +
            scale_color_viridis_b() +
            theme_bw()
        



    } else {
        paste("Warning: The file", checkm2_file, "is not accessible.")
    }
})

```



*Fig. `r figno()`: [Checkm2](https://github.com/chklovski/CheckM2) results. Axes are in percents. Colored by coding density. Samples in the lower right corner are relatively better.*





## Kraken2 taxonomical classification

```{r echo=FALSE, message=F, warning=F}
try({
    kraken2_file = "results_ac2/collected_results/kraken2_reports.tsv"
    if (file.exists(kraken2_file)) {
        
        
        
        
        kraken2_df = read_tsv(kraken2_file) %>% 
            rename(percent = match_percent) %>% 
            mutate(percent = round(percent, 1))
            #mutate(percent_str = paste(sprintf("%.1f", percent)))
        
        
        kraken2_df %>% group_by(sample) %>% 
            #filter(level == "S" | level == "U")
            filter(level == "S") %>% 
            mutate(rank = row_number(-percent),
                   rank_text = paste("hit", rank),
                   clade_text = paste0(percent, "% (", clade, ")")) %>% 
                   #clade_text = paste0(clade, " ", match_percent, ")")) %>% 
            
            filter(rank <= 3) %>% 
            pivot_wider(id_cols = sample, names_from = rank_text, values_from = c(percent, clade)) %>% 
            
        
            arrange(sample) %>% 
            
            select(ends_with("1"), ends_with("2"), ends_with("3")) %>% 
            
            
            #mutate_if(is.numeric, percent = paste(sprintf("%.1f", percent)))
    
        
            datatable(class = 'cell-border stripe')
                
        
        
    } else {
        paste("Warning: The file", kraken2_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Listing of the 3 highest species hits for each sample. Species identification is provided by [Kraken 2](https://github.com/DerrickWood/kraken2/wiki/About-Kraken-2). The percentages indicate the proportion of sequences (equivalent to fasta records) mapping to the species.*

`r if (file.exists(kraken2_file)) {paste("Using the", Sys.getenv("ASSCOM2_KRAKEN2_DB"), "database")}`.



## GTDB bacteria taxonomical classification

```{r echo=FALSE, message=F, warning=F}
try({
    gtdbtk_file = "results_ac2/gtdbtk/gtdbtk.bac.summary.tsv"
    if (file.exists(gtdbtk_file)) {
        
        gtdbtk_df = read_tsv(gtdbtk_file) %>% 
            select(sample = user_genome, classification, fastani_ani, fastani_reference) %>% 
            mutate(classification = classification %>% str_replace_all(";", "<br />")) # New line at each taxa level
        
        
        # Force the table to show missing samples by left joining onto the metadata table.
        metadata_translate %>% 
            select(sample) %>% 
            left_join(gtdbtk_df) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe', escape = F)
                
        
    } else {
        paste("Warning: The file", gtdbtk_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Species classification provided by the [GTDB-tk](https://github.com/Ecogenomics/GTDBTk) classify workflow.*

`r if (file.exists(gtdbtk_file)) {paste("Using the", Sys.getenv("GTDBTK_DATA_PATH"), "database")}`










## MLST

```{r echo=FALSE, message=F, warning=F}
try({
    #få mlst til at spytte header ud.
    #mlst <- read.table(file = 'mlst.tsv', sep = '\t', header = FALSE)
    mlst_file = "results_ac2/mlst/mlst.tsv"
    if (file.exists(mlst_file)) {
        mlst_df <- read_tsv("results_ac2/mlst/mlst.tsv", col_names = F)
        
        # Generate a vector of allele columns if any exist.
        if( length(mlst_df) > 3) { 
            num_alleles <- length(mlst_df) - 3
            allele_columns = paste('al.', 1:num_alleles)
        } else {
            allele_columns = NULL

        }
        
        names(mlst_df) = c("filename", "scheme", "sequence_type", allele_columns)
        
        
        mlst_df %>%
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
            
        
        #mlst_df %>% datatable(
        #  options = list(
        #   autoWidth = TRUE, 
        #   columnDefs = list(list(width = '300px'))),
          #class = 'cell-border stripe',
          #rownames = FALSE,
          #colnames = c('Isolate','Scheme', 'SequenceType', rep('Allel',allelnum) )
          #)
        
          #kable() %>% 
          #kable_paper('hover', full_width = F)
    } else {
        paste("Warning: The file", mlst_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Table of MLST (Multi Locus Sequence Typing) results. Called with [mlst](https://github.com/tseemann/mlst#mlst) which incorporates components of the [PubMLST](https://pubmlst.org/) database.*

#### How to customize the mlst-analysis

Mlst automatically detects the best scheme for typing, one sample at a time. If you don't agree with the automatic detection, you can enforce a single scheme across all samples by (re)running assemblycomparator2 with the trailing command-line argument: `--config mlst_scheme=hpylori -R mlst report`. Replace *hpylori* with the mlst scheme you wish to use. You can find a full list of available schemes in the output directory in "mlst/mlst_schemes.txt".

## Resistance

The resistance typing results below are all called with [Abricate](https://github.com/tseemann/abricate#abricate), using different underlying databases:

### NCBI Resistance

```{r echo=FALSE, message=F, warning=F}
try({
    abricate_ncbi_file = "results_ac2/abricate/ncbi_summarized.tsv"
    if (file.exists(abricate_ncbi_file)) {
        abricate_ncbi_df = read_tsv(abricate_ncbi_file) %>% 
            rename(filename = `#FILE`, num_found = NUM_FOUND)
        
        
        abricate_ncbi_df %>%
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
    
        
    } else {
        paste("Warning: The file", abricate_ncbi_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Table of NCBI Resistance gene calls called with [NCBI AMRFinder](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6811410/).*

### Card Resistance genes

```{r echo=FALSE, message=F, warning=F}
try({
    abricate_card_file = "results_ac2/abricate/card_summarized.tsv"
    if (file.exists(abricate_card_file)) {
        abricate_card_df = read_tsv(abricate_card_file) %>% 
            rename(filename = `#FILE`, num_found = NUM_FOUND)
        
        
        abricate_card_df %>%
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
    
        
    } else {
        paste("Warning: The file", abricate_card_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Table of [Card](https://card.mcmaster.ca/) (Comprehensive Antibiotic Resistance Database) results*

### Plasmidfinder calls

```{r echo=FALSE, message=F, warning=F}
try({
    abricate_plasmidfinder_file = "results_ac2/abricate/plasmidfinder_summarized.tsv"
    if (file.exists(abricate_plasmidfinder_file)) {
        abricate_plasmidfinder_df = read_tsv(abricate_plasmidfinder_file) %>% 
            rename(filename = `#FILE`, num_found = NUM_FOUND)
        
        
        abricate_plasmidfinder_df %>%
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe')
    
        
    } else {
        paste("Warning: The file", abricate_plasmidfinder_file, "is not accessible.")
    }
    
})
```

*Table `r tableno()`: Table of [PlasmidFinder](https://cge.cbs.dtu.dk/services/PlasmidFinder/) plasmid calls. Note that plasmidfinder uses short substrings for recognizing the plasmids, and not necessarily longer sequences i.e. complete plasmid sequences.*

### VFDB calls

```{r echo=FALSE, message=F, warning=F}
try({
    abricate_vfdb_file = "abricate/vfdb_summarized.tsv"
    if (file.exists(abricate_vfdb_file)) {
        abricate_vfdb_df = read_tsv(abricate_vfdb_file) %>% 
            rename(filename = `#FILE`, num_found = NUM_FOUND)
        
        
        abricate_vfdb_df %>%
            left_join(metadata_translate) %>% 
            select(sample, everything(), -filename) %>% 
            arrange(sample) %>% 
            datatable(class = 'cell-border stripe', options = list(dom = 'ltpi'))
    
        
    } else {
        paste("Warning: The file", abricate_vfdb_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Table of [VFDB](http://www.mgc.ac.cn/VFs/main.htm) virulence factor calls: "An integrated and comprehensive online resource for curating information about virulence factors of bacterial pathogens".*







## Functional Enrichment

[KEGG Orthology](https://www.genome.jp/kegg/ko.html) is a curated database of most known orthologous genes. The ortholog grouping makes it possible to transfer knowledge about pathways and their genes, from one set of species to another. In this analysis we ask the question; whether more genes from a specific pathway are present in the genome compared to what we expect by chance. The p-value tells us what the probability is of observing the present genes from each pathway, given that the genomes are randomly generated. The p-values are then corrected for multiple testing using the Benjamini-Hochberg method. Only statistically significant results are shown in the figure.

The pathways can be looked up at [KEGG Pathway](https://www.genome.jp/kegg/pathway.html).




```{r echo=FALSE, message=F, warning=F}
sample_pathway_enrichment_analysis_file = "results_ac2/collected_results/sample_pathway_enrichment_analysis.tsv"

try({
    if (file.exists(sample_pathway_enrichment_analysis_file)) {
        sample_pathway_enrichment_analysis_df = read_tsv(sample_pathway_enrichment_analysis_file) %>% 
            separate(generatio, into = c("k", "n"), sep = "/", remove = F) %>% 
            separate(bgratio, into = c("M", "N"), sep = "/", remove = F) %>% 
            mutate_at(c("k", "n", "M", "N"), as.numeric) %>% 
            mutate(
                sample = paste0(sample, " {", n, "}"),
                description = paste0(description, " [", M, "]")
                #myratio = paste0((k/M) %>% signif(1), "%")
            )
      } else {
    paste("Warning: The file", sample_pathway_enrichment_analysis_file, "is not accessible.")

    }
})

```

```{r echo=FALSE, message=F, warning=F}
# This chunk is needed for setting the size of the following plot.
try({
    if (file.exists(sample_pathway_enrichment_analysis_file)) {
        fig_height = max(4, (sample_pathway_enrichment_analysis_df$description %>% unique() %>% length()) * 0.4)
        
        fig_width = max(8, (metadata_df$sample %>% length()) * 1)
    
        
        
        
        knitr::opts_chunk$set(fig.height = fig_height,
                              fig.width = fig_width)
    }
})
```


```{r echo=FALSE, message=F, warning=F}
# It shouldn't be necessary to use the metadata_translate table, as the factors should already be ordered alphabetically.
try({
    if (file.exists(sample_pathway_enrichment_analysis_file)) {
        sample_pathway_enrichment_analysis_df %>% 
            ggplot(aes(sample, description, fill = `p.adjust`, label = k)) +
            geom_tile() + 
            geom_text(color = "grey95", size = 3) +
            labs(y = "KEGG pathway", fill = "adjusted\np-value") + 
            theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
    }
})


```

*Fig. `r figno()`: KEGG pathways which are significantly enriched for in each full genome. The darker the color, the more significant the enrichment is. The color of each tile shows the fdr-adjusted p-value which has been adjusted for each sample independently. The text on the tile denotes the number of genes that the genome contains from the listed pathway. The numbers in the square bracket next to each pathway denotes the total size of that pathway. The curly braces next to the sample names denote the number of genes in the genome that are contained in the complete KEGG orthology database. Results are obtained using [clusterProfiler](https://github.com/YuLab-SMU/clusterProfiler). The background is defined as the full database of 13224 genes.*




## Pan and Core genome

[Roary](https://sanger-pathogens.github.io/Roary/) the pan genome pipeline computes the number of orthologous genes in a number of core/pan spectrum partitions.

The core genome denotes the genes which are conserved between all samples (intersection), whereas the pan genome is the union of all genes across all samples.

```{r echo=FALSE, message=F, warning=F}
try({
    roary_summary_file = "results_ac2/roary/summary_statistics.txt"
    if (file.exists(roary_summary_file)) {
        paste("yes")
        read_tsv(roary_summary_file, col_names = c("ortholog class", "definition", "count")) %>% 
            #mutate(type = paste(partition, definition)) %>% 
            
            #select(type, count) %>% 
            datatable(class = "stripe", rownames = F,  options = list(dom = 't', ordering=F), width = 400)
    } else {
        paste("Warning: The file", roary_summary_file, "is not accessible.")
    }
})
```

*Table `r tableno()`: Distribution of genes in different core/pan spectrum partitions.*

------------------------------------------------------------------------

```{r echo=FALSE, message=F, warning=F}
try({
    # This chunk is needed for setting the size of the roary gpa plot
    fig_height = max(1.6,
                     (metadata_df$sample %>% length) *0.2)
    
    knitr::opts_chunk$set(fig.height = fig_height,
                          fig.width = 9)
})
```

```{r echo = F, message = F, warning = F}
try({
    roary_gpa_file = "results_ac2/roary/gene_presence_absence.Rtab"
    if (file.exists(roary_gpa_file)) {
        paste("yes")
        roary_gpa_df = read_tsv(roary_gpa_file)
        
        roary_gpa_df %>% 
            #select(-Gene) %>% 
            mutate(sum = rowSums(across(where(is.numeric)))) %>%
            #mutate(order = 1:(dim(.)[1])) %>% View
            mutate(genes = 1:length(Gene)) %>% 
            select(-Gene) %>% 
        
            pivot_longer(c(everything(), -genes, -sum), names_to = "sample", values_to = "present") %>% 
            filter(present >= 1) %>% 
            #View
            mutate(sample = fct_reorder(sample, desc(sample))) %>% 
            ggplot(aes(genes, sample, fill = factor(sum))) + geom_tile() +
            #labs(fill = "shared between\nsamples") + 
            labs(fill = "number of\nsamples") +
            
            theme_classic() 
    } else {
        paste("Warning: The file", roary_gpa_file, "is not accessible.")
    }
})
```

*Fig. `r figno()`: Distribution of genes in the different samples. Each vertical line represents a gene, and all lines have the same width regardless of the size of the gene it represents. The genes are ordered and colored by the number of samples sharing them.*

## Core genome phylogeny

```{r echo=FALSE, message=F, warning=F}
# This chunk is needed for setting the size of the following plot
try({
    fig_height = max(4,
                     (metadata_df$sample %>% length) * 0.4)
    
    knitr::opts_chunk$set(fig.height = fig_height,
                          fig.width = 10)
})
```

```{r echo=FALSE, message=F, warning=F}
try({
    fasttree_file = "results_ac2/fasttree/fasttree.newick"
    if (file.exists(fasttree_file)) {
    
       tree <- ape::read.tree(fasttree_file)
       
       #tree = phytools::midpoint.root(tree)
       #devtools::install_github("igraph/rigraph")
       #tree = phangorn::midpoint(tree)
       
       #plot(tree)
       #axis(1)
       
       #tree$tip.label = paste0(" ", tree$tip.label)
       #phytools::plotTree(tree, align.tip.label = T, lwd = 1, mar = c(0,0,0,0))
       #axis(1)
    
       tree$tip.label = paste0(" ", tree$tip.label)
       ape::plot.phylo(tree, align.tip.label = T); axis(1)
       ## Error in axis(1) : plot.new has not been called yet
           
            
    } else {
        paste("Warning: The file", fasttree_file, "is not accessible.")
    }

})

```

*Fig. `r figno()`: Phylogenetic NJ-tree from the concatenated core genome of all samples. The core genome phylogeny is provided with [FastTree](http://www.microbesonline.org/fasttree/) with the generalized time-reversible (GTR) model of nucleotide evolution. The plotted tree is not rooted.*

```{r echo=FALSE, message=F, warning=F, fig.height = 4, fig.width = 6}
try({
    snp_dists_file = "results_ac2/snp-dists/snp-dists.tsv"
    if (file.exists(snp_dists_file)) {
        
        snp_dists_df =read_tsv(snp_dists_file)
        names(snp_dists_df)[1] = "sample"
        snp_dists_df %>% 
            arrange(sample) %>% 
            datatable()
        

            
    } else {
        paste("Warning: The file", snp_dists_file, "is not accessible.")
    }

})

```

*Table `r tableno()`: Pairwise distances between the samples in the core genome. SNP-distances between the core gene alignment. Calculated with [snp-dists](https://github.com/tseemann/snp-dists#snp-dists). The shown table is symmetrical around the diagonal.*

```{r echo=FALSE, message=F, warning=F, fig.height = 3, fig.width = 9}
try({
    snp_dists_file = "results_ac2/snp-dists/snp-dists.tsv"
    if (file.exists(snp_dists_file)) {

        
        mat = snp_dists_df %>% column_to_rownames(var = "sample")
        mat[lower.tri(mat, diag = T)] = NA
        mat %>% rownames_to_column("sample") %>% 
            #as.tibble() %>% changed to as_tibble() due to warning in output.
            as_tibble() %>% 
            pivot_longer(-sample) %>%
            ggplot(aes(value)) +
            geom_histogram() +
            theme_bw()
            
    
        
        
            
    } else {
        paste("Warning: The file", snp_dists_file, "is not accessible.")
    }

})

```

*Fig. `r figno()`: Pairwise distances between the samples in the core genome.*

------------------------------------------------------------------------

## Mashtree phylogeny

[Mashtree](https://github.com/lskatz/mashtree) computes an approximation of ANI using the minhash distance measure. On these distances, a phylogenetic tree is then created using the neighbor-joining algorithm. The plotted tree is not rooted.


```{r echo=FALSE, message=F, warning=F}
# This chunk is needed for setting the size of the mashtree plot
try({
    fig_height = max(4,
                     (metadata_df$sample %>% length) * 0.4)
    
    knitr::opts_chunk$set(fig.height = fig_height,
                          fig.width = 10)
})
```

```{r echo=FALSE, message=F, warning=F}
try({
    mashtree_file = "results_ac2/mashtree/mashtree.newick"
    if (file.exists(mashtree_file)) {
    
       tree <- ape::read.tree(mashtree_file)
       
       #tree = phytools::midpoint.root(tree)
       #devtools::install_github("igraph/rigraph")
       #tree = phangorn::midpoint(tree)
       
       #plot(tree)
       #axis(1)
       
       #tree$tip.label = paste0(" ", tree$tip.label)
       #phytools::plotTree(tree, align.tip.label = T, lwd = 1, mar = c(0,0,0,0))
       #axis(1)
    
       tree$tip.label = paste0(" ", tree$tip.label)
       ape::plot.phylo(tree, align.tip.label = T)
       axis(1)
           
            
    } else {
        paste("Warning: The file", mashtree_file, "is not accessible.")
    }

})

```

*Fig. `r figno()`: Approximation of a phylogenetic tree calculated with mashtree.*

------------------------------------------------------------------------

The [assemblycomparator2](https://github.com/cmkobel/assemblycomparator2#assemblycomparator2) pipeline and report is developed by [Oliver Hansen](https://github.com/oliverh2020) & [Carl M. Kobel](https://github.com/cmkobel) `version 2.3.0`
