Flexible workflow designed for bacterial WGS analyses (annotation, core/pan-genome reconstruction, phylogeny)

public public 1yr ago 0 bookmarks

This pipeline is written specifically for annotating the bacteria whole genome sequences (WGS) . The pipeline handles multiple operations that are necessary for bacterial genome analysis. Including:

  1. Annotating bacterial WGS

  2. Constructing a pangenome for bacterial WGS dataset

  3. Identify core and accessory loci for bacterial WGS dataset

  4. Produce core gene concatenation alignment (with & without recombination detection)

  5. Identify potential recombination regions (recent & ancestral) - (WGS wise & Per-gene)

  6. Identify SNPs from conserved regions of the bacterial genomes

  7. Reconstruct Phylogeny of input dataset (Maximum Liklihood)

  8. Add Annotation to alignment and ML trees taxa (designed for BEAST Analysis)

Overall Workflow

pipeline_workflow

Installation

  1. Install conda (Python3) in your local computer or on the computing cluster. Detailed instruction can be find here

  2. make a working directory

    mkdir {BactPrep_dir}*
    cd {BactPrep_dir}
    

    * this name can change base on your project

  3. clone the repository into local working directory

    git clone https://github.com/rx32940/BactPrep.git
    
  4. If first time using the pipeline

    cd BactPrep 
    conda create -n BactPrep python=3 mamba -c conda-forge -y
    conda activate BactPrep 
    # if this step is not complete, set channel priirity in conda env to flexible with command: 
    # conda config --set channel_priority true
    mamba install --file workflow/env/install.yaml 
    source INSTALL.sh 
    

    * this name can change base on your project

    • 4.1) if used the pipeline before or has matlab runtime R2016b (MCR) AND fastGear executable installed on the machine, use flag --mcr_path and --fastgear_exe to specify the absolute path to MCR and fasrGear executable. IF these two software were installed during previous use of BactPrep. you can find them in the resources folder from the previous download (please see example #6 below for detail).
  1. You are now good to go! RUN:

    start_analysis.py ALL(coreGen/wgsRecomb/panRecomb)
    

    OR

    python start_analysis.py ALL(coreGen/wgsRecomb/panRecomb)
    
  2. after running all your analysis, deactivate the env

    conda deactivate
    

Sample dataset

218 Streptococcus pneumoniae PMEN1 WGS assemblies collected from the year 1984 - 2008 from 22 unique countries globally

  • The sample dataset can be downloaded to your work directory by:
mkdir -p $INPATH/assemblies
cd $INPATH/assemblies
zenodo_get -d 10.5281/zenodo.5603335
rm $INPATH/assemblies/md5sums*

Reference genome for Streptococcus pneumoniae PMEN1 can be downloaded from NCBI: Streptococcus pneumoniae ATCC 700669 (firmicutes)

cd $INPATH/
wget https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/026/665/GCF_000026665.1_ASM2666v1/GCF_000026665.1_ASM2666v1_genomic.fna.gz
gunzip GCF_000026665.1_ASM2666v1_genomic.fna.gz

Instruction

Module Selection:

ALL : this module will attempt to run wgsRecomb , coreGen , and coreRecomb module

  • All options required for these three modules are also required for ALL module

wgsRecomb : detect recombination from WGS alignment

coreGen : construct bacteria pangenome

panRecomb : will attempt to detect recombination for each gene in the all genes in the pangenome individually

  • predict recombinaiton among lineages detected by BAPs (can also provide your own lineage)
  • this module use gene loci detected by Roary, thus will also run module coreGen
  • please use geneRecomb module for individual gene/alignment of interest

geneRecomb : will detect recombination from a gene/alignment interested

coreRecomb : will dect recombinations only from the core genes detected by coreGen module (Roary)

  • this is part of the ALL module
  • this module use gene loci detected by Roary, thus will also run module coreGen
  • will mask detected recombination region, and call SNPs from conserved region of core genome alignment
  • recombinations were detected for each gene individually
  • will also reconstruct phylogeny for the dataset based on the core clonal SNPs.
usage: start_analysis.py MODULE [options]
Please always specify the program to use in the first argument, or the whole pipeline will attemp to run
positional arguments:
 {ALL,wgsRecomb,coreGen,coreRecomb,panRecomb,geneRecomb}
 Specify the module you would like to run
optional arguments:
 -h, --help show this help message and exit
general arguments:
 -i , --input path to input dir with assemblies
 -p , --name provide name prefix for the output files
 -t , --thread num of threads
 -o , --output path to the output directory
arguments for if you would like to add metadata to output:
 -M, --addMetadata must have the flag specify if want to allow annotation
 -a , --annotate path to a csv file containing sample metadata
 -s , --sample integer indicates which column the sample name is in the metadata csv file
 -m , --metadata metadata chosen to annotate ML tree/alignment after the sample name
arguments for wgsRecomb module:
 -r , --ref reference (required for wgsRecomb module)
 -v , --phage phage region identified for masking (bed file)
 -G , --gubbins any additional Gubbins arguments (please refer to Gubbins manual)
arguments for coreGen module:
 -g , --gff path to input dir with gff (this can replace input assemblies dir in coreGen module Must be gff3 files)
 -c , --core define core gene definition by percentage for coreGen module (default=99)
 -k , --kingdom specify the kingom of input assemlies for genome annotation (default=Bacteria)
 -R , --roary any additional roary arguments (please refer to Roary manual)
arguments for all three fastGear modules (coreRecomb, panRecomb, geneRecomb):
 --mcr_path path to mcr runtime (need to install before use any of the fastGear module
 --fastgear_exe path to the excutable of fastGear
 --fg , --fastgear_param 
 path to fastGear params
arguments for geneRecomb module:
 -n , --alignment input alignment (either -n/-fl is required for geneRecomb module)
 -fl , --alnlist input alignment list with path to gene alignments (either -n/-fl is required for geneRecomb module)
Enjoy the program! :)

Run : start_analysis.py ALL(coreGen/wgsRecomb/panRecomb)

Output Files

FAQS

1) Get Start - How to run ALL Module if you would like to run "wgsRecomb", "coreGen", and "coreRecomb" modules all together, you can just use the "ALL" module. Note: a reference genome (-r) is necessary to run "wgsRecomb" module

EXAMPLE:

start_analysis.py ALL -p PMEN1.dated \
-o $OUTPATH \
-i $INPATH/assemblies \
-r $INPATH/GCF_000026665.1_ASM2666v1_genomic.fna

1.1) If you already have gff files obtained from previous analysis, gff dir can be used as input for "coreGen module". This will saves a lot time

start_analysis.py ALL -p PMEN1.dated \
-o $OUTPATH \
-t 10 \
-g $INPATH/gff \ # gff dir as input
--mcr_path {path_to_previous_BactPrep_folder}/resources/mcr \ # absolute path to mcr R2016b
--fastgear_exe /home/user/SOFTWARE/fastGEARpackageLinux64bit # absolute path to fastGear excutable

2) Obtain Annotated Outputs if you would like to obtain annotated phylogenies and alignments, please provide a CSV file with annotation of every isolates. Flag -M must be specified for annotation. -a is the path to the CSV metadata file. -s allows the you to specify the index of the column matches with the input assemblies' file names , default is 1. -m asks for the column names of the metadata you would like to add for annotations (comma separated).

EXAMPLE CSV File: ENA Accession | Strain | Year | Country -- | -- | -- | -- ERS009226 | ARG 740 | 1995 | Argentina ERS009778 | 3122 | 1994 | Canada ERS009785 | 36148 | 2008 | Canada ERS004773 | HK P1 | 2000 | China ERS004775 | HK P38 | 2000 | China

EXAMPLE:

start_analysis.py ALL -p PMEN1.dated \
-o $OUTPATH \
-i $INPATH/assemblies \
-r $INPATH/GCF_000026665.1_ASM2666v1_genomic.fna \
-M \
-a $INPATH/PMEN1.dated.metadata.csv \
-s 1 \
-m Year,Country

3) IF you would only like to run "wgsRecomb" please keep in mind, a reference genome must provided by user."wgsRecomb" module will call snps from the reference genome for each input WGS assemblies, and combine them into a multiple sequence alignment using Snippy , where genome regions shared by all isolates in the input dataset will be extracted. Gubbins will take the Snippy input to detect recombination regions from the multi-sequence alignment. At end of the pipeline, SNPs outside of the recombination regions will be used to reconstruct the input dataset's phylogeny with IQTree . Annotation will be added to phylogenies and SNPs alignments if a metadata file is provided by user (please see example 2 for details).

EXAMPLE:

start_analysis.py wgsRecomb -p PMEN1.dated \
-o $OUTPATH \
-i $INPATH/assemblies \
-r $INPATH/GCF_000026665.1_ASM2666v1_genomic.fna

4) IF you would only like to run "coreGen" a reference file would be required for this module. All input WGS assemblies will be annotated by Prokka . Using prokka's gene annotations, Roary will 1) reconstruct the pangenome of the input dataset, and 2) identify core genes shared by 99% (this can be adjust by user by -c flag) of the isolates in the input dataset. Roary will also provide a core gene concatenation alignment, which will be used for phylogeny reconstruction using IQTree at end of the pipeline. Annotation will be added to phylogenies and SNPs alignments if a metadata file is provided by user (please see example 2 for details).

EXAMPLE:

start_analysis.py wgsRecomb -p PMEN1.dated \
-o $OUTPATH \
-i $INPATH/assemblies

5) IF you would only like to run "coreRecomb" pipeline implemented in the "coreGen" module will run first. "coreRecomb" module will identify homologous recombinaition from every core gene identified by Roary . The identified recombination regions will be masked in the gene alignments before all core genes' masked alignments are concatenated into a super-gene alignment. core SNPs outside of the recombination regions will be called, SNPs outside of the recombination regions will be used to reconstruct the input dataset's phylogeny with IQTree . Annotation will be added to phylogenies and SNPs alignments if a metadata file is provided by user (please see example 2 for details).

EXAMPLE:

start_analysis.py coreRecomb \
-p PMEN1.dated \
-o $WORKPATH -i $WORKPATH/assemblies \
-r $WORKPATH/GCF_000026665.1_ASM2666v1_genomic.fna \
-t 10 \
-M \
-a $WORKPATH/PMEN1.dated.metadata.csv \
-m Year,Country

6) IF matlab runtime (MCR) version R2016a is installed or this is not the first time you are running this pipeline. if you have already installed MCR R2016a and fastGear executable before on your machine, or you have already installed these two dependencies the previous times you were using BactPrep. You can use flag --mcr_path and --fastgear_exe to avoid installing these two dependencies again. you don't need to run INSTALL.sh script again if these two scripts is already installed, but a conda env still need to be created and activated to run BactPrep pipeline

EXAMPLE:

conda env create -f workflow/env/install.yaml -n BactPrep
conda activate BactPrep
start_analysis.py panRecomb -p PMEN1.dated_fastGear_pan \
-o $OUTPATH \
-t 10 \
-i $INPATH/assemblies \
--mcr_path {path_to_previous_BactPrep_folder}/matlab/v901 \
--fastgear_exe {path_to_previous_BactPrep_folder}/fastGEARpackageLinux64bit 

7) IF you would like to inform wgsRecomb (gubbins) about already known phage region phage region can be provided to snippy before running gubbins. If you would like to provide known phage region while running gubbins, use -v or --phage to provide phage region in a BED file.

EXAMPLE:

start_analysis.py wgsRecomb \
-p PMEN1.dated \
-o $WORKPATH -i $WORKPATH/assemblies \
-r $WORKPATH/GCF_000026665.1_ASM2666v1_genomic.fna \
-v $WORKPATH/phage_region.bed

8) IF additional arguments need to be specificed for Roary and Gubbins when using "coreGEN", "wgsRecomb", or "ALL" module additional Roary and Gubbins arguments that is not specificed by BactPrep can be added by using the -R of -G flags, respectively. Dependencies used for these additional arguments need to be install by user.

SPACE is necessary at the beginning of the string

Example:

start_analysis.py ALL \
-p PMEN1.dated \
-o $WORKPATH -g $WORKPATH/gff \
-r $WORKPATH/GCF_000026665.1_ASM2666v1_genomic.fna \
-R " -r -y -iv 1.5"
  1. If you have trouble installing fastGear with INSTALL.sh script. please follow the instruction below for installation.

    1. mcr has many versions, use the link to download the version compatible with fastGear :

      Download and install fastGear excutable:

      1. change directory to: {absolute_path_to_BactPrep}/resources/mcr
      2. you can download mcr provided by fastGear developers: https://users.ics.aalto.fi/~pemartti/fastGEAR/ wget --no-check-certificate https://users.ics.aalto.fi/~pemartti/fastGEAR/fastGEARpackageLinux64bit.tar.gz -P {absolute_path_to_BactPrep}/resources )
      3. Unzip the downloaded file tar -zvxf fastGEARpackageLinux64bit.tar.gz

      Download and install Matlab Runtime:

      1. Download MCR zip provided by fastGear developers: wget https://users.ics.aalto.fi/~pemartti/fastGEAR/MCRInstallerLinux64bit.zip -P {absolute_path_to_BactPrep}/resources --no-check-certificate

      2. Unzip the downloaded file unzip MCRInstallerLinux64bit.zip

        1. or download version R2016a from MATLAB: https://www.mathworks.com/products/compiler/matlab-runtime.html
      3. change directory after unzip the downloaded file cd MCRInstallerLinux64bit

      4. install: ./install -destinationFolder {absolute_path_to_BactPrep}/resources/mcr/ -mode silent -agreeToLicense yes

        1. if you would like to install with a GUI interface, please allow X11 display at the terminial, do ./install , this will open the GUI installation, and will allow you to change the directory to install, please install to {absolute_path_to_BactPrep}/resources/mcr
    2. if you already have mcr (R2016a) on your machine (or used this pipeline before), you do not need to reinstall mcr, please specify the absolute path with --mcr_path flag, which leads to the absolute path of your installed mcr

      1. --mcr_path : ex. --mcr_path {absolute_path_to_BactPrep}resources/mcr/

Code Snippets

10
11
12
13
14
15
16
17
18
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/change_fasta_header.py {input.metadata_file} {input.original_alignment} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
29
30
31
32
33
34
35
36
37
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/rename_phylogeny_taxa.py {input.metadata_file} {input.tree} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
10
11
12
13
14
15
16
17
18
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/change_fasta_header.py {input.metadata_file} {input.original_alignment} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
29
30
31
32
33
34
35
36
37
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/rename_phylogeny_taxa.py {input.metadata_file} {input.tree} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
10
11
12
13
14
15
16
17
18
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/change_fasta_header.py {input.metadata_file} {input.original_alignment} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
29
30
31
32
33
34
35
36
37
shell:
    """
    if [[ -n {input.metadata_file} ]]; 
    then
        python {WORKFLOW}scripts/rename_phylogeny_taxa.py {input.metadata_file} {input.tree} {params.meta_include} {params.key_column_index} {output}
    else
        touch {output}
    fi
    """
6
7
8
9
shell:
    """
    python {WORKFLOW}scripts/get.genes.roary.core.aln.py {input} {output}
    """
20
21
22
23
24
25
shell:
    """
    LD_LIBRARY_PATH={matlab_path}
    {fastGear_exe}run_fastGEAR.sh {mcr_path} {fastGear_dir}roary_pangenome_seq/{wildcards.core_locus}.fa.aln {fastGear_core_dir}core_loci_fastGear_out/{wildcards.core_locus}/{wildcards.core_locus}.mat {fastGear_params}
    cp {fastGear_dir}roary_pangenome_seq/{wildcards.core_locus}.fa.aln {fastGear_core_dir}core_loci_fastGear_out/{wildcards.core_locus}/{wildcards.core_locus}.fa
    """
45
46
47
48
shell:
    """
    bedtools maskfasta -fi {input.fasta} -bed {input.bed} -fo {output}
    """
61
62
63
64
run:
    loci = [file.split("/")[-1].split("_core_mask")[0].strip() for file in input if not file.startswith(".")]
    with open(str(output[0]), mode='w', encoding='utf-8') as myfile:
        myfile.write('\n'.join(loci))
73
74
75
76
77
78
79
80
81
shell:
    """
    cd {fastGear_core_dir}plot_coregenome/
    python {WORKFLOW}scripts/post_fastGear.py \
    -i {fastGear_core_dir}core_loci_fastGear_out \
    -g {input.loci} \
    -o {fastGear_core_dir}plot_coregenome/core_fastgear_plot \
    -s True -f pdf -p {input.tree} -z True -y 100 -x 100
    """
88
89
90
91
shell:
    """
        perl {WORKFLOW}scripts/catfasta2phyml.pl -f -c -s --verbose {fastGear_core_dir}masked_coregene_aln/*fasta > {output}
    """
100
101
102
103
shell:
    """
        snp-sites {input} -o {output}
    """
117
118
119
120
shell:
    """
        iqtree -bb 1000 -nt AUTO -m MFP -pre {params.prefix} -s {input.snps_aln} -fconst $(snp-sites -C {input.core_aln})
    """
 6
 7
 8
 9
10
11
12
shell:
    """
    for i in {params.input_files};
    do
    cp $i {fastGear_gene_dir}input_alns/{wildcards.gene}.fasta
    done
    """
22
23
24
25
26
shell:
    """
    LD_LIBRARY_PATH={matlab_path}
    {fastGear_exe}run_fastGEAR.sh {mcr_path} {input} {fastGear_gene_dir}{wildcards.gene}/{wildcards.gene}.mat {fastGear_exe}fG_input_specs.txt 
    """
 6
 7
 8
 9
10
shell:
    """
        mkdir -p {fastGear_dir}roary_pangenome_seq
        python {WORKFLOW}scripts/change.roary.gene.alns.headers.py {roary_dir}pan_genome_sequences {fastGear_dir}roary_pangenome_seq {input}
    """
18
19
20
21
22
23
shell:
    """
    LD_LIBRARY_PATH={matlab_path}
    {fastGear_exe}run_fastGEAR.sh {mcr_path} {fastGear_dir}roary_pangenome_seq/{wildcards.locus}.fa.aln {fastGear_dir}loci_fastGear_out/{wildcards.locus}/{wildcards.locus}.mat {fastGear_params} 
    cp {fastGear_dir}roary_pangenome_seq/{wildcards.locus}.fa.aln {fastGear_dir}loci_fastGear_out/{wildcards.locus}/{wildcards.locus}.fa
    """
35
36
37
38
39
run:
    loci = [file.split("/")[-3] for file in input]
    print(loci)
    with open(str(output[0]), mode='w', encoding='utf-8') as myfile:
        myfile.write('\n'.join(loci))
48
49
50
51
52
53
54
55
56
shell:
    """
    cd {fastGear_dir}plot_pangenome/
    python {WORKFLOW}scripts/post_fastGear.py \
    -i {fastGear_dir}loci_fastGear_out \
    -g {input.loci} \
    -o {fastGear_dir}plot_pangenome/pan_fastgear_plot \
    -s True -f pdf -p {input.tree} -z False -y 100 -x 100
    """
13
14
15
16
17
shell:
    """
    cd {gubbins_dir}
    run_gubbins.py{params.additional} --threads {threads} -v -p {params.out_prefix} {input}
    """
26
27
28
29
shell:
    """
    cat {input} | seqkit grep -v -p Reference > {output}
    """
42
43
44
45
shell:
    """
    iqtree -bb 1000 -nt AUTO -m MFP -pre {params.prefix} -s {input}
    """
13
14
15
16
17
18
19
shell:
    """
        PIRATE \
        -i {input} -o {params.out_dir} \
        -a -r -t {threads} \
        {params.mcl}       
    """
28
29
30
31
32
shell:
    """
       perl {WORKFLOW}PIRATE_to_roary.pl -i {input} -o {pirate_dir}pirate_roary_pres_abs.csv 

    """
4
5
6
7
shell:
    """
    mv {asm_dir}{wildcards.sample}* {output}
    """
21
22
23
24
25
26
27
28
shell:
    """
    prokka -kingdom {params.kingdom} \
    -outdir {output} \
    -prefix {wildcards.sample} \
    {input} --force -cpu {threads}

    """
34
35
36
37
shell:
    """
        cp {input}/{wildcards.sample}.gff {gff_dir}{wildcards.sample}".gff"
    """
16
17
18
19
20
21
22
23
shell:
    """
        roary{params.additional} -e -n -p {threads} -f {params.out_dir} {input} -v -cd {core_percentage} -z

        cp -r {roary_dir}*/* {roary_dir}

        rm -rf {roary_dir}_*
    """
36
37
38
39
shell:
    """
    iqtree -bb 1000 -nt AUTO -m MFP -pre {params.prefix} -s {input}
    """
6
7
script:
    "{WORKFLOW}scripts/get_sample_names.py"
11
12
13
14
shell:
    """
    snippy --outdir {output} --ctgs {input} --ref {reference} --cpus {threads}
    """
25
26
27
28
shell:
    """
    snippy-core{params.mask} {input} --prefix {snippy_dir}core
    """
37
38
39
40
41
shell:
    """
    snippy-clean_full_aln {input} > {snippy_dir}clean.full.aln

    """
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from Bio import SeqIO
import pandas as pd
import sys

print(sys.argv[1])
metadata = pd.read_csv(str(sys.argv[1]))

print(int(sys.argv[4]))
dict_key= metadata.columns[int(sys.argv[4])]

dict_list=[]
items_list=str(sys.argv[3]).split(",")
for item in items_list:
    temp_dict=metadata.loc[:,[dict_key,item]].set_index(dict_key).to_dict()[item]
    dict_list.append(temp_dict)

with open(str(sys.argv[5]), "w+") as w:
    print("start a new file, overwrriten the old file if exist")

with open(str(sys.argv[2])) as f, open(str(sys.argv[5]), "w") as w:
    records = SeqIO.parse(f,"fasta")
    for r in records:
        old_id = r.id
        new_name=r.id
        for d in range(len(dict_list)):
            current_dict= dict_list[d]
            current_meta=current_dict[old_id]
            new_name = new_name + "|" + str(current_meta) 
        r.id = new_name
        r.description = ""
        print(r.id)
        SeqIO.write(r, w, "fasta")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import pandas as pd
from Bio import SeqIO
import sys
import os

input_dir=sys.argv[1]
output_dir=sys.argv[2]

# read in roary's output file
roary_output=pd.read_csv(sys.argv[3])

# remove the first 14 columns
biosample_roaryID=roary_output.iloc[1,14:].to_frame()

# set the name for the columb with Roary ID 
biosample_roaryID.columns = ["RoaryID"]

# remove the cluster number after roary ID 
biosample_roaryID= biosample_roaryID["RoaryID"].str.split("_").str[0].to_frame()

# make rownames (BioSample Accesion) a column (instead of rownames)
biosample_roaryID.index.name = 'BioSampleID'

# reset the rwonames of the dataframe
biosample_roaryID.reset_index(inplace=True)

# turn dataframe into a dictionary between Roary ID and BioSample Accession 
biosample_roaryID_dict=biosample_roaryID.set_index('RoaryID').to_dict()['BioSampleID']

# declare a function to change the header from Roary output to Biosample ID
def change_header(gene_fasta, changed_fasta):
    with open(gene_fasta) as f, open(changed_fasta, "w") as w:
            records = SeqIO.parse(f,"fasta")
            for r in records:
                currentID=r.id
                roaryID = currentID.split("_")[0]
                BioSampleAcc=biosample_roaryID_dict[roaryID]
                r.id = BioSampleAcc
                r.description = ""
                SeqIO.write(r, w, "fasta")


# get directory
directory = os.fsencode(os.path.join(input_dir))

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    old_filename=os.path.join(input_dir,filename)
    new_filename=os.path.join(output_dir,filename)
    change_header(old_filename, new_filename)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os
from Bio import SeqIO
import sys

roary_aln_coreGenes = sys.argv[1]
roary_coreGenes_file = sys.argv[2]

with open(roary_coreGenes_file, "w") as w:
    print("Start writing core genes locus tag in Roary's core_gene_alignment.aln")


with open(roary_aln_coreGenes) as file:
    for line in file.readlines():
        if "locus_tag" in line:
                current_tag=line.split("=")[1]
                with open(roary_coreGenes_file, "a") as w:
                    w.write(current_tag)
1
2
3
4
5
import os

with open(snakemake.output[0], "w") as f:
    for file in os.listdir(snakemake.input[0]):
        f.write(os.path.splitext(file)[0] + "\n")
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import copy
from Bio import SeqIO
from collections import defaultdict
from collections import OrderedDict
from random import randint
import gzip
from glob import glob
import multiprocessing
import argparse
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from glob import glob
import pandas as pd
from Bio import Phylo
import pylab
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.ticker import FuncFormatter, MaxNLocator, MultipleLocator, FixedLocator, FormatStrFormatter #BW: for x-axis labelling
import os.path

def main():


    parser = argparse.ArgumentParser(description='make various plots from fastGEAR output')
    parser.add_argument("-i", type=str, help="FastGEAR folder. Should have folders with gene names only no suffix or prefix")
    parser.add_argument("-o", type=str, help="Ouput name")
    parser.add_argument("-g", type=str, help="Genes of interest GOI list. Can be comma separated after flag GOI1,GOI2,GOI3 or a file.txt with one GOI per line. GOIs need to be named exactly as per fastGEAR run", default = None)
    parser.add_argument("-b", type=str, help="Sample of interest SOI list. Can be comma separated after flag SOI1,SOI2,SOI3 or a file.txt with one SOI per line. SOIs need to be named exactly as per fastGEAR run. PLEASE NOTE, ancestral recombinations cannot be filtered out by sample name. Suggest using recent only if using SOI list.", default = None)
    parser.add_argument("-t", type=int, help="Threads", default = 4)
    parser.add_argument("-y", type=int, help="Minimum y value to display gene name is scatter plot", default = 4)
    parser.add_argument("-x", type=int, help="Minimum y value to display gene name is scatter plot", default = 4)
    parser.add_argument("-s", type=str2bool, help="Make scatter plot of recent Vs ancestral recombinations", default = True)
    parser.add_argument("-z", type=str2bool, help="Make heatmap of recombinations. Default True", default = True)
    parser.add_argument("-u", type=str2bool, help="Make recombinations per gene plot. Default True", default = True)
    parser.add_argument("-a", type=str2bool, help="Include ancestral recombination. Default True", default = True)
    parser.add_argument("-r", type=str2bool, help="Exclude genes that had no recombination. Default True", default = True)
    parser.add_argument("-p", type=str, help="Tree file for sample order OR txt file of samples in order one per line must end in .txt or will parse as tree file.")
    parser.add_argument("-f", type=str, help="File type. Default png.", default = 'png')
    parser.add_argument("-xs", type=int, help="Heatmap x-axis font size", default = '10')
    parser.add_argument("-d", type=int, help="Division factor to draw ticks in heatmap. If 0, will use gene boundaries", default = 0) #BW: for x-axis labelling
    args = parser.parse_args()

    fout_sanity_checker = open('counts.txt','w')
    #plot heatmap
    y_height, order = parse_tree(args) #BW added MaxYaxis to calculate y-axis ticks
    MaxYaxis = len(order)-1
    gene_len_dict = parse_genes(args)
    genes = list(gene_len_dict.keys())
    colors = ['blue','green','#e6194b','#f58231','#911eb4','#46f0f0','#f032e6',
              '#d2f53c','#fabebe','#008080','#e6beff','#aa6e28',
               '#808000','#000080','#808080','#000000','#aaffc3']#as distaninct as possible

    recombinations = defaultdict(int)
    for i in range(0, len(genes), args.t):
        chunk = genes[i:i+args.t]
        recent_recombinations_sets = scatter_multi('recent', i, args, chunk, order)
        for gene_recent, recent_recombinations in recent_recombinations_sets:
            recombinations[gene_recent] += len(recent_recombinations)
        if args.a:
            ancestral_recombinations_sets = scatter_multi('ancestral', i, args, chunk, order)
            for gene_ancestral, ancestral_recombinations in ancestral_recombinations_sets:
                recombinations[gene_ancestral] += len(ancestral_recombinations)
    #remove genes with no recombination
    if args.r:
        recombinations = {key:value for key,value in recombinations.items() if value != 0}
        gene_len_dict = {key:value for key,value in gene_len_dict.items() if key in recombinations}
        genes = [gene for gene in genes if gene in recombinations]
        assert len(genes) == len(recombinations)

    if args.u:
        print ('Making recombination count plot')
        #instanciate plot
        fig = plt.figure(figsize=(50, 50), dpi =300)
        ax = fig.add_subplot(111, aspect='equal') # Default (x,y), width, height
        #legend
        legend = []
        for i in range(9):#might need to make this dynamic...
            c=colors[i]
            i+=1.0
            i/=10.0
            p = patches.Rectangle((0.5, i), 0.1, 0.05, facecolor=c,edgecolor='black')
            legend.append(p)
        plt.legend(legend, ['0-24', '25-49', '50-74','75-99', '100-124','125-149','150-174','175-200', '200+'], fontsize=55)
        tick_locs = []
        lens = []
        for gene in recombinations:
            total_length = sum(list(gene_len_dict.values()))
            x, total_length_so_far, gene_len_percent = get_coords(args, gene_len_dict, gene, total_length)
            count = recombinations.get(gene)
            if count in list(range(0,25)):
                c=colors[0]
            elif count in list(range(25,50)):
                c=colors[1]
            elif count in list(range(50,75)):
                c=colors[2]
            elif count in list(range(75,100)):
                c=colors[3]
            elif count in list(range(100,125)):
                c=colors[4]
            elif count in list(range(125,150)):
                c=colors[5]
            elif count in list(range(150,175)):
                c=colors[6]
            elif count in list(range(175,200)):
                c=colors[7]
            elif count in list(range(201,1111)):
                c=colors[8]
            else:
                print ('number of recombinations exceeds codes ability to color!!!', count)
            if count == 0:
                height = 0.0
            else:
                height = (float(count)/2.0)*0.01
            p = patches.Rectangle((x, 0.0), gene_len_percent, height, facecolor=c,edgecolor=None)
            ax.add_patch(p)
            tick_locs.append(sum(lens) + gene_len_percent/2.0)#get loc in middle of gene
            lens.append(gene_len_percent)
        if len(recombinations) < 33:
            plt.xticks(tick_locs, list(recombinations.keys()),rotation=45, fontsize = 33)
        plt.title('Recombinations per ' + str(len(recombinations)) + ' gene')
        plt.savefig(args.o + '_recombination_count.' + args.f, dpi=300, bbox_inches='tight')
        plt.close('all')
        fout_sanity_checker.write('recombination count plot gene count: ' + str(len(recombinations)))
        for gene in recombinations:
            fout_sanity_checker.write(gene+',')
        fout_sanity_checker.write('\n')

    if args.z:
        print ('making heatmap...')
        #instanciate plot
        fig = plt.figure(figsize=(50, 50), dpi =300)
        ax = fig.add_subplot(111, aspect='equal') # Default (x,y), width, height
        for i in range(0, len(genes), args.t):
            tmp = genes[i:i+args.t]
            tmp = [(gene, args, gene_len_dict, y_height, order, colors) for gene in tmp]
            p = multiprocessing.Pool(processes = args.t)
            tmp_genes = p.map(make_patches, tmp)
            p.close()
            for gene_patch_list in tmp_genes:
                for gene_patch in gene_patch_list:
                    ax.add_patch(gene_patch)
        '''
        #BW Divide x axis by number of fractions, or by gene boundaries, depending on -d flag
        cumulativeLenlist = []
        if args.d is 0:
            #Set ticks by genes
            cumulativeLen2 = 0
            listOfGenes = []
            for key in gene_len_dict:
                cumulativeLen2 = cumulativeLen2 + gene_len_dict[key]
                cumulativeLenlist.append(cumulativeLen2/cumulativeLen)
                listOfGenes.append(key) #get list of genes for label
                ax.xaxis.set_major_locator(FixedLocator(cumulativeLenlist)) #Sets ticks at intervals of given by -d.
                ax.set_xticklabels((listOfGenes), fontsize=args.xs, rotation='vertical')

        else:
            divisionFactor = args.d
            ax.xaxis.set_major_locator(MultipleLocator(1/divisionFactor)) #Sets ticks at intervals of given by -d.
            ax.set_xticklabels(frange((0-(cumulativeLen/divisionFactor)), cumulativeLen, cumulativeLen/divisionFactor), fontsize=args.xs, rotation='vertical')
        #broke
        #ax.yaxis.set_major_locator(MultipleLocator(1/MaxYaxis)) #BW Sets y-axis ticks to match the number of taxa
        #print (MaxYaxis, 1/MaxYaxis)
        #ax.set_yticklabels(frange(0.0, MaxYaxis, 1.0/MaxYaxis), fontsize=0) #Sets labels for y-axis to invisible (size 0)
        '''
        fig.savefig(args.o + '_heat.' + args.f, dpi=300, bbox_inches='tight')
        plt.close('all')
    if args.s:
        print ('Getting recombinations per gene')
        #plot recent (y) Vs ancestral (x) on scatter plot
        data = {'x':[], 'y':[], 'gene':[]}
        for i in range(0, len(genes), args.t):
            chunk = genes[i:i+args.t]
            recent_recombinations_dicts = scatter_multi('recent', i, args, chunk, order)
            ancestral_recombinations_dicts = scatter_multi('ancestral', i, args, chunk, order)
            for gene_recent, recent_recombinations_dict in recent_recombinations_dicts:
                  data['y'].append(len(recent_recombinations_dict))
                  data['gene'].append(gene_recent)
            for j, tmp_tuple in enumerate(ancestral_recombinations_dicts):
                  gene_ancestral, ancestral_recombinations_dict = tmp_tuple
                  try: assert data['gene'][i+j] == gene_ancestral
                  except: print (data['gene'][i+j], gene_ancestral)
                  data['x'].append(len(ancestral_recombinations_dict))
        # display scatter plot data
        plt.figure(figsize=(15,15))
        plt.scatter(data['x'], data['y'], marker = 'o')
        plt.title('FastGEAR ancestral Vs recent recombinations', fontsize=20)
        plt.xlabel('Ancestral', fontsize=15)
        plt.ylabel('Recent', fontsize=15)
        plt.xticks([x for x in (range((max(data.get('x')) + 20)*2)[::20])], fontsize=10)#always more recent
        plt.yticks([x for x in (range(max(data.get('y')) + 20)[::20])], fontsize=10)
        # add labels
        with open(args.o + '_scatter_count.csv', 'w') as fout:
            fout.write('Gene,Recent,Ancestral\n')
            for label, x, y in zip(data['gene'], data['x'], data['y']):
                fout.write(','.join([label, str(y), str(x)]) + '\n')
                if x > int(args.x) and y > int(args.y):
                    plt.annotate(label, xy = (x, y), fontsize=15)
        plt.savefig(args.o + '_scatter.' + args.f, dpi=300, bbox_inches='tight')
        plt.close('all')

    fout_sanity_checker.close()

def str2bool(v):

    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def scatter_multi(when, i, args, tmp, order):

    tmp = [(args, gene, when, order) for gene in tmp]
    p = multiprocessing.Pool(processes = args.t)
    recombinations_dicts = p.map(count_recombinations, tmp)
    p.close()

    return recombinations_dicts

def make_patches(tuple_of_args):

    '''
    Calculate all patches
    '''

    gene, args, gene_len_dict, height, order, colors = tuple_of_args
    #parse FG output folder
    lineages, base = base_lineage(args, gene, order)
    recent_recombinations_dict = get_recombinations(args, gene, 'recent', order)
    ancestral_recombinations_dict = get_recombinations(args, gene, 'ancestral', order) #-no strain name details
    '''
    print (gene, 'order',order[:3],order)
    print ('')
    print (gene,'lineages',list(lineages.keys())[:3])
    print ('')
    print (gene,'recent_recombinations_dict',list(recent_recombinations_dict.keys())[:3],recent_recombinations_dict)
    print ('')
    print (gene,'ancestral_recombinations_dict',list(ancestral_recombinations_dict.keys())[:3],ancestral_recombinations_dict)
    '''
    #prepare colors
    yellow = '#ffff00' #most common - background
    tmp_colors = copy.deepcopy(colors)
    tmp_colors.insert(int(base), yellow)
    #pepare to make patches
    gene_len = gene_len_dict.get(gene)
    total_length = sum(list(gene_len_dict.values()))
    x, total_length_so_far, gene_len_percent = get_coords(args, gene_len_dict, gene, total_length)
    y = 1.0
    patches_list = []
    #width = 1.5/float(len(order))
    width= 0.01
    for j, sample in enumerate(order):
        if sample in lineages:
            c = tmp_colors[lineages.get(sample)]
            p = patches.Rectangle((x, y - height), gene_len_percent, height, facecolor=c,edgecolor='black', linewidth=width ) #(x,y), width, height
            patches_list.append(p)
            if len(ancestral_recombinations_dict) > 0:#identify the strains in the recipient lineage - lineage2 == lineages.get(sample)
                for recombination in ancestral_recombinations_dict:
                    if int(ancestral_recombinations_dict.get(recombination).get('lineage2')) == int(lineages.get(sample)):

                        start = ancestral_recombinations_dict.get(recombination).get('start')
                        end = ancestral_recombinations_dict.get(recombination).get('end')
                        c = tmp_colors[int(ancestral_recombinations_dict.get(recombination).get('lineage1'))]#use color of donor lineage
                        patches_list = overlay_recombinations(x, total_length, height, y, patches_list, width, c, start, end)
            if sample in recent_recombinations_dict:#recent ontop of ancestral

                for recombination in recent_recombinations_dict.get(sample):
                    start = recent_recombinations_dict.get(sample).get(recombination).get('start')
                    end = recent_recombinations_dict.get(sample).get(recombination).get('end')
                    c = tmp_colors[recent_recombinations_dict.get(sample).get(recombination).get('donor_lineage')]
                    patches_list = overlay_recombinations(x, total_length, height, y, patches_list, width, c, start, end)
        y -= height
    return patches_list

def overlay_recombinations(x, total_length, height, y, patches_list, width, c, start, end):

    tmp_x =  x + (start/total_length)
    recombination_len = (x + (end/total_length)) - tmp_x
    p = patches.Rectangle((tmp_x, y - height), recombination_len, height, facecolor=c, edgecolor='black', linewidth=width)
    patches_list.append(p)

    return patches_list

def parse_list(arg):

    if ',' in arg:
        GOI = arg.strip().split(',')
    else:
        GOI=[]
        with open(arg, 'r') as fin:
            for line in fin:
                GOI.append(line.strip())
    return GOI

def parse_tree(args):

    '''
    Get the order of sample in the tree
    '''

    order = []
    if args.p.endswith('.txt'):
        with open(args.p, 'r') as fin:
            for line in fin:
                order.append(line.strip())
    else:
        t = Phylo.read(args.p, 'newick')
        t.ladderize()#branches with fewer leaf nodes are displayed on top - as per itol
        for node in t.find_clades():
            if node.name:
                order.append(node.name)
        #PLot - full tree only
        fig = plt.figure(figsize=(15, 55), dpi =300)
        ax = fig.add_subplot(111)
        Phylo.draw(t, do_show=False, axes=ax, )
        pylab.axis('off')
        pylab.rcParams.update({'font.size': 0.5})
        pylab.savefig(args.o+'_tree.' + args.f,format=args.f, bbox_inches='tight', dpi=300)
        plt.close('all')

    if args.b:
        SOI = parse_list(args.b)
        order = [sample for sample in order if sample in SOI]
        last_sample_in_SOI = sorted(list(SOI))[-1]
        try:  assert len(SOI) == len(order)
        except: print ('Your sample names dont match those in the tree!!!! tree = ', node.name, 'ur input = ', last_sample_in_SOI)
    height = 1.00/len(order)
    #write
    with open('order_of_samples_from_tree.txt', 'w') as fout:
        for sample in order:
            fout.write(sample + '\n')
    print ('Number of samples in tree or order file: ', len(order))    

    return height, order


def parse_genes(args):

    '''
    Parse fastGEAR output folder
    '''
    if args.g:
        GOI = parse_list(args.g)
    if args.g:
        genes_output_folders = []
        for gene in GOI:
            genes_output_folders.append(args.i + '/' + gene)
    else:
        genes_output_folders = glob(args.i + '/*')
    number_of_samples = []
    gene_len_dict = OrderedDict()
    for i, gene_path in enumerate(genes_output_folders):
        if os.path.isfile(gene_path+'/output/recombinations_recent.txt'):
            if os.path.isfile(gene_path+'/output/lineage_information.txt'):
                with open(gene_path+'/output/recombinations_recent.txt', 'r') as fin:
                    if fin.readline().strip() == '0 RECENT RECOMBINATION EVENTS':
                        if not args.a:# skip if ancestral = Fasle
                            continue
                gene = gene_path.strip().split('/')[-1]
                if args.g:
                    if gene not in GOI:
                        continue
                found = False

                for suffix in ['.fa', '.fasta', '.fna', '.aln', '.fsa']:
                    if os.path.exists(gene_path + '/' + gene + suffix):
                        for i, record in enumerate(SeqIO.parse(gene_path + '/' + gene + suffix,'fasta')):
                            gene_len_dict[gene] = len(str(record.seq))
                            found = True
                        number_of_samples.append(i+1)
                if not found:
                    print('Cant find gene alignment for ' + gene + ' . Please use one of the following suffixes: .fa', '.fasta', '.fna', '.aln', '.fsa')
            else:
                print ('missing a file!!!!!!!!!!!!',gene_path+'/output/lineage_information.txt')
        else:
            print ('missing a file!!!!!!!!!!!!',gene_path+'/output/recombinations_recent.txt')
    if args.g:
        input_gene = sorted(list(GOI))[0]
        try:  assert len(GOI) == len(gene_len_dict)
        except: print ('Your gene names dont match those in fastGEAR!!!! fastGEAR = ', str(len(gene_len_dict)), 'example gene = ',gene,'ur input = ', str(len(GOI)), 'example gene = ', input_gene)
    print ('Number of genes is', len(gene_len_dict))
    print ('Max number of samples in an alignment is', max(number_of_samples))

    global cumulativeLen #BW declare global cumulativeLen variable so that it can be used for the heatmap Y-axis
    cumulativeLen = 0 #LM - does it need to be global?

    #write
    with open('order_and_length_of_genes.txt', 'w') as fout:
        for gene in gene_len_dict:
            cumulativeLen = cumulativeLen + gene_len_dict.get(gene) #BW
            fout.write(gene + '\t' + str(gene_len_dict.get(gene)) +'\t' + str(cumulativeLen) + '\n') #BW added cumulativeLen
    return gene_len_dict


def get_coords(args, gene_len_dict, gene, total_length):

    '''
    Get x coordinates
    '''
    gene_len = gene_len_dict.get(gene)
    gene_len_percent = gene_len/total_length
    total_length_so_far = 0
    x = 0.0
    gene_len = gene_len_dict.get(gene)
    total_length = sum(list(gene_len_dict.values()))
    for previous_gene in gene_len_dict:
        if previous_gene == gene:
            break
        previous_gene_len = gene_len_dict.get(previous_gene)
        previous_gene_len_percent = previous_gene_len/total_length
        total_length_so_far += previous_gene_len
        x += previous_gene_len_percent

    return x, total_length_so_far, gene_len_percent



def count_recombinations(tuple_of_args):

    args, gene, recent_or_ancestral, order = tuple_of_args
    #get recombination counts (start end are same)
    if args.b:
        SOI = parse_list(args.b)
    recombinations_dict = defaultdict(int)#this mays well be a set - never use teh count...
    if os.path.isfile(args.i + '/' + gene + '/output/recombinations_' + recent_or_ancestral + '.txt'):
        with open(args.i + '/' + gene + '/output/recombinations_' + recent_or_ancestral + '.txt', 'r') as fin:
            fin.readline()#RECOMBINATIONS IN LINEAGES
            fin.readline()#Start End Lineage1 Lineage2 log(BF)
            for line in fin:
                bits = line.strip().split()
                if bits == []:
                    continue
                if recent_or_ancestral == 'recent':
                    start, end, donor_lineage, recipient_strain, _, strain_name = bits[:6]
                    strain_name = get_sample(strain_name, order, gene)
                    if args.b:
                        if strain_name in SOI:
                            recombinations_dict[start + ':' + end] += 1
                    else:
                        recombinations_dict[start + ':' + end] += 1
                if recent_or_ancestral == 'ancestral':#is there a way to filter this by SOI? if not then using SOI with ancestral isn't great
                    start, end, l1, l2, _ = bits
                    recombinations_dict[start + ':' + end] += 1

    return (gene, recombinations_dict) 

def bits(line, recombinations_dict, order, gene):

    start, end, donor_lineage, recipient_strain, _, strain_name = line.strip().split()[:6]
    sample = get_sample(strain_name, order, gene)
    recombinations_dict[sample][start + ':' + end]['start'] = float(start)
    recombinations_dict[sample][start + ':' + end]['end'] = float(end)
    recombinations_dict[sample][start + ':' + end]['donor_lineage'] = int(donor_lineage)
    recombinations_dict[sample][start + ':' + end]['recipient_strain'] = recipient_strain

    return recombinations_dict

def get_recombinations(args, gene, age, order):

    '''
    from Pekka
     The way I draw the recombinations:
    1) For each ancestral recombination: identify the strains in the recipient lineage (this is assumed to be lineage 2, as it is the smaller one). Draw a segment in each of these strains, using the color of the donor lineage (Lineage 1).
2) For each recent recombination: draw a segment in the recipient, using the color of the donor lineage.

    Note that the recent recombinations should be on top of the ancestral ones. (Of course one could draw just one or the other)
    '''
    #get  recombinations
    if args.b:
        SOI = parse_list(args.b)
    if os.path.isfile(args.i + '/' + gene + '/output/recombinations_' + age + '.txt'):
        with open(args.i + '/' + gene + '/output/recombinations_' + age + '.txt', 'r') as fin:
            fin.readline()
            fin.readline()#Start End DonorLineage RecipientStrain log(BF) StrainName
            if age == 'recent':
                recombinations_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))
                for line in fin:
                    start, end, donor_lineage, recipient_strain, _, strain_name = line.strip().split()[:6]
                    sample = get_sample(strain_name, order, gene)
                    if args.b:
                        if sample in SOI:
                            recombinations_dict = bits(line, recombinations_dict, order, gene)
                    else:
                        recombinations_dict = bits(line, recombinations_dict, order, gene)
            if age == 'ancestral':
                recombinations_dict = defaultdict(lambda: defaultdict(str))
                for line in fin:
                    start, end, l1, l2, _ = line.strip().split()
                    recombinations_dict[start + ':' + end]['start'] = float(start)
                    recombinations_dict[start + ':' + end]['end'] = float(end)
                    recombinations_dict[start + ':' + end]['lineage1'] = int(l1)#donor
                    recombinations_dict[start + ':' + end]['lineage2'] = int(l2)#recipient
        return recombinations_dict

def get_sample(name, order, gene):

    sample = '_'.join(name.split('.')[0].split('_')[:-1]) #Removes any suffix. And contig number
    if 'MGAS5005' in name:
        sample = 'LD_MGAS5005_M1'
    if sample not in order:
        sample = name.split('.')[0]
        #try: assert sample in order #need a better way to test
        #except: print (name, 'is in the alignemnt for gene ',gene,' but not in -p input !')
    return sample


def base_lineage(args, gene, order):

    #get base lineage
    lineages = defaultdict(int)
    most_common = defaultdict(int)
    if os.path.isfile(args.i + '/' + gene + '/output/lineage_information.txt'):
        with open(args.i + '/' + gene + '/output/lineage_information.txt', 'r') as fin:
            fin.readline() #'StrainIndex', 'Lineage', 'Cluster', 'Name'
            for line in fin:
                strain_index, lineage, cluster, name = line.strip().split()[:4]
                sample = get_sample(name, order, gene)
                lineages[sample] = int(lineage)
                most_common[lineage] += 1
    else:
        print (gene +' has no base lineage_information.txt')

    count = 0
    for lineage in most_common:
        if most_common.get(lineage) > count:
            biggest = lineage
            count = most_common.get(lineage)

    return lineages, biggest

#Functions added by BW - to relabel axes
def format_fn(tick_val, tick_pos):
    if int(tick_val) in xs:
        return labels[int(tick_val)]
    else:
        return ''

def frange(start, stop, step):
    i = start
    while i < stop:
        yield int(i) #BW used int(i) to get rounded numbers
        i += step


if __name__ == "__main__":
    main()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pandas as pd
import os
from Bio import Phylo
import sys

allDated_meta = pd.read_csv(str(sys.argv[1]))
dict_key= allDated_meta.columns[int(sys.argv[4])]

dict_list=[]
items_list=str(sys.argv[3]).split(",")
for item in items_list:
    temp_dict=allDated_meta.loc[:,[dict_key,item]].set_index(dict_key).to_dict()[item]
    dict_list.append(temp_dict)


tree = Phylo.read(str(sys.argv[2]),"newick")

for taxa in tree.get_terminals():
    newname=str(taxa)
    for d in range(len(dict_list)):
        newname=newname + "|"+ str(dict_list[d][str(taxa)]) 
    tree.find_any(taxa).name = newname

Phylo.write(tree,str(sys.argv[5]),"newick")
ShowHide 31 more snippets with no or duplicated tags.

Login to post a comment if you would like to share your experience with this workflow.

Do you know this workflow well? If so, you can request seller status , and start supporting this workflow.

Free

Created: 1yr ago
Updated: 1yr ago
Maitainers: public
URL: https://github.com/rx32940/BactPrep
Name: bactprep
Version: 1
Badge:
workflow icon

Insert copied code into your website to add a link to this workflow.

Downloaded: 0
Copyright: Public Domain
License: MIT License
  • Future updates

Related Workflows

cellranger-snakemake-gke
snakemake workflow to run cellranger on a given bucket using gke.
A Snakemake workflow for running cellranger on a given bucket using Google Kubernetes Engine. The usage of this workflow ...