diff --git "a/data/dataset_Microbiology.csv" "b/data/dataset_Microbiology.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Microbiology.csv" @@ -0,0 +1,51299 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Microbiology","microsud/Tools-Microbiome-Analysis","CODE_OF_CONDUCT.md",".md","3359","77","# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behaviour that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at sudarshanshetty9@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq +","Markdown" +"Microbiology","microsud/Tools-Microbiome-Analysis","setup_microbiome_analysis.R",".R","2908","87"," +############################################################################################################################################ +# # +# START OF CODE # +# # +############################################################################################################################################ + +# These are some R pacakges I commonly use for analysis. Everytime I update R to latest version, I run this installation to in setup my environment. + +# Copy from here + +setup_microbiome_analysis <- function(){ + + .packages = c(""ape"", + ""gridExtra"", + ""picante"", + ""data.table"", + ""RColorBrewer"", + ""DT"", + ""reshape"", + ""reshape2"", + ""magrittr"", + ""markdown"", + ""ggpubr"", + ""tibble"", + ""pheatmap"", + ""dplyr"", + ""viridis"", + ""devtools"", + ""rmdformats"", + ""intergraph"", + ""network"", + ""igraph"", + ""ggplot2"", + ""gridExtra"", + ""knitr"", + ""vegan"", + ""plyr"", + ""dplyr"", + ""ggrepel"", + ""ggnetwork"", + ""ade4"", + ""rmarkdown"", + ""formatR"", + ""caTools"", + ""GGally"") + + .bioc_packages <- c(""phyloseq"", + ""microbiome"", + ""phangorn"", + ""genefilter"") + if (!requireNamespace(""BiocManager"", quietly = TRUE)) + install.packages(""BiocManager"") + + # Install CRAN packages (if not already installed) + .inst <- .packages %in% installed.packages() + if(length(.packages[!.inst]) > 0) install.packages(.packages[!.inst]) + + .inst <- .bioc_packages %in% installed.packages() + if(any(!.inst)) { + BiocManager::install(.bioc_packages[!.inst]) + } + + + if (!(""microbiomeutilities"" %in% installed.packages())) { + devtools::install_github(""microsud/microbiomeutilities"") + } + + if (!(""SpiecEasi"" %in% installed.packages())) { + devtools::install_github(""zdk123/SpiecEasi"") + } + + if (!(""ggnet"" %in% installed.packages())) { + devtools::install_github(""briatte/ggnet"") + } + + message(""If there was no error then you are ready to do microbiome data analysis"") + +} + +setup_microbiome_analysis() + +# Copy until here previous line! + +####################################################END OF CODE########################################################################### + +","R" +"Microbiology","lskatz/lyve-SET","plugins/correct_vcf_filter.py",".py","2241","71","#!/usr/local/bin/python +# Khushbu Patel | 05/15/2018 +# Corrects the filter and Calculates number of bases falsely assigned incorrect filter when the bases pass the consensus and coverage. Prints out a new vcf with filters corrected. +# Python 3.4 +# Usage: ./correct_vcf_filter.py inputfile.vcf +# Output will be another vcf file, named correct_vcf.vcf; This script will not overwrite the original VCF + +import sys +import os +import subprocess + +infile= sys.argv[1] # Takes the file name as a command line argument +f=open(infile,""r"") + +basename = os.path.basename(infile) +outfile_vcf = basename + ""_corrected.vcf"" +outfile_txt = basename + ""_corrected.txt"" +temp = [] +count = 0 +out = [] +ID = '' +old_filter = 0 + + +with open(outfile_vcf, 'a') as f1: + with open(outfile_txt, 'a') as f2: + f2.write( ""CHROM\tPOS\tNEW_FILTER\tDEPTH\tFREQ\tOLD_FILTER\n"") + for line in f: + line =line.rstrip() + if line.startswith('#'): + ID = line # Printing the headers + f1.write(ID) + f1.write(""\n"") + + else: + array = line.split() + temp = array[9].split(':') + + if(array[6] != ""PASS""): + if(len(temp)> 6): + old_filter = array[6] # Stores old filter + temp[6] = temp[6].replace('%','') + if(int(temp[3]) >= 20 and float(temp[6]) < 5.0): # if coverage and consensus both meet, change the filter to PASS + #print(line, ""--Incorrect Filter!"") # Sanity check! + array[6] = ""PASS"" + count += 1 # Count the number of sites that have been assigned wrong filter + out = '\t'.join(array) + f1.write(out) + str = array[0]+'\t'+array[1]+'\t'+array[6]+'\t'+temp[3]+'\t'+temp[6]+'\t'+old_filter+'\n' + f2.write(str) + + + else: # if allele frequency is greater than 5% or coverage does not meet; keep the filter + out = '\t'.join(array) + f1.write(out) + f1.write(""\n"") + + else: # else - print everything as is + out = '\t'.join(array) + f1.write(out) + f1.write(""\n"") + + else: # else - print everything as is + out = '\t'.join(array) + f1.write(out) + f1.write(""\n"") + + + +print('Number of sites that had been assigned wrong filters %d'%count) +","Python" +"Microbiology","lskatz/lyve-SET","docs/TESTDATA.md",".md","999","16","To make a test dataset, create a directory with all lowercase with the the files SRA and NUCLEOTIDE. These files are described below; you do not have to create any other files in the test data directory. + +All directories must start off by containing the files SRA and NUCLEOTIDE which have identifiers for raw reads and for genome assemblies (draft or finished). The first identifier in NUCLEOTIDE will be the reference genome. + +The final files/directories in each must be the following +asm/ NUCLEOTIDE reads/ reference/ SRA +* asm/ has all the genome assemblies +* NUCLEOTIDE has all assembly identifiers. The reference genome is the first listing +* reads/ has all raw read fastq files +* reference/ contains a single reference genome assembly +* SRA has a listing of all raw read identifiers that should be downloaded + +CREDITS +* Test lambda data were obtained from the CFSAN SNP pipeline at https://github.com/CFSAN-Biostatistics/snp-pipeline +* Other datasets were created between EDLB and CFSAN +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/OUTPUT.md",".md","7316","133","Below is a visualization of the workflow with output files. +Then in the next section, a table with the description of all output files. + +Visualization of output files +============================= + +```mermaid +flowchart TD + subgraph LOGDIR [""log directory""] + LOG[""main log file""] + subgraph LOGSUBDIR [""SGELK subfolder""] + LOGS[""launch_set.pl.$$.log: individual log files""] + JOBS[""qsub.$$.pl: individual jobs to execute""] + FINISHED[""launch_set.pl.$$.finished: individual jobs that were finished""] + SUBMITTED[""launch_set.pl.$$.submitted: individual jobs that were submitted""] + RUNNING[""launch_set.pl.$$.running: individual jobs that are running""] + end + end + + SET_MANAGE_CREATE[--create] --> |Create all directories such as reads, reference| READSDIR + SET_MANAGE_READS[--add-reads] --> |Create all directories such as reads, reference| READSDIR + SET_MANAGE_ASM[--add-assembly] --> |Add an assembly| ASMDIR + SET_MANAGE_REF[--change-reference] --> |Add a reference genome| REFDIR + SET_MANAGE --- SET_MANAGE_CREATE + SET_MANAGE --- SET_MANAGE_READS + SET_MANAGE --- SET_MANAGE_ASM + SET_MANAGE --- SET_MANAGE_REF + subgraph READSDIR [""reads directory""] + direction LR; + SEQUENCER[""R1 R2 fastq files""] + RAW[""Raw reads""] + CLEANED[""Cleaned reads""] + + RAW --> |run_assembly_trimClean.pl| CLEANED + SEQUENCER --> |shuffleSplitReads.pl| RAW + + end + subgraph REFDIR [""reference directory""] + direction LR; + REF[""Reference genome""] + UNMASKEDBED[""unmaskedRegions.bed""] + MASKEDBED[""maskedRegions.bed""] + + REF --> |findPhages.pl| MASKEDBED + MASKEDBED --> |invert| UNMASKEDBED + end + subgraph ASMDIR [""asm directory""] + INASM[""input assemblies""] + end + LAUNCH_SMALT{{launch_smalt.pl}} + + ASMDIR --> |samtools wgsim| READSDIR + READSDIR --> |launch_smalt.pl| LAUNCH_SMALT + REFDIR --> |launch_smalt.pl; only accept unmasked regions| LAUNCH_SMALT + LAUNCH_SMALT --> |make a bam, once per genome| BAMDIR + subgraph BAMDIR [""bam directory""] + direction LR; + BAM[""*.bam""] + BAMIDX[""*.bam.bai""] + BAMCLIFFS[""*.bam.cliffs.bed""] + + BAM --> |set_findCliffs.pl| BAMCLIFFS + BAM --> |samtools index| BAMIDX + end + LAUNCH_VARSCAN{{launch_varscan.pl}} + + BAMDIR --> |launch_varscan.pl \nexclude any regions in *.bam.cliffs.bed\nAccept SNPs at %consenus, X depth, fwd/rev support| LAUNCH_VARSCAN + REFDIR --> |launch_varscan.pl\ndo not reprocess with unmaskedRegions.bed \nb/c launch_smalt.pl already used it| LAUNCH_VARSCAN + LAUNCH_VARSCAN --> |make a vcf, once per genome| VCFDIR + subgraph VCFDIR [""VCF directory""] + direction LR; + VCF[""vcf files""] + VCFIDX[""vcf index files""] + + VCF --> |bcftools index| VCFIDX + end + VCFDIR --> |set_mergeVcf.sh: combine all Vcfs into \nout.pooled.vcf.gz and out.pooled.snps.vcf.gz| MSADIR + subgraph MSADIR [""MSA directory""] + direction LR; + MERGEVCF{{set_mergeVcf.sh}} + VCFPOOLED[""out.pooled.vcf.gz""] + VCFSNPSPOOLED[""out.pooled.snps.vcf.gz""] + SNPMATRIX[""out.snpmatrix.tsv""] + FILTEREDMATRIX[""out.filteredMatrix.tsv""] + FULLALN[""out.aln.fasta""] + INFORMATIVEALN[""out.informative.fasta""] + TREE[""out.RAxML_bipartitions; tree.dnd""] + PAIRWISE[""out.pairwise.tsv""] + PAIRWISEMATRIX[""out.pairwiseMatrix.tsv""] + + MERGEVCF --> VCFPOOLED + MERGEVCF --> VCFSNPSPOOLED + VCFPOOLED --> |pooledToMatrix.sh| SNPMATRIX + SNPMATRIX --> |filterMatrix.pl| FILTEREDMATRIX + SNPMATRIX --> |matrixToAlignment.pl| FULLALN + FILTEREDMATRIX --> |matrixToAlignment.pl| INFORMATIVEALN + FULLALN --> |pairwiseDistances.pl| PAIRWISE + PAIRWISE --> |pairwiseTo2d.pl| PAIRWISEMATRIX + INFORMATIVEALN --> |launch_raxml.sh| TREE + end +``` + +Output files +============ +| File | Description | Notes | +|:--------|:---------------|:------| +|project/msa | The multiple sequence alignment directory | Most of the output files you want are here like the multiple sequence alignment and the phylogeny| +|`project/msa/out.pooled.vcf.gz` | The pooled VCF file created from `bcftools merge` | +|`project/msa/out.pooled.snps.vcf.gz` | SNPs vcf | The same data as `out.pooled.vcf.gz` but filtered to SNPs only. | +|`project/msa/out.pooled.vcf.gz.tbi`, `out.pooled.snps.vcf.gz.tbi` | the tabix index file for each VCF | +|`project/msa/out.snpmatrix.tsv` | The `bcftools query` output | This file is essentially the main SNP matrix and describes the position and allele for each genome. Each allele is in the genotype (GT) format, as specified in the vcf format specification | +|`project/msa/out.filteredMatrix.tsv` | The filtered `bcftools query` output | After `out.snpmatrix.tsv` is generated, this file describes remaining SNPs after some are filtered out, usually because the `--allowedFlanking` option in `launch_set.pl`, `--allowed` in `filterMatrix.pl`, or similar parameters in other scripts | +|`project/msa/out.aln.fasta` | The output alignment file in fasta format. | Make any changes to this file before running a phylogeny |program. Do not use `out.informative.fasta` to make edits because positions might come and go and therefore you might lose resolution. After any edits, use `removeUninformativeSites.pl` to re-create `out.informative.fasta` | +| `project/msa/out.informative.fasta` | The alignment after removing uninformative columns (ambiguities, invariants, gaps) | Do not make any changes to this file before running a phylogeny. Make the changes in `out.aln.fasta` | +| `project/msa/out.RAxML_bipartitions` | RAxML-generated tree in newick format | +| `project/msa/tree.dnd` | Symlink to `out.RAxML_bipartitions`| +| `project/msa/out.pairwise.tsv` | Pairwise distances file | Format: tab-delimited with three columns: genome1, genome2, hqSNP distance | +| `project/msa/out.pairwiseMatrix.tsv` | Pairwise distances matrix | The same data as `out.pairwise.tsv`, but in a 2-d matrix. Generated with `pairwiseTo2d.pl`. | +|project/log| Log files| +|`project/log/launch_set.log` | The main log file | +|project/asm, project/reads || The input assemblies and reads. | +|project/reference | Where the reference fasta file is| +|`project/reference/maskedRegions.bed` | Regions of the reference genome that is masked for analysis. | +|project/reference/maskedRegions | BED-formatted files that describe regions that should be masked in the reference genome.| You may also create your own file that can have any filename with extension `.bed`. This file can describe your manually-chosen regions that should be masked. These regions will be incorporated into `project/reference/maskedRegions.bed`.| +|`project/reference/maskedRegions/phages.bed`| BED-formatted file describing predicted phage sites|| +|project/bam| Output bam files are here| +|`project/bam/*.sorted.bam` | Sorted bam files | The query and reference name are encoded in the filename; many times the reference name will just be called ""reference."" | +|`project/bam/*.sorted.bam.bai` | Samtools index file | +|`project/bam/*.sorted.bam.cliffs.bed` | Files describing genome depth cliffs | These are only present if you specified `--mask-cliffs` | +|project/vcf |VCF files|Have the same file format as the `*.sorted.bam` files, so that they can be matched easily when running Lyve-SET. These files are sorted with vcftools and compressed with bgzip.| +|`project/vcf/*.vcf.gz`|VCF files || +|`project/vcf/*.vcf.gz.tbi`| Tabix index files| +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/TIPS.md",".md","16327","348","# Tips and Tricks + +Here are just some tips and tricks that I have used or that others have contributed + +## Masking a region in your reference genome + +Yes, there is actually a mechanism to manually mask troublesome regions in the reference genome! Under `project/reference/maskedRegions`, create a file with an extension `.bed`. This file has at least three columns: `contig`, `start`, `stop`. BED is a standard file format and is better described here: https://genome.ucsc.edu/FAQ/FAQformat.html#format1 + +The Lyve-SET phage-finding tool that uses PHAST actually puts a `phages.bed` file into that directory. In the course of the pipeline, Lyve-SET will use any BED files in that directory to 1) ignore any reads that are mapped entirely in those regions and 2) ignore any SNPs that are found in those regions. In the future, Lyve-SET will also use individualized BED files in the bam directory to mask SNPs found on a per-genome basis. + +## Using multiple processors on a single-node machine + +Unfortunately if you are not on a cluster, then Lyve-SET will only work on a single node. Here are some ways of using xargs to speed up certain steps of Lyve-SET. Incorporating these changes or something similar is on my todo list but for now it is easier to post them. + +### Making pileups + +In the case where you want to generate all the pileups on one node using SNAP using 24 cores + + ls reads/*.fastq.gz | xargs -n 1 -I {} basename {} | xargs -P 24 -n 1 -I {} launch_smalt.pl -f reads/{} -b bam/{}-2010EL-1786.sorted.bam -t tmp -r reference/2010EL-1786.fasta --numcpus 1 + +### Calling SNPs + +In the case where you have all pileups finished and want to call SNPs on a single node. This example uses 24 cpus. At the end of this example, you will still need to sort the VCF files (`vcf-sort`), compress them with `bgzip`, and index them with `tabix`. + + # Call SNPs into vcf file + ls bam/*.sorted.bam | xargs -n 1 -I {} basename {} .sorted.bam | xargs -P 24 -n 1 -I {} sh -c ""/home/lkatz/bin/Lyve-SET/scripts/launch_varscan.pl bam/{}.sorted.bam --tempdir tmp --reference reference/2010EL-1786.fasta --altfreq 0.75 --coverage 10 > vcf/{}.vcf"" + # sort/compress/index + cd vcf; + ls *.vcf| xargs -I {} -P 24 -n 1 sh -c ""vcf-sort < {} > {}.tmp && mv -v {}.tmp {} && bgzip {} && tabix {}.gz"" + +## SNP interrogation + +### What are the differences between just two isolates? + +Sometimes you just want to know the SNPs that define one isolate, or maybe find which SNPs define which clades. +Here is a method to show unique SNPs between two isolates. +You can expand this idea to more isolates or otherwise refine it as needed. + +```bash +$ cut -f 1,2,5,6 out.snpmatrix.tsv | awk '$3!=$4 && $3!=""N"" && $4!=""N""' | head -n 3 +# [1]CHROM [2]POS [5]sample1:GT [6]sample2:GT +gi|9626243|ref|NC_001416.1| 403 A G +gi|9626243|ref|NC_001416.1| 753 A G +``` + +In this example, only the first two sites are shown (`head -n 3`) +and show that at positions 403 and 753, there are differences between sample1 and sample2. +Sites with `N` are ignored with logic like `$3!=""N""`. +Otherwise `awk` is just selecting for rows where the samples differ (`$3!=$4`) +`cut` is used to grab only the position columns 1 and 2 and then to keep only two samples at columns 5 and 6. + +### What are the differences between two groups of isolates? + +To do this, we can run `bcftools isec` in combination with `bcftools filter` and `bcftools view`. +In this section, we can use the lambda subset to pretend that there are two clades with clade1 having sample1 and sample2, +and clade2 having samples 3 and 4. + +Go into the `msa` subfolder with `cd msa`. + + # Make files with sample1 and sample2, and then sample3 and sample4 + echo -e ""sample1\nsample2"" > clade1.txt + echo -e ""sample3\nsample4"" > clade2.txt + +Use the file that already contains SNPs for all samples and divide it into the two clades + + bcftools filter -i 'ALT!=""N""' out.pooled.snps.vcf.gz | \ + bcftools view -S clade1.txt | \ + bgzip -c > clade1.snps.vcf.gz + bcftools filter -i 'ALT!=""N""' out.pooled.snps.vcf.gz | \ + bcftools view -S clade2.txt | \ + bgzip -c > clade2.snps.vcf.gz + +Index the new VCF files + + tabix clade1.snps.vcf.gz + tabix clade2.snps.vcf.gz + +Find the intersection of all SNPs between the two clades + + bcftools isec -p isec clade1.snps.vcf.gz clade2.snps.vcf.gz + +Go into the new `isec` folder and format all the vcf files + + cd isec + for i in *.vcf; do + bgzip $i + tabix $i.gz + done + +View the notes on which file is which. Typically, `0000.vcf.gz` is going to be sites exclusive to only clade1. +`0001.vcf.gz` is going to be sites exclusive to only clade2. +`0002.vcf.gz` is records in clade1 that are also in clade2. +`0003.vcf.gz` is records in clade2 that are also in clade1. + + cat README.txt + + This file was produced by vcfisec. + The command line was: bcftools isec -p isec clade1.snps.vcf.gz clade2.snps.vcf.gz + + Using the following file names: + isec/0000.vcf for records private to clade1.snps.vcf.gz + isec/0001.vcf for records private to clade2.snps.vcf.gz + isec/0002.vcf for records from clade1.snps.vcf.gz shared by both clade1.snps.vcf.gz clade2.snps.vcf.gz + isec/0003.vcf for records from clade2.snps.vcf.gz shared by both clade1.snps.vcf.gz clade2.snps.vcf.gz + +Merge back into one happy VCF file + + bcftools merge 0002.vcf.gz 0003.vcf.gz > merged.vcf + bgzip merged.vcf + tabix merged.vcf.gz + +View it. These are now SNPs that _could_ differentiate clade1 from clade2, but not necessarily 100%. +For example, a SNP might only occur in sample1 but not sample2 even though it's the same clade. + + query -H -f '%CHROM\t%POS\t%REF\t%ALT[\t%GT]\n' merged.vcf.gz | column -ts $'\t' | less -S + +In our example with lambda, with its star phylogeny, however, we do not have SNPs that are 100%. +Hopefully your results differ in this regard :) + + # [1]CHROM [2]POS [3]REF [4]ALT [5]sample1:GT [6]sample2:GT [7]sample3:GT [8]sample4:GT + gi|9626243|ref|NC_001416.1| 403 G A 1/1 0/0 0/0 0/0 + gi|9626243|ref|NC_001416.1| 550 G A 0/0 0/0 0/0 1/1 + gi|9626243|ref|NC_001416.1| 586 C G 0/0 0/0 0/0 1/1 + gi|9626243|ref|NC_001416.1| 753 G A 1/1 0/0 0/0 0/0 + gi|9626243|ref|NC_001416.1| 1019 C T 0/0 0/0 0/0 1/1 + +### SNP counting + +How many sites are in the Lyve-SET analysis? Count the number of lines in `out.snpmatrix.tsv`. Subtract 1 for the header. + +How many SNPs are in the Lyve-SET analysis? Count the number of lines in `out.filteredMatrix.tsv`. Subtract 1 for the +header. + +I want to count the number of sites as defined as X. Use `out.snpmatrix.tsv` and `filterMatrix.pl` to filter it your way. If you are an advanced user, you can use `bcftools query` on `out.pooled.vcf.gz`. + +### Why did a SNP fail? + +To see why any SNP failed, view the vcf files in the VCF directory. Parse them with `bcftools`. + +#### View the FILTER column + + $ bcftools query -f '%CHROM\t%POS\t%REF\t%ALT\t%FILTER\n' sample1.fastq.gz-reference.vcf.gz | head + gi|9626243|ref|NC_001416.1| 1 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 2 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 3 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 4 C N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 5 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 6 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 7 C N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 8 G N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 9 A N DP10;AF0.75 + gi|9626243|ref|NC_001416.1| 10 C N DP10;AF0.75 + +#### View MORE information with bcftools + + $ bcftools query -f '%CHROM\t%POS\t%REF\t%ALT\t%FILTER[\t%TGT\t%DP]\n' sample1.fastq.gz-reference.vcf.gz | head + gi|9626243|ref|NC_001416.1| 1 G N DP10;AF0.75 N/N 2 + gi|9626243|ref|NC_001416.1| 2 G N DP10;AF0.75 N/N 4 + gi|9626243|ref|NC_001416.1| 3 G N DP10;AF0.75 N/N 4 + gi|9626243|ref|NC_001416.1| 4 C N DP10;AF0.75 N/N 4 + gi|9626243|ref|NC_001416.1| 5 G N DP10;AF0.75 N/N 4 + gi|9626243|ref|NC_001416.1| 6 G N DP10;AF0.75 N/N 5 + gi|9626243|ref|NC_001416.1| 7 C N DP10;AF0.75 N/N 5 + gi|9626243|ref|NC_001416.1| 8 G N DP10;AF0.75 N/N 6 + gi|9626243|ref|NC_001416.1| 9 A N DP10;AF0.75 N/N 6 + gi|9626243|ref|NC_001416.1| 10 C N DP10;AF0.75 N/N 6 + +#### View the definitions for FILTER codes + +For example, `DP10` indicates that the user set 10x as a threshold and the site has less than 10x coverage. + + $ zgrep ""##FILTER"" sample1.fastq.gz-reference.vcf.gz + ##FILTER= + ##FILTER= + ##FILTER= + ##FILTER= + ##FILTER= + ##FILTER= + ##FILTER= + +### Find constant sites + +Lyve-SET focuses on variable sites, but what if you wanted to look at how many constant sites there are? +This is at least useful for when you need to tell BEAST or other similar programs what your constant sites are. + +To get the full alignment, you can run the following `bcftools` command, +followed by some parsing + +```bash +bcftools query -f '%CHROM\t%POS\t%REF\t[%TGT\t]\n' --print-header out.pooled.vcf.gz > full.tsv.unrefined.tmp + +# Get the first nucleotide of every nucleotide call to convert from diploid to haploid +perl -lane ' + BEGIN{ + # print the header + $line=<>; + chomp($line); + print $line; + $numFields=scalar(split(/\t/,$line)); + $lastIndex=$numFields-1; +} +for(@F[3..$lastIndex]){ + $_=substr($_,0,1); +} +print join(""\t"",@F); +' < full.tsv.unrefined.tmp > full.tsv +# Now you have full.tsv + +# Parse full.tsv to get counts of constant sites +tail -n +2 full.tsv | perl -MData::Dumper -lane ' + # Print a dot every 100k lines + print STDERR ""Looked at $. lines"" if($. % 100000 == 0); + + # Remove the contig, pos, ref fields + splice(@F,0,3); + # Pretend the first sample is the reference + # and remove it from the list of samples with shift() + $ref=shift(@F); + # Skip if ""reference"" base is ambiguous + next if($ref eq ""N""); + # The site is constant until proven otherwise + $is_constant=1; + # Loop through all samples after the first + for my $nt(@F){ + # If the samples nucleotide is not equal to the first samples, + # then label as not constant and go to the next site + if($nt ne $ref){ + $is_constant=0; + last; + } + } + $const{$ref} += $is_constant; + END{ + print Dumper \%const; + print STDERR ""\n""; + } +' +``` + +This will give you output similar to + +```text +$VAR1 = { + 'A' => 638550, + 'T' => 683152, + 'C' => 443617, + '.' => 0, + 'G' => 412973 + }; +``` + +Where you get counts for every nucleotide where it was constant at any given site in the set of samples. +You might be able to put it into BEAST with some syntax similar to (but not necessarily): + +```xml + + + + + + + + +``` + +And then, lastly, to get the full alignment including constant sites, you can transform `full.tsv` like so + +```bash +matrixToAlignment.pl full.tsv > full.fasta +``` + +## A word on Grapetree and other minimum spanning tree software + +It has been asked before if you can use Grapetree or something similar with Lyve-SET results. +First, yes you can but second, _why_? +A minimum spanning tree (MST) is useful for grouping similar profiles into the same circle. +Circles of profiles are linked by lines of a certain distance. +Then, circles of profiles are larger or smaller depending on how many members are in the circle. +This is a great way to visualize something like an outbreak. +However, it is not so great if every single sample has a different profile. +If you have different profiles, suddenly the MST becomes less informative and more chaotic. + +If you still want to do this, then here are some example steps on how to run Grapetree on Lyve-SET results. + +```bash +# make the profile spreadsheet from the alignment +# by formatting the alignment into two-lines-per-entry fasta +seqtk seq -l 0 out.informative.fasta | \ + perl -lane ' + # Get the defline + $sample=$_; + # Get the sequence + $seq=<>; + # Remove the newlines + chomp($sample, $seq); + # Remove the > from the defline + $sample =~ s/>//; + # Transform the sequence into a set of sites in an array + @seq=split(//, $seq); + # Print the profile + print join(""\t"", $sample, @seq); + # Find out how many sites there are for the next step using STDERR + print STDERR ""# numSites: "".scalar(@seq); + ' > profile.tmp.tsv +# numSites: 168 +# numSites: 168 +# numSites: 168 +# numSites: 168 +``` + +Now that we have a profile in `profile.tmp.tsv`, we still need a header using `168` sites. + +```bash +# Generate a header of sites. ""0"" for the column of samples. +seq 0 168 | tr '\n' '\t' > profile.tsv +# Punctuate the header with a newline +echo >> profile.tsv +# Grab the data +cat profile.tmp.tsv >> profile.tsv +# Run grapetree however you want. Here is a very simple invocation. +grapetree --profile profile.tsv +(sample1:85,sample2:80,sample3:75,sample4:0); +``` + +## Other manual steps in Lyve-SET + +### From a set of VCFs to finished results + + mergeVcf.sh -o msa/out.pooled.vcf.gz vcf/*.vcf.gz # get a pooled VCF + cd msa + pooledToMatrix.sh -o out.bcftoolsquery.tsv out.pooled.vcf.gz # Create a readable matrix + filterMatrix.pl --noambiguities --noinvariant < out.bcftoolsquery.tsv > out.filteredbcftoolsquery.tsv # Filter out low-quality sites + matrixToAlignment.pl < out.filteredbcftoolsquery.tsv > out.aln.fas # Create an alignment in standard fasta format + set_processMsa.pl --numcpus 12 --auto --force out.aln.fas # Run the next steps in this mini-pipeline + +### Manual steps in `set_processMsa.pl` + +Hopefully all these commands make sense but please tell me if I need to expound. + + cd msa + removeUninformativeSites.pl --gaps-allowed --ambiguities-allowed out.aln.fas > /tmp/variantSites.fasta + pairwiseDistances.pl --numcpus 12 /tmp/variantSites.fasta | sort -k3,3n | tee pairwise.tsv | pairwiseTo2d.pl > pairwise.matrix.tsv && rm /tmp/variantSites.fasta + set_indexCase.pl pairwise.tsv | sort -k2,2nr > eigen.tsv # Figure out the most ""connected"" genome which is the most likely index case + launch_raxml.sh -n 12 informative.aln.fas informative # create a tree with the suffix 'informative' + applyFstToTree.pl --numcpus 12 -t RAxML_bipartitions.informative -p pairwise.tsv --outprefix fst --outputType averages > fst.avg.tsv # look at the Fst for your tree (might result in an error for some trees, like polytomies) + applyFstToTree.pl --numcpus 12 -t RAxML_bipartitions.informative -p pairwise.tsv --outprefix fst --outputType samples > fst.samples.tsv # instead of average Fst values per tree node, shows you each repetition + +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/FAQ.md",".md","3025","40","Reference genomes +================= + +Can I have multiple reference genomes? +-------------------------------------- +No. However, you can add multiple assemblies to the asm directory. Assemblies don't have the same error profile as reads and so you might expect some skew in the ultimate phylogeny. + +How do I choose a reference genome? +----------------------------------- +The best reference genome for an outbreak is something in-clade. You might even need to assemble the genome from your own reads before starting. An outgroup is not as related to your clade by definition and so it is probably not the best genome to use. The next best quality is a closed genome, or a genome with a high N50. + +How to I include my reference genome in my analysis? +---------------------------------------------------- +You might have noticed that your reference genome is not included in the final analysis. +If you want to include the reference genome in your final tree or SNP matrix, there are about two ways. +Either: + +* Copy the assembly into the asm subfolder. There is a more automated way to do that with the `set_manage.pl` script, using `--add-assembly` as shown [here](EXAMPLES.md#prepare-the-project-directory) +* Find the original raw reads, e.g. Illumina fastq files, and place them into he reads folder. You can directly copy the interleaved files into that folder, or you can run `set_manage.pl --add-reads` on those interleaved files. + +**NOTE** Keep the assembly in the `reference/` subfolder and continue to point `-ref` to the assembly in the `reference` subfolder. + +High-quality-ness +================= + +What are the different ways that SNPs in Lyve-SET have high confidence? +----------------------------------------------------------------------- + +High quality for SNPs indicates that the resulting phylogeny will be high-fidelity. Although some SNPs are discarded that we are less sure about, the SNPs that we _are_ most sure about are retained, and the resulting phylogeny is the best inference. + +User Lori Gladney created [this flowchart](../images/Lyve-SET_masking_mindmap_11-20-17.pdf) to help understand these points. + +* **Detection of troublesome regions** such that they are not considered in hqSNP analysis. Currently in v1.0, only phage genes are detected; however other databases could be added in the future, and also I am open to other suggestions. Users can also specify a BED-formatted file to describe regions to mask. +* Only **unambiguous mapping** allowed +* Default **75% consensus** and **10x** coverage thresholds. These options can be changed when you launch Lyve-SET. +* Mechanisms to **remove clustered SNPs** -- not on by default however. +* **Maximum likelihood** phylogeny reconstruction. Ascertainment bias is also considered through RAxML v8. +* Both **forward and reverse reads** must support each SNP. +* Each read must have **95% identity** to the reference genome. In other words, if the read is 100bp, then only 5 differences in the read can be tolerated before the read is discarded. +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/VIZ.md",".md","1794","22","# Visualization + +A large question is, after you are finished with a Lyve-SET run, how do you visualize the results? One of the advantages of Lyve-SET is its use of standard file formats. Therefore most files can be visualized in standard software. All output files are documented under [OUTPUT.md](OUTPUT.md). + +## Tree + +You can visualize the tree in many different tree drawing programs out there. Some of my personal favorites are [MEGA](http://www.megasoftware.net) and [Figtree](http://tree.bio.ed.ac.uk/software/figtree). When prompted, open `tree.dnd`. Some commercial software includes BioNumerics, CLC, and Geneious. + +## SNP positions + +SNP positions are encoded in the vcf files under the vcf directory. You can view them in any standard viewer such as [IGV](http://software.broadinstitute.org/software/igv). On the command line, although difficult to visualize, you can use `bcftools` which is redistributed in Lyve-SET. + +To get started on IGV, first load the reference genome assembly. Second, load the bam and vcf files. You will immediately be able to browse the genome with these bam and vcf tracks. However for the advanced features, there is a learning curve (but it is worth it). + +## Read alignments + +Read alignments are encoded in bam files under the bam directory. These can be viewed with [IGV](http://software.broadinstitute.org/software/igv) and many commercial software packages such as CLC and Geneious. Additionally if you are command-line-inclined, you can view them with `samtools tview` which is redistributed with Lyve-SET. + +## SNP distances + +SNP distances might be the easiest to visualize. These can be viewed in LibreOffice or Microsoft Excel. Simply open `out.pairewiseMatrix.tsv` and turn on conditional formatting. This shows the distance heatmap. +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/INSTALL.md",".md","2697","89","Installation +============ + +## Containers + +Here are the methods for installing with either Docker or Singularity. + + docker pull staphb/lyveset:1.1.4f + + singularity build lyveset.1.1.4f.sif docker://staphb/lyveset:1.1.4f + +Requirements +------------ + +* **Perl, multithreaded** + * BioPerl +* **BLAST+** +* **Edirect** (for downloading of test data) +* **GIT**, **SVN** (for installation and updating) + +### Other requirements + +Usually these packages are installed, but if you have a totally fresh system, you might want to consider installing the following + +* zlib +* curses +* zip/unzip +* build-essential + +Some Perl modules are needed in earlier versions of Lyve-SET including v1.1.4f. + +* File::Slurp +* URI::Escape + +Quickie Installation +-------------------- + +1. Run `make install` while you are in the Lyve-SET directory. This step probably takes 10-20 minutes. +2. Update the path to include the scripts subdirectory. You can do this yourself if you are comfortable or run `make env`. +3. Update your current session's path: `source ~/.bashrc` + +In-depth Installation +--------------------- + +Download the latest stable version from https://github.com/lskatz/lyve-SET/releases. You can also roll the dice by getting the cutting edge version with git. + + tar -zxvf lyve-SET-1.1.4f.tar.gz + cd lyve-SET-1.1.4f.tar.gz + make install + make env + +Other Installation Options +------------ +* `make install` +* `make install-optional` to install optional prerequisite software including bwa and snap +* `make env` - update `PATH` and `PERL5LIB` in the `~/.bashrc` file. +* `make check` - check and see if you have all the prerequisites +* `make test` - run a test phage dataset provided by CFSAN +* `make help` - for other `make` options +* `make clean` - clean up an old installation in preparation for a new installation + +### Fine details + +* `make install-*` - Many other installation options are available including but not limited to: + * `make install-smalt` + * `make install-CGP` + * `make install-samtools` +* `make clean-*` - Every `make install` command comes with a `make clean` command, e.g.: + * `make clean-CGP` + +Upgrading +--------- + +### By stable releases +Unfortunately the best way to get the next stable release is to download the full version like usual, followed by `make install`. If successful, then delete the directory containing the older version. + + cd ~/tmp + wget https://github.com/lskatz/lyve-SET/archive/v1.1.4f.tar.gz + tar zxvf release.tar.gz + cd Lyve-SET + make install # takes 10-20 minutes to download packages on broadband; install + cd ~/bin + rm -r Lyve-SET && mv ~/tmp/Lyve-SET . + +### By `git` + git pull -u origin master + make clean + make install +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/TROUBLESHOOTING.md",".md","5827","75","# Troubleshooting + +Things do not always go smoothly. Here is a list of things to try out if things go wrong. + +## Interleaved reads + +Why are both R1 and R2 showing up in my results? + +Lyve-SET requires _interleaved_ reads (or commonly called ""shuffled""). This means that there is one fastq file per genome and that their format is such that there is one forward read, followed by its reverse reads, followed by the next forward read, etc. +To interleave one set of reads, you can use the script `run_assembly_shuffleReads.pl`. To shuffle many pairs of reads, you can use `shuffleSplitReads.pl`. Both have usage statements if you run them with `--help`. + +## Smalt says that there is an invalid fastq/fasta format + +This can be the result of a few different things. + +### Reference assembly integrity + +First, check to see if your reference genome is intact. + +* Manually inspect the fasta file with `less`, e.g., `less reference/reference.fasta`. +* Another way to manually inspect the fasta file is with `grep`, e.g., `grep -A 1 "">"" reference/reference.fasta`. +* Get some summary metrics with `run_assembly_metrics.pl`, e.g., `run_assembly_metrics.pl reference/reference.fasta | column -t`. + +### Fastq integrity + +You can also see if your fastq files are intact which is a little more tricky. + +* Are your files in the interleaved format? See [Interleaved reads](#interleaved-reads). +* Are your files gzipped? Use the Linux command `file` to see that it says 'gzip' in the description of your files. For example, `file reads/*.fastq.gz`. It is not necessary to have gzipped files, but it _is_ necessary for the extension to match the type. For example you do not want to have compressed files that end in `.fastq.gz` or uncompressed files that end in `.fastq`. +* Are the actual files intact? + * You can use the [lskScript](https://github.com/lskatz/lskScripts) tool `validateFastq.pl` to find common mistakes. For example: `zcat reads/genome.fastq.gz | validateFastq.pl --pe --min-length 1 --verbose`. + * Is the interleaved file line count the number of lines of both R1 and R2? Example command: `zcat R1.fastq.gz | wc -l`. + * Simply reshuffle: `shuffleSplitReads.pl -o shuffled --numcpus 1 split/*.fastq.gz` + +## BCFtools merge + +### cannot read fastq header; error with bcftools merge + +This is likely due to [Fastq integrity](#fastq-integrity) + +## The tree was not created + +### Too few taxa + +RAxML requires at least four genomes to create a tree. If you have few genomes in your analysis, perhaps the `out.pairwise.tsv` or `out.pairwiseMatrix.tsv` file would make more sense in terms of deliverable results. + +### Nonunique names + +* RAxML only considers the **first 30 characters** of your genome name. In the offhand chance that you have two genomes with filenames that vary on the 31st or later characters, then consider renaming your files appropriately. +* Did you include **R1 and R2 and/or also the shuffled reads**? Lyve-SET requires shuffled reads and so if you haven't done this, please follow the steps under the section [Interleaved reads](#interleaved-reads). You should not be using both R1 and R2 in your input directly. If they are already shuffled, delete all instances of R1 and R2 files in the project directory. However, *do not* delete the shuffled file. *Do not* delete your original data (just a general tip). Delete R1/R2 files and their derivative files in the reads subdirectory, the tmp subdirectory, the bam subdirectory, and the vcf subdirectory. Delete all files in the msa directory, because they will have to be recreated. Rerun Lyve-SET. This is a huge issue because + 1. R1 and R2 SNPs will not be as accurate as the paired-end shuffled entry, because their read mapping is not as accurate + 2. These less accurate entries will enter noise into the tree inferrence. + +### Not enough variable sites + +#### Best case scenario + +This isn't a huge problem but it's not immediately obvious that this is the case always. If all of your genomes have the exact same SNP profile, then the multiple sequence alignment will have zero variable sites, and RAxML will fail. This is a result in itself because it says that all your genomes have the same genomic profile. + +How do you detect this? You can view `out.snpmatrix.tsv` to see if there are many sites without majority ambiguous allele calls. You can see if `out.snpmatrix.tsv` has many sites. Therefore you can do a simple calculation to show that you have many high-quality sites but few or no variable sites. + +How do you avoid this situation? If you have a good outgroup, then there will be variable sites, and it won't matter if your clade of interest has no variation between them. RAxML can build a tree when there are a few guaranteed variable sites introduced by the outgroup. This outgroup by definition is a genome that is phylogenetically related but is not the same profile as your clade of interest. + +#### Worst case scenario + +What if they are *supposed* to have different SNP profiles? + +1. Check to see if the **number of masked sites is huge** in the multiple sequence alignment. `launch_set.log` in the log directory should inform you of huge percentages of masked sites. +2. Check to see if there are weird read mappings. See the [visualization guide](VIZ.md) for more details. Or some basic commands + * `samtools depth bam/somegenome.bam | less` + * `samtools flagstat bam/somegenome.bam` + * `bam stats --basic --in bam/somegenome.bam` +3. Check to see if there are a ton of **failed sites** in the VCF files. This is more complicated but it will give you a trend. For example, do you see a lot of low coverage sites? Low consensus sites? + * Example command to view the number of sites passing, or number of sites failed per reason `bcftools view --no-header somegenome.vcf.gz | cut -f 7 | sort | uniq -c` +","Markdown" +"Microbiology","lskatz/lyve-SET","docs/EXAMPLES.md",".md","6596","148","Examples +======== + +Run a test dataset +------------------ + +The script `set_test.pl` will run an actual test on a given dataset. It uses `set_downloadTestData.pl` to get any bacterial genomes and then runs `launch_set.pl`. However, the lambda dataset is small enough to fit on GIT and does not need to be downloaded. + + Runs a test dataset with Lyve-SET + Usage: set_test.pl dataset [project] + dataset names could be one of the following: + escherichia_coli, lambda, listeria_monocytogenes, salmonella_enterica_agona + NOTE: project will be the name of the dataset, if it is not given + + --numcpus 1 How many cpus you want to use + --do-nothing To print the commands but do not run system calls + +`$ set_test.pl lambda # will run the entire lambda phage dataset and produce meaningful results in ./lambda/msa/` + + +Prepare the project directory +----------------------------- + +The script `set_manage.pl` sets up the project directory and adds reads, and you should use the following syntax: + + $ set_manage.pl --create setTest + +Depending on your knowledge of Linux, you might choose to set up the rest of the project using `set_manage.pl` or using symlinks. This is the `set_manage.pl` way: + + $ set_manage.pl setTest --add-reads file1.fastq.gz + $ set_manage.pl setTest --add-reads file2.fastq.gz + $ set_manage.pl setTest --add-reads file3.fastq.gz + $ set_manage.pl setTest --add-reads file4.fastq.gz + $ set_manage.pl setTest --add-reads file5.fastq.gz + $ set_manage.pl setTest --add-assembly file1.fasta + $ set_manage.pl setTest --add-assembly file2.fasta + $ set_manage.pl setTest --change-reference file3.fasta + +This is the symlink way: + + $ cd setTest/reads + $ ln -sv path/to/reads/*.fastq.gz . # symlink reads + $ cd ../asm + $ ln -sv path/to/assemblies/*.fasta . # symlink the assemblies + $ cd ../reference + # copy the assembly in case you need to alter it (e.g., remove small contigs or edit deflines) + $ cp -v path/to/assemblies/reference.fasta . + +Run Lyve-SET with as few options as possible + + $ launch_set.pl setTest + +More complex + + $ launch_set.pl setTest --queue all.q --numnodes 20 --numcpus 12 --noclean --notrees + +If you specified notrees, then you can edit the multiple sequence alignment before analyzing it. See the next section on examples on how/why you would edit the alignment. + + $ cd setTest/msa + $ gedit out.aln.fas # alter the deflines or whatever you want before moving on + # => out.aln.fas is here + $ set_process_msa.pl --auto --numcpus 12 + # Optionally, qsub this script instead because it could be cpu-intensive + $ qsub -pe smp 12 -cwd -V -o trees.log -j y -N msaLyveSET -S $(which perl) $(which set_process_msa.pl) --auto --numcpus 12 + +If you make a mistake and need to redo something: + + # remove all intermediate files + $ rm setProj/bam/genome* + $ rm setProj/vcf/genome* setProj/vcf/unfiltered/genome* + # OR, remove a genome entirely + $ set_manage.pl setProj --remove-reads genome.fastq.gz + $ set_manage.pl setProj --remove-assembly genome.fasta + # remove the last multiple sequence alignment files + $ rm -r setProj/msa/* + # or save the MSA results for another time + $ mv setProj/msa setProj/msa.oldresults && mkdir setProj/msa + # redo the analysis (all untouched bams and vcfs will not be redone) + $ launch_set.pl setProj + +Why would you want to edit the out.aln.fas file? Or what kinds of things can you observe here before making a tree? + + # Alter the identifiers of your genomes, so that they look nice in the phylogeny(ies) + $ sed -i.bak 's/\.fastq\.gz.*//' out.aln.fas + # OR maybe to just remove the reference genome name: + $ sed -i.bak 's/\-reference.*//' out.aln.fas + + # Be sure that the taxa names are unique still. + # If there is any output, then you have duplicated names which need to be fixed. + $ grep "">"" out.aln.fas | sort | uniq -d # nothing should show up + + # After the taxon names are edited nicely, + # back up the out.aln.fas file before any entries are removed + $ cp -v out.aln.fas out.aln.fas.bak + + # => All extensions are removed in taxon names; a backup of the file was named out.aln.fas.bak + # find the genomes with the most number of Ns (ie masked SNP calls) + $ perl -lane 'chomp; if(/^>/){s/>//;$id=$_;}else{$num=(s/(N)/$1/gi); print ""$id\t$num"";}' < out.aln.fas|sort -k2,2n|column -t + # => consider removing any genome with too many masked bases by manually editing the file. + + # Run SET on your new set of genomes out.aln.fas. + $ set_process_msa.pl out.aln.fas --auto --numcpus 12 + + # Create a new subset as needed, but you should always read from your master record and not the informative.aln.fas file + # which is now out.aln.fas.bak + $ cp -v out.aln.fas.bak out.aln.fas + $ ... # more editing here + $ set_process_msa.pl out.aln.fas --auto --numcpus 12 + + +Specific ways to regenerate files +--------------------------------- + +Lyve-SET is very modular and so there are specific scripts to regenerate files. Since you might edit the msa files, you might want to know how to recover in case you make a mistake. + +Need to remake out.aln.fas? + + $ mvcfToAlignment.pl out.pooled.vcf.gz --bcfOutput bcfquery.out > out.aln.fas + +Need to remake out.pooled.vcf.gz? Use bcftools. + + $ bcftools merge vcf/unfiltered/*.vcf.gz -O -z > msa/out.pooled.vcf.gz + $ tabix -f msa/out.pooled.vcf.gz # Always index your compressed vcf files + +Need to remake all the other msa files after you recreated out.aln.fas? + + $ set_processMsa.pl --auto out.aln.fas --numcpus 12 --force + +Need to make a backup of your current results? Just rename the directory but make sure that the msa directory still exists. + + $ mv msa/ msa.bak/ && mkdir msa + +Special cases +------------- + +Q: What if you have a non-Illumina file that you would like to use? + +A: You can still map your reads separately into a sorted bam file and then run SET after that bam file has been created. For example, if you have a 454 or Ion Torrent file, you can map it using bwa-sw with the following steps. Keep the file naming system intact. + + bwa index -a bwtsw reference/2010EL-1786.fasta + bwa bwasw -t 12 reference/2010EL-1786.fasta reads/example.fastq.gz > tmp/example.fastq.gz.sam + samtools view -bS tmp/example.fastq.gz.sam > tmp/example.fastq.gz.bam + samtools sort tmp/example.fastq.gz.bam bam/example.fastq.gz-2010EL-1786.sorted # produces the bam extension + samtools index bam/example.fastq.gz-2010EL-1786.sorted.bam + rm -v tmp/example* + + launch_set.pl ... +","Markdown" +"Microbiology","lskatz/lyve-SET","scripts/launch_phyml.sh",".sh","906","38","#!/bin/sh +#$ -S /bin/sh +#$ -pe smp 1 +#$ -cwd +#$ -V +#$ -o launch_phyml.sh.out -j y + +# makes a tree out of an aln + +script=`basename $0`; +aln=$1 +if [ ""$aln"" = """" ]; then + echo Usage: `basename $0` aln.phy + exit 1; +fi + +# find which phyml to use +phyml=`(which phyml-mpi || which phyml || which PhyML || which PhyML-3.1_linux64 || which phyml_linux_64) 2>/dev/null`; +if [ $? -gt 0 ]; then echo ""Could not find phyml""; exit 1; fi; +echo ""$script: Found phyml at $phyml"" + +# get the extension +b=`basename $aln`; +suffix=""${b##*.}""; +if [ ""$suffix"" != ""phy"" ]; then + echo ""Converting to phylip format because I did not see a phy extension""; + convertAlignment.pl -f phylip -i $aln -o $aln.phy; + if [ $? -gt 0 ]; then exit 1; fi; + aln=""$aln.phy""; +fi; + + +yes | \ + $phyml -i $aln -b -4 -m GTR -s BEST --quiet; +if [ $? -gt 0 ]; then echo ""$script: ERROR in phyml"" exit 1; fi; +echo ""$script: Finished without error!""; + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/testInstallation.sh",".sh","112","9","#!/bin/bash + +set -e + +set_test.pl --numcpus 2 lambda lambda -- --noqsub --nodiagnose + +echo ""Everything passed!"" + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/pooledToMatrix.sh",".sh","1272","69","#!/bin/bash +# Runs bcftools query to make a SNP matrix + +script=$(basename $0); + +usage () { + echo ""$script: generates a SNP matrix using BCFtools and a pooled VCF file"" + echo ""USAGE: $script -o bcfmatrix.tsv pooled.vcf.gz"" + return 0; +} + +logmsg () { + echo ""$script: $@""; + return 0; +} + +while getopts ""ho:"" o; do + case ""${o}"" in + h) + usage + exit 1 + ;; + o) + OUT=""$OPTARG"" + ;; + *) + echo ""ERROR: I do not understand option $OPTARG"" + ;; + esac +done +shift $(($OPTIND-1)) # remove the flag arguments from ARGV + +IN=$1 + +if [ ""$OUT"" == """" ] || [ ""$IN"" == """" ]; then + usage + exit 1; +fi + +# Create the basic matrix +t='\t' +command=""bcftools query -i '%TYPE=\""snp\""' -f '%CHROM$t%POS$t%REF$t[%TGT$t]\\n' --print-header $IN > $OUT.unrefined.tmp"" +logmsg $command; +eval $command +if [ $? -gt 0 ]; then + echo -e ""ERROR with bcftools:\n $command""; + exit 1 +fi + +# post-process the matrix +logmsg ""Post-processing"" +perl -lane ' + BEGIN{ + # print the header + $line=<>; + chomp($line); + print $line; + $numFields=scalar(split(/\t/,$line)); + $lastIndex=$numFields-1; + } + for(@F[3..$lastIndex]){ + $_=substr($_,0,1); + } + print join(""\t"",@F); + ' < $OUT.unrefined.tmp > $OUT.tmp; + +mv -v $OUT.tmp $OUT; +rm -v $OUT.unrefined.tmp; +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/set_mergeVcf.sh",".sh","3491","127","#!/bin/bash +# Uses bcftools to merge vcf files + +script=$(basename $0); +bindir=$(dirname $0); +export PATH=$bindir:$PATH; # enforce the Lyve-SET path + +function logmsg(){ + echo ""$script: $@"" +} + +NUMCPUS=1; # default number of cpus +while getopts ""o:n:t:r:s"" o; do + case ""${o}"" in + o) + OUT=""$OPTARG"" + ;; + n) + NUMCPUS=""$OPTARG"" + ;; + t) + TEMPDIR=""$OPTARG"" + ;; + s) + ALSOSNPS=1 + ;; + *) + logmsg ""ERROR: I do not understand option --$o $OPTARG"" + exit 1 + ;; + esac +done +shift $(($OPTIND-1)) # remove the flag arguments from ARGV + +IN=""$@""; +if [ ""$IN"" == """" ] || [ ""$OUT"" == """" ]; then + echo ""$script: merges VCF files that are compressed with bgzip and indexed with tabix"" + echo ""Usage: $script -o pooled.vcf.gz *.vcf.gz"" + echo "" -o output.vcf.gz The output compressed VCF file"" + echo "" -t /tmp/mergeVcfXXXXXX A temporary directory that will be completely removed upon exit"" + echo "" -s Output SNPs only file in addition to the whole thing"" + echo "" -n 1 Number of cpus"" + exit 1; +fi + +SNPSOUT=$(dirname $OUT)/$(basename $OUT .vcf.gz)"".snps.vcf.gz"" + +if [ ""$TEMPDIR"" == """" ]; then + TEMPDIR=$(mktemp -d /tmp/mergeVcf.XXXXXX); + trap ""rm -rvf $TEMPDIR"" EXIT TERM INT +fi +mkdir -pv ""$TEMPDIR""; # just in case +logmsg ""temporary directory is $TEMPDIR""; + +# Run makeRegions.pl based on how many cpus there are +# and really parallelize this script! +logmsg ""Dividing the genome into regions, making it easier to multithread"" +makeRegions.pl --numchunks $NUMCPUS --numcpus $NUMCPUS $IN > $TEMPDIR/regions.txt +if [ $? -gt 0 ]; then + logmsg ""ERROR running makeRegions.pl!""; + exit 1; +fi +REGION=$(cat $TEMPDIR/regions.txt); + +# Multithread, one thread per region +logmsg ""Running bcftools merge""; +export IN; +export script; +# TODO if we upgrade past v1.3.1, add in the parameter '--filter-logic x' +echo ""$REGION"" | xargs -P $NUMCPUS -n 1 bash -c 'echo ""$script: merging SNPs in $0""; out='$TEMPDIR'/merged.$$.vcf; bcftools merge --merge all --regions ""$0"" --force-samples -o $out $IN && bgzip $out && tabix $out.gz && echo ""$script: finished with region $0"";' +if [ $? -gt 0 ]; then + logmsg ""ERROR with bcftools merge"" + exit 1; +fi + +logmsg ""Concatenating vcf output"" +bcftools concat --allow-overlaps --remove-duplicates $TEMPDIR/merged.*.vcf.gz > $TEMPDIR/concat.vcf +if [ $? -gt 0 ]; then + logmsg ""ERROR with bcftools concat"" + exit 1; +fi + +# Generate a SNPs-only merged file, if requested +if [ ""$ALSOSNPS"" == 1 ]; then + logmsg ""parsing $TEMPDIR/concat.vcf for SNPs"" + bcftools view --include '%TYPE=""snp""' $TEMPDIR/concat.vcf > $TEMPDIR/hqPos.vcf + if [ $? -gt 0 ]; then + logmsg ""ERROR with bcftools view"" + exit 1; + fi +else + logmsg ""user did not request SNPs-only file also"" +fi + +# BGzip, tabix, and mv hqSNPs and concat vcfs +for VCF in $TEMPDIR/concat.vcf $TEMPDIR/hqPos.vcf; do + if [ ! -e ""$VCF"" ]; then + continue; + fi; + + bgzip $VCF + if [ $? -gt 0 ]; then + logmsg ""ERROR with bgzip $VCF"" + exit 1; + fi + tabix $VCF.gz + if [ $? -gt 0 ]; then + logmsg ""ERROR with tabix $VCF.gz"" + exit 1; + fi +done + +# mv over the SNPs-only files +if [ ""$ALSOSNPS"" == 1 ]; then + mv -v $TEMPDIR/hqPos.vcf.gz $SNPSOUT + mv -v $TEMPDIR/hqPos.vcf.gz.tbi $SNPSOUT.tbi + logmsg ""SNPs-only file can be found in $SNPSOUT""; +fi + +# Lastly, mv over the large file +mv -v $TEMPDIR/concat.vcf.gz $OUT +mv -v $TEMPDIR/concat.vcf.gz.tbi $OUT.tbi +logmsg ""Output file can be found in $OUT"" + +exit 0; + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/launch_vcfToAlignment.sh",".sh","742","30","#!/bin/sh + +bamDir=$1 +vcfDir=$2 +ref=$3 +out=$4 +numCpus=8; + +if [ ""$out"" = """" ]; then + echo usage: $0 bam/ vcf/ ref.fasta out.aln.fas + echo "" bam directory's *.sorted.bam will be read"" + echo "" vcf dir's *.vcf will be read"" + echo "" vcfDir/*.badsites.txt will be used as 'bad sites', as produced by filterVcf.pl"" + exit 1; +fi; + +echo ""gathering $vcfDir/*.badsites.txt"" +bad=""$vcfDir/allsites.txt"" +sort $vcfDir/*.badsites.txt | uniq > $bad +if [ $? -gt 0 ]; then exit 1; fi; + +echo ""vcfToAlignment.pl"" +vcfToAlignment.pl $bamDir/*.sorted.bam $vcfDir/*.vcf -o $out -r $ref -b $bad -a 0 -n $numCpus +if [ $? -gt 0 ]; then exit 1; fi; + +echo ""convertAlignment.pl"" +convertAlignment.pl -i $out -o $out.phy -f phylip -r +if [ $? -gt 0 ]; then exit 1; fi; + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/launch_raxml.sh",".sh","2406","95","#!/bin/bash +# converts alignment to phylip and then makes a tree out of it +# Author: Lee Katz +# TODO: make an outgroup parameter, probably using eigenvectors (least connected is the best guess for an outgroup) + +#$ -S /bin/bash +#$ -pe smp 2 +#$ -cwd +#$ -V +#$ -o launch_raxml.sh.out -j y + +############### +## Parse options +# defaults +outgroupParam="""" +numcpus=${NSLOTS:-2} +# parsing +while getopts "":n:o:"" o; do + case ""${o}"" in + n) + numcpus=$OPTARG + ;; + o) + outgroupParam=""-o $OPTARG"" + ;; + *) + echo ""ERROR: I do not understand option $OPTARG"" + ;; + esac +done +shift $(($OPTIND-1)) # remove the flag arguments from ARGV + +####################### +## positional arguments +aln=$1 +prefix=$2 +if [ ""$prefix"" == """" ]; then + echo Usage: `basename $0`"" [options] aln.phy outprefix"" + echo -e ""Options:\n -n numcpus\n -o outgroup"" + exit 1; +fi + +############################ +## Convert the alignment (?) +# get the extension +b=`basename $aln`; +suffix=""${b##*.}""; +if [ ""$suffix"" != ""phy"" ]; then + echo ""Converting to phylip format because I did not see a phy extension""; + convertAlignment.pl -f phylip -i $aln -o $aln.phy; + if [ $? -gt 0 ]; then exit 1; fi; + aln=""$aln.phy""; +fi; + +# Which raxml to use? In order of lesser priority +# so that higher priority overrides the previous choice. +which raxmlHPC 1>/dev/null 2>&1 && EXEC=$(which raxmlHPC) +which raxmlHPC-PTHREADS 1>/dev/null 2>&1 && EXEC=$(which raxmlHPC-PTHREADS) +if [ ""$EXEC"" == """" ]; then + echo ""ERROR: I did not find raxml in the path!""; + exit 1; +fi; + +# Raxml-pthreads must have >1 cpu and so fix it if that happens +if [ $EXEC == ""raxmlHPC-PTHREADS"" ]; then + # attempt to switch back to regular raxml + which raxmlHPC 1>/dev/null 2>&1 && EXEC=raxmlHPC + + # If it is still the pthreads version change the cpus + if [ $EXEC == ""raxmlHPC-PTHREADS"" ] && [ $numcpus -lt 2 ]; then + numcpus=2 + fi +fi + +# what version is raxml? +VERSION=$($EXEC -v | grep -o 'version [0-9]' | grep -o [0-9]); +echo ""I detect that you are using version $VERSION of raxml."" + +XOPTS="""" +if [ $VERSION = 8 ]; then + MODEL=ASC_GTRGAMMA + XOPTS=""$XOPTS --asc-corr=lewis "" +else + MODEL=GTRGAMMA +fi + +## time to run the program! +COMMAND=""$EXEC -f a -s $aln -n $prefix -T $numcpus -p $RANDOM -x $RANDOM -N 100 -m $MODEL $outgroupParam $XOPTS"" +eval $COMMAND +if [ $? -gt 0 ]; then + echo -e ""ERROR with command:\n $COMMAND""; + exit 1; +fi + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/varscan.sh",".sh","938","39","#!/bin/bash + +# script to call varscan.jar +# adapted from Seth Sims September 26, 2014 +# Lee Katz + +JAR=$(dirname $0)""/../lib/varscan.v2.3.7.jar"" +JAVA=$(\which java 2>/dev/null || /usr/bin/java); +GREP=$(\which grep 2>/dev/null || /bin/grep); + +if [ ! -e $JAVA ]; then + echo ""ERROR: java is not in your path!""; + exit 1; +fi; +if [ ! -e $GREP ]; then + echo ""ERROR: grep is not in your path!""; + exit 1; +fi; + +if [ ! -e ""$JAR"" ]; then + echo ""ERROR: jar file does not exist at $JAR"" + echo "" Please edit $0 to reflect where the jar file is."" + exit 1; +fi + +if [ ""$1"" == """" ]; then + script=$(basename $0) + echo ""This is the Lyve-SET method of calling varscan. Usage help below is from varscan itself."" + echo ""Run 'java -jar $JAR' for more information"" + echo + echo ""USAGE: $script [COMMAND] [OPTIONS]"" + echo + $JAVA -jar ""$JAR"" 2>&1 | $GREP -v 'java -jar' | $GREP . + echo + exit 0 +fi + +$JAVA -jar ""$JAR"" ""$@"" +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/launch_freebayes.sh",".sh","3016","80","#!/bin/sh +ref=$1 +bam=$2 +out_vcf=$3 +minAltFrac=$4 +minCoverage=$5 + +readSnpLimit=10; + +b=`basename $out_vcf .vcf`; + +if [ ""$out_vcf"" = """" ]; then + script=`basename $0`; + echo usage: $script ref.fasta query.bam out.vcf min_alt_frac min_coverage; + echo "" where min_al_frac can be 0.75 and min_coverage can be 10"" + exit 1; +fi; + +if [ -e ""$out_vcf"" ]; then + echo ""Found $out_vcf! I will not rewrite it."" + exit 0; +fi; + +# freebayes params +if [ ""$minAltFrac"" = """" ]; then minAltFrac=0.75; fi; +if [ ""$minCoverage"" = """" ]; then minCoverage=10; fi; + +# for filtering, for later +new_vcf=""$out_vcf"".tmp +b=`basename $out_vcf .vcf`; +d=`dirname $out_vcf`; +unfiltered_vcf=""$d/unfiltered/$b.vcf"" +bad=$out_vcf"".badsites.txt"" + +mkdir -p ""$d/unfiltered""; + +# freebayes +echo ""Running Freebayes"" +echo ""$bam => $out_vcf"" + +freebayes \ + `# input and output`\ + --bam $bam \ + --vcf $unfiltered_vcf \ + --fasta-reference $ref \ + \ + `# reporting` \ + --pvar 0.0001 `# Report sites if the probability that there is a polymorphism at the site is greater than N. default: 0.0001`\ + \ + `# population model`\ + --ploidy 1 `# Sets the default ploidy for the analysis to N. default: 2`\ + \ + `# allele scope`\ + --no-mnps `# Ignore multi-nuceotide polymorphisms, MNPs.`\ + \ + `# indel realignment`\ + `#--left-align-indels` `# Left-realign and merge gaps embedded in reads. default: false`\ + `#--no-indels` \ + \ + `# input filters`\ + --min-mapping-quality 0 `# Exclude alignments from analysis if they have a mapping quality less than Q. default: 30`\ + --min-base-quality 20 `# Exclude alleles from analysis if their supporting base quality is less than Q. default: 20`\ + `#--read-snp-limit $readSnpLimit` `# Exclude reads with more than N base mismatches, ignoring gaps with quality >= mismatch-base-quality-threshold. default: ~unbounded`\ + `# --indel-exclusion-window 5` `# Ignore portions of alignments this many bases from a putative insertion or deletion allele. default: 0`\ + --min-alternate-fraction $minAltFrac `# Require at least this fraction of observations supporting an alternate allele within a single individual in the in order to evaluate the position. default: 0.0`\ + --min-coverage $minCoverage `# Require at least this coverage to process a site. default: 0` + +if [ $? -gt 0 ]; then exit 1; fi; + +# put in the correct sample name +mv $unfiltered_vcf ""$unfiltered_vcf.tmp"" && \ + sed '/^#CHROM/s/unknown/'$b'/' ""$unfiltered_vcf.tmp"" > $unfiltered_vcf + +echo ""Filtering FreeBayes calls"" +filterVcf.pl $unfiltered_vcf --noindels -d $minCoverage -o $new_vcf -b $bad +if [ ""$?"" -gt 0 ]; then exit 1; fi; +mv -v $new_vcf $out_vcf +if [ ""$?"" -gt 0 ]; then exit 1; fi; + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/testScripts.sh",".sh","784","34","#!/bin/bash + +# This test assumes that set_test.pl has already been run +# and that it generated project directory lambda. + +# Run every shell script in unitTests +testsDir=$(dirname $0)/unittests +echo ""Running tests in $testsDir"" +FAIL=0; +for i in $testsDir/*.sh; do + b=$(basename $i) + echo ""Running $b"" + + # While running the program, indent any output. + bash $i 2>&1 | perl -lane 'chomp; print "" $_"";' + # Checking the exit code is bash-specific and so the #! line is important + exit_code=${PIPESTATUS[0]} + + # If there is any failure, mark it and move on + if [ ""$exit_code"" -gt 0 ]; then + echo ""$b failed"" + FAIL=$(($FAIL + 1)) + else + echo ""$b passed"" + fi +done + +# Exit with how many tests failed +if [ ""$FAIL"" -gt 0 ]; then + echo ""Failed $FAIL tests"" + exit $FAIL +fi + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/unittests/densityVcf.sh",".sh","1617","48","#!/bin/bash + +# This test assumes that set_test.pl has already been run +# and that it generated project directory lambda. + +####### density filtering ########## +# All positions +positions=$(zgrep -v '^#' lambda/msa/out.pooled.snps.vcf.gz | cut -f 2); +# Density filter of 2 that removes the first site: no two sites should +# be within 158 positions of each other. +filteredPositionsWindow2=$(densityFilterVcf.pl --window 158 --density-filter 2 lambda/msa/out.pooled.snps.vcf.gz | grep -v '^#' | cut -f 2) + +smallestDifference2=$( + echo ""$filteredPositionsWindow2"" | perl -e ' + @site=<>; + chomp(@site); + for($i=0;$i<@site-1;$i++){ + print $site[$i+1] - $site[$i].""\n""; + } + ' |\ + sort -n | head -n 1 +) +if [ ""$smallestDifference2"" -lt 158 ]; then + echo ""Did not remove sites close together than 158 when density filtering was 2"" + echo ""Smallest distance between sites was $smallestDifference2"" + exit 1 +fi + +# Density filter of 3 that removes the first site: no two sites, separated +# by one site, should be within 184 positions of each other. +filteredPositionsWindow3=$(densityFilterVcf.pl --window 184 --density-filter 3 lambda/msa/out.pooled.snps.vcf.gz | grep -v '^#' | cut -f 2) +smallestDifference3=$( + echo ""$filteredPositionsWindow3"" | perl -e ' + @site=<>; + chomp(@site); + for($i=0;$i<@site-2;$i++){ + print $site[$i+2] - $site[$i].""\n""; + } + ' |\ + sort -n | head -n 1 +) +if [ ""$smallestDifference3"" -lt 184 ]; then + echo ""Did not remove sites close together than 158 when density filtering was 2"" + echo ""Smallest distance between sites was $smallestDifference3"" + exit 1 +fi + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/unittests/pairwise.sh",".sh","481","19","#!/bin/bash + + +min_snps=$(sort -k3,3n lambda/msa/out.pairwise.tsv | head -n 1 | cut -f 3) +max_snps=$(sort -k3,3n lambda/msa/out.pairwise.tsv | tail -n 1 | cut -f 3) + +if [ ""$min_snps"" != ""37"" ]; then + echo ""I expected the minimum number of SNPs to be 37, but it is $min_snps""; + cat lambda/msa/out.pairwise.tsv + exit 1 +fi +if [ ""$max_snps"" != ""92"" ]; then + echo ""I expected the maximum number of SNPs to be 92, but it is $max_snps""; + cat lambda/msa/out.pairwise.tsv + exit 1 +fi + + +","Shell" +"Microbiology","lskatz/lyve-SET","scripts/unittests/makeRegions.sh",".sh","437","14","#!/bin/bash + +correctRegion=""NC_001416.1:1-48502"" +region=$(makeRegions.pl lambda/reference/reference.fasta) +files_to_test=""lambda/reference/reference.fasta lambda/bam/sample1.fastq.gz-reference.sorted.bam lambda/vcf/sample2.fastq.gz-reference.vcf.gz"" + +for file in $files_to_test; do + region=$(makeRegions.pl $file) + if [ ""$region"" != ""$correctRegion"" ]; then + echo ""ERROR: did not get correct region from $file"" + exit 1 + fi +done +","Shell" +"Microbiology","phac-nml/quasitools","setup.py",".py","1532","47",""""""" +Copyright Government of Canada 2015-2019 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from setuptools import find_packages, setup + +dependencies = ['biopython', 'click', 'numpy', 'pysam', 'scipy', 'PyAAVF'] + + +setup( + name='quasitools', + version = ""0.7.0"", + url='https://github.com/phac-nml/quasitools.git', + license='Apache License, Version 2.0', + author='Eric Enns', + author_email='eric.enns@canada.ca', + description='Quasitools is a collection of tools for analysing Viral Quasispecies', + long_description=__doc__, + packages=find_packages(exclude=['tests']), + include_package_data=True, + zip_safe=False, + platforms='any', + install_requires=dependencies, + entry_points=''' + [console_scripts] + quasitools=quasitools.cli:cli + ''', + classifiers=[ + 'License :: OSI Approved :: Apache Software License', + 'Environment :: Console', + 'Programming Language :: Python :: 3', + ] +) +","Python" +"Microbiology","phac-nml/quasitools","CHANGELOG.md",".md","3816","162","# Change Log + +All notable changes to Quasitools will be documented in this file. + +## 0.7.0 ## + +### Added ### + +Commands: + +- complexity bam: measures the complexity of a quasispecies across a reference genome using aligned reads in BAM format + +Options: + +- complexity: now has the option to filter out low frequency haplotypes + +### Changed ### + +- `complexity` has been replaced with `complexity fasta` and `complexity bam` +- Fixed a complexity bug with haplotype counting and consensus sequence generation. +- Fixed a complexity bug when parsing haplotypes with indels. + +## 0.6.0 ## + +### Changed ### + +- Integrated PyAAVF and changed output of mutation report in `hydra` command to produce AAVF file along with `call aavar` to produced AAVF file instead of HMCF file. +- Made various changes to the documentation to improve clarity. +- Fixed quasitools distance sometimes crashing because of uneven coverage. +- Improved the execution time of quasitools distance. +- Fixed the Hamming distance calculation using integers instead of floats, depending on the Python version. + +## 0.5.1 ## + +### Added ### + +- Use MkDocs for documentation + +### Changed ### + +- Make VCF dependency optional in aavar and add optional VCF dependency in codonvar +- Fix hydra consensus output: exclude header line if there are no sequence lines +- Remove a deprecated regular expression sequence in reference_parser.py + +## 0.5.0 ## + +2018-09-25 + +### Added ### + +Commands: + +- complexity: measures the complexity of a quasispecies + +### Changed ### + +- Improved read parsing, pileup generation, and related interal data structures. + +## 0.4.2 ## + +2018-07-25 + +### Changed ### + +- Fix bug in quality_control where iteratively trimmed reads are not used when printing output file. + +## 0.4.1 ## + +2018-07-24 + +### Changed ### + +- Updated hydra command and quality command to fix boolean flag for enabling median or mean score cutoff value. + +## 0.4.0 ## + +2018-06-29 + +### Added ### + + - commands: + - quality: performs quality control on FASTQ reads + - modules: + - quality_control.py: contains QualityControl class + +### Changed ### + +- Updated hydra command to use new quality control class, masking and/or trimming reads based on command-line options that user has specified. +- Fixed bug in cmd_consensus.py which occured when there are multiple records in the reference file and the user is writing to a file. + +## 0.3.1 ## + +2018-04-13 + +### Added ### + +- Updated hydra command to accept an id to be used as the sequence identifier + in the consensus report, and as the RG-id in the bam file + +## 0.3.0 ## + +2018-04-10 + +### Added ### + + - commands: + - distance: returns the evolutionary distances between viral quasispecies as a distance matrix + - modules: + - pileup.py: contains Pileup and Pileup_List classes + - distance.py: contains Distance_Matrix class + +## 0.2.3 ## + +2018-03-16 + +### Changed ### + +- Fixed FASTA identifier in consensus output for the consensus and hydra commands +- User can pass in a default id as an option +- RG tag is used if present in the supplied .bam file + +## 0.2.2 ## + +2017-11-27 + +### Changed ### + + - Updated samtools dependency to v1.3 + +## 0.2.1 ## + +2017-11-22 + +### Changed ### + + - fixed call codonvar command to properly output to either file or stdout depending on flag + +## 0.2.0 ## + +2017-11-03 + +### Added ### + + - commands: + - hydra: which identifies HIV Drug Resistance in a NGS sample + - call: new base command for nt, aa, and codon variant calling + - ntvar: formally just callntvar + - aavar: formally aavariants + - codonvar: reports codon variants for use with dnds command + - dnds: calculates dnds values per coding region using codonvar output + +### Changed ### + + - Renamed aa_census command to aa_coverage + - Hardended command options and parameters + +## 0.1.0 ## + +2017-09-06 + +This is the initial release of Quasitools +","Markdown" +"Microbiology","phac-nml/quasitools","quasitools/mapped_read.py",".py","8953","247",""""""" +Copyright Government of Canada 2015-2017 + +Written by: Eric Enns, Eric Chubaty, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import decimal + + +class MappedRead(object): + + def __init__(self, seq_id, query_start, query_end, differences, ref_start, + ref_end, strand): + + self.seq_id = seq_id + self.query_start = query_start + self.query_end = query_end + self.differences = differences + self.ref_start = ref_start + self.ref_end = ref_end + self.strand = strand + + def query_length(self): + """"""Calculate and return the length of read mapped to the reference. + + >>> mr = MappedRead('read1', 10, 300, {'110': 'g', '300': 'tagt'}, 100, + >>> 390, 97, 99.3127, '+') + >>> print(mr.query_length()) + 291 + """""" + return self.query_end + 1 - self.query_start + + def codon_start(self, frame): + """"""Calculate and return the first position of the first codon for the + given frame in reference base position. + + >>> mr = MappedRead('read1', 10, 300, {'110': 'g', '300': 'tagt'}, 100, + >>> 390, 96.6667, 99.3103, '+') + >>> print(mr.codon_start(0)) + 102 + >>> print(mr.codon_start(1)) + 100 + >>> print(mr.codon_start(2)) + 101 + """""" + codon_start = self.ref_start + + while codon_start % 3 != frame: + codon_start += 1 + + return codon_start + + def codon_end(self, frame): + """"""Calculate and return the last position of the last codon for the + given frame in reference base position. + + >>> mr = MappedRead('read1', 10, 300, {'110': 'g', '300': 'tagt'}, 100, + >>> 390, 96.6667, 99.3103, '+') + >>> print(mr.codon_end(0)) + 389 + >>> print(mr.codon_end(1)) + 390 + >>> print(mr.codon_end(2)) + 388 + """""" + codon_end = self.ref_end + + while (codon_end - 2) % 3 != frame: + codon_end -= 1 + + return codon_end + + +class MappedReadCollection(object): + + def __init__(self, reference): + self.mapped_reads = {} + self.reference = reference + + def pileup(self, indels=True): + """"""Build and return a pileup from the object."""""" + pileup = [{} for i in range(0, len(self.reference.seq))] + + for name, mapped_read in self.mapped_reads.items(): + for i in range(mapped_read.ref_start, mapped_read.ref_end + 1): + if i not in mapped_read.differences: + pileup[i][self.reference.sub_seq(i, i).upper()] = \ + pileup[i].get(self.reference.sub_seq(i, i).upper(), 0)\ + + 1 + elif len(mapped_read.differences[i]) == 1: + if mapped_read.differences[i] == '-': + pileup[i]['-'] = pileup[i].get('-', 0) + 1 + else: + pileup[i][mapped_read.differences[i].upper()] = \ + pileup[i].get( + mapped_read.differences[i].upper(), 0 + ) + 1 + else: + difference = mapped_read.differences[i] + difference = difference.replace( + '.', self.reference.sub_seq(i, i).upper()) + if not indels: + difference = difference[:1] + pileup[i][difference.upper()] = \ + pileup[i].get(difference.upper(), 0) + 1 + + return pileup + + def coverage(self, pileup=None): + if pileup is None: + pileup = self.pileup() + + coverage = [0 for pos in range(0, len(pileup))] + for pos in range(0, len(pileup)): + for k, v in pileup[pos].items(): + if not k.startswith('-'): + coverage[pos] += v + + return coverage + + def to_consensus(self, percentage): + """"""Generates and returns a consensus sequence + + >>> ref = Reference('hxb2_pol', + >>> 'GAAGAAATGAGTTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTT') + >>> mrs = MappedReadCollection.from_bam(ref, 65, 75, + >>> 'tests/data/test1.bam') + >>> print(mrs.to_consensus(20)) + GAAGAAATGAGTTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTT + """""" + iupac = {'A': 'A', + 'C': 'C', + 'G': 'G', + 'T': 'T', + 'AC': 'M', + 'AG': 'R', + 'AT': 'W', + 'CG': 'S', + 'CT': 'Y', + 'GT': 'K', + 'ACG': 'V', + 'ACT': 'H', + 'AGT': 'D', + 'CGT': 'B', + 'ACGT': 'N'} + + pileup = self.pileup(indels=(percentage == 100)) + + # do not include indels in coverage calculations + coverage = self.coverage(pileup) + start, end = None, None + consensus = '' + for pos in range(0, len(pileup)): + if coverage[pos] >= 100: + if start is None: + start = pos + end = pos + + con_bp = '' + + if coverage[pos] > 0: + # if percentage is 100, we are generating a consensus sequence + # of the most common sequence + if percentage == 100: + con_bp_with_indel = sorted( + [(v, k) for k, v in pileup[pos].items()], + reverse=True)[0][1] + if len(con_bp_with_indel) > 1: + # TODO recalculate consensus base if we can't + # incorporate insertion + if pos % 3 != 2: + consensus += con_bp_with_indel[:1] + else: + if len(con_bp_with_indel) % 3 != 1: + consensus += con_bp_with_indel[:1] + else: + consensus += con_bp_with_indel + else: + consensus += con_bp_with_indel + # else we are generating a sanger-like consensus sequence + else: + for token, token_count in sorted(pileup[pos].items()): + if token != '-' and token.upper() != 'N': + if decimal.Decimal(token_count) / coverage[pos] * \ + 100 >= percentage: + con_bp += token + + if len(con_bp.upper()) == 0: + consensus += 'N' + else: + consensus += iupac[con_bp.upper()] + else: + consensus += 'n' + + consensus_seq = '' + if start is not None: + while start % 3 != 0: + start += 1 + while end % 3 != 2: + end -= 1 + consensus_seq = consensus[start:end + 1] + + return consensus_seq + + def mask_unconfident_differences(self, variants_obj): + """"""Mask unconfident differences by changing their case to lower"""""" + + variants = variants_obj.variants + rid = next(iter(variants.keys())) + + for name, mapped_read in self.mapped_reads.items(): + for pos in mapped_read.differences: + # mapped_read.differences[pos] will be a string of length 1. + # or more. + # If we have a substitution/deletion, it will be of length 1. + # If we have an insertion, it will be of length >= 2 with the + # first position being a substitution/deletion or a match ( + # indicated with a '.') + substitution = mapped_read.differences[pos][:1] + insertion = mapped_read.differences[pos][1:] + + if substitution != ""."" and substitution != ""-"": + if (substitution.lower() not in variants[rid][pos + 1] or + substitution.lower() == ""n"" or + variants[rid][pos + 1][substitution.lower()].filter + != ""PASS""): + substitution = substitution.lower() + + mapped_read.differences[pos] = substitution + insertion + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Microbiology","phac-nml/quasitools","quasitools/calculate.py",".py","10116","567",""""""" +# ============================================================================= + +Copyright Government of Canada 2018 + +Written by: Eric Marinier, Public Health Agency of Canada, + National Microbiology Laboratory + +Funded by the National Micriobiology Laboratory and the Genome Canada / Alberta + Innovates Bio Solutions project ""Listeria Detection and Surveillance + using Next Generation Genomics"" + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +# ============================================================================= +"""""" + +import math + +GAP = '-' + + +def shannon_entropy(frequencies): + """""" + # ======================================================================== + + SHANNON ENTROPY + + + PURPOSE + ------- + + Calculates the Shannon entropy of a list of frequencies. + + + INPUT + ----- + + [FLOAT LIST] [frequencies] + The list of frequencies. These frequencies should sum to 1. + + + RETURN + ------ + + [FLOAT] + The Shannon entropy of the frequencies. + + # ======================================================================== + """""" + + entropy = 0 + + for frequency in frequencies: + + entropy -= float(frequency) * math.log(float(frequency)) + + return entropy + + +def minimum_mutation_frequency(M, N, a): + """""" + # ======================================================================== + + MINIMUM MUTATION FREQUENCY + + + PURPOSE + ------- + + Calculates the minimum mutation frequency. + + + INPUT + ----- + + [INT] [M] + The number of mutations. + + [INT] [N] + The total number of clones (reads) sampled from the viral + quasispecies. + + [INT] [a] + The length of the amplicons. + + + RETURN + ------ + + [FLOAT] + The minimum mutation frequency. + + # ======================================================================== + """""" + + Mfmin = float(M) / (float(N) * float(a)) + + return Mfmin + + +def mutation_frequency(H, D): + """""" + # ======================================================================== + + MUTATION FREQUENCY + + + PURPOSE + ------- + + Calculates the mutation frequency. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The mutation frequency. + + # ======================================================================== + """""" + + sumd = 0 + + for i in range(0, H): + + sumd += D[0][i] + + Mfe = float(sumd) / float(H) + + return Mfe + + +def maximum_mutation_frequency(H, F, D): + """""" + # ======================================================================== + + MAXIMUM MUTATION FREQUENCY + + + PURPOSE + ------- + + Calculates the maximum mutation frequency. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [FLOAT LIST] [F] + A list of (relative) frequencies. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The maximum mutation frequency. + + # ======================================================================== + """""" + + Mfmax = 0 + + for i in range(0, H): + + Mfmax += F[i] * D[0][i] + + return Mfmax + + +def sample_nucleotide_diversity_entity(H, D): + """""" + # ======================================================================== + + SAMPLE NUCLEOTIDE DIVERSITY (ENTITY-LEVEL) + + + PURPOSE + ------- + + Calculates the sample nucleotide diversity. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The entity-level sample nucleotide diversity. + + # ======================================================================== + """""" + + sum_substitutions = 0 + + for i in range(0, H): + + for j in range(0, H): + + sum_substitutions += D[i][j] + + diversity = float(sum_substitutions) / (float(H) * float(H - 1)) + + return diversity + + +def population_nucleotide_diversity(H, p, D): + """""" + # ======================================================================== + + POPULATION NUCLEOTIDE DIVERSITY + + + PURPOSE + ------- + + Calculates the population nucleotide diversity. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [FLOAT] [p] + A list of (relative) frequencies. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The population nucleotide diversity. + + # ======================================================================== + """""" + + diversity = 0 + + for i in range(0, H): + + for j in range(0, H): + + diversity += p[i] * D[i][j] * p[j] + + return diversity + + +def sample_nucleotide_diversity(N, H, p, D): + """""" + # ======================================================================== + + SAMPLE NUCLEOTIDE DIVERSITY + + + PURPOSE + ------- + + Calculates the sample nucleotide diversity. + + + INPUT + ----- + + [INT] [N] + The total number of clones (reads) sampled from the viral + quasispecies. + + [INT] [H] + The number of haplotypes. + + [FLOAT] [p] + A list of (relative) frequencies. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The sample nucleotide diversity. + + # ======================================================================== + """""" + + diversity = 0 + + for i in range(0, H): + + for j in range(0, H): + + diversity += p[i] * D[i][j] * p[j] + + diversity *= (float(N) / float(N - 1)) + + return diversity + + +def simpson_index(H, P): + """""" + # ======================================================================== + + SIMPSON INDEX + + + PURPOSE + ------- + + Calculates the Simpson index. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [FLOAT] [P] + A list of (relative) frequencies. + + + RETURN + ------ + + [FLOAT] + The Simpson index. + + # ======================================================================== + """""" + + index = 0 + + for i in range(0, H): + + index += float(P[i]) * float(P[i]) + + return index + + +def gini_simpson_index(H, P): + """""" + # ======================================================================== + + GINI-SIMPSON INDEX + + + PURPOSE + ------- + + Calculates the Gini-Simpson index. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [FLOAT] [P] + A list of (relative) frequencies. + + + RETURN + ------ + + [FLOAT] + The Gini-Simpson index. + + # ======================================================================== + """""" + + return (1 - simpson_index(H, P)) + + +def hill_number(H, P, Q): + """""" + # ======================================================================== + + HILL NUMBER + + + PURPOSE + ------- + + Calculates the simpson index. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [FLOAT] [P] + A list of (relative) frequencies. + + [INT] [Q] + The particular Hill number to calculate. + + + RETURN + ------ + + [FLOAT] + The Hill number for the passed Q. + + # ======================================================================== + """""" + + # Undefined at one, exponent of entropy: + if Q == 1: + + entropy = shannon_entropy(P) + number = math.exp(entropy) + return number + + else: + + number = 0 + + for i in range(0, H): + + number += math.pow(P[i], Q) + + number = math.pow(number, (1.0 / (1.0 - Q))) + + return number + + +def FAD(H, D): + """""" + # ======================================================================== + + FUNCTIONAL ATTRIBUTE DIVERSITY + + + PURPOSE + ------- + + Calculates the functional attribute diversity. + + + INPUT + ----- + + [INT] [H] + The number of haplotypes. + + [2D ARRAY] [D] + A distance matrix of haplotypes pair-wise genetic distances + (fraction of nt differences). + + + RETURN + ------ + + [FLOAT] + The functional attribute diversity. + + # ======================================================================== + """""" + + number = 0 + + for i in range(0, H): + + for j in range(0, H): + + number += D[i][j] + + return number + + +def hamming_distance(sequence1, sequence2): + """""" + # ======================================================================== + + HAMMING DISTANCE + + + PURPOSE + ------- + + Calculates the Hamming distance between two sequences. + + + INPUT + ----- + + [STRING] [sequence1] + The first of two sequences. + + [STRING] [sequence2] + The second of two sequences. + + + RETURN + ------ + + [INT] + The Hamming distance between the two passed sequences. + + # ======================================================================== + """""" + + if len(sequence1) != len(sequence2): + raise ValueError( + ""Hamming Distance is undefined for sequences of unequal length."") + + distance = 0 + + for i in range(0, len(sequence1)): + + if (sequence1[i] != sequence2[i]) \ + and (sequence1[i] != GAP) and (sequence2[i] != GAP): + + distance += 1 + + return distance +","Python" +"Microbiology","phac-nml/quasitools","quasitools/utilities.py",".py","2442","73",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +INSERTION = 1 +DELETION = 2 +REF_SKIP = 3 +SOFT_CLIP = 4 +HARD_CLIP = 5 + + +def sam_alignment_to_padded_alignment(alignment, reference): + ref_dna = reference.sub_seq(alignment.reference_start, + alignment.reference_end-1) + query_dna = alignment.query_alignment_sequence + + pad_ref, pad_match, pad_query = '', '', '' + + for (operation, length) in alignment.cigartuples: + if operation is SOFT_CLIP: + """"""nothing needs to be done for soft clips"""""" + elif operation is INSERTION: + pad_ref += '-' * length + pad_query += query_dna[0:length] + query_dna = query_dna[length:] + pad_match += ' ' * length + elif operation is DELETION or operation is REF_SKIP: + pad_ref += ref_dna[0:length] + ref_dna = ref_dna[length:] + pad_query += '-' * length + pad_match += ' ' * length + elif operation is HARD_CLIP: + """"""nothing needs to be done for hard clips"""""" + else: + pad_ref += ref_dna[0:length] + ref_dna = ref_dna[length:] + pad_query += query_dna[0:length] + query_dna = query_dna[length:] + pad_match += '|' * length + + return (pad_ref, pad_match, pad_query) + + +def pairwise_alignment_to_differences(pad_ref, pad_query, ref_start): + differences = dict() + + index = -1 + for i, c in enumerate(pad_ref): + if c == '-': + if ref_start + index not in differences.keys(): + differences[ref_start + index] = '.' + differences[ref_start + index] += pad_query[i] + else: + index += 1 + if c is not pad_query[i]: + differences[ref_start + index] = pad_query[i] + + return differences +","Python" +"Microbiology","phac-nml/quasitools","quasitools/patient_analyzer.py",".py","12179","329",""""""" +Copyright Government of Canada 2017 - 2018 + +Written by: Camy Tran and Matthew Fogel, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import subprocess +import PyAAVF.parser as parser +from quasitools.parsers.genes_file_parser import parse_BED4_file +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.nt_variant import NTVariantCollection +from quasitools.aa_variant import AAVariantCollection +from quasitools.mutations import MutationDB +from quasitools.aa_census import AACensus, CONFIDENT +from quasitools.quality_control import QualityControl +from quasitools.quality_control import LENGTH +from quasitools.quality_control import SCORE +from quasitools.quality_control import NS +import Bio.SeqIO + +# GLOBALS + +ERROR_RATE = ""error_rate"" +MIN_VARIANT_QUAL = ""min_variant_qual"" +MIN_AC = ""min_ac"" +MIN_DP = ""min_dp"" +MIN_FREQ = 'min_freq' + + +class PatientAnalyzer(): + def __init__(self, id, output_dir, reads, reference, + BED4_file, mutation_db, quiet, consensus_pct): + self.id = id + self.output_dir = output_dir + self.reads = reads + self.reference = reference + self.mutation_db = mutation_db + self.BED4_file = BED4_file + + self.quiet = quiet + self.consensus_pct = consensus_pct + + self.input_size = 0 + self.determine_input_size() + + self.references = parse_references_from_fasta(self.reference) + self.genes = parse_BED4_file(BED4_file, self.references[0].name) + + self.quality = QualityControl() + + if not os.path.isdir(output_dir): + os.mkdir(output_dir) + + self.filtered_reads_dir = ""%s/filtered.fastq"" % output_dir + + def determine_input_size(self): + sequences = Bio.SeqIO.parse(self.reads, ""fastq"") + + for seq in sequences: + self.input_size += 1 + + def filter_reads(self, quality_filters): + # Calls quality_control.filter_reads function + if not self.quiet: + print(""# Performing quality control on reads..."") + + # return true if filtering function finished successfully + return self.quality.filter_reads(self.reads, + self.filtered_reads_dir, + quality_filters) + + def analyze_reads(self, fasta_id, variant_filters, + reporting_threshold, generate_consensus): + + # Map reads against reference using bowtietwo + if not self.quiet: + print(""# Mapping reads..."") + + try: + bam = self.generate_bam(fasta_id) + except Exception as error: + raise(error) + + if not self.quiet: + print(""# Loading read mappings..."") + + # cmd_consensus + if generate_consensus: + cons_seq_file = open(""%s/consensus.fasta"" % self.output_dir, ""w+"") + + mapped_read_collection_arr = [] + for r in self.references: + mrc = parse_mapped_reads_from_bam(r, bam) + mapped_read_collection_arr.append(mrc) + consensus_seq = mrc.to_consensus(self.consensus_pct) + if generate_consensus and len(consensus_seq) > 0: + cons_seq_file.write('>{0}_{1}_{2}\n{3}'.format( + fasta_id, reporting_threshold, r.name, + consensus_seq)) + + if generate_consensus: + cons_seq_file.close() + + # cmd_callntvar + if not self.quiet: + print(""# Identifying variants..."") + + variants = NTVariantCollection.from_mapped_read_collections( + variant_filters[ERROR_RATE], self.references, + *mapped_read_collection_arr) + + variants.filter('q%s' % variant_filters[MIN_VARIANT_QUAL], + 'QUAL<%s' % variant_filters[MIN_VARIANT_QUAL], True) + variants.filter('ac%s' % variant_filters[MIN_AC], + 'AC<%s' % variant_filters[MIN_AC], True) + variants.filter('dp%s' % variant_filters[MIN_DP], + 'DP<%s' % variant_filters[MIN_DP], True) + + vcf_file = open(""%s/hydra.vcf"" % self.output_dir, ""w+"") + vcf_file.write(variants.to_vcf_file()) + vcf_file.close() + + # cmd_aa_census + if not self.quiet: + print(""# Masking filtered variants..."") + + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants) + + if not self.quiet: + print(""# Building amino acid census..."") + + # Determine which frames our genes are in + frames = set() + + for gene in self.genes: + frames.add(self.genes[gene]['frame']) + + aa_census = AACensus(self.reference, mapped_read_collection_arr, + self.genes, frames) + + coverage_file = open(""%s/coverage_file.csv"" % self.output_dir, ""w+"") + coverage_file.write(aa_census.coverage(frames)) + coverage_file.close() + + # cmd_aavariants + if not self.quiet: + print(""# Finding amino acid mutations..."") + + # Create AAVar collection and print the aavf file + aa_vars = AAVariantCollection.from_aacensus(aa_census) + + # Filter for mutant frequency + aa_vars.filter('mf%s' % variant_filters[MIN_FREQ], + 'freq<%s' % variant_filters[MIN_FREQ], True) + + # Build the mutation database and update collection + if self.mutation_db is not None: + mutation_db = MutationDB(self.mutation_db, self.genes) + aa_vars.apply_mutation_db(mutation_db) + + aavf_obj = aa_vars.to_aavf_obj(""hydra"", + os.path.basename(self.reference), + CONFIDENT) + records = list(aavf_obj) + + mut_report = open(""%s/mutation_report.aavf"" % self.output_dir, ""w+"") + + writer = parser.Writer(mut_report, aavf_obj) + + for record in records: + writer.write_record(record) + + mut_report.close() + writer.close() + + # cmd_drmutations + if not self.quiet: + print(""# Writing drug resistant mutation report..."") + + dr_report = open(""%s/dr_report.csv"" % self.output_dir, ""w+"") + dr_report.write(aa_vars.report_dr_mutations(mutation_db, + reporting_threshold)) + dr_report.close() + + self.output_stats(mapped_read_collection_arr) + + # This is a helper method that generates the bam file. + # It takes as an argument the fasta_id, which is used by bowtie2 as the + # RG-ID in the output bam file. + def generate_bam(self, fasta_id): + """""" Runs bowtietwo local alignment on self.reads + to generate a bam file """""" + + sorted_bam_fn = ""%s/align.bam"" % self.output_dir + log_fn = ""%s/log.txt"" % self.output_dir + bowtietwo_bam_output = sorted_bam_fn[0:sorted_bam_fn.rindex(""."")] + bam_fn = ""%s/tmp.bam"" % self.output_dir + sam_fn = ""%s/tmp.sam"" % self.output_dir + + # create the files + bam_fh = open(bam_fn, ""w+"") + sam_fh = open(sam_fn, ""w+"") + log_fh = open(log_fn, ""w+"") + log_fh.write(""Log output:\n"") + log_fh.close() + + bowtietwo_index = self.reference[0:self.reference.rindex(""."")] + + bowtietwo_cmd = [""bowtie2"", ""--local"", ""--rdg"", '8,3', ""--rfg"", '8,3', + ""--rg-id"", fasta_id, ""--ma"", ""1"", ""--mp"", '2,2', ""-S"", + sam_fn, ""-x"", bowtietwo_index, ""-U"", + self.filtered_reads_dir] + + proc = subprocess.Popen(bowtietwo_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + try: + self.process_tool_output(proc, log_fn, ""bowtie2"") + except Exception as error: + raise(error) + + # Convert sam output to bam output + sam_to_bam_cmd = [""samtools"", ""view"", ""-bt"", + (""%s.fai"" % self.reference), ""-o"", bam_fn, sam_fn] + + proc = subprocess.Popen(sam_to_bam_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + try: + self.process_tool_output(proc, log_fn, ""samtools view"") + except Exception as error: + raise(error) + + # Sort bam output + sort_bam_cmd = [""samtools"", ""sort"", bam_fn, ""-T"", bowtietwo_bam_output, + ""-o"", sorted_bam_fn] + + proc = subprocess.Popen(sort_bam_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + try: + self.process_tool_output(proc, log_fn, ""samtools sort"") + except Exception as error: + raise(error) + + # Index bam output + index_bam_cmd = [""samtools"", ""index"", sorted_bam_fn] + + proc = subprocess.Popen(index_bam_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + try: + self.process_tool_output(proc, log_fn, ""samtools index"") + except Exception as error: + raise(error) + + bam_fh.close() + sam_fh.close() + + os.unlink(bam_fn) + os.unlink(sam_fn) + + return sorted_bam_fn + + def process_tool_output(self, proc, log_fn, name): + """"""Captures process output, printing it to a log file and + throwing an exception if an error has occured"""""" + output, error = proc.communicate() + if proc.returncode != 0: + fd = open(log_fn, ""a+"") + fd.write(""Error: %s returned the following output:"" + ""\n%s"" % (name, error)) + fd.close() + raise Exception(""%s returned the following output:"" + ""\n%s"" % (name, error)) + else: + fd = open(log_fn, ""a+"") + fd.write(""%s output: %s %s"" % (name, output, error)) + # printing stdout and stderr though bowtie2 currently will always + # output to stderr instead of stdout even if no error occurred + fd.close() + + def output_stats(self, mapped_read_collection_arr): + self.amount_filtered = self.quality.get_amount_filtered() + mr_len = len(mapped_read_collection_arr[0].mapped_reads) + + stats_report = open(""%s/stats.txt"" % self.output_dir, ""w+"") + + stats_report.write(""Input Size: %i\n"" % self.input_size) + stats_report.write(""Number of reads filtered due to length: %i\n"" % + self.amount_filtered[LENGTH]) + stats_report.write((""Number of reads filtered due to average "" + ""quality score: %i\n"") + % self.amount_filtered[SCORE]) + stats_report.write((""Number of reads filtered due to presence "" + ""of Ns: %i\n"") % self.amount_filtered[NS]) + stats_report.write(""Number of reads filtered due to excess "" + ""coverage: 0\n"") + stats_report.write((""Number of reads filtered due to poor "" + ""mapping: %i\n"") % + (self.input_size - self.amount_filtered[LENGTH] - + self.amount_filtered[SCORE] - + self.amount_filtered[NS] - + mr_len)) + stats_report.write(""Percentage of reads filtered: %0.2f"" % + (float(self.input_size - mr_len) / + self.input_size * 100)) + + stats_report.close() +","Python" +"Microbiology","phac-nml/quasitools","quasitools/nt_variant.py",".py","7017","171",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import re +from datetime import date +from scipy.stats import poisson +from numpy import log10 +from quasitools.variant import Variant, VariantCollection + + +class NTVariant(Variant): + def __info_to_str(self): + """"""Convert info dict to info string for vcf entry."""""" + return ""DP=%i;AC=%i;AF=%0.4f"" % (self.info['DP'], + self.info['AC'], + self.info['AF']) + + def to_vcf_entry(self): + return ""%s\t%i\t%s\t%s\t%s\t%s\t%s\t%s"" % (self.chrom, self.pos, + self.id, self.ref, self.alt, + self.qual, self.filter, + self.__info_to_str()) + + +class NTVariantCollection(VariantCollection): + @classmethod + def from_mapped_read_collections(cls, error_rate, references, *args): + """"""Build the NTVariantCollection from any number of + MappedReadCollection objects"""""" + obj = cls(references) + + for mrc in args: + pileup = mrc.pileup() + rid = mrc.reference.name + + coverage = mrc.coverage(pileup) + + for pos in range(0, len(pileup)): + for event, event_count in pileup[pos].items(): + alt_allele = event.lower() + if len(event) > 1: + alt_allele = event[:1].lower() + + if alt_allele != '-' and alt_allele != \ + mrc.reference.sub_seq(pos, pos).lower(): + + if rid in obj.variants and pos+1 in obj.variants[rid] \ + and alt_allele in obj.variants[rid][pos+1]: + + variant_obj = obj.variants[rid][pos+1][alt_allele] + + new_allele_count = \ + event_count + variant_obj.info['AC'] + variant_obj.info['AC'] = new_allele_count + variant_obj.info['AF'] = \ + float(new_allele_count) / coverage[pos] + + else: + event_frequency = \ + float(event_count) / coverage[pos] + + variant_obj = NTVariant(chrom=mrc.reference.name, + pos=pos+1, + ref=mrc.reference.sub_seq( + pos, pos).lower(), + alt=alt_allele, + info={ + 'DP': coverage[pos], + 'AC': event_count, + 'AF': event_frequency + }) + + obj.variants[rid][pos+1][alt_allele] = variant_obj + + for alt_allele, variant in obj.variants[rid][pos+1].items(): + variant.qual = obj.__calculate_variant_qual( + error_rate, variant.info['AC'], variant.info['DP']) + + return obj + + def to_vcf_file(self): + """"""Build a string representation of our Variants object + (i.e. a vcf file)."""""" + d = date.today() + + report = ""##fileformat=VCFv4.2\n"" + report += ""##fileDate=%s\n"" % (d.strftime(""%Y%m%d"")) + report += ""##source=quasitools\n"" + + # print contig info per reference + for reference in self.references: + report += ""##contig=\n"" % (reference.name, + len(reference.seq)) + + info_line = ""##INFO=\n"" + + report += info_line % (""DP"", ""1"", ""Integer"", ""Total Depth"") + report += info_line % (""AC"", ""A"", ""Integer"", ""Allele Count"") + report += info_line % (""AF"", ""A"", ""Float"", ""Allele Frequency"") + + filter_line = ""##FILTER=\n"" + + for id, filter in self.filters.items(): + report += filter_line % (id, filter['result'], + filter['expression']) + + report += ""#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"" + + for rid in self.variants: + for pos in self.variants[rid]: + for alt_allele, variant in sorted( + self.variants[rid][pos].items()): + if variant.qual > 0: + report += ""\n"" + variant.to_vcf_entry() + + return report + + def __calculate_variant_qual(self, error_rate, variant_count, coverage): + """"""Calculate variant qual using poisson distribution."""""" + avg_errors = coverage * error_rate + + prob = poisson.cdf(variant_count-1, avg_errors) + + qual = 100 + if prob < 1: + qual = int(min((-10) * log10(1-prob), 100)) + + return qual + + def filter(self, id, expression, result): + """"""Apply filter to variants given an id, expression and result."""""" + self.filters[id] = {'expression': expression, 'result': result} + + # only allow simple expressions for the time being i.e. DP>30 + (attribute, operator, value) = re.split('([><=!]+)', expression) + + for rid in self.variants: + for pos in self.variants[rid]: + for alt_allele, variant in self.variants[rid][pos].items(): + attribute_value = None + if hasattr(variant, attribute.lower()): + attribute_value = eval( + ""variant.%s"" % attribute.lower()) + else: + attribute_value = variant.info[attribute.upper()] + + if eval(""%s %s %s"" % (attribute_value, operator, value)) \ + != result: + if variant.filter == '.': + variant.filter = 'PASS' + else: + if variant.filter == '.' or variant.filter == 'PASS': + variant.filter = id + else: + variant.filter += "";%s"" % id +","Python" +"Microbiology","phac-nml/quasitools","quasitools/aa_variant.py",".py","15177","349",""""""" +Copyright Government of Canada 2017 + +Written by: Eric Chubaty, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import re +import datetime +from PyAAVF.model import AAVF, Record, Info, Filter +from collections import defaultdict +from Bio.Seq import Seq +from quasitools.aa_census import CONFIDENT, UNCONFIDENT +from quasitools.variant import Variant, VariantCollection +from numpy import array as np_array + + +class AAVariant(Variant): + + def __init__(self, gene=""."", freq=0, + coverage=0, census_ind=0, + info=dict(), **kwargs): + """"""Add additional fields to Variant for AAVariant"""""" + super(AAVariant, self).__init__(**kwargs) + + self.info = info + self.gene = gene + self.freq = freq + self.coverage = coverage + self.census_ind = census_ind + + def info_to_dict(self): + info_dict = {} + + info_dict['RC'] = self.info['RC'] + info_dict['AC'] = self.info['AC'] + info_dict['ACF'] = self.info['ACF'] + info_dict['CAT'] = self.info['CAT'] + info_dict['SRVL'] = self.info['SRVL'] + + return info_dict + + +class AAVariantCollection(VariantCollection): + + def __init__(self, references): + """"""Add additional field to VariantCollection for AAVariantCollection"""""" + super(AAVariantCollection, self).__init__(references) + self.variants = defaultdict( + lambda: defaultdict(lambda: defaultdict(dict))) + + @classmethod + def from_aacensus(cls, aa_census): + """"""Build the AAVariantCollection from any number of + AACensus objects"""""" + + # Handle aa_census being an array or single element nicely + aa_census = np_array([aa_census]).flatten() + + var_collect = cls(aa_census) + + # Build up the Collection of AAVariants from many census + for census_ind, census in enumerate(aa_census): + # For each gene in this census + for gene_key in census.genes: + gene = census.genes[gene_key] + frame = gene['frame'] + + # Find reference sequence for this frame + ref_seq = census.mapped_read_collections[0].reference.seq + ref_seq = ref_seq[ + frame:((len(ref_seq) - frame) - + (len(ref_seq) - frame) % 3 + frame) + ] + + # Turn sequence to amino acids + ref_aa = Seq(ref_seq).translate() + + # Used for WC in info field for each variant + ref_codon_array = re.findall("".{3}"", ref_seq) + + # Build up what will be the key to the dictionary + for ref_codon_pos in range(gene['start'] // 3, + gene['end'] // 3 - 2): + coverage = census.coverage_at(frame, ref_codon_pos) + + for confidence in (CONFIDENT, UNCONFIDENT): + for aa in census.aminos_at( + frame, ref_codon_pos, confidence + ): + + # Only add it if it is a mutation (it differs) + if aa != ref_aa[ref_codon_pos]: + + # Grab values for this mutation + + frequency = census.amino_frequency_at( + frame, ref_codon_pos, aa, confidence + ) / float(coverage) + + chrom = gene['chrom'] + + # Find AC (Allele Count) and + # ACF (Allele Count Frequency) + ac = """" + acf = """" + + for codon in census.amino_to_codons_at( + frame, ref_codon_pos, aa, confidence + ): + + ac += ""%s,"" % codon + + freq_acf = census\ + .codon_frequency_for_amino_at( + frame, ref_codon_pos, + aa, confidence, codon + ) + + acf += ""%0.4f,"" % (float(freq_acf) / + coverage) + + # Create AAVariant & slap it in the + # collection + mutation = AAVariant(chrom=chrom, + gene=gene_key, + id=""mutation"", + ref=ref_aa[ + ref_codon_pos], + alt=aa, + freq=frequency, + coverage=coverage, + census_ind=census_ind, + pos=(ref_codon_pos - ( + gene['start'] // 3 + ) + 1), + info={ + 'RC': ref_codon_array[ + ref_codon_pos + ].lower(), + 'AC': ac[:-1], + 'ACF': acf[:-1], + 'CAT': ""."", + 'SRVL': ""."" + }) + + var_collect.variants[chrom][ref_codon_pos][ + confidence][aa] = mutation + + return var_collect + + def to_aavf_obj(self, source_command, reference_filename, confidence): + metadata = {} + infos = {} + filters = {} + column_headers = [""CHROM"", ""GENE"", ""POS"", ""REF"", ""ALT"", ""FILTER"", + ""ALT_FREQ"", ""COVERAGE"", ""INFO""] + record_list = [] + + # Build metadata + metadata['fileformat'] = 'AAVFv1.0' + metadata['fileDate'] = datetime.date.today().strftime(""%Y%m%d"") + metadata['source'] = ""quasitools:%s"" % source_command + metadata['reference'] = [reference_filename] + + # Build infos + infos[""RC""] = Info(""RC"", ""1"", ""String"", ""Reference Codon"", + source_command, ""1.0"") + infos[""AC""] = Info(""AC"", ""."", ""String"", ""Alternate Codon"", + source_command, ""1.0"") + infos[""ACF""] = Info(""ACF"", ""."", ""Float"", (""Alternate Codon Frequency,"" + ""for each Alternate Codon,"" + ""in the same order as"" + ""listed.""), + source_command, ""1.0"") + infos[""CAT""] = Info(""CAT"", ""."", ""String"", ""Drug Resistance Category"", + source_command, ""1.0"") + infos[""SRVL""] = Info(""SRVL"", ""."", ""String"", + ""Drug Resistance Surveillance"", + source_command, ""1.0"") + + # Build filters + filters[""af0.01""] = Filter(""af0.01"", ""Set if True; alt_freq<0.01"") + + # Build record_list from self.variants + for chrom in self.variants: + for ref_codon_pos in self.variants[chrom]: + for aa in self.variants[chrom][ref_codon_pos][confidence]: + variant = (self.variants[chrom][ref_codon_pos] + [confidence][aa]) + + if aa.lower() != ""x"": + curr_record = Record(variant.chrom, variant.gene, + variant.pos, variant.ref, + variant.alt, variant.filter, + ""%0.4f"" % variant.freq, + variant.coverage, + variant.info_to_dict()) + + record_list.append(curr_record) + + return AAVF(metadata, infos, filters, column_headers, record_list) + + def report_dr_mutations(self, mutation_db, reporting_threshold): + """"""Builds a report of all drug resistant amino acid mutations present + in the AACensus object using a MutationDB object. A string containing + the report is then returned. + """""" + + report = (""Chromosome,Gene,Category,"" + ""Surveillance,Wildtype,Position,Mutation,"" + ""Mutation Frequency,Coverage\n"") + + # Loop through the mutation database and report on present mutations + for census in self.references: + + for dr_mutation_pos in mutation_db.positions(): + dr_mutations = mutation_db.mutations_at(dr_mutation_pos) + + for name in census.genes: + if (dr_mutation_pos >= census.genes[name]['start'] // 3 + and dr_mutation_pos <= + (census.genes[name]['end'] - 2) // 3): + + gene_name = name + + chrom = census.genes[gene_name]['chrom'] + + for dr_mutation in dr_mutations: + + if dr_mutation_pos in self.variants[chrom]: + if CONFIDENT in self.variants[chrom][dr_mutation_pos]: + if (dr_mutation in + self.variants[chrom][ + dr_mutation_pos][CONFIDENT] and + self.variants[chrom][ + dr_mutation_pos][CONFIDENT] + [dr_mutation].filter == ""PASS""): + + mutation_freq = ( + self.variants[chrom][ + dr_mutation_pos][ + CONFIDENT][ + dr_mutation].freq + ) * 100 + + coverage = self.variants[chrom][ + dr_mutation_pos][ + CONFIDENT][ + dr_mutation].coverage + + if mutation_freq > reporting_threshold: + report += ( + ""%s,%s,%s,%s,%s,%s,%s,%0.2f,%s\n"" + % (chrom, + dr_mutations[dr_mutation].gene, + dr_mutations[dr_mutation].category, + dr_mutations[ + dr_mutation].surveillance, + dr_mutations[dr_mutation].wildtype, + dr_mutations[dr_mutation].gene_pos, + dr_mutation, + mutation_freq, + coverage)) + + return report[:-1] + + def apply_mutation_db(self, mutation_db): + """"""Apply the mutation database to the variant collection + to update each variants category and surveillance variable within it. + + Assumes mutation_db != None + """""" + + # Iterate over the keys in variants + for chrom in self.variants: + for ref_codon_pos in self.variants[chrom]: + + dr_mutations = mutation_db.mutations_at(ref_codon_pos) + + for confidence in (CONFIDENT, UNCONFIDENT): + for aa in self.variants[chrom][ + ref_codon_pos][confidence]: + + # Init drug resistance variables + dr_mutation = None + category = ""."" + surveillance = ""."" + + # Assign cat and srvl if it's in the mutation db + if aa in dr_mutations: + dr_mutation = dr_mutations[aa] + category = dr_mutation.category + surveillance = dr_mutation.surveillance + + # Get the mutation to update + mutation = self.variants[chrom][ + ref_codon_pos][confidence][aa] + + # Update the mutation + mutation.info['CAT'] = category + mutation.info['SRVL'] = surveillance + + def filter(self, id, expression, result): + """"""Apply filter to variants given an id, expression and result."""""" + self.filters[id] = {'expression': expression, 'result': result} + + # only allow simple expressions for the time being i.e. DP>30 + (attribute, operator, value) = re.split('([><=!]+)', expression) + + for chrom in self.variants: + for ref_codon_pos in self.variants[chrom]: + + for confidence in self.variants[chrom][ref_codon_pos]: + for aa in self.variants[chrom][ref_codon_pos][confidence]: + attribute_value = None + + variant = self.variants[chrom][ + ref_codon_pos][confidence][aa] + + if hasattr(variant, attribute.lower()): + attribute_value = eval( + ""variant.%s"" % attribute.lower()) + else: + attribute_value = variant.info[attribute.upper()] + + if eval(""%s %s %s"" % ( + attribute_value, operator, value + )) != result: + if variant.filter == '.': + variant.filter = 'PASS' + else: + if variant.filter == '.' or \ + variant.filter == 'PASS': + variant.filter = id + else: + variant.filter += "";%s"" % id +","Python" +"Microbiology","phac-nml/quasitools","quasitools/variant.py",".py","1239","43",""""""" +Copyright Government of Canada 2015-2017 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + + +from collections import defaultdict + + +class Variant(object): + + def __init__(self, chrom, pos, id='.', ref='', alt='', qual='.', + filter='.', info='.'): + self.chrom = chrom + self.pos = pos + self.id = id + self.ref = ref + self.alt = alt + self.qual = qual + self.filter = filter + self.info = info + + +class VariantCollection(object): + + def __init__(self, references): + self.variants = defaultdict(lambda: defaultdict(dict)) + self.references = references + self.filters = {} +","Python" +"Microbiology","phac-nml/quasitools","quasitools/__init__.py",".py","0","0","","Python" +"Microbiology","phac-nml/quasitools","quasitools/quality_control.py",".py","9232","313",""""""" +Copyright Government of Canada 2018 + +Written by: Eric Marinier and Matthew Fogel, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import Bio.SeqIO +from Bio.Seq import Seq + +# GLOBALS + +TRIMMING = ""trimming"" +MASKING = ""masking"" +MASK_CHARACTER = ""N"" +MIN_READ_QUAL = ""min_read_qual"" +LENGTH_CUTOFF = ""length_cutoff"" +MEDIAN_CUTOFF = ""median_cutoff"" +MEAN_CUTOFF = ""mean_cutoff"" +SUCCESS = ""success"" +LENGTH = ""length"" +SCORE = ""score"" +NS = ""ns"" +PASS = 0 +FAIL_LENGTH = 1 +FAIL_SCORE = 2 +FAIL_NS = 3 + +# FILTERING SPECIFICATIONS + + +class QualityControl(): + """"""This class performs quality control on FASTQ reads."""""" + + def __init__(self): + """""" + Create instance of QualityControl class. + + Initialize a dictionary containing frequencies that reads were + filtered for reasons such as length, score, and ns. Initialize + another dictionary that contains status values and keys for the last + time passes_filters was called. + + """""" + self.amount_filtered = {} + self.amount_filtered[LENGTH] = 0 + self.amount_filtered[SCORE] = 0 + self.amount_filtered[NS] = 0 + self.status = {PASS: SUCCESS, + FAIL_LENGTH: LENGTH, + FAIL_SCORE: SCORE, + FAIL_NS: NS} + + def get_median_score(self, read): + """""" + Return the median score of a sequence record. + + INPUT + ----- + + [BIOPYTHON SEQRECORD] [read] + The read where the median score will be retrieved from. + + RETURN + ------ + + [INT] [median_score] + + """""" + length = len(read.seq) + last_pos = length - 1 + + scores = list(read.letter_annotations['phred_quality']) + + if length % 2 == 0: + median_score = ((scores[int(last_pos // 2)] + + scores[int(last_pos // 2) + 1]) / 2) + else: + median_score = scores[int(last_pos // 2)] + + return median_score + + def get_mean_score(self, read): + """""" + Return the mean score of a sequence record. + + INPUT + ----- + + [BIOPYTHON SEQRECORD] [read] + The read where the mean score will be retrieved from. + + RETURN + ------ + + [INT] [mean_score] + + """""" + mean_score = (float(sum(read.letter_annotations['phred_quality'])) / + float(len(read.letter_annotations['phred_quality']))) + + return mean_score + + def trim_read(self, read, filters): + """""" + Iteratively trim the read until it meets all the filtering criteria. + + INPUT + ----- + + [BIOPYTHON SEQRECORD] [read] + The read to iteratively trim until it meets filtering criteria. + + [(FILTER -> VALUE) DICTIONARY] [filters] + The filtering critiera, as a dictionary of (filter, value) pairs, + which will be tested against the read after each iteration of read + trimming. + + POST + ---- + + The read will first be evaluated against the filtering criteria. If the + read passes the filtering criteria, then the read will be returned + without modification. However, if the read does not meet the filtering + criteria, it will be trimmed iteratively. + + In the latter case, the read will be trimmed iteratively, base by base, + from the tail end of the read, starting at position [len(read) - 1], + until either the read meets the filtering criteria, or the read is too + short. + + The trimmed and modified read will still be returned if it fails to be + improved with iterative trimming. + + """""" + length = len(read.seq) + len_cutoff = filters.get(LENGTH_CUTOFF) + status = self.passes_filters(read, filters) + # while read has not passed all filters and is >= the length cutoff, + # iteratively trim the read + while status is not PASS and length >= len_cutoff: + read = read[:-1] + length = len(read.seq) + status = self.passes_filters(read, filters) + + return read + + def mask_read(self, read, filters): + """""" + Mask the nucleotide of all low quality positions in the read. + + INPUT + ----- + + [BIOPYTHON SEQRECORD] [read] + The read to mask low quality positions within. + + [(FILTER -> VALUE) DICTIONARY] [filters] + The filtering criteria, as a dictionary of (filter, value) pairs. + The minimum quality score will be taken from this dictionary as the + value of the MIN_READ_QUAL key. + + POST + ---- + + The nucleotide positions in the passed read will be masked with + a MASK_CHARACTER if their PHRED quality score is below the minimum. + + """""" + scores = list(read.letter_annotations['phred_quality']) + minimum = int(filters.get(MIN_READ_QUAL)) + + # Check every quality score: + for i in range(0, len(scores)): + + score = int(scores[i]) + + # Is the score too low? + if score < minimum: + + # Mask the base at this position: + sequence = str(read.seq) + sequence = sequence[:i] + MASK_CHARACTER + sequence[i + 1:] + read.seq = Seq(sequence) + + return + + def passes_filters(self, read, filters): + """""" + Determine whether or not the read passes all the filtering criteria. + + INPUT + ----- + + [BIOPYTHON SEQRECORD] [read] + The read that will be evaluated using the filtering criteria. + + [(FILTER -> VALUE) DICTIONARY] [filters] + The filtering criteria, as a dictionary of (filter, value) pairs, + all of which will be tested against the read. + + RETURN + ------ + + [INT] [result] + PASS: the read passes all the filtering criteria + FAIL_LENGTH: the read fails due to read length + FAIL_SCORE: the read fails due to read score + FAIL_NS: the read fails due to MASK_CHARACTERs + + """""" + length_cutoff = filters.get(LENGTH_CUTOFF) + median_cutoff = filters.get(MEDIAN_CUTOFF) + mean_cutoff = filters.get(MEAN_CUTOFF) + filter_ns = filters.get(NS) + + if length_cutoff and len(read.seq) < length_cutoff: + return FAIL_LENGTH + + if median_cutoff and self.get_median_score(read) < median_cutoff: + return FAIL_SCORE + + elif mean_cutoff and self.get_mean_score(read) < mean_cutoff: + return FAIL_SCORE + + if filter_ns and MASK_CHARACTER.lower() in read.seq.lower(): + return FAIL_NS + + return PASS + + def filter_reads(self, reads_location, output_location, filters): + """""" + Filter reads according to a variety of filtering criteria. + + INPUT + ----- + + [FILE LOCATION] [reads_location] + The file location of a FASTQ-encoded reads file. + + [FILE LOCATION] [output_location] + The output location of the filtered reads. + + [(FILTER -> VALUE) DICTIONARY] [filters] + The filtering criteria, as a dictionary of (filter, value) pairs, + all of which will be tested against the read. + + RETURN + ------ + + Returns true if function completed successfully. + + POST + ---- + + Writes FASTQ reads that pass the filtering criteria to + [output_location]. The self.amount_filtered dict will + contain the frequencies that a read was filtered (excluded from being + written to [output_location]) due to failing the filtering criteria. + + """""" + filtered_reads_file = open(output_location, ""w+"") + reads = Bio.SeqIO.parse(reads_location, ""fastq"") + + for read in reads: + + if filters.get(TRIMMING): + + read = self.trim_read(read, filters) + + key = self.passes_filters(read, filters) + + if key == PASS: + + if filters.get(MASKING): + + self.mask_read(read, filters) + + Bio.SeqIO.write(read, filtered_reads_file, ""fastq"") + + elif self.status.get(key) in self.amount_filtered: + + self.amount_filtered[self.status.get(key)] += 1 + + filtered_reads_file.close() + + return True + + def get_amount_filtered(self): + """""" + Get the frequencies that the read was filtered. + + RETURN + ------ + + [(FILTER -> FREQUENCY) DICTIONARY] [self.amount_filtered] + The dictionary containing the frequencies that the read was + filtered due to filtering criteria. + + """""" + return self.amount_filtered +","Python" +"Microbiology","phac-nml/quasitools","quasitools/mutations.py",".py","2806","84",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from collections import defaultdict + + +class Mutation(object): + def __init__(self, gene, wildtype, gene_pos, frequency, filter): + self.gene = gene + self.wildtype = wildtype + self.gene_pos = gene_pos + self.frequency = frequency + self.filter = filter + + +class MutationDBEntry(object): + def __init__(self, gene, wildtype, gene_pos, category, surveillance, + comment): + self.gene = gene + self.wildtype = wildtype + self.gene_pos = gene_pos + self.category = category + self.surveillance = surveillance + self.comment = comment + + +class MutationDB(object): + def __init__(self, mutation_db, genes): + self.mutation_db = mutation_db + self.genes = genes + self.mutations = defaultdict(dict) + + self._build() + + def _build(self): + """"""Builds the mutations dictionary for the mutation database object"""""" + + with open(self.mutation_db, ""r"") as input: + for line in input: + if line[0] != ""#"": + gene, wildtype, gene_pos, mutation, category, \ + surveillance, comment = line.rstrip().split(""\t"") + + ref_pos = \ + int(gene_pos) - 1 + (self.genes[gene][""start""] // 3) + + if surveillance == ""Yes"" or surveillance == ""No"": + db_entry = MutationDBEntry(gene, wildtype, gene_pos, + category, surveillance, + comment) + + self.mutations[ref_pos][mutation] = db_entry + else: + raise ValueError(""Mutation Database is incorrectly"" + ""formatted."") + + def positions(self): + """"""Returns a list of positions that contain a drug resistant mutation + """""" + + return sorted(self.mutations.keys()) + + def mutations_at(self, pos): + """"""Returns a list of drug resistant mutations found at the given + position. + """""" + + return self.mutations[pos] +","Python" +"Microbiology","phac-nml/quasitools","quasitools/cli.py",".py","2493","86",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import sys +import click + + +CONTEXT_SETTINGS = dict(auto_envvar_prefix='QUASITOOLS') + + +class Context(object): + + def __init__(self): + self.verbose = False + + def log(self, msg, *args): + """"""Logs a message to stderr."""""" + if args: + msg %= args + click.echo(msg, file=sys.stderr) + + def vlog(self, msg, *args): + """"""Logs a message to stderr only if verbose is enabled."""""" + if self.verbose: + self.log(msg, *args) + + +pass_context = click.make_pass_decorator(Context, ensure=True) +cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), + 'commands')) + + +class QuasiToolsCLI(click.MultiCommand): + + def list_commands(self, ctx): + rv = [] + for filename in os.listdir(cmd_folder): + if filename.endswith('.py') and \ + filename.startswith('cmd_'): + rv.append(filename[4:-3]) + rv.sort() + return rv + + def get_command(self, ctx, name): + try: + if sys.version_info[0] == 2: + name = name.encode('ascii', 'replace') + mod = __import__('quasitools.commands.cmd_' + name, + None, None, ['cli']) + except ImportError: + return + return mod.cli + +# By default click will go to setup.py and scan for +# the version number and then store it in the variable version. + + +@click.version_option( + None, + ""--ver"", + ""--version"", + message=('quasitools, version %(version)s')) +@click.command(cls=QuasiToolsCLI, context_settings=CONTEXT_SETTINGS) +@click.option('-v', '--verbose', is_flag=True, + help='Enables verbose mode.') +@pass_context +def cli(ctx, verbose): + """"""A collection of tools for Viral Quasispecies."""""" + ctx.verbose = verbose +","Python" +"Microbiology","phac-nml/quasitools","quasitools/codon_variant.py",".py","11327","305",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import re +from collections import defaultdict +from quasitools.aa_census import CONFIDENT +from quasitools.variant import Variant, VariantCollection +from numpy import array as np_array +from Bio.Seq import Seq +from numpy import log + + +class CodonVariant(Variant): + + def __init__(self, gene, nt_start_gene, nt_end_gene, + nt_start, nt_end, ref_codon, mutant_codon, + ref_aa, mutant_aa, coverage, mutant_freq, + mutant_type, ns_count, s_count, **kwargs): + super(CodonVariant, self).__init__(**kwargs) + + self.gene = gene + self.nt_start_gene = nt_start_gene + self.nt_end_gene = nt_end_gene + self.nt_start = nt_start + self.nt_end = nt_end + self.ref_codon = ref_codon + self.mutant_codon = mutant_codon + self.ref_aa = ref_aa + self.mutant_aa = mutant_aa + self.coverage = coverage + self.mutant_freq = mutant_freq + self.mutant_type = mutant_type + self.ns_count = ns_count + self.s_count = s_count + + def to_csv_entry(self, offset): + return ""%s,%i-%i,%i,%i,%s,%s,%s,%s,%i,%.2f,%s,%0.4f,%0.4f\n"" % ( + self.gene, self.nt_start_gene+offset, self.nt_end_gene+offset, + self.nt_start+offset, self.nt_end+offset, self.ref_codon, + self.mutant_codon, self.ref_aa, self.mutant_aa, + self.coverage, self.mutant_freq, self.mutant_type, + self.ns_count, self.s_count + ) + + @classmethod + def from_aacensus(cls, gene_key, aa, codon, census, ref_codon_pos): + codon_permutations = [ + [[0]], [[0, 1], [1, 0]], + [ + [0, 1, 2], [0, 2, 1], + [1, 0, 2], [1, 2, 0], + [2, 0, 1], [2, 1, 0] + ] + ] + + gene = census.genes[gene_key] + frame = gene['frame'] + chrom = gene['chrom'] + + coverage = census.coverage_at(frame, ref_codon_pos) + ref_seq = census.mapped_read_collections[0].reference.seq + ref_codon = ref_seq[(ref_codon_pos*3+frame): + (ref_codon_pos*3+frame) + 3].lower() + ref_aa = Seq(ref_codon).translate()[0] + + if aa == ref_aa: + mutation_type = ""S"" + else: + mutation_type = ""NS"" + + nt_change_count = sum(1 for c in codon if not c.islower()) + base_change_pos = [] + + for codon_pos in range(0, 3): + nucleotide = codon[ + codon_pos:codon_pos+1] + if nucleotide.upper() == nucleotide: + base_change_pos.append(codon_pos) + + ns_count = 0 + s_count = 0 + + for codon_permutation in codon_permutations[nt_change_count-1]: + codon_pathway = ref_codon + for base_pos in codon_permutation: + mutant_pos = base_change_pos[base_pos] + mutant_nt = codon[mutant_pos:mutant_pos+1] + codon_pathway = codon_pathway[:mutant_pos] + \ + mutant_nt + codon_pathway[mutant_pos+1:] + + if Seq(codon_pathway).translate()[0] == ref_aa: + s_count += 1.0 + else: + ns_count += 1.0 + + return cls( + chrom=chrom, + gene=gene_key, + id=""mutation"", + coverage=coverage, + mutant_freq=census.codon_frequency_for_amino_at( + frame, + ref_codon_pos, + aa, + CONFIDENT, + codon)/float(coverage)*100.0, + pos=(ref_codon_pos - (gene['start'] // 3) + 1), + nt_start_gene=gene['start'], + nt_end_gene=gene['end'], + nt_start=ref_codon_pos*3 + frame, + nt_end=ref_codon_pos*3 + frame+2, + ref_codon=ref_codon, + mutant_codon=codon, + ref_aa=ref_aa, + mutant_aa=aa, + mutant_type=mutation_type, + ns_count=ns_count/len(codon_permutations[nt_change_count-1]), + s_count=s_count/len(codon_permutations[nt_change_count-1])) + + +class CodonVariantCollection(VariantCollection): + + def __init__(self, references): + super(CodonVariantCollection, self).__init__(references) + self.variants = defaultdict( + lambda: defaultdict(lambda: defaultdict(dict))) + + @classmethod + def from_aacensus(cls, aa_census): + """"""Build the CodonVariantCollection from any number of + AACensus objects"""""" + + # Handle aa_census being an array or single element nicely + aa_census = np_array([aa_census]).flatten() + + var_collect = cls(aa_census) + + # Build up the collection of CodonVariants from many census + for census_ind, census in enumerate(aa_census): + + # For each gene in this census + for gene_key in census.genes: + gene = census.genes[gene_key] + frame = gene['frame'] + + # Find reference sequence for this frame + ref_seq = census.mapped_read_collections[0].reference.seq + ref_seq = ref_seq[ + frame:((len(ref_seq) - frame) - + (len(ref_seq) - frame) % 3 + frame) + ] + + # Used for WC in info field for each variant + ref_codon_array = re.findall("".{3}"", ref_seq) + + gene_start = gene['start'] // 3 + gene_end = gene['end'] // 3 - 2 + + for ref_codon_pos in range(gene_start, gene_end): + ref_codon = ref_codon_array[ref_codon_pos] + + for aa in census.aminos_at(frame, ref_codon_pos, + CONFIDENT): + frequency = census.amino_frequency_at( + frame, ref_codon_pos, aa, CONFIDENT) + if frequency >= 0.01: + for codon in census.amino_to_codons_at( + frame, ref_codon_pos, + aa, CONFIDENT): + if codon != ref_codon.lower(): + mutation = CodonVariant.from_aacensus( + gene_key, + aa, codon, + census, + ref_codon_pos) + + var_collect.variants[gene_key][ + (ref_codon_pos*3 + frame)][ + codon] = mutation + return var_collect + + def to_csv_file(self, offset): + """"""""Build a string representation of our CodonVariant objects + (i.e. a csv file)."""""" + + report = (""#gene,nt position (gene),nt start position,"" + ""nt end position,ref codon,mutant codon,"" + ""ref AA,mutant AA,coverage,mutant frequency,"" + ""mutant type,NS count,S count\n"") + + for gene in self.variants: + for pos in self.variants[gene]: + for codon in self.variants[gene][pos]: + report += self.variants[gene][pos][ + codon].to_csv_entry(offset) + + return report[:-1] + + def report_dnds_values(self, ref_seq, offset): + report = ""#gene,pn,ps,pn_sites,ps_sites,dn/ds\n"" + + # Iterate through the variants to + # create a gene map and report on each gene + genes = defaultdict(lambda: defaultdict(lambda: + defaultdict(lambda: defaultdict(int)))) + + for gene in self.variants: + for pos in self.variants[gene]: + for codon in self.variants[gene][pos]: + variant = self.variants[gene][pos][codon] + + genes[gene]['start'] = variant.nt_start_gene + genes[gene]['end'] = variant.nt_end_gene + + if variant.ns_count > 0: + genes[gene][pos]['NS'][variant.ns_count] += ( + variant.mutant_freq/100.0) + if variant.s_count > 0: + genes[gene][pos]['S'][variant.s_count] += ( + variant.mutant_freq/100.0) + + for gene in genes: + s_sites = 0 + ns_sites = 0 + gene_seq = ref_seq[(genes[gene]['start'] - offset): + (genes[gene]['end'] - offset + 1)] + + pn = 0 + ps = 0 + + ns_ncod = 0 + s_ncod = 0 + + pn_ncod = 0 + ps_ncod = 0 + + for i in range(0, len(gene_seq)-1, 3): + codon = gene_seq[i:i+3] + aa = Seq(codon).translate()[0] + non_syn = 0 + + # synonymous sites only occur at 1st and 3rd pos in a codon + for j in range(0, 3): + for nt in ('a', 'c', 'g', 't'): + if nt.lower() != codon[j:j+1].lower(): + mod_codon = codon[:j] + nt + codon[j+1:] + mod_aa = Seq(mod_codon).translate()[0] + if mod_aa.upper() != aa.upper(): + non_syn += 1/3.0 + + ns_sites += non_syn + s_sites += 3-non_syn + + if non_syn > 0: + ns_ncod += 1 + if 3-non_syn > 0: + s_ncod += 1 + + pni = 0 + psi = 0 + + if 'NS' in genes[gene][i]: + for count in genes[gene][i]['NS']: + pni += genes[gene][i]['NS'][count] * ( + count/non_syn) + pn += pni + pn_ncod += 1 + + if 'S' in genes[gene][i]: + for count in genes[gene][i]['S']: + psi += genes[gene][i]['S'][count] * ( + count/(3-non_syn)) + ps += psi + ps_ncod += 1 + + if pn_ncod > 0 and ps_ncod > 0: + pn = pn/pn_ncod + ps = ps/ps_ncod + + if (1-(4*pn/3.0) > 0) and (1-(4*ps/3.0) > 0): + dn = -(3/4.0)*log(1-(4*pn/3.0)) + ds = -(3/4.0)*log(1-(4*ps/3.0)) + report += ""%s,%0.4f,%0.4f,%i,%i,%0.4f\n"" % \ + (gene, pn, ps, pn_ncod, ps_ncod, dn/ds) + else: + report += ""%s,%0.4f,%0.4f,%i,%i,N/A\n"" % \ + (gene, pn, ps, pn_ncod, ps_ncod) + + return report[:-1] +","Python" +"Microbiology","phac-nml/quasitools","quasitools/haplotype.py",".py","10203","471",""""""" +# ============================================================================= + +Copyright Government of Canada 2019 + +Written by: Eric Marinier, Public Health Agency of Canada, + National Microbiology Laboratory + +Funded by the National Micriobiology Laboratory and the Genome Canada / Alberta + Innovates Bio Solutions project ""Listeria Detection and Surveillance + using Next Generation Genomics"" + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +# ============================================================================= +"""""" + + +import numpy + +import quasitools.calculate as calculate +from quasitools.pileup import Pileup +GAP = '-' + + +class Haplotype: + """""" + # ======================================================================== + + HAPLOTYPE + + # ======================================================================== + """""" + + def __init__(self, sequence, count=1): + """""" + # ==================================================================== + + INIT + + # ==================================================================== + """""" + + self.sequence = sequence + self.count = count + + def __eq__(self, other): + """""" + # ==================================================================== + + EQUALS + + # ==================================================================== + """""" + + # Override the default Equals behavior: + + if isinstance(other, self.__class__): + return self.sequence == other.sequence + + return False + + def __ne__(self, other): + """""" + # ==================================================================== + + NOT EQUALS + + # ==================================================================== + """""" + # Override the default Unequal behavior + + if isinstance(other, self.__class__): + return self.sequence != other.sequence + + return False + + +def sort_haplotypes(haplotypes, consensus): + """""" + # ======================================================================== + + SORT HAPLOTYPES + + + PURPOSE + ------- + + Sorts a list of haplotypes according their Hamming distance from the + consensus sequence. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of haplotypes to sort. + + [String] consensus + The consensus sequence for the list of haplotypes. + + + RETURN + ------ + + [HAPLOTYPE LIST] + A list of sorted haplotypes, according to their number of mutations + from the consensus sequence of all the sequences. + + # ======================================================================== + """""" + + sorted_haplotypes = [] + + # a list of (Haplotype, Hamming distance) tuples. + tuple_list = [] + for haplotype in haplotypes: + + # creates a list of tuples that contains the haplotype and its Hamming + # distance. + tuple_list.append( + (haplotype, + calculate.hamming_distance( + haplotype.sequence, + consensus))) + + # Sort list in ascending order based on the Hamming distance. + sorted_list = \ + sorted(tuple_list, key=lambda items: items[1], reverse=False) + + # Iterates through sorted list placing the haplotype in + # sorted haplotypes. + sorted_haplotypes = [x[0] for x in sorted_list] + + return sorted_haplotypes + + +def build_consensus_from_haplotypes(haplotypes): + """""" + # ======================================================================== + + BUILD CONSENSUS FROM HAPLOTYPES + + + PURPOSE + ------- + + Builds a consensus from a list of Haplotype objects. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of haplotypes. + + + RETURN + ------ + + [String] consensus + The consensus sequence. + + # ======================================================================== + """""" + + pileup = build_pileup_from_haplotypes(haplotypes) + + consensus = pileup.build_consensus() + + return consensus + + +def build_pileup_from_haplotypes(haplotypes): + """""" + # ======================================================================== + + BUILD PILEUP FROM HAPLOTYPES + + + PURPOSE + ------- + + Creates a pileup from a list of Haplotype objects. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of haplotypes. + [BOOLEAN] [gaps] + Indicate whether or not there are gaps in our haplotype sequences. + + RETURN + ------ + + [PILEUP] [pileup] + A pilup object. + + # ======================================================================== + """""" + + pileup_list = [] + + if haplotypes: + + length = len(haplotypes[0].sequence) + + # Initialize empty dictionaries + for i in range(0, length): + pileup_list.append({}) + + for haplotype in haplotypes: + for i in range(0, length): + + base = haplotype.sequence[i] + + if pileup_list[i].get(base): + pileup_list[i][base] += haplotype.count + else: + pileup_list[i][base] = haplotype.count + + pileup = Pileup(pileup_list) + + return pileup + + +def build_distiance_matrix(haplotypes): + """""" + # ======================================================================== + + BUILD DISTANCE MATRIX + + + PURPOSE + ------- + + Builds a distance matrix of all the haplotypes. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of Haplotypes from which to build the distance matrix. + + + RETURN + ------ + + [2D ARRAY] + A distance matrix of the passed haplotypes. + + # ======================================================================== + """""" + + x = len(haplotypes) + + matrix = numpy.zeros(shape=(x, x)) + + for i in range(0, len(matrix)): + + for j in range(0, len(matrix)): + + matrix[i][j] = calculate_distance(haplotypes[i], haplotypes[j]) + + return matrix + + +def calculate_distance(haplotype1, haplotype2): + """""" + # ======================================================================== + + CALCULATE DISTANCE + + + PURPOSE + ------- + + Calculates the distance between two haplotypes. + + + INPUT + ----- + + [HAPLOTYPE] [haplotype1] + The first of two haplotypes to calculate the distance between. + + [HAPLOTYPE] [haplotype2] + The second of two haplotypes to calculate the distance between. + + + RETURN + ------ + + [FLOAT] + The genetic distance between the two passed haplotypes. + + # ======================================================================== + """""" + + hamming_distance = \ + calculate.hamming_distance(haplotype1.sequence, haplotype2.sequence) + genetic_distance = \ + float(hamming_distance) / float(len(haplotype1.sequence)) + + return genetic_distance + + +def calculate_total_clones(haplotypes): + """""" + # ======================================================================== + + CALCULATE TOTAL CLONES + + + PURPOSE + ------- + + Calculates the total number of clones accross multiple haplotypes. Note + that there may be multiple clones associated with each haplotype. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of Haplotypes from which to build the distance matrix. + + + RETURN + ------ + + [INT] + The total number of clones accross all the haplotypes in the list. + + # ======================================================================== + """""" + + total = 0 + + for haplotype in haplotypes: + + total += haplotype.count + + return total + + +def build_counts(haplotypes): + """""" + # ======================================================================== + + BUILD COUNTS + + + PURPOSE + ------- + + Builds the a list of the counts of each haplotype in a passed haplotype + list. + + Example: + + haplotype1.sequence = ""AAA"" + haplotype1.count = 3 + + haplotype1.sequence = ""CGC"" + haplotype1.count = 5 + + haplotype1.sequence = ""TCC"" + haplotype1.count = 1 + + haplotypes = [haplotype1, haplotype2, haplotype3] + + build_counts(haplotypes) -> [3, 5, 1] + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of Haplotypes. + + + RETURN + ------ + + [INT LIST] + A list of the counts of each haplotype, in the same order as the + original haplotype list. + + # ======================================================================== + """""" + + counts = [] + + for haplotype in haplotypes: + + count = haplotype.count + counts.append(count) + + return counts + + +def build_frequencies(haplotypes): + """""" + # ======================================================================== + + BUILD FREQUENCIES + + + PURPOSE + ------- + + Builds the a list of the frequencies of each haplotype in a passed + haplotype list. + + Example: + + haplotype1.sequence = ""AAA"" + haplotype1.count = 3 + + haplotype1.sequence = ""CGC"" + haplotype1.count = 5 + + haplotype1.sequence = ""TCC"" + haplotype1.count = 1 + + haplotypes = [haplotype1, haplotype2, haplotype3] + + build_counts(haplotypes) -> [3/9, 5/9, 1/9] + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + The list of Haplotypes. + + + RETURN + ------ + + [FLOAT LIST] + A list of the frequencies of each haplotype, in the same order as the + original haplotype list. + + # ======================================================================== + """""" + + counts = build_counts(haplotypes) + total = calculate_total_clones(haplotypes) + frequencies = [] + + for count in counts: + + frequency = float(count) / float(total) + frequencies.append(frequency) + + return frequencies +","Python" +"Microbiology","phac-nml/quasitools","quasitools/aa_census.py",".py","6794","173",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from Bio.Seq import Seq +from collections import defaultdict + +CONFIDENT = 0 +UNCONFIDENT = 1 + + +class AACensus(object): + def __init__(self, ref_file, mapped_read_collections, genes, frames): + self.ref_file = ref_file + self.mapped_read_collections = mapped_read_collections + self.genes = genes + self.positional_freq = defaultdict(lambda: defaultdict( + lambda: defaultdict(int))) + self.frames = frames + + self._build() + + def _build(self): + """"""Builds the amino acid census"""""" + + for frame in self.frames: + for mrc in self.mapped_read_collections: + # For each mapped_read translate in the frame, store the + # frequencies of the coded amino acid. + for name, mapped_read in mrc.mapped_reads.items(): + # Get the start of the first codon and the end of the last + # codon. + start = mapped_read.codon_start(frame) + end = mapped_read.codon_end(frame) + + confidence = {} + + read_wo_ins = mrc.reference.sub_seq( + start, start + (end - start)).lower() + + # Build up a base from our reference to apply our + # differences to (ignore insertions) + for pos in mapped_read.differences: + difference = (mapped_read.differences[pos])[:1] + + # If we are within the region of read that contains + # complete codons and we have a difference at this + # position, (the difference isn't equal to ""."") apply + # it. + if pos >= start and pos <= end and difference != '.': + + # If the difference is lower case, that means it + # was filtered out during variant calling + # and as such it is unconfident. + if difference != difference.upper(): + confidence[((pos - start) // 3)] = UNCONFIDENT + + read_wo_ins = read_wo_ins[:(pos - start)] + \ + difference.upper() + \ + read_wo_ins[(pos - start + 1):] + + # Translate the read + read_wo_ins = \ + read_wo_ins[:len(read_wo_ins) - (len(read_wo_ins) % 3)] + + read_aas = Seq(read_wo_ins.replace(""-"", ""N"")).translate() + + # Calculate the first position + start_aa = ((start) // 3) + + # Add our codons and aas to the aa census + for i in range(0, len(read_aas)): + # Get the confidence for this codon/aa + aa_confidence = CONFIDENT + if i in confidence: + aa_confidence = confidence[i] + + # Retrieve the codon which produces the aa (have to + # convert aa positions to codon positions) + codon = read_wo_ins[i*3:(i*3)+3] + aa = read_aas[i] + + # If we have a complete codon (codon doesn't contain a + # ""-""), add it to our frequencies. + if codon.find(""-"") == -1: + self.positional_freq[ + (frame, (start_aa + i), aa_confidence) + ][aa][codon] += 1 + else: + self.positional_freq[ + (frame, (start_aa + i), UNCONFIDENT) + ]['X'][codon] += 1 + + def aminos_at(self, frame, position, confidence): + """"""Returns a list of all the amino acids at the given position"""""" + return self.positional_freq[(frame, position, confidence)].keys() + + def amino_to_codons_at(self, frame, position, aa, confidence): + """"""Finds the codons that produce the amino acid at the given position + """""" + return self.positional_freq[(frame, position, confidence)][aa].keys() + + def codon_frequency_for_amino_at(self, frame, position, aa, confidence, + codon): + """"""Finds the frequency for a codon of an amino acid at the given + position. + """""" + + frequency = 0 + + if codon in self.positional_freq[(frame, position, confidence)][aa]: + frequency = self.positional_freq[ + (frame, position, confidence)][aa][codon] + + return frequency + + def amino_frequency_at(self, frame, position, aa, confidence): + """"""Finds the frequency for an amino acid at the given position"""""" + + frequency = 0 + + if aa in self.positional_freq[(frame, position, confidence)]: + for codon in self.positional_freq[ + (frame, position, confidence)][aa]: + + frequency += self.positional_freq[ + (frame, position, confidence)][aa][codon] + + return frequency + + def coverage_at(self, frame, position): + """"""Finds the coverage at a given position"""""" + + coverage = 0 + + for confidence in (CONFIDENT, UNCONFIDENT): + for aa in self.positional_freq[(frame, position, confidence)]: + coverage += \ + self.amino_frequency_at(frame, position, aa, confidence) + + return coverage + + def coverage(self, frames): + """"""Calculates the coverage and returns it as a string"""""" + # ""//"" specifies integer division for python 3 + length = len(self.mapped_read_collections[0].reference.seq) // 3 + + coverage_csv = """" + for frame in frames: + coverage_csv += ""frame: %i\n"" % frame + + for i in range(0, length): + local_coverage = self.coverage_at(frame, i) + coverage_csv += ""%s,%s\n"" % (i + 1, local_coverage) + + coverage_csv += ""\n"" + + return coverage_csv +","Python" +"Microbiology","phac-nml/quasitools","quasitools/pileup.py",".py","15297","538",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import numpy as np + +BASES = ['A', 'C', 'T', 'G'] +GAP = '-' + + +class Pileup_List(object): + """"""This class contains a list of Pileups."""""" + + def __init__(self, pileups): + """""" + Create a array of Pileup objects. + + INPUT: + [ARRAY OF PILEUPS] [pileups] - list of Pileup objects + RETURN: + [None] + POST: + Pileup list is constructed. + + """""" + self.pileups = pileups + self.left_pos_truncated = 0 + self.right_pos_truncated = 0 + + def all_have_coverage(self, position): + """""" + Determine if all Pileup objects have coverage at the present position. + + INPUT: + [INT] [position] - position in each pileup to check for coverage + + RETURN: + Returns BOOL true if all pileups have coverage at the position or + false if at least one pileup does not have coverage at the position + + POST: + None + + """""" + if any(not pileup.has_coverage(position) for pileup in self.pileups): + return False + else: + return True + # end if + + # end def + + def normalize_pileups(self): + """""" + Normalize pileups. + + Convert the read count for each base in each four-tuple + of bases (A, C, T, G) into a decimal proportion of the total read + counts for that four-tuple. The bounds are between 0 and 1. + This prevents large read counts for a single base from inflating + the cosine simularity calculation. + + INPUT: [None] + + RETURN: [None] + + POST: All Pileups in the Pileup_List are normalized. + + """""" + for pileup in self.pileups: + pileup.normalize_pileup() + # end def + + def get_num_left_positions_truncated(self): + """""" + Return number of left positions truncated. + + Returned value was saved the most recent time truncate_output or + remove_no_coverage was called. + + INPUT: [None] + + RETURN: [INT] [self.left_pos_truncated] + + POST: [None] + + """""" + return self.left_pos_truncated + + def get_num_right_positions_truncated(self): + """""" + Return number of right positions truncated. + + Returned value was saved the most recent time truncate_output or + remove_no_coverage was called. + + INPUT: [None] + + RETURN: [INT] [self.right_pos_truncated] + + POST: [None] + + """""" + return self.right_pos_truncated + + def get_pileups_as_array(self): + """""" + Return Pileup_List object as a two-dimensional array of dictionaries. + + INPUT: [None] + + RETURN: [ARRAY OF ARRAY OF DICTIONARIES] [pileup_list] + + POST: [None] + + """""" + return [pileup.get_pileup_as_array_of_dictionaries() + for pileup in self.pileups] + + def get_pileups_as_numerical_array(self): + """""" + Return Pileup_List object as a two-dimensional numerical array. + + INPUT: [None] + + RETURN: [ARRAY] [pileup_list] + + POST: [None] + + """""" + return [pileup.get_pileup_as_numerical_array() + for pileup in self.pileups] + + def get_pileup_length(self): + """""" + Get pileup length. + + This function returns the (single) length of all the pileups in the + list of pileups. The function assumes the lengths of all the pileups + are the same. + + INPUT: [None] + + RETURN: [INT] [len(self.pileups[0])] + + POST: [None] + + """""" + return len(self.pileups[0].get_pileup_as_array_of_dictionaries()) + + def select_pileup_range(self, curr_start, curr_end): + """""" + Ignore all regions of the pileup before curr_start and after curr_end. + + INPUT: + [int] [curr_start] - current start position. Must be zero-indexed + (between zero inclusive and the length of the Pileup exclusive). + [int] [curr_end] - current end position. Must be zero-indexed + (between zero inclusive and the length of the Pileup exclusive). + RETURN: + [None] + POST: + Positions before curr_start and after curr_end are ignored in the + pileup list. + + """""" + for pileup in self.pileups: + pileup.select_pileup_range(curr_start, curr_end) + + def remove_no_coverage(self): + """""" + Remove no coverage regions. + + Delete all regions of the pileup for all Pileup objects in the pileup + list where there is no coverage for at least one pileup (all four + bases - A, C, T, and G are absent). + + INPUT: + [None] + + RETURN: + [None] + + POST: + Sections of the pileup where there is no coverage for at least one + pileup are deleted from all pileups in the pileup list. + + """""" + # First truncate end positions to determine number of contiguous + # positions that were truncated on the left and the right. + self.truncate_output() + + deletion_list = [] + + if len(self.pileups) > 0 and self.get_pileup_length() > 0: + # iterate through every position in reference + for position in range(0, self.get_pileup_length()): + # add pos'n with empty coverage in pileup to deletion_list + if not self.all_have_coverage(position): + deletion_list.insert(0, position) + + for pileup in self.pileups: + pileup.remove_pileup_positions(deletion_list) + # end def + + def truncate_output(self): + """""" + Truncate output. + + Delete contiguous start and end regions of the pileup for all pileups + in the pileup list where there is no coverage (all four bases - A, C, + T, and G are absent). + + INPUT: + [None] + + RETURN: + [None] + + POST: + The pileups are truncated (sections of the pileup where there + is no coverage are deleted from all pileups in the pileup list. + If curr_start > curr_end the pileup_list is empty after truncation. + + """""" + self.left_pos_truncated, self.right_pos_truncated = 0, 0 + deletion_list_left, deletion_list_right, deletion_list = [], [], [] + num_pos = self.get_pileup_length() + + if len(self.pileups) > 0 and self.get_pileup_length() > 0: + # iterate through every position in reference + for left in range(0, num_pos): + if not self.all_have_coverage(left): + deletion_list_left.insert(0, left) + self.left_pos_truncated += 1 + else: + break + + for right in reversed(range(self.left_pos_truncated, num_pos)): + if not self.all_have_coverage(right): + deletion_list_right.append(right) + self.right_pos_truncated += 1 + else: + break + + # example: [7 6 5 3 2 1] = [7 6 5] + [3 2 1] + deletion_list = deletion_list_right + deletion_list_left + + for pileup in self.pileups: + pileup.remove_pileup_positions(deletion_list) + # end def + + +class Pileup(object): + """"""This class stores a pileup and utilities for modifying the pileup."""""" + + def __init__(self, pileup): + """""" + Create a Pileup. + + The object represents the Pileup of reads + mapped against a reference file. + + INPUT: + [ARRAY OF DICTIONARIES] [pileup] + + RETURN: + [None] + + POST: + Pileup is constructed. + + """""" + self.pileup = pileup + + def has_coverage(self, position): + """""" + Determine whether the Pileup has coverage at the present position. + + INPUT: + [INT] [position] - position in the Pileup to check for coverage + + RETURN: + Returns BOOL true if the Pileup has coverage at the position and + false otherwise. + + POST: + None + + """""" + curr_pos_list = [self.pileup[position].get(base, 0) for base in BASES] + + if (np.sum(curr_pos_list) == 0 or self.pileup[position] == {}): + return False + else: + return True + # end if + + # end def + + def normalize_pileup(self): + """""" + Normalize pileup. + + This function converts the read count for each base in each four-tuple + of bases (A, C, T, G) into a decimal proportion of the total read + counts for that four-tuple. The bounds are between 0 and 1 inclusive. + This prevents large read counts for a base from inflating + the cosine simularity calculation. + + INPUT: [None] + + RETURN: [None] + + POST: The Pileup's values are normalized. + + """""" + new_list = [] + for i in range(0, len(self.pileup)): + curr_pos = [self.pileup[i].get(base, 0) for base in BASES] + total = float(np.sum(curr_pos)) + items = self.pileup[i].items() + + # normalize the data for all dictionaries in the pileup + if total > 0: + new_list.append( + {key: (float(val) / total) for (key, val) in items + if key is not GAP}) + else: + new_list.append( + {key: 0 for (key, value) in items if key is not GAP}) + # end if + self.pileup = new_list + # end def + + def get_pileup_as_array_of_dictionaries(self): + """""" + Return the pileup in the Pileup object as an array of dictionaries. + + INPUT: [None] + + RETURN: [ARRAY OF DICTIONARIES] [pileup] + + POST: [None] + + """""" + return self.pileup + + def get_pileup_as_numerical_array(self): + """""" + Return the pileup in the Pileup object as a numerical 1D array. + + INPUT: [None] + + RETURN: [ARRAY] [pileup] + + POST: [None] + + """""" + # create a list of the read counts of each base at each position in the + # pileup, zero if the base is not in the dictionary at the position + first = 0 + last = len(self.pileup) + numerical_array = [self.pileup[dict].get(base, 0) + for dict in range(first, last) for base in BASES] + return numerical_array + + def remove_pileup_positions(self, deletion_list): + """""" + Remove pileup positions. + + Delete positions in the Pileup specified in deletion_list, an array + of integers sorted in descending order. + + INPUT: + [ARRAY] [deletion_list] - list of positions to delete in descending + order of indices. + + RETURN: + [None] + + POST: + The specified positions in deletion_list have been removed from + the Pileup. + + """""" + for position in deletion_list: + del self.pileup[position] + # end for + + def select_pileup_range(self, curr_start, curr_end): + """""" + Ignore all regions of the Pileup before curr_start and after curr_end. + + INPUT: + [int] [curr_start] - current start position. Must be zero-indexed + (between zero inclusive and the length of the Pileup exclusive). + [int] [curr_end] - current end position. Must be zero-indexed + (between zero inclusive and the length of the Pileup exclusive). + + RETURN: + [None] + + POST: + Positions before curr_start and after curr_end are ignored in the + Pileup. + + """""" + self.pileup = self.pileup[curr_start:curr_end + 1] + + def build_consensus(self): + """""" + # ==================================================================== + + BUILD CONSENSUS + + + PURPOSE + ------- + + Builds the consensus sequence of the pileup. + + + RETURN + ------ + + [STRING] + The consensus sequence of the pileup. + + # ==================================================================== + """""" + + consensus = """" + + for position in self.pileup: + + """""" + We want to sort by values largest to smallest and then keys + keys smallest to largest if we have a tie in value + position.items(), use (-x[1], x[0]) as a proxy value to be + sorted. x is in the form of (key, value), therefore + (-x[1], x[0]) yields (value, key). The negative '-' sign in front + of the value tuple element designates sorting values + from descending order (i.e largest to smallest). keys are sorted + in ascending order. + """""" + sorted_position = \ + sorted(position.items(), key=lambda x: (-x[1], x[0])) + base = sorted_position[0][0] + consensus = consensus + str(base) + + return consensus + + def count_unique_mutations(self): + """""" + # ==================================================================== + + COUNT UNIQUE MUTATIONS + + + PURPOSE + ------- + + Counts the number of unique mutations in the pileup. There should be + no gaps in the pileup when using this function. + + + RETURN + ------ + + [INT] + The number of unique mutations. + + # ==================================================================== + """""" + + # !!This assumes there are no gaps in the passed pileup!! + + # We need the number mutations at all mutation sites. + # These are positions in the pileup with at least 1 disagreement. + unique_mutations = 0 + + for position in self.pileup: + + unique_mutations += len(position) - 1 + # Number of different bases at position. + + return unique_mutations + + def count_polymorphic_sites(self): + """""" + # ==================================================================== + + COUNT POLYMOPRHIC SITES + + + PURPOSE + ------- + + Counts the number of polymorphic sites in the pileup. + + + RETURN + ------ + + [INT] + The number of polymporphic sites in the pileup. + + # ==================================================================== + """""" + + # !!This assumes there are no gaps in the passed pileup!! + + # We need the number of polymorphic sites. + # These are positions in the pileup with at least 1 disagreement. + polymorphic_sites = 0 + + for position in self.pileup: + + if len(position) > 1: + + polymorphic_sites += 1 + + return polymorphic_sites +","Python" +"Microbiology","phac-nml/quasitools","quasitools/reference.py",".py","1048","35",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + + +class Reference(object): + def __init__(self, name, seq): + self.name = name + self.seq = seq + + def sub_seq(self, start, end): + """"""Returns a portion of the sequence + + >>> r = Reference('gattaca', 'gattaca') + >>> print(r.sub_seq(1,5)) + attac + >>> print(r.sub_seq(1,1)) + a + """""" + return self.seq[start:end+1] +","Python" +"Microbiology","phac-nml/quasitools","quasitools/distance.py",".py","5112","168",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import numpy as np + +from scipy.spatial.distance import pdist +from scipy.spatial.distance import squareform +from scipy.spatial.distance import cosine + + +class DistanceMatrix(object): + """"""This class performs distance comparison on pileups."""""" + + def __init__(self, pileups, file_list): + """""" + Intialize DistanceMatrix object. + + INPUT: + [ARRAY] [pileups] - Two dimensional numerical array that represents + a list of pileups. Every row represents a pileup and every four + values in each row represents the base counts for a particular + position for the pileup. + + [FILE LOCATION TUPLE] [file_list] - files names which represent a + pileup + """""" + self.pileups = pileups + self.file_list = file_list + # end def + + def get_distance_matrix(self): + """""" + Calculate angular cosine distance between viral quasispecies. + + The viral quasispecies are represented by the pileups. + + Angular Cosine Distance = 2 * ACOS(similarity) / PI + + INPUT: + [None] + + RETURN: + Returns a pairwise matrix containing the angular cosine distance + between all viral quasispecies is returned. The first row and first + column of the distance matrix contain labels for which quasispecies + are to be compared in each cell corresponding to the row and column + + POST: + The internal pileup object is not changed by this function. + + """""" + matrix = self.get_similarity_matrix() + new_matrix = 2 * np.arccos(matrix) / np.pi + return new_matrix.tolist() + # end def + + def get_similarity_matrix_as_csv(self): + """""" + Convert a 2D array to a csv-formatted string. + + The 2D array is a cosine similarity matrix. + + Print out 8 decimal places. + + INPUT: + [None] + + RETURN: + [STRING] [csvOut] CSV representation of a pairwise similarity + matrix + """""" + matrix = self.get_similarity_matrix() + return self.__get_matrix_as_csv(matrix) + + def get_distance_matrix_as_csv(self): + """""" + Convert a 2D array to a csv-formatted string. + + The 2D array is an angular cosine distance matrix. + + Print out 8 decimal places. + + INPUT: + [None] + + RETURN: + [STRING] [csvOut] CSV representation of a pairwise similarity + matrix + """""" + matrix = self.get_distance_matrix() + return self.__get_matrix_as_csv(matrix) + + def __get_matrix_as_csv(self, matrix): + """""" + Convert a 2D array to a csv-formatted string. + + Print out 8 decimal places. + + INPUT: + [ARRAY] [matrix] - 2D array (cosine similarity matrix) + + RETURN: + [STRING] [csvOut] CSV representation of a pairwise similarity + matrix + + POST: + [None] + + """""" + # (distMatrix[i+1]).insert(0, file_list[i]) + # convert from 2d array to csv formatted string + files = [file for file in list(self.file_list)] + csvOut = 'Quasispecies,' + ','.join(files) + + for row in range(0, len(matrix)): + csvOut += ""\n"" + currElements = ['%.08f' % element for element in matrix[row]] + csvOut += ','.join([self.file_list[row]] + currElements) + # end for + + return csvOut + # end def + + def get_similarity_matrix(self): + """""" + Calculate cosine similarity between viral quasispecies. + + The viral quasispecies are represented by the pileups. + + Cosine similarity = (u * v) / ( ||u|| * ||v|| ) + + INPUT: + [None] + + RETURN: + Returns a pairwise matrix containing the cosine similarity function + between all viral quasispecies is returned. The 1st row and column + of the similarity matrix contain labels for which quasispecies + are to be compared in each cell corresponding to the row and column + + POST: + The internal pileup object is not changed by this function. + + """""" + baseList = np.array(self.pileups) + + # create distance matrix for csv file + simi_matrix = squareform(1 - pdist(baseList, cosine)) + di = np.diag_indices(len(simi_matrix)) + simi_matrix[di] = 1.0 + simi_matrix = simi_matrix.tolist() + + return simi_matrix +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_distance.py",".py","10785","257",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +from quasitools.distance import DistanceMatrix +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import parse_pileup_list_from_bam + + +@click.command('distance', short_help='Calculate the evolutionary distance ' + 'between viral quasispecies using angular cosine distance.') +@click.argument('reference', nargs=1, required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('bam', nargs=-1, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-n/-dn', '--normalize/--dont_normalize', default=True, + help=""Normalize read count data so that the read counts per "" + + ""4-tuple (A, C, T, G) sum to one."") +@click.option('-od/-os', '--output_distance/--output_similarity', default=True, + help=""Output an angular distance matrix (by default), or "" + + ""output a cosine similarity matrix (cosine similarity is not a"" + + "" metric)"") +@click.option('-s', '--startpos', type=int, help=""Set the start base "" + + ""position of the reference to use in the distance or "" + + ""similarity calculation. Start position is one-indexed. "" + + "" I.e. it must be between one and the total length of the "" + + ""reference sequence(s), inclusive."") +@click.option('-e', '--endpos', type=int, help=""Set the end base position"" + + "" of the reference to use in the distance or similarity "" + ""calculation. End position is one-indexed. "" + + "" I.e. it must be between one and the total length of the "" + + ""reference sequence(s), inclusive."") +@click.option('-o', '--output', type=click.File('w'), help=""Output the "" + + ""quasispecies distance or similarity matrix in CSV format in a"" + + "" file."") +@click.option('-t', '--truncate', 'no_coverage', flag_value='truncate', + help=""Ignore contiguous start and end pileup"" + + "" regions with no coverage."") +@click.option('-r', '--remove_no_coverage', 'no_coverage', + default=True, flag_value='remove_no_coverage', + help=""Ignore all pileup regions with no coverage."") +@click.option('-k', '--keep_no_coverage', 'no_coverage', + flag_value='keep_no_coverage', + help=""Do not ignore pileup regions with no coverage."") +@click.pass_context +def cli(ctx, reference, bam, normalize, output_distance, startpos, endpos, + output, no_coverage): + """"""Quasitools distance produces a measure of evolutionary distance [0 - 1] + between quasispecies, computed using the angular cosine distance + function defined below. + + Cosine similarity = (u * v) / ( ||u|| * ||v|| ) + + Angular Cosine Distance = 2 * ACOS(Cosine similarity) / PI + + The tool outputs by default an angular cosine distance matrix. + Use the flag defined below to instead output a similarity matrix. + + By default the data is normalized and all regions of the pileup with + no coverage are removed. + + It is possible to truncate only the contiguous start and end regions of + the pileup that have no coverage, or keep all no coverage regions in + the pileup. + + Normalization is done dividing base read counts (A, C, T, G) inside + every 4-tuple by the sum of the read counts inside the same tuple. + The normalized read counts inside each 4-tuple sum to one."""""" + + click.echo(""Using file %s as reference"" % (reference)) + for file in bam: + click.echo(""Reading input from file(s) %s"" % (file)) + + dist(ctx, reference, bam, normalize, output_distance, startpos, endpos, + output, no_coverage) + + click.echo(""Complete!"") + + +def dist(ctx, reference, bam, normalize, output_distance, startpos, endpos, + output, no_coverage): + + """""" + dist - Performs the main part of the program + + INPUT: + [CONTEXT] [ctx] + [FASTA FILE LOCATION] [reference] + [LIST (BAM FILE LOCATION)] [bam] + [BOOL] [normalize/dont_normalize] + [BOOL] [output_distance/output_similarity] + [INT] [startpos] + [INT] [endpos] + [STRING] [output] + Output the CSV-formatted matrix output in a file + instead of in the terminal. + [STRING] [truncate/remove_no_coverage/keep_no_coverage] + Options to truncate low-coverage regions on the ends of the pileup, + ignore all low coverage regions, or keep all low coverage regions + + RETURN: + None. + + POST: + The distance matrix is printed out unless an error message was raised. + + """""" + + if len(bam) < 2: + raise click.UsageError(""At least two bam file locations are required"" + + "" to perform quasispecies distance comparison."") + # Build the reference object. + references = parse_references_from_fasta(reference) + + pileups = parse_pileup_list_from_bam(references, bam) + + if pileups.get_pileup_length() == 0: + raise click.UsageError(""Empty pileup was produced from BAM files. "" + + ""Halting program"") + + click.echo(""Constructed pileup from reference."") + # click.echo the number of positions in pileup + click.echo(""The pileup covers %d positions before modifications."" % + pileups.get_pileup_length()) + + if startpos is None: + startpos = 1 + if endpos is None: + endpos = pileups.get_pileup_length() + + click.echo(""The start position is %d."" % startpos) + click.echo(""The end position is %d."" % endpos) + + # indicate if the start or end position is < 1 or a priori invalid + if int(startpos) < 1: + raise click.UsageError(""Start position must be >= 1."") + if int(endpos) < 1: + raise click.UsageError(""End position must be >= 1."") + if int(startpos) > int(endpos): + raise click.UsageError(""Start position must be <= end position."") + + # indicate whether the user-specified start and end position is out + # of bounds (comparing to actual number of positions in pileup) + if startpos > pileups.get_pileup_length(): + raise click.UsageError(""Start position must be less than or"" + + "" equal to the number of nucleotide base "" + + ""positions in pileup (%s)."" + % pileups.get_pileup_length()) + if endpos > pileups.get_pileup_length(): + raise click.UsageError(""End position must be less than or equal to "" + + ""the number of nucleotide base positions in "" + + ""pileup (%s)."" % pileups.get_pileup_length()) + + # we convert the start and end positions from one-based indexing to + # zero-based indexing which is expected by distance.py and pileup.py + startpos -= 1 + endpos -= 1 + + # if there is no errors so far, proceed with running program + modified = modify_pileups(ctx, normalize, startpos, endpos, no_coverage, + pileups) + + if (no_coverage != 'keep_no_coverage') and (len(modified) == 0): + raise click.UsageError(""Entire pileup was truncated due to "" + + ""lack of coverage. Halting program"") + + dist = DistanceMatrix(modified, bam) + + if output_distance: + click.echo(""Outputting an angular cosine distance matrix."") + if output: + output.write(dist.get_distance_matrix_as_csv()) + else: + click.echo(dist.get_distance_matrix_as_csv()) + + else: + click.echo(""Outputting a cosine similarity matrix."") + if output: + output.write(dist.get_similarity_matrix_as_csv()) + else: + click.echo(dist.get_similarity_matrix_as_csv()) +# end def + + +def modify_pileups(ctx, normalize, startpos, endpos, no_coverage, pileups): + + """""" + modify_pileups - Performs normalization, truncation and/or selecting the + range of the pileup, if these options are enabled. + + INPUT: + [CONTEXT] [ctx] + [BOOL] [normalize/dont_normalize] + [INT] [startpos] + [INT] [endpos] + [STRING] [no_coverage] [truncate/remove_no_coverage/keep_no_coverage] + Options to truncate low-coverage regions on the ends of the pileup, + ignore all low coverage regions, or keep all low coverage regions + [PILEUP_LIST] [pileups] + The pileups to be modified + + RETURN: + [2D ARRAY] [pileups] + The modified pileups, returned as a two-dimensional array. + + POST: + The calling function, dist, will use the 2D array that is returned. + + """""" + + startpos = int(startpos) + endpos = int(endpos) + pileups.select_pileup_range(startpos, endpos) + + # converting startpos and endpos back to one-based indexing for click.echo + click.echo((""The pileup covers %s positions after selecting "" + + ""range between original pileup positions %d and %d."") + % (pileups.get_pileup_length(), startpos + 1, endpos + 1)) + + if normalize: + pileups.normalize_pileups() + + old_length = pileups.get_pileup_length() + + if no_coverage != 'keep_no_coverage': + if no_coverage == 'truncate': + pileups.truncate_output() + click.echo(""Truncating positions with no coverage that "" + + ""are contiguous with the start or end "" + + ""position of the pileup only."") + elif no_coverage == 'remove_no_coverage': + pileups.remove_no_coverage() + click.echo(""Truncating all positions with no coverage."") + + click.echo(""%d positions were truncated on the left."" % + pileups.get_num_left_positions_truncated()) + click.echo(""%d positions were truncated on the right."" % + pileups.get_num_right_positions_truncated()) + click.echo(""%d positions were removed in total from the pileup."" % + (old_length - pileups.get_pileup_length())) + # end if + return pileups.get_pileups_as_numerical_array() +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_complexity.py",".py","27732","1108",""""""" +Copyright Government of Canada 2019 + +Written by: Eric Marinier and Ahmed Kidwai, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +__version__ = '0.1.1' + +import click +import math +import csv +import sys + +import quasitools.calculate as calculate +import quasitools.haplotype as haplotype +import quasitools.constants.complexity_constants as constant +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import \ + parse_haplotypes_from_bam, \ + parse_haplotypes_from_fasta + +# Here we are setting up a nesting of Click commands. This allows us to run +# quasitools complexity only when grouped with a subcommand (BAM or FASTA) +@click.group(invoke_without_command=False) +@click.pass_context +def cli(ctx): + ''' + Reports the per-amplicon (fasta) or k-mer complexity of the pileup, + for each k-mer position in the reference complexity (bam and reference) + of a quasispecies using several measures outlined in the following work: + + Gregori, Josep, et al. ""Viral quasispecies complexity measures."" + Virology 493 (2016): 227-237. + ''' + + pass + +# Subcommand for when a multi-alligned fasta file is provided +# When the fasta subcommand is called we will obtain complexity +# report of per-amplicon complexity. + + +@cli.command( + 'fasta', short_help='Calculates various quasispecies complexity ' + + 'measures on a multiple aligned FASTA file.') +@click.argument('fasta_location', nargs=1, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-o', '--output_location', type=click.Path(exists=False), + help=""Output the "" + + ""quasispecies complexity in CSV format to the specified file."") +def fasta(fasta_location, output_location): + ''' + Reports the per-amplicon (fasta) or k-mer complexity of the pileup, + for each k-mer position in the reference complexity (bam and reference) + of a quasispecies using several measures outlined in the following work: + + Gregori, Josep, et al. ""Viral quasispecies complexity measures."" + Virology 493 (2016): 227-237. + ''' + + """""" + # ======================================================================== + + FASTA COMPLEXITY + + + PURPOSE + ------- + + Creates a report of k-mer complexity of the pileup, for each k-mer position + in the reference. + + INPUT + ----- + + [(FASTA) FILE LOCATION] [fasta_location] + The file location of an aligned FASTA file for which to calculate the + complexity measures. + [(OUTPUT) FILE LOCATION] [output_location] + The location of the output file. + + RETURN + ------ + + [NONE] + + + POST + ---- + + The complexity computation will be completed and the results will be + stored in CSV file. + + # ======================================================================== + """""" + + haplotypes = parse_haplotypes_from_fasta(fasta_location) + + measurements = measure_complexity(haplotypes) + + # if the output_location is specificed open it as complexit_file, if not + # specified, complexity_file is set as sys.stdout. + with open(output_location, 'w') if output_location else sys.stdout as \ + complexity_file: + measurement_to_csv([measurements], complexity_file) + + +# NGS Data from BAM and its corresponding reference file. +# When the bam subcommand is called we will produce a report of +# k-mer complexity of the pileup, for each k-mer position in the reference +@cli.command( + 'bam', short_help=""Calculates various quasispecies complexity "" + + ""measures on next generation sequenced data from a BAM file "" + + ""and it's corresponding reference file."") +@click.argument('reference_location', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('bam_location', nargs=1, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('k') +@click.option( + '-f', + '--haplotype_filter', + type=float, + default=0, + help="" User defined "" + + ""A filter between 0 and 100, inclusive. Abundances"" + + ""below the filter size will be removed from each positional"" + + ""list. The default is 0 (i.e. no filtering)."") +@click.option('-o', '--output_location', type=click.Path(exists=False), + help=""Output the "" + + ""quasispecies complexity in CSV format to the specified file."") +def bam(reference_location, bam_location, k, + haplotype_filter, output_location): + ''' + Reports the per-amplicon (fasta) or k-mer complexity of the pileup, + for each k-mer position in the reference complexity (bam and reference) + of a quasispecies using several measures outlined in the following work: + + Gregori, Josep, et al. ""Viral quasispecies complexity measures."" + Virology 493 (2016): 227-237. + ''' + + """""" + # ======================================================================== + + BAM COMPLEXITY + + + PURPOSE + ------- + + Create a report of k-mer complexity of the pileup, for each k-mer position + in the reference. + + + INPUT + ----- + + [(BAM) FILE LOCATION] [bam_location] + The file location of a bam file. + [(REFERENCE) FILE LOCATION] [reference_location] + The file location of the reference file. + [INT] k + Provides the sequence length for our reads from a given starting + position. + [FLOAT] haplotype_filter: + User defined filter between 0 and 100, haplotypes under the filter + size will be removed from each positional list. Default is set to + 0 (i.e it will not filter). + + [(OUTPUT) FILE LOCATION] [output_location] + The location of the output file. + + RETURN + ------ + + [NONE] + + + POST + ---- + + The complexity computation will be completed and the results will be stored + in CSV file or std.out. + + # ======================================================================== + """""" + k = int(k) + + references = parse_references_from_fasta(reference_location) + # A list where each position contains a list of haplotypes of length k + # starting at that position in the reference. + haplotype_list = parse_haplotypes_from_bam( + references, reference_location, bam_location, k) + + measurements_list = [] + + for i in range(len(haplotype_list)): + + haplotypes = haplotype_list[i] + # Remove haplotypes below threshold. + + # Get total number of haplotypes for each position. + total_haplotypes = haplotype.calculate_total_clones(haplotypes) + + # Add haplotypes within threshold to new haplotypes list + haplotypes_within_filter = [ + hap for hap in haplotypes if ( + float( + hap.count) / + float(total_haplotypes) * + 100) >= haplotype_filter] + + measurements = measure_complexity(haplotypes_within_filter) + measurements_list.append(measurements) + + # if the output_location is specificed open it as complexit_file, if not + # specified, complexity_file is set as sys.stdout. + with open(output_location, 'w') if output_location else sys.stdout as \ + complexity_file: + measurement_to_csv(measurements_list, complexity_file) + + +def measure_complexity(haplotypes): + """""""" + #======================================================================== + + MEASURE COMPLEXITY + + PURPOSE + ------- + + Calculate a number of complexity measurements for Haplotype objects. + + + INPUT + ------- + + [HAPLOTYPE LIST] [haplotypes] + - An unsorted list of Haplotype objects. + + + RETURN + ------- + + [LIST] [measurements] + - A list of complexity measurements. List position is specified by + constant values defined in constants/complexity_constanty.py + + #======================================================================== + """""" + + # Initialize measurements list to length of the measurements name + # dictionary. + + measurements = [constant.UNDEFINED for x in range( + len(constant.MEASUREMENTS_NAMES))] + + # If no haplotypes we will return measurements as its initialized state. + if not haplotypes: + return measurements + + haplotype_consensus = haplotype.build_consensus_from_haplotypes( + haplotypes) + sorted_haplotypes = haplotype.sort_haplotypes( + haplotypes, haplotype_consensus) + + pileup = haplotype.build_pileup_from_haplotypes(sorted_haplotypes) + + distance_matrix = haplotype.build_distiance_matrix(sorted_haplotypes) + counts = haplotype.build_counts(sorted_haplotypes) + frequencies = haplotype.build_frequencies(sorted_haplotypes) + + # Set the Incidence - Entity Level # + + measurements[constant.NUMBER_OF_HAPLOTYPES] = \ + get_number_of_haplotypes(sorted_haplotypes) + + measurements[constant.HAPLOTYPE_POPULATION] = \ + get_haplotype_population(counts) + + measurements[constant.NUMBER_OF_POLYMORPHIC_SITES] = \ + get_number_of_polymorphic_sites(pileup) + + measurements[constant.NUMBER_OF_MUTATIONS] = get_number_of_mutations( + pileup) + + # Set the Abundance - Molecular Level: # + + shannon_entropy = get_shannon_entropy(sorted_haplotypes, frequencies) + + measurements[constant.SHANNON_ENTROPY_NUMBER] = shannon_entropy + + measurements[constant.SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_N] = \ + get_shannon_entropy_normalized_to_n( + sorted_haplotypes, shannon_entropy) + + measurements[constant.SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_H] = \ + get_shannon_entropy_normalized_to_h( + sorted_haplotypes, shannon_entropy) + + measurements[constant.SIMPSON_INDEX] = \ + get_simpson_index(frequencies) + + measurements[constant.GINI_SIMPSON_INDEX] = \ + get_gini_simpson_index(frequencies) + + hill_numbers_list = get_hill_numbers( + frequencies, constant.HILL_NUMBER_LENGTH) + + ''' + We iterate through the number of elements in the Hill number list, + at each iteration we place the Hill number at element i into measurements + at element HILL_NUMBER_0+i. + ''' + for i in range(len(hill_numbers_list)): + measurements[constant.HILL_NUMBER_0 + i] = (hill_numbers_list[i]) + + # Functional Incidence - Entity Level # + + measurements[constant.MINIMUM_MUTATION_FREQUENCY] = \ + get_minimum_mutation_frequency( + sorted_haplotypes, pileup) + + measurements[constant.MUTATION_FREQUENCY] = get_mutation_frequency( + distance_matrix) + + measurements[constant.FUNCTIONAL_ATTRIBUTE_DIVERSITY] = \ + get_FAD(distance_matrix) + + measurements[constant.SAMPLE_NUCLEOTIDE_DIVERSITY_ENTITY] = \ + get_sample_nucleotide_diversity_entity( + distance_matrix, frequencies) + + # Functional Abundance - Molecular Level # + + measurements[constant.MAXIMUM_MUTATION_FREQUENCY] = \ + get_maximum_mutation_frequency( + counts, distance_matrix, frequencies) + + measurements[constant.POPULATION_NUCLEOTIDE_DIVERSITY] = \ + get_population_nucleotide_diversity( + distance_matrix, frequencies) + + # Other # + + measurements[constant.SAMPLE_NUCLEOTIDE_DIVERSITY] = \ + get_sample_nucleotide_diversity( + distance_matrix, frequencies, sorted_haplotypes) + + return measurements + + +def get_haplotype_population(counts): + """""" + # ======================================================================== + + GET HAPLOTYPE POPULATION + + + PURPOSE + ------- + + Returns the population of haplotypes. + + + INPUT + ----- + + [INT LIST] [counts] + A haplotype counts, from the counts of the most abundant to the counts + of the least abundant haplotype. + + + RETURN + ------ + + [INT] + The haplotype population which is defined as the number of + unique haplotypes. + + # ======================================================================== + """""" + + return sum(counts) + + +def get_sample_nucleotide_diversity( + distance_matrix, + frequencies, + haplotypes): + """""" + # ======================================================================== + + GET SAMPLE NUCLEOTIDE DIVERSITY + + + PURPOSE + ------- + + Reports the sample nucleotide diversity. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of Haplotype objects. + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the haplotypes. + + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the haplotypes. + + This is expected to be calculated in a similar manner as: + haplotype.build_distiance_matrix(haplotypes) + + RETURN + ------ + + [FLOAT] [snd] + The sample nucleotide diversity. + + # ======================================================================== + """""" + + N = haplotype.calculate_total_clones(haplotypes) + H = len(frequencies) + P = frequencies + D = distance_matrix + + if N > 1: + snd = calculate.sample_nucleotide_diversity(N, H, P, D) + else: + snd = constant.UNDEFINED + + return snd + + +def get_population_nucleotide_diversity( + distance_matrix, frequencies): + """""" + # ======================================================================== + + GET POPULATION NUCLEOTIDE DIVERSITY + + PURPOSE + ------- + Returns the population nucleotide diversity. + + + INPUT + ----- + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the haplotypes. + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [pnd] + The population nucleotide diversity. + + # ======================================================================== + """""" + + H = len(frequencies) + P = frequencies + D = distance_matrix + + pnd = calculate.population_nucleotide_diversity(H, P, D) + + return pnd + + +def get_maximum_mutation_frequency( + counts, + distance_matrix, + frequencies): + """""" + # ======================================================================== + + GET MAXMIMUM MUTATION FREQUENCY + + PURPOSE + ------- + + Returns the maximum mutation frequency of the haplotypes. + + + INPUT + ----- + + [INT LIST] [counts] + A haplotype counts, from the counts of the most abundant to the counts + of the least abundant haplotype. + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the sorted haplotypes. + + This is expected to be calculated in a similar manner as: + haplotype.build_distiance_matrix(haplotypes) + + + RETURN + ------ + + [FLOAT] [maximum_mutation_frequency] + The maximum mutation frequency. + + # ======================================================================== + """""" + + H = len(counts) + F = frequencies + D = distance_matrix + + maximum_mutation_frequency = calculate.maximum_mutation_frequency(H, F, D) + + return maximum_mutation_frequency + + +def get_sample_nucleotide_diversity_entity( + distance_matrix, frequencies): + """""" + # ======================================================================== + + GET SAMPLE NUCLEOTIDE DIVERSITY (ENTITY LEVEL) + + + PURPOSE + ------- + + Returns the entity-level sample nucleotide diversity. + + + INPUT + ----- + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the haplotypes. + + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the sorted haplotypes. + + This is expected to be calculated in a similar manner as: + haplotype.build_distiance_matrix(haplotypes) + + + RETURN + ------ + + [FLOAT] snde + Sample nucleotide diversity entity. + + # ======================================================================== + """""" + + H = len(frequencies) + D = distance_matrix + + if H > 1: + snde = calculate.sample_nucleotide_diversity_entity(H, D) + else: + snde = constant.UNDEFINED + + return snde + + +def get_FAD(distance_matrix): + """""" + # ======================================================================== + + REPORT FUNCTIONAL ATTRIBUTE DIVERSITY + + + PURPOSE + ------- + + Reports the functional attribute diversity. + + + INPUT + ----- + + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the sorted haplotypes. + + This is expected to be calculated in a similar manner as: + haplotype.build_distiance_matrix(haplotypes) + + + RETURN + ------ + + [FLOAT] [fad] + The functional attribute diversity. + + # ======================================================================== + """""" + + H = len(distance_matrix) + D = distance_matrix + + fad = calculate.FAD(H, D) + + return fad + + +def get_mutation_frequency(distance_matrix): + """""" + # ======================================================================== + + GET MUTATION FREQUENCY + + + PURPOSE + ------- + + Reports the mutation frequency of the haplotypes. + + + INPUT + ----- + + [2D ARRAY] [distance_matrix] + A two dimensional array, representing the distance matrix of distances + between the sorted haplotypes. + + This is expected to be calculated in a similar manner as: + haplotype.build_distiance_matrix(haplotypes) + + + RETURN + ------ + + [FLOAT] [mutation_frequency] + The mutation frequency. + + # ======================================================================== + """""" + + H = len(distance_matrix) + D = distance_matrix + mutation_frequency = calculate.mutation_frequency(H, D) + + return mutation_frequency + + +def get_minimum_mutation_frequency(haplotypes, pileup): + """""" + # ======================================================================== + + GET MINIMUM MUTATION FREQUENCY + + + PURPOSE + ------- + + Returns the minimum mutation frequency of the sorted haplotypes. + + + INPUT + ----- + + [PILEUP] [pileup] + A Pileup object, which represents the pileup of aligned reads. + + [HAPLOTYPE LIST] [haplotypes] + A list of sorted Haplotype objects. + + + RETURN + ------ + + [FLOAT][minimum_mutation_frequency] + The minimum mutation frequency. + + # ======================================================================== + """""" + + M = pileup.count_unique_mutations() + N = haplotype.calculate_total_clones(haplotypes) + a = len(haplotypes[0].sequence) + + minimum_mutation_frequency = calculate.minimum_mutation_frequency(M, N, a) + + return minimum_mutation_frequency + + +def get_number_of_haplotypes(haplotypes): + """""" + # ======================================================================== + + GET NUMBER OF HAPLOTYPES + + + PURPOSE + ------- + + Returns the number of (unique) Haplotype objects. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of sorted Haplotype objects. + + + RETURN + ------ + + [INT] [len(haplotypes)] + The unique number of Haplotype objects. + + # ======================================================================== + """""" + + return len(haplotypes) + + +def get_number_of_polymorphic_sites(pileup): + """""" + # ======================================================================== + + GET NUMBER OF POLYMORPHIC SITES + + + PURPOSE + ------- + + Returns the number of polymorphic sites. + + + INPUT + ----- + + [PILEUP] [pileup] + A Pileup object, which represents the pileup of aligned reads. + + + RETURN + ------ + + [INT] (pileup.count_polymorphic_sites()) + The number of polymorphic sites in pileuip. + + # ======================================================================== + """""" + + return pileup.count_polymorphic_sites() + + +def get_number_of_mutations(pileup): + """""" + # ======================================================================== + + GET NUMBER OF MUTATIONS + + + PURPOSE + ------- + + Returns the number of mutations. + + + INPUT + ----- + + [PILEUP] [pileup] + A Pileup object, which represents the pileup of aligned reads. + + + RETURN + ------ + + [INT] pileup.count_unique_mutations() + The number of mutations. + + # ======================================================================== + """""" + + return pileup.count_unique_mutations() + + +def get_shannon_entropy(haplotypes, frequencies): + """""" + # ======================================================================== + + GET SHANNON ENTROPY + + + PURPOSE + ------- + + Returns the Shannon entropy of the haplotypes. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of sorted Haplotype objects, for which to + report the Shannon entropy. + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [hs] + The Shannon Entropy of the haplotypes, determined from their + frequencies. + + # ======================================================================== + """""" + + Hs = calculate.shannon_entropy(frequencies) + + return Hs + + +def get_shannon_entropy_normalized_to_n(haplotypes, Hs): + """""" + # ======================================================================== + + GET SHANNON ENTROPY NORMALIZED TO N + + + PURPOSE + ------- + + Returns the Shannon entropy of the haplotypes normalized to N. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of sorted Haplotype objects, for which to + report the Shannon entropy. + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [hsn] + The Shannon entropy, normalized to the number of clones. + This is the sum of all counts of each haplotype. + + # ======================================================================== + """""" + + N = haplotype.calculate_total_clones(haplotypes) + + if float(math.log(N)) != 0: + Hsn = float(Hs) / float(math.log(N)) # entropy normalized to N. + else: + Hsn = 0 + + return Hsn + + +def get_shannon_entropy_normalized_to_h(haplotypes, Hs): + """""" + # ======================================================================== + + GET SHANNON ENTROPY NORMALIZED TO H + + + PURPOSE + ------- + + Returns the Shannon entropy of the haplotypes normalized to N. + + + INPUT + ----- + + [HAPLOTYPE LIST] [haplotypes] + A list of sorted Haplotype objects, for which to + report the Shannon entropy. + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [hsn] + The Shannon entropy, normalized to the number of haplotypes. + This is the length of the haplotypes list. + + # ======================================================================== + """""" + + H = len(haplotypes) + + if float(math.log(H)) != 0: + Hsh = float(Hs) / float(math.log(H)) # entropy normalized to H. + else: + Hsh = 0 + + return Hsh + + +def get_simpson_index(frequencies): + """""" + # ======================================================================== + + GET SIMPSON INDEX + + + PURPOSE + ------- + + Returns the Simpson Index. + + + INPUT + ----- + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [simpson_index] + The Simpson Index. + + # ======================================================================== + """""" + + H = len(frequencies) + P = frequencies + + simpson_index = calculate.simpson_index(H, P) + + return simpson_index + + +def get_gini_simpson_index(frequencies): + """""" + # ======================================================================== + + GET GINI-SIMPSON INDEX + + + PURPOSE + ------- + + Returns the Gini-Simpson index. + + + INPUT + ----- + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + + RETURN + ------ + + [FLOAT] [gini_simpson_index] + The Gini-Simpson index. + + # ======================================================================== + """""" + + H = len(frequencies) + P = frequencies + gini_simpson_index = calculate.gini_simpson_index(H, P) + + return gini_simpson_index + + +def get_hill_numbers(frequencies, end, start=0): + """""" + # ======================================================================== + + GET HILL NUMBERS + + + PURPOSE + ------- + + Return the 0, 1, 2, and 3 Hill numbers. + + + INPUT + ----- + + [FLOAT LIST] [frequencies] + A list of (relative) frequencies of the Haplotypes. + + [INT] [start] + An integer value to designate the starting position of our + Hill numbers list. + [INT] [end] + An integer value to designate the end position of our + Hill numbers list. + + + RETURN + ------ + + [FLOAT LIST] [list_of_hill_numbers] + A list of Hill numbers. + + # ======================================================================== + """""" + + P = frequencies + H = len(frequencies) + + list_of_hill_numbers = [] + + # Iterate over the range of hill numbers. + for hill_number_pos in range(start, end): + # Make sure a hill number is valid at that index + # A Hill number (Hn) can be calculate if we have at least Hn + 1 + # haplotypes. That is, the length the haplotype frequencies list (H) + # must be at least (Hn + 1). + if H >= hill_number_pos + 1: + list_of_hill_numbers.append(calculate.hill_number( + H, P, hill_number_pos)) + else: + break + + return list_of_hill_numbers + + +def measurement_to_csv(measurements_list, complexity_file): + """""" + # ======================================================================== + + MEASUREMENTS TO CSV + + + PURPOSE + ------- + + Report a number of complexity measurements. + + + INPUT + ----- + + [[List]] [measurements_list] + A two dimensional list that contains a number of complexity + measurements each position contains haplotypes of length position + k. + [(OUTPUT) FILE] [complexity_file] + The output file. + + POST + ------ + A CSV file that reports a number of complexity measurements for a + starting postion to k (BAM) or per amplicon (FASTA). Data is written + into complexity_file which is either a user defined file or sys.stdout + when the file is not specified. + + # ======================================================================== + """""" + + measurements_col_titles = [""Position""] + + for i in range(len(constant.MEASUREMENTS_NAMES)): + measurements_col_titles.append(constant.MEASUREMENTS_NAMES[i]) + + writer = csv.writer(complexity_file) + writer.writerow(measurements_col_titles) + + for position in range(len(measurements_list)): + measurements = measurements_list[position] + writer.writerow([position] + measurements) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_hydra.py",".py","8006","183",""""""" +Copyright Government of Canada 2017 - 2018 + +Written by: Camy Tran and Matthew Fogel, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +from collections import defaultdict +import click +from quasitools.patient_analyzer import PatientAnalyzer + +# GLOBALS + +from quasitools.quality_control import TRIMMING +from quasitools.quality_control import MASKING +from quasitools.quality_control import MIN_READ_QUAL +from quasitools.quality_control import LENGTH_CUTOFF +from quasitools.quality_control import MEDIAN_CUTOFF +from quasitools.quality_control import MEAN_CUTOFF +from quasitools.quality_control import NS +from quasitools.patient_analyzer import ERROR_RATE +from quasitools.patient_analyzer import MIN_VARIANT_QUAL +from quasitools.patient_analyzer import MIN_DP +from quasitools.patient_analyzer import MIN_AC +from quasitools.patient_analyzer import MIN_FREQ + +BASE_PATH = os.path.abspath(os.path.join(os.path.abspath(__file__), + os.pardir, os.pardir, ""data"")) +REFERENCE = os.path.join(BASE_PATH, ""hxb2_pol.fas"") +BED4_FILE = os.path.join(BASE_PATH, ""hxb2_pol.bed"") +MUTATION_DB = os.path.join(BASE_PATH, ""mutation_db.tsv"") + + +@click.command('hydra', short_help='Identify HIV Drug Resistance in a next ' + 'generation sequencing dataset.') +@click.argument('forward', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reverse', required=False, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-o', '--output_dir', required=True, + type=click.Path(exists=False, file_okay=False, dir_okay=True, + writable=True)) +@click.option('-m', '--mutation_db', + type=click.Path(exists=True, file_okay=True, dir_okay=False), + default=MUTATION_DB) +@click.option('-rt', '--reporting_threshold', default=1, + type=click.IntRange(1, 100, clamp=True), + help='Minimum mutation frequency percent to report.') +@click.option('-gc', '--generate_consensus', + help='Generate a mixed base consensus sequence.', is_flag=True) +@click.option('-cp', '--consensus_pct', default=20, + type=click.IntRange(1, 100, clamp=True), + help='Minimum percentage a base needs to be incorporated ' + 'into the consensus sequence.') +@click.option('-q', '--quiet', is_flag=True, + help='Suppress all normal output.') +@click.option('-tr', '--trim_reads', is_flag=True, + help='Iteratively trim reads based on filter values if enabled. ' + 'Remove reads which do not meet filter values if disabled.') +@click.option('-mr', '--mask_reads', is_flag=True, + help='Mask low coverage regions in reads if below minimum read' + ' quality. This option and --ns cannot be both enabled ' + 'simultaneously.') +@click.option('-rq', '--min_read_qual', default=30, help='Minimum quality for ' + 'a position in a read to be masked.') +@click.option('-lc', '--length_cutoff', default=100, + help='Reads which fall short of the specified length ' + 'will be filtered out.') +@click.option('-sc', '--score_cutoff', default=30, + help='Reads that have a median or mean quality score (depending' + ' on the score type specified) less than the score cutoff ' + 'value will be filtered out.') +@click.option('-me/-mn', '--median/--mean', + default=True, + help='Use either median score (default) or mean score for the ' + 'score cutoff value.') +@click.option('-n', '--ns', is_flag=True, help='Flag to enable the ' + 'filtering of n\'s. This option and --mask_reads cannot be both' + ' enabled simultaneously.') +@click.option('-e', '--error_rate', default=0.0021, + help='Error rate for the sequencing platform.') +@click.option('-vq', '--min_variant_qual', default=30, help='Minimum quality ' + 'for variant to be considered later on in the pipeline.') +@click.option('-md', '--min_dp', default=100, + help='Minimum required read depth for variant to be considered' + ' later on in the pipeline.') +@click.option('-ma', '--min_ac', default=5, + help='The minimum required allele count for variant to be ' + 'considered later on in the pipeline.') +@click.option('-mf', '--min_freq', default=0.01, + help='The minimum required frequency for mutation to be ' + 'considered in drug resistance report.') +@click.option('-i', '--id', + help='Specify FASTA sequence identifier to be used in the ' + 'consensus report.') +@click.pass_context +def cli(ctx, output_dir, forward, reverse, mutation_db, reporting_threshold, + generate_consensus, consensus_pct, quiet, trim_reads, mask_reads, + min_read_qual, length_cutoff, score_cutoff, median, ns, error_rate, + min_variant_qual, min_dp, min_ac, min_freq, id): + + if not os.path.isdir(output_dir): + os.mkdir(output_dir) + reads = forward + + if mask_reads and ns: + raise click.UsageError(""--ns and --mask_reads cannot be enabled"" + + "" simultaneously."") + + # The fasta_id is used as the sequence id in the consensus report + # and as the RG-ID in the bt2-generated bam file. + # It defaults to the forward fasta file name. + if id: + fasta_id = id + else: + fasta_id = os.path.basename(forward).split('.')[0] + + # Combine the fwd and reverse reads into one fastq file + if reverse: + reads = ""%s/combined_reads.fastq"" % output_dir + cat_cmd = ""cat %s %s > %s"" % (forward, reverse, reads) + os.system(cat_cmd) + + # If user did not specify an id, append name of reverse fasta file + if not id: + fasta_id += (""_%s"" % os.path.basename(reverse).split('.')[0]) + + quality_filters = defaultdict(dict) + + if trim_reads: + quality_filters[TRIMMING] = True + + if mask_reads: + quality_filters[MASKING] = True + + quality_filters[LENGTH_CUTOFF] = length_cutoff + + if median: + quality_filters[MEDIAN_CUTOFF] = score_cutoff + else: + quality_filters[MEAN_CUTOFF] = score_cutoff + # end if + + if ns: + quality_filters[NS] = True + else: + quality_filters[NS] = False + + quality_filters[MIN_READ_QUAL] = min_read_qual + + variant_filters = defaultdict(dict) + variant_filters[ERROR_RATE] = error_rate + variant_filters[MIN_VARIANT_QUAL] = min_variant_qual + variant_filters[MIN_DP] = min_dp + variant_filters[MIN_AC] = min_ac + variant_filters[MIN_FREQ] = min_freq + + patient_analyzer = PatientAnalyzer(id=REFERENCE[REFERENCE.rfind('/')+1:], + output_dir=output_dir, + reads=reads, reference=REFERENCE, + BED4_file=BED4_FILE, + mutation_db=mutation_db, quiet=quiet, + consensus_pct=consensus_pct) + + patient_analyzer.filter_reads(quality_filters) + try: + patient_analyzer.analyze_reads(fasta_id, variant_filters, + reporting_threshold, generate_consensus) + except Exception as error: + raise click.UsageError(str(error)) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_drmutations.py",".py","3749","94",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, Eric Chubaty, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +from quasitools.cli import pass_context +from quasitools.aa_census import AACensus +from quasitools.aa_variant import AAVariantCollection +from quasitools.mutations import MutationDB +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.genes_file_parser import parse_BED4_file +from quasitools.parsers.nt_variant_file_parser \ + import parse_nt_variants_from_vcf + + +@click.command('find_mutations', + short_help='Identifies amino acid mutations.') +@click.argument('bam', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('variants', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('bed4_file', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('mutation_db', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-f', '--min_freq', default=0.01, + help='the minimum required frequency.') +@click.option('-t', '--reporting_threshold', default=1, + help='the minimum percentage required for an entry in the drug' + 'resistant report.') +@click.option('-o', '--output', type=click.File('w')) +@pass_context +def cli(ctx, bam, reference, variants, bed4_file, min_freq, mutation_db, + reporting_threshold, output): + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # Create a MappedReadCollection object + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + variants_obj = parse_nt_variants_from_vcf(variants, rs) + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants_obj) + + # Parse the genes from the gene file + genes = parse_BED4_file(bed4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + # Create an AACensus object + aa_census = AACensus(reference, mapped_read_collection_arr, genes, frames) + + # Create AAVar collection and print the aavf file + aa_vars = AAVariantCollection.from_aacensus(aa_census) + + # Filter for mutant frequency + aa_vars.filter('mf' + str(min_freq), 'freq<' + str(min_freq), True) + + # Build the mutation database + mutation_db = MutationDB(mutation_db, genes) + + # Generate the mutation report + if output: + output.write(aa_vars.report_dr_mutations(mutation_db, + reporting_threshold)) + output.close() + else: + click.echo(aa_vars.report_dr_mutations(mutation_db, + reporting_threshold)) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_dnds.py",".py","1658","44",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.codon_variant_file_parser \ + import parse_codon_variants + + +@click.command('dnds', short_help='Calculate the dn/ds ' + 'value for each region in a bed file.') +@click.argument('csv', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('offset', required=True, type=int) +@click.option('-o', '--output', type=click.File('w')) +@click.pass_context +def cli(ctx, csv, reference, offset, output): + rs = parse_references_from_fasta(reference) + ref_seq = rs[0].seq + + codon_variants = parse_codon_variants(csv, rs) + + if output: + output.write(codon_variants.report_dnds_values(ref_seq, offset)) + else: + click.echo(codon_variants.report_dnds_values(ref_seq, offset)) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_aacoverage.py",".py","2781","72",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +from quasitools.cli import pass_context +from quasitools.aa_census import AACensus +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.genes_file_parser import parse_BED4_file + + +@click.command('aa_coverage', + short_help='Builds an amino acid census and returns its ' + 'coverage.') +@click.argument('bam', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('bed4_file', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-o', '--output', type=click.File('w')) +@pass_context +def cli(ctx, bam, reference, bed4_file, output): + """"""This script builds an amino acid census and returns its coverage. + The BAM alignment file corresponds to a pileup of sequences aligned to + the REFERENCE. A BAM index file (.bai) must also be present and, except + for the extension, have the same name as the BAM file. The REFERENCE must + be in FASTA format. The BED4_FILE must be a BED file with at least 4 + columns and specify the gene locations within the REFERENCE. + + The output is in CSV format."""""" + + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # Create a MappedReadCollection object + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + # Parse the genes from the gene file + genes = parse_BED4_file(bed4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene][""frame""]) + + # Create an AACensus object + aa_census = AACensus(reference, mapped_read_collection_arr, genes, frames) + + if output: + output.write(aa_census.coverage(frames)) + output.close() + else: + click.echo(aa_census.coverage(frames)) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_consensus.py",".py","2371","65",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +import pysam +import os +from quasitools.cli import pass_context +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam + + +@click.command('consensus', + short_help='Generate a consensus sequence from a BAM file.') +@click.argument('bam', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-p', '--percentage', default=100, + help='percentage to include base in mixture.') +@click.option('-i', '--id', + help='specify default FASTA sequence identifier to be used ' + 'for sequences without an RG tag.') +@click.option('-o', '--output', type=click.File('w')) +@pass_context +def cli(ctx, bam, reference, percentage, id, output): + rs = parse_references_from_fasta(reference) + bam_header = pysam.Samfile(bam, ""rb"").header + + if id: + fasta_id = id + else: + fasta_id = os.path.basename(bam).split('.')[0] + + for r in rs: + mrc = parse_mapped_reads_from_bam(r, bam) + + conseq = mrc.to_consensus(percentage) + + if hasattr(bam_header, 'RG'): + fasta_id = bam_header['RG'] + + if output: + output.write('>{0}_{1}_{2}\n{3}'.format(fasta_id, percentage, + r.name, conseq)) + else: + click.echo('>{0}_{1}_{2}\n{3}'.format(fasta_id, percentage, r.name, + conseq)) + if output: + output.close() +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/__init__.py",".py","0","0","","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_quality.py",".py","4396","111",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +from collections import defaultdict +import click +from quasitools.quality_control import QualityControl + +# GLOBALS + +from quasitools.quality_control import TRIMMING +from quasitools.quality_control import MASKING +from quasitools.quality_control import MIN_READ_QUAL +from quasitools.quality_control import LENGTH_CUTOFF +from quasitools.quality_control import MEDIAN_CUTOFF +from quasitools.quality_control import MEAN_CUTOFF +from quasitools.quality_control import NS + + +@click.command('quality', short_help='Perform quality control on FASTQ reads.') +@click.argument('forward', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reverse', required=False, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-o', '--output_dir', required=True, + type=click.Path(exists=False, file_okay=False, dir_okay=True, + writable=True)) +@click.option('-tr', '--trim_reads', is_flag=True, + help='Iteratively trim reads based on filter values if enabled. ' + 'Remove reads which do not meet filter values if disabled.') +@click.option('-mr', '--mask_reads', is_flag=True, + help='Mask low quality regions in reads if below minimum read' + ' quality. This option and --ns cannot be both enabled ' + 'simultaneously.') +@click.option('-rq', '--min_read_qual', default=30, help='Minimum quality for ' + 'positions in read if masking is enabled.') +@click.option('-lc', '--length_cutoff', default=100, + help='Reads which fall short of the specified length ' + 'will be filtered out.') +@click.option('-sc', '--score_cutoff', default=30, + help='Reads that have a median or mean quality score (depending' + ' on the score type specified) less than the score cutoff ' + 'value will be filtered out.') +@click.option('-me/-mn', '--median/--mean', + default=True, + help='Use either median score (default) or mean score for the ' + 'score cutoff value.') +@click.option('-n', '--ns', is_flag=True, help='Flag to enable the ' + 'filtering of n\'s. This option and --mask_reads cannot be both ' + 'enabled simultaneously.') +@click.pass_context +def cli(ctx, forward, reverse, output_dir, trim_reads, mask_reads, + min_read_qual, length_cutoff, score_cutoff, median, ns): + """"""Quasitools quality performs quality control on FASTQ reads and outputs + the filtered FASTQ reads in the specified directory."""""" + + if mask_reads and ns: + raise click.UsageError(""--ns and --mask_reads cannot be enabled"" + + "" simultaneously."") + + if not os.path.isdir(output_dir): + os.mkdir(output_dir) + reads = forward + + # Combine the fwd and reverse reads into one fastq file + if reverse: + reads = ""%s/combined_reads.fastq"" % output_dir + cat_cmd = ""cat %s %s > %s"" % (forward, reverse, reads) + os.system(cat_cmd) + + quality_filters = defaultdict(dict) + + if trim_reads: + quality_filters[TRIMMING] = True + + if mask_reads: + quality_filters[MASKING] = True + + quality_filters[LENGTH_CUTOFF] = length_cutoff + + if median: + quality_filters[MEDIAN_CUTOFF] = score_cutoff + else: + quality_filters[MEAN_CUTOFF] = score_cutoff + # end if + + if ns: + quality_filters[NS] = True + else: + quality_filters[NS] = False + + quality_filters[MIN_READ_QUAL] = min_read_qual + + filter_dir = ""%s/filtered.fastq"" % output_dir + quality_control = QualityControl() + quality_control.filter_reads(reads, filter_dir, quality_filters) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/commands/cmd_call.py",".py","7699","205",""""""" +Copyright Government of Canada 2017 - 2018 + +Written by: Eric Enns, Cole Peters, Eric Chubaty, Camy Tran, and Matthew Fogel + National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import click +import os +import sys +from quasitools.nt_variant import NTVariantCollection +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.aa_census import AACensus, CONFIDENT +from quasitools.aa_variant import AAVariantCollection +from quasitools.mutations import MutationDB +from quasitools.parsers.genes_file_parser import parse_BED4_file +from quasitools.parsers.nt_variant_file_parser \ + import parse_nt_variants_from_vcf +from quasitools.codon_variant import CodonVariantCollection +import PyAAVF.parser as parser + + +@click.group(invoke_without_command=False) +@click.pass_context +def cli(ctx): + pass + + +@cli.command('ntvar', short_help='Call nucleotide variants from a BAM file.') +@click.argument('bam', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-e', '--error_rate', default=0.0021, + help='estimated sequencing error rate.') +@click.option('-o', '--output', type=click.File('w')) +def ntvar(bam, reference, error_rate, output): + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # create MappedReadCollection object + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + variants = NTVariantCollection.from_mapped_read_collections( + error_rate, rs, *mapped_read_collection_arr) + + variants.filter('q30', 'QUAL<30', True) + variants.filter('ac5', 'AC<5', True) + variants.filter('dp100', 'DP<100', True) + + if output: + output.write(variants.to_vcf_file()) + output.close() + else: + click.echo(variants.to_vcf_file()) + + +@cli.command('aavar', short_help='Identifies amino acid mutations.') +@click.argument('bam', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('bed4_file', required=True, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('variants', required=False, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.argument('mutation_db', required=False, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-f', '--min_freq', default=0.01, + help='the minimum required frequency.') +@click.option('-e', '--error_rate', default=0.0021, + help='estimated sequencing error rate.') +@click.option('-o', '--output', type=click.File('w')) +def aavar(bam, reference, bed4_file, variants, mutation_db, + min_freq, error_rate, output): + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # Create a MappedReadCollection object + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + if variants: + variants_obj = parse_nt_variants_from_vcf(variants, rs) + else: + variants = NTVariantCollection.from_mapped_read_collections( + error_rate, rs, *mapped_read_collection_arr) + variants.filter('q30', 'QUAL<30', True) + variants.filter('ac5', 'AC<5', True) + variants.filter('dp100', 'DP<100', True) + variants_obj = variants + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants_obj) + + # Parse the genes from the gene file + genes = parse_BED4_file(bed4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + # Create an AACensus object + aa_census = AACensus(reference, mapped_read_collection_arr, genes, frames) + + # Create AAVar collection and print the aavf file + aa_vars = AAVariantCollection.from_aacensus(aa_census) + + # Filter for mutant frequency + aa_vars.filter('mf0.01', 'freq<0.01', True) + + # Build the mutation database and update collection + if mutation_db is not None: + mutation_db = MutationDB(mutation_db, genes) + aa_vars.apply_mutation_db(mutation_db) + + aavf_obj = aa_vars.to_aavf_obj(""aavar"", os.path.basename(reference), + CONFIDENT) + records = list(aavf_obj) + + if output: + writer = parser.Writer(output, aavf_obj) + else: + writer = parser.Writer(sys.stdout, aavf_obj) + + for record in records: + writer.write_record(record) + + if output: + output.close + + writer.close() + + +@cli.command('codonvar', short_help='Identify the number of ' + 'non-synonymous and synonymous mutations.') +@click.argument('bam', required=True, type=click.Path(exists=True, + file_okay=True, dir_okay=False)) +@click.argument('reference', required=True, type=click.Path(exists=True, + file_okay=True, dir_okay=False)) +@click.argument('offset', required=True, type=float) +@click.argument('bed4_file', required=True, type=click.Path(exists=True, + file_okay=True, dir_okay=False)) +@click.argument('variants', required=False, + type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option('-e', '--error_rate', default=0.0021, + help='estimated sequencing error rate.') +@click.option('-o', '--output', type=click.File('w')) +def codonvar(bam, reference, offset, bed4_file, variants, error_rate, output): + rs = parse_references_from_fasta(reference) + mapped_read_collection_arr = [] + + # Create a MappedReadCollection object + for r in rs: + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + if variants: + variants_obj = parse_nt_variants_from_vcf(variants, rs) + else: + variants = NTVariantCollection.from_mapped_read_collections( + error_rate, rs, *mapped_read_collection_arr) + variants.filter('q30', 'QUAL<30', True) + variants.filter('ac5', 'AC<5', True) + variants.filter('dp100', 'DP<100', True) + variants_obj = variants + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants_obj) + + # Parse the genes from the gene file + genes = parse_BED4_file(bed4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + aa_census = AACensus(reference, mapped_read_collection_arr, genes, frames) + + codon_variants = CodonVariantCollection.from_aacensus(aa_census) + + if output: + output.write(codon_variants.to_csv_file(offset)) + output.close() + else: + click.echo(codon_variants.to_csv_file(offset)) +","Python" +"Microbiology","phac-nml/quasitools","quasitools/constants/__init__.py",".py","0","0","","Python" +"Microbiology","phac-nml/quasitools","quasitools/constants/complexity_constants.py",".py","1936","54","UNDEFINED = """" + +# Measurement Positions +NUMBER_OF_HAPLOTYPES = 0 +HAPLOTYPE_POPULATION = 1 +NUMBER_OF_POLYMORPHIC_SITES = 2 +NUMBER_OF_MUTATIONS = 3 +SHANNON_ENTROPY_NUMBER = 4 +SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_N = 5 +SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_H = 6 +SIMPSON_INDEX = 7 +GINI_SIMPSON_INDEX = 8 +HILL_NUMBER_0 = 9 +HILL_NUMBER_1 = 10 +HILL_NUMBER_2 = 11 +HILL_NUMBER_3 = 12 +MINIMUM_MUTATION_FREQUENCY = 13 +MUTATION_FREQUENCY = 14 +FUNCTIONAL_ATTRIBUTE_DIVERSITY = 15 +SAMPLE_NUCLEOTIDE_DIVERSITY_ENTITY = 16 +MAXIMUM_MUTATION_FREQUENCY = 17 +POPULATION_NUCLEOTIDE_DIVERSITY = 18 +SAMPLE_NUCLEOTIDE_DIVERSITY = 19 + + +# Dictionary of Names +MEASUREMENTS_NAMES = { + NUMBER_OF_HAPLOTYPES: ""Number of Haplotypes"", + HAPLOTYPE_POPULATION: ""Haplotype Population"", + NUMBER_OF_POLYMORPHIC_SITES: ""Number of Polymorphic Sites"", + NUMBER_OF_MUTATIONS: ""Number of Mutations"", + SHANNON_ENTROPY_NUMBER: ""Shannon Entropy"", + SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_N: ""Shannon Entropy Normalized to N"", + SHANNON_ENTROPY_NUMBER_NORMALIZED_TO_H: ""Shannon Entropy Normalized to H"", + SIMPSON_INDEX: 'Simpson Index', + GINI_SIMPSON_INDEX: ""Gini-Simpson Index"", + HILL_NUMBER_0: ""Hill Number #0"", + HILL_NUMBER_1: ""HIll Number #1"", + HILL_NUMBER_2: ""Hill Number #2"", + HILL_NUMBER_3: ""Hill Number #3"", + MINIMUM_MUTATION_FREQUENCY: ""Minimum Mutation Frequency"", + MUTATION_FREQUENCY: ""Mutation Frequency"", + FUNCTIONAL_ATTRIBUTE_DIVERSITY: ""Functional Attribute Diversity"", + SAMPLE_NUCLEOTIDE_DIVERSITY_ENTITY: ""Sample Nucleotide Diversity (Entity)"", + MAXIMUM_MUTATION_FREQUENCY: ""Maximum Mutation Frequency"", + POPULATION_NUCLEOTIDE_DIVERSITY: ""Population Nucleotide Diversity"", + SAMPLE_NUCLEOTIDE_DIVERSITY: ""Sample Nucleotide Diversity"", +} + +# The number of hill numbers we want to calculate. +# if we want more hill numbers the measurement positions +# and dictionary names need to be updated. +HILL_NUMBER_LENGTH = 4 +","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/nt_variant_file_parser.py",".py","2155","58",""""""" +Copyright Government of Canada 2015-2017 + +Written by: Camy Tran, Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from quasitools.nt_variant import NTVariant, NTVariantCollection + + +def parse_nt_variants_from_vcf(variant_file, references): + """"""Build variants object from a vcf file"""""" + + obj = NTVariantCollection(references) + + # Read in and parse the variants file + # The file uses 1 as the first position but 0 is the first position in + # mapped reads. + with open(variant_file, ""r"") as input: + for line in input: + if line[0] != ""#"": + chrom, pos, var_id, ref, alt, qual, var_filter, info = \ + line.rstrip().split(""\t"") + + dp, ac, af = info.rstrip().split(';') + + dp = dp.rstrip().split('=')[1] + ac = ac.rstrip().split('=')[1] + af = af.rstrip().split('=')[1] + + variant_obj = NTVariant(chrom=chrom, + id=var_id, + pos=int(pos), + ref=ref, + alt=alt, + qual=qual, + filter=var_filter, + info={ + 'DP': dp, + 'AC': ac, + 'AF': af + }) + + obj.variants[chrom][int(pos)][alt] = variant_obj + + return obj +","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/genes_file_parser.py",".py","1723","55",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, Eric Chubaty, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from collections import defaultdict + +# BED FILE POSITIONS: +CHROM = 0 +START = 1 +END = 2 +NAME = 3 + + +def parse_BED4_file(BED4_file, ref_chrom): + """"""Parses a BED4+ file (BED file with at least 4 columns) and returns + a dictionary of genes. Each gene is a dictionary that contains the gene's + starting and ending positions as well as its frame."""""" + + genes = defaultdict(lambda: defaultdict(dict)) + + with open(BED4_file, ""r"") as f: + for line in f: + + tokens = line.rstrip().split(""\t"") + chrom = tokens[CHROM] + start = tokens[START] + end = tokens[END] + name = tokens[NAME] + # all other tokens are ignored + + if chrom != ref_chrom: + raise ValueError(""Chrom in genes bed file doesn't match "" + ""reference"") + + genes[name][""chrom""] = chrom + genes[name][""start""] = int(start) + genes[name][""end""] = int(end) + genes[name][""frame""] = int(start) % 3 + + return genes +","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/__init__.py",".py","0","0","","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/codon_variant_file_parser.py",".py","2271","65",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +from quasitools.codon_variant import CodonVariant, CodonVariantCollection + + +def parse_codon_variants(csv, references): + """"""Parse a codon variants csv and build a codon variants object"""""" + + variant_collect = CodonVariantCollection(references) + + with open(csv, ""r"") as f: + for line in f: + if line[0] != ""#"": + ( + gene, gene_start_end, nt_start, + nt_end, ref_codon, mutant_codon, + ref_aa, mutant_aa, coverage, + mutant_freq, mutant_type, + ns_count, s_count + ) = line.rstrip().split("","") + + gene_start, gene_end = gene_start_end.split('-') + + pos = int(nt_start)-int(gene_start) + + variant = CodonVariant( + chrom=gene, + pos=pos, + gene=gene, + nt_start_gene=int(gene_start), + nt_end_gene=int(gene_end), + nt_start=int(nt_start), + nt_end=int(nt_end), + ref_codon=ref_codon, + mutant_codon=mutant_codon, + ref_aa=ref_aa, + mutant_aa=mutant_aa, + coverage=int(coverage), + mutant_freq=float(mutant_freq), + mutant_type=mutant_type, + ns_count=float(ns_count), + s_count=float(s_count)) + + variant_collect.variants[gene][ + pos][mutant_codon] = variant + + f.close() + return variant_collect +","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/reference_parser.py",".py","1331","47",""""""" +Copyright Government of Canada 2015-2017 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import re +import Bio.SeqIO.FastaIO +from quasitools.reference import Reference + + +def parse_references_from_fasta(fasta): + """"""Parse Reference objects from a fasta file. + + >>> rs = parse_references_from_fasta('tests/data/ref1.fasta') + >>> print(length(rs)) + 1 + >>> print(rs[0].seq) + AGCATGTTAGATAAGATAGCTGTGCTAGTAGGCAGTCAGCGCCAT + """""" + references = () + + handle = open(fasta) + + for header, seq in Bio.SeqIO.FastaIO.SimpleFastaParser(handle): + name = re.search(r""(\S+)"", header).group(0) + references += (Reference(name, seq),) + + return references + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Microbiology","phac-nml/quasitools","quasitools/parsers/mapped_read_parser.py",".py","16238","624",""""""" +Copyright Government of Canada 2015-2019 + +Written by: Eric Enns, National Microbiology Laboratory, + Public Health Agency of Canada + +Modified by: Ahmed Kidwai, Matthew Fogel and Eric Marinier, + National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pysam +import Bio.SeqIO + +from quasitools.utilities import sam_alignment_to_padded_alignment, \ + pairwise_alignment_to_differences +from quasitools.mapped_read import MappedRead, MappedReadCollection +from quasitools.pileup import Pileup, Pileup_List +from quasitools.haplotype import Haplotype + + +REVERSE_COMPLEMENTED = 16 +FORWARD = '+' +REVERSE = '-' +GAP = '-' + + +def parse_mapped_reads_from_bam(reference, bam): + """"""Parse MappedRead mrcects from a bam file and produce a MappedReadCollection. + """""" + mrc = MappedReadCollection(reference) + sam = pysam.AlignmentFile(bam, ""rb"") + + for alignment in sam.fetch(reference=reference.name): + padded_alignment = sam_alignment_to_padded_alignment(alignment, + reference) + + direct = FORWARD + if alignment.flag & REVERSE_COMPLEMENTED: + direct = REVERSE + # TODO only calculate differences when identity < 100 + differences = pairwise_alignment_to_differences( + padded_alignment[0], padded_alignment[2], + alignment.reference_start) + + mapped_read = MappedRead(alignment.query_name, + alignment.query_alignment_start, + alignment.query_alignment_end - 1, + differences, + alignment.reference_start, + alignment.reference_end - 1, + direct) + # generate read_id, such that pair end data does not have the same key + # in the hash, by adding a 1 for forward read and 2 for reverse read + read_id = ""{0}_{1}"".format(alignment.query_name, + '1' if direct == FORWARD else '2') + mrc.mapped_reads[read_id] = mapped_read + + return mrc + + +def parse_haplotypes_from_bam( + references, + reference, + bam_location, + k): + """""""""" + #======================================================================== + + PARSE HAPLOTYPES FROM BAM + + PURPOSE + ------- + + This is the function to call to generate a list of haplotypes of length k, + across the reference, when the input is a BAM file. + + INPUT + ------- + [LIST (REFERENCE] [references] + - A list of quasitool Reference objects. + [REFERENCE_LOCATION][reference] + - The location of the reference file. + [BAM_FILE_LOCATION] [bam_location] + - The aligned BAM file from which we'll retrieve our haplotypes. + [INT] [k] + - The length we want our starting position take reads from. + + RETURN + ------- + [LIST of HAPLOTYPES] [haplotypes] + An 2D list containing a list of unsorted haplotypes, for each + position in the reference sequenence until, reference length - k + 1. + + #======================================================================== + """""" + + haplotypes = [] + samfile = pysam.AlignmentFile(bam_location, ""rb"") + + for reference in references: + + length = len(reference.seq) + for i in range(0, length - k + 1): + haplotype_list = ( + parse_haplotypes_from_bam_range( + samfile, + reference, + bam_location, + i, k)) + + haplotypes.append(haplotype_list) + + return haplotypes + + +def parse_haplotypes_from_bam_range( + samfile, + reference, + bam_location, + start, + k): + """""""""" + #======================================================================== + PARSE HAPLOTYPES FROM BAM + + PURPOSE + ------- + + Builds and returns an unsorted list of Haplotype objects from start to + start + k. + + + INPUT + ------- + [LIST (REFERENCE] [references] + - A list of Reference objects associated with the provided BAM + file location. + [BAM file location] [bam_location] + - The aligned BAM FILE from which we'll retrieve our haplotypes. + [INT] [start] + - The starting 0-based reference postion. + [INT] [k] + - The length of the haplotypes to generate. + RETURN + ------- + [LIST] [haplotyess] + - Unsorted list of Haplotype objects from start to start + k. + + #======================================================================== + """""" + + haplotypes = {} + + reads = samfile.fetch(reference.name, start, start + k) + + for read in reads: + + positional_array = create_positional_array(read.cigartuples) + + # Shift the positional array to align with the reference: + positional_array = [x + read.reference_start for x in positional_array] + read_sequence = read.query_alignment_sequence + + haplotype_start = get_index_in_list(positional_array, start) + haplotype_end = get_index_in_list(positional_array, start + k - 1) + 1 + + # check if read maps to the reference. + if haplotype_start < 0 or haplotype_end < 0: + + continue + + # Checks for deletions. + if haplotype_end - haplotype_start != k: + + continue + + # checks for inserts + if not is_consecutive_list( + positional_array[haplotype_start:haplotype_end]): + continue + + # Checking the read covers the entire region: + if read.get_overlap(start, start + k) == k: + + sequence = str(read_sequence[haplotype_start: haplotype_end]) + if sequence in haplotypes: + haplotype = haplotypes.get(sequence) + haplotype.count += 1 + else: + haplotypes[sequence] = Haplotype(sequence) + + haplotypes_list = list(haplotypes.values()) + + return haplotypes_list + + +def is_consecutive_list(list_of_integers): + """""" + # ======================================================================== + + IS CONSECUTIVE LIST + + + PURPOSE + ------- + + Reports if elments in a list increase in a consecutive order. + + + INPUT + ----- + + [[List]] [list_of_integers] + - A list of integers. + + Return + ------ + [BOOLEAN] + - Returns true is a list is consecutive or false if the same + number appears consecutively. + + # ======================================================================== + """""" + + for i in range(1, len(list_of_integers)): + if list_of_integers[i] - list_of_integers[i - 1] != 1: + return False + + return True + + +def get_index_in_list(list_of_integers, value): + """""" + # ======================================================================== + + GET INDEX IN LIST + + + PURPOSE + ------- + + Checks if a list contains a specific value. + + INPUT + ----- + + [[List]] [list_of_integers] + - A list of integers. + [(INT) VALUE] [value] + - The value we we are searching for in the list of integers. + + POST + ------ + [[INDEX] [INT]]: + - If the value is found in list of integers we return the index, + otherwise return -1. + + + # ======================================================================== + """""" + + try: + return list_of_integers.index(value) + + except ValueError: + return -1 + + +def create_positional_array(cigar_tuples): + """""" + # ======================================================================== + + CREATE POSITIONAL ARRAY + + + PURPOSE + ------- + + Create a positional array that maps positions in a + CIGAR tuple to a list. + + Ex. CIGAR tuple is: [(0, 4), (2, 1) (1, 2)] + + Positional Array is Initialized to Empty. + position (an int) starts at 0. + + We look at each item in the CIGAR tuple where + the first item is the operation (ex. match, delete, insert) + and the second item is number of bases involved in the operation. + + The returned array maps positions the read (as a list indicies) + to relative positions in the reference. This returned list of + relative positions starts at 0. + + + If we have a match we append the current reletive position + of the reference to the positional array (which represents + positions in the read) and then we will increase the relative + position in the reference. This process is repeated for the + length of the match. + + If the operation is a insertion we appending the positional array + with the left anchored relative position of the insert in + the reference. This proccess is repeated for the length of the insert. + This means the same relative position is appended multiple times. + + If the operation is a deletion we will increase the relative position + in the reference by the length of the operation. + This means no value gets appended to the positional array. + + So for the CIGAR tuple list above we would get a positional + array that looks as follows: + + 1. Looking at first tuple in the list: + The tuple's operation is 0 (i.e a match). + positional_array = [0, 1, 2, 3] + position: 4 + + 2. Looking at second tuple in the list: + The tuple's operation is 2 (i.e a delete) + positional_array: [0, 1, 2, 3] (didn't change) + position: 5 + + 3. Looking at the third tuple in the list: + The tuple's operation is 1 (i.e an insert) + positional_array = [0, 1, 2, 3, 4,4] + position: 5 + + INPUT + ----- + + [[CIGAR] TUPLE] [cigar_tuples] + - A list containing the CIGAR tuples. (operation, length). + + Return + ------ + [[LIST] [INT]] + - A positional array that maps CIGAR tuples to the read. + + # ======================================================================== + """""" + + positional_array = [] + OPERATION = 0 + LENGTH = 1 + position = 0 # 0-based + + MATCH = 0 + INSERT = 1 + DELETE = 2 + + for tup in cigar_tuples: + + if tup[OPERATION] == MATCH: + + for i in range(tup[LENGTH]): + + positional_array.append(position) # consume read + position = position + 1 # consume reference + + if tup[OPERATION] == INSERT: + + for i in range(tup[LENGTH]): + + positional_array.append(position - 1) # consume read + + if tup[OPERATION] == DELETE: + + position += tup[LENGTH] # consume reference + + return positional_array + + +def parse_pileup_from_bam(references, bam_location): + """""" + PARSE PILEUP FROM BAM + + + PURPOSE + ------- + + Constructs a Pileup obect from reference objects and a BAM file. + + + INPUT + ----- + + [LIST (REFERENCE)] [references] + A list of quasitools Reference objects. + + + [BAM FILE LOCATION)] [bam_location] + The file location of the aligned BAM file from which to build the + pileup object. + + + RETURN + ------ + + [Pileup] + A new pileup object constructed from the information in the Reference + object(s) and the BAM file. + + """""" + + # PySam bases: + A = 0 + C = 1 + G = 2 + T = 3 + + pileup = [] + samfile = pysam.AlignmentFile(bam_location, ""rb"") + + for reference in references: + + coverage = samfile.count_coverage( + contig=reference.name, start=0, stop=len(reference.seq), + quality_threshold=0) + + for column in range(len(coverage[0])): + + dictionary = {} + + if coverage[A][column] > 0: + dictionary[""A""] = coverage[A][column] + + if coverage[C][column] > 0: + dictionary[""C""] = coverage[C][column] + + if coverage[G][column] > 0: + dictionary[""G""] = coverage[G][column] + + if coverage[T][column] > 0: + dictionary[""T""] = coverage[T][column] + + pileup.append(dictionary) + + return Pileup(pileup) + + +def parse_pileup_list_from_bam(references, file_list): + """""" + # ======================================================================== + + PARSE PILEUP LIST FROM BAM + + + PURPOSE + ------- + + Constructs a Pileup_List object from Reference objects and multiple BAM + files. The Pileup_List will contain multiple Pileup objects, one + associated with each BAM file. The Reference objects must be correspond to + every BAM file. + + + INPUT + ----- + + [LIST (REFERENCE)] [references] + A list of quasitools Reference objects. + + [LIST (BAM FILE LOCATIONS)] [file_list] + A list of BAM file locations, each corresponding to one alignment + pileup. All BAM files must each correspond to the same associated + References objects. + + + RETURN + ------ + + [Pileup_List] + A new Pileup_List object representing a collection of Pileup objects. + + # ======================================================================== + """""" + + pileups = [] + + for bam_location in file_list: + + pileup = parse_pileup_from_bam(references, bam_location) + pileups.append(pileup) + + return Pileup_List(pileups) + + +def parse_pileup_from_fasta(reads_location, gaps=False): + """""" + # ======================================================================== + + PARSE PILEUP FROM FASTA + + + PURPOSE + ------- + + Parses an aligned FASTA file and returns a Pileup file corresponding to + the aligned FASTA file. + + + INPUT + ----- + + [(FASTA) FILE LOCATION] [reads_location] + The file location of the aligned FASTA file. + + [BOOLEAN] [gaps] + Whether or not to include gaps in the pileup. This is default by + false. + + + RETURN + ------ + + [Pileup] + A new pileup object constructed from the information in the aligned + FASTA file. + + # ======================================================================== + """""" + + pileup = [] + reads = Bio.SeqIO.parse(reads_location, ""fasta"") + + read = next(reads) + + for i in range(len(read)): + + pileup.append({}) + + while read: + + for i in range(len(read)): + + base = read[i] + + if pileup[i].get(base): + pileup[i][base] += 1 + + else: + pileup[i][base] = 1 + + read = next(reads, None) + + # Remove the gaps from the pileup. + if not gaps: + + for position in pileup: + + position.pop(GAP, None) + + return Pileup(pileup) + + +def parse_haplotypes_from_fasta(reads_location): + """""" + # ======================================================================== + + PARSE HAPLOTYPES FROM READS + + + PURPOSE + ------- + + Builds a list of Haplotype objects from aligned FASTA reads. + + + INPUT + ----- + + [FILE LOCATION] [reads_location] + The location of the aligned FASTA reads. + + [STRING] [consensus] + The consensus sequence of the pileup. + + + RETURN + ------ + + [HAPLOTYPE LIST] + A list of Haplotype objects, defined by the aligned FASTA reads. + + # ======================================================================== + """""" + + haplotypes = {} # (sequence, Haplotype) + + reads = Bio.SeqIO.parse(reads_location, ""fasta"") + + for read in reads: + + sequence = str(read.seq) + if sequence in haplotypes: + + haplotype = haplotypes.get(sequence) + haplotype.count += 1 + + else: + + haplotypes[sequence] = Haplotype(sequence) + + haplotypes_list = list(haplotypes.values()) + + return haplotypes_list + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Microbiology","phac-nml/quasitools","docs/aavar.md",".md","6825","150","# aavar + +Call amino acid mutations from a [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) alignment file and a supplied reference file. Please refer to [Data Formats](../formats) for detailed information about the the expected input formats for this tool. + +## Basic Usage + +```bash +quasitools aavar [options] [variants file] [mutation db] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned sequences in the BAM file. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +### BED File + +A [BED file](https://bedtools.readthedocs.io/en/latest/content/general-usage.html) that specifies the coordinates of genes, with repsect to the provided reference. This BED file must be a BED4+ file and therefore contain at least the first 4 BED file columns. The ""names"" of these genetic regions in the BED4 file must be the same names used in the ""genetic regions"" column of the mutation database. Please refer to [Data Formats](../formats) for more information. + +### Variants File + +A [VCF (Variant Call Format)](https://en.wikipedia.org/wiki/Variant_Call_Format) file format specifying identified variants in the BAM file, with respect to the passed reference file. When this file is provided, the computational running time of the program is improved. This variants file should be generated using the same BAM and reference files passed as parameters to program. The VCF output of [call ntvar](../ntvar) may be used as input to this program. + +### Mutation Database + +The mutation database describes specific mutations within the named genetic regions specified previously in the BED4 file. When provided to the tool, the surveillence and drug resistance category information are included in the output mutation annotation. + +The entries in the ""genetic regions"" colummn of this database must match the ""names"" column of the provided BED4 file. Please refer to [Data Formats](../formats) for more information. + +## Options + +### Minimum Frequency + +```text +-f, --min_freq FLOAT +``` + +The minimum observed frequency for a variant to reported. The default frequency is 0.01. + +### Error Rate + +```text +-e, --error_rate FLOAT +``` + +This is the expected substitution sequencing error rate. The default value is 0.0021 substitutions per sequenced base. + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the identified amino acid mutations. + +## Output + +The amino acid mutations that exceed the minimum frequency threshold will be output in [AAVF](https://github.com/winhiv/aavf-spec/blob/master/AAVFv1.0.pdf) format. By default, the results will be printed to standard output. The user may direct the output to a file by specifying a file name with the ```-o / --output``` option. + +## Examples + +### Data + +The following example data may be used to run the tool: + +* [hiv.fasta](data/hiv.fasta) +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) +* [variant.vcf](data/variant.vcf) +* [hiv_db.tsv](data/hiv_db.tsv) + +### Example: No Database + +#### Command + +``` +quasitools call aavar variant.bam hiv.fasta hiv.bed +``` + +#### Output + +```text +##reference=hiv.fasta +##source=quasitools:aavar +##fileformat=AAVFv1.0 +##fileDate=20190206 +##INFO= +##INFO= +##INFO= +##INFO= +##INFO= +##FILTER= +#CHROM GENE POS REF ALT FILTER ALT_FREQ COVERAGE INFO +AF033819.3 gag 339 P Q PASS 1.0000 133 SRVL=.;AC=cAa;CAT=.;ACF=1.0000;RC=cca +AF033819.3 env 67 N T PASS 1.0000 116 SRVL=.;AC=aCt;CAT=.;ACF=1.0000;RC=aat +AF033819.3 gag 441 Y S PASS 1.0000 109 SRVL=.;AC=tCc;CAT=.;ACF=1.0000;RC=tac +AF033819.3 pol 141 I S PASS 1.0000 145 SRVL=.;AC=aGt;CAT=.;ACF=1.0000;RC=att +AF033819.3 vpu 34 L I PASS 1.0000 118 SRVL=.;AC=Ata;CAT=.;ACF=1.0000;RC=tta +AF033819.3 env 302 N Y PASS 1.0000 138 SRVL=.;AC=Tat;CAT=.;ACF=1.0000;RC=aat +AF033819.3 gag 3 A P PASS 1.0000 140 SRVL=.;AC=Ccg;CAT=.;ACF=1.0000;RC=gcg +AF033819.3 pol 246 Q H PASS 1.0000 139 SRVL=.;AC=caT;CAT=.;ACF=1.0000;RC=caa +AF033819.3 gag 230 E D PASS 1.0000 126 SRVL=.;AC=gaT;CAT=.;ACF=1.0000;RC=gaa +AF033819.3 pol 96 G E PASS 1.0000 128 SRVL=.;AC=gAa;CAT=.;ACF=1.0000;RC=gga +``` + +Observe that there is no information under ```INFO``` column of the output for ```SRVL``` (surveillance) and ```CAT``` (drug resistance category). This is because a mutation database was not provided. + +### Example: With Database + +#### Command + +```bash +quasitools call aavar variant.bam hiv.fasta hiv.bed variant.vcf hiv_db.tsv +``` + +#### Output + +```text +##reference=hiv.fasta +##source=quasitools:aavar +##fileformat=AAVFv1.0 +##fileDate=20190206 +##INFO= +##INFO= +##INFO= +##INFO= +##INFO= +##FILTER= +#CHROM GENE POS REF ALT FILTER ALT_FREQ COVERAGE INFO +AF033819.3 gag 339 P Q PASS 1.0000 133 SRVL=.;AC=cAa;CAT=.;ACF=1.0000;RC=cca +AF033819.3 env 67 N T PASS 1.0000 116 SRVL=No;AC=aCt;CAT=minor;ACF=1.0000;RC=aat +AF033819.3 gag 441 Y S PASS 1.0000 109 SRVL=No;AC=tCc;CAT=minor;ACF=1.0000;RC=tac +AF033819.3 pol 141 I S PASS 1.0000 145 SRVL=.;AC=aGt;CAT=.;ACF=1.0000;RC=att +AF033819.3 vpu 34 L I PASS 1.0000 118 SRVL=Yes;AC=Ata;CAT=major;ACF=1.0000;RC=tta +AF033819.3 env 302 N Y PASS 1.0000 138 SRVL=.;AC=Tat;CAT=.;ACF=1.0000;RC=aat +AF033819.3 gag 3 A P PASS 1.0000 140 SRVL=Yes;AC=Ccg;CAT=major;ACF=1.0000;RC=gcg +AF033819.3 pol 246 Q H PASS 1.0000 139 SRVL=No;AC=caT;CAT=minor;ACF=1.0000;RC=caa +AF033819.3 gag 230 E D PASS 1.0000 126 SRVL=.;AC=gaT;CAT=.;ACF=1.0000;RC=gaa +AF033819.3 pol 96 G E PASS 1.0000 128 SRVL=Yes;AC=gAa;CAT=major;ACF=1.0000;RC=gga +``` + +Observe that under the ```INFO``` column of the output, that the ```SRVL``` and ```CAT``` information is included in the annotation, if the mutation was specified in the mutation database. + + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/codonvar.md",".md","3978","89","# codonvar + +Call codon variants for a given [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) alignment file. A report is generated that details nucleotide variants within codons and the resulting amino acid variants. The report indicates whether the nucleotide variants correspond to a synonymous or a non-synonymous mutation. + +## Basic Usage + +```bash +quasitools codonvar [options] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned BAM sequences. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +### Offset + +An integer to offset the reported positions in the output. This does not change the frame or coordinates of coding sequences in the BED file. + +It may be useful to provide an offset when providing a gene as a reference and gene products in the BED file, but want to report codon variants with respect to the entire chromosome. In this circumstance, the offset would be the position of the reference gene, with respect to the chromosome on which it resides. + +### BED File + +A [BED file](https://bedtools.readthedocs.io/en/latest/content/general-usage.html) that specifies the coordinates of genes, with repsect to the provided reference. This BED file must be a BED4+ file and therefore contain at least the first 4 BED file columns. The ""names"" of these genetic regions in the BED4 file must be the same names used in the ""genetic regions"" column of the mutation database. Please refer to [Data Formats](../formats) for more information. + +### Mutation Database + +The mutation database describes specific mutations within the named genetic regions specified previously in the BED4 file. The entries in the ""genetic regions"" colummn of this database must match the ""names"" column of the provided BED4 file. Please refer to [Data Formats](../formats) for more information. + +## Options + +### Error Rate + +```text +-e, --error_rate FLOAT +``` + +This is the expected substitution sequencing error rate. The default value is 0.0021 substitutions per sequenced base. + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the identified amino acid mutations. +## Example + +### Data + +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) +* [hiv.fasta](data/hiv.fasta) +* [hiv.bed](data/hiv.bed) + +### Command + +```bash +quasitools call codonvar variant.bam hiv.fasta 0 hiv.bed +``` + +### Output + +```text +#gene,nt position (gene),nt start position,nt end position,ref codon,mutant codon,ref AA,mutant AA,coverage,mutant frequency,mutant type,NS count,S count +vpu,5607-5855,5706,5708,tta,Ata,L,I,118,100.00,NS,1.0000,0.0000 +nef,8342-8713,8630,8632,ctg,Ttg,L,L,143,100.00,S,0.0000,1.0000 +pol,1630-4641,2050,2052,att,aGt,I,S,145,100.00,NS,1.0000,0.0000 +pol,1630-4641,2986,2988,gaa,gaG,E,E,107,100.00,S,0.0000,1.0000 +pol,1630-4641,2419,2421,ctg,ctC,L,L,143,100.00,S,0.0000,1.0000 +pol,1630-4641,1654,1656,cta,ctC,L,L,110,100.00,S,0.0000,1.0000 +pol,1630-4641,1915,1917,gga,gAa,G,E,128,100.00,NS,1.0000,0.0000 +pol,1630-4641,2365,2367,caa,caT,Q,H,139,100.00,NS,1.0000,0.0000 +env,5770-8340,5968,5970,aat,aCt,N,T,116,100.00,NS,1.0000,0.0000 +env,5770-8340,6136,6138,acc,acG,T,T,134,100.00,S,0.0000,1.0000 +env,5770-8340,7363,7365,gca,gcC,A,A,128,100.00,S,0.0000,1.0000 +env,5770-8340,6673,6675,aat,Tat,N,Y,138,100.00,NS,1.0000,0.0000 +gag,335-1837,1655,1657,tac,tCc,Y,S,109,100.00,NS,1.0000,0.0000 +gag,335-1837,716,718,gtc,gtG,V,V,131,100.00,S,0.0000,1.0000 +gag,335-1837,341,343,gcg,Ccg,A,P,140,100.00,NS,1.0000,0.0000 +gag,335-1837,1022,1024,gaa,gaT,E,D,126,100.00,NS,1.0000,0.0000 +gag,335-1837,1349,1351,cca,cAa,P,Q,133,100.00,NS,1.0000,0.0000 +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/legal.md",".md","650","17","# Legal + +Copyright Government of Canada 2017-2018 + +Written by: National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +","Markdown" +"Microbiology","phac-nml/quasitools","docs/installation.md",".md","1110","26","# Installation + +## Conda + +Conda is an open source package management system and environment management system that allows users to install software quickly and easily on a variety of operating systems. + +The simpliest way to install quasitools is with Conda. Install quasitools from [Bioconda](https://bioconda.github.io/) with [Conda](https://conda.io/docs/) ([installation instructions](https://bioconda.github.io/#install-conda)). If this is your first time installing software with Bioconda, then you will need to add the appropriate Conda channels for the first time: + +```bash +conda config --add channels defaults +conda config --add channels conda-forge +conda config --add channels bioconda +``` + +Installing quasitools with Conda: + +```bash +conda install quasitools +``` + +If everything was successful, you should be able to verify your installation by running ```quasitools --help``` and see quasitool's help message. + +## Galaxy + +When installing quasitools into an instance of Galaxy, please install quasitools from the [main Galaxy toolshed](https://toolshed.g2.bx.psu.edu/view/nml/quasitools/9fb9fed71486). +","Markdown" +"Microbiology","phac-nml/quasitools","docs/quality.md",".md","3427","142","# Quality + +Performs quality control measures of FASTQ reads and outputs filtered FASTQ reads. The tool may filter reads based on average quality score, median quality score, mask low quality bases, perform iterative read trimming, and filter based on read length. + +## Basic Usage + +```bash +quasitools quality [options] [] -o +``` + +## Arguments + +### FASTQ Forward + +The forward or single-end FASTQ-format reads to be correted. + +### FASTQ Reverse + +The reverse reads, associated with paired-end data, to be corrected. This argument is not used if the tool is provided with only single-end reads. + +## Options + +### Output Directory + +```text +-o, --output_dir DIRECTORY +``` + +The location of the output directory. + +### Trim Reads + +```text +-tr, --trim_reads +``` + +If enabled, the software will iteratively trim the ends of reads until they either meet filter values or become to short. If trimmed reads become too short, they will be discarded. + +If this option is disabled, the software will instead discard reads that do not meet filter values. + +### Mask Reads + +```text +-mr, --mask_reads +``` + +This option will mask low quality regions with ""N"" if they are below the minimum read quality threshold. This option and N-filtering (--ns) cannot be enabled simultaneously. + +### Minimum Read Quality + +```text +-rq, --min_read_qual INTEGER +``` + +Applies when read masking is enabled. The minimum quality for positions in the read before becoming masked with an ""N"". + + +### Length Cutoff + +```text +-lc, --length_cutoff INTEGER +``` + +Filters out any reads shorter than this length. + +### Score Cutoff + +```text +-sc, --score_cutoff INTEGER +``` + +This software will filter out reads that have a median (default) or mean score less than this value. + +### Median or Mean Score Filtering + +```text +-me, --median / -mn, --mean +``` + +This determines whether the software will use median (default) or mean score as a cutoff for read filtering. + +### Filtering Ns + +```text +-n, --ns +``` + +If enabled, the software will discard any reads that contain N characters. + +### Help + +```text +--help +``` + +Displays the help message and exits. + +## Output + +The filtered reads will be writen to the output directory. + +## Applications + +* Read quality control before other performing other analyses. + +## Example + +This example masks all positions with quality scores less than 30 as Ns. + +### Data + +* [reads.fastq](data/reads.fastq) + +### Command + +```bash +quasitools quality -mr -rq 30 reads.fastq -o output +``` + +### Output + +```text +@AF033819.3-1820 +AACAAACTTGGCNATGAAAGCAACACTTTTTACAATANCAATTGGTACAAGCAGTNTTAGGCNGACNTCCTNGNTGCTTNNAGGGCTCTAGTCTAGNANC ++ +CCCFFAFFHHHF)IGCFIFJIJIJIJJIIE@HBJGIJ(IIHCJHIBIJIJIBHDA/CJGI@H=DFE3EDE@'G;DCA?D0:AADDCDDCADDEDDC9E+D +@AF033819.3-1819 +TAATAAGACGNTCAATGNAACAGGACCATGTACAAANGTNAGCACAGTANAATGTACACATGGNATTAGGCCAGTAGTANCANCTCNNCTNCTGTTAANN ++ +?@CFFFBBHF2DDIJJG>DB(BABCDDD>( +@AF033819.3-1818 +TAATNCNGACGCTCTCGGANCCATCTCNCTCCTTCTNGCCNNCGCNAGTCAAAATTTTTGNCGTACTCACNAGTNNCCNCCNCTCGCCTCTTGCCGTGNG ++ +@C?F1B;DHGGHGGJIIGIC +@AF033819.3-1817 +CNGCCATTGTCANTATGTATTGTTTTTANTGGCCATNNTCCNGCTAATTTTAAAAGAAAATATGCTGTTTCCNNCCCTNTTTNTGCTGNAATNACTTCTN ++ +C=?FDFDDHDHB0@JJIEJICDIHJDIF1IFJIGJJ):?IE>IFCHDIIJ@J@JCJJJ?JDEIJIFIHGJCJ95B?CD,@D?2DFBDE;DEC>DCEBBD3 + +(output truncated) +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/requirements.md",".md","854","13","# Requirements + +If quasitools is installed through Conda or Galaxy, then dependencies should be installed automatically. However, several tools within quasitools require BAM and BAM index files as input. These will need to be created using alignment software, such as [Bowtie 2](http://bowtie-bio.sourceforge.net/bowtie2/index.shtml) to generate BAM alignment files and [SAMTools](http://www.htslib.org/) to generate BAM index files. Please see the [Data Formats](../formats) resource for more information about how to prepare input to quasitools. + +## HyDRA Pipeline + +When running quasitools directly from source, the HyDRA pipeline requires the follow dependencies: + +* [pysam](https://pysam.readthedocs.io/en/latest/api.html) >= 0.8.1 +* [SAMTools](http://www.htslib.org/) v1.3 +* [Bowtie 2](http://bowtie-bio.sourceforge.net/bowtie2/index.shtml) v2.2.6 + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/hydra.md",".md","7618","241","# HyDRA + +HyDRA is an annotated reference-based bioinformatics pipeline, which analyzes next-generation sequencing data for genotyping HIV-1 drug resistance mutation. It utilizes an annotated HXB2 sequence for reference mapping by Bowtie2, and stringent data quality assurance and variant calling to identify HIV drug resistant (HIVDR) associated mutations based on the [Stanford HIV Drug Resistance Database](https://hivdb.stanford.edu/) and the 2009 WHO list for Sruveillance of Transmitted HIVDR. All HIVDR mutations found in the _pol_ gene; _protease_ (PR), _reverse transcriptase_ (RT), and _integrase_ (IN) are reported according to classifications outlined in the [Stanford Surveillance Drug Resistance Mutation list](https://hivdb.stanford.edu/pages/surveillance.html). + +## Basic Usage + +```bash +quasitools hydra [OPTIONS] [REVERSE READS] +``` + +## Arguments + +### Forward Reads + +The forward or single-end FASTQ-format reads. HyDRA will attempt to identify known drug resistant mutations in these reads. + +### Reverse Reads + +This parameter is optional. If provided, these reads will be assumed to be paired with the provided forward reads and HyDRA will attempt to identify known drug resistant mutations in both sets of reads. + +## Options + +### Output + +```text +-o, --output DIRECTORY +``` + +The location of the output directory, which will contain several files created from HyDRA's operation, including any identified drug resistant mutations. + +### Mutation Database + +```text +-m, --mutation_db FILE +``` + +The mutation database describes specific mutations within the named genetic regions specified previously in the BED4 file. When provided to the tool. The entries in the ""genetic regions"" colummn of this database must match the ""names"" column of the provided BED4 file. Please refer to [Data Formats](../formats) for more information. + +### Reporting Threshold + +```text +-rt, --reporting_threshold INTEGER +``` + +The minimum number of observations required in the read data (FASTQ file) for an entry to be reported in the drug resistance report. Mutations with a number of observations less than this will not be reported. The default value is 1. + +### Generate Consensus + +```text +-gc, --generate_consensus +``` + +When this flag is set, the consensus sequence of the provided reads will be reported in the HyDRA output. + +### Consensus Percentage + +```text +-cp, --consensus_pct INTEGER +``` + +The minimum percentage of observations for an observation to be incorporated into the consensus. This option must be used with the `-gc/--generate_consensus` flag turned. + +This option causes the consensus construction to operate in one of two distinct modes. When the percentage is set to exactly ```100```, then the consensus is generated using by taking the most abundant base at each position. In contrast, when the percentage is less than ```100```, then the consensus is generated by comparing the frequency of each base at a position against the treshold. The default value is ```100```. + +These two modes of operation are described in greater detail within the description for [quasitools consensus](../consensus). + +### Quiet + +```text +-q, --quiet +``` + +This flag is used to suppress all standard output throughout the pipeline. However, this does not affect any file generation. + +### Trim Reads + +```text +-tr, --trim_reads +``` + +When this flag is enabled, the pipeline will iteratively trim the ends of reads until they either meet filter values or become too short. If trimmed reads become too short, they will be discarded. When this flag is not enabled, the pipeline will remove reads which do not meet filter values. + +### Mask Reads + +```text +-mr, --mask_reads +``` + +This option will mask low quality regions with ""N"" if they are below the minimum read quality threshold. This option and N-filtering cannot be enabled simultaneously. + +### Minimum Read Quality + +```text +-rq, --min_read_qual INTEGER +``` + +When read masking is enabled, this parameter is the minimum quality that a position must have in a read must have. If below this threshold, the position will be masked as an ```N```. + +### Length Cutoff + +```text +-lc, --length_cutoff INTEGER +``` + +Reads which fall short of the specified length will be filtered out. + +### Mean or Median Score + +```text +-me, --median / -mn, --mean +``` + +This determines whether the pipeline will use a mean or median (default) score as a cutoff for read filtering. + +### Score Cutoff + +```text +-sc, --score_cutoff INTEGER +``` + +Reads that have a median or mean quality score (depending on the score type specified) less than the score cutoff value will be filtered out. + +### Filter Ns + +```text +-n, --ns +``` + +If enabled, the pipeline will discard any reads that contain ```N``` characters. + +### Error Rate + +```text +-e, --error_rate FLOAT +``` + +The estimated substitution sequencing error rate for the sequencing platform. + +### Minimum Variant Quality + +```text +-vq, --min_variant_qual INTEGER +``` + +Minimum quality for an amino acid variant to be included in the produced AAVF ([Amino Acid Variant Format](https://github.com/winhiv/aavf-spec/raw/master/AAVFv1.0.pdf)) file. This minimum will affect which amino acid variants are reported. + +### Minimum Depth + +```text +-md, --min_dp INTEGER +``` + +Minimum required read depth for observed nucleotide variants included for processing in the pipeline. + +### Minimum Allele Count + +```text +-ma, --min_ac INTEGER +``` + +The minimum required allele count for observed nucleotide variants to be included for processing in the pipeline. + +### Minimum Frequency + +```text +-mf, --min_freq FLOAT +``` + +The minimum required frequency for observed amino acid variants to be included for processing in the pipeline. + +### ID + +```text +-i, --id TEXT +``` + +This is used to specifiy a FASTA sequence identifier to be used in the consensus report output. + +## Output + +The output directory location will default to the current directory and will be called `data/`. It will include the following output files: + +* align.bam +* align.bam.bai +* consensus.fasta +* coverage_file.csv +* dr_report.csv +* filtered.fastq +* hydra.vcf +* mutation_report.aavf +* stats.txt + +## Example + +### Data + +The following example data may be used to run the tool: + +* [variant.fastq](data/variant.fastq) + +### Command + +```bash +quasitools hydra variant.fastq -o output +``` + +### Output + +**Standard Output** + +```text +# Performing quality control on reads... +# Mapping reads... +# Loading read mappings... +# Identifying variants... +# Masking filtered variants... +# Building amino acid census... +# Finding amino acid mutations... +# Writing drug resistant mutation report... +``` + +**mutation_report.aavf** + +```text +##reference=hxb2_pol.fas +##source=quasitools:hydra +##fileformat=AAVFv1.0 +##fileDate=20190215 +##INFO= +##INFO= +##INFO= +##INFO= +##INFO= +##FILTER= +#CHROM GENE POS REF ALT FILTER ALT_FREQ COVERAGE INFO +hxb2_pol PR 85 I S PASS 1.0000 144 SRVL=.;AC=aGt;CAT=.;ACF=1.0000;RC=att +hxb2_pol RT 91 Q H PASS 1.0000 131 SRVL=.;AC=caT;CAT=.;ACF=1.0000;RC=caa +hxb2_pol PR 40 G E PASS 1.0000 122 SRVL=.;AC=gAa;CAT=.;ACF=1.0000;RC=gga +``` + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/index.md",".md","1907","30","# Introduction + +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Anaconda-Server Badge](https://anaconda.org/bioconda/quasitools/badges/installer/conda.svg)](https://anaconda.org/bioconda/quasitools) + +Quasitools is a collection of tools for analysing viral quasispecies data. The following tools are currently available in quasitools: + +* **[aacoverage](aacoverage.md)**: builds an amino acid consensus and returns its coverage +* **[call aavr](aavar.md)**: call amino acid mutations for a BAM file and a supplied reference file +* **[call codonvar](codonvar.md)**: call codon variants for a BAM file and a supplied reference file +* **[call ntvar](ntvar.md)**: call nucleotide variants for a BAM file and a supplied reference file +* **[complexity](complexity.md)**: reports the complexity of a quasispecies using several measures +* **[consensus](consensus.md)**: generate a consensus sequence from a BAM file +* **[distance](distance.md)**: measures the distance between quasispecies using angular cosine distance +* **[dnds](dnds.md)**: calculates the dn/ds value for each region in a bed file +* **[drmutations](drmutations.md)**: identifies amino acid mutations +* **[hydra](hydra.md)**: identify HIV drug resistance mutations in an NGS dataset +* **[quality](quality.md)**: perform quality control on FASTQ reads + +# Release + +__quasitools 0.7.0__ + +This release provides greater functionality for the complexity tool, including the ability to run on aligned read data and filter out low frequency haplotypes. + +# Resources + +* __Website__: [https://phac-nml.github.io/quasitools/](https://phac-nml.github.io/quasitools/) +* __Installation__: [https://phac-nml.github.io/quasitools/installation/](https://phac-nml.github.io/quasitools/installation/) +* __GitHub__: [https://github.com/phac-nml/quasitools](https://github.com/phac-nml/quasitools) +","Markdown" +"Microbiology","phac-nml/quasitools","docs/distance.md",".md","5000","148","# Distance + +Measures and reports the distance between multiple read pileups from multiple quasispecies samples, aligned to the same genomic region. This tool determines the cosine relatedness between viral quasispecies, reporting either angular cosine distance or cosine similarity as measures of relatedness. These measures of relatedness should be understood as approximations for evolutionary distance. + +The software represents quasispecies pileup data as vectors and measures the cosine angle between every pair of vectors. This has the benefit of comparing the relative composition of the quasispecies and is robust against widely varying degrees of coverage. This method does not reduce the quasipecies data into a consensus vector and therefore can capture more nuanced differences between two quasispecies pileups. The software can also normalize the pileup vectors to prevent bias of relative coverage within a single pileup. + +## Basic Usage + +```bash +quasitools distance [options] ()+ +``` +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. This tool requires at least two BAM files. However, there is no uppoer limit. A BAM index file (.bai) is also required for each BAM input and each BAM index file should be named the same as its corresponding BAM file, with the extension instead changed from "".bam"" to "".bai"". Each BAM file must be aligned to the same reference genome. + +### Reference File + +A reference file related to all of the aligned BAM sequence files. The provided reference file must be the same reference file used when producing all of the BAM and BAM index files. + +## Options + +### Normalize + +```text +-n, --normalize / -dn, --dont_normalize +``` + +Whether or not to normalize read count data so that counts at each position sum to one. This is useful if one region of the reference has more coverage depth than another region. Normalization will ensure each base position will contribute equally to the distance measurement. Normalization is done by dividing base read counts (A, C, T, G) inside every 4-tuple by the sum of the read counts inside the same tuple. + +### Output Distance + +```text +-od, --output_distance / -os, --output_similarity +``` + +Either output an angular distance matrix (by default) or output a cosine similarity matrix. Please be aware that cosine similarity is not a metric. + +### Start Position + +```text +-s, --startpos INTEGER +``` + +Sets the start base position of the reference to use in the distance or similarity calculation. The start position is one-indexed [1, n]. + +### End Position + +```text +-e, --endpos INTEGER +``` + +Sets the end base position of the reference to use in the distance or similarity calculation. The end position is one-indexed [1, n]. + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the quasispecies distance or similarity matrix in CSV format. + +### Truncate + +```text +-t, --truncate +``` + +Ignores congiguous start and end pileup regions with no coverage. + +### Remove No Coverage + +```text +-r, --remove_no_coverage +``` + +Remove all regions of the pileup with no coverage from the distance calculations. + +### Keep No Coverage + +```text +-k, --keep_no_coverage +``` + +Do not remove regions of the pileup with no coverage from the distance calculations. + +### Help + +```text +--help +``` + +Show a help message and exit. + + +## Output + +A distance matrix with the distances between all pairs of quasispecies pileups will be written to standard output. The user may also have the matrix written to a file by specifying the location with the `-o` command. + +## Applications + +* Generating a distance matrix between inputs for the purpose of clustering. + +## Example + +### Data + +The following example data may be used to run the tool: + +* [hiv.fasta](data/hiv.fasta) +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) +* [variant2.bam](data/variant2.bam) +* [variant2.bai](data/variant2.bai) +* [variant3.bam](data/variant3.bam) +* [variant3.bai](data/variant3.bai) + +### Command + +```bash +quasitools distance hiv.fasta variant.bam variant2.bam variant3.bam +``` + +### Output + +```text +Using file hiv.fasta as reference +Reading input from file(s) variant.bam +Reading input from file(s) variant2.bam +Reading input from file(s) variant3.bam +Constructed pileup from reference. +The pileup covers 9181 positions before modifications. +The start position is 1. +The end position is 9181. +The pileup covers 9181 positions after selecting range between original pileup positions 1 and 9181. +Truncating all positions with no coverage. +1 positions were truncated on the left. +1 positions were truncated on the right. +2 positions were removed in total from the pileup. +Outputting an angular cosine distance matrix. +Quasispecies,variant.bam,variant2.bam,variant3.bam +variant.bam,0.00000000,0.06414799,0.07023195 +variant2.bam,0.06414799,0.00000000,0.07760542 +variant3.bam,0.07023195,0.07760542,0.00000000 +Complete! +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/complexity.md",".md","4957","146","# complexity + +Reports various measures of viral quasispecies complexity. + +## Basic Usage + +FASTA Input: + +```bash +quasitools complexity fasta [OPTIONS] +``` + +BAM Input: + +```bash +quasitools complexity bam [OPTIONS] +``` + +## Arguments + +### FASTA Reads File + +This input file is only necessary when running the tool in FASTA mode. + +An aligned FASTA file containing multiple aligned sequences, representing haplotypes of a genomic region from the mutant spectrum of interest. This FASTA file would likely be created using a multiple sequence alignment tool from aligning amplicon sequencing data. + +### FASTA Reference File + +This input file is only necessary when running the tool in BAM mode. + +A reference file of the sequence of interest. The BAM file must be generated using this reference file. + +### BAM File + +This input file is only necessary when running the tool in BAM mode. + +A BAM file describing the alignments of reads to the same reference provided as input. These reads should be derived from a quasispecies mutant spectrum. This BAM file would likely be created using a read aligner which aligns FASTQ reads to a FASTA reference. + +### k-mer Size + +This input is only necessary when running the tool in BAM mode. + +The *k*-mer size defines the length of the *k*-mer sequence fragments. A sliding window of this *k*-mer size is used to scan across the reference genome. The sequences at each sliding window are used to calculate the quasispecies complexity. + +## Options + +### FILTER + +``` +-f [INTEGER] +``` + +This option is only available when running the tool in BAM mode. + +This option allows for a user-defined filter size between 0 and 100. Haplotypes under the filter size will not be used when calculating the quasispecies complexity at a particular position in the genome. + +### OUTPUT FILE + +``` +-o [USER-DEFINED-FILE-NAME.CSV] +``` + +This option is availble when running the tool in both BAM and FASTA mode. + +This option allows users to define an output file location, where the program output will be written in CSV format. + +## Output + +The quasispecies complexity measures are taken from *Gregori, Josep, et al. 2016*. These include the following various indices: + +Incidence (Entity Level): + +* Number of haplotypes +* Number of polymorphic sites +* Number of mutations + +Abundance (Molecular Level): + +* Shannon entropy +* Simpson index +* Gini-Simpson index +* Hill numbers + +Functional (Incidence): + +* Minimum mutation frequency (Mf min) +* Mutation frequency (Mfe) +* FAD +* Sample nucleotide diversity + +Functional (Abundance): + +* Maximum mutation frequency (Mf max) +* Population nucleotide diversity + +## Applications + +* Assessing the quasispecies complexity of a genomic region. +* Comparing the quasispecies complexity of multiple genomic regions from the same mutant spectrum. + +## Example: FASTA Reads File + +### Data + +The following example data may be used to run the tool: + +* [aligned.fasta](data/aligned.fasta) + +### Command + +```bash +quasitools complexity fasta aligned.fasta +``` + +### Output + +```text +Position,Number of Haplotypes,Haplotype Population,Number of Polymorphic Sites,Number of Mutations,Shannon Entropy,Shannon Entropy Normalized to N,Shannon Entropy Normalized to H,Simpson Index,Gini-Simpson Index,Hill Number #0,HIll Number #1,Hill Number #2,Hill Number #3,Minimum Mutation Frequency,Mutation Frequency,Functional Attribute Diversity,Sample Nucleotide Diversity (Entity),Maximum Mutation Frequency,Population Nucleotide Diversity,Sample Nucleotide Diversity +0,9,30,38,40,1.8774672554524843,0.5520018525167073,0.8544721713101401,0.19111111111111112,0.8088888888888889,9.0,6.536927510444632,5.232558139534883,4.543368996115371,0.013333333333333334,0.05555555555555555,7.379999999999999,0.10249999999999998,0.03866666666666667,0.06682222222222223,0.06912643678160921 +``` + + +## Example: BAM File With a Reference FASTA + +### Data + +The following example data may be used to run the tool: + +* [generated.fasta](data/generated.fasta) +* [generated.bam](data/generated.bam) +* [generated.bai](data/generated.bai) + + +### Command + +```bash +quasitools complexity bam generated.fasta generated.bam 200 +``` + +### Output + +```text +Position,Number of Haplotypes,Haplotype Population,Number of Polymorphic Sites,Number of Mutations,Shannon Entropy,Shannon Entropy Normalized to N,Shannon Entropy Normalized to H,Simpson Index,Gini-Simpson Index,Hill Number #0,HIll Number #1,Hill Number #2,Hill Number #3,Minimum Mutation Frequency,Mutation Frequency,Functional Attribute Diversity,Sample Nucleotide Diversity (Entity),Maximum Mutation Frequency,Population Nucleotide Diversity,Sample Nucleotide Diversity +0,6,6,6,15,1.7917594692280547,0.9999999999999999,0.9999999999999999,0.16666666666666669,0.8333333333333333,6.0,5.999999999999998,5.999999999999999,6.000000000000001,0.0125,0.01916666666666667,0.7300000000000004,0.02433333333333335,0.019166666666666665,0.020277777777777773,0.02433333333333333 +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/formats.md",".md","13283","227","# Data Formats + +This resource provides a detailed description of the various data formats used by quasitools, either as input or output, and their relationship to each other. In general, the data inputs usually must be consistent with each other. If you change one of the inputs, it is possible that some of the other inputs will need to change as well. + +## Overview + +The following is a summary of the formats used by quasitools: + +| Format | Description | +| --- | --- | +| Reads | A FASTQ file containing sequencing reads. | +| Reference | A FASTA reference of either a gene, chromosome, or genome. | +| BAM | Specifies sequence alignments between the FASTA reference and FASTQ reads. | +| BAI | Indexes the BAM file for faster processing. | +| BED4 | Specifies the coordinates of coding sequences in the reference. | +| Mutation Database | Specifies meaningful amino acid mutations within coding sequences. | +| Codon Variants CSV | Specifies nucleotide variants within codons and resulting amino acid mutations. | +| VCF | Specifies observed nucleotide variants and related information. | +| AAVF | Specifies observed amino acid variants and related information. | + +## Relationships + +The following is a summary of the relationships between quasitools inputs: + +| Input | Input | Relationship | +| --- | --- | --- | +| BAM | Reads | The BAM file describes the alignment of reads to a reference. | +| BAM | Reference | The BAM file describes the alignment of reads to a reference. | +| BAM | BAI | The BAM index (BAI) file must be created from the BAM file. | +| BED4 | Reference | The BED4 file describes coding sequences on the reference. | +| BED | Mutation Database | The BED ""name"" column must be consistent with the MutationDB ""coding sequences"" column. | + +## Reads + +Most tools in quasitools do not operated directly on reads and instead require BAM alignment files, which must be created manually by the user. Please see the BAM format section for more information. + +## Reference + +The reference file must be in [FASTA format](https://en.wikipedia.org/wiki/FASTA_format). When providing a BAM file, BAM index file (BAI), and a reference file together to the same program within quasitools, the BAM file must have been generated from an alignment with the reference and the BAM index file generated from the BAM file. + +## BAM + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) is the binary version of a [SAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file. A SAM (Sequence Alignment/Map) file is a tab-delimited text file that specifies sequence alignments. SAM files are often converted into BAM files to reduce storage space and allow faster processing. + +Within quasitools, BAM files are used to provide information about how sequencing reads aligned to a reference file. A BAM index file (.bai) is also required by quasitools and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". When running quasitools, it is important to ensure that the BAM file, BAM index file, and reference file are consistent with each other. The BAM file should be generated from an alignment against the reference and the BAM index file should be generated from the BAM file. + +BAM alignment files may be generated using read or sequence alignment software, such as [Bowtie2](http://bowtie-bio.sourceforge.net/bowtie2/index.shtml). If your sequence alignment software does not output a BAI file, you may use [samtools](http://www.htslib.org/doc/) to index your BAM file. + +## BED4 + +A [BED file](https://bedtools.readthedocs.io/en/latest/content/general-usage.html) specifies the coordinates of coding sequences, with repsect to sequences within a FASTA reference. The FASTA sequences are larger sequences, such a chromosomes or genes. The specified coding sequences are smaller sequences within the FASTA sequences. These small sequences within FASTA sequences may be genes or gene products. However, the should not contain non-coding sequences. The coordinates of the coding sequences must be specified in 0-based nucleotide coordinates and the length of each coding sequence must be divisible by three. + +The BED files used with quasitools must be BED4+ files and therefore must contain at least the first 4 BED file columns. It is very likely that these BED4 files will need to be manually created with knowledge of the locations of coding sequences in the reference. It is very important that the ```names``` of these coding sequences are the same names used in the ```coding sequences``` column of the mutation database, if the user is providing both files as inputs to a tool. The format of the BED files expected by quasitools is as follows: + +``` +[identifier] [start] [end] [name] +``` + +There must only be one record per line in the BED4 file. The items in each record are specified as follows: + +| Item | Description | Values | +| --- | --- | --- | +| identifier | The sequence identifier of the FASTA sequence within the FASTA reference file. | string | +| start | The starting nucleotide coordinate of the coding sequence. | integer | +| end | The ending nucleotide coordinate of the coding sequence. | integer | +| name | The name of the coding sequence. | string | + +### Example: Genes Witin a Chromsome + +**Reference File (FASTA)** + +```text +>chromosome1 +ACGTACGT ... +>chromesome2 +GGAATTCC ... +``` + +**BED4 File** + +```text +chromosome1 300 599 gene1 +chromosome1 900 1199 gene2 +chromosome2 300 599 gene3 +``` + +Observe that ```chromosome1``` and ```chromosome2``` are the names of contigs in a reference FASTA file. Our BED4 file specifies three genes within the reference file. ```gene1``` and ```gene2``` reside on the ```chromosome1``` contig and ```gene3``` resides on the ```chromosome2``` contig. + +### Example: Gene Products Witin a Gene + +**Reference File (FASTA)** + +```text +>gene1 +ACGTACGT ... +``` + +**BED4 File** + +```text +gene1 300 599 product1 +gene1 900 1199 product2 +``` + +Observe that our reference file specifics one contig, ```gene1```, which corresponds to a gene. The coding sequences specific in the BED4 file are instead gene products: ```product1``` and ```product2```. + +### Example: Gene Products Witin a Chromosome + +**Reference File (FASTA)** + +```text +>chromosome1 +ACGTACGT ... +>chromesome2 +GGAATTCC ... +``` + +**BED4 File** + +```text +chromosome1 300 399 product1 +chromosome1 900 999 product2 +chromosome2 300 399 product3 +``` + +Observe that ```chromosome1``` and ```chromosome2``` are the names of contigs in a reference FASTA file. Our BED4 file specifies three coding sequences which are gene products (assumed to be within genes). ```product1``` and ```product2``` reside on ```chromosome1``` and ```product3``` resides on ```chromosome2```. + +## Mutation Database + +The mutation database describes specific mutations within the named coding sequences specified previously in the BED4 file. It is used to report animo acid mutations that the user has identified. The mutation database is represented as a specifically formated TSV (tab separated values) file. The mutation database format is as follows: + +```text +[coding sequence] [wildtype] [position] [mutation] [category] [surveillance] [comment] +``` + +| Item | Description | Values | +| --- | --- | --- | +| coding sequence | The name of the coding sequence (CDS or gene product). | string | +| wildtype | The amino acid of wildtype. | character | +| position | The position of the amino acid within the coding sequence. | integer | +| mutation | The amino acid of the muation. | character | +| category | A categorization of the mutation. | string | +| surveillance | Whether or not the mutation is part of a surveillance program. | string | +| comment | A user-provided comment about the mutation. | string | + +In this format, there is one mutation entry per line in the file. Each item of every entry is separated by tabs. A line may be a comment if the very first character of the line is a ```#``` character. Please note that the ```position``` is the amino acid position within that particular coding sequence, in amino acid coordinates. It is very important that the values of the ""coding sequence"" column are the same names used in the ""name"" column of the BED4 file, if the user is providing both files as inputs to a tool. Every name that appears in the ```coding sequence``` column must also appear in the ```name``` column of the BED4 file. However, not every ```name``` in the BED4 file must appear under the ```coding sequence``` column in the mutation database. + +It is very likely that these mutation database files will need to be manually created with knowledge of the locations of mutations within the coding sequences specified in the BED file. + +### Example: Mutations Within a Gene + +**Mutation Database** + +```text +#genetic region wildtype position mutation category surveillance comment +gene1 M 10 F major Yes comment1 +gene1 K 20 I minor No comment2 +gene2 W 5 V major No comment3 +``` + +**BED4 File** + +```text +chromosome1 300 599 gene1 +chromosome1 900 1199 gene2 +chromosome2 300 599 gene3 +``` + +Observe that the all names in the first column of the mutation database (```gene1```, ```gene2```) appear in the last column of the BED4 file. However, not every named coding sequence in the BED4 (```gene3```) has to appear in the mutation database ```coding sequence``` column. + +## Codon Variants CSV + +The codon variants CSV file is consistent with the standard CSV format. The file describes nucleotide variants within codons and their resulting amino acid variants. It also clarifies whether the nucleotide variants are synonymous or a non-synonymous mutations. The codon variants CSV file has the following comment header: + +```text +#gene,nt position (gene),nt start position,nt end position,ref codon,mutant codon,ref AA,mutant AA,coverage,mutant frequency,mutant type,NS count,S count +``` + +The items on each line correspond to the following information: + +| Position | Name | Description | +| --- | --- | --- | +| 0 | gene | The name of the coding region. | +| 1 | nt position (gene) | The start and end nucleotide positions of the gene which contains the codon. | +| 2 | nt start position | The start nucleotide position of the codon. | +| 3 | nt end position | The end nucleotide position of the codon. | +| 4 | ref codon | The codon in the reference. | +| 5 | mutant codon | The mutant codon in the data. | +| 6 | ref AA | The corresponding amino acid in the reference. | +| 7 | mutant AA | The corresponding amino acid in the mutant. | +| 8 | coverage | The coverage of the codon. | +| 9 | mutant frequency | The observed frequency of the mutant codon. | +| 10 | mutant type | Whether or not the mutation is synonymous (S) or nonsynonymous (NS). | +| 11 | NS count | The expected number of nonsynonymous sites in the codon. A number between [0, 3]. | +| 12 | S count | The expected number of synonymous sites in the codon. A number between [0, 3]. | + +Please refer to [Nei and Gojobori 1986](https://academic.oup.com/mbe/article/3/5/418/988012) for more information about how to calculate ```NS count``` and ```S count```. + +## VCF + +The VCF format used within quasitools is consistent with the standard VCF format. However, quasitools uses custom values in the ```FILTER``` and ```INFO``` columns. + +### FILTER + +| Name | Meaning | +| --- | --- | +| dp100 | This variant was filtered because the coverage depth was less than 100. | +| q30 | This variant was filtered because the quality of the variant was less than 30. | +| ac5 | This variant was filtered because the variant was observed less than 5 times. | + +Of particular interest is the ```q30``` flag. This flag is set when the estimated quality of the variant is less than 30. quasitools calculates the probability of a variant being legitimate using the Poisson cumulative distribution function. In this framework, λ is the expected number of errors at a particular position (the coverage depth of that position multiplied by the error rate). + +In order for the variant to accepted as a real mutation, the probability of the observed variant being caused entirely by errors must be sufficiently low. In other words, at least some of the observed variant was probably caused by at least one real mutation. In order for the probability to be sufficiently low, it must be less than Q30 (1 in 1000 chance). When performing this probability calculation, we assume the worst case scenario: all expected substution errors at a particular position are the same nucleotide as the variant being tested, rather than being evenly distributed evenly across all possible substitions. + +### INFO + +| Name | Meaning | +| --- | --- | +| DP | The total coverage depth of the pileup at this position. | +| AC | The number of times this particular variants was observed in the pileup at this position. | +| AF | The frequency of this particular variants was observed in the pileup at this position. | + +## AAVF + +AAVF is a text file format, inspired by the Variant Call Format (VCF). It contains meta-information lines, a head line, and then data lines each containing information about a position in a gene within a genome. Please refer to the [AAVF documentation](https://github.com/winhiv/aavf-spec/raw/master/AAVFv1.0.pdf) for more information. + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/consensus.md",".md","4245","105","# Consensus + +Generate a consensus sequence from a BAM file. With default settings, a simple majority base rule will be used to build the consensus. However, the user may specify a minimum percentage of abundance for base incorporation into the consensus sequence, which may produce IUPAC codes in the consensus. + +## Basic Usage + +```bash +quasitools consensus [options] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned BAM sequences. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +## Options + +### Percentage + +```text +-p, --percentage INTEGER +``` + +This percentage option causes the consensus tool to operate in one of two distinct modes. When the percentage is set to exactly ```100```, then the consensus is generated using by taking the most abundant base at each position. In contrast, when the percentage is less than ```100```, then the consensus is generated by comparing the frequency of each base at a position against the treshold. The default value is ```100```. These two modes of operation are described in greater detail below. + +When this percentage is set to exactly ```100```, then the most frequent base will be incorporated into the consensus sequence. The incorporated base will be the most abundant base at the position. In the case of a tie, the base will be chosen in reverse alphabetical order. When no base is present (zero coverage, inserstion, only ```N```), then an ambigious ```N``` base will be incorporated. Additionally, insertions that are at least a multiple of 3 (i.e. codon length) will be incorporated. + +When this percentage is less than ```100```, then the tool will determine how many different bases pass the minimum incorporation threshold (```percentage```) at each position. Any bases that exceed this threshold will be incorporated into the consensus sequence at the given position. When multiple bases exceed the minimum threshold, then the base is converted to an ambigious IUPAC base. A table outlining these conversation is found below: + +| Bases Exceeding Treshold | Incorporated Base | +|---|---| +| A | A | +| C | C | +| G | G | +| T | T | +| AC | M | +| AG | R | +| AT | W | +| CG | S | +| CT | Y | +| GT | K | +| ACG | V | +| ACT | H | +| AGT | D | +| CGT | B | +| ACGT | N | + +For example, if the ```percentage``` is ```20``` and ```A``` has been observed 30% of the time, ```G``` has been observed 30% of the time, and ```T``` has been observed 40% of the time, then the base incorporated into the consensus will be ```D```. However, when there is zero coverage, or no bases meet the percentage threshold an ambigious ```N``` base will be incorporated into the consensus. Insertions will not be inserted into the consensus when run in this mode of operation. + +### ID + +```text +-i, --id TEXT +``` + +Specify the default FASTA sequence identifier to be used for sequences without an RG tag. + +### Output + +```text +-o, --ouput FILENAME +``` + +The file output location for the generated consensus sequence. + +## Output + +A consensus sequence on FASTA fortmat will be output to standard out unless specified otherwise. + +## Example + +### Data + +The following example data may be used to run the tool: + +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) +* [hiv.fasta](data/hiv.fasta) + +### Command + +```bash +quasitools consensus variant.bam hiv.fasta +``` + +### Output + +```text +>variant_100_AF033819.3 +ACTCTGGTAACTAGAGATCCCTCAGACCCATTTAGTCAGTGTGGAAAATCTCTAGCAGTGGCGCCCGAACAGGGACCTGA +AAGCGAAAGGGAAACCAGAGGAGCTCTCTCGACGCAGGACTCGGCTTGCTGAAGCGCGCACGGCAAGAGGCGAGGGGCGG +CGACTGGTGAGTACGCCAAAAATTTTGACTAGCGGAGGCTAGAAGGAGAGAGATGGGTCCGAGAGCGTCAGTATTAAGCG +GGGGAGAATTAGATCGATGGGAAAAAATTCGGTTAAGGCCAGGGGGAAAGAAAAAATATAAATTAAAACATATAGTATGG +GCAAGCAGGGAGCTAGAACGATTCGCAGTTAATCCTGGCCTGTTAGAAACATCAGAAGGCTGTAGACAAATACTGGGACA +GCTACAACCATCCCTTCAGACAGGATCAGAAGAACTTAGATCATTATATAATACAGTAGCAACCCTCTATTGTGTGCATC + +(output truncated) +``` + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/dnds.md",".md","2872","63","# dNdS + +Determines the dN/dS ratio for each codon variant in a supplied csv file (codon variants). The dN/dS ratio is the ratio between the number of nonsynonymous substitutions per non-synonymous site to the number of synonymous substitutions per synonymous site. + +The reported ratio is calculated by observing by first observing what proportion of nonsynonymous and synonymous sites have mutations, pN and pS. However, pN and pS are calculated with consideration for many reads are covering the same mutation sites. pN and pS are then converted to dN and dS using the Jukes-Cantor correction, which estimates the expected proportion of changes between two sequences (unobservable), based on our observed proportions (pN and pS). The corrected Jukes-Cantor rates will be higher, because the expectation is that over time, multiple mutations will have happened at the same site and this information is lost in our observed proportions; a slightly higher mutation rate (dN and dS) would have been required to observe our proportions (pN and pS). + +This dN/dS ratio can be used as an indicator of evolutionary pressure acting on a codon. For more information about the dN/dS calculation and how to interpret the ratio, please view [Morelli et al. 2013](https://veterinaryresearch.biomedcentral.com/articles/10.1186/1297-9716-44-12) and [Nei and Gojobori 1986](https://academic.oup.com/mbe/article/3/5/418/988012). + +## Basic Usage + +```bash +quasitools dnds [options] +``` + +## Arguments + +### Codon Variants CSV + +The codon variants CSV file should be taken directly from the output of [call codonvar](../codonvar) and provided as input when running this tool. For more information about this format, please refer to [Data Formats](../formats). + +### Reference File + +A reference file to compare the codon variants against. The provided reference file must be the same reference file used when producing the codon variants CSV file. + +### Offset + +An integer to offset the reported positions in the output. This does not change the frame or coordinates of coding sequences in the BED file. + +It may be useful to provide an offset when providing a gene as a reference and gene products in the BED file, but want to report codon variants with respect to the entire chromosome. In this circumstance, the offset would be the position of the reference gene, with respect to the chromosome on which it resides. + +## Options + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the dN/dS ratios. + +## Example + +### Data + +* [hiv.fasta](data/hiv.fasta) +* [variant_codonvar.csv](data/variant_codonvar.csv) + + +### Command + +```bash +quasitools dnds variant_codonvar.csv hiv.fasta 0 +``` + +### Output + +```text +#gene,pn,ps,pn_sites,ps_sites,dn/ds +pol,0.4345,1.5000,3,3,N/A +env,0.3750,1.0000,2,2,N/A +gag,0.4375,1.0000,4,1,N/A +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/ntvar.md",".md","3805","109","# ntvar + +Calls nucleotide variants observed witin an aligned BAM file when compared against a supplied reference file. + +## Basic Usage + +```bash +quasitools ntvar [options] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned BAM sequences. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +## Options + +### Error Rate + +```text +-e, --error_rate FLOAT +``` + +This is the expected substitution sequencing error rate. The default value is 0.0021 substitutions per sequenced base. + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the identified nucleotide variants in VCF format. Otherwise, the results are printed to standard output. + +## Output + +The output of the tool is a list of the variants observed witin the aligned BAM file when compared against the supplied reference file. The output is in VCF format and the quasitools provides the following additional information in the ```FILTER``` and ```INFO``` columns of the VCF file. + +Please see [Data Formats](../formats) for more information about the custom fields used by quasitools. However, a short description is provided below. + +### FILTER + +| Name | Meaning | +| --- | --- | +| dp100 | This variant was filtered because the coverage depth was less than 100. | +| q30 | This variant was filtered because the quality of the variant was less than 30. | +| ac5 | This variant was filtered because the variant was observed less than 5 times. | + +### INFO + +| Name | Meaning | +| --- | --- | +| DP | The total coverage depth of the pileup at this position. | +| AC | The number of times this particular variants was observed in the pileup at this position. | +| AF | The frequency of this particular variants was observed in the pileup at this position. | + +## Example + +### Data + +The following example data may be used to run the tool: + +* [hiv.fasta](data/hiv.fasta) +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) + +### Command + +```bash +quasitools call ntvar variant.bam hiv.fasta +``` + +### Output + +```text +##fileformat=VCFv4.2 +##fileDate=20190206 +##source=quasitools +##contig= +##INFO= +##INFO= +##INFO= +##FILTER= +##FILTER= +##FILTER= +#CHROM POS ID REF ALT QUAL FILTER INFO +AF033819.3 153 . t a 100 PASS DP=129;AC=129;AF=1.0000 +AF033819.3 342 . g c 100 PASS DP=141;AC=141;AF=1.0000 +AF033819.3 719 . c g 100 PASS DP=132;AC=132;AF=1.0000 +AF033819.3 1025 . a t 100 PASS DP=129;AC=129;AF=1.0000 +AF033819.3 1351 . c a 100 PASS DP=135;AC=135;AF=1.0000 +AF033819.3 1657 . a c 100 PASS DP=111;AC=111;AF=1.0000 +AF033819.3 1917 . g a 100 PASS DP=128;AC=128;AF=1.0000 +AF033819.3 2052 . t g 100 PASS DP=147;AC=147;AF=1.0000 +AF033819.3 2368 . a t 100 PASS DP=140;AC=140;AF=1.0000 +AF033819.3 2422 . g c 100 PASS DP=146;AC=146;AF=1.0000 +AF033819.3 2989 . a g 100 PASS DP=108;AC=108;AF=1.0000 +AF033819.3 5707 . t a 100 PASS DP=119;AC=119;AF=1.0000 +AF033819.3 5970 . a c 100 PASS DP=117;AC=117;AF=1.0000 +AF033819.3 6139 . c g 100 PASS DP=138;AC=138;AF=1.0000 +AF033819.3 6674 . a t 100 PASS DP=142;AC=142;AF=1.0000 +AF033819.3 7366 . a c 100 PASS DP=129;AC=129;AF=1.0000 +AF033819.3 8631 . c t 100 PASS DP=144;AC=144;AF=1.0000 +``` +","Markdown" +"Microbiology","phac-nml/quasitools","docs/aacoverage.md",".md","1967","91","# Amino Acid Coverage + +Builds an amino acid census and returns its coverage. + +## Basic Usage + +```bash +quasitools aacoverage [options] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned BAM sequences. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +### BED File + +A [BED file](https://bedtools.readthedocs.io/en/latest/content/general-usage.html) that specifies the coordinates of genes, with repsect to the provided reference. This BED file must be a BED4+ file. That is, the BED file must contain at least the first 4 BED file columns. + +## Options + +### Output + +```text +-o, --output FILENAME +``` + +The file output location of the amino acid coverage. + +## Output + +The amino acid coverage will be output in CSV format. The output will have one entry per line, with the amino acid position and the coverage at that position. By default, this will be printed to standard output. The user may direct the output to a file by specifying a file name with the `-o/--output` option. + +## Applications + +* Generating a report of the amino acid coverage, with respect to a referemce, from a BAM alignment file. + +## Example + +### Data + +The following example data may be used to run the tool: + +* [hiv.fasta](data/hiv.fasta) +* [hiv.bed](data/hiv.bed) +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) + +### Command + +```bash +quasitools aacoverage variant.bam hiv.fasta hiv.bed +``` + +### Output + +```text +frame: 0 +1,0 +2,4 +3,5 +4,9 +5,11 +6,13 +7,15 +8,17 +9,21 +10,22 +11,26 +12,26 +13,28 +14,32 +15,33 +16,37 +17,38 +18,43 +19,44 +20,45 +21,50 +22,54 +23,57 + +(output truncated) +``` + +","Markdown" +"Microbiology","phac-nml/quasitools","docs/contact.md",".md","48","4","# Contact + +**Eric Enns**: eric.enns@canada.ca +","Markdown" +"Microbiology","phac-nml/quasitools","docs/drmutations.md",".md","3365","81","# Drug Resistance Mutations + +Generates a report detailing the drug resistant mutations found. This tool identifies which nucleotide mutations, identified in the VCF file, have resulted in a noteworthy amino acid mutation, as specified by the mutation database. Please refer to [Data Formats](../formats) for detailed information about the the expected input formats for this tool. + +## Basic Usage + +```bash +quasitools drmutations [options] +``` + +## Arguments + +### BAM File + +A [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) file (.bam) of sequences aligned to a related reference. A BAM index file (.bai) is also required and should be named the same as the BAM file, with the extension instead changed from "".bam"" to "".bai"". + +### Reference File + +A reference file related to the aligned sequences in the BAM file. The provided reference file must be the same reference file used when producing the BAM and BAM index files. + +### Variants File + +A VCF-formated file containing information about nucleotide variants in the reads with respect to an aligned to the provided reference. The read alignment information is taken from the provided BAM file. Only mutations which ```PASS``` the VCF filters will be considered when running the tool. Additionally, a VCF file may be created using [quasitools call ntvar](../ntvar). + +### BED File + +A [BED file](https://bedtools.readthedocs.io/en/latest/content/general-usage.html) that specifies the coordinates of genes, with repsect to the provided reference. This BED file must be a BED4+ file and therefore contain at least the first 4 BED file columns. The ""names"" of these genetic regions in the BED4 file must be the same names used in the ""genetic regions"" column of the mutation database. Please refer to [Data Formats](../formats) for more information. + +### Mutation Database + +The mutation database describes specific mutations within the named genetic regions specified previously in the BED4 file. When provided to the tool. The entries in the ""genetic regions"" colummn of this database must match the ""names"" column of the provided BED4 file. Please refer to [Data Formats](../formats) for more information. + +## Options + +### Reporting Threshold + +```text +-t, --reporting_threshold INTEGER +``` + +The minimum number of observations required in the read data (BAM file) for an entry to be reported in the drug resistance report. Mutations with a number of observations less than this will not be reported. The default value is 1. + +### Output + +```text +-o, --output FILENAME +``` + +The file output location to write the identified drug resistant mutations. + + +## Example + +### Data + +* [variant.bam](data/variant.bam) +* [variant.bai](data/variant.bai) +* [hiv.fasta](data/hiv.fasta) +* [variant.vcf](data/variant.vcf) +* [hiv.bed](data/hiv.bed) +* [hiv_db.tsv](data/hiv_db.tsv) + +### Command + +```bash +quasitools drmutations variant.bam hiv.fasta variant.vcf hiv.bed hiv_db.tsv +``` + +### Output + +```text +Chromosome,Gene,Category,Surveillance,Wildtype,Position,Mutation,Mutation Frequency,Coverage +AF033819.3,gag,major,Yes,A,3,P,100.00,140 +AF033819.3,gag,minor,No,Y,441,S,100.00,109 +AF033819.3,pol,major,Yes,G,96,E,100.00,128 +AF033819.3,pol,minor,No,Q,246,H,100.00,139 +AF033819.3,vpu,major,Yes,L,34,I,100.00,118 +AF033819.3,env,minor,No,N,67,T,100.00,116 +``` + +","Markdown" +"Microbiology","phac-nml/quasitools","tests/test_mapped_read.py",".py","5745","65",""""""" +Copyright Government of Canada 2015-2017 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +from quasitools.mapped_read import MappedRead, MappedReadCollection +from quasitools.reference import Reference +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam + +class TestMappedRead: + @classmethod + def setup_class(self): + self.mr = MappedRead('read1', 10, 300, {'110': 'g', '300': 'tagt'}, 100, 390, '+') + + def test_query_length(self): + assert self.mr.query_length() == 291 + + def test_codon_start(self): + assert self.mr.codon_start(0) == 102 + assert self.mr.codon_start(1) == 100 + assert self.mr.codon_start(2) == 101 + + def test_codon_end(self): + assert self.mr.codon_end(0) == 389 + assert self.mr.codon_end(1) == 390 + assert self.mr.codon_end(2) == 388 + +class TestMappedReadCollection: + @classmethod + def setup_class(self): + self.reference = Reference('test', 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG') + self.mapped_reads_obj = MappedReadCollection(self.reference) + + for i in range(0,5): + self.mapped_reads_obj.mapped_reads[""{0}_{1}"".format('read%s' % i, 1)] = MappedRead('read%i' % i, 0, 34, {10: '-'}, 0, 35, '+' ) + + for i in range(5,100): + self.mapped_reads_obj.mapped_reads[""{0}_{1}"".format('read%s' % i, 1)] = MappedRead('read%i' % i, 0, 34, {}, 0, 35, '+' ) + + def test_from_bam(self): + reference = Reference('hxb2_pol', 'CCTCAGGTCACTCTTTGGCAACGACCCCTCGTCACAATAAAGATAGGGGGGCAACTAAAGGAAGCTCTATTAGATACAGGAGCAGATGATACAGTATTAGAAGAAATGAGTTTGCCAGGAAGATGGAAACCAAAAATGATAGGGGGAATTGGAGGTTTTATCAAAGTAAGACAGTATGATCAGATACTCATAGAAATCTGTGGACATAAAGCTATAGGTACAGTATTAGTAGGACCTACACCTGTCAACATAATTGGAAGAAATCTGTTGACTCAGATTGGTTGCACTTTAAATTTTCCCATTAGCCCTATTGAGACTGTACCAGTAAAATTAAAGCCAGGAATGGATGGCCCAAAAGTTAAACAATGGCCATTGACAGAAGAAAAAATAAAAGCATTAGTAGAAATTTGTACAGAGATGGAAAAGGAAGGGAAAATTTCAAAAATTGGGCCTGAAAATCCATACAATACTCCAGTATTTGCCATAAAGAAAAAAGACAGTACTAAATGGAGAAAATTAGTAGATTTCAGAGAACTTAATAAGAGAACTCAAGACTTCTGGGAAGTTCAATTAGGAATACCACATCCCGCAGGGTTAAAAAAGAAAAAATCAGTAACAGTACTGGATGTGGGTGATGCATATTTTTCAGTTCCCTTAGATGAAGACTTCAGGAAGTATACTGCATTTACCATACCTAGTATAAACAATGAGACACCAGGGATTAGATATCAGTACAATGTGCTTCCACAGGGATGGAAAGGATCACCAGCAATATTCCAAAGTAGCATGACAAAAATCTTAGAGCCTTTTAGAAAACAAAATCCAGACATAGTTATCTATCAATACATGGATGATTTGTATGTAGGATCTGACTTAGAAATAGGGCAGCATAGAACAAAAATAGAGGAGCTGAGACAACATCTGTTGAGGTGGGGACTTACCACACCAGACAAAAAACATCAGAAAGAACCTCCATTCCTTTGGATGGGTTATGAACTCCATCCTGATAAATGGACAGTACAGCCTATAGTGCTGCCAGAAAAAGACAGCTGGACTGTCAATGACATACAGAAGTTAGTGGGGAAATTGAATTGGGCAAGTCAGATTTACCCAGGGATTAAAGTAAGGCAATTATGTAAACTCCTTAGAGGAACCAAAGCACTAACAGAAGTAATACCACTAACAGAAGAAGCAGAGCTAGAACTGGCAGAAAACAGAGAGATTCTAAAAGAACCAGTACATGGAGTGTATTATGACCCATCAAAAGACTTAATAGCAGAAATACAGAAGCAGGGGCAAGGCCAATGGACATATCAAATTTATCAAGAGCCATTTAAAAATCTGAAAACAGGAAAATATGCAAGAATGAGGGGTGCCCACACTAATGATGTAAAACAATTAACAGAGGCAGTGCAAAAAATAACCACAGAAAGCATAGTAATATGGGGAAAGACTCCTAAATTTAAACTGCCCATACAAAAGGAAACATGGGAAACATGGTGGACAGAGTATTGGCAAGCCACCTGGATTCCTGAGTGGGAGTTTGTTAATACCCCTCCCTTAGTGAAATTATGGTACCAGTTAGAGAAAGAACCCATAGTAGGAGCAGAAACCTTCTATGTAGATGGGGCAGCTAACAGGGAGACTAAATTAGGAAAAGCAGGATATGTTACTAATAGAGGAAGACAAAAAGTTGTCACCCTAACTGACACAACAAATCAGAAGACTGAGTTACAAGCAATTTATCTAGCTTTGCAGGATTCGGGATTAGAAGTAAACATAGTAACAGACTCACAATATGCATTAGGAATCATTCAAGCACAACCAGATCAAAGTGAATCAGAGTTAGTCAATCAAATAATAGAGCAGTTAATAAAAAAGGAAAAGGTCTATCTGGCATGGGTACCAGCACACAAAGGAATTGGAGGAAATGAACAAGTAGATAAATTAGTCAGTGCTGGAATCAGGAAAGTACTATTTTTAGATGGAATAGATAAGGCCCAAGATGAACATGAGAAATATCACAGTAATTGGAGAGCAATGGCTAGTGATTTTAACCTGCCACCTGTAGTAGCAAAAGAAATAGTAGCCAGCTGTGATAAATGTCAGCTAAAAGGAGAAGCCATGCATGGACAAGTAGACTGTAGTCCAGGAATATGGCAACTAGATTGTACACATTTAGAAGGAAAAGTTATCCTGGTAGCAGTTCATGTAGCCAGTGGATATATAGAAGCAGAAGTTATTCCAGCAGAAACAGGGCAGGAAACAGCATATTTTCTTTTAAAATTAGCAGGAAGATGGCCAGTAAAAACAATACATACTGACAATGGCAGCAATTTCACCGGTGCTACGGTTAGGGCCGCCTGTTGGTGGGCGGGAATCAAGCAGGAATTTGGAATTCCCTACAATCCCCAAAGTCAAGGAGTAGTAGAATCTATGAATAAAGAATTAAAGAAAATTATAGGACAGGTAAGAGATCAGGCTGAACATCTTAAGACAGCAGTACAAATGGCAGTATTCATCCACAATTTTAAAAGAAAAGGGGGGATTGGGGGGTACAGTGCAGGGGAAAGAATAGTAGACATAATAGCAACAGACATACAAACTAAAGAATTACAAAAACAAATTACAAAAATTCAAAATTTTCGGGTTTATTACAGGGACAGCAGAAATCCACTTTGGAAAGGACCAGCAAAGCTCCTCTGGAAAGGTGAAGGGGCAGTAGTAATACAAGATAATAGTGACATAAAAGTAGTGCCAAGAAGAAAAGCAAAGATCATTAGGGATTATGGAAAACAGATGGCAGGTGATGATTGTGTGGCAAGTAGACAGGATGAGGATTAG') + mrc = parse_mapped_reads_from_bam(reference, 'tests/data/test1.bam') + + assert len(mrc.mapped_reads) == 6308 + + def test_pileup(self): + assert self.mapped_reads_obj.pileup() == [{'A': 100}, {'G': 100}, {'C':100}, {'T':100}, {'T':100}, {'A':100}, {'G':100}, {'C':100}, {'T':100}, {'A':100}, {'A':95, '-':5}, {'G':100}, {'C':100}, {'T':100}, {'A':100}, {'C':100}, {'C':100}, {'T':100}, {'A':100}, {'T':100}, {'A':100}, {'T':100}, {'C':100}, {'T':100}, {'T':100}, {'G':100}, {'G':100}, {'T':100}, {'C':100}, {'T':100}, {'T':100}, {'G':100}, {'G':100}, {'C':100}, {'C':100}, {'G':100}] + + def test_to_consensus(self): + assert self.mapped_reads_obj.to_consensus(100) == 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG' + assert self.mapped_reads_obj.to_consensus(20) == 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG' +","Python" +"Microbiology","phac-nml/quasitools","tests/test_aa_census.py",".py","2073","61",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.aa_census import AACensus +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.genes_file_parser import parse_BED4_file +from quasitools.parsers.reference_parser import parse_references_from_fasta + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +VALID_COVERAGE_CSV = TEST_PATH + ""/data/output/coverage_file.csv"" + +class TestMappedRead: + @classmethod + def setup_class(self): + reference = TEST_PATH + ""/data/hxb2_pol.fas"" + bam = TEST_PATH + ""/data/align.bam"" + BED4_file = TEST_PATH + ""/data/hxb2_pol.bed"" + + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # create MappedReadCollection object + mapped_read_collection_arr.append( + parse_mapped_reads_from_bam(r, bam)) + + genes = parse_BED4_file(BED4_file, rs[0].name) + + # Determine which frames our genes are in + self.frames = set() + + for gene in genes: + self.frames.add(genes[gene][""frame""]) + + self.aa_census = AACensus(reference, mapped_read_collection_arr, + genes, self.frames) + + def test_coverage(self): + + with open(VALID_COVERAGE_CSV, ""r"") as input: + coverage = input.read() + + assert self.aa_census.coverage(self.frames) == coverage +","Python" +"Microbiology","phac-nml/quasitools","tests/test_patient_analyzer.py",".py","5805","151",""""""" +Copyright Government of Canada 2017 - 2018 + +Written by: Camy Tran and Matthew Fogel, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import shutil +from collections import defaultdict +import pytest +from quasitools.patient_analyzer import PatientAnalyzer +import Bio.SeqIO + +# globals +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +READS = TEST_PATH + ""/data/reads_w_K103N.fastq"" +FORWARD = TEST_PATH + ""/data/forward.fastq"" +REVERSE = TEST_PATH + ""/data/reverse.fastq"" +REFERENCE = TEST_PATH + ""/data/hxb2_pol.fas"" +BED4_FILE = TEST_PATH + ""/data/hxb2_pol.bed"" +MUTATION_DB = TEST_PATH + ""/data/mutation_db.tsv"" +OUTPUT_DIR = TEST_PATH + ""/test_patient_analyzer_output"" +FILTERED_DIR = OUTPUT_DIR + ""/filtered.fastq"" + +from quasitools.quality_control import TRIMMING + +# used for masking +from quasitools.quality_control import MASKING +from quasitools.quality_control import MASK_CHARACTER +from quasitools.quality_control import MIN_READ_QUAL + +# used in quality_control.passes_filters +from quasitools.quality_control import LENGTH_CUTOFF +from quasitools.quality_control import MEDIAN_CUTOFF +from quasitools.quality_control import MEAN_CUTOFF +from quasitools.quality_control import NS + +# used in patient_analyzer +from quasitools.patient_analyzer import ERROR_RATE +from quasitools.patient_analyzer import MIN_VARIANT_QUAL +from quasitools.patient_analyzer import MIN_AC +from quasitools.patient_analyzer import MIN_DP +from quasitools.patient_analyzer import MIN_FREQ + +class TestPatientAnalyzer: + @classmethod + def setup_class(self): + # Test defaults + self.patient_analyzer = PatientAnalyzer(id=""test"",reads=READS, + reference=REFERENCE, + output_dir=OUTPUT_DIR, + BED4_file=BED4_FILE, + mutation_db=MUTATION_DB, + quiet=False, consensus_pct=20) + + + def test_combine_reads(self): + # Combine the fwd and reverse into one file + reads = ""%s/combined_reads.fastq"" % OUTPUT_DIR + cat_cmd = ""cat %s %s > %s"" % (FORWARD, REVERSE, reads) + os.system(cat_cmd) + + assert os.path.isfile(""%s/combined_reads.fastq"" % OUTPUT_DIR) + + def test_filter_reads(self): + + # tests for filtering of reads without iterative trimming or masking + # of coverage regions enabled + + quality_filters = defaultdict(dict) + + quality_filters[LENGTH_CUTOFF] = 100 + quality_filters[MEAN_CUTOFF] = 30 + quality_filters[MASKING] = True + quality_filters[MIN_READ_QUAL] = 30 + + status = self.patient_analyzer.filter_reads(quality_filters) + + assert status # assert that status is true (filtering has occured) + + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + + for seq in seq_rec_obj: + avg_score = quality_filters[MEAN_CUTOFF] + 1 + avg_score = (float(sum(seq.letter_annotations['phred_quality'])) / + float(len(seq.letter_annotations['phred_quality']))) + + # check that length and score are both over threshold + assert len(seq.seq) >= quality_filters[LENGTH_CUTOFF] and \ + avg_score >= quality_filters[MEAN_CUTOFF] + + # patient_analyzer.filter_reads calls quality_control.filter_reads + # more tests for filtering reads can be found in test_quality_control + + def test_generate_bam(self): + assert not os.path.isfile(""%s/align.bam"" % OUTPUT_DIR) + fasta_id = os.path.basename(self.patient_analyzer.reads).split('.')[0] + self.patient_analyzer.generate_bam(fasta_id) + + assert os.path.isfile(""%s/align.bam"" % OUTPUT_DIR) + + if os.path.isfile(""%s/align.bam"" % OUTPUT_DIR): + os.remove(""%s/align.bam"" % OUTPUT_DIR) + + def test_analyze_reads(self): + quality_filters = defaultdict(dict) + + # test defaults + variant_filters = defaultdict(dict) + variant_filters[ERROR_RATE] = 0.0021 + variant_filters[MIN_VARIANT_QUAL] = 30 + variant_filters[MIN_DP] = 100 + variant_filters[MIN_AC] = 5 + variant_filters[MIN_FREQ] = 0.01 + + generate_consensus = True + reporting_threshold = 20 + + fasta_id = os.path.basename(self.patient_analyzer.reads).split('.')[0] + + self.patient_analyzer.analyze_reads(fasta_id, + variant_filters, + reporting_threshold, + generate_consensus) + + assert os.path.isfile(""%s/consensus.fasta"" % OUTPUT_DIR) + assert os.path.isfile(""%s/coverage_file.csv"" % OUTPUT_DIR) + assert os.path.isfile(""%s/dr_report.csv"" % OUTPUT_DIR) + assert os.path.isfile(""%s/hydra.vcf"" % OUTPUT_DIR) + assert os.path.isfile(""%s/mutation_report.aavf"" % OUTPUT_DIR) + assert os.path.isfile(""%s/stats.txt"" % OUTPUT_DIR) + + assert not os.path.isfile(""%s/tmp.bam"" % OUTPUT_DIR) + assert not os.path.isfile(""%s/tmp.sam"" % OUTPUT_DIR) + + # Remove the output directory so that multiple tests (python 2.x, 3.x, etc.) + # can run without erroring out with ""File/directory exists"" + shutil.rmtree(""%s"" % OUTPUT_DIR) +","Python" +"Microbiology","phac-nml/quasitools","tests/test_complexity.py",".py","14715","401",""""""" +# ============================================================================= +Copyright Government of Canada 2019 + +Written by: Ahmed Kidwai, Public Health Agency of Canada, + National Microbiology Laboratory + +Funded by the National Micriobiology Laboratory and the Genome Canada / Alberta + Innovates Bio Solutions project ""Listeria Detection and Surveillance + using Next Generation Genomics"" + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +# ============================================================================= +"""""" + +import os +import pytest +import quasitools.commands.cmd_complexity as complexity +import quasitools.haplotype as haplotype +import quasitools.calculate as calculate +import quasitools.pileup as pileup +from click.testing import CliRunner +import click +import csv + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + + +# Test Consensus made by two expected haplotype lists. +class Test_Consensus: + + def test_consensus_simple(self): + + haplotypes_list = [ + haplotype.Haplotype(""AAAATAAA"", 2), + haplotype.Haplotype(""AAAAAAAA"", 3), + haplotype.Haplotype(""AAAAAAAA"", 4), + haplotype.Haplotype(""GAAAAAAC"", 6) + ] + + expected_consensus = ""AAAAAAAA"" + result = haplotype.build_consensus_from_haplotypes( \ + haplotypes_list) + + assert expected_consensus == result + + def test_consensus_degenerate(self): + haplotypes_list = [ + haplotype.Haplotype(""AAAATAAC"", 1), + haplotype.Haplotype(""AAAATAAC"", 1), + haplotype.Haplotype(""AAAATAAC"", 1), + haplotype.Haplotype(""TAAAGAAA"", 1) + ] + + expected_consensus = ""AAAATAAC"" + result = haplotype.build_consensus_from_haplotypes( \ + haplotypes_list) + + assert expected_consensus == result + + def test_consensus_tie(self): + haplotypes_list = [ + haplotype.Haplotype(""AAAATAAC"", 6), + haplotype.Haplotype(""AAAATAAC"", 3), + haplotype.Haplotype(""AAAATAAC"", 4), + haplotype.Haplotype(""TAAAGAAA"", 13) + ] + + expected_consensus = ""AAAAGAAA"" + result = haplotype.build_consensus_from_haplotypes( \ + haplotypes_list) + + assert expected_consensus == result + + def test_consensus_missing(self): + + haplotypes_list = [] + + result = haplotype.build_consensus_from_haplotypes( \ + haplotypes_list) + + expected_consensus = """" + + assert expected_consensus == result + + +# Test to see if bam subcommand runs. + +class Test_BAM_Complexity: + @classmethod + def setup(self): + self.bam_location = TEST_PATH + '/data/complexity.bam' + self.reference_location = TEST_PATH + '/data/complexity_reference.fasta' + self.bam_location2 = TEST_PATH + '/data/complexity_data.bam' + self.output_location_bam = TEST_PATH + '/data/output_bam.csv' + self.output_location_bam_filter = TEST_PATH + '/data/output_bam2.csv' + self.output_location_bam_filter2 = TEST_PATH + '/data/output_bam3.csv' + self.output_location_bam_filter3 = TEST_PATH + '/data/output_bam4.csv' + self.output_location_bam_filter4 = TEST_PATH + '/data/output_bam5.csv' + + def test_complexity_bam(self): + + runner = CliRunner() + result = runner.invoke(complexity.bam, [self.reference_location,\ + self.bam_location, ""1"", '--output_location', \ + self.output_location_bam]) + + # Check if output file is created + assert os.path.exists(TEST_PATH + '/data/output_bam.csv') + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_bam.csv'): + # split each row into a list + csv_row = line.split(',') + + # Check if last row has these values for each column + assert csv_row[0].strip() == '199' + assert csv_row[1].strip() == '3' + assert csv_row[2].strip() == '10' + assert csv_row[3].strip() == '1' + assert csv_row[4].strip() == '2' + + # Test BAM complexity when filter of 25 is applied + def test_complexity_filter_25(self): + + runner = CliRunner() + result = runner.invoke(complexity.bam, [self.reference_location,\ + self.bam_location, ""1"",""--haplotype_filter"", \ + 25, '--output_location', \ + self.output_location_bam_filter]) + + # Check if output file is created + assert os.path.exists(TEST_PATH + '/data/output_bam2.csv') + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_bam2.csv'): + # split each row into a list + csv_row = line.split(',') + + assert csv_row[0].strip() == '199' + assert csv_row[1].strip() == '2' + assert csv_row[2].strip() == '9' + assert csv_row[3].strip() == '1' + assert csv_row[4].strip() == '1' + + # Test Complexity filter with a filter of 0 (i.e no filtering, everything should pass) + def test_compexity_filter_0(self): + + runner = CliRunner() + result = runner.invoke(complexity.bam, [self.reference_location,\ + self.bam_location, ""1"",""--haplotype_filter"", \ + 0, '--output_location', \ + self.output_location_bam_filter2]) + + # Check if output file is created + assert os.path.exists(TEST_PATH + '/data/output_bam3.csv') + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_bam3.csv'): + # split each row into a list + csv_row = line.split(',') + + assert csv_row[0].strip() == '199' + assert csv_row[1].strip() == '3' + assert csv_row[2].strip() == '10' + assert csv_row[3].strip() == '1' + assert csv_row[4].strip() == '2' + + # Test the complexity filter with a value of 100. + # Since the BAM file has multiple haplotypes at every position, nothing should pass the filter. + def test_compexity_filter_100(self): + + runner = CliRunner() + result = runner.invoke(complexity.bam, [self.reference_location,\ + self.bam_location, ""1"",""--haplotype_filter"", \ + 100, '--output_location', \ + self.output_location_bam_filter3]) + + # Check if output file is created + assert os.path.exists(TEST_PATH + '/data/output_bam4.csv') + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_bam4.csv'): + # split each row into a list + csv_row = line.split(',') + + assert csv_row[0].strip() == '199' + assert csv_row[1].strip() == '' + assert csv_row[2].strip() == '' + assert csv_row[3].strip() == '' + assert csv_row[4].strip() == '' + + # Test the complexity filter with a value of 100. + # Since the BAM file has only one haplotype at every position, everything should pass filter. + def test_compexity_filer_100_2(self): + runner = CliRunner() + result = runner.invoke(complexity.bam, [self.reference_location,\ + self.bam_location2, ""50"",""--haplotype_filter"", \ + 100, '--output_location', \ + self.output_location_bam_filter4]) + + # Check if output file is created: + assert os.path.exists(TEST_PATH +'/data/output_bam5.csv') + + # Check to see if the expected values are found in the CSV + # file that we created. We will only look at the last row of this file. + for line in open(TEST_PATH + '/data/output_bam5.csv'): + # split each row into a list + csv_row = line.split(',') + + # This is just the row number, nothing was processed. + assert csv_row[0].strip() == '150' + + # Row numbers + assert csv_row[1].strip() == '1' + assert csv_row[2].strip() == '1' + assert csv_row[3].strip() == '0' + assert csv_row[4].strip() == '0' + + + +# Test to see if the fasta subcommand runs. +class Test_FASTA_Complexity: + @classmethod + def setup(self): + self.fasta_location = TEST_PATH + '/data/complexity.fasta' + self.output_location_fasta = TEST_PATH + '/data/output_fasta.csv' + + + def test_complexity_fasta(self): + + runner = CliRunner() + result = runner.invoke(complexity.fasta, [self.fasta_location, ""--output_location"", self.output_location_fasta], catch_exceptions=False) + + # If method ran successfully the exit code is 0. + assert result.exit_code == 0 + # Check if output file is created + assert os.path.exists(TEST_PATH + '/data/output_fasta.csv') + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_fasta.csv'): + csv_row = line.split(',') + + # Check if last row has these values for each column + assert csv_row[0].strip() == '0' + assert csv_row[1].strip() == '2' + assert csv_row[2].strip() == '2' + assert csv_row[3].strip() == '7' + assert csv_row[4].strip() == '7' + + +# Test each measurment +class Test_Measurements(): + + @classmethod + def setup(self): + + self.consensus = ""AAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"" + + self.haplotypes_list = [ + haplotype.Haplotype(""AAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"", 1), + haplotype.Haplotype(""AAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"", 1), + haplotype.Haplotype(""GAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"", 1), + haplotype.Haplotype(""TAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"", 6), + haplotype.Haplotype(""CAGAGTTGTGAGGAGTACTCACCTCAGTAGACAAGGAGAGCTA"", 6) + ] + + self.sorted_hap = haplotype.sort_haplotypes(self.haplotypes_list, self.consensus) + + self.pileup = haplotype.build_pileup_from_haplotypes(self.sorted_hap) + + self.frequencies = haplotype.build_frequencies(self.sorted_hap) + + self.distance_matrix = haplotype.build_distiance_matrix(self.sorted_hap) + + self.counts = haplotype.build_counts(self.sorted_hap) + + def test_number_of_mutations(self): + + unique_mutations = self.pileup.count_unique_mutations() + + assert unique_mutations == 3 + + + def test_number_of_polymorphic_sites(self): + + number_of_polymorphic_sites = self.pileup.count_polymorphic_sites() + + assert number_of_polymorphic_sites == 1 + + def test_shannon_entropy(self): + + shannon_entropy = calculate.shannon_entropy(self.frequencies) + + assert float(""{0:.2f}"".format(shannon_entropy))== 1.27 + + def test_shannon_entropy_normalized_to_n(self): + + Hs = 1.23 + + Hsn = complexity.get_shannon_entropy_normalized_to_n(self.sorted_hap, Hs) + + assert float(""{0:.2f}"".format(Hsn)) == 0.45 + + def test_shannon_entropy_normalized_to_h(self): + + Hs = 1.23 + + Hsn = complexity.get_shannon_entropy_normalized_to_h(self.sorted_hap, Hs) + + assert float(""{0:.2f}"".format(Hsn)) == 0.76 + + + def test_minimum_muttion_frequency(self): + + minimum_mutation_frequency = complexity.get_minimum_mutation_frequency(self.sorted_hap,self.pileup) + + assert float(""{0:.3f}"".format(minimum_mutation_frequency)) == 0.005 + + def test_mutation_frequency(self): + + mutation_frequency = complexity.get_mutation_frequency(self.distance_matrix) + assert float(""{0:.2f}"".format(mutation_frequency)) == 0.01 + + def test_functional_attribute_diversity(self): + + FAD = complexity.get_FAD(self.distance_matrix) + assert float(""{0:.2f}"".format(FAD)) == 0.42 + + def test_sample_nucleotide_diversity_entity(self): + + SND = complexity.get_sample_nucleotide_diversity(self.distance_matrix, self.frequencies, self.sorted_hap) + + assert float(""{0:.2f}"".format(SND)) == 0.02 + + def test_maximum_mutation(self): + + maximum_mutation_frequency = complexity.get_maximum_mutation_frequency(self.counts, self.distance_matrix, self.frequencies) + + assert float(""{0:.2f}"".format(maximum_mutation_frequency)) == 0.02 + + def test_population_nucleotide_diversity(self): + + PND = complexity.get_population_nucleotide_diversity(self.distance_matrix, self.frequencies) + + assert float(""{0:.2f}"".format(PND)) == 0.02 + + def test_sample_nucleotide_diversity_entity(self): + + snde = complexity.get_sample_nucleotide_diversity_entity(self.distance_matrix, self.frequencies) + + assert float(""{0:.2f}"".format(snde)) == 0.02 + + +class Test_CSV_Building: + + @classmethod + def setup(self): + + self.measurements = [[1,2,3,4,5]] + + def test_measurements_to_csv(self): + + file_directory = TEST_PATH + '/data/output_built_csv.csv' + + with open(file_directory, 'w') as \ + complexity_file: + complexity.measurement_to_csv(self.measurements, complexity_file) + + assert os.path.exists(file_directory) + + # Check to see if expected values are found in csv + # file that we created. We will look at the last row. + for line in open(TEST_PATH + '/data/output_built_csv.csv'): + csv_row = line.split(',') + + # Check if last row has these values for each column + assert csv_row[0].strip() == '0' + assert csv_row[1].strip() == '1' + assert csv_row[2].strip() == '2' + assert csv_row[3].strip() == '3' + assert csv_row[4].strip() == '4' + assert csv_row[5].strip() == '5' + +","Python" +"Microbiology","phac-nml/quasitools","tests/test_pileup.py",".py","15879","360",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os + +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam, parse_pileup_list_from_bam +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.pileup import Pileup_List +from quasitools.pileup import Pileup +from quasitools import cli +from quasitools.commands.cmd_distance import dist + +from click.testing import CliRunner + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + +class TestPileups: + + """""" + CLASS VARIABLES + """""" + + pileup1 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {}]] #test 5 + + pileup1_startpos_1 = 2 + pileup1_endpos_1 = 4 + + pileup1_startpos_2 = 3 + pileup1_endpos_2 = 3 + + pileup1_truncated_1 = [[{'C': 3}], [{'C': 3}], [{'C': 3}], [{'C': 3}], [{'C': 3}]] + + pileup1_truncated_2 = [[], [], [], [], []] + + pileup2 = [[{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 2 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{}, {'T': 2}, {}, {'G': 4}, {}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup2_startpos = 2 + pileup2_endpos = 4 + + pileup2_select_range_expected_out = [[{'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'C': 3}, {'G': 4}, {}], #test 2 + [{'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{}, {'G': 4}, {}], #test 4 + [{'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup2_truncate_expected_out = [[{'G': 4}], [{'G': 4}], [{'G': 4}], [{'G': 4}], [{'G': 4}]] + + #files for testing pileup matrix + pileup3 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 1 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 5 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}], #test 6 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {}, {'G': 8}], #test 7 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}, {'T': 6}, {'C': 7}, {'G': 8}]] #test 8 + + pileup3_remove_out = [[{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 1 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 2 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 3 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 4 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 5 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 6 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}], #test 7 + [{'T': 2}, {'C': 3}, {'A': 5}, {'T': 6}, {'G': 8}]] #test 8 + + pileup3_num_start_truncated = 1 + pileup3_num_end_truncated = 0 + + pileup4 = [[{'A': 1, 'T': 0, 'C': 0, 'G': 0}, # test 1 a + {'A': 0, 'T': 2, 'C': 0, 'G': 0}, # test 1 b + {'A': 0, 'T': 0, '-': 4, 'G': 0}], # test 1 c + [{'-': 1, 'T': 0, 'C': 0, 'G': 0}, # test 2 a + {'A': 0, 'T': 2, 'C': 0, 'G': 0}, # test 2 b + {'A': 0, '-': 5, 'C': 0, 'G': 0}]] # test 2 c + + pileup4_truncated_out = [[{'A': 0, 'T': 2, 'C': 0, 'G': 0}], #test 1 + [{'A': 0, 'T': 2, 'C': 0, 'G': 0}]] + + pileup4_num_start_truncated = 1 + pileup4_num_end_truncated = 1 + + pileup5 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}]] #test 5 + + pileup5_truncated_out = [[{'T': 2}], + [{'T': 2}], + [{'T': 2}], + [{'T': 2}], + [{'T': 2}]] + + pileup5_num_start_truncated = 1 + pileup5_num_end_truncated = 3 + + pileup6 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}]] #test 5 + + pileup6_truncated_out = [[{'C': 3}], + [{'C': 3}], + [{'C': 3}], + [{'C': 3}], + [{'C': 3}]] + + pileup6_num_start_truncated = 2 + pileup6_num_end_truncated = 2 + + pileup7 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}]] #test 5 + + pileup7_truncated_out = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}]] #test 5 + + pileup7_num_start_truncated = 0 + pileup7_num_end_truncated = 0 + + pileup8 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup8_truncated_out = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {}, {'C': 3}, {'G': 4}, {'A': 5}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup8_num_start_truncated = 0 + pileup8_num_end_truncated = 0 + + pileup9 = [[{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 2 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 3 + [{}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 4 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup9_truncated_out = [[{'T': 2}, {'C': 3}, {'G': 4}], #test 1 + [{'T': 2}, {'C': 3}, {'G': 4}], #test 2 + [{'T': 2}, {'C': 3}, {'G': 4}], #test 3 + [{'T': 2}, {'C': 3}, {'G': 4}], #test 4 + [{'T': 2}, {'C': 3}, {'G': 4}]] #test 5 + + pileup9_num_start_truncated = 1 + pileup9_num_end_truncated = 1 + + pileup10 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {}, {'G': 4}, {}], #test 4 + [{'A': 1}, {}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup10_truncated_out = [[{'A': 1}], #test 1 + [{'A': 1}], #test 2 + [{'A': 1}], #test 3 + [{'A': 1}], #test 4 + [{'A': 1}]] #test 5 + + pileup10_num_start_truncated = 0 + pileup10_num_end_truncated = 4 + + """""" + TESTS + """""" + @classmethod + def setup_class(self): + self.bam1 = TEST_PATH + '/data/quasi1.bam' + self.bam2 = TEST_PATH + '/data/quasi2.bam' + self.test_cp_files = (self.bam1, self.bam2) + self.test_cp_ref = TEST_PATH+'/data/hxb2_pol.fas' + self.references = parse_references_from_fasta(self.test_cp_ref) + + def test_construct_pileup_list(self): + """""" + test_construct_pileup_list - Checks that the pileup length and the + first few indices of the pileup are correct. + + INPUT: + [None] + + RETURN: + [None] + + POST: + [None] + """""" + + bamPileup = parse_pileup_list_from_bam(self.references, self.test_cp_files) + pileup_as_array = bamPileup.get_pileups_as_array() + pileup_as_numerical_array = bamPileup.get_pileups_as_numerical_array() + + assert len(pileup_as_array)==2 + assert len(pileup_as_array[0])==2844 + assert len(pileup_as_array[1])==2844 + assert len(pileup_as_numerical_array[0])==(2844 * 4) + assert len(pileup_as_numerical_array[1])==(2844 * 4) + assert pileup_as_array[0][0:10] == [{'C': 12}, {'C': 12}, {'T': 12}, {'C': 12}, {'G': 2, 'C': 3, 'T': 1, 'A': 6}, {'G': 12}, {'G': 12}, {'T': 12}, {'C': 12}, {'G': 2, 'C': 3, 'T': 1, 'A': 6}] + assert pileup_as_array[1][0:10] == [{'C': 12}, {'C': 12}, {'T': 12}, {'C': 12}, {'A': 6, 'C': 5, 'G': 1}, {'G': 12}, {'A': 4, 'G': 8}, {'T': 12}, {'C': 12}, {'A': 7, 'T': 1, 'C': 3, 'G': 1}] + #end def + + @pytest.mark.parametrize(""pileup,expected_truncated_pileup,expected_left_pos_truncated,expected_right_pos_truncated"", + [(pileup4, pileup4_truncated_out, pileup4_num_start_truncated, pileup4_num_end_truncated), + (pileup5, pileup5_truncated_out, pileup5_num_start_truncated, pileup5_num_end_truncated), + (pileup6, pileup6_truncated_out, pileup6_num_start_truncated, pileup6_num_end_truncated), + (pileup7, pileup7_truncated_out, pileup7_num_start_truncated, pileup7_num_end_truncated), + (pileup8, pileup8_truncated_out, pileup8_num_start_truncated, pileup8_num_end_truncated), + (pileup9, pileup9_truncated_out, pileup9_num_start_truncated, pileup9_num_end_truncated), + (pileup10, pileup10_truncated_out, pileup10_num_start_truncated, pileup10_num_end_truncated)]) + def test_truncate_output(self, pileup, expected_truncated_pileup, expected_left_pos_truncated, expected_right_pos_truncated): + """""" + test_truncate_output - Checks that the expected truncated outputs + matches the actual output. + + INPUT: + [2D ARRAY OF DICTIONARIES] [pileup] # to be truncated + [2D ARRAY OF DICTIONARIES] [expected_truncated_pileup] + [2D ARRAY OF DICTIONARIES] [expected_left_pos_truncated] + # number of contiguous left positions that were truncated + [2D ARRAY OF DICTIONARIES] [expected_right_pos_truncated] + # number of contiguous right positions that were truncated + + RETURN: + [None] + + POST: + Checks that the expected outputs match the actual output + """""" + pileups = Pileup_List([Pileup(bam) for bam in pileup]) + pileups.truncate_output() + truncated = pileups.get_pileups_as_array() + + assert truncated == expected_truncated_pileup + assert pileups.get_num_left_positions_truncated() == expected_left_pos_truncated + assert pileups.get_num_right_positions_truncated() == expected_right_pos_truncated + + @pytest.mark.parametrize(""pileup,expected_truncated_pileup,expected_left_pos_truncated,expected_right_pos_truncated"", + [(pileup3, pileup3_remove_out, pileup3_num_start_truncated, pileup3_num_end_truncated)]) + def test_remove_no_coverage(self, pileup, expected_truncated_pileup, expected_left_pos_truncated, expected_right_pos_truncated): + """""" + test_remove_no_coverage - Checks that the after truncating all + empty positions from the pileup that the output is as expected + + INPUT: + [2D ARRAY OF DICTIONARIES] [pileup] # to be truncated + [2D ARRAY OF DICTIONARIES] [expected_remove_no_coverage_pileup] + [2D ARRAY OF DICTIONARIES] [expected_left_pos_truncated] + # number of contiguous left positions that were truncated + [2D ARRAY OF DICTIONARIES] [expected_right_pos_truncated] + # number of contiguous right positions that were truncated + + RETURN: + [None] + + POST: + Checks that the expected outputs match the actual output + """""" + pileups = Pileup_List([Pileup(bam) for bam in pileup]) + pileups.remove_no_coverage() + truncated = pileups.get_pileups_as_array() + + assert truncated == expected_truncated_pileup + assert pileups.get_num_left_positions_truncated() == expected_left_pos_truncated + assert pileups.get_num_right_positions_truncated() == expected_right_pos_truncated + + @pytest.mark.parametrize(""pileup,startpos,endpos,expected_remove_no_coverage"", + [(pileup1, 2, 4, pileup1_truncated_1), + (pileup1, 3, 3, pileup1_truncated_2)]) + def test_select_pileup_range_and_remove_no_coverage(self, pileup, startpos, endpos, expected_remove_no_coverage): + """""" + select_pileup_range_and_truncate_output - Checks if the program works + as expected when removing all no coverage regions after first selecting + a specified range. + + INPUT: + [2D ARRAY of DICTIONARIES] [pileup] + [INT] [startpos] + [INT] [endpos] + [2D ARRAY OF DICTIONARIES] [expected_remove_no_coverage] + + RETURN: + TODO + POST: + TODO + """""" + + pileups = Pileup_List([Pileup(bam) for bam in pileup]) + pileups.select_pileup_range(startpos, endpos) + pileups.remove_no_coverage() + truncated = pileups.get_pileups_as_array() + + assert truncated == expected_remove_no_coverage + + @pytest.mark.parametrize(""pileup,startpos,endpos,pileup_select_range_expected_out,pileup_truncate_expected_out"", + [(pileup2, 2, 4, pileup2_select_range_expected_out, pileup2_truncate_expected_out)]) + def select_pileup_range_and_truncate_output(self, pileup, startpos, endpos, pileup_select_range_expected_out, pileup_truncate_expected_out): + """""" + select_pileup_range_and_truncate_output - Checks if the program works + as expected when truncating contiguous start and end regions after + first selecting a specified range. + + INPUT: + [2D ARRAY of DICTIONARIES] [pileup] + [INT] [startpos] + [INT] [endpos] + [2D ARRAY OF DICTIONARIES] [pileup_select_range_expected_out] + [2D ARRAY OF DICTIONARIES] [pileup_truncate_expected_out] + RETURN: + TODO + POST: + TODO + """""" + + pileups = Pileup_List([Pileup(bam) for bam in pileup]) + pileups.select_pileup_range(startpos, endpos) + select_pileup = pileups.get_pileups_as_array() + + # assert that the pileup positions before startpos and after endpos + # have been ignored + assert select_pileup == pileup_select_range_expected_out + + pileups.truncate_output() + truncated_pileup = pileups.get_pileups_as_array() + + # assert that the pileup is truncated now as expected + assert truncated_pileup == pileup_truncate_expected_out +","Python" +"Microbiology","phac-nml/quasitools","tests/test_nt_variant.py",".py","3726","78",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import copy +from quasitools.nt_variant import NTVariant, NTVariantCollection +from quasitools.parsers.reference_parser import parse_references_from_fasta + +class TestNTVariant: + @classmethod + def setup_class(self): + self.variant = NTVariant('hxb2_pol',1,ref='g',alt='t',qual='30',filter='PASS',info={'DP':400,'AC':12,'AF':0.03}) + + def test_to_vcf_entry(self): + assert self.variant.to_vcf_entry() == 'hxb2_pol\t1\t.\tg\tt\t30\tPASS\tDP=400;AC=12;AF=0.0300' + +class TestNTVariantCollection: + @classmethod + def setup_class(self): + self.references = parse_references_from_fasta('tests/data/ref1.fasta') + self.variant_collection = NTVariantCollection(self.references) + + self.variant_collection.variants['ref1']['3']['t'] = NTVariant(chrom='ref1', pos=3, ref='c', alt='t', qual=30, info={'DP':400,'AC':12,'AF':0.03}) + self.variant_collection.variants['ref1']['10']['a'] = NTVariant(chrom='ref1', pos=10, ref='a', alt='t', qual=23, info={'DP':200,'AC':7,'AF':0.035}) + + def test_from_mapped_read_collections(self): + #TODO: add actual test for Variants.from_mapped_reads method + assert True + + def test_to_vcf_file(self): + vcf_file_string = self.variant_collection.to_vcf_file() + + assert ""##fileformat=VCFv4.2"" in vcf_file_string + assert ""##fileDate="" in vcf_file_string + assert ""##source=quasitools"" in vcf_file_string + assert ""##INFO="" in vcf_file_string + assert ""##INFO="" in vcf_file_string + assert ""##INFO="" in vcf_file_string + assert ""#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"" in vcf_file_string + assert ""ref1\t3\t.\tc\tt\t30\t.\tDP=400;AC=12;AF=0.0300"" in vcf_file_string + assert ""ref1\t10\t.\ta\tt\t23\t.\tDP=200;AC=7;AF=0.0350"" in vcf_file_string + + def test_calculate_variant_qual(self): + qual1 = self.variant_collection._NTVariantCollection__calculate_variant_qual(0.01, 12, 400) + qual2 = self.variant_collection._NTVariantCollection__calculate_variant_qual(0.01, 7, 200) + + assert qual1 == 30 + assert qual2 == 23 + + def test_filter(self): + variant_collection_copy = copy.deepcopy(self.variant_collection) + + variant_collection_copy.filter('q30', 'QUAL<30', True) + assert variant_collection_copy.variants['ref1']['3']['t'].filter == 'PASS' + assert variant_collection_copy.variants['ref1']['10']['a'].filter == 'q30' + + variant_collection_copy.filter('ac5', 'AC<5', True) + assert variant_collection_copy.variants['ref1']['3']['t'].filter == 'PASS' + assert variant_collection_copy.variants['ref1']['10']['a'].filter == 'q30' + + variant_collection_copy.filter('dp100', 'DP<100', True) + assert variant_collection_copy.variants['ref1']['3']['t'].filter == 'PASS' + assert variant_collection_copy.variants['ref1']['10']['a'].filter == 'q30' +","Python" +"Microbiology","phac-nml/quasitools","tests/__init__.py",".py","0","0","","Python" +"Microbiology","phac-nml/quasitools","tests/test_reference.py",".py","919","28",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +from quasitools.reference import Reference + +class TestReference: + @classmethod + def setup_class(self): + self.reference = Reference('gattaca', 'gattaca') + + def test_sub_seq(self): + assert self.reference.sub_seq(1,5) == 'attac' +","Python" +"Microbiology","phac-nml/quasitools","tests/test_utilities.py",".py","1723","45",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +from quasitools.utilities import * +from quasitools.reference import Reference +from pysam import AlignedSegment + +def test_sam_alignment_to_padded_alignment(): + alignment = AlignedSegment() + alignment.reference_start = 0 + alignment.query_sequence = 'AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG' + alignment.cigartuples = ((0,10), (2,1), (0,25)) + ref = Reference('test', 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG') + + (pad_ref, pad_match, pad_query) = sam_alignment_to_padded_alignment(alignment, ref) + + assert pad_ref == 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG' + assert pad_match == '|||||||||| |||||||||||||||||||||||||' + assert pad_query == 'AGCTTAGCTA-GCTACCTATATCTTGGTCTTGGCCG' + +def test_pairwise_alignment_to_differences(): + ref = Reference('test', 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG') + pad_ref = 'AGCTTAGCTAAGCTACCTATATCTTGGTCTTGGCCG' + pad_query = 'AGCTTAGCTA-GCTACCTATATCTTGGTCTTGGCCG' + ref_start = 0 + + differences = pairwise_alignment_to_differences(pad_ref, pad_query, ref_start) + + assert differences == {10: '-'} +","Python" +"Microbiology","phac-nml/quasitools","tests/test_genes_parser.py",".py","2703","74",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.parsers.genes_file_parser import parse_BED4_file + +class TestGenesFileParser: + def test_valid_BED4_file(self): + """"""Tests to make sure that valid BED4+ files (bed files with at least 4 + columns) are parsed properly. + """""" + + # Create a valid BED4 file + valid_BED4_file = os.path.join(os.path.dirname( + os.path.abspath(__file__)), ""data"", ""valid_BED4_file.bed"") + + ref_name = ""ref1"" + + genes = {""gene1"": {""start"": 0, ""end"": 100}, + ""gene 2"": {""start"": 101, ""end"": 200}, # Spaces are allowed in the gene name + ""gene3"": {""start"": 201, ""end"": 300}} + + with open(valid_BED4_file, ""w+"") as f: + for gene in genes: + f.write(""%s\t%s\t%s\t%s\n"" % (ref_name, genes[gene][""start""], + genes[gene][""end""], gene)) + + parsed_genes = parse_BED4_file(valid_BED4_file, ref_name) + + for gene in parsed_genes: + assert gene in genes + assert parsed_genes[gene][""start""] == genes[gene][""start""] + assert parsed_genes[gene][""end""] == genes[gene][""end""] + assert parsed_genes[gene][""frame""] == genes[gene][""start""] % 3 + + os.remove(valid_BED4_file) + + def test_invalid_BED4_file(self): + """"""Tests to make sure that an exception is raised when attempting to + parse an invalid BED4 file. + """""" + + # Create an invalid genes file + invalid_BED4_file = os.path.join(os.path.dirname( + os.path.abspath(__file__)), ""data"", ""invalid_BED4_file.bed"") + + ref_name = ""ref1"" + + with open(invalid_BED4_file, ""w+"") as f: + f.write(""%s\t0\t100\t0\n"" % ref_name) + # Add a genes reference name that doesn't match + # This should raise a ValueError + f.write(""different_reference\t101\t200\t2"") + + with pytest.raises(ValueError): + parse_BED4_file(invalid_BED4_file, ref_name) + + os.remove(invalid_BED4_file) +","Python" +"Microbiology","phac-nml/quasitools","tests/test_nt_variant_parser.py",".py","5066","111",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.parsers.nt_variant_file_parser import parse_nt_variants_from_vcf +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.nt_variant import NTVariant, NTVariantCollection + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + +class TestNtVariantParser: + def test_valid_vcf_file(self): + """"""Tests to ensure that valid vcf files are parsed properly."""""" + + reference = TEST_PATH + \ + ""/data/hxb2_pol.fas"" + bam = TEST_PATH + ""/data/align.bam"" + + rs = parse_references_from_fasta(reference) + + mapped_read_collection_arr = [] + for r in rs: + # Create a MappedReadCollection object + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + variants_obj = NTVariantCollection(rs) + + for i in range(0, 20): + variant = NTVariant(chrom=""hxb2_pol"", + pos=i, + id=""."", + ref='a', + alt='t', + qual=""50"", + filter=""PASS"", + info={""DP"": ""300"", + ""AC"": ""1"", + ""AF"": ""0.0025""} + ) + + variants_obj.variants[""hxb2_pol""][i]['t'] = variant + + #Create a valid vcf file + valid_vcf_file = TEST_PATH + ""/data/valid_vcf_file.vcf"" + + with open(valid_vcf_file, ""w+"") as f: + f.write(""##fileformat=VCFv4.2\n"" + ""##fileDate=20171005\n"" + ""##source=quasitools\n"" + ""##INFO=\n"" + ""##INFO=\n"" + ""##INFO=\n"" + ""##FILTER=\n"" + ""##FILTER=\n"" + ""##FILTER=\n"" + ""#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO"" + ) + + for rid in variants_obj.variants: + for pos in variants_obj.variants[rid]: + for alt in variants_obj.variants[rid][pos]: + variant = variants_obj.variants[rid][pos][alt] + f.write(""\n%s\t%i\t%s\t%s\t%s\t%s\t%s"" % ( + variant.chrom, int(variant.pos), + variant.id, variant.ref, + variant.alt, variant.qual, + variant.filter) ) + f.write(""\tDP=%i;AC=%i;AF=%0.4f"" % (int(variant.info[""DP""]), + int(variant.info[""AC""]), + float(variant.info[""AF""]))) + + parsed_nt_var = parse_nt_variants_from_vcf(valid_vcf_file, rs) + + # Check equality of parsed NTVariantCollection vs. the valid NTVariantCollection + for rid in parsed_nt_var.variants: + for pos in parsed_nt_var.variants[rid]: + for alt in parsed_nt_var.variants[rid][pos]: + parsed_variant = parsed_nt_var.variants[rid][pos][alt] + variant = variants_obj.variants[rid][pos][alt] + + assert parsed_variant.chrom == variant.chrom + assert parsed_variant.pos == variant.pos + assert parsed_variant.id == variant.id + assert parsed_variant.ref == variant.ref + assert parsed_variant.alt == variant.alt + assert parsed_variant.qual == variant.qual + assert parsed_variant.filter == variant.filter + assert parsed_variant.info[""DP""] == variant.info[""DP""] + assert parsed_variant.info[""AC""] == variant.info[""AC""] + assert parsed_variant.info[""AF""] == variant.info[""AF""] + + os.remove(valid_vcf_file) +","Python" +"Microbiology","phac-nml/quasitools","tests/test_dnds.py",".py","2173","65",""""""" +Copyright Government of Canada 2015 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pdb +import pytest +import os +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.codon_variant_file_parser import parse_codon_variants + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +VALID_DNDS_REPORT = TEST_PATH + ""/data/output/dnds_report.csv"" + +class TestDnds: + @classmethod + def setup(self): + csv = TEST_PATH + ""/data/output/mutant_types.csv"" + reference = TEST_PATH + ""/data/hxb2_pol.fas"" + self.offset = 1269 + + rs = parse_references_from_fasta(reference) + self.ref_seq = rs[0].seq + + self.codon_variants = parse_codon_variants(csv, rs) + + + def test_dnds(self): + # Read from file and make sure there are no empty lines + with open(VALID_DNDS_REPORT, ""r"") as input: + valid_report = input.read() + + # Sort and filter for comparison + valid_dnds_values = sorted(filter(None, + valid_report.split(""\n""))) + + # Create the report string + test_report = self.codon_variants.report_dnds_values(self.ref_seq, self.offset) + + # Split into lines and sort + test_values = sorted(test_report.split(""\n"")) + + assert len(valid_dnds_values) == len(test_values) + + # Compare each line in the test report to the valid report + for pos in range(0, len(valid_dnds_values)): + if valid_dnds_values[pos][0:1] != ""#"": + assert valid_dnds_values[pos] == \ + test_values[pos] + +","Python" +"Microbiology","phac-nml/quasitools","tests/test_mutation_db.py",".py","1779","61",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.mutations import MutationDB +from quasitools.parsers.genes_file_parser import parse_BED4_file + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + +class TestMutationDB: + @classmethod + def setup_class(self): + BED4_file = TEST_PATH + ""/data/hxb2_pol.bed"" + mutation_db_file = TEST_PATH + ""/data/mutation_db.tsv"" + + genes = parse_BED4_file(BED4_file, ""hxb2_pol"") + + self.mutation_db = MutationDB(mutation_db_file, genes) + + def test_mutations_at(self): + + # Our pos is one less than the mutation db file since our first + # position is 0 but the files is 1 + pos = 9 + mutations = [""F"", ""I"", ""V"", ""R"", ""Y""] + + mutations_at_pos = self.mutation_db.mutations_at(pos) + + assert len(mutations_at_pos) == 5 + + for mutation in mutations: + assert mutation in mutations_at_pos + + def test_positions(self): + + positions = self.mutation_db.positions() + + assert len(positions) == 96 + + assert positions[0] == 9 + + assert positions[30] == 142 + + assert positions[-1] == 921 +","Python" +"Microbiology","phac-nml/quasitools","tests/test_quality_control.py",".py","14072","431",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import shutil +from collections import defaultdict +import pytest +from quasitools.patient_analyzer import PatientAnalyzer +from quasitools.quality_control import QualityControl +import Bio.SeqIO +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +READS = TEST_PATH + ""/data/reads_w_K103N.fastq"" +OUTPUT_DIR = TEST_PATH + ""/test_quality_control_output"" +FILTERED_DIR = OUTPUT_DIR + ""/filtered.fastq"" + +# globals + +from quasitools.quality_control import TRIMMING + +# used for masking +from quasitools.quality_control import MASKING +from quasitools.quality_control import MASK_CHARACTER +from quasitools.quality_control import MIN_READ_QUAL + +# used in quality_control.passes_filters +from quasitools.quality_control import LENGTH_CUTOFF +from quasitools.quality_control import MEDIAN_CUTOFF +from quasitools.quality_control import MEAN_CUTOFF +from quasitools.quality_control import NS + +# used in qaulity_control.passes_filters +from quasitools.quality_control import PASS +from quasitools.quality_control import FAIL_LENGTH +from quasitools.quality_control import FAIL_SCORE +from quasitools.quality_control import FAIL_NS + +class TestQualityControl: + @classmethod + def setup_class(self): + # Test defaults + self.quality_control = QualityControl() + if not os.path.isdir(OUTPUT_DIR): + os.mkdir(OUTPUT_DIR) + + @pytest.fixture + def filters(self): + filtering = defaultdict(dict) + + filtering[TRIMMING] = True + filtering[MASKING] = True + + filtering[LENGTH_CUTOFF] = 2 + filtering[MEAN_CUTOFF] = 30 + filtering[MIN_READ_QUAL] = 30 + #filtering[NS] = True + + return filtering + + def test_get_median_score(self): + """""" + test_get_median_score - Checks that the function correctly calculates + median score + + INPUT: + [None] + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [35, 30, 50, 70] + + assert self.quality_control.get_median_score(seq_record) == 40 + + seq = Seq(""CAT"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [35, 30, 50] + + assert self.quality_control.get_median_score(seq_record) == 30 + + def test_get_mean_score(self): + """""" + test_get_mean_score - Checks that the function correctly calculates + mean score + + INPUT: + [None] + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [20, 40, 60, 80] + + assert self.quality_control.get_mean_score(seq_record) == 50 + + def test_filter_and_trim_reads(self, filters): + """""" + test_filter_and_trim_reads - Checks that the reads have been trimmed + until all filters pass or read falls below length cutoff and that this + result is reflected in the filtered read saved to file by filter reads + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [30, 30, 3, 1] + + filters[MASKING] == False + filters[TRIMMING] = True + + INPUT_DIR = TEST_PATH + ""/data/sample_filter.fastq"" + + Bio.SeqIO.write(seq_record, INPUT_DIR, ""fastq"") + + self.quality_control.filter_reads(INPUT_DIR, FILTERED_DIR, filters) + + # there should be only one object in the seq_rec_obj iterable + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + recs = list(seq_rec_obj) + assert len(recs) == 1 + assert len(recs[0].seq) == 2 + + def test_trim_reads(self, filters): + """""" + test_trim_reads - Checks that the reads have been trimmed until all + filters pass or read falls below length cutoff + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [30, 30, 3, 1] + + filters[MASKING] == False + filters[TRIMMING] = True + trimmed_read = self.quality_control.trim_read(seq_record, filters) + + assert len(trimmed_read.seq) == 2 + + def test_filter_and_mask_reads(self, filters): + """""" + test_filter_and_mask_reads - Checks that all low coverage regions have + been masked with an N and that this result is + reflected in the filtered read saved to file by filter reads + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [30, 30, 3, 1] + + filters[TRIMMING] = False + filters[MASKING] == True + filters[NS] = False + # we are not testing any other functions that will be called when + # score < MEAN_CUTOFF, only testing masking, so we set below filter val + # to 0 + filters[MEAN_CUTOFF] = 0 + + INPUT_DIR = TEST_PATH + ""/data/sample_mask.fastq"" + + Bio.SeqIO.write(seq_record, INPUT_DIR, ""fastq"") + + self.quality_control.filter_reads(INPUT_DIR, FILTERED_DIR, filters) + + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + recs = list(seq_rec_obj) + assert len(recs) == 1 + # there should be only one object in the seq_rec_obj iterable + assert len(recs[0].seq) == 4 + assert recs[0].seq[0:4] == 'GANN' + + def test_mask_reads(self, filters): + """""" + test_mask_reads - Checks that all low coverage regions have been + masked with an N. + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.id = ""first"" + seq_record.letter_annotations[""phred_quality""] = [30, 30, 3, 1] + + filters[TRIMMING] = False + filters[MASKING] == True + filters[NS] = False + self.quality_control.mask_read(seq_record, filters) + + assert len(seq_record.seq) == 4 + assert seq_record.seq[0:4] == 'GANN' + + def test_passes_filters(self, filters): + """""" + test_passes_filters - Checks that the correct status is returned if + the read fails to pass at least one of the filters + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + failed_status = {0: ""success"", 1: ""length"", 2: ""score"", 3: ""ns""} + + # sample Biopython read for testing + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [35, 3, 5, 7] + key = self.quality_control.passes_filters(seq_record, filters) + assert key == FAIL_SCORE # did not pass filters due + # to score + + seq = Seq(""G"") + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [35] + key = self.quality_control.passes_filters(seq_record, filters) + assert key == FAIL_LENGTH # did not pass filters due + # to score + + # test where multiple characters are already masked due to low quality + filters[NS] = True # turn on filtering of ns in the sequence + filters[MASKING] = False # turn off masking of low coverage regions + seq = Seq(""GNNN"") + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [80, 20, 20, 20] + key = self.quality_control.passes_filters(seq_record, filters) + assert key == FAIL_NS # did not pass filters due to + # score + + def test_filter_reads_with_mean_score(self, filters): + """""" + test_filter_reads_with_mean_score - Checks that the filter_reads + function performs as expected with iterative trimming and/or masking + enabled. This includes testing with the mean used for score. + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + # test with iterative trimming and masking enabled + + # sample Biopython reads for testing + seq_record_list = [] + seq = Seq(""GATC"") + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [35, 3, 5, 7] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [4, 3, 5, 7] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [29, 29, 29, 29] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [35, 30, 50, 70] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [30, 33, 35, 30] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [30, 30, 30, 30] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [29, 29, 31, 31] + seq_record_list.append(seq_record) + + INPUT_DIR = TEST_PATH+""/data/sample_mean.fastq"" + + Bio.SeqIO.write(seq_record_list, INPUT_DIR, ""fastq"") + + self.quality_control.filter_reads(INPUT_DIR, FILTERED_DIR, filters) + + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + assert(sum(1 for seq in seq_rec_obj) == 4) + + self.quality_control.filter_reads(INPUT_DIR, FILTERED_DIR, filters) + + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + + for read in seq_rec_obj: + mean = (float(sum(read.letter_annotations['phred_quality'])) / + float(len(read.letter_annotations['phred_quality']))) + + assert mean >= filters[MEAN_CUTOFF] + + for base_pos in range(0, len(read.seq)): + if (read.letter_annotations['phred_quality'][base_pos] + < filters[MIN_READ_QUAL]): + assert read.seq[base_pos] == MASK_CHARACTER + + def test_filter_reads_with_median_score(self, filters): + """""" + test_filter_reads_with_median_score - Checks that the filter_reads + function performs as expected with iterative trimming and/or masking + enabled. This includes testing with the median used for score. + + INPUT: + [dict] [filters] # provided with fixture + + RETURN: + [None] + + POST: + [None] + """""" + # test with iterative trimming and masking enabled + # tests with median_cutoff used instead of mean_cutoff + filters[MEDIAN_CUTOFF] = 30 + del filters[MEAN_CUTOFF] + + INPUT_DIR = TEST_PATH+""/data/sample2.fastq"" + + # more sample Biopython reads for testing + seq_record_list = [] + seq = Seq(""GATC"") + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [35, 30, 50, 10] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [29, 30, 29, 29] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [29, 29, 30, 29] + seq_record_list.append(seq_record) + + seq_record = SeqRecord(seq) + seq_record.letter_annotations[""phred_quality""] = [29, 29, 29, 29] + seq_record_list.append(seq_record) + + + Bio.SeqIO.write(seq_record_list, INPUT_DIR, ""fastq"") + self.quality_control.filter_reads(INPUT_DIR, FILTERED_DIR, filters) + seq_rec_obj = Bio.SeqIO.parse(FILTERED_DIR, ""fastq"") + + for read in seq_rec_obj: + length = len(read.seq) + + scores = list(read.letter_annotations['phred_quality']) + if length % 2 == 0: + median_score = ((scores[int((length - 1) // 2)] + + scores[int((length - 1) // 2) + 1]) / 2) + else: + median_score = scores[int((length - 1) // 2)] + + assert self.quality_control.get_median_score(read) >= \ + filters.get(MEDIAN_CUTOFF) + + for base_pos in range(0, len(read.seq)): + if (read.letter_annotations['phred_quality'][base_pos] + < filters[MIN_READ_QUAL]): + assert read.seq[base_pos] == MASK_CHARACTER +","Python" +"Microbiology","phac-nml/quasitools","tests/test_cli.py",".py","6931","156",""""""" +Copyright Government of Canada 2015 + +Written by: Eric Enns, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import pytest +from click.testing import CliRunner +from quasitools import cli + +# GLOBALS +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +REF = TEST_PATH + '/data/hxb2_pol.fas' +BAM1 = TEST_PATH + '/data/quasi1.bam' +BAM2 = TEST_PATH + '/data/quasi2.bam' +FORWARD = TEST_PATH + '/data/forward.fastq' +REVERSE = TEST_PATH + '/data/reverse.fastq' + +@pytest.fixture +def runner(): + return CliRunner() + +def test_cli(runner): + result = runner.invoke(cli.cli) + assert result.exit_code == 0 + assert not result.exception + assert result.output.split('\n', 1)[0].strip() == 'Usage: cli [OPTIONS] COMMAND [ARGS]...' + +def test_cli_distance(runner): + """""" + test_cli_distance - Checks that if there are errors the correct exit + code is raised. + + INPUT: + [None] + RETURN: + [None] + POST: + [None] + """""" + + # tests that are expected to pass + + result = runner.invoke(cli.cli, ['distance', REF]) + assert result.exit_code == 2 # test expected to fail + assert result.exception # exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1]) + assert result.exit_code == 2 # test expected to fail + assert result.exception # exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2]) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '--output', '--keep_no_coverage']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 1', '-e 1', '--output', '--keep_no_coverage']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 1', '-e 2844', '--output', '--keep_no_coverage']) + assert result.exit_code == 0 # test expected to succeed, UsageError raised + assert not result.exception # no exception should be raised + + # tests that are expected to fail + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 0', '-e 2844', '--output', '--keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s -1', '-e 0', '--output', '--keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 1', '-e 2845', '--output', '--keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 2845', '-e 2846', '--output', '--keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, BAM1, BAM2, '--normalize', '--output_distance', '-s 100', '-e 99', '--output', '----keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + + result = runner.invoke(cli.cli, ['distance', REF, '--normalize', '--output_distance', '-s 1', '-e 2844', '--output', '--keep_no_coverage']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # no exception should be raised + +def test_cli_quality(runner): + """""" + test_cli_quality - Adds tests to cli + + INPUT: + [None] + RETURN: + [None] + POST: + [None] + """""" + + result = runner.invoke(cli.cli, ['quality', FORWARD, REVERSE, '-o', 'test_cli_quality']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # exception should not be raised + + result = runner.invoke(cli.cli, ['quality', FORWARD, REVERSE, '-o', 'test_cli_quality', '-tr', '-mr', '-me', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # exception should not be raised + + result = runner.invoke(cli.cli, ['quality', FORWARD, REVERSE, '-o', 'test_cli_quality', '-tr', '-me', '-n', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # exception should not be raised + + result = runner.invoke(cli.cli, ['quality', FORWARD, REVERSE, '-o', 'test_cli_quality', '-tr', '-mr', '-me', '-n', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 2 # test expected to fail, UsageError raised + assert result.exception # exception should be raised + + +def test_cli_hydra(runner): + """""" + test_cli_hydra - Adds tests to cli + + INPUT: + [None] + RETURN: + [None] + POST: + [None] + """""" + result = runner.invoke(cli.cli, ['hydra', FORWARD, REVERSE, '-o', 'test_cli_hydra', '-tr', '-mr', '-me', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # exception should not be raised + + result = runner.invoke(cli.cli, ['hydra', FORWARD, REVERSE, '-o', 'test_cli_hydra', '-tr', '-me', '-n', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 0 # test expected to pass + assert not result.exception # exception should not be raised + + result = runner.invoke(cli.cli, ['hydra', FORWARD, REVERSE, '-o', 'test_cli_hydra', '-tr', '-mr', '-me', '-n', '-sc', '30', '-lc', '100', '-rq', '30']) + assert result.exit_code == 2 # # test expected to fail, UsageError raised + assert result.exception # exception should be raised +","Python" +"Microbiology","phac-nml/quasitools","tests/test_codon_variant.py",".py","8890","186",""""""" +Copyright Government of Canada 2015 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pdb +import pytest +import os +from quasitools.codon_variant import CodonVariant, CodonVariantCollection +from quasitools.nt_variant import NTVariant, NTVariantCollection +from quasitools.aa_census import AACensus +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.codon_variant_file_parser import parse_codon_variants +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.genes_file_parser import parse_BED4_file + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + +class TestCodonVariant: + @classmethod + def setup_class(self): + self.offset = 1269 + self.variant = CodonVariant( + chrom=""hxb2_pol"", + pos=1, + gene=""gag"", + nt_start_gene=1309, + nt_end_gene=2841, + nt_start=2077, + nt_end=2079, + ref_codon=""ata"", + mutant_codon=""aAa"", + ref_aa=""I"", + mutant_aa=""K"", + coverage=563, + mutant_freq=1.60, + mutant_type=""S"", + ns_count=1.0000, + s_count=1.5000) + + def test_to_csv_entry(self): + assert self.variant.to_csv_entry(self.offset) == ( + ""gag,%i-%i,%i,%i,ata,aAa,I,K,563,1.60,S,1.0000,1.5000\n"" % ( + 1309+self.offset, 2841+self.offset, 2077+self.offset, 2079+self.offset) ) + +class TestCodonVariantCollection: + @classmethod + def setup_class(self): + self.reference = TEST_PATH + ""/data/hxb2_pol.fas"" + self.references = parse_references_from_fasta(self.reference) + self.variant_collection = CodonVariantCollection(self.references) + self.offset = 1269 + + self.variant_collection.variants['gag']['3']['aTa'] = CodonVariant( + chrom=""hxb2_pol"", + pos=1, + gene=""gag"", + nt_start_gene=1309, + nt_end_gene=2841, + nt_start=2077, + nt_end=2079, + ref_codon=""ata"", + mutant_codon=""aTa"", + ref_aa=""I"", + mutant_aa=""K"", + coverage=563, + mutant_freq=1.60, + mutant_type=""S"", + ns_count=1.0000, + s_count=1.5000) + self.variant_collection.variants['tat']['10']['aAa'] = CodonVariant( + chrom=""hxb2_pol"", + pos=2, + gene=""tat"", + nt_start_gene=3309, + nt_end_gene=4841, + nt_start=4000, + nt_end=4002, + ref_codon=""ata"", + mutant_codon=""aAa"", + ref_aa=""I"", + mutant_aa=""K"", + coverage=563, + mutant_freq=1.60, + mutant_type=""S"", + ns_count=1.0000, + s_count=1.5000) + + def test_from_aacensus(self): + bam = TEST_PATH + ""/data/align.bam"" + BED4_file = TEST_PATH + ""/data/hxb2_pol.bed"" + mapped_read_collection_arr = [] + error_rate = 0.0038 + + # Create a MappedReadCollection object + for r in self.references: + mapped_read_collection_arr.append(parse_mapped_reads_from_bam(r, bam)) + + variants = NTVariantCollection.from_mapped_read_collections( + error_rate, self.references, *mapped_read_collection_arr) + variants.filter('q30', 'QUAL<30', True) + variants.filter('ac5', 'AC<5', True) + variants.filter('dp100', 'DP<100', True) + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants) + + # Parse the genes from the gene file + genes = parse_BED4_file(BED4_file, self.references[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + aa_census = AACensus(self.reference, mapped_read_collection_arr, genes, frames) + + test_variants = CodonVariantCollection.from_aacensus(aa_census) + ref_seq = self.references[0].seq + + for gene in test_variants.variants: + assert gene in genes + for pos in test_variants.variants[gene]: + for frame in frames: + nt_pos = pos/3 - frame + assert nt_pos >= genes[gene]['start'] or nt_pos <= genes[gene]['end'] + for codon in test_variants.variants[gene][pos]: + ref_codon = ref_seq[(pos):(pos) + 3].lower() + assert codon != ref_codon + + def test_to_csv_file(self): + csv_file_string = self.variant_collection.to_csv_file(self.offset) + # pdb.set_trace() + assert ( ""#gene,nt position (gene),nt start position,nt end position,"" + ""ref codon,mutant codon,ref AA,mutant AA,coverage,mutant frequency,"" + ""mutant type,NS count,S count"" ) in csv_file_string + assert ( ""gag,%i-%i,%i,%i,ata,aTa,I,K,563,1.60,S,1.0000,1.5000"" % ( + 1309+self.offset, 2841+self.offset, 2077+self.offset, 2079+self.offset) ) in csv_file_string + assert ( ""tat,%i-%i,%i,%i,ata,aAa,I,K,563,1.60,S,1.0000,1.5000"" % ( + 3309+self.offset, 4841+self.offset, 4000+self.offset, 4002+self.offset) ) in csv_file_string + + def test_report_dnds_values(self): + valid_dnds_report = TEST_PATH + ""/data/output/dnds_report.csv"" + csv = TEST_PATH + ""/data/output/mutant_types.csv"" + ref_seq = self.references[0].seq + codon_variants = parse_codon_variants(csv, self.references) + + # Read from file and make sure there are no empty lines + with open(valid_dnds_report, ""r"") as input: + valid_report = input.read() + + # Sort and filter for comparison + valid_dnds_values = sorted(filter(None, + valid_report.split(""\n""))) + + # Create the report string + test_report = codon_variants.report_dnds_values(ref_seq, self.offset) + + # Split into lines and sort + test_values = sorted(test_report.split(""\n"")) + + assert len(valid_dnds_values) == len(test_values) + + # Compare each line in the test report to the valid report + for pos in range(0, len(valid_dnds_values)): + if valid_dnds_values[pos][0:1] != ""#"": + assert valid_dnds_values[pos] == \ + test_values[pos] + +","Python" +"Microbiology","phac-nml/quasitools","tests/test_distance.py",".py","12865","246",""""""" +Copyright Government of Canada 2018 + +Written by: Matthew Fogel, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.distance import DistanceMatrix +from quasitools.pileup import Pileup_List +from quasitools.pileup import Pileup + +class TestDistance: + + """""" + CLASS VARIABLES + """""" + + pileup0 = [[{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {'A': 5}], #test 1 + [{'A': 1}, {'T': 2}, {'C': 3}, {'G': 4}, {}], #test 2 + [{'A': 1}, {'T': 2}, {'C': 3}, {}, {'A': 5}], #test 3 + [{'A': 1}, {'T': 2}, {}, {'G': 4}, {}], #test 4 + [{'A': 1}, {}, {'C': 3}, {'G': 4}, {'A': 5}]] #test 5 + + pileup0_files = ('test1.bam', 'test2.bam', 'test3.bam', 'test4.bam', 'test5.bam') + + pileup0_truncate_out = [[{'A': 1}], #test 1 + [{'A': 1}], #test 2 + [{'A': 1}], #test 3 + [{'A': 1}], #test 4 + [{'A': 1}]] #test 5 + + pileup0_normal_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam +test1.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test2.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test3.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test4.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test5.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000"""""" + + pileup0_unnormal_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam +test1.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test2.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test3.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test4.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000 +test5.bam,1.00000000,1.00000000,1.00000000,1.00000000,1.00000000"""""" + + pileup0_normal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam +test1.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test2.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test3.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test4.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test5.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000"""""" + + pileup0_unnormal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam +test1.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test2.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test3.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test4.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000 +test5.bam,0.00000000,0.00000000,0.00000000,0.00000000,0.00000000"""""" + + pileup0_startpos = 0 + pileup0_endpos = 0 + + #files for testing pileup matrix + pileup1 = [[{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1, 'T': 1, 'C': 1}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test1 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1, 'T': 1, 'C': 1000000}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test2 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1, 'T': 1000000, 'C': 1}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test3 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1000000, 'T': 1, 'C': 1}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test4 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1000000, 'T': 1, 'C': 1000000}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test5 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1000000, 'T': 1000000, 'C': 1}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test6 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1, 'T': 1000000, 'C': 1000000}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}], #test7 + [{'A': 1, 'T': 1, 'C': 1, 'G': 1}, {'A': 1000000, 'T': 1000000, 'C': 1000000}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}, {'T': 12}, {'C': 12}, {'G': 12}, {'A': 12}]] #test8 + + pileup1_files = ('test1.bam', 'test2.bam', 'test3.bam', 'test4.bam', 'test5.bam', 'test6.bam', 'test7.bam', 'test8.bam') + + #expected output files for pileup1 + + pileup1_normal_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam,test6.bam,test7.bam,test8.bam +test1.bam,1.00000000,0.96329037,0.96329037,0.96329037,0.99043043,0.99043043,0.99043043,1.00000000 +test2.bam,0.96329037,1.00000000,0.89189249,0.89189249,0.97259768,0.91702091,0.97259768,0.96329037 +test3.bam,0.96329037,0.89189249,1.00000000,0.89189249,0.91702091,0.97259768,0.97259768,0.96329037 +test4.bam,0.96329037,0.89189249,0.89189249,1.00000000,0.97259768,0.97259768,0.91702091,0.96329037 +test5.bam,0.99043043,0.97259768,0.91702091,0.97259768,1.00000000,0.97142866,0.97142866,0.99043043 +test6.bam,0.99043043,0.91702091,0.97259768,0.97259768,0.97142866,1.00000000,0.97142866,0.99043043 +test7.bam,0.99043043,0.97259768,0.97259768,0.91702091,0.97142866,0.97142866,1.00000000,0.99043043 +test8.bam,1.00000000,0.96329037,0.96329037,0.96329037,0.99043043,0.99043043,0.99043043,1.00000000"""""" + + pileup1_unnormal_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam,test6.bam,test7.bam,test8.bam +test1.bam,1.00000000,0.02940769,0.02940769,0.02940769,0.04156468,0.04156468,0.04156468,0.05089630 +test2.bam,0.02940769,1.00000000,0.00000200,0.00000200,0.70710749,0.00000212,0.70710749,0.57735142 +test3.bam,0.02940769,0.00000200,1.00000000,0.00000200,0.00000212,0.70710749,0.70710749,0.57735142 +test4.bam,0.02940769,0.00000200,0.00000200,1.00000000,0.70710749,0.70710749,0.00000212,0.57735142 +test5.bam,0.04156468,0.70710749,0.00000212,0.70710749,1.00000000,0.50000100,0.50000100,0.81649699 +test6.bam,0.04156468,0.00000212,0.70710749,0.70710749,0.50000100,1.00000000,0.50000100,0.81649699 +test7.bam,0.04156468,0.70710749,0.70710749,0.00000212,0.50000100,0.50000100,1.00000000,0.81649699 +test8.bam,0.05089630,0.57735142,0.57735142,0.57735142,0.81649699,0.81649699,0.81649699,1.00000000"""""" + + pileup1_normal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam,test6.bam,test7.bam,test8.bam +test1.bam,0.00000000,0.17303053,0.17303053,0.17303053,0.08814309,0.08814309,0.08814309,0.00000000 +test2.bam,0.17303053,0.00000000,0.29875524,0.29875524,0.14937762,0.26117362,0.14937762,0.17303053 +test3.bam,0.17303053,0.29875524,0.00000000,0.29875524,0.26117362,0.14937762,0.14937762,0.17303053 +test4.bam,0.17303053,0.29875524,0.29875524,0.00000000,0.14937762,0.14937762,0.26117362,0.17303053 +test5.bam,0.08814309,0.14937762,0.26117362,0.14937762,0.00000000,0.15254569,0.15254569,0.08814309 +test6.bam,0.08814309,0.26117362,0.14937762,0.14937762,0.15254569,0.00000000,0.15254569,0.08814309 +test7.bam,0.08814309,0.14937762,0.14937762,0.26117362,0.15254569,0.15254569,0.00000000,0.08814309 +test8.bam,0.00000000,0.17303053,0.17303053,0.17303053,0.08814309,0.08814309,0.08814309,0.00000000"""""" + + pileup1_unnormal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam,test3.bam,test4.bam,test5.bam,test6.bam,test7.bam,test8.bam +test1.bam,0.00000000,0.98127578,0.98127578,0.98127578,0.97353148,0.97353148,0.97353148,0.96758440 +test2.bam,0.98127578,0.00000000,0.99999873,0.99999873,0.49999936,0.99999865,0.49999936,0.60817255 +test3.bam,0.98127578,0.99999873,0.00000000,0.99999873,0.99999865,0.49999936,0.49999936,0.60817255 +test4.bam,0.98127578,0.99999873,0.99999873,0.00000000,0.49999936,0.49999936,0.99999865,0.60817255 +test5.bam,0.97353148,0.49999936,0.99999865,0.49999936,0.00000000,0.66666593,0.66666593,0.39182610 +test6.bam,0.97353148,0.99999865,0.49999936,0.49999936,0.66666593,0.00000000,0.66666593,0.39182610 +test7.bam,0.97353148,0.49999936,0.49999936,0.99999865,0.66666593,0.66666593,0.00000000,0.39182610 +test8.bam,0.96758440,0.60817255,0.60817255,0.60817255,0.39182610,0.39182610,0.39182610,0.00000000"""""" + + #files for testing pileup2 matrix of ones + pileup2 = ([[{'A': 1, 'T': 1, 'C': 1}, {'T': 1}], #test 1 + [{'A': 1, 'T': 1, 'C': 1}, {'T': 1}]]) # test 2 + + pileup2_files = ('test1.bam', 'test2.bam') + + pileup2_normal_out = """"""Quasispecies,test1.bam,test2.bam +test1.bam,1.00000000,1.00000000 +test2.bam,1.00000000,1.00000000"""""" + + pileup2_unnormal_out = """"""Quasispecies,test1.bam,test2.bam +test1.bam,1.00000000,1.00000000 +test2.bam,1.00000000,1.00000000"""""" + + pileup2_normal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam +test1.bam,0.00000000,0.00000000 +test2.bam,0.00000000,0.00000000"""""" + + pileup2_unnormal_angular_distance_out = """"""Quasispecies,test1.bam,test2.bam +test1.bam,0.00000000,0.00000000 +test2.bam,0.00000000,0.00000000"""""" + + """""" + TESTS + """""" + + @classmethod + def setup_class(self): + self.expected_csv_distance = """" + self.expected_csv_similarity = """" + + @pytest.fixture(scope=""function"", params=[(True, pileup0, pileup0_files, pileup0_normal_out, pileup0_normal_angular_distance_out, pileup0_startpos, pileup0_endpos), + (True, pileup1, pileup1_files, pileup1_normal_out, pileup1_normal_angular_distance_out, None, None), + (True, pileup2, pileup2_files, pileup2_normal_out, pileup2_normal_angular_distance_out, None, None), + (False, pileup0, pileup0_files, pileup0_unnormal_out, pileup0_unnormal_angular_distance_out, pileup0_startpos, pileup0_endpos), + (False, pileup1, pileup1_files, pileup1_unnormal_out, pileup1_unnormal_angular_distance_out, None, None), + (False, pileup2, pileup2_files, pileup2_unnormal_out, pileup2_unnormal_angular_distance_out, None, None)]) + def matrix(self, request): + """""" + matrix - test fixture for test_get_similarity_matrix function + and test_get_distance_matrix function + + INPUT: + [LIST OF TUPLES] + request.param[0]---[BOOL] [normalize] # normalized or not + request.param[1]---[ARRAY] [pileup list] + request.param[2]---[ARRAY] [pileup_files] # file names corresponding to pileups + request.param[3]---[ARRAY] normalized or unnormalized similarity csv-format output + request.param[4]---[ARRAY] normalized or unnormalized distance csv-format output + request.param[5]---[INT or NONE] [startpos or default if NONE] + request.param[6]---[INT or NONE] [endpos or default if NONE] + + RETURN: + [DistanceMatrix] [matrix with the pileup to be used] + + POST: + self.expected_csv_distance is now a csv representation of the + expected distance that should be calculated from this matrix. + + self.expected_csv_similarity is now a csv representation of the + expected similarity that should be calculated from this matrix. + """""" + pileups = Pileup_List([Pileup(bam) for bam in request.param[1]]) + + # if startpos is int and endpos is int (aka they are not None) + if type(request.param[5]) is int and type(request.param[6]) is int: + pileups.select_pileup_range(request.param[5], request.param[6]) + + # if boolean normalize flag (request.param[0]) is true normalize + if request.param[0] is True: + pileups.normalize_pileups() + + # create matrix with pileup + dist = DistanceMatrix(pileups.get_pileups_as_numerical_array(), request.param[2]) + + self.expected_csv_similarity = request.param[3] + self.expected_csv_distance = request.param[4] + + return dist + + #end def + + def test_get_similarity_matrix(self, matrix): + """""" + test_get_similarity_matrix - Checked that the actual output matches the + expected output. + + INPUT: + [FIXTURE] [matrix] - returns DistanceMatrix object. + + RETURN: + [None] + + POST: + [None] + """""" + csv_similarity = matrix.get_similarity_matrix_as_csv() + assert csv_similarity == self.expected_csv_similarity + #end def + + def test_get_distance_matrix(self, matrix): + """""" + test_get_distance_matrix - Checked that the actual output matches the + expected output. + + INPUT: + [FIXTURE] [matrix] - returns DistanceMatrix object. + + RETURN: + [None] + + POST: + [None] + """""" + csv_distance = matrix.get_distance_matrix_as_csv() + assert csv_distance == self.expected_csv_distance + #end def +","Python" +"Microbiology","phac-nml/quasitools","tests/test_aa_variant.py",".py","7476","206",""""""" +Copyright Government of Canada 2017 + +Written by: Cole Peters, Eric Chubaty, National Microbiology Laboratory, Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +import re +import string +import PyAAVF.parser as parser +from quasitools.aa_census import AACensus, CONFIDENT +from quasitools.aa_variant import AAVariantCollection +from quasitools.nt_variant import NTVariantCollection +from quasitools.mutations import MutationDB +from quasitools.parsers.mapped_read_parser import parse_mapped_reads_from_bam +from quasitools.parsers.genes_file_parser import parse_BED4_file +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.parsers.nt_variant_file_parser \ + import parse_nt_variants_from_vcf + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +VARIANTS_FILE = TEST_PATH + ""/data/output/nt_variants.vcf"" +VALID_AA_VARIANTS_AAVF = TEST_PATH + ""/data/output/mutation_report.aavf"" +VALID_DR_MUTATIONS_CSV = TEST_PATH + ""/data/output/dr_report.csv"" + + +class TestAAVariant: + + @classmethod + def setup(self): + self.reference = TEST_PATH + ""/data/hxb2_pol.fas"" + bam = TEST_PATH + ""/data/align.bam"" + BED4_file = TEST_PATH + ""/data/hxb2_pol.bed"" + mutation_db = TEST_PATH + ""/data/mutation_db.tsv"" + min_freq = 0.01 + + rs = parse_references_from_fasta(self.reference) + + mapped_read_collection_arr = [] + for r in rs: + # Create a MappedReadCollection object + mapped_read_collection_arr.append( + parse_mapped_reads_from_bam(r, bam)) + + variants_obj = parse_nt_variants_from_vcf(VARIANTS_FILE, rs) + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants_obj) + + # Parse the genes from the gene file + genes = parse_BED4_file(BED4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + # Create an AACensus object + aa_census = AACensus(self.reference, mapped_read_collection_arr, genes, + frames) + + # Find the AA mutations + self.aa_collection = AAVariantCollection.from_aacensus( + aa_census) + + # Build the mutation database + self.mutation_db = MutationDB(mutation_db, genes) + + def test_dr_mutations(self): + reporting_threshold = 1 + + with open(VALID_DR_MUTATIONS_CSV, ""r"") as input: + # Read both sample and collection, remove nl, and compare + dr_mutations = [x.replace(""\n"", """") for x in input.readlines()] + + # Apply filter to the collection + self.aa_collection.filter('mf0.01', 'freq<0.01', True) + + # Get the report and compare outputs + collection = self.aa_collection.report_dr_mutations( + self.mutation_db, reporting_threshold + ).split(""\n"") + + assert dr_mutations == collection + + def test_aa_variants(self): + aavf_path = TEST_PATH + ""/data/output/temp.aavf"" + aavf_out = open(aavf_path, ""w"") + + # Read from file and make sure there are no empty lines + with open(VALID_AA_VARIANTS_AAVF, ""r"") as input: + valid_variants = input.read() + + # Sort and filter so comparison order will be fine afterwards + valid_variants_lines = sorted(filter(None, valid_variants.split(""\n""))) + + # Apply the filter to the collection + self.aa_collection.filter('af0.01', 'freq<0.01', True) + + # Do the thing with the mutation_db + self.aa_collection.apply_mutation_db(self.mutation_db) + + aavf_obj = self.aa_collection.to_aavf_obj(""test"", os.path.basename(self.reference), CONFIDENT) + records = list(aavf_obj) + + writer = parser.Writer(aavf_out, aavf_obj) + + for record in records: + writer.write_record(record) + + aavf_out.close() + + with open(aavf_path, ""r"") as input: + aa_variants = input.read() + + # Make sure it's sorted and has no empty strings + aa_variants_lines = sorted(filter(None, aa_variants.split(""\n""))) + + # Check the length + assert len(valid_variants_lines) == len(aa_variants_lines) + + # Make sure all the tokens that need to be there are there + for pos in range(0, len(valid_variants_lines)): + if valid_variants_lines[pos][0:1] != ""#"": + valid_variants_tokens = \ + re.split(""[,=;\t]"", valid_variants_lines[pos].rstrip()) + + aa_variants_tokens = re.split( + ""[,=;\t]"", aa_variants_lines[pos]) + + for token in aa_variants_tokens: + assert token in valid_variants_tokens + + writer.close() + # remove temp test file + + def test_aa_variants_nodb(self): + # Same as previous test but for no mutation db + aavf_path = TEST_PATH + ""/data/output/temp.aavf"" + aavf_out = open(aavf_path, ""w"") + + # Read from file and make sure there are no empty lines + with open(VALID_AA_VARIANTS_AAVF, ""r"") as input: + valid_variants = input.read() + + valid_variants_lines = sorted(filter(None, valid_variants.split(""\n""))) + + # Replace category and surveillance with "".""s + # Okay because comparisons only done on non ""#"" lines + for i, x in enumerate(valid_variants_lines): + tokens = x.split("";"") + + # Change result to be what it would be without a db + if len(tokens) > 2: + x = x.replace(tokens[-2], ""CAT=."", 1) + x = x.replace(tokens[-1], ""SRVL=."", 1) + valid_variants_lines[i] = x + + # Apply the filter to the collection + self.aa_collection.filter('af0.01', 'freq<0.01', True) + + aavf_obj = self.aa_collection.to_aavf_obj(""test"", os.path.basename(self.reference), CONFIDENT) + records = list(aavf_obj) + + writer = parser.Writer(aavf_out, aavf_obj) + + for record in records: + writer.write_record(record) + + aavf_out.close() + + with open(aavf_path, ""r"") as input: + aa_variants = input.read() + + # Make sure it's sorted and has no empty strings + aa_variants_lines = sorted(filter(None, aa_variants.split(""\n""))) + + # Check the length + assert len(valid_variants_lines) == len(aa_variants_lines) + + # Make sure all the tokens that need to be there are there + for pos in range(0, len(valid_variants_lines)): + if valid_variants_lines[pos][0:1] != ""#"": + valid_variants_tokens = \ + re.split(""[,=;\t]"", valid_variants_lines[pos].rstrip()) + + aa_variants_tokens = re.split( + ""[,=;\t]"", aa_variants_lines[pos]) + + for token in aa_variants_tokens: + assert token in valid_variants_tokens +","Python" +"Microbiology","phac-nml/quasitools","tests/test_mutant_types.py",".py","3589","102",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import os +import pytest +from quasitools.codon_variant import CodonVariantCollection +from quasitools.nt_variant import NTVariantCollection +from quasitools.aa_census import AACensus +from quasitools.parsers.mapped_read_parser import \ + parse_mapped_reads_from_bam +from quasitools.parsers.reference_parser import \ + parse_references_from_fasta +from quasitools.parsers.genes_file_parser import parse_BED4_file + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) +VALID_MUTANT_TYPES_CSV = TEST_PATH + ""/data/output/mutant_types.csv"" + +class TestMutantTypes: + + @classmethod + def setup(self): + bam = TEST_PATH + ""/data/align.bam"" + reference = TEST_PATH + ""/data/hxb2_pol.fas"" + BED4_file = TEST_PATH + ""/data/hxb2_pol.bed"" + error_rate = 0.0038 + + rs = parse_references_from_fasta(reference) + mapped_read_collection_arr = [] + + # Create a MappedReadCollection object + for r in rs: + mapped_read_collection_arr.append( + parse_mapped_reads_from_bam(r, bam)) + + variants = NTVariantCollection.from_mapped_read_collections( + error_rate, rs, *mapped_read_collection_arr) + variants.filter('q30', 'QUAL<30', True) + variants.filter('ac5', 'AC<5', True) + variants.filter('dp100', 'DP<100', True) + + # Mask the unconfident differences + for mrc in mapped_read_collection_arr: + mrc.mask_unconfident_differences(variants) + + # Parse the genes from the gene file + genes = parse_BED4_file(BED4_file, rs[0].name) + + # Determine which frames our genes are in + frames = set() + + for gene in genes: + frames.add(genes[gene]['frame']) + + aa_census = AACensus(reference, + mapped_read_collection_arr, + genes, + frames) + + self.codon_variants = CodonVariantCollection.from_aacensus( + aa_census) + + def test_mutant_types(self): + offset = 1269 + + # Read from file and make sure there are no empty lines + with open(VALID_MUTANT_TYPES_CSV, ""r"") as input: + valid_mutant_types = input.read() + + # Sort and filter for comparison + valid_mutant_types_lines = sorted(filter(None, + valid_mutant_types.split(""\n""))) + + # Create the report string + mutant_types = self.codon_variants.to_csv_file(offset) + + # Split into lines and sort + mutant_types_lines = sorted(mutant_types.split(""\n"")) + + assert len(valid_mutant_types_lines) == len(mutant_types_lines) + + # Compare each line in the test report to the valid report + for pos in range(0, len(valid_mutant_types_lines)): + if valid_mutant_types_lines[pos][0:1] != ""#"": + assert valid_mutant_types_lines[pos] == \ + mutant_types_lines[pos] +","Python" +"Microbiology","phac-nml/quasitools","tests/test_codon_variant_parser.py",".py","4614","106",""""""" +Copyright Government of Canada 2017 + +Written by: Camy Tran, National Microbiology Laboratory, + Public Health Agency of Canada + +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this work except in compliance with the License. You may obtain a copy of the +License at: + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +"""""" + +import pytest +import os +from quasitools.parsers.codon_variant_file_parser import parse_codon_variants +from quasitools.parsers.reference_parser import parse_references_from_fasta +from quasitools.codon_variant import CodonVariant, CodonVariantCollection + + +TEST_PATH = os.path.dirname(os.path.abspath(__file__)) + +class TestCodonVariantParser: + def test_valid_csv_file(self): + """"""Tests to make sure that a valid codon variant csv file is properly + parsed into a CodonVariantCollection object. + """""" + + reference = TEST_PATH + ""/data/hxb2_pol.fas"" + rs = parse_references_from_fasta(reference) + + var_obj = CodonVariantCollection(rs) + + for i in range(0, 30): + variant = CodonVariant( + chrom=""hxb2_pol"", + pos=i, + gene=""gag"", + nt_start_gene=1309+i, + nt_end_gene=2841+i, + nt_start=2077+i, + nt_end=2079+i, + ref_codon=""ata"", + mutant_codon=""aAa"", + ref_aa=""I"", + mutant_aa=""K"", + coverage=563+i, + mutant_freq=1.60+i, + mutant_type=""S"", + ns_count=1.0000, + s_count=1.5000) + + pos = int(variant.nt_start)-int(variant.nt_start_gene) + var_obj.variants[""gag""][pos][""aAa""] = variant + + valid_csv = TEST_PATH + ""/data/valid_csv.csv"" + + with open(valid_csv, ""w+"") as f: + f.write(""#gene,nt position (gene),nt start position,"" + ""nt end position,ref codon,mutant codon,ref AA,mutant AA,"" + ""coverage,mutant frequency,mutant type,NS count,S count"") + + for gene in var_obj.variants: + for pos in var_obj.variants[gene]: + for codon in var_obj.variants[gene][pos]: + variant = var_obj.variants[gene][pos][codon] + + f.write(""%s,%i-%i,%i,%i,%s,%s,%s,%s,%i,%.2f,%s,%0.4f,%0.4f\n"" % ( + variant.gene, variant.nt_start_gene, variant.nt_end_gene, + variant.nt_start, variant.nt_end, variant.ref_codon, + variant.mutant_codon, variant.ref_aa, variant.mutant_aa, + variant.coverage, variant.mutant_freq, variant.mutant_type, + variant.ns_count, variant.s_count)) + + + parsed_codon_variants = parse_codon_variants(valid_csv, rs) + + for gene in parsed_codon_variants.variants: + for pos in parsed_codon_variants.variants[gene]: + for codon in parsed_codon_variants.variants[gene][pos]: + parsed_variant = parsed_codon_variants.variants[gene][pos][codon] + variant = var_obj.variants[gene][pos][codon] + + assert parsed_variant.chrom == variant.chrom + assert parsed_variant.nt_start_gene == variant.nt_start_gene + assert parsed_variant.nt_end_gene == variant.nt_end_gene + assert parsed_variant.nt_start == variant.nt_start + assert parsed_variant.nt_end == variant.nt_end + assert parsed_variant.ref_codon == variant.ref_codon + assert parsed_variant.mutant_codon == variant.mutant_codon + assert parsed_variant.ref_aa == variant.ref_aa + assert parsed_variant.mutant_aa == variant.mutant_aa + assert parsed_variant.coverage == variant.coverage + assert parsed_variant.mutant_freq == variant.mutant_freq + assert parsed_variant.mutant_type == variant.mutant_type + assert parsed_variant.ns_count == variant.ns_count + assert parsed_variant.s_count == variant.s_count + + os.remove(valid_csv) + +","Python" +"Microbiology","alienzj/gtdb2ncbi","SECURITY.md",".md","619","22","# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. +","Markdown" +"Microbiology","alienzj/gtdb2ncbi","src/main.rs",".rs","12376","306","use calamine::{Reader, Xlsx}; +use clap::{App, Arg}; +use csv::{ReaderBuilder, Trim, WriterBuilder}; + +use std::collections::HashMap; +use std::io::Cursor; +use std::process; + +fn main() { + const ARCHAEA_XLSX: &[u8] = include_bytes!(""../data/ncbi_vs_gtdb_r220_archaea.xlsx""); + const BACTERIA_XLSX: &[u8] = include_bytes!(""../data/ncbi_vs_gtdb_r220_bacteria.xlsx""); + + let archaea_map = parse(ARCHAEA_XLSX); + let bacteria_map = parse(BACTERIA_XLSX); + + let matches = App::new(""gtdb2ncbi"") + .version(""0.1"") + .author(""alienzj "") + .about(""convert taxonomy system from GTDB to NCBI"") + .arg( + Arg::with_name(""input"") + .short(""i"") + .long(""input"") + .value_name(""FILE"") + .help(""GTDB taxonomy input file"") + .takes_value(true), + ) + .arg( + Arg::with_name(""output"") + .short(""o"") + .long(""output"") + .value_name(""FILE"") + .help(""NCBI taxonomy output file"") + .takes_value(true), + ) + .get_matches(); + + let input = matches.value_of(""input"").unwrap_or_else(|| { + eprintln!(""please supply --input [FILE]""); + process::exit(1); + }); + let output = matches.value_of(""output"").unwrap_or_else(|| { + eprintln!(""please supply --output [FILE]""); + process::exit(1); + }); + + let mut rdr = ReaderBuilder::new() + .trim(Trim::All) + .delimiter(b'\t') + .from_path(input) + .unwrap(); + + let mut wtr = WriterBuilder::new() + .delimiter(b'\t') + .from_path(output) + .unwrap(); + + let mut headers = rdr.headers().unwrap().to_owned(); + headers.push_field(""NCBI_taxonomy""); + + wtr.write_record(&headers).unwrap(); + + for result in rdr.records() { + let mut record = result.unwrap(); + // we assume the gtdb classification locate at the 3th column + let classification = record.get(2).unwrap(); + + let lineages: Vec<&str> = classification.split(';').rev().collect(); + + let mut classification_ncbi = String::new(); + let mut classification_sensitive = String::new(); + + for i in 0..(lineages.len() - 1) { + match archaea_map.get(lineages[i]) { + Some(v) => { + if v.len() == 2 { + classification_ncbi = String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI"") + + &classification_sensitive; + } else { + if lineages[i + 1] == v[2] { + classification_ncbi = String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI"") + + &classification_sensitive; + } else { + classification_ncbi = String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI?"") + + &classification_sensitive; + } + } + } + None => match bacteria_map.get(lineages[i]) { + Some(v) => { + if v.len() == 2 { + classification_ncbi = String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI"") + + &classification_sensitive; + } else { + if lineages[i + 1] == v[2] { + classification_ncbi = + String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI"") + + &classification_sensitive; + } else { + classification_ncbi = + String::from("";"") + &v[1] + &classification_ncbi; + classification_sensitive = String::from("";"") + + &v[1] + + &String::from(""__NCBI?"") + + &classification_sensitive; + } + } + } + None => { + let level: Vec<&str> = lineages[i].split(""__"").collect(); + if level[1] == """" { + classification_ncbi = + String::from("";"") + &lineages[i] + &classification_ncbi; + classification_sensitive = + String::from("";"") + &lineages[i] + &classification_sensitive; + } else { + classification_ncbi = String::from("";"") + + &level[0] + + &String::from(""__NCBI_UNKNOWN"") + + &classification_ncbi; + classification_sensitive = String::from("";"") + + &level[0] + + &String::from(""__NCBI_UNKNOWN"") + + &classification_sensitive; + } + } + }, + } + } + + classification_ncbi = String::from("""") + lineages.last().unwrap() + &classification_ncbi; + classification_sensitive = + String::from("""") + lineages.last().unwrap() + &classification_sensitive; + + println!(""{}"", classification); + println!(""{}"", classification_sensitive); + println!(""{}\n"", classification_ncbi); + + record.push_field(&classification_ncbi); + + wtr.write_record(&record).unwrap(); + } + + wtr.flush().unwrap(); +} + +fn parse(raw_xlsx: &[u8]) -> HashMap> { + let reader = Cursor::new(raw_xlsx); + + let mut excel: Xlsx<_> = Xlsx::new(reader).unwrap(); + + let mut map: HashMap> = HashMap::new(); + + for s in excel.sheet_names().to_owned() { + if let Some(Ok(range)) = excel.worksheet_range(&s) { + for r in range.rows().skip(1) { + if let Some(gtdb) = r[3].get_string() { + if let Some(ncbi) = r[0].get_string() { + for lineage in gtdb.split(',') { + if lineage.contains('(') { + let lineages: Vec<&str> = lineage + .trim() + .split(|c| c == '(' || c == ')' || c == '%') + .collect(); + + let key = String::from(lineages[0]); + let percent = lineages[2].trim().trim_start_matches('<'); + + if !map.contains_key(&key) { + map.insert( + key, + vec![ + String::from(percent), + String::from(ncbi), + String::from(lineages[1]), + ], + ); + } else { + println!(""percent: {}"", percent); + let percent_1: f32 = map.get(&key).unwrap()[0].parse().unwrap(); + let percent_2: f32 = percent.parse().unwrap(); + if (percent_2 - percent_1) > 20.0 { + map.insert( + key, + vec![ + String::from(percent), + String::from(ncbi), + String::from(lineages[1]), + ], + ); + } + } + } else { + let lineages: Vec<&str> = lineage.trim().rsplitn(2, ' ').collect(); + + let key = String::from(lineages[1]); + let percent = lineages[0] + .trim() + .trim_start_matches('<') + .trim_end_matches('%'); + + if !map.contains_key(&key) { + map.insert( + key, + vec![String::from(percent), String::from(ncbi)], + ); + } else { + println!(""percent: {}"", percent); + let percent_1: f32 = map.get(&key).unwrap()[0].parse().unwrap(); + let percent_2: f32 = percent.parse().unwrap(); + if (percent_2 - percent_1) > 20.0 { + map.insert( + key, + vec![String::from(percent), String::from(ncbi)], + ); + } + } + } + } + } + } + } + } + } + map +} + +/* +fn parse_gtdb(gtdb: &str, ncbi: &str) -> Vec<(String, Vec)> { + gtdb.split(',') + .map(|lineage| { + if lineage.contains('(') { + let lineages: Vec<&str> = lineage.trim().split(|c| c == '(' || c == ')').collect(); + ( + String::from(lineages[0]), + vec![String::from(ncbi), String::from(lineages[1])], + ) + } else { + let lineages: Vec<&str> = lineage.trim().rsplitn(2, ' ').collect(); + (String::from(lineages[1]), vec![String::from(ncbi)]) + } + }) + .collect::)>>() +} + +fn parse_sheet( + sheet: Range, + name: &str, +) -> Result)>, String>>, String> { + Ok(sheet + .rows() + .skip(1) + .map(|row| match row[0].get_string() { + None => Err(format!(""sheet {} is empty"", name)), + Some(ncbi) => match row[3].get_string() { + None => Err(format!(""sheet{} is empty"", name)), + Some(gtdb) => Ok(parse_gtdb(gtdb, ncbi)), + }, + }) + .collect()) +} + +fn parse_excel(raw_xlsx: &[u8]) -> Result>, String> { + let reader = Cursor::new(raw_xlsx); + let mut excel: Xlsx<_> = Xlsx::new(reader).unwrap(); + + let mut tax_map: HashMap> = excel + .sheet_names() + .into_iter() + .map(|name| match excel.worksheet_range(name) { + None => Err(format!(""sheet {} is empty"", name)), + Some(Err(err)) => Err(format!(""{}"", err)), + Some(Ok(sheet)) => parse_sheet(sheet, name), + }) + // FIXME + .collect(); + + Ok(tax_map) +} +*/ + +#[test] +fn split() { + assert_eq!(""s__"".trim().split(""__"").collect::>()[1], """"); +} + +#[test] +fn split_() { + assert_eq!(""s__a"".trim().split(""__"").collect::>().len(), 1); +} +","Rust" +"Microbiology","ktmeaton/ncov-recombinant","CHANGELOG.md",".md","131382","1466","# CHANGELOG + +## v0.7.0 + +### Notes + +This is a minor release aimed towards a `nextclade` dataset upgrade from `2022-10-27` to `2023-01-09` which adds nomenclature for newly designated recombinants `XBH` - `XBP`. This release also adds initial support for the detection of ""recursive recombination"" including `XBL` and `XBN` which are recombinants of `XBB`. + +#### Documentation + +- [Issue #24](https://github.com/ktmeaton/ncov-recombinant/issues/24): Create documentation on [Read The Docs](https://ncov-recombinant.readthedocs.io/en/stable/) + +#### Dataset + +- [Issue #210](https://github.com/ktmeaton/ncov-recombinant/issues/210): Handle numeric strain names. + +#### Resources + +- [Issue #185](https://github.com/ktmeaton/ncov-recombinant/issues/185): Simplify creation of the pango-lineage nomenclature phylogeny to use the [lineage_notes.txt](https://github.com/cov-lineages/pango-designation/blob/master/lineage_notes.txt) file and the [pango_aliasor](https://github.com/corneliusroemer/pango_aliasor) library. + +#### sc2rf + +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Add bypass to intermission allele ratio for edge cases. +- [Issue #204](https://github.com/ktmeaton/ncov-recombinant/issues/204): Add special handling for XBB sequenced with ARTIC v4.1 and dropout regions. +- [Issue #205](https://github.com/ktmeaton/ncov-recombinant/issues/205): Add new column `parents_conflict` to indicate whether the reported lineages from covSPECTRUM conflict with the reported parental clades from `sc2rf. +- [Issue #213](https://github.com/ktmeaton/ncov-recombinant/issues/213): Add `XBK` to auto-pass lineages. +- [Issue #222](https://github.com/ktmeaton/ncov-recombinant/issues/222): Add new parameter `--gisaid-access-key` to `sc2rf` and `sc2rf_recombinants`. +- [Issue #229](https://github.com/ktmeaton/ncov-recombinant/issues/229): Fix bug where auto-pass lineages are missing when exclude_negatives is set to true. +- [Issue #231](https://github.com/ktmeaton/ncov-recombinant/issues/231): Fix bug where 'null' lineages in covSPECTRUM caused error in `sc2rf` postprocess. +- The order of the `postprocessing.py` was rearranged to have more comprehensive details for auto-pass lineages. +- Add `XAN` to auto-pass lineages. + +#### Plot + +- [Issue #209](https://github.com/ktmeaton/ncov-recombinant/issues/209): Restrict the palette for `rbd_level` to the range of `0:12`. +- [Issue #218](https://github.com/ktmeaton/ncov-recombinant/issues/218): Fix bug concerning data fragmentation with large numbers of sequences. +- [Issue #221](https://github.com/ktmeaton/ncov-recombinant/issues/221): Remove parameter `--singletons` in favor of `--min-cluster-size` to control cluster size in plots. +- [Issue #224](https://github.com/ktmeaton/ncov-recombinant/issues/224): Fix bug where plot crashed with extremely large datasets. +- Combine `plot` and `plot_historical` into one snakemake rule. Also at custom pattern `plot_NX` (ex. `plot_N10`) to adjust min cluster size. + +#### Report + +- Combine `report` and `report_historical` into one snakemake rule. + +#### Validate + +- [Issue #225](https://github.com/ktmeaton/ncov-recombinant/issues/225): Fix bug where false negatives passed validation because the status column wasn't checked. + +##### Designated Lineages + +- [Issue #217](https://github.com/ktmeaton/ncov-recombinant/issues/217): `XBB.1.5` +- [Issue #196](https://github.com/ktmeaton/ncov-recombinant/issues/196): `XBF` +- [Issue #206](https://github.com/ktmeaton/ncov-recombinant/issues/206): `XBG` +- [Issue #196](https://github.com/ktmeaton/ncov-recombinant/issues/198): `XBH` +- [Issue #199](https://github.com/ktmeaton/ncov-recombinant/issues/199): `XBJ` +- [Issue #213](https://github.com/ktmeaton/ncov-recombinant/issues/213): `XBK` +- [Issue #219](https://github.com/ktmeaton/ncov-recombinant/issues/219): `XBL` +- [Issue #215](https://github.com/ktmeaton/ncov-recombinant/issues/215): `XBM` +- [Issue #197](https://github.com/ktmeaton/ncov-recombinant/issues/197): `XBN` + +##### Proposed Lineages + +- [Issue #203](https://github.com/ktmeaton/ncov-recombinant/issues/203): `proposed1305` +- [Issue #208](https://github.com/ktmeaton/ncov-recombinant/issues/208): `proposed1340` +- [Issue #212](https://github.com/ktmeaton/ncov-recombinant/issues/212): `proposed1425` +- [Issue #214](https://github.com/ktmeaton/ncov-recombinant/issues/214): `proposed1440` +- [Issue #216](https://github.com/ktmeaton/ncov-recombinant/issues/216): `proposed1444` +- [Issue #220](https://github.com/ktmeaton/ncov-recombinant/issues/220): `proposed1576` + +### Commits + +- [```2964b4a1```](https://github.com/ktmeaton/ncov-recombinant/commit/2964b4a1) docs: update notes to include 1576 proposed issue +- [```fdc874ab```](https://github.com/ktmeaton/ncov-recombinant/commit/fdc874ab) docs: add test summary package for v0.7.0 +- [```3f3d4438```](https://github.com/ktmeaton/ncov-recombinant/commit/3f3d4438) docs: update docs v0.7.0 +- [```78696b36```](https://github.com/ktmeaton/ncov-recombinant/commit/78696b36) script: add bug fix to sc2rf postprocess for #231 +- [```403777a0```](https://github.com/ktmeaton/ncov-recombinant/commit/403777a0) script: lint plotting script +- [```2a09c783```](https://github.com/ktmeaton/ncov-recombinant/commit/2a09c783) script: fix sc2rf postprocess bug in duplicate removal +- [```d44d5f90```](https://github.com/ktmeaton/ncov-recombinant/commit/d44d5f90) data: add XBP to controls-gisaid +- [```4293439c```](https://github.com/ktmeaton/ncov-recombinant/commit/4293439c) profile: add controls-gisaid to virusseq builds +- [```91d6fb89```](https://github.com/ktmeaton/ncov-recombinant/commit/91d6fb89) defaults: update nextclade dataset to 2023-02-01 +- [```630b2cd5```](https://github.com/ktmeaton/ncov-recombinant/commit/630b2cd5) resources: update +- [```49e6f598```](https://github.com/ktmeaton/ncov-recombinant/commit/49e6f598) profile: add virusseq profile +- [```7e586d1d```](https://github.com/ktmeaton/ncov-recombinant/commit/7e586d1d) script: add extra logic for auto-passing lineages +- [```0ebe5e9c```](https://github.com/ktmeaton/ncov-recombinant/commit/0ebe5e9c) script: fix bug in report where it didn't check that plots existed +- [```25b2f243```](https://github.com/ktmeaton/ncov-recombinant/commit/25b2f243) docs: update developers guide +- [```914d933f```](https://github.com/ktmeaton/ncov-recombinant/commit/914d933f) defaults: add XBN to controls-gisaid and validation +- [```8eaf08a9```](https://github.com/ktmeaton/ncov-recombinant/commit/8eaf08a9) data: restore controls-gisaid strain list +- [```fa123009```](https://github.com/ktmeaton/ncov-recombinant/commit/fa123009) script: defragment plot for 218 +- [```5f24f695```](https://github.com/ktmeaton/ncov-recombinant/commit/5f24f695) dataset: update controls-gisaid strain list +- [```efc5aab7```](https://github.com/ktmeaton/ncov-recombinant/commit/efc5aab7) defaults: update validation to fix XBH dropout +- [```5a76f81c```](https://github.com/ktmeaton/ncov-recombinant/commit/5a76f81c) sc2rf: update sc2rf to use gisaid access token +- [```84a01cfc```](https://github.com/ktmeaton/ncov-recombinant/commit/84a01cfc) script: fix validate bug for #225 +- [```cc031e37```](https://github.com/ktmeaton/ncov-recombinant/commit/cc031e37) env: version control all docs dependencies +- [```e1c18b91```](https://github.com/ktmeaton/ncov-recombinant/commit/e1c18b91) env: add kaleido for static image export +- [```f63a254a```](https://github.com/ktmeaton/ncov-recombinant/commit/f63a254a) docs: update configuration and faq +- [```41c533fd```](https://github.com/ktmeaton/ncov-recombinant/commit/41c533fd) docs: update links in developers guide +- [```71d48037```](https://github.com/ktmeaton/ncov-recombinant/commit/71d48037) defaults: update validation values +- [```35a5d1ee```](https://github.com/ktmeaton/ncov-recombinant/commit/35a5d1ee) script: change slurm job name to basename of conda env +- [```04e425f8```](https://github.com/ktmeaton/ncov-recombinant/commit/04e425f8) docs: change links to html refs +- [```ccda5121```](https://github.com/ktmeaton/ncov-recombinant/commit/ccda5121) docs: add pipeline definiton example +- [```18e7ae78```](https://github.com/ktmeaton/ncov-recombinant/commit/18e7ae78) docs: remove README content and link to read the docs +- [```5f7ec1a1```](https://github.com/ktmeaton/ncov-recombinant/commit/5f7ec1a1) docs: rename sphinx pages +- [```d9cc87dd```](https://github.com/ktmeaton/ncov-recombinant/commit/d9cc87dd) workflow: create new pattern plot_NX to customize min cluster size +- [```1c3cc7a4```](https://github.com/ktmeaton/ncov-recombinant/commit/1c3cc7a4) docs: success with read the docs, fix description include +- [```5921240b```](https://github.com/ktmeaton/ncov-recombinant/commit/5921240b) env: add sphinx rtd theme +- [```cd789917```](https://github.com/ktmeaton/ncov-recombinant/commit/cd789917) docs: try read the docs with requirements +- [```6d63bcbf```](https://github.com/ktmeaton/ncov-recombinant/commit/6d63bcbf) docs: remove sphinx conda too slow +- [```47fe5a54```](https://github.com/ktmeaton/ncov-recombinant/commit/47fe5a54) env: switch git from anaconda to conda-forge channel +- [```7e8c4c6c```](https://github.com/ktmeaton/ncov-recombinant/commit/7e8c4c6c) docs: downgrade sphinx python to 3.8 +- [```28e7be0e```](https://github.com/ktmeaton/ncov-recombinant/commit/28e7be0e) docs: attempt conda 3 with sphinx readthedocs +- [```985159b6```](https://github.com/ktmeaton/ncov-recombinant/commit/985159b6) docs: attempt conda 2 with sphinx readthedocs +- [```7ab1c5d9```](https://github.com/ktmeaton/ncov-recombinant/commit/7ab1c5d9) docs: attempt conda with sphinx readthedocs +- [```6d7079a8```](https://github.com/ktmeaton/ncov-recombinant/commit/6d7079a8) docs: add sphinx for readthedocs #24 +- [```1809dad5```](https://github.com/ktmeaton/ncov-recombinant/commit/1809dad5) workflow: update validation for new controls-gisaid strains +- [```71c0fb34```](https://github.com/ktmeaton/ncov-recombinant/commit/71c0fb34) script: catch tight layout warnings for #224 +- [```690bbd7c```](https://github.com/ktmeaton/ncov-recombinant/commit/690bbd7c) resources: update issues +- [```348264b4```](https://github.com/ktmeaton/ncov-recombinant/commit/348264b4) resources: add proposed1444 and proposed1576 to breakpoints +- [```3f657060```](https://github.com/ktmeaton/ncov-recombinant/commit/3f657060) resources: add XBL and XBM to breakpoints +- [```a8528cc0```](https://github.com/ktmeaton/ncov-recombinant/commit/a8528cc0) docs: add development section to README +- [```b0446f66```](https://github.com/ktmeaton/ncov-recombinant/commit/b0446f66) docs: add development section to README +- [```03a65ebf```](https://github.com/ktmeaton/ncov-recombinant/commit/03a65ebf) ci: extend miniforge-variant to all jobs for #223 +- [```f186a1c6```](https://github.com/ktmeaton/ncov-recombinant/commit/f186a1c6) ci: use miniforge-variant to fix #223 +- [```cb1bda73```](https://github.com/ktmeaton/ncov-recombinant/commit/cb1bda73) script: add intermission ratio bypass for #195 +- [```c0429ec3```](https://github.com/ktmeaton/ncov-recombinant/commit/c0429ec3) parameter: update nextclade data +- [```2377fce6```](https://github.com/ktmeaton/ncov-recombinant/commit/2377fce6) script: improve postprocess duplicate reconciliation for lineage matches +- [```6b891c92```](https://github.com/ktmeaton/ncov-recombinant/commit/6b891c92) resources: add proposed1440 to breakpoints #214 +- [```7171dcfd```](https://github.com/ktmeaton/ncov-recombinant/commit/7171dcfd) resources: add proposed1425 to breakpoints #212 +- [```d5a2bf1c```](https://github.com/ktmeaton/ncov-recombinant/commit/d5a2bf1c) resources: add proposed1393 to breakpoints #211 +- [```18961b51```](https://github.com/ktmeaton/ncov-recombinant/commit/18961b51) script: improve postprocess duplicate reconciliation with multiple strain matches +- [```1d7263f9```](https://github.com/ktmeaton/ncov-recombinant/commit/1d7263f9) resources: add proposed1340 to breakpoints #208 +- [```9b06cff6```](https://github.com/ktmeaton/ncov-recombinant/commit/9b06cff6) resources: update validation for controls +- [```762fc77d```](https://github.com/ktmeaton/ncov-recombinant/commit/762fc77d) script: fix postprocess bug in auto-pass parsing +- [```ea7cdcaf```](https://github.com/ktmeaton/ncov-recombinant/commit/ea7cdcaf) param: add XBK to resources and voc +- [```ccc08dba```](https://github.com/ktmeaton/ncov-recombinant/commit/ccc08dba) resources: upgrade sc2rf, upgrade Nextclade #176, update XBG breakpoints #206, parent conflict #205, rbd palette #209 +- [```c0c9209b```](https://github.com/ktmeaton/ncov-recombinant/commit/c0c9209b) script: fix cluster str recode in plot_breakpoints +- [```044040c2```](https://github.com/ktmeaton/ncov-recombinant/commit/044040c2) param: add XAN to auto-pass +- [```d7e728d0```](https://github.com/ktmeaton/ncov-recombinant/commit/d7e728d0) script: handle numeric strain names for #210 +- [```c014cfb7```](https://github.com/ktmeaton/ncov-recombinant/commit/c014cfb7) script: hardcode rbd palette range from 0 to 12 for #209 +- [```91f4bb05```](https://github.com/ktmeaton/ncov-recombinant/commit/91f4bb05) script: fix missing X parent in lineage_tree for #185 +- [```f341dd59```](https://github.com/ktmeaton/ncov-recombinant/commit/f341dd59) ci: switch flake8 repo from gitlab to github +- [```dea9eeb3```](https://github.com/ktmeaton/ncov-recombinant/commit/dea9eeb3) resources: update XBB validation lineage +- [```be32e69e```](https://github.com/ktmeaton/ncov-recombinant/commit/be32e69e) workflow: fix typo in nextclade dataset_dir +- [```575255b8```](https://github.com/ktmeaton/ncov-recombinant/commit/575255b8) workflow: move lineage tree to resources as not dependent on nextclade for #185 +- [```447b0b8b```](https://github.com/ktmeaton/ncov-recombinant/commit/447b0b8b) env: add pango-aliasor for #185 +- [```823428a9```](https://github.com/ktmeaton/ncov-recombinant/commit/823428a9) param: add XBB_ARTIC alt breakpoints for #204 + +## v0.6.1 + +### Notes + +This is a minor bugfix release aimed towards resolving network connectivity errors and catching false positives. + +#### sc2rf + +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Consider alleles outside of parental regions as intermissions (conflicts) to catch false positives. +- [Issue #201](https://github.com/ktmeaton/ncov-recombinant/issues/201): Make LAPIS query of covSPECTRUM optional, to help with users with network connectivity issues. This can be set with the flag `lapis: false` in builds under the rule `sc2rf_recombinants`. +- [Issue #202](https://github.com/ktmeaton/ncov-recombinant/issues/202): Document connection errors related to LAPIS and provide options for solutions. + +### Commits + +- [```83ee0139```](https://github.com/ktmeaton/ncov-recombinant/commit/83ee0139) docs: update changelog for v0.6.1 +- [```00fe2fc8```](https://github.com/ktmeaton/ncov-recombinant/commit/00fe2fc8) docs: update notes for v0.6.1 +- [```fa03ea96```](https://github.com/ktmeaton/ncov-recombinant/commit/fa03ea96) workflow: fix bug where rbd_levels log was incorrectly named +- [```a281b75c```](https://github.com/ktmeaton/ncov-recombinant/commit/a281b75c) workflow: make lapis optional param for #201 #202 +- [```75684b55```](https://github.com/ktmeaton/ncov-recombinant/commit/75684b55) docs: update docs +- [```1085ce0e```](https://github.com/ktmeaton/ncov-recombinant/commit/1085ce0e) script: postprocess count alleles outside regions as intermissions for #195 +- [```c11770c1```](https://github.com/ktmeaton/ncov-recombinant/commit/c11770c1) param: add XAV to auto-pass for #104 #195 + +## v0.6.0 + +### Notes + +This is a major release that includes the following changes: + +- Detection of all recombinants in [Nextclade dataset 2022-10-27](https://github.com/nextstrain/nextclade_data/releases/tag/2022-10-31--11-48-49--UTC): `XA` to `XBE`. +- Implementation of recombinant sublineages (ex. `XBB.1`). +- Implementation of immune-related statistics (`rbd_level`, `immune_escape`, `ace2_binding`) from `nextclade`, the `Nextstrain` team, and Jesse Bloom's group: + + - https://github.com/nextstrain/ncov/blob/master/defaults/rbd_levels.yaml + - https://jbloomlab.github.io/SARS-CoV-2-RBD_DMS_Omicron/epistatic-shifts/ + - https://jbloomlab.github.io/SARS2_RBD_Ab_escape_maps/escape-calc/ + - https://doi.org/10.1093/ve/veac021 + - https://doi.org/10.1101/2022.09.15.507787 + - https://doi.org/10.1101/2022.09.20.508745 + +#### Dataset + +- [Issue #168](https://github.com/ktmeaton/ncov-recombinant/issues/168): NULL collection dates and NULL country is implemented. +- `controls` was updated to in include 1 strain from `XBB` for a total of 22 positive controls. The 28 negative controls were unchanged from `v0.5.1`. +- `controls-gisaid` strain list was updated to include `XA` through to `XBE` for a total of 528 positive controls. This includes sublineages such as `XBB.1` and `XBB.1.2` which synchronizes with [Nextclade Dataset 2022-10-19](https://github.com/nextstrain/nextclade_data/releases/tag/2022-10-19). The 187 negatives controls were unchanged from `v0.5.1`. + +#### Nextclade + +- [Issue #176](https://github.com/ktmeaton/ncov-recombinant/issues/176): Upgrade Nextclade dataset to tag `2022-10-27` and upgrade Nextclade to `v2.8.0`. +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Use the nextclade dataset `sars-cov-2-21L` to calculate `immune_escape` and `ace2_binding`. + +#### RBD Levels + +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Create new rule `rbd_levels` to calculate the number of key receptor binding domain (RBD) mutations. + +#### Lineage Tree + +- [Issue #185](https://github.com/ktmeaton/ncov-recombinant/issues/185): Use nextclade dataset Auspice tree for lineage hierarchy. Previously, the phylogeny of lineages was constructed from the [cov-lineages website YAML](https://github.com/cov-lineages/lineages-website/blob/master/_data/lineages.yml). Instead, we now use the tree provided with nextclade datasets, to better synchronize the lineage model with the output. + +Rather than creating the output tree in `resources/lineages.nwk`, the lineage tree will output to `data/sars-cov-2_/tree.nwk`. This is because different builts might use different nextclade datasets, and so are dataset specific output. + +#### sc2rf + +- [Issue #179](https://github.com/ktmeaton/ncov-recombinant/issues/179): Fix bug where `sc2rf/recombinants.ansi.txt` is truncated. +- [Issue #180](https://github.com/ktmeaton/ncov-recombinant/issues/180): Fix recombinant sublineages (ex. XAY.1) missing their derived mutations in the `cov-spectrum_query`. Previously, the `cov-spectrum_query` mutations were only based on the parental alleles (before recombination). This led to sublinaeges (ex. `XAY.1`, `XAY.2`) all having the exact same query. Now, the `cov-spectrum_query` will include _all_ substitutions shared between all sequences in the `cluster_id`. +- [Issue #187](https://github.com/ktmeaton/ncov-recombinant/issues/187): Document bug that occurs if duplicate sequences are present, and the initial validation was skipped by not running `scripts/create_profile.sh`. +- [Issue #191](https://github.com/ktmeaton/ncov-recombinant/issues/191) and [Issue #192](https://github.com/ktmeaton/ncov-recombinant/issues/192): Reduce false positives by ensuring that each mode of sc2rf has at least one additional parental population that serves as the alternative hypothesis. +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Implement a filter on the ratio of intermissions to alleles. Sequences will be marked as false positives if the number of intermissions (i.e. alleles that conflict with the identified parental region) is greater than or equal to the number of alleles contributed by the minor parent. This ratio indicates that there is more evidence that conflicts with recombination than there is allele evidence that supports a recombinant origin. + +#### Linelist + +- [Issue #183](https://github.com/ktmeaton/ncov-recombinant/issues/183): Recombinant sublineages. When nextclade calls a lineage (ex. `XAY.1`) which is a sublineage of a sc2rf lineage (`XAY`), we prioritize the nextclade assignment. +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Add immune-related statistics: `rbd_levels`, `rbd_substitutions`, `immune_escape`, and `ace2_binding`. + +#### Plot + +- [Issue #57](https://github.com/ktmeaton/ncov-recombinant/issues/57): Include substitutions within breakpoint intervals for breakpoint plots. This is a product of [Issue #180](https://github.com/ktmeaton/ncov-recombinant/issues/180) which provides access to _all_ substitutions. +- [Issue #112](https://github.com/ktmeaton/ncov-recombinant/issues/112): Fix bug where breakpoints plot image was out of bounds. +- [Issue #188](https://github.com/ktmeaton/ncov-recombinant/issues/188): Remove the breakpoints distribution axis (ex. `breakpoints_clade.png`) in favor of putting the legend at the top. This significant reduces plotting issues (ex. [Issue #112](https://github.com/ktmeaton/ncov-recombinant/issues/112)). +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Create new plot `rbd_level`. + +#### Validate + +##### Designated Lineages + +- [Issue #85](https://github.com/ktmeaton/ncov-recombinant/issues/85): `XAY`, updated controls +- [Issue #178](https://github.com/ktmeaton/ncov-recombinant/issues/178): `XAY.1` +- [Issue #172](https://github.com/ktmeaton/ncov-recombinant/issues/172): `XBB.1` +- [Issue #175](https://github.com/ktmeaton/ncov-recombinant/issues/175): `XBB.1.1` +- [Issue #184](https://github.com/ktmeaton/ncov-recombinant/issues/184): `XBB.1.2` +- [Issue #173](https://github.com/ktmeaton/ncov-recombinant/issues/173): `XBB.2` +- [Issue #174](https://github.com/ktmeaton/ncov-recombinant/issues/174): `XBB.3` +- [Issue #181](https://github.com/ktmeaton/ncov-recombinant/issues/181): `XBC.1` +- [Issue #182](https://github.com/ktmeaton/ncov-recombinant/issues/182): `XBC.2` +- [Issue #171](https://github.com/ktmeaton/ncov-recombinant/issues/171): `XBD` +- [Issue #177](https://github.com/ktmeaton/ncov-recombinant/issues/177): `XBE` + +##### Proposed Lineages + +- [Issue #198](https://github.com/ktmeaton/ncov-recombinant/issues/198): `proposed1229` +- [Issue #199](https://github.com/ktmeaton/ncov-recombinant/issues/199): `proposed1268` +- [Issue #197](https://github.com/ktmeaton/ncov-recombinant/issues/197): `proposed1296` + +### Commits + +- [```2506e907```](https://github.com/ktmeaton/ncov-recombinant/commit/2506e907) docs: update changelog and add v0.6.0 testing summary package +- [```0cc421e0```](https://github.com/ktmeaton/ncov-recombinant/commit/0cc421e0) docs: update all contributors +- [```cd9b6cbb```](https://github.com/ktmeaton/ncov-recombinant/commit/cd9b6cbb) resources: update issues +- [```0fa2e3c1```](https://github.com/ktmeaton/ncov-recombinant/commit/0fa2e3c1) docs: update readme +- [```375c3a76```](https://github.com/ktmeaton/ncov-recombinant/commit/375c3a76) resources: add proposed lineages for #197 #198 #199 +- [```dad989e7```](https://github.com/ktmeaton/ncov-recombinant/commit/dad989e7) param: remove BQ.1 from sc2rf mode VOC as its too close to BA.5.3 +- [```d7cb005f```](https://github.com/ktmeaton/ncov-recombinant/commit/d7cb005f) docs: update issue template lineage-validation +- [```1beac97e```](https://github.com/ktmeaton/ncov-recombinant/commit/1beac97e) resources: add XBF to curated breakpoints for #196 +- [```fae7bfdb```](https://github.com/ktmeaton/ncov-recombinant/commit/fae7bfdb) script: sc2rf implement intermission allele ratio for #195 +- [```89a41265```](https://github.com/ktmeaton/ncov-recombinant/commit/89a41265) script: additional manual curation of lineage_tree +- [```ebd3ce1f```](https://github.com/ktmeaton/ncov-recombinant/commit/ebd3ce1f) resources: update validation strains for controls-gisaid +- [```d8bff572```](https://github.com/ktmeaton/ncov-recombinant/commit/d8bff572) script: add RBD Level slide to report +- [```c1879c1d```](https://github.com/ktmeaton/ncov-recombinant/commit/c1879c1d) script: catch errors in rbd_level plotting with no recombinants +- [```63545a08```](https://github.com/ktmeaton/ncov-recombinant/commit/63545a08) script: fix bug in linelist with cluster_privates +- [```c24a7179```](https://github.com/ktmeaton/ncov-recombinant/commit/c24a7179) resources: update issues +- [```d32d557f```](https://github.com/ktmeaton/ncov-recombinant/commit/d32d557f) docs: update development notes +- [```7f825a41```](https://github.com/ktmeaton/ncov-recombinant/commit/7f825a41) script: manual fix for CK in lineage_tree +- [```fdd6f66d```](https://github.com/ktmeaton/ncov-recombinant/commit/fdd6f66d) workflow: implement rbd levels for #193 +- [```0058dd6e```](https://github.com/ktmeaton/ncov-recombinant/commit/0058dd6e) param: upgrade nextclade dataset to 2022-10-27 and reduce breakpoints of XA mode +- [```fb062c32```](https://github.com/ktmeaton/ncov-recombinant/commit/fb062c32) env: upgrade nextclade to v2.8.0 +- [```800c1e9c```](https://github.com/ktmeaton/ncov-recombinant/commit/800c1e9c) param: experiment with XAJ mode for 191 +- [```6958337f```](https://github.com/ktmeaton/ncov-recombinant/commit/6958337f) env: version control pip to v22.3 on conda-forge +- [```2bf5141b```](https://github.com/ktmeaton/ncov-recombinant/commit/2bf5141b) env: change anaconda channel to conda-forge for #170 +- [```9b484d3b```](https://github.com/ktmeaton/ncov-recombinant/commit/9b484d3b) script: allow NULL dates in metadata for #168 remove breakpoint dist axis for #188 fix breakpoints plot out of bounds for #112 +- [```90b153e7```](https://github.com/ktmeaton/ncov-recombinant/commit/90b153e7) docs: update dev notes +- [```5057814a```](https://github.com/ktmeaton/ncov-recombinant/commit/5057814a) resources: remove deprecated lineages and geo_resolutions +- [```28c1b8bd```](https://github.com/ktmeaton/ncov-recombinant/commit/28c1b8bd) resources: update issues and breakpoints +- [```379112b4```](https://github.com/ktmeaton/ncov-recombinant/commit/379112b4) profile: update validation values +- [```f8f4273c```](https://github.com/ktmeaton/ncov-recombinant/commit/f8f4273c) profile: update controls-gisaid to XBE +- [```e462cead```](https://github.com/ktmeaton/ncov-recombinant/commit/e462cead) profile: add XBB.1 to controls +- [```c2aca577```](https://github.com/ktmeaton/ncov-recombinant/commit/c2aca577) profile: increase max jobs in controls-gisaid-hpc +- [```eabbed42```](https://github.com/ktmeaton/ncov-recombinant/commit/eabbed42) param: add more BA.5 sublineages to sc2rf lineages +- [```75e674e0```](https://github.com/ktmeaton/ncov-recombinant/commit/75e674e0) workflow: implement sublineages for #183 +- [```5caaaa4f```](https://github.com/ktmeaton/ncov-recombinant/commit/5caaaa4f) workflow: use nextclade dataset for phylogeny for #185 +- [```732f5eea```](https://github.com/ktmeaton/ncov-recombinant/commit/732f5eea) resources: add XBC.1 to breakpoints for #181 +- [```2c1f09a5```](https://github.com/ktmeaton/ncov-recombinant/commit/2c1f09a5) resources: add new lineage XAY.1 to curated breakpoints for #178 +- [```b44e68e1```](https://github.com/ktmeaton/ncov-recombinant/commit/b44e68e1) script: use all substitutions for cov-spectrum for #180 and #57 +- [```9d222e1f```](https://github.com/ktmeaton/ncov-recombinant/commit/9d222e1f) script: ignore issue 848 when downloading, is manually curated +- [```98c8a912```](https://github.com/ktmeaton/ncov-recombinant/commit/98c8a912) script: bugfix where sc2rf ansi was truncated for #179 +- [```1e29d7ea```](https://github.com/ktmeaton/ncov-recombinant/commit/1e29d7ea) env: upgrade nextclade and nextclade dataset for #176 +- [```409183f5```](https://github.com/ktmeaton/ncov-recombinant/commit/409183f5) resources: update breakpoints for proposed1139 #165 + +## v0.5.1 + +### Notes + +#### Workflow + +- [Issue #169](https://github.com/ktmeaton/ncov-recombinant/issues/169): AttributeError: 'str' object has no attribute 'name' + +#### Resources + +- [Issue #167](https://github.com/ktmeaton/ncov-recombinant/issues/167): Alias key out of date, change source + +#### Validate + +##### Proposed Lineages + +- [Issue #166](https://github.com/ktmeaton/ncov-recombinant/issues/166): `proposed1138` +- [Issue #165](https://github.com/ktmeaton/ncov-recombinant/issues/165): `proposed1139` + +### Commits + +- [```799904eb```](https://github.com/ktmeaton/ncov-recombinant/commit/799904eb) docs: update CHANGELOG for v0.5.1 +- [```1f9cd623```](https://github.com/ktmeaton/ncov-recombinant/commit/1f9cd623) docs: update docs for v0.5.1 +- [```43fc4d71```](https://github.com/ktmeaton/ncov-recombinant/commit/43fc4d71) env: update tabulate channel for #169 +- [```3b9c3796```](https://github.com/ktmeaton/ncov-recombinant/commit/3b9c3796) env: version control tabulate for #169 +- [```5f57bca2```](https://github.com/ktmeaton/ncov-recombinant/commit/5f57bca2) script: update alias url for #167 +- [```31647371```](https://github.com/ktmeaton/ncov-recombinant/commit/31647371) docs: update readme hpc section + +## v0.5.0 + +### Notes + +> Please check out the `v0.5.0` [Testing Summary Package](https://ktmeaton.github.io/ncov-recombinant/docs/testing_summary_package/ncov-recombinant_v0.4.2_v0.5.0.html) for a comprehensive report. + +This is a minor release that includes the following changes: + +1. Detection of all recombinants in [Nextclade dataset 2022-09-27](https://github.com/nextstrain/nextclade_data/releases/tag/2022-09-28--16-01-10--UTC): `XA` to `XBC`. +1. Create any number of custom `sc2rf` modes with CLI arguments. + +#### Resources + +- [Issue #96](https://github.com/ktmeaton/ncov-recombinant/issues/96): Create newick phylogeny of pango lineage parent child relationships, to get accurate sublineages including aliases. +- [Issue #118](https://github.com/ktmeaton/ncov-recombinant/issues/118): Fix missing pango-designation issues for XAY and XBA. + +#### Datasets + +- [Issue #25](https://github.com/ktmeaton/ncov-recombinant/issues/25): Reduce positive controls to one sequence per clade. Add new positive controls `XAL`, `XAP`, `XAS`, `XAU`, and `XAZ`. +- [Issue #92](https://github.com/ktmeaton/ncov-recombinant/issues/92): Reduce negative controls to one sequence per clade. Add negative control for `22D (Omicron) / BA.2.75`. +- [Issue #155](https://github.com/ktmeaton/ncov-recombinant/issues/155): Add new profile and dataset `controls-gisaid`. Only a list of strains is provided, as GISAID policy prohibits public sharing of sequences and metadata. + +#### Profile Creation + +- [Issue #77](https://github.com/ktmeaton/ncov-recombinant/issues/77): Report slurm command for `--hpc` profiles in `scripts/create_profiles.sh`. +- [Issue #153](https://github.com/ktmeaton/ncov-recombinant/issues/153): Fix bug where build parameters `metadata` and `sequences` were not implemented. + +#### Nextclade + +- [Issue #81](https://github.com/ktmeaton/ncov-recombinant/issues/81): Upgrade Nextclade datasets to 2022-09-27 +- [Issue #91](https://github.com/ktmeaton/ncov-recombinant/issues/91): Upgrade Nextclade to v2.5.0 + +#### sc2rf + +- [Issue #78](https://github.com/ktmeaton/ncov-recombinant/issues/78): Add new parameter `max_breakpoint_len` to `sc2rf_recombinants` to mark samples with two much uncertainty in the breakpoint interval as false positives. +- [Issue #79](https://github.com/ktmeaton/ncov-recombinant/issues/79): Add new parameter `min_consec_allele` to `sc2rf_recombinants` to ignore recombinant regions with less than this number of consecutive alleles (both diagnostic SNPs and diganostic reference alleles). +- [Issue #80](https://github.com/ktmeaton/ncov-recombinant/issues/80): Migrate [sc2rf](https://github.com/lenaschimmel/sc2rf) froma submodule to a subdirectory (including LICENSE!). This is to simplify the updating process and avoid errors where submodules became out of sync with the main pipeline. +- [Issue #83](https://github.com/ktmeaton/ncov-recombinant/issues/83): Improve error handling in `sc2rf_recombinants` when the input stats files are empty. +- [Issue #89](https://github.com/ktmeaton/ncov-recombinant/issues/89): Reduce the default value of the parameter `min_len` in `sc2rf_recombinants` from `1000` to `500`.This is to handle `XAP` and `XAJ`. +- [Issue #90](https://github.com/ktmeaton/ncov-recombinant/issues/90): Auto-pass select nextclade lineages through `sc2rf`: `XN`, `XP`, `XAR`, `XAS`, and `XAZ`. This requires differentiating the nextclade inputs as separate parameters `--nextclade` and `--nextclade-no-recom`. + + `XN`,`XP`, and `XAR` have extremely small recombinant regions at the terminal ends of the genome. Depending on sequencing coverage, `sc2rf` may not reliably detect these lineages. + + The newly designated `XAS` and `XAZ` pose a challenge for recombinant detection using diagnostic alleles. The first region of `XAS` could be either `BA.5` or `BA.4` based on subsitutions, but is mostly likely `BA.5` based on deletions. Since the region contains no diagnostic alleles to discriminate `BA.5` vs. `BA.4`, breakpoints cannot be detected by `sc2rf`. + + Similarly for `XAZ`, the `BA.2` segments do not contain any `BA.2` diagnostic alleles, but instead are all reversion from `BA.5` alleles. The `BA.2` parent was discovered by deep, manual investigation in the corresponding pango-designation issue. Since the `BA.2` regions contain no diagnostic for `BA.2`, breakpoints cannot be detected by `sc2rf`. + +- [Issue #95](https://github.com/ktmeaton/ncov-recombinant/issues/95): Generalize `sc2rf_recombinants` to take any number of ansi and csv input files. This allows greater flexibility in command-line arguments to `sc2rf` and are not locked into the hardcoded `primary` and `secondary` parameter sets. +- [Issue #96](https://github.com/ktmeaton/ncov-recombinant/issues/96): Include sub-lineage proportions in the `parents_lineage_confidence`. This reduces underestimating the confidence of a parental lineage. +- [Issue #150](https://github.com/ktmeaton/ncov-recombinant/issues/150): Fix bug where `sc2rf` would write empty output csvfiles if no recombinants were found. +- [Issue #151](https://github.com/ktmeaton/ncov-recombinant/issues/151): Fix bug where samples that failed to align were missing from the linelists. +- [Issue #158](https://github.com/ktmeaton/ncov-recombinant/issues/158): Reduce `sc2rf` param `--max-intermission-length` from `3` to `2` to be consistent with [Issue #79](https://github.com/ktmeaton/ncov-recombinant/issues/79). +- [Issue #161](https://github.com/ktmeaton/ncov-recombinant/issues/161): Implement selection method to pick best results from various `sc2rf` modes. +- [Issue #162](https://github.com/ktmeaton/ncov-recombinant/issues/162): Upgrade `sc2rf/virus_properties.json`. +- [Issue #163](https://github.com/ktmeaton/ncov-recombinant/issues/163): Use LAPIS `nextcladePangoLineage` instead of `pangoLineage`. Also disable default filter `max_breakpoint_len` for `XAN`. +- [Issue #164](https://github.com/ktmeaton/ncov-recombinant/issues/164): Fix bug where false positives would appear in the filter `sc2rf` ansi output (`recombinants.ansi.txt`). +- The optional `lapis` parameter for `sc2rf_recombinants` has been removed. Querying [LAPIS](https://lapis.cov-spectrum.org/) for parental lineages is no longer experimental and is now an essential component (cannot be disabled). +- The mandatory `mutation_threshold` parameter for `sc2rf` has been removed. Instead, `--mutation-threshold` can be set independently in each of the `scrf` modes. + +#### Linelist + +- [Issue #157](https://github.com/ktmeaton/ncov-recombinant/issues/157]): Create new parameters `min_lineage_size` and `min_private_muts` to control lineage splitting into `X*-like`. + +#### Plot + +- [Issue #17](https://github.com/ktmeaton/ncov-recombinant/issues/17]): Create script to plot lineage assignment changes between versions using a Sankey diagram. +- [Issue #82](https://github.com/ktmeaton/ncov-recombinant/issues/82]): Change epiweek start from Monday to Sunday. +- [Issue #111](https://github.com/ktmeaton/ncov-recombinant/issues/111]): Fix breakpoint distribution axis that was empty for clade. +- [Issue #152](https://github.com/ktmeaton/ncov-recombinant/issues/152): Fix file saving bug when largest lineage has `/` characters. + +#### Report + +- [Issue #88](https://github.com/ktmeaton/ncov-recombinant/issues/88): Add pipeline and nextclade versions to powerpoint slides as footer. This required adding `--summary` as param to `report`. + +#### Validate + +- [Issue #56](https://github.com/ktmeaton/ncov-recombinant/issues/56): Change rule `validate` from simply counting the number of positives to validating the fields `lineage`, `breakpoints`, `parents_clade`. This involves adding a new default parameter `expected` for rule `validate` in `defaults/parameters.yaml`. + +##### Designated Lineages + +- [Issue #149](https://github.com/ktmeaton/ncov-recombinant/issues/149): `XA` +- [Issue #148](https://github.com/ktmeaton/ncov-recombinant/issues/148): `XB` +- [Issue #147](https://github.com/ktmeaton/ncov-recombinant/issues/147): `XC` +- [Issue #146](https://github.com/ktmeaton/ncov-recombinant/issues/146): `XD` +- [Issue #145](https://github.com/ktmeaton/ncov-recombinant/issues/145): `XE` +- [Issue #144](https://github.com/ktmeaton/ncov-recombinant/issues/144): `XF` +- [Issue #143](https://github.com/ktmeaton/ncov-recombinant/issues/143): `XG` +- [Issue #141](https://github.com/ktmeaton/ncov-recombinant/issues/141): `XH` +- [Issue #142](https://github.com/ktmeaton/ncov-recombinant/issues/142): `XJ` +- [Issue #140](https://github.com/ktmeaton/ncov-recombinant/issues/140): `XK` +- [Issue #139](https://github.com/ktmeaton/ncov-recombinant/issues/139): `XL` +- [Issue #138](https://github.com/ktmeaton/ncov-recombinant/issues/138): `XM` +- [Issue #137](https://github.com/ktmeaton/ncov-recombinant/issues/137): `XN` +- [Issue #136](https://github.com/ktmeaton/ncov-recombinant/issues/136): `XP` +- [Issue #135](https://github.com/ktmeaton/ncov-recombinant/issues/135): `XQ` +- [Issue #134](https://github.com/ktmeaton/ncov-recombinant/issues/134): `XR` +- [Issue #133](https://github.com/ktmeaton/ncov-recombinant/issues/133): `XS` +- [Issue #132](https://github.com/ktmeaton/ncov-recombinant/issues/132): `XT` +- [Issue #131](https://github.com/ktmeaton/ncov-recombinant/issues/131): `XU` +- [Issue #130](https://github.com/ktmeaton/ncov-recombinant/issues/130): `XV` +- [Issue #129](https://github.com/ktmeaton/ncov-recombinant/issues/129): `XW` +- [Issue #128](https://github.com/ktmeaton/ncov-recombinant/issues/128): `XY` +- [Issue #127](https://github.com/ktmeaton/ncov-recombinant/issues/127): `XZ` +- [Issue #126](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAA` +- [Issue #125](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAB` +- [Issue #124](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAC` +- [Issue #123](https://github.com/ktmeaton/ncov-recombinant/issues/123): `XAD` +- [Issue #122](https://github.com/ktmeaton/ncov-recombinant/issues/122): `XAE` +- [Issue #120](https://github.com/ktmeaton/ncov-recombinant/issues/120): `XAF` +- [Issue #121](https://github.com/ktmeaton/ncov-recombinant/issues/119): `XAG` +- [Issue #119](https://github.com/ktmeaton/ncov-recombinant/issues/119): `XAH` +- [Issue #117](https://github.com/ktmeaton/ncov-recombinant/issues/117): `XAJ` +- [Issue #116](https://github.com/ktmeaton/ncov-recombinant/issues/116): `XAK` +- [Issue #115](https://github.com/ktmeaton/ncov-recombinant/issues/115): `XAL` +- [Issue #110](https://github.com/ktmeaton/ncov-recombinant/issues/110): `XAM` +- [Issue #109](https://github.com/ktmeaton/ncov-recombinant/issues/109): `XAN` +- [Issue #108](https://github.com/ktmeaton/ncov-recombinant/issues/108): `XAP` +- [Issue #107](https://github.com/ktmeaton/ncov-recombinant/issues/107): `XAQ` +- [Issue #87](https://github.com/ktmeaton/ncov-recombinant/issues/87): `XAS` +- [Issue #105](https://github.com/ktmeaton/ncov-recombinant/issues/102): `XAT` +- [Issue #103](https://github.com/ktmeaton/ncov-recombinant/issues/103): `XAU` +- [Issue #104](https://github.com/ktmeaton/ncov-recombinant/issues/104): `XAV` +- [Issue #105](https://github.com/ktmeaton/ncov-recombinant/issues/105): `XAW` +- [Issue #85](https://github.com/ktmeaton/ncov-recombinant/issues/85): `XAY` +- [Issue #87](https://github.com/ktmeaton/ncov-recombinant/issues/87): `XAZ` +- [Issue #94](https://github.com/ktmeaton/ncov-recombinant/issues/94): `XBA` +- [Issue #114](https://github.com/ktmeaton/ncov-recombinant/issues/14): `XBB` +- [Issue #160](https://github.com/ktmeaton/ncov-recombinant/issues/160): `XBC` + +##### Proposed Lineages + +- [Issue #99](https://github.com/ktmeaton/ncov-recombinant/issues/99): `proposed808` + +### Pull Requests + +- [```pull/113```](https://github.com/ktmeaton/ncov-recombinant/pull/113) docs: add issues template for lineage validation + +### Commits + +- [```b48ad6d7```](https://github.com/ktmeaton/ncov-recombinant/commit/b48ad6d7) docs: fix CHANGELOG pr +- [```04b17918```](https://github.com/ktmeaton/ncov-recombinant/commit/04b17918) docs: update readme and changelog +- [```72dd5a8f```](https://github.com/ktmeaton/ncov-recombinant/commit/72dd5a8f) docs: add testing summary package for v0.4.2 to v0.5.0 +- [```558f7d79```](https://github.com/ktmeaton/ncov-recombinant/commit/558f7d79) resources: fix breakpoints for XAE #122 +- [```91e5843b```](https://github.com/ktmeaton/ncov-recombinant/commit/91e5843b) script: bugfix sc2rf ansi output for #164 +- [```9bc13639```](https://github.com/ktmeaton/ncov-recombinant/commit/9bc13639) docs: update issues and validation table order +- [```b63520e5```](https://github.com/ktmeaton/ncov-recombinant/commit/b63520e5) script: implement lineage check in dups for #117 #161 +- [```901898da```](https://github.com/ktmeaton/ncov-recombinant/commit/901898da) sc2rf updates for #158 #161 #162 #163 +- [```96fa6af1```](https://github.com/ktmeaton/ncov-recombinant/commit/96fa6af1) dataset: update controls-gisaid strain list and validation +- [```84466a10```](https://github.com/ktmeaton/ncov-recombinant/commit/84466a10) workflow: new param dup_method for #161 +- [```9ca0c71e```](https://github.com/ktmeaton/ncov-recombinant/commit/9ca0c71e) script: implement duplicate reconciliation for #161 +- [```112ea684```](https://github.com/ktmeaton/ncov-recombinant/commit/112ea684) param: upgrade nextclade dataset for #159 +- [```859b92c8```](https://github.com/ktmeaton/ncov-recombinant/commit/859b92c8) script: add more detail to validate table for failing samples +- [```5e285912```](https://github.com/ktmeaton/ncov-recombinant/commit/5e285912) script: add param --min-link-size to compare_positives +- [```bd01a5e4```](https://github.com/ktmeaton/ncov-recombinant/commit/bd01a5e4) workflow: added failed validate output to rule log +- [```8e5b90fb```](https://github.com/ktmeaton/ncov-recombinant/commit/8e5b90fb) workflow: don't use metadata for sc2rf_recombinants when exclude_negatives is true +- [```cdf45407```](https://github.com/ktmeaton/ncov-recombinant/commit/cdf45407) param: add new params min-lineage-size and min-private-muts for #157 +- [```bc04fddf```](https://github.com/ktmeaton/ncov-recombinant/commit/bc04fddf) workflow: update validation strains for #155 +- [```6aa95221```](https://github.com/ktmeaton/ncov-recombinant/commit/6aa95221) param: fix typo of missing --mutation-threshold +- [```25df848c```](https://github.com/ktmeaton/ncov-recombinant/commit/25df848c) param: remove param mutation_threshold as universal param for sc2rf +- [```46d2ee95```](https://github.com/ktmeaton/ncov-recombinant/commit/46d2ee95) dataset: remove false positive LC0797902 from negative controls +- [```b106b9d1```](https://github.com/ktmeaton/ncov-recombinant/commit/b106b9d1) profile: change default hpc jobs from 2 to 10 +- [```d6d02721```](https://github.com/ktmeaton/ncov-recombinant/commit/d6d02721) workflow: update validation table +- [```d308d54b```](https://github.com/ktmeaton/ncov-recombinant/commit/d308d54b) script: fix node ordering in compare_positives +- [```ea65c6ff```](https://github.com/ktmeaton/ncov-recombinant/commit/ea65c6ff) ci: remove GISAID workflow for #154 +- [```122e579c```](https://github.com/ktmeaton/ncov-recombinant/commit/122e579c) ci: test storing csv files as secrets for #154 +- [```d281add4```](https://github.com/ktmeaton/ncov-recombinant/commit/d281add4) ci: experiment with secrets with test data for #154 +- [```1d5406f5```](https://github.com/ktmeaton/ncov-recombinant/commit/1d5406f5) script: generalize compare_positives to use other lineage columns +- [```ffd4f159```](https://github.com/ktmeaton/ncov-recombinant/commit/ffd4f159) scripts: fix bug where metadata and sequences param were not implemented for #153 +- [```7974860a```](https://github.com/ktmeaton/ncov-recombinant/commit/7974860a) resources: special handling of proposed808 issues and breakpoints for #99 +- [```d0e3f41a```](https://github.com/ktmeaton/ncov-recombinant/commit/d0e3f41a) script: fix file saving bug in report for #152 +- [```f7d3157b```](https://github.com/ktmeaton/ncov-recombinant/commit/f7d3157b) script: fix file saving bug in plot for #152 +- [```f9931bb3```](https://github.com/ktmeaton/ncov-recombinant/commit/f9931bb3) script: fix missing samples in sc2rf output for #151 +- [```18b94df5```](https://github.com/ktmeaton/ncov-recombinant/commit/18b94df5) script: force sc2rf to always output csvfile headers for #150 +- [```e1f14dfe```](https://github.com/ktmeaton/ncov-recombinant/commit/e1f14dfe) resources: update breakpoints for proposed808 #99 +- [```35aaa922```](https://github.com/ktmeaton/ncov-recombinant/commit/35aaa922) resources: update breakpoints for XA - XAZ +- [```05cba895```](https://github.com/ktmeaton/ncov-recombinant/commit/05cba895) resources: update breakpoints for XV #130 +- [```1b0a02bf```](https://github.com/ktmeaton/ncov-recombinant/commit/1b0a02bf) resources: add gauntlet samples (all XA*) to validation +- [```29c7798d```](https://github.com/ktmeaton/ncov-recombinant/commit/29c7798d) param: add XAR to sc2rf auto-pass for 106 +- [```0e6b413e```](https://github.com/ktmeaton/ncov-recombinant/commit/0e6b413e) docs: change next ver from v0.4.3 to v0.5.0 +- [```f8197e80```](https://github.com/ktmeaton/ncov-recombinant/commit/f8197e80) workflow: fix bug in rule validate where path was hard-coded +- [```abb4dec6```](https://github.com/ktmeaton/ncov-recombinant/commit/abb4dec6) resources: update breakpoints for XAA #126 +- [```d012b936```](https://github.com/ktmeaton/ncov-recombinant/commit/d012b936) resources: update breakpoints for XAG and XAH for #120 and #121 +- [```d389e048```](https://github.com/ktmeaton/ncov-recombinant/commit/d389e048) param: add new XAJ mode for sc2rf for #117 +- [```be853ac1```](https://github.com/ktmeaton/ncov-recombinant/commit/be853ac1) scripts: update rule validate for #56 +- [```a02b4deb```](https://github.com/ktmeaton/ncov-recombinant/commit/a02b4deb) docs: add issues template for lineage validation #113 +- [```1b3cb780```](https://github.com/ktmeaton/ncov-recombinant/commit/1b3cb780) script: fix bug of missing issues for #118 +- [```82d9ce32```](https://github.com/ktmeaton/ncov-recombinant/commit/82d9ce32) docs: update validation release notes +- [```1b705a6a```](https://github.com/ktmeaton/ncov-recombinant/commit/1b705a6a) resources: update XAU breakpoints for #103 +- [```18021fe3```](https://github.com/ktmeaton/ncov-recombinant/commit/18021fe3) docs: add XAQ issue #107 to release notes +- [```7ca8f06f```](https://github.com/ktmeaton/ncov-recombinant/commit/7ca8f06f) docs: add XAQ issue #107 to release notes +- [```e9d8f905```](https://github.com/ktmeaton/ncov-recombinant/commit/e9d8f905) docs: add issue #111 to release notes +- [```a638835a```](https://github.com/ktmeaton/ncov-recombinant/commit/a638835a) script: fix bug in plot_breakpoints when axis empty for #111 +- [```ba7ec30c```](https://github.com/ktmeaton/ncov-recombinant/commit/ba7ec30c) resources: update breakpoints for XAP #108 +- [```d3952e44```](https://github.com/ktmeaton/ncov-recombinant/commit/d3952e44) docs: fix typo in relesae notes +- [```d56956d6```](https://github.com/ktmeaton/ncov-recombinant/commit/d56956d6) docs: add issues #86 and #87 to release notes +- [```00a706a8```](https://github.com/ktmeaton/ncov-recombinant/commit/00a706a8) script: remove redundant --clades arg in sc2rf bash script +- [```378eea62```](https://github.com/ktmeaton/ncov-recombinant/commit/378eea62) param: add new sc2rf modes XB and proposed808 for #98 and #99 +- [```bb802647```](https://github.com/ktmeaton/ncov-recombinant/commit/bb802647) docs: add issue #17 to release notes +- [```b6688c86```](https://github.com/ktmeaton/ncov-recombinant/commit/b6688c86) env: add plotly to conda env and control all versions +- [```adc6777e```](https://github.com/ktmeaton/ncov-recombinant/commit/adc6777e) script: improve directory creation in compare positives +- [```15a1fc04```](https://github.com/ktmeaton/ncov-recombinant/commit/15a1fc04) script: add breakpoint axis label for #97 +- [```f256a75f```](https://github.com/ktmeaton/ncov-recombinant/commit/f256a75f) docs: add notes for v0.4.3 +- [```c3785fa0```](https://github.com/ktmeaton/ncov-recombinant/commit/c3785fa0) env: upgrade csvtk to v0.24.0 +- [```7936e0ef```](https://github.com/ktmeaton/ncov-recombinant/commit/7936e0ef) param: fix typo in mode omicron_omicron +- [```d014d0a1```](https://github.com/ktmeaton/ncov-recombinant/commit/d014d0a1) param: revert XAS mode to default for #86 +- [```ea83d78e```](https://github.com/ktmeaton/ncov-recombinant/commit/ea83d78e) script: fix bug in postprocess where max_breakpoint_len was not checked +- [```ab030e21```](https://github.com/ktmeaton/ncov-recombinant/commit/ab030e21) param: add new XAS mode to default sc2rf runs for #86 +- [```6ccd0aa8```](https://github.com/ktmeaton/ncov-recombinant/commit/6ccd0aa8) workflow: first draft of pango lineage tree for #96 +- [```9d2382cb```](https://github.com/ktmeaton/ncov-recombinant/commit/9d2382cb) workflow: add param fix for postprocess inputs +- [```93007726```](https://github.com/ktmeaton/ncov-recombinant/commit/93007726) script: fix cli --clades arg parsing for scr2rf.sh +- [```bed29fdb```](https://github.com/ktmeaton/ncov-recombinant/commit/bed29fdb) script: add new csv col alleles to sc2rf +- [```bd681d5e```](https://github.com/ktmeaton/ncov-recombinant/commit/bd681d5e) workflow: generalize sc2rf_recombinants inputs for #95 +- [```0315ffd6```](https://github.com/ktmeaton/ncov-recombinant/commit/0315ffd6) docs: update development docs +- [```70111447```](https://github.com/ktmeaton/ncov-recombinant/commit/70111447) resources: update breakpoints and issues +- [```076e14bb```](https://github.com/ktmeaton/ncov-recombinant/commit/076e14bb) dataset: reduce controls to one sequence per clade for #25,92 +- [```77d2210d```](https://github.com/ktmeaton/ncov-recombinant/commit/77d2210d) workflow: update rules for #46, #88, #89, #90 +- [```d84205a0```](https://github.com/ktmeaton/ncov-recombinant/commit/d84205a0) script: add new param auto_pass for #90 +- [```99b895a4```](https://github.com/ktmeaton/ncov-recombinant/commit/99b895a4) params: update params for #46, #89, #90 +- [```3e3d1022```](https://github.com/ktmeaton/ncov-recombinant/commit/3e3d1022) script: add pipeline version to report for #88 +- [```2e6ac558```](https://github.com/ktmeaton/ncov-recombinant/commit/2e6ac558) script: remove sc2rf_ver col from summary for #80 +- [```18c35940```](https://github.com/ktmeaton/ncov-recombinant/commit/18c35940) env: upgrade nextclade to v2.5.0 for #91 +- [```a67e1159```](https://github.com/ktmeaton/ncov-recombinant/commit/a67e1159) workflow: autopass XAS through sc2rf for #86 +- [```2e16dac5```](https://github.com/ktmeaton/ncov-recombinant/commit/2e16dac5) resources: update breakpoints and mutations +- [```a7026450```](https://github.com/ktmeaton/ncov-recombinant/commit/a7026450) workflow: upgrade nextclade dataset to 2022-08-23 for #81 +- [```53fb4a8a```](https://github.com/ktmeaton/ncov-recombinant/commit/53fb4a8a) workflow: re-add sc2rf as subdirectory for #80 +- [```4b8b3fab```](https://github.com/ktmeaton/ncov-recombinant/commit/4b8b3fab) workflow: remove sc2rf submodule again +- [```b650e562```](https://github.com/ktmeaton/ncov-recombinant/commit/b650e562) workflow: add sc2rf as subdirectory for #80 +- [```073f3b94```](https://github.com/ktmeaton/ncov-recombinant/commit/073f3b94) workflow: remove sc2rf as submodule +- [```5ab5c1b5```](https://github.com/ktmeaton/ncov-recombinant/commit/5ab5c1b5) resources: updated curated breakpoints +- [```5635b872```](https://github.com/ktmeaton/ncov-recombinant/commit/5635b872) resources: update issues +- [```78e1f064```](https://github.com/ktmeaton/ncov-recombinant/commit/78e1f064) script: change epiweek to start on Sundary (cdc) for #82 +- [```37f40480```](https://github.com/ktmeaton/ncov-recombinant/commit/37f40480) script: add tables to compare positives between versions for #17 +- [```8eef7548```](https://github.com/ktmeaton/ncov-recombinant/commit/8eef7548) script: create new script to compare positives between versions +- [```ebf1e222```](https://github.com/ktmeaton/ncov-recombinant/commit/ebf1e222) script: compare linelists from different versions for #17 +- [```8401c353```](https://github.com/ktmeaton/ncov-recombinant/commit/8401c353) workflow: add new param max_breakpoint_len for #78 +- [```8bbcc041```](https://github.com/ktmeaton/ncov-recombinant/commit/8bbcc041) script: report slurm command for --hpc profiles for #77 +- [```c40a6791```](https://github.com/ktmeaton/ncov-recombinant/commit/c40a6791) workflow: restrict config rules to one thread +- [```c2b1ea57```](https://github.com/ktmeaton/ncov-recombinant/commit/c2b1ea57) script: revert unpublished lineages for #76 +- [```dbe359c8```](https://github.com/ktmeaton/ncov-recombinant/commit/dbe359c8) resources: add 882 to breakpoints + +## v0.4.2 + +### Notes + +This is a minor bug fix and enhancement release with the following changes: + +#### Linelist + +- [Issue #70](https://github.com/ktmeaton/ncov-recombinant/issues/70): Fix missing `sc2rf` version from `recombinant_classifier_dataset` +- [Issue #74](https://github.com/ktmeaton/ncov-recombinant/issues/74): Correctly identify `XN-like` and `XP-like`. Previously, these were just assigned `XN`/`XP` regardless of whether the estimated breakpoints conflicted with the curated ones. +- [Issue #76](https://github.com/ktmeaton/ncov-recombinant/issues/76): Mark undesignated lineages with no matching sc2rf lineage as `unpublished`. + +#### Plot + +- [Issue #71](https://github.com/ktmeaton/ncov-recombinant/issues/71): Only truncate `cluster_id` while plotting, not in table generation. +- [Issue #72](https://github.com/ktmeaton/ncov-recombinant/issues/72): For all plots, truncate the legend labels to a set number of characters. The exception to this are parent labels (clade,lineage) because the full label is informative. +- [Issue #73](https://github.com/ktmeaton/ncov-recombinant/issues/73), [#75](https://github.com/ktmeaton/ncov-recombinant/issues/75): For all plots except breakpoints, lineages will be defined by the column `recombinant_lineage_curated`. Previously it was defined by the combination of `recombinant_lineage_curated` and `cluster_id`, which made cluttered plots that were too difficult to interpret. +- New parameter `--lineage-col` was added to `scripts/plot_breakpoints.py` to have more control on whether we want to plot the raw lineage (`lineage`) or the curated lineage (`recombinant_lineage_curated`). + +### Commits + +- [```8953ef03```](https://github.com/ktmeaton/ncov-recombinant/commit/8953ef03) docs: add CHANGELOG for v0.4.2 +- [```7ec5ccc6```](https://github.com/ktmeaton/ncov-recombinant/commit/7ec5ccc6) docs: add notes for v0.4.2 +- [```1b3b1f1d```](https://github.com/ktmeaton/ncov-recombinant/commit/1b3b1f1d) script: restore column name to recombinant_classifer_dataset +- [```901caf98```](https://github.com/ktmeaton/ncov-recombinant/commit/901caf98) script: restore recombinant_lineage_curated of -like lineages +- [```d6be9611```](https://github.com/ktmeaton/ncov-recombinant/commit/d6be9611) script: change internal delim of classifier for #70 +- [```cdb4a78a```](https://github.com/ktmeaton/ncov-recombinant/commit/cdb4a78a) script: fix recombinant_classifier missing sc2rf for #70 +- [```bf7a4e57```](https://github.com/ktmeaton/ncov-recombinant/commit/bf7a4e57) script: mark undesignated lineages with no matching sc2rf lineage as unpublished for #76 +- [```46f6d754```](https://github.com/ktmeaton/ncov-recombinant/commit/46f6d754) workflow: update linelists and plotting for #74 and #75 +- [```c03dd3be```](https://github.com/ktmeaton/ncov-recombinant/commit/c03dd3be) script: don't split largest by cluster id for #73 +- [```e9802e79```](https://github.com/ktmeaton/ncov-recombinant/commit/e9802e79) script: majority of plots will not split by cluster_id for #73 +- [```bafb38fb```](https://github.com/ktmeaton/ncov-recombinant/commit/bafb38fb) script: fix cluster ID truncation for issue #71 +- [```ab712593```](https://github.com/ktmeaton/ncov-recombinant/commit/ab712593) resources: curate and test breakpoints for proposed895 + +## v0.4.1 + +### Notes + +This is a minor bug fix release with the following changes: + +- [Issue #63](https://github.com/ktmeaton/ncov-recombinant/issues/63): Remove `usher` and `protobuf` from the conda environment. +- [Issue #68](https://github.com/ktmeaton/ncov-recombinant/issues/68): Remove [ncov](https://github.com/nextstrain/ncov) as a submodule. +- [Issue #69](https://github.com/ktmeaton/ncov-recombinant/issues/69): Remove 22C and 22D from `sc2rf/mapping.csv` and `sc2rf/virus_properties.json`, as these interfere with breakpoint detection for XAN. + +### Commits + +- [```88650696```](https://github.com/ktmeaton/ncov-recombinant/commit/88650696) docs: add CHANGELOG for v0.4.1 +- [```00a2eec3```](https://github.com/ktmeaton/ncov-recombinant/commit/00a2eec3) docs: add notes for v0.4.1 +- [```d74a81d3```](https://github.com/ktmeaton/ncov-recombinant/commit/d74a81d3) sc2rf: revert 22C and 22D clade addition +- [```7b662940```](https://github.com/ktmeaton/ncov-recombinant/commit/7b662940) env: remove usher for issue #63 +- [```adf92399```](https://github.com/ktmeaton/ncov-recombinant/commit/adf92399) submodule: remove ncov for issue #68 +- [```0790aa04```](https://github.com/ktmeaton/ncov-recombinant/commit/0790aa04) docs: update CHANGELOG for v0.4.0 + +## v0.4.0 + +### Notes + +#### General + +v0.4.0 has been trained and validated on the latest generation of SARS-CoV-2 Omicron clades (ex. 22A/BA.4 and 22B/BA.5). Recombinant sequences involving BA.4 and BA.5 can now be detected, unlike in v0.3.0 where they were not included in the `sc2rf` models. + +v0.4.0 is also a **major** update to how sequences are categorized into lineages/clusters. A recombinant lineage is now defined as a group of sequences with a unique combination of: + +- Lineage assignment (ex. `XM`) +- Parental clades (ex. `Omicron/21K,Omicron/21L`) +- Breakpoints (ex. `17411:21617`) +- **NEW**: Parental lineages (ex. `BA.1.1,BA.2.12.1`) + +Novel recombinants (i.e. undesignated) can be identified by a lineage assignment that does not start with `X*` (ex. `BA.1.1`) _or_ with a lineage assignment that contains `-like` (ex. `XM-like`). A cluster of sequences may be flagged as `-like` if one of the following criteria apply: + +1. The lineage assignment by [Nextclade](https://github.com/nextstrain/nextclade) conflicts with the published breakpoints for a designated lineage (`resources/breakpoints.tsv`). + + - Ex. An `XE` assigned sample has breakpoint `11538:12879`, which conflicts with the published `XE` breakpoint (`ex. 8394:12879`). This will be renamed `XE-like`. + +1. The cluster has 10 or more sequences, which share at least 3 private mutations in common. + + - Ex. A large cluster of sequences (N=50) are assigned `XM`. However, these 50 samples share 5 private mutations `T2470C,C4586T,C9857T,C12085T,C26577G` which do not appear in true `XM` sequences. These will be renamed `XM-like`. Upon further review of the reported matching [pango-designation issues](https://github.com/cov-lineages/pango-designation/issues) (`460,757,781,472,798`), we find this cluster to be a match to `proposed798`. + +The ability to identify parental lineages and private mutations is largely due to improvements in the [newly released nextclade datasets](https://github.com/nextstrain/nextclade_data/releases/tag/2022-07-26--13-04-52--UTC), , which have increased recombinant lineage accuracy. As novel recombinants can now be identified without the use of the custom UShER annotations (ex. proposed771), all UShER rules and output have been removed. This significantly improves runtime, and reduces the need to drop non-recombinant samples for performance. The result is more comparable output between different dataset sizes (4 samples vs. 400,000 samples). + +> **Note!** Default parameters have been updated! Please regenerate your profiles/builds with: +> +> ```bash +> scripts/create_profile.sh --data data/custom +> ``` + +#### Datasets + +- [Issue #49](https://github.com/ktmeaton/ncov-recombinant/issues/49): The tutorial lineages were changed from `XM`,`proposed467`, `miscBA1BA2Post17k`, to `XD`, `XH`, `XAN`. The previous tutorial sequences had genome quality issues. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Add `XAN` to the controls dataset. This is BA.2/BA.5 recombinant. +- [Issue #62](https://github.com/ktmeaton/ncov-recombinant/issues/62): Add `XAK` to the controls dataset. This is BA.2/BA.1 VUM recombinant monitored by the ECDC. + +#### Nextclade + +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): `nextclade` is now run twice. Once with the regular `sars-cov-2` dataset and once with the `sars-cov-2-no-recomb` dataset. The `sars-cov-2-no-recomb` dataset is used to get the nucleotide substitutions before recombination occurred. These are identified by taking the `substitutions` column, and excluding the substitutions found in `privateNucMutations.unlabeledSubstitutions`. The pre-recombination substitutions allow us to identify the parental lineages by querying [cov-spectrum](https://cov-spectrum.org/). +- [Issue #48](https://github.com/ktmeaton/ncov-recombinant/issues/48): Make the `exclude_clades` completely optional. Otherwise an error would be raised if the user didn't specify any. +- [Issue #50](https://github.com/ktmeaton/ncov-recombinant/issues/50): Upgrade from `v1.11.0` to `v2.3.0`. Also upgrade the default dataset tags to [2022-07-26T12:00:00Z](https://github.com/nextstrain/nextclade_data/releases/tag/2022-07-26--13-04-52--UTC) which had significant bug fixes. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Relax the recombinant criteria, by flagging sequences with ANY labelled private mutations as a potential recombinant for further downstream analysis. This was specifically for BA.5 recombinants (ex. `XAN`) as no other columns from the `nextclade` output indicated this could be a recombinant. +- Restrict `nextclade` output to `fasta,tsv` (alignment and QC table). This saves on file storage, as the other default output is not used. + +#### sc2rf + +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): `sc2rf` is now run twice. First, to detect recombination between clades (ex. `Delta/21J` & `Omicron/21K`). Second, to detect recombination within Omicron (ex. `Omicron/BA.2/21L` & `Omicron/BA.5/22B`). It was not possible to define universal parameters for `sc2rf` that worked for both distantly related clades, and the closely related Omicron lineages. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Rename parameter `clades` to `primary_clades` and add new parameter `secondary_clades` for detecting BA.5. +- [Issue #53](https://github.com/ktmeaton/ncov-recombinant/issues/53): Identify the parental lineages by splitting up the observed mutations (from `nextclade`) into regions by breakpoint. Then query the list of mutations in and report the lineage with the highest prevalence. +- Tested out `--enable-deletions` again, which caused issues for `XD`. This confirms that using deletions is still ineffective for defining breakpoints. +- Add `B.1.631` and `B.1.634` to `sc2rf/mapping.tsv` and as potential clades in the default parameters. These are parents for `XB`. +- Add `B.1.438.1` to `sc2rf/mapping.tsv` and as a otential clade in the default parameters. This is a parent for [`proposed808`](https://github.com/cov-lineages/pango-designation/issues/808). +- Require a recombinant region to have at least one substitution unique to the parent (i.e. diagnostic). This reduces false positives. +- Remove the debugging mode, as it produced overly verbose output. It is more efficient to rerun manually with custom parameters tailored to the kind of debugging required. +- Change parent clade nomenclature from `Omicron/21K` to the more comprehensive `Omicron/BA.1/21K`. This makes it clear which lineage is involved, since it's not always obvious how Nextclade clades map to pango lineages. + +#### UShER + +- [Issue #63](https://github.com/ktmeaton/ncov-recombinant/issues/63): All UShER rules and output have been removed. First, because the latest releases of nextclade datasets (tag `2022-07-26T12:00:00Z`) have dramatically improved lineage assignment accuracy for recombinants. Second, was to improve runtime and simplicity of the workflow, as UShER adds significantly to runtime. + +#### Linelist + +- [Issue #30](https://github.com/ktmeaton/ncov-recombinant/issues/30): Fixed the bug where distinct recombinant lineages would occasionally be grouped into one `cluster_id`. This is due to the new definition for recombinant lineages (see General) section, which now includes parental _lineages_ and have sufficient resolving power. +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): Added new column `parents_subs`, which are the substitutions found in the parental lineages _before_ recombination occurred using the `sars-cov-2-no-recomb` nextclade dataset. Also added new columns: `parents_lineage`, `parents_lineage_confidence`, based on querying `cov-spectrum` for the substitutions found in `parents_subs`. +- [Issue #53](https://github.com/ktmeaton/ncov-recombinant/issues/53): Added new column `cov-spectrum_query` which includes the substitutions that are shared by ALL sequences of the recombinant lineage. +- Added new column `cluster_privates` which includes the private substitutions shared by ALL sequences of the recombinant lineage. +- Renamed `parents` column to `parents_clade`, to differentiate it from the new column `parents_lineage`. + +#### Plot + +- [Issue #4](https://github.com/ktmeaton/ncov-recombinant/issues/4), [Issue #57](https://github.com/ktmeaton/ncov-recombinant/issues/57): Plot distributions of each parent separately, rather than stacking on one axis. Also plot the substitutions as ticks on the breakpoints figure. + +| v0.3.0 | v0.4.0 | +| -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| ![breakpoints_clade_v0.3.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/4fbde4b90/images/breakpoints_clade_v0.3.0.png) | ![breakpoints_clade_v0.4.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/4fbde4b90/images/breakpoints_clade_v0.4.0.png) | + +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): Plot breakpoints separately by clade _and_ lineage. In addition, distinct clusters within the same recombinant lineage are noted by including their cluster ID as a suffix. As an example, please see `XM (USA) and X (England)` below. Where the lineage is the same (`XM`), but the breakpoints differ, as do the parental lineages (`BA.2` vs `BA.2.12.1`). These clusters are distinct because `XM (England)` lacks substitutions occurring around position 20000. + +| Clade | Lineage | +|:--------------------------------------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------------------------:| +| ![breakpoints_clade](https://github.com/ktmeaton/ncov-recombinant/raw/432b6b79/images/breakpoints_clade_v0.4.0.png) | ![breakpoints_clade](https://github.com/ktmeaton/ncov-recombinant/raw/432b6b79/images/breakpoints_lineage_v0.4.0.png) | + +- [Issue #58](https://github.com/ktmeaton/ncov-recombinant/issues/58): Fix breakpoint plotting from all lineages to just those observed in the reporting period. Except for the breakpoint plots in `plots_historical`. +- [Issue #59](https://github.com/ktmeaton/ncov-recombinant/issues/59): Improved error handling of breakpoint plotting when a breakpoint could not be identified by `sc2rf`. This is possible if `nextclade` was the only program to detect recombination (and thus, we have no breakpoint data from `sc2rf`). +- [Issue #64](https://github.com/ktmeaton/ncov-recombinant/issues/64): Improved error handling for when the lag period (ex. 4 weeks) falls outside the range of collection dates (ex. 2 weeks). +- [Issue #65](https://github.com/ktmeaton/ncov-recombinant/issues/65): Improved error handling of distribution plotting when only one sequence is present. +- [Issue #67](https://github.com/ktmeaton/ncov-recombinant/issues/67): Plot legends are placed above the figure and are dynamically sized. + +| v0.3.0 | v0.4.0 | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ![lineages_output_v0.3.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/af2f25d3c5e7c1d56244390ee90bec405b23949a/images/lineages_output_v0.3.0.png) | ![lineages_output_v0.4.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/af2f25d3c5e7c1d56244390ee90bec405b23949a/images/lineages_output_v0.4.0.png) | + +#### Report + +- [Issue #60](https://github.com/ktmeaton/ncov-recombinant/issues/60): Remove changelog from final slide, as this content did not display correctly +- [Issue #61](https://github.com/ktmeaton/ncov-recombinant/issues/61): Fixed bug in the `report.xlsx` where the number of proposed and unpublished recombinant lineages/sequences was incorrect. + +#### Validation + +- [Issue #58](https://github.com/ktmeaton/ncov-recombinant/issues/58): New rule (`validate`) to validate the number of positives in controlled datasets (ex. controls, tutorials) against `defaults/validation.tsv`. If validation fails based on an incorrect number of positives, the pipeline will exit with an error. This is to make it more obvious when results have changed during Continuous Integration (CI) + +### Commits + +- [```c027027b```](https://github.com/ktmeaton/ncov-recombinant/commit/c027027b) docs: remove dev notes +- [```77d9f01b```](https://github.com/ktmeaton/ncov-recombinant/commit/77d9f01b) ci: remove unit test workflow +- [```574f8c15```](https://github.com/ktmeaton/ncov-recombinant/commit/574f8c15) docs: update instructions in README +- [```79b61fe2```](https://github.com/ktmeaton/ncov-recombinant/commit/79b61fe2) ci: remove unit tests +- [```3d53ebd2```](https://github.com/ktmeaton/ncov-recombinant/commit/3d53ebd2) docs: update notes for v0.4.0 +- [```b968dc6d```](https://github.com/ktmeaton/ncov-recombinant/commit/b968dc6d) script: add more subs columns to lineages linelist +- [```75477ec4```](https://github.com/ktmeaton/ncov-recombinant/commit/75477ec4) script: adjust lag epiweek by 1 when overlaps +- [```20409f5c```](https://github.com/ktmeaton/ncov-recombinant/commit/20409f5c) sc2rf: mapping change 22C to BA.2.12.1 and add 22D +- [```432b6b79```](https://github.com/ktmeaton/ncov-recombinant/commit/432b6b79) docs: add breakpoints lineage output for v0.4.0 +- [```4fbde4b9```](https://github.com/ktmeaton/ncov-recombinant/commit/4fbde4b9) docs: add breakts output image to compare v0.3.0 and v0.4.0 +- [```af2f25d3```](https://github.com/ktmeaton/ncov-recombinant/commit/af2f25d3) docs: add lineage output image for v0.4.0 to compare +- [```5615f113```](https://github.com/ktmeaton/ncov-recombinant/commit/5615f113) docs: add lineage output image for v0.3.0 to compare +- [```57a08096```](https://github.com/ktmeaton/ncov-recombinant/commit/57a08096) profile: adjust plotting min and max dates for tutorial +- [```4226c85b```](https://github.com/ktmeaton/ncov-recombinant/commit/4226c85b) script: mark nextclade recombinants unverified by sc2rf as false positives +- [```d6700e7a```](https://github.com/ktmeaton/ncov-recombinant/commit/d6700e7a) docs: rearrange sections in README +- [```7f773ba7```](https://github.com/ktmeaton/ncov-recombinant/commit/7f773ba7) docs: update report and slides images and links +- [```3599a7f4```](https://github.com/ktmeaton/ncov-recombinant/commit/3599a7f4) script: don't use proposed* lineages from sc2rf as consensus lineage +- [```76106b50```](https://github.com/ktmeaton/ncov-recombinant/commit/76106b50) docs: add new image for lineages plot +- [```86c2fa2e```](https://github.com/ktmeaton/ncov-recombinant/commit/86c2fa2e) docs: update README and images +- [```488ea6c7```](https://github.com/ktmeaton/ncov-recombinant/commit/488ea6c7) script: dynamic legends for #67 +- [```bec01845```](https://github.com/ktmeaton/ncov-recombinant/commit/bec01845) script: move plot legend to top for #67 +- [```42d1281b```](https://github.com/ktmeaton/ncov-recombinant/commit/42d1281b) script: make sure X*-like lineages have proposed status +- [```230f9495```](https://github.com/ktmeaton/ncov-recombinant/commit/230f9495) resources: update issues +- [```3c2f4c84```](https://github.com/ktmeaton/ncov-recombinant/commit/3c2f4c84) script: detect novel recombinants based on private mutations +- [```d9e279be```](https://github.com/ktmeaton/ncov-recombinant/commit/d9e279be) resources: update breakpoints for XAF and XAG +- [```2d070cb2```](https://github.com/ktmeaton/ncov-recombinant/commit/2d070cb2) script: improve linelist efficiency for assigning cluster ids +- [```b65437f2```](https://github.com/ktmeaton/ncov-recombinant/commit/b65437f2) script: add create_logger function to general functions import +- [```489154f6```](https://github.com/ktmeaton/ncov-recombinant/commit/489154f6) sc2rf: explicitly call variables \_primary and \_secondary +- [```8f464a14```](https://github.com/ktmeaton/ncov-recombinant/commit/8f464a14) script: simplify extra columns for summary script +- [```30f90443```](https://github.com/ktmeaton/ncov-recombinant/commit/30f90443) workflow: formally run sc2rf in primary/secondary mode in parallel +- [```6688c828```](https://github.com/ktmeaton/ncov-recombinant/commit/6688c828) defaults: restore validation counts for XN and XP +- [```043b691e```](https://github.com/ktmeaton/ncov-recombinant/commit/043b691e) script: add special processing for XN and XP +- [```939cc967```](https://github.com/ktmeaton/ncov-recombinant/commit/939cc967) script: only adjust lineage status in linelist if positive +- [```28d91363```](https://github.com/ktmeaton/ncov-recombinant/commit/28d91363) dataset: update tutorial strains for #49 +- [```09e53a94```](https://github.com/ktmeaton/ncov-recombinant/commit/09e53a94) workflow: remove usher for #63 +- [```22c63de0```](https://github.com/ktmeaton/ncov-recombinant/commit/22c63de0) workflow: add XAK to controls for Issue #62 +- [```342fa2a3```](https://github.com/ktmeaton/ncov-recombinant/commit/342fa2a3) script: create separate slides for designated, proposed, and unpublished for issue #61 +- [```84c9b57d```](https://github.com/ktmeaton/ncov-recombinant/commit/84c9b57d) script: create separate plots for designated, proposed, and unpublished for issue #61 +- [```81c58931```](https://github.com/ktmeaton/ncov-recombinant/commit/81c58931) script: if lineage is proposed* use as curated lineage rather than cluster_id +- [```2db6100b```](https://github.com/ktmeaton/ncov-recombinant/commit/2db6100b) ci: fix typo in profile creation job names +- [```18102431```](https://github.com/ktmeaton/ncov-recombinant/commit/18102431) script: remove changelog from report slides for issue #60 +- [```b7784b30```](https://github.com/ktmeaton/ncov-recombinant/commit/b7784b30) docs: use new breakpoints path for README +- [```66ee7d1d```](https://github.com/ktmeaton/ncov-recombinant/commit/66ee7d1d) nextclade: upgrade datasets to tag 2022-07-26 for issue #50 +- [```7880327c```](https://github.com/ktmeaton/ncov-recombinant/commit/7880327c) ci: don't trigger pipeline on images changes +- [```e8c71171```](https://github.com/ktmeaton/ncov-recombinant/commit/e8c71171) docs: update breakpoints images +- [```e13138e8```](https://github.com/ktmeaton/ncov-recombinant/commit/e13138e8) script: rename NA to Unknown parent when plotting breakpoints +- [```fc1b6129```](https://github.com/ktmeaton/ncov-recombinant/commit/fc1b6129) script: remove unneeded constants in plot +- [```77d3614a```](https://github.com/ktmeaton/ncov-recombinant/commit/77d3614a) dataset: change controls proposed771 to XAN +- [```f2d72330```](https://github.com/ktmeaton/ncov-recombinant/commit/f2d72330) script: catch empty plot when using tight_layout for breakpoints +- [```b55dbe95```](https://github.com/ktmeaton/ncov-recombinant/commit/b55dbe95) workflow: include unpublished in positive status for rule validate +- [```557295b5```](https://github.com/ktmeaton/ncov-recombinant/commit/557295b5) script: plotting catch when breakpoints are NA +- [```2306305d```](https://github.com/ktmeaton/ncov-recombinant/commit/2306305d) profile: set exclusions for tutorial to default +- [```c049ccba```](https://github.com/ktmeaton/ncov-recombinant/commit/c049ccba) resource: update curated breakpoints +- [```218bab52```](https://github.com/ktmeaton/ncov-recombinant/commit/218bab52) env: upgrade nextclade to v2.3.0 for issue #50 +- [```a9ea0bd4```](https://github.com/ktmeaton/ncov-recombinant/commit/a9ea0bd4) workflow: fix typo in rule validate that hard-coded controls +- [```cf613c34```](https://github.com/ktmeaton/ncov-recombinant/commit/cf613c34) workflow: control breakpoint plotting by clusters file +- [```0d4b50a4```](https://github.com/ktmeaton/ncov-recombinant/commit/0d4b50a4) resource: update breakpoints figures +- [```6520457a```](https://github.com/ktmeaton/ncov-recombinant/commit/6520457a) script: plot subs along with breakpoints for issue #57 +- [```8110faa7```](https://github.com/ktmeaton/ncov-recombinant/commit/8110faa7) script: create a plot for cluster_id mostly for breakpoint plotting +- [```6f02f09c```](https://github.com/ktmeaton/ncov-recombinant/commit/6f02f09c) script: for plot import function categorical_palette +- [```1f6195df```](https://github.com/ktmeaton/ncov-recombinant/commit/1f6195df) profile: by default do not retry jobs +- [```2842a4f9```](https://github.com/ktmeaton/ncov-recombinant/commit/2842a4f9) workflow: add rule validate for issue #56 +- [```693b07df```](https://github.com/ktmeaton/ncov-recombinant/commit/693b07df) script: empty df catching in plot breakpoints +- [```12567fde```](https://github.com/ktmeaton/ncov-recombinant/commit/12567fde) workflow: classify any sequence with unlabeled private mutations as a potential positive +- [```534ac899```](https://github.com/ktmeaton/ncov-recombinant/commit/534ac899) docs: add more comments to summary script +- [```82b6a696```](https://github.com/ktmeaton/ncov-recombinant/commit/82b6a696) script: fix bug in parent palette for plot breakpoints +- [```42510719```](https://github.com/ktmeaton/ncov-recombinant/commit/42510719) config: remove explicit conda activation in slurm script and profiles +- [```ab44e5d7```](https://github.com/ktmeaton/ncov-recombinant/commit/ab44e5d7) docs: update readme contributors +- [```e8e2b134```](https://github.com/ktmeaton/ncov-recombinant/commit/e8e2b134) dataset: upgrade nextclade dataset +- [```086768c7```](https://github.com/ktmeaton/ncov-recombinant/commit/086768c7) parameters: restrict breakpoints and parents to 10 for sc2rf +- [```83af3a73```](https://github.com/ktmeaton/ncov-recombinant/commit/83af3a73) sc2rf: output NA for false positives breakpoints +- [```4baee0de```](https://github.com/ktmeaton/ncov-recombinant/commit/4baee0de) script: catch empty dataframe in script plot +- [```1dc84bf6```](https://github.com/ktmeaton/ncov-recombinant/commit/1dc84bf6) profile: adjust plot end date for positive controls +- [```be431cdf```](https://github.com/ktmeaton/ncov-recombinant/commit/be431cdf) workflow: restrict nextclade clades again +- [```76e31f68```](https://github.com/ktmeaton/ncov-recombinant/commit/76e31f68) resources: add breakpoints by clade +- [```07d96a1e```](https://github.com/ktmeaton/ncov-recombinant/commit/07d96a1e) workflow: fix bug in plot_historical +- [```2086b254```](https://github.com/ktmeaton/ncov-recombinant/commit/2086b254) sc2rf: update lineage mapping +- [```0d911b20```](https://github.com/ktmeaton/ncov-recombinant/commit/0d911b20) env: reorganize dependencies +- [```c165074b```](https://github.com/ktmeaton/ncov-recombinant/commit/c165074b) workflow: separate plot_breakpoints into separate script +- [```0497dffd```](https://github.com/ktmeaton/ncov-recombinant/commit/0497dffd) profile: controls-negative include false positives +- [```8bb41c45```](https://github.com/ktmeaton/ncov-recombinant/commit/8bb41c45) script: add separate report slides for clade/lineage parent breakpoints +- [```411bc235```](https://github.com/ktmeaton/ncov-recombinant/commit/411bc235) workflow: remove subtree params and add secondary clades +- [```f80386aa```](https://github.com/ktmeaton/ncov-recombinant/commit/f80386aa) sc2rf: catch empty secondary csv +- [```6d1b03e0```](https://github.com/ktmeaton/ncov-recombinant/commit/6d1b03e0) sc2rf: add optional secondary csv for #51 +- [```a629eb06```](https://github.com/ktmeaton/ncov-recombinant/commit/a629eb06) workflow: detect recombination with BA.5 for #51 +- [```c44b468a```](https://github.com/ktmeaton/ncov-recombinant/commit/c44b468a) env: remove plotly and kaleido from env +- [```a485215d```](https://github.com/ktmeaton/ncov-recombinant/commit/a485215d) dataset: add proposed771 to controls for #51 +- [```eba827a9```](https://github.com/ktmeaton/ncov-recombinant/commit/eba827a9) script: define lineages by parental lineages for #46 +- [```d6319bad```](https://github.com/ktmeaton/ncov-recombinant/commit/d6319bad) workflow: relax nextclade exclusion filter for #48 +- [```fb7a0a4f```](https://github.com/ktmeaton/ncov-recombinant/commit/fb7a0a4f) env: upgrade nextclade to v2.2.0 for #50 +- [```31ec45be```](https://github.com/ktmeaton/ncov-recombinant/commit/31ec45be) resources: update breakpoints parents nomenclature +- [```7f00564d```](https://github.com/ktmeaton/ncov-recombinant/commit/7f00564d) (unverified) sc2rf,postprocess: add unique_subs to output +- [```3e3e46c2```](https://github.com/ktmeaton/ncov-recombinant/commit/3e3e46c2) workflow: implement cov-spectrum query to identify parent lineages +- [```041de538```](https://github.com/ktmeaton/ncov-recombinant/commit/041de538) workflow: customize nextclade to run with our without recombinant dataset +- [```7acc598f```](https://github.com/ktmeaton/ncov-recombinant/commit/7acc598f) script: remove edges from stacked bar plots for issue #43 +- [```ab589bb7```](https://github.com/ktmeaton/ncov-recombinant/commit/ab589bb7) docs: add mark horsman for ideas and design +- [```151e481d```](https://github.com/ktmeaton/ncov-recombinant/commit/151e481d) bug: fix svg font export for issues #42 +- [```b34c1452```](https://github.com/ktmeaton/ncov-recombinant/commit/b34c1452) bug: fix ouput typo in issues_download +- [```601a0c7a```](https://github.com/ktmeaton/ncov-recombinant/commit/601a0c7a) resources: also output svg for issues breakpoints +- [```a2a8b00d```](https://github.com/ktmeaton/ncov-recombinant/commit/a2a8b00d) workflow: add plotting issues breakpoints to rule issues_download +- [```5a5a2f41```](https://github.com/ktmeaton/ncov-recombinant/commit/5a5a2f41) resources: update breakpoints plot +- [```2113f6f9```](https://github.com/ktmeaton/ncov-recombinant/commit/2113f6f9) script: plot breakpoints of curate lineages in resources +- [```5f4b901d```](https://github.com/ktmeaton/ncov-recombinant/commit/5f4b901d) docs: add new breakpoints image to readme +- [```bfdf2191```](https://github.com/ktmeaton/ncov-recombinant/commit/bfdf2191) workflow: cleanup Thumbs +- [```869f3b4e```](https://github.com/ktmeaton/ncov-recombinant/commit/869f3b4e) script: add breakpoints as a plot and report slide +- [```e988f251```](https://github.com/ktmeaton/ncov-recombinant/commit/e988f251) bug: fix missing rule\_name for \_historical +- [```8bc6aef4```](https://github.com/ktmeaton/ncov-recombinant/commit/8bc6aef4) env: add plotly and kaleido to env +- [```066e0c00```](https://github.com/ktmeaton/ncov-recombinant/commit/066e0c00) resources: add 781 789 798 to curated breakpoints +- [```4ff587c5```](https://github.com/ktmeaton/ncov-recombinant/commit/4ff587c5) resources: update issues and curated breakpoints +- [```cc146425```](https://github.com/ktmeaton/ncov-recombinant/commit/cc146425) docs: add instructions for updating conda env +- [```8592a156```](https://github.com/ktmeaton/ncov-recombinant/commit/8592a156) bug: fix usher_collapse metadata output to allow for hCoV-19 prefix +- [```9ea4f1b3```](https://github.com/ktmeaton/ncov-recombinant/commit/9ea4f1b3) docs: add --recurse-submodules instruction to updating + +## v0.3.0 + +### Notes + +#### Major Changes + +1. Default parameters have been updated! Please regenerate your profiles/builds with: + + ```bash + bash scripts/create_profile.sh --data data/custom + ``` + +1. Rule outputs are now in sub-directories for a cleaner `results` directory. +1. The in-text report (`report.pptx`) statistics are no longer cumulative counts of all sequences. Instead they, will match the reporting period in the accompanying plots. + +#### Bug Fixes + +1. Improve subtree collapse effiency (#35). +1. Improve subtree aesthetics and filters (#20). +1. Fix issues rendering as float (#29). +1. Explicitly control the dimensions of plots for powerpoint embedding. +1. Remove hard-coded `extra_cols` (#26). +1. Fix mismatch in lineages plot and description (#21). +1. Downstream steps no longer fail if there are no recombinant sequences (#7). + +#### Workflow + +1. Add new rule `usher_columns` to augment the base usher metadata. +1. Add new script `parents.py`, plots, and report slide to summarize recombinant sequences by parent. +1. Make rules `plot` and `report` more dynamic with regards to plots creation. +1. Exclude the reference genome from alignment until `faToVcf`. +1. Include the log path and expected outputs in the message for each rule. +1. Use sub-functions to better control optional parameters. +1. Make sure all rules write to a log if possible (#34). +1. Convert all rule inputs to snakemake rule variables. +1. Create and document a `create_profile.sh` script. +1. Implement the `--low-memory` mode parameter within the script `usher_metadata.sh`. + +#### Data + +1. Create new controls datasets: + + - `controls-negatives` + - `controls-positives` + - `controls` + +1. Add versions to `genbank_accessions` for `controls`. + +#### Programs + +1. Upgrade UShER to v0.5.4 (possibly this was done in a prior ver). +1. Remove `taxonium` and `chronumental` from the conda env. + +#### Parameters + +1. Add parameters to control whether negatives and false_positives should be excluded: + + - `exclude_negatives: false` + - `false_positives: false` + +1. Add new optional param `max_placements` to rule `linelist`. +1. Remove `--show-private-mutations` from `debug_args` of rule `sc2rf`. +1. Add optional param `--sc2rf-dir` to `sc2rf` to enable execution outside of `sc2rf` dir. +1. Add params `--output-csv` and `--output-ansi` to the wrapper `scripts/sc2rf.sh`. +1. Remove params `nextclade_ref` and `custom_ref` from rule `nextclade`. +1. Change `--breakpoints 0-10` in `sc2rf`. + +#### Continuous Integration + +1. Re-rename tutorial action to pipeline, and add different jobs for different profiles: + + - Tutorial + - Controls (Positive) + - Controls (Negative) + - Controls (All) + +#### Output + +1. Output new `_historical` plots and slides for plotting all data over time. +1. Output new file `parents.tsv` to summarize recombinant sequences by parent. +1. Order the colors/legend of the stacked bar `plots` by number of sequences. +1. Include lineage and cluster id in filepaths of largest plots and tables. +1. Rename the linelist output: + + - `linelist.tsv` + - `positives.tsv` + - `negatives.tsv` + - `false_positives.tsv` + - `lineages.tsv` + - `parents.tsv` + +1. The `report.xlsx` now includes the following tables: + + - lineages + - parents + - linelist + - positives + - negatives + - false_positives + - summary + - issues + +### Pull Requests + +- [```pull/19```](https://github.com/ktmeaton/ncov-recombinant/pull/19) docs: add lenaschimmel as a contributor for code + +### Commits + +- [```2f8b498a```](https://github.com/ktmeaton/ncov-recombinant/commit/2f8b498a) docs: update changelog for v0.3.0 +- [```0486d3be```](https://github.com/ktmeaton/ncov-recombinant/commit/0486d3be) docs: add updating section to readme for issue #33 +- [```e8eda400```](https://github.com/ktmeaton/ncov-recombinant/commit/e8eda400) resources: updates issues with curate breakpoints +- [```12e3700f```](https://github.com/ktmeaton/ncov-recombinant/commit/12e3700f) bug: catch empty dataframe in plot +- [```d1ccca2a```](https://github.com/ktmeaton/ncov-recombinant/commit/d1ccca2a) workflow: first successful high-throughput run +- [```cd741a10```](https://github.com/ktmeaton/ncov-recombinant/commit/cd741a10) workflow: add new rules plot_historical and report_historical +- [```c2cc1380```](https://github.com/ktmeaton/ncov-recombinant/commit/c2cc1380) env: remove openpyxl from environment +- [```7dc7c039```](https://github.com/ktmeaton/ncov-recombinant/commit/7dc7c039) workflow: remove rule report_redact #31 +- [```9ca5f822```](https://github.com/ktmeaton/ncov-recombinant/commit/9ca5f822) script: rearrange merge file order in summary +- [```aa28eb9f```](https://github.com/ktmeaton/ncov-recombinant/commit/aa28eb9f) workflow: create new rule report_redact for #31 +- [```4748815d```](https://github.com/ktmeaton/ncov-recombinant/commit/4748815d) env: add openpyxl to environment for excel parsing in python +- [```0060904a```](https://github.com/ktmeaton/ncov-recombinant/commit/0060904a) script: template duplicate labelling in usher_collapse for later +- [```a82359a7```](https://github.com/ktmeaton/ncov-recombinant/commit/a82359a7) data: add accession versions to controls metadata +- [```af7341aa```](https://github.com/ktmeaton/ncov-recombinant/commit/af7341aa) data: add accession versions to controls metadata +- [```d860a4c8```](https://github.com/ktmeaton/ncov-recombinant/commit/d860a4c8) workflow: add new rule usher_columns to augment the base usher metadata +- [```2511673d```](https://github.com/ktmeaton/ncov-recombinant/commit/2511673d) improve subtree collapse effiency (#35) and output aesthetics (#20) +- [```1e81be3b```](https://github.com/ktmeaton/ncov-recombinant/commit/1e81be3b) bug: remove non-existant param --log in rule usher_metadata +- [```02198b4c```](https://github.com/ktmeaton/ncov-recombinant/commit/02198b4c) script: add logging to usher_collapse +- [```d40d3d78```](https://github.com/ktmeaton/ncov-recombinant/commit/d40d3d78) ci: don't run pipeline just for images changes +- [```b880d9c8```](https://github.com/ktmeaton/ncov-recombinant/commit/b880d9c8) docs: update powerpoint image to proper ver +- [```2d6514a0```](https://github.com/ktmeaton/ncov-recombinant/commit/2d6514a0) docs: update demo excel and slides with links and content +- [```59c24ffe```](https://github.com/ktmeaton/ncov-recombinant/commit/59c24ffe) bug: fix typo that prevented low_memory_mode from activating +- [```4d94df1d```](https://github.com/ktmeaton/ncov-recombinant/commit/4d94df1d) bug: continue supply missing build param to _params_ functions +- [```c16c3377```](https://github.com/ktmeaton/ncov-recombinant/commit/c16c3377) bug: supply missing build param to _params_linelist +- [```c31c2204```](https://github.com/ktmeaton/ncov-recombinant/commit/c31c2204) docs: remove plotting data table from FAQ +- [```5461cbf2```](https://github.com/ktmeaton/ncov-recombinant/commit/5461cbf2) docs: describe how to include more custom metadata columns +- [```7295c8c0```](https://github.com/ktmeaton/ncov-recombinant/commit/7295c8c0) script: implement low memory mode within usher_metadata script +- [```6588f619```](https://github.com/ktmeaton/ncov-recombinant/commit/6588f619) workflow: restore original config merge logic +- [```ae96cf3d```](https://github.com/ktmeaton/ncov-recombinant/commit/ae96cf3d) docs: rearrange sections in README +- [```e99cdef9```](https://github.com/ktmeaton/ncov-recombinant/commit/e99cdef9) docs: add tips for speeding up usher in FAQ +- [```753d1e1d```](https://github.com/ktmeaton/ncov-recombinant/commit/753d1e1d) resources: add proposed759 to curated breakpoints +- [```1ea5610e```](https://github.com/ktmeaton/ncov-recombinant/commit/1ea5610e) docs: change troubleshooting section to FAQ +- [```42152710```](https://github.com/ktmeaton/ncov-recombinant/commit/42152710) workflow: add logging to sc2rf_recombinants for issue #34 +- [```ca930fe3```](https://github.com/ktmeaton/ncov-recombinant/commit/ca930fe3) bug: fix status of designated recombinants missed by sc2rf (XB) +- [```2c6102a6```](https://github.com/ktmeaton/ncov-recombinant/commit/2c6102a6) script: in plotting data replace counts that are empty string with 0 +- [```0c7fa988```](https://github.com/ktmeaton/ncov-recombinant/commit/0c7fa988) docs: tidy up comments in default parameters.yaml +- [```43c61d43```](https://github.com/ktmeaton/ncov-recombinant/commit/43c61d43) bug: fix sc2rf postprocessing bug where sequences with only parent were missing filtered regions +- [```6a00c866```](https://github.com/ktmeaton/ncov-recombinant/commit/6a00c866) ci: split jobs by profile for testing profile creation (#27) +- [```aeabf009```](https://github.com/ktmeaton/ncov-recombinant/commit/aeabf009) ci: add new action profile_creation to test script create_profile.sh +- [```9a6758e2```](https://github.com/ktmeaton/ncov-recombinant/commit/9a6758e2) add controls section to README +- [```ef250a22```](https://github.com/ktmeaton/ncov-recombinant/commit/ef250a22) script: add -controls suffix to profiles created with --controls param +- [```150a3e17```](https://github.com/ktmeaton/ncov-recombinant/commit/150a3e17) docs: update troubleshooting section +- [```90b406c8```](https://github.com/ktmeaton/ncov-recombinant/commit/90b406c8) script: remove --partition flag to scripts/slurm.sh +- [```a0c6ece2```](https://github.com/ktmeaton/ncov-recombinant/commit/a0c6ece2) docs: update google drive link to example slides +- [```a37afeea```](https://github.com/ktmeaton/ncov-recombinant/commit/a37afeea) docs: update instructions for create_profile.sh +- [```f9d050d2```](https://github.com/ktmeaton/ncov-recombinant/commit/f9d050d2) add execute permissions to scripts +- [```38b5b422```](https://github.com/ktmeaton/ncov-recombinant/commit/38b5b422) bug: use a full loop to check issue formatting +- [```307b4f67```](https://github.com/ktmeaton/ncov-recombinant/commit/307b4f67) catch issues list when converting to str +- [```639f8c26```](https://github.com/ktmeaton/ncov-recombinant/commit/639f8c26) bug: fix issues rendering as float in tables for issue #29 +- [```35ea4be1```](https://github.com/ktmeaton/ncov-recombinant/commit/35ea4be1) remove param --sc2rf-dir from scripts/sc2rf.sh +- [```5a2a9520```](https://github.com/ktmeaton/ncov-recombinant/commit/5a2a9520) docs: update images for excel and powerpoint +- [```3ae737d5```](https://github.com/ktmeaton/ncov-recombinant/commit/3ae737d5) env: comment out yarn which is a dev dependency +- [```3842e898```](https://github.com/ktmeaton/ncov-recombinant/commit/3842e898) improve logging in create_profile +- [```84c684ca```](https://github.com/ktmeaton/ncov-recombinant/commit/84c684ca) workflow: separate profiles for controls,controls-positive,controls-negative +- [```ad5e8e4b```](https://github.com/ktmeaton/ncov-recombinant/commit/ad5e8e4b) limit missing strains output from create_profile +- [```a4898ecf```](https://github.com/ktmeaton/ncov-recombinant/commit/a4898ecf) docs: update development notes +- [```34ee2fff```](https://github.com/ktmeaton/ncov-recombinant/commit/34ee2fff) docs: add links to contributors plugins +- [```b6b0c999```](https://github.com/ktmeaton/ncov-recombinant/commit/b6b0c999) revert to automated all-contributors +- [```e1a248f8```](https://github.com/ktmeaton/ncov-recombinant/commit/e1a248f8) add @yatisht and @AngieHinrichs to credits for usher +- [```e3f432c4```](https://github.com/ktmeaton/ncov-recombinant/commit/e3f432c4) start adding contributors +- [```862757bd```](https://github.com/ktmeaton/ncov-recombinant/commit/862757bd) docs: create .all-contributorsrc [skip ci] +- [```a0532792```](https://github.com/ktmeaton/ncov-recombinant/commit/a0532792) docs: update README.md [skip ci] +- [```6e67e73f```](https://github.com/ktmeaton/ncov-recombinant/commit/6e67e73f) update unpublished regex to solve #21 +- [```5ba6b37b```](https://github.com/ktmeaton/ncov-recombinant/commit/5ba6b37b) remove taxonium and chronumental from env +- [```2a5fc627```](https://github.com/ktmeaton/ncov-recombinant/commit/2a5fc627) add artifacts for all pipelines +- [```664b2e9b```](https://github.com/ktmeaton/ncov-recombinant/commit/664b2e9b) fix trailing whitespace in metadata +- [```eada2fa3```](https://github.com/ktmeaton/ncov-recombinant/commit/eada2fa3) fix negative controls metadata +- [```9aecd69a```](https://github.com/ktmeaton/ncov-recombinant/commit/9aecd69a) fix plot dimensions for pptx embed +- [```657e8838```](https://github.com/ktmeaton/ncov-recombinant/commit/657e8838) fix outdir for linelist +- [```6fb389dc```](https://github.com/ktmeaton/ncov-recombinant/commit/6fb389dc) fix input type for controls build +- [```8ed69ce0```](https://github.com/ktmeaton/ncov-recombinant/commit/8ed69ce0) upload tutorial pptx as artifact +- [```c6e647d2```](https://github.com/ktmeaton/ncov-recombinant/commit/c6e647d2) update ci profile for test action +- [```19cdb8ed```](https://github.com/ktmeaton/ncov-recombinant/commit/19cdb8ed) lint pipeline +- [```22e3aa6b```](https://github.com/ktmeaton/ncov-recombinant/commit/22e3aa6b) split controls action into positives,negatives,and all +- [```33491320```](https://github.com/ktmeaton/ncov-recombinant/commit/33491320) rename action Tutorial to Pipeline +- [```da2890d6```](https://github.com/ktmeaton/ncov-recombinant/commit/da2890d6) fix profile in install action +- [```8a4d4fbb```](https://github.com/ktmeaton/ncov-recombinant/commit/8a4d4fbb) lint all files +- [```b167ea45```](https://github.com/ktmeaton/ncov-recombinant/commit/b167ea45) update readme with profile creation instructions +- [```4d2848b9```](https://github.com/ktmeaton/ncov-recombinant/commit/4d2848b9) add script to generate new profiles and builds +- [```407f8aba```](https://github.com/ktmeaton/ncov-recombinant/commit/407f8aba) checkpoint before auto-generating builds +- [```ccb3471b```](https://github.com/ktmeaton/ncov-recombinant/commit/ccb3471b) add new negatives dataset +- [```964a22f8```](https://github.com/ktmeaton/ncov-recombinant/commit/964a22f8) (broken) script overhaul +- [```1f1ca1b4```](https://github.com/ktmeaton/ncov-recombinant/commit/1f1ca1b4) add param --sc2rf-dir to allow execution outside of main directory +- [```21541f02```](https://github.com/ktmeaton/ncov-recombinant/commit/21541f02) add exclude_negatives and exclude_false_positives to parameters +- [```0b5854a2```](https://github.com/ktmeaton/ncov-recombinant/commit/0b5854a2) update docs +- [```58b6396a```](https://github.com/ktmeaton/ncov-recombinant/commit/58b6396a) split controls data into positives and negatives +- [```11f9f6a4```](https://github.com/ktmeaton/ncov-recombinant/commit/11f9f6a4) consolidate positives and negatives profiles into controls +- [```581255c8```](https://github.com/ktmeaton/ncov-recombinant/commit/581255c8) generalize hpc profiles +- [```1e2a70a4```](https://github.com/ktmeaton/ncov-recombinant/commit/1e2a70a4) update HPC instructions in README +- [```a18b19e3```](https://github.com/ktmeaton/ncov-recombinant/commit/a18b19e3) (broken) add negatives data and profile +- [```11817639```](https://github.com/ktmeaton/ncov-recombinant/commit/11817639) (broken) make plots and report dynamic +- [```e833d151```](https://github.com/ktmeaton/ncov-recombinant/commit/e833d151) create tutorial-hpc profile +- [```c4ac5699```](https://github.com/ktmeaton/ncov-recombinant/commit/c4ac5699) remove redundant profile laptop +- [```c5107017```](https://github.com/ktmeaton/ncov-recombinant/commit/c5107017) remove ci profile +- [```4be07e79```](https://github.com/ktmeaton/ncov-recombinant/commit/4be07e79) actually rename pipeline to tutorial +- [```89c4d6b5```](https://github.com/ktmeaton/ncov-recombinant/commit/89c4d6b5) rename pipeline action to tutorial +- [```7614b399```](https://github.com/ktmeaton/ncov-recombinant/commit/7614b399) exclude alpha beta gamma by default from Nextclade +- [```d2c2461c```](https://github.com/ktmeaton/ncov-recombinant/commit/d2c2461c) update dev docs +- [```f9368d11```](https://github.com/ktmeaton/ncov-recombinant/commit/f9368d11) remove proposed636 which is now XZ +- [```4fbd0ce4```](https://github.com/ktmeaton/ncov-recombinant/commit/4fbd0ce4) add XAA and XAB to resources +- [```65efd145```](https://github.com/ktmeaton/ncov-recombinant/commit/65efd145) add xz to resources +- [```f3641b19```](https://github.com/ktmeaton/ncov-recombinant/commit/f3641b19) add parents slide to report and excel +- [```4e25f665```](https://github.com/ktmeaton/ncov-recombinant/commit/4e25f665) add new script parents to summarize recombinants by parent +- [```0decd47a```](https://github.com/ktmeaton/ncov-recombinant/commit/0decd47a) catch when no designated sequences are present +- [```189fbb2a```](https://github.com/ktmeaton/ncov-recombinant/commit/189fbb2a) update resources breakpoints +- [```3c5b4965```](https://github.com/ktmeaton/ncov-recombinant/commit/3c5b4965) update sc2rf with new logic for terminal deletions +- [```e37d68d9```](https://github.com/ktmeaton/ncov-recombinant/commit/e37d68d9) update issues and breakpoints +- [```761d41bf```](https://github.com/ktmeaton/ncov-recombinant/commit/761d41bf) use date in changelog for report +- [```3c486dbc```](https://github.com/ktmeaton/ncov-recombinant/commit/3c486dbc) add zip to environment +- [```1ff37195```](https://github.com/ktmeaton/ncov-recombinant/commit/1ff37195) add more info about system config + +## v0.2.1 + +### Notes + +#### Params + +1. New optional param `motifs` for rule `sc2rf_recombinants`. +1. New param `weeks` for new rule `plot`. +1. Removed `prev_linelist` param. + +#### Output + +1. Switch from a pdf `report` to powerpoint slides for better automation. +1. Create summary plots. +1. Split `report` rule into `linelist` and `report`. +1. Output `svg` plots. + +#### Workflow + +1. New rule `plot`. +1. Changed growth calculation from a comparison to the previous week to a score of sequences per day. +1. Assign a `cluster_id` according to the first sequence observed in the recombinant lineage. +1. Define a recombinant lineage as a group of sequences that share the same: + - Lineage assignment + - Parents + - Breakpoints or phylogenetic placement (subtree) +1. For some sequences, the breakpoints are inaccurate and shifted slightly due to ambiguous bases. These sequences can be assigned to their corresponding cluster because they belong to the same subtree. +1. For some lineages, global prevalence has exceeded 500 sequences (which is the subtree size used). Sequences of these lineages are split into different subtrees. However, they can be assigned to the correct cluster/lineage, because they have the same breakpoints. +1. Confirmed not to use deletions define recombinants and breakpoints (differs from published)? + +#### Programs + +1. Move `sc2rf_recombinants.py` to `postprocess.py` in ktmeaton fork of `sc2rf`. +1. Add false positives filtering to `sc2rf_recombinants` based on parents and breakpoints. + +#### Docs + +1. Add section `Configuration` to `README.md`. + +### Commits + +- [```c2369c75```](https://github.com/ktmeaton/ncov-recombinant/commit/c2369c75) update CHANGELOG after README overhaul +- [```9c8a774e```](https://github.com/ktmeaton/ncov-recombinant/commit/9c8a774e) update autologs to exclude first blank line in notes +- [```2a8a7af5```](https://github.com/ktmeaton/ncov-recombinant/commit/2a8a7af5) overhaul README +- [```9c2bd2f5```](https://github.com/ktmeaton/ncov-recombinant/commit/9c2bd2f5) change asterisks to dashes +- [```46d4ec81```](https://github.com/ktmeaton/ncov-recombinant/commit/46d4ec81) update autologs to allow more complex notes content +- [```a01a903c```](https://github.com/ktmeaton/ncov-recombinant/commit/a01a903c) split docs into dev and todo +- [```23e8d715```](https://github.com/ktmeaton/ncov-recombinant/commit/23e8d715) change color palette for plotting +- [```785b8a19```](https://github.com/ktmeaton/ncov-recombinant/commit/785b8a19) add optional param motifs for sc2rf_recombinants +- [```d1c1559e```](https://github.com/ktmeaton/ncov-recombinant/commit/d1c1559e) restore pptx template to regular view +- [```6adc5d32```](https://github.com/ktmeaton/ncov-recombinant/commit/6adc5d32) add seaborn to environment +- [```35a04471```](https://github.com/ktmeaton/ncov-recombinant/commit/35a04471) add changelog to report pptx +- [```99e98aa7```](https://github.com/ktmeaton/ncov-recombinant/commit/99e98aa7) add epiweeks to environment +- [```1644b1fc```](https://github.com/ktmeaton/ncov-recombinant/commit/1644b1fc) add pptx report +- [```1ab93aff```](https://github.com/ktmeaton/ncov-recombinant/commit/1ab93aff) (broken) start plotting +- [```094530f0```](https://github.com/ktmeaton/ncov-recombinant/commit/094530f0) swithc sc2rf to a postprocess script +- [```02193d6e```](https://github.com/ktmeaton/ncov-recombinant/commit/02193d6e) try generalizing sc2rf post-processing + +## v0.2.0 + +### Notes + +#### Bugs + +1. Fix bug in `sc2rf_recombinants` regions/breakpoints logic. +1. Fix bug in `sc2rf` where a sample has no definitive substitutions. + +#### Params + +1. Allow `--breakpoints 0-4`, for XN. We'll determine the breakpoints in post-processing. +1. Bump up the `min_len` of `sc2rf_recombinants` to 1000 bp. +1. Add param `mutation_threshold` to `sc2rf`. +1. Reduce default `mutation_threshold` to 0.25 to catch [Issue #591](https://github.com/cov-lineages/pango-designation/issues/591_. +1. Bump up subtree size from 100 sequences to 500 sequences. + + - Trying to future proof against XE growth (200+ sequences) + +1. Discovered that `--primers` interferes with breakpoint detection, use only for debugging. +1. Only use `--enable-deletions` in `sc2rf` for debug mode. Otherwise it changes breakpoints. +1. Only use `--private-mutations` to `sc2rf` for debug mode. Unreadable output for bulk sample processing. + +#### Report + +1. Change `sc2rf_lineage` column to use NA for no lineage found. + + - This is to troubleshot when only one breakpoint matches a lineage. + +1. Add `sc2rf_mutations_version` to summary based on a datestamp of `virus_properties.json`. +1. Allow multiple issues in report. +1. Use three status categories of recombinants: + + - Designated + - Proposed + - Unpublished + +1. Add column `status` to recombinants. +1. Add column `usher_extra` to `usher_metadata` for 2022-05-06 tree. +1. Separate out columns lineage and issue in `report`. +1. Add optional columns to report. +1. Fixed growth calculations in report. +1. Add a Definitions section to the markdown/pdf report. +1. Use parent order for breakpoint matching, as we see same breakpoint different parents. +1. Add the number of usher placements to the summary. + +#### Output + +1. Set Auspice default coloring to `lineage_usher` where possible. +1. Remove nwk output from `usher` and `usher_subtrees`: + + - Pull subtree sample names from json instead + +1. Output `linelist.exclude.tsv` of false-positive recombinants. + +#### Programs + +1. Update `nextclade_dataset` to 2022-04-28. +1. Add `taxoniumtools` and `chronumental` to environment. +1. Separate nextclade clades and pango lineage allele frequences in `sc2rf`. +1. Exclude BA.3, BA.4, and BA.5 for now, as their global prevalence is low and they are descendants of BA.2. + +#### Profiles + +1. Add a `tutorial` profile. + + - (N=2) Designated Recombinants (pango-designation) + - (N=2) Proposed Recombinants (issues, UCSC) + - (N=2) Unpublished Recombinants + +1. Add XL to `controls`. +1. Add XN to `controls`. +1. Add XR to `controls`. +1. Add XP to `controls`. + +#### Workflow + +1. Split `usher_subtree` and `usher_subtree_collapse` into separate rules. + + - This speeds up testing for collapsing trees and styling the Auspice JSON. + +1. Force include `Nextclade` recombinants (auto-pass through `sc2rf`). +1. Split `usher` and `usher_stats` into separate rules. + +### Pull Requests + +- [```pull/13```](https://github.com/ktmeaton/ncov-recombinant/pull/13) Three status categories: designated, proposed, unpublished + +### Commits + +- [```10388a6e```](https://github.com/ktmeaton/ncov-recombinant/commit/10388a6e) update docs for v0.2.0 +- [```32b9e8ab```](https://github.com/ktmeaton/ncov-recombinant/commit/32b9e8ab) separate usher and usher_stats rule and catch 3 or 4 col usher +- [```70da837c```](https://github.com/ktmeaton/ncov-recombinant/commit/70da837c) update github issues and breakpoints for 636 and 637 +- [```9ed10f17```](https://github.com/ktmeaton/ncov-recombinant/commit/9ed10f17) skip parsing github issues that don't have body +- [```216cb28e```](https://github.com/ktmeaton/ncov-recombinant/commit/216cb28e) put the date in the usher data for tutorial +- [```c95cca0e```](https://github.com/ktmeaton/ncov-recombinant/commit/c95cca0e) update usher v0.5.3 +- [```98c91bee```](https://github.com/ktmeaton/ncov-recombinant/commit/98c91bee) finish reporting cycle 2022-05-11 +- [```e4755f16```](https://github.com/ktmeaton/ncov-recombinant/commit/e4755f16) new sc2rf mutation data by clade +- [```4a501d56```](https://github.com/ktmeaton/ncov-recombinant/commit/4a501d56) separate omicron lineages from omicron clades +- [```d6185aaf```](https://github.com/ktmeaton/ncov-recombinant/commit/d6185aaf) testing change to auto-pass nextclade recombinants +- [```2e02922f```](https://github.com/ktmeaton/ncov-recombinant/commit/2e02922f) add XL XN XR XP to controls +- [```e2c9675b```](https://github.com/ktmeaton/ncov-recombinant/commit/e2c9675b) add usher_extra and qc file to sc2rf recombinants +- [```941a64c5```](https://github.com/ktmeaton/ncov-recombinant/commit/941a64c5) update github issues +- [```943cde95```](https://github.com/ktmeaton/ncov-recombinant/commit/943cde95) add usher placements to summary +- [```0d0ffbd4```](https://github.com/ktmeaton/ncov-recombinant/commit/0d0ffbd4) combine show-private-mutations with ignore-shared +- [```f1d7e6c1```](https://github.com/ktmeaton/ncov-recombinant/commit/f1d7e6c1) update sc2rf after terminal bugfixes +- [```8f4fd95a```](https://github.com/ktmeaton/ncov-recombinant/commit/8f4fd95a) add country England to geo res +- [```efeeb6ca```](https://github.com/ktmeaton/ncov-recombinant/commit/efeeb6ca) add mutation threshold param sep for sc2rf +- [```9c42bc6c```](https://github.com/ktmeaton/ncov-recombinant/commit/9c42bc6c) limit table col width size in report +- [```7d746e3f```](https://github.com/ktmeaton/ncov-recombinant/commit/7d746e3f) fix growth calculation +- [```0dc7f464```](https://github.com/ktmeaton/ncov-recombinant/commit/0dc7f464) identify sc2rf lineage by breakpoints and parents +- [```19fc3721```](https://github.com/ktmeaton/ncov-recombinant/commit/19fc3721) add parents to breakpoints and issues +- [```27bbff0a```](https://github.com/ktmeaton/ncov-recombinant/commit/27bbff0a) generate geo_resolutions from ncov defaults lat longs +- [```86aa78ba```](https://github.com/ktmeaton/ncov-recombinant/commit/86aa78ba) add map to auspice subtrees +- [```2499827e```](https://github.com/ktmeaton/ncov-recombinant/commit/2499827e) add taxoniumtools and chronumental to env +- [```ec46a569```](https://github.com/ktmeaton/ncov-recombinant/commit/ec46a569) change tutorial seq names from underscores to dashes +- [```27170a0b```](https://github.com/ktmeaton/ncov-recombinant/commit/27170a0b) fix issues line endings +- [```e8eb1215```](https://github.com/ktmeaton/ncov-recombinant/commit/e8eb1215) update nextclade dataset to 2022-04-28 +- [```89335c3a```](https://github.com/ktmeaton/ncov-recombinant/commit/89335c3a) (broken) updating columns in report +- [```67475ecc```](https://github.com/ktmeaton/ncov-recombinant/commit/67475ecc) update sc2rf +- [```79b7b2b9```](https://github.com/ktmeaton/ncov-recombinant/commit/79b7b2b9) add tip to readme +- [```10df6a54```](https://github.com/ktmeaton/ncov-recombinant/commit/10df6a54) remove all sample extraction from usher +- [```2ffbcb61```](https://github.com/ktmeaton/ncov-recombinant/commit/2ffbcb61) switch sc2rf submodule to ktmeaton fork +- [```e2adaabe```](https://github.com/ktmeaton/ncov-recombinant/commit/e2adaabe) disable snakemake report in pipeline ci +- [```f12fef14```](https://github.com/ktmeaton/ncov-recombinant/commit/f12fef14) edit line linst preview instructions +- [```d10eb730```](https://github.com/ktmeaton/ncov-recombinant/commit/d10eb730) add collection date to tutorial +- [```d4e0aa86```](https://github.com/ktmeaton/ncov-recombinant/commit/d4e0aa86) very preliminary credits and tutorial +- [```e9c41e6e```](https://github.com/ktmeaton/ncov-recombinant/commit/e9c41e6e) change ci pipeline to tutorial build +- [```4de7370d```](https://github.com/ktmeaton/ncov-recombinant/commit/4de7370d) add tutorial data +- [```8d8c88fc```](https://github.com/ktmeaton/ncov-recombinant/commit/8d8c88fc) set min version for click to troubleshoot env creation +- [```c7fb50a4```](https://github.com/ktmeaton/ncov-recombinant/commit/c7fb50a4) better issue reporting +- [```b2699823```](https://github.com/ktmeaton/ncov-recombinant/commit/b2699823) update sc2rf + +## v0.1.2 + +### Notes + +1. Add lineage `XM` to controls. + + - There are now publicly available samples. + +1. Correct `XF` and `XJ` controls to match issues. +1. Create a markdown report with program versions. +1. Fix `sc2rf_recombinants` bug where samples with >2 breakpoints were being excluded. +1. Summarize recombinants by parents and dates observed. +1. Change `report.tsv` to `linelist.tsv`. +1. Use `date_to_decimal.py` to create `num_date` for auspice subtrees. +1. Add an `--exclude-clades` param to `sc2rf_recombinants.py`. +1. Add param `--ignore-shared-subs` to `sc2rf`. + + - This makes regions detection more conservative. + - The result is that regions/clade will be smaller and breakpoints larger. + - These breakpoints more closely match pango-designation issues. + +1. Update breakpoints in controls metadata to reflect the output with `--ignore-shared-subs`. +1. Bump up `min_len` for `sc2rf_recombinants` to 200 bp. +1. Add column `sc2rf_lineage` to `sc2rf_recombinants` output. + + - Takes the form of X*, or proposed{issue} to follow UShER. + +1. Consolidate lineage assignments into a single column. + + - sc2rf takes priority if a single lineage is identified. + - usher is next, to resolve ties or if sc2rf had no lineage. + +1. Slim down the conda environment and remove unnecessary programs. + + - `augur` + - `seaborn` + - `snipit` + - `bedtools` + - Comment out dev tools: `git` and `pre-commit`. + +1. Use github api to pull recombinant issues. +1. Consolidate \*_to_\* files into `resources/issues.tsv`. +1. Use the `--clades` param of `sc2rf` rather than using `exclude_clades`. +1. Disabled `--rebuild-examples` in `sc2rf` because of requests error. +1. Add column `issue` to `recombinants.tsv`. +1. Get `ncov-recombinant` version using tag. +1. Add documentation to the report. + + - What the sequences column format means: X (+X) + - What the different lineage classifers. + +### Pull Requests + +- [```pull/10```](https://github.com/ktmeaton/ncov-recombinant/pull/10) Automated report generation and sc2rf lineage assignments + +### Commits + +- [```941f0c08```](https://github.com/ktmeaton/ncov-recombinant/commit/941f0c08) update CHANGELOG +- [```bce219b6```](https://github.com/ktmeaton/ncov-recombinant/commit/bce219b6) fix notes conflict +- [```cdb3bc7f```](https://github.com/ktmeaton/ncov-recombinant/commit/cdb3bc7f) fix duplicate pr output in autologs +- [```0a8ffd84```](https://github.com/ktmeaton/ncov-recombinant/commit/0a8ffd84) update notes for v0.1.2 +- [```0075209b```](https://github.com/ktmeaton/ncov-recombinant/commit/0075209b) add issue to recombinants report +- [```0fd8fea0```](https://github.com/ktmeaton/ncov-recombinant/commit/0fd8fea0) (broken) troubleshoot usher collapse json +- [```b0ab72b9```](https://github.com/ktmeaton/ncov-recombinant/commit/b0ab72b9) update breakpoints +- [```a3058c57```](https://github.com/ktmeaton/ncov-recombinant/commit/a3058c57) update sc2rf examples +- [```b5f2a0f8```](https://github.com/ktmeaton/ncov-recombinant/commit/b5f2a0f8) update and clean controls data +- [```f69f254c```](https://github.com/ktmeaton/ncov-recombinant/commit/f69f254c) add curated breakpoints to issues +- [```4e9d2dc9```](https://github.com/ktmeaton/ncov-recombinant/commit/4e9d2dc9) add an issues script and resources file +- [```16059610```](https://github.com/ktmeaton/ncov-recombinant/commit/16059610) major environment reduction +- [```5ced9193```](https://github.com/ktmeaton/ncov-recombinant/commit/5ced9193) remove bedtools from env +- [```28777cb9```](https://github.com/ktmeaton/ncov-recombinant/commit/28777cb9) remove seaborn from env +- [```01f459c4```](https://github.com/ktmeaton/ncov-recombinant/commit/01f459c4) remove snipit from env +- [```7d6ef729```](https://github.com/ktmeaton/ncov-recombinant/commit/7d6ef729) remove augur from env +- [```9a2e948d```](https://github.com/ktmeaton/ncov-recombinant/commit/9a2e948d) fix pandas warnings in report +- [```78daee55```](https://github.com/ktmeaton/ncov-recombinant/commit/78daee55) remove script usher_plot as now we rely on auspice +- [```a7bd52f1```](https://github.com/ktmeaton/ncov-recombinant/commit/a7bd52f1) remove script update_controls which is now done manually +- [```93a30200```](https://github.com/ktmeaton/ncov-recombinant/commit/93a30200) consolidate lineage call in report +- [```5f3e3633```](https://github.com/ktmeaton/ncov-recombinant/commit/5f3e3633) hardcode columns for report +- [```6333fde4```](https://github.com/ktmeaton/ncov-recombinant/commit/6333fde4) improve type catching in date_to_decimal +- [```557627a4```](https://github.com/ktmeaton/ncov-recombinant/commit/557627a4) update controls breakpoints and add col sc2rf_lineage +- [```7e2ad531```](https://github.com/ktmeaton/ncov-recombinant/commit/7e2ad531) add param --ignore-shared-subs to sc2rf +- [```519a9eea```](https://github.com/ktmeaton/ncov-recombinant/commit/519a9eea) overhaul reporting workflow +- [```6fa674f2```](https://github.com/ktmeaton/ncov-recombinant/commit/6fa674f2) update controls metadata and dev notes +- [```46155a84```](https://github.com/ktmeaton/ncov-recombinant/commit/46155a84) add XM to controls +- [```d2d4cd80```](https://github.com/ktmeaton/ncov-recombinant/commit/d2d4cd80) update notes for v0.1.2 +- [```17ae6eeb```](https://github.com/ktmeaton/ncov-recombinant/commit/17ae6eeb) add issue to recombinants report +- [```2ab8dd30```](https://github.com/ktmeaton/ncov-recombinant/commit/2ab8dd30) (broken) troubleshoot usher collapse json +- [```e4fd3352```](https://github.com/ktmeaton/ncov-recombinant/commit/e4fd3352) update breakpoints +- [```c743ad3d```](https://github.com/ktmeaton/ncov-recombinant/commit/c743ad3d) update sc2rf examples +- [```62e1ffc1```](https://github.com/ktmeaton/ncov-recombinant/commit/62e1ffc1) update and clean controls data +- [```9c401a0c```](https://github.com/ktmeaton/ncov-recombinant/commit/9c401a0c) add curated breakpoints to issues +- [```7cf953ad```](https://github.com/ktmeaton/ncov-recombinant/commit/7cf953ad) add an issues script and resources file +- [```fbf35e51```](https://github.com/ktmeaton/ncov-recombinant/commit/fbf35e51) major environment reduction +- [```1b1f16e9```](https://github.com/ktmeaton/ncov-recombinant/commit/1b1f16e9) remove bedtools from env +- [```7b650279```](https://github.com/ktmeaton/ncov-recombinant/commit/7b650279) remove seaborn from env +- [```b32608e7```](https://github.com/ktmeaton/ncov-recombinant/commit/b32608e7) remove snipit from env +- [```9cab231e```](https://github.com/ktmeaton/ncov-recombinant/commit/9cab231e) remove augur from env +- [```a69836a8```](https://github.com/ktmeaton/ncov-recombinant/commit/a69836a8) fix pandas warnings in report +- [```b3137ed3```](https://github.com/ktmeaton/ncov-recombinant/commit/b3137ed3) remove script usher_plot as now we rely on auspice +- [```06fa080d```](https://github.com/ktmeaton/ncov-recombinant/commit/06fa080d) remove script update_controls which is now done manually +- [```e8d46a64```](https://github.com/ktmeaton/ncov-recombinant/commit/e8d46a64) consolidate lineage call in report +- [```ccfea688```](https://github.com/ktmeaton/ncov-recombinant/commit/ccfea688) hardcode columns for report +- [```5172755e```](https://github.com/ktmeaton/ncov-recombinant/commit/5172755e) improve type catching in date_to_decimal +- [```74f0e528```](https://github.com/ktmeaton/ncov-recombinant/commit/74f0e528) update controls breakpoints and add col sc2rf_lineage +- [```d4664015```](https://github.com/ktmeaton/ncov-recombinant/commit/d4664015) add param --ignore-shared-subs to sc2rf +- [```659d7f83```](https://github.com/ktmeaton/ncov-recombinant/commit/659d7f83) overhaul reporting workflow +- [```e8e3444f```](https://github.com/ktmeaton/ncov-recombinant/commit/e8e3444f) update controls metadata and dev notes +- [```07a5ff52```](https://github.com/ktmeaton/ncov-recombinant/commit/07a5ff52) add XM to controls + +## v0.1.1 + +### Notes + +1. Add lineage `XD` to controls. + + - There are now publicly available samples. + +1. Add lineage `XQ` to controls. + + - Has only 1 diagnostic substitution: 2832. + +1. Add lineage `XS` to controls. +1. Exclude lineage `XR` because it has no public genomes. + + - `XR` decends from `XQ` in the UShER tree. + +1. Test `sc2rf` dev to ignore clade regions that are ambiguous. +1. Add column `usher_pango_lineage_map` that maps github issues to recombinant lineages. +1. Add new rule `report`. +1. Filter non-recombinants from `sc2rf` ansi output. +1. Fix `subtrees_collapse` failing if only 1 tree specified +1. Add new rule `usher_metadata` for merge metadata for subtrees. + +### Commits + +- [```b8f89d5e```](https://github.com/ktmeaton/ncov-recombinant/commit/b8f89d5e) update docs for v0.1.1 +- [```2b8772ab```](https://github.com/ktmeaton/ncov-recombinant/commit/2b8772ab) update autologs for pr date matching +- [```f2a7547d```](https://github.com/ktmeaton/ncov-recombinant/commit/f2a7547d) add low_memory_mode for issue #9 +- [```94fc9426```](https://github.com/ktmeaton/ncov-recombinant/commit/94fc9426) add log to report rule +- [```861ffb17```](https://github.com/ktmeaton/ncov-recombinant/commit/861ffb17) update usher output image +- [```fdee0da6```](https://github.com/ktmeaton/ncov-recombinant/commit/fdee0da6) add new rule usher_metadata +- [```c5003453```](https://github.com/ktmeaton/ncov-recombinant/commit/c5003453) add max parents param to sc2rf recombinants +- [```70cad049```](https://github.com/ktmeaton/ncov-recombinant/commit/70cad049) add max ambig filter to defaults for sc2rf +- [```b4cc40f4```](https://github.com/ktmeaton/ncov-recombinant/commit/b4cc40f4) add script to collapse usher metadata for auspice +- [```847c6d24```](https://github.com/ktmeaton/ncov-recombinant/commit/847c6d24) catch single trees in usher collapse +- [```636778e0```](https://github.com/ktmeaton/ncov-recombinant/commit/636778e0) rename sc2rf txt output to ansi +- [```bae50814```](https://github.com/ktmeaton/ncov-recombinant/commit/bae50814) change final target to report +- [```9a830085```](https://github.com/ktmeaton/ncov-recombinant/commit/9a830085) add new rule report +- [```601e1728```](https://github.com/ktmeaton/ncov-recombinant/commit/601e1728) add XD to controls +- [```baa1d64e```](https://github.com/ktmeaton/ncov-recombinant/commit/baa1d64e) relax sc2rf --unique from 2 to 1 for XQ +- [```bffbb9ad```](https://github.com/ktmeaton/ncov-recombinant/commit/bffbb9ad) add column sc2rf_clades_filter +- [```109ed5d2```](https://github.com/ktmeaton/ncov-recombinant/commit/109ed5d2) test sc2rf dev to not report ambiguous regions +- [```d9fdffef```](https://github.com/ktmeaton/ncov-recombinant/commit/d9fdffef) fix tab spaces at end of usher placement +- [```085e1764```](https://github.com/ktmeaton/ncov-recombinant/commit/085e1764) update sc2rf for tsv/csv PR +- [```d2363855```](https://github.com/ktmeaton/ncov-recombinant/commit/d2363855) set threads and cpus to 1 for all single-thread rules +- [```13027205```](https://github.com/ktmeaton/ncov-recombinant/commit/13027205) impose wildcard constraint on nextclade_dataset +- [```30e1406b```](https://github.com/ktmeaton/ncov-recombinant/commit/30e1406b) fix typo in csv path for sc2rf +- [```d6d8377a```](https://github.com/ktmeaton/ncov-recombinant/commit/d6d8377a) add XS breakpoints to metadata +- [```371e4069```](https://github.com/ktmeaton/ncov-recombinant/commit/371e4069) add XS and XQ to controls +- [```1e31e429```](https://github.com/ktmeaton/ncov-recombinant/commit/1e31e429) add breakpoints reference file in controls +- [```3088ad60```](https://github.com/ktmeaton/ncov-recombinant/commit/3088ad60) catch if sc2rf has no output +- [```64211360```](https://github.com/ktmeaton/ncov-recombinant/commit/64211360) catch all extra args in slurm +- [```c7a6b9ce```](https://github.com/ktmeaton/ncov-recombinant/commit/c7a6b9ce) remove unused nextclade_recombinants script +- [```38645ce9```](https://github.com/ktmeaton/ncov-recombinant/commit/38645ce9) remove codecov badge +- [```50fa9d89```](https://github.com/ktmeaton/ncov-recombinant/commit/50fa9d89) update CHANGELOG for v0.1.0 + +## v0.1.0 + +### Notes + +1. Add Stage 1: Nextclade. +1. Add Stage 2: sc2rf. +1. Add Stage 3: UShER. +1. Add Stage 4: Summary. +1. Add Continuous Integration workflows: `lint`, `test`, `pipeline`, and `release`. +1. New representative controls dataset: + + - Exclude XA because this is an Alpha recombinant (poor lineage accuracy). + - Exclude XB because of [current issue](https://github.com/summercms/covid19-pango-designation/commit/26b7359e34a0b2f122215332b6495fea97ff3fe7) + - Exclude XC because this is an Alpha recombinant (poor lineage accuracy). + - Exclude XD because there are no public genomes. + - Exclude XK because there are no public genomes. + +### Pull Requests + +- [```pull/3```](https://github.com/ktmeaton/ncov-recombinant/pull/3) Add Continuous Integration workflows: lint, test, pipeline, and release. + +### Commits + +- [```34c721b7```](https://github.com/ktmeaton/ncov-recombinant/commit/34c721b7) rearrange summary cols +- [```18b389de```](https://github.com/ktmeaton/ncov-recombinant/commit/18b389de) disable usher plotting +- [```0a101dd9```](https://github.com/ktmeaton/ncov-recombinant/commit/0a101dd9) covert sc2rf_recombinants to a script +- [```494fb60c```](https://github.com/ktmeaton/ncov-recombinant/commit/494fb60c) change nextclade filtering to multi columns +- [```f0676bd8```](https://github.com/ktmeaton/ncov-recombinant/commit/f0676bd8) add python3 directive to unit tests +- [```9da626fd```](https://github.com/ktmeaton/ncov-recombinant/commit/9da626fd) update unit tests for new controls dataset +- [```46717c6f```](https://github.com/ktmeaton/ncov-recombinant/commit/46717c6f) fix summary script for new ver +- [```9fc690ed```](https://github.com/ktmeaton/ncov-recombinant/commit/9fc690ed) fix usher public-latest links +- [```1fb28ea0```](https://github.com/ktmeaton/ncov-recombinant/commit/1fb28ea0) change sc2rf to bash script +- [```ba98d936```](https://github.com/ktmeaton/ncov-recombinant/commit/ba98d936) update sc2rf params +- [```89647109```](https://github.com/ktmeaton/ncov-recombinant/commit/89647109) update sc2rf artpoon pr +- [```2b7dcab4```](https://github.com/ktmeaton/ncov-recombinant/commit/2b7dcab4) ignore my_profiles +- [```9df0f9b4```](https://github.com/ktmeaton/ncov-recombinant/commit/9df0f9b4) add debugging mode for sc2rf (lint) +- [```caaf4deb```](https://github.com/ktmeaton/ncov-recombinant/commit/caaf4deb) add debugging mode for sc2rf +- [```7ec53ac6```](https://github.com/ktmeaton/ncov-recombinant/commit/7ec53ac6) remove unecessary param exp_input +- [```a3810bca```](https://github.com/ktmeaton/ncov-recombinant/commit/a3810bca) add program versions to summary +- [```3376196b```](https://github.com/ktmeaton/ncov-recombinant/commit/3376196b) Add Continuous Integration workflows: lint, test, pipeline, and release. (#3) +- [```db45768f```](https://github.com/ktmeaton/ncov-recombinant/commit/db45768f) more instructions for visualizing output +- [```ee4c2660```](https://github.com/ktmeaton/ncov-recombinant/commit/ee4c2660) update readme keywords +- [```cb5b2c23```](https://github.com/ktmeaton/ncov-recombinant/commit/cb5b2c23) add instructions for slurm submission +- [```f04eb28b```](https://github.com/ktmeaton/ncov-recombinant/commit/f04eb28b) adjust laptop profile to use 1 cpu +- [```eafed44e```](https://github.com/ktmeaton/ncov-recombinant/commit/eafed44e) add snakefile +- [```eb214d72```](https://github.com/ktmeaton/ncov-recombinant/commit/eb214d72) add scripts +- [```cb47b046```](https://github.com/ktmeaton/ncov-recombinant/commit/cb47b046) add README.md +- [```3794d8de```](https://github.com/ktmeaton/ncov-recombinant/commit/3794d8de) add images dir +- [```f1c0cef8```](https://github.com/ktmeaton/ncov-recombinant/commit/f1c0cef8) add profiles laptop and hpc +- [```6f5fd84b```](https://github.com/ktmeaton/ncov-recombinant/commit/6f5fd84b) add release notes +- [```92b0c476```](https://github.com/ktmeaton/ncov-recombinant/commit/92b0c476) add default parameters +- [```c79bfe12```](https://github.com/ktmeaton/ncov-recombinant/commit/c79bfe12) add submodule ncov +- [```2a65e92d```](https://github.com/ktmeaton/ncov-recombinant/commit/2a65e92d) add submodule sc2rf +- [```0f8bfe33```](https://github.com/ktmeaton/ncov-recombinant/commit/0f8bfe33) add submodule autologs +- [```b6f1e1d6```](https://github.com/ktmeaton/ncov-recombinant/commit/b6f1e1d6) add report captions +- [```68fd2dec```](https://github.com/ktmeaton/ncov-recombinant/commit/68fd2dec) add conda env +- [```8907375e```](https://github.com/ktmeaton/ncov-recombinant/commit/8907375e) add reference dataset +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","sc2rf/sc2rf.py",".py","54818","1534","#!/usr/bin/env python3 + +import csv +import enum +from typing import NamedTuple +from termcolor import colored, cprint +import json +import argparse +import os +import requests +from tqdm import tqdm +import urllib.parse +import itertools + + +colors = [""red"", ""green"", ""blue"", ""yellow"", ""magenta"", ""cyan""] + +width_override = None + +# I removed ""ORF"" from the names, because often we only see the first one or two letters of a name, and ""ORF"" provides no information +genes = { + ""1a"": (266, 13468), + ""1b"": (13468, 21555), + ""S"": (21563, 25384), + ""E"": (26245, 26472), + ""3a"": (25393, 26220), + ""M"": (26523, 27191), + ""6"": (27202, 27387), + ""7a"": (27394, 27759), + ""7b"": (27756, 27887), + ""8"": (27894, 28259), + ""N"": ( + 28274, + 28283, + ), # my algorithm does not like that ORF9b is inside N, so I split N in two halves + ""9b"": (28284, 28577), + ""N"": (28578, 29533), + """": (29534, 99999), # probably nothing, but need something to mark the end of N +} + + +class Interval: + """"""An interval of integers, e.g., 27, 27-, -30 or 27-30"""""" + + def __init__(self, string): + # TODO allow multiple separators, see https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters + self.original_string = string + parts = string.split(""-"") + if len(parts) == 1: + self.min = int(parts[0]) + self.max = int(parts[0]) + elif len(parts) == 2: + self.min = int(parts[0]) if parts[0] else None + self.max = int(parts[1]) if parts[1] else None + else: + raise ValueError(""invalid interval: "" + string) + + def matches(self, num): + """"""check if num is within closed interval"""""" + if self.min and num < self.min: + return False + if self.max and num > self.max: + return False + + return True + + def __str__(self): + return self.original_string + + +def main(): + """"""Command line interface"""""" + global mappings + global width_override + global dot_character + + dot_character = ""•"" + + # This strange line should enable handling of + # ANSI / VT 100 codes in windows terminal + # See https://stackoverflow.com/a/39675059/39946 + os.system("""") + + parser = argparse.ArgumentParser( + description=""Analyse SARS-CoV-2 sequences for potential, unknown recombinant variants."", + epilog='An Interval can be a single number (""3""), a closed interval (""2-5"" ) or an open one (""4-"" or ""-7"").' + "" The limits are inclusive. Only positive numbers are supported."", + formatter_class=ArgumentAdvancedDefaultsHelpFormatter, + ) + parser.add_argument( + ""input"", nargs=""*"", help=""input sequence(s) to test, as aligned .fasta file(s)"" + ) + parser.add_argument( + ""--primers"", + nargs=""*"", + metavar=""PRIMER"", + help=""Filenames of primer set(s) to visualize. The .bed formats for ARTIC and EasySeq are recognized and supported."", + ) + parser.add_argument( + ""--primer-intervals"", + nargs=""*"", + metavar=""INTERVAL"", + type=Interval, + help=""Coordinate intervals in which to visualize primers."", + ) + parser.add_argument( + ""--parents"", + ""-p"", + default=""2-4"", + metavar=""INTERVAL"", + type=Interval, + help=""Allowed number of potential parents of a recombinant."", + ) + parser.add_argument( + ""--breakpoints"", + ""-b"", + default=""1-4"", + metavar=""INTERVAL"", + type=Interval, + help=""Allowed number of breakpoints in a recombinant."", + ) + parser.add_argument( + ""--clades"", + ""-c"", + nargs=""*"", + default=[""20I"", ""20H"", ""20J"", ""21I"", ""21J"", ""BA.1"", ""BA.2"", ""BA.3""], + help='List of variants which are considered as potential parents. Use Nextstrain clades (like ""21B""), or Pango Lineages (like ""B.1.617.1"") or both. Also accepts ""all"".', + ) + parser.add_argument( + ""--unique"", + ""-u"", + default=2, + type=int, + metavar=""NUM"", + help=""Minimum of substitutions in a sample which are unique to a potential parent clade, so that the clade will be considered."", + ) + parser.add_argument( + ""--max-intermission-length"", + ""-l"", + metavar=""NUM"", + default=2, + type=int, + help=""The maximum length of an intermission in consecutive substitutions. Intermissions are stretches to be ignored when counting breakpoints."", + ) + parser.add_argument( + ""--max-intermission-count"", + ""-i"", + metavar=""NUM"", + default=8, + type=int, + help=""The maximum number of intermissions which will be ignored. Surplus intermissions count towards the number of breakpoints."", + ) + parser.add_argument( + ""--max-name-length"", + ""-n"", + metavar=""NUM"", + default=30, + type=int, + help=""Only show up to NUM characters of sample names."", + ) + parser.add_argument( + ""--max-ambiguous"", + ""-a"", + metavar=""NUM"", + default=50, + type=int, + help=""Maximum number of ambiguous nucs in a sample before it gets ignored."", + ) + parser.add_argument( + ""--force-all-parents"", + ""-f"", + action=""store_true"", + help=""Force to consider all clades as potential parents for all sequences. Only useful for debugging."", + ) + parser.add_argument( + ""--select-sequences"", + ""-s"", + default=""0-999999"", + metavar=""INTERVAL"", + type=Interval, + help=""Use only a specific range of input sequences. DOES NOT YET WORK WITH MULTIPLE INPUT FILES."", + ) + parser.add_argument( + ""--enable-deletions"", + ""-d"", + action=""store_true"", + help=""Include deletions in lineage comparision."", + ) + parser.add_argument( + ""--show-private-mutations"", + action=""store_true"", + help=""Display mutations which are not in any of the potential parental clades."", + ) + parser.add_argument( + ""--rebuild-examples"", + ""-r"", + action=""store_true"", + help=""Rebuild the mutations in examples by querying cov-spectrum.org."", + ) + parser.add_argument( + ""--mutation-threshold"", + ""-t"", + metavar=""NUM"", + default=0.75, + type=float, + help=""Consider mutations with a prevalence of at least NUM as mandatory for a clade (range 0.05 - 1.0, default: %(default)s)."", + ) + parser.add_argument( + ""--add-spaces"", + metavar=""NUM"", + nargs=""?"", + default=0, + const=5, + type=int, + help=""Add spaces between every N colums, which makes it easier to keep your eye at a fixed place."", + ) + parser.add_argument( + ""--sort-by-id"", + metavar=""NUM"", + nargs=""?"", + default=0, + const=999, + type=int, + help=""Sort the input sequences by the ID. If you provide NUM, only the first NUM characters are considered. Useful if this correlates with meaning full meta information, e.g. the sequencing lab."", + ) + # parser.add_argument('--sort-by-first-breakpoint', action='store_true', help='Does what it says.') + parser.add_argument( + ""--verbose"", + ""-v"", + action=""store_true"", + help=""Print some more information, mostly useful for debugging."", + ) + parser.add_argument( + ""--ansi"", + action=""store_true"", + help=""Use only ASCII characters to be compatible with ansilove."", + ) + parser.add_argument(""--update-readme"", action=""store_true"", help=argparse.SUPPRESS) + parser.add_argument( + ""--hide-progress"", + action=""store_true"", + help=""Don't show progress bars during long task."", + ) + parser.add_argument( + ""--csvfile"", + type=argparse.FileType(""w""), + help=""Path to write results in CSV format."", + ) + parser.add_argument( + ""--ignore-shared"", + action=""store_true"", + help=""Ignore substitutions that are shared between all parents."", + ) + parser.add_argument( + ""--gisaid-access-key"", + help=""covSPECTRUM accessKey for GISAID data."", + ) + + sc2rf_dir = os.path.dirname(os.path.realpath(__file__)) + + global args + args = parser.parse_args() + + mapping_path = os.path.join(sc2rf_dir, ""mapping.csv"") + mappings = read_mappings(mapping_path) + + if args.ansi: + dot_character = ""."" + + if args.update_readme: + update_readme(parser) + print(""Readme was updated. Program exits."") + return + + if args.rebuild_examples: + rebuild_examples() + if len(args.input) == 0: + print( + ""Examples were rebuilt, and no input sequences were provided. Program exits."" + ) + return + elif len(args.input) == 0: + print( + ""Input sequences must be provided, except when rebuilding the examples. Use --help for more info. Program exits."" + ) + return + + if args.mutation_threshold < 0.05 or args.mutation_threshold > 1.0: + print(""mutation-threshold must be between 0.05 and 1.0"") + return + + global reference + vprint(""Reading reference genome, lineage definitions..."") + reference_path = os.path.join(sc2rf_dir, ""reference.fasta"") + reference = read_fasta(reference_path, None)[""MN908947 (Wuhan-Hu-1/2019)""] + + virus_properties_path = os.path.join(sc2rf_dir, ""virus_properties.json"") + all_examples = read_examples(virus_properties_path) + + used_examples = [] + if ""all"" in args.clades: + used_examples = all_examples + else: + # screen for a subset of examples only + for example in all_examples: + if ( + len(example[""NextstrainClade""]) + and example[""NextstrainClade""] in args.clades + ): + used_examples.append(example) + elif ( + len(example[""PangoLineage""]) and example[""PangoLineage""] in args.clades + ): + used_examples.append(example) + + if args.force_all_parents and not args.parents.matches(len(used_examples)): + print( + ""The number of allowed parents, the number of selected clades and the --force-all-parents conflict so that the results must be empty."" + ) + return + + vprint(""Done.\nReading actual input."") + all_samples = dict() + for path in args.input: + read_samples = read_subs_from_fasta(path) + for key, val in read_samples.items(): + all_samples[key] = val # deep copy + vprint(""Done."") + + global primer_sets + primer_sets = dict() + if args.primers: + vprint(""Reading primers."") + for path in args.primers: + pools = read_bed(path) + primer_sets[path] = pools + vprint(""Done."") + + calculate_relations(used_examples) + + # lists of samples keyed by tuples of example indices + match_sets = dict() + + vprint(""Scanning input for matches against lineage definitons..."") + for sa_name, sa in my_tqdm(all_samples.items(), desc=""First pass scan""): + matching_example_indices = [] + if args.force_all_parents: + matching_example_indices = range(0, len(used_examples)) + else: + for i, ex in enumerate(used_examples): + matches_count = len(sa[""subs_set""] & ex[""unique_subs_set""]) + # theoretically > 0 already gives us recombinants, but they are much + # more likely to be errors or coincidences + if matches_count >= args.unique: + matching_example_indices.append(i) + + matching_examples_tup = tuple(matching_example_indices) + + if args.parents.matches(len(matching_example_indices)): + # print(f""{sa_name} is a possible recombinant of {len(matching_example_names)} lineages: {matching_example_names}"") + if match_sets.get(matching_examples_tup): + match_sets[matching_examples_tup].append(sa) + else: + match_sets[matching_examples_tup] = [sa] + + vprint(""Done.\nPrinting detailed analysis:\n\n"") + + # Write the headers to output csv file + writer = None + if args.csvfile: + fieldnames = [ + ""sample"", + ""examples"", + ""intermissions"", + ""breakpoints"", + ""regions"", + ""unique_subs"", + ""alleles"", + ] + if args.show_private_mutations: + fieldnames.append(""privates"") + writer = csv.DictWriter(args.csvfile, fieldnames=fieldnames) + writer.writeheader() + + # Write the data to the output csv file + if len(match_sets): + + for matching_example_indices, samples in match_sets.items(): + show_matches( + [used_examples[i] for i in matching_example_indices], + samples, + writer=writer, + ) + else: + print(""First pass found no potential recombinants, see "") + + +def my_tqdm(*margs, **kwargs): + return tqdm( + *margs, delay=0.1, colour=""green"", disable=bool(args.hide_progress), **kwargs + ) + + +def update_readme(parser: argparse.ArgumentParser): + # on wide monitors, github displays up to 90 columns of preformatted text + # but 10% of web users have screens which can only fit 65 characters + global width_override + width_override = 65 + + help = parser.format_help() + + new_lines = [] + + between_markers = False + + with open(""README.md"", ""rt"") as old_readme: + for line in old_readme: + if line.strip() == """": + between_markers = True + new_lines.append(""\n"") + + if line.strip() == """": + between_markers = False + new_lines.append(""```\n"") + new_lines.append(help + ""\n"") + new_lines.append(""```\n"") + + if not between_markers: + new_lines.append(line) + + with open(""README.md"", ""wt"") as new_readme: + new_readme.writelines(new_lines) + + +def vprint(text: str): + if args.verbose: + print(text) + + +def rebuild_examples(): + print(""Rebuilding examples from cov-spectrum.org..."") + with open(""virus_properties.json"", newline="""", mode=""w"") as jsonfile: + + the_list = [] + + for variant_props in mappings[""list""]: + pango = variant_props[""PangoLineage""] + clade = variant_props[""NextstrainClade""] + who_label = variant_props[""WhoLabel""] + query = """" + if variant_props[""Query""]: + query = ( + f""?variantQuery={urllib.parse.quote_plus(variant_props['Query'])}"" + ) + elif pango and len(pango) > 0: + query = f""?nextcladePangoLineage={pango}*"" + # WHO Labels were deprecated in cov-spectrum #546 + # elif clade and len(clade) > 0 and who_label: + # query = f""?nextstrainClade={clade}%20({who_label})"" + # elif clade and len(clade) > 0 and not who_label: + # query = f""?nextstrainClade={clade}"" + elif clade and len(clade) > 0: + query = f""?nextstrainClade={clade}"" + else: + print(""Variant has neither pango nor clade, check out mapping.csv!"") + continue + + print(f""Fetching data for {query}"") + if args.gisaid_access_key == None: + url = f""https://lapis.cov-spectrum.org/open/v1/sample/nuc-mutations{query}&minProportion=0.05"" + else: + url = f""https://lapis.cov-spectrum.org/gisaid/v1/sample/nuc-mutations{query}&minProportion=0.05&accessKey={args.gisaid_access_key}"" + print(f""Url is {url}"") + + r = requests.get(url) + result = r.json() + if len(result[""errors""]): + print(""Errors occured while querying cov-spectrum.org:"") + for e in result[""errors""]: + print("" "" + e) + + variant = variant_props.copy() + variant[""mutations""] = result[""data""] + + names = [who_label, pango, clade] + names = [n for n in names if n is not None and len(n.strip()) > 0] + variant[""name""] = "" / "".join(names) + + the_list.append(variant) + + props = { + ""schemaVersion"": ""s2r 0.0.2"", + ""comment"": ""New file format, no longer looks like the original virus_properties.json"", + ""variants"": the_list, + } + + json.dump(props, jsonfile, indent=4) + print(""Examples written to disk."") + + +def read_examples(path): + with open(path, newline="""") as jsonfile: + props = json.load(jsonfile) + assert props[""schemaVersion""] == ""s2r 0.0.2"" + examples = [] + for variant in props[""variants""]: + subs_dict = dict() + for m in variant[""mutations""]: + if m[""proportion""] < args.mutation_threshold: + continue + sub_string = m[""mutation""].strip() + + if len(sub_string) > 0: + sub = parse_sub(sub_string) + if (sub.mut != ""-"" or args.enable_deletions) and sub.mut != ""."": + subs_dict[sub.coordinate] = sub + example = { + ""name"": variant[""name""], + ""NextstrainClade"": variant[""NextstrainClade""], + ""PangoLineage"": variant[""PangoLineage""], + ""subs_dict"": subs_dict, + ""subs_list"": list(subs_dict.values()), + ""subs_set"": set(subs_dict.values()), + ""missings"": [], + } + + examples.append(example) + + return examples + + +class Primer(NamedTuple): + start: int + end: int + direction: str + alt: bool + name: str + sequence: str + + +class Amplicon: + left_primers: list + right_primer: list + number: int + color: str + start: int + end: int + + def __init__(self, number: int): + self.number = number + self.left_primers = list() + self.right_primers = list() + self.color = get_color(number) + self.start = None + self.end = None + self.amp_start = None + self.amp_end = None + + def __str__(self): + return f""Amplicon {self.number} ({self.start} to {self.end})"" + + def add_primer(self, primer): + if primer.direction == ""+"": + self.left_primers.append(primer) + if self.amp_start: + self.amp_start = max(self.amp_start, primer.end + 1) + else: + self.amp_start = primer.end + 1 + else: + self.right_primers.append(primer) + if self.amp_end: + self.amp_end = min(self.amp_end, primer.start - 1) + else: + self.amp_end = primer.start - 1 + + if self.start: + self.start = min(self.start, primer.start) + else: + self.start = primer.start + + if self.end: + self.end = max(self.end, primer.end) + else: + self.end = primer.end + + def get_char(self, coord: int): + if coord <= self.start or coord >= self.end: + return "" "" + + for primer in self.left_primers: + if primer.start <= coord and primer.end >= coord: + if primer.alt: + return ""{"" if args.ansi else ""‹"" + else: + return ""<"" if args.ansi else ""«"" + + for primer in self.right_primers: + if primer.start <= coord and primer.end >= coord: + if primer.alt: + return ""}"" if args.ansi else ""›"" + else: + return "">"" if args.ansi else ""»"" + + return ""-"" + + def overlaps_coord(self, coord: int, actual_amplicon: bool): + if actual_amplicon: + return coord >= self.amp_start and coord <= self.amp_end + else: + return coord >= self.start and coord <= self.end + + def overlaps_interval(self, interval: Interval): + if interval.max and self.start > interval.max: + return False + if interval.min and self.end < interval.min: + return False + return True + + +def read_bed(path): + pools = dict() + index = 0 + current_name = None + with open(path, newline="""") as bed: + for line in bed: + parts = line.strip().split(""\t"") + + if parts[0] == parts[3]: # EasySeq format + name = parts[6] + name_parts = name.split(""_"") + amplicon_index = int(name_parts[1]) + amplicon = Amplicon(amplicon_index) + left_primer = Primer( + start=int(parts[1]), + end=int(parts[2]), + name=""left_"" + str(amplicon_index), + alt=False, + direction=""+"", + sequence=None, + ) + right_primer = Primer( + start=int(parts[4]), + end=int(parts[5]), + name=""right_"" + str(amplicon_index), + alt=False, + direction=""-"", + sequence=None, + ) + amplicon.add_primer(left_primer) + amplicon.add_primer(right_primer) + + pool_index = (amplicon_index + 1) % 2 + 1 + + if not pools.get(pool_index): + pools[pool_index] = dict() + + pools[pool_index][amplicon_index] = amplicon + + else: + # ARTIC format + name = parts[3] + name_parts = name.split(""_"") + amplicon_index = int(name_parts[1]) + pool_index = parts[4] + direction = parts[5] + + pool = pools.get(pool_index) + if not pool: + pool = dict() + pools[pool_index] = pool + + amplicon = pool.get(amplicon_index) + if not amplicon: + amplicon = Amplicon(amplicon_index) + pool[amplicon_index] = amplicon + + primer = Primer( + start=int(parts[1]), + end=int(parts[2]), + name=parts[3], + alt=len(name_parts) == 4, + direction=direction, + sequence=parts[6] if 6 < len(parts) else None, + ) + + amplicon.add_primer(primer) + + return pools + + +def read_fasta(path, index_range): + """""" + :param path: str, absolute or relative path to FASTA file + :param index_range: Interval, select specific records from FASTA + :return: dict, sequences keyed by header + """""" + sequences = dict() + index = 0 + current_name = None + + file_pos = 0 + with my_tqdm( + total=os.stat(path).st_size, desc=""Read "" + path, unit_scale=True + ) as pbar: + with open(path, newline="""") as fasta: + current_sequence = """" + for line in fasta: + file_pos += len(line) + pbar.update(file_pos - pbar.n) + if line[0] == "">"": + if current_name and (not index_range or index_range.matches(index)): + sequences[current_name] = current_sequence + index += 1 + if index_range and index_range.max and index > index_range.max: + return sequences + current_sequence = """" + current_name = line[1:].strip() + else: + current_sequence += line.strip().upper() + sequences[current_name] = current_sequence + + return sequences + + +def read_subs_from_fasta(path): + """""" + Extract substitutions relative to reference genome. + :param path: str, path to input FASTA file + :return: dict, substitutions (as dict, list or set) keyed by genome name + """""" + fastas = read_fasta(path, args.select_sequences) + sequences = dict() + start_n = -1 # used for tracking runs of Ns or gaps + removed_due_to_ambig = 0 + for name, fasta in my_tqdm(fastas.items(), desc=""Finding mutations in "" + path): + subs_dict = dict() # substitutions keyed by position + missings = list() # start/end tuples of N's or gaps + coverage = list() # inverse of missings, start/end tuples without N's or gaps + + # Coverage is always bases that are not ""-"" or ""N"", regardess of --enable-deletions + no_cov_matches = [""N"", ""-""] + + # Missing can vary, depending on --enable-deletions + missings_matches = [""N""] + if not args.enable_deletions: + missings_matches.append(""-"") + + if len(fasta) != len(reference): + print( + f""Sequence {name} not properly aligned, length is {len(fasta)} instead of {len(reference)}."" + ) + else: + ambiguous_count = 0 + start_cov = 1 + for i in range(1, len(reference) + 1): + r = reference[i - 1] + s = fasta[i - 1] + + if s not in no_cov_matches: + coverage.append(i) + + if s in missings_matches: + missings.append(i) + + if r != s and s not in missings_matches: + subs_dict[i] = Sub(r, i, s) # nucleotide substitution + + if not s in ""AGTCN-"": + ambiguous_count += 1 # count mixtures + + # Collapse bases into interval + coverage = list(to_ranges(coverage)) + missings = list(to_ranges(missings)) + + if ambiguous_count <= args.max_ambiguous: + sequences[name] = { + ""name"": name, # isn't this redundant? + ""subs_dict"": subs_dict, + ""subs_list"": list(subs_dict.values()), + ""subs_set"": set(subs_dict.values()), + ""missings"": missings, + ""coverage"": coverage, + } + else: + removed_due_to_ambig += 1 + + if removed_due_to_ambig: + print( + f""Removed {removed_due_to_ambig} of {len(fastas)} sequences with more than { args.max_ambiguous} ambiguous nucs."" + ) + + return sequences + + +class Sub(NamedTuple): + ref: str + coordinate: int + mut: str + + +def parse_sub(s): + if s[0].isdigit(): + coordinate = int(s[0:-1]) + return Sub(reference[coordinate - 1], coordinate, s[-1]) + else: + return Sub(s[0], int(s[1:-1]), s[-1]) + + +def prunt(s, color=None): + if color: + cprint(s, color, end="""") + else: + print(s, end="""") + + +def fixed_len(s, l): + trunc = s[0:l] + return trunc.ljust(l) + + +def show_matches(examples, samples, writer): + """""" + Display results to screen + :param examples: list, dict for every variant reference genome with keys: + ['name', 'NextstrainClade', 'PangoLineage', 'subs_dict', + 'subs_list', 'subs_set', 'missings', 'unique_subs_set'] + :param samples: list, dict for every query genome, same structure as above + :param writer: csv.DictWriter, optional (defaults to None) + """""" + ml = args.max_name_length + examples_str = "","".join([ex[""name""] for ex in examples]) + + if args.sort_by_id: + samples.sort(key=lambda sample: sample[""name""][: args.sort_by_id]) + + # set union of mutations in all example genomes + coords = set() + for ex in examples: + for sub in ex[""subs_list""]: + coords.add(sub.coordinate) + + private_coords = set() + if args.show_private_mutations: + # append mutations unique to sample genomes + for sa in samples: + for sub in sa[""subs_list""]: + # Check if this is a private mutation + if sub.coordinate not in coords: + private_coords.add(sub.coordinate) + + # Add in the private mutations + coords = coords.union(private_coords) + + if args.ignore_shared: + filter_coords = set() + for coord in coords: + parents_matches = 0 + for ex in examples: + # Store of list of substitutions coords for this example + ex_coords = [sub.coordinate for sub in ex[""subs_list""]] + # check if the coord matches this parent + if coord in ex_coords: + parents_matches += 1 + + # Ignore this coord it if was found in all parents (except if there was only 1 parent) + if parents_matches == len(examples) and len(examples) != 1: + continue + # Always add a definitive match or private + elif parents_matches <= 1: + filter_coords.add(coord) + # Check if we're showing substitutions found in multiple parents + elif parents_matches > 1 and not args.ignore_shared: + filter_coords.add(coord) + + coords = filter_coords + + if args.primers: + for name, primer_set in primer_sets.items(): + for pool in primer_set.values(): + for amplicon in pool.values(): + if args.primer_intervals: + # check if amplicon should be shown at all, or if it's outside primer_intervals + amplicon_matches = False + for interval in args.primer_intervals: + if amplicon.overlaps_interval(interval): + amplicon_matches = True + break + if not amplicon_matches: + continue + + # check if enough of the actual amplicon range is shown to display its number + name_len = len(str(amplicon.number)) + matched_coords = 0 + for coord in coords: + if amplicon.overlaps_coord(coord, True): + matched_coords += 1 + if matched_coords < name_len: + coords.update( + range(amplicon.amp_start, amplicon.amp_start + name_len) + ) + + # make sure that every alt primer is shown for at least one coord + # otherwise mismatches in the primary primer may look as if they + # would not be compensated by an alt primer + for primer in amplicon.left_primers + amplicon.right_primers: + if primer.alt: + coords.add(primer.start) + + # if amplicon.number == 76: + # coords.update(range(amplicon.start, amplicon.end + 1)) + + ordered_coords = list(coords) + ordered_coords.sort() + + ordered_privates = list(private_coords) + ordered_privates.sort() + + color_by_name = dict() + color_index = 0 + for ex in examples: + color_by_name[ex[""name""]] = get_color(color_index) + color_index += 1 + + # This method works in a weird way: it pre-constructs the lines for the actual sequences, + # and while it constructs the strings, it decides if they are worth showing at the same time. + # Then, if at least one such string was collected, it prints the header lines for them, and after that the strings. + + ###### SHOW SAMPLES + current_color = ""grey"" + collected_outputs = [] + last_id = """" + + for sa in my_tqdm( + samples, desc=f""Second pass scan for {[ex['name'] for ex in examples]}"" + ): + # current_color = get_color(color_index) + # color_by_name[sa['name']] = current_color + + prev_definitive_match = None + breakpoints = 0 + definitives_since_breakpoint = 0 + definitives_count = [] + unique_subs = [] + alleles = [] + regions = [] # for CSV output + privates = [] + last_coord = None + + if len(ordered_coords) == 0: + continue + else: + start_coord = ordered_coords[0] + + output = """" + + output += fixed_len(sa[""name""], ml) + "" "" + + for c, coord in enumerate(ordered_coords): + + matching_exs = [] + + if args.add_spaces and c % args.add_spaces == 0: + output += "" "" + + # ----------------------------------------------------------------- + # OPTION 1: MISSING DATA + + if is_missing(coord, sa[""missings""]): + # TBD: Is this always going to be an N? + + alleles.append(""{}|{}|{}"".format(coord, ""Missing"", ""N"")) + output += colored(""N"", ""white"", attrs=[""reverse""]) + + # Did we find a matching example in the previous region? + if prev_definitive_match: + + # If we have recently seen a definitive, add to the counts + if definitives_since_breakpoint: + definitives_count.append( + (prev_definitive_match, definitives_since_breakpoint) + ) + + # Since we don't know the parent of missing, treat as a breakpoint + breakpoints += 1 + regions.append((start_coord, last_coord, prev_definitive_match)) + # Reset the previous match + prev_definitive_match = None + # Reset definitives count + definitives_since_breakpoint = 0 + + # ----------------------------------------------------------------- + # OPTION 2: NON-MISSING DATA + + else: + + # ------------------------------------------------------------- + # OPTION 2a: Substitution + + if sa[""subs_dict""].get(coord): + + # Search for an example that matches this substitution + for ex in examples: + if ( + ex[""subs_dict""].get(coord) + and ex[""subs_dict""].get(coord).mut + == sa[""subs_dict""][coord].mut + ): + matching_exs.append(ex[""name""]) + + # Initialize the formatting of the output base + text = sa[""subs_dict""][coord].mut + fg = ""white"" + bg = None + attrs = [""bold""] + + # If this is a terminal deletion, recode to N + if text == ""-"": + + # Has there been coverage in prior coords? + # Just check the first tuple of coverage (beginning) + prev_terminal_deletion = True + first_cov_coord = sa[""coverage""][0][0] + if first_cov_coord < coord: + prev_terminal_deletion = False + + # Has there been coverage in proceeding coords? + # Just check the last tuple of coverage (end) + proc_terminal_deletion = True + last_cov_coord = sa[""coverage""][-1][1] + if last_cov_coord > coord: + proc_terminal_deletion = False + + if prev_terminal_deletion or proc_terminal_deletion: + text = ""N"" + + # Check if this is an N + if text == ""N"": + alleles.append(""{}|{}|{}"".format(coord, ""Missing"", ""N"")) + fg = ""white"" + attrs = [""reverse""] + + # none of the examples match - private mutation + elif len(matching_exs) == 0: + bg = ""on_cyan"" + privates.append(sa[""subs_dict""].get(coord)) + # Output the base, then skip to the next record + # ie. don't save the current coords as a last coord for breakpoints + alleles.append(""{}|{}|{}"".format(coord, ""Private"", text)) + output += colored(text, fg, bg, attrs=attrs) + continue + + # exactly one of the examples match - definite match + elif len(matching_exs) == 1: + unique_subs.append(""{}|{}"".format(coord, matching_exs[0])) + alleles.append(""{}|{}|{}"".format(coord, matching_exs[0], text)) + + fg = color_by_name[matching_exs[0]] + + # If the previous region matched a different example, this is the start of a new parental region + if matching_exs[0] != prev_definitive_match: + + if prev_definitive_match: + # record the previous parental region + regions.append( + (start_coord, last_coord, prev_definitive_match) + ) + # record a breakpoint + breakpoints += 1 + + # Record definitive substitutions observed in the previous region + if definitives_since_breakpoint: + definitives_count.append( + ( + prev_definitive_match, + definitives_since_breakpoint, + ) + ) + + # The current coordinate begins the new region + start_coord = coord + # The current example is the new parent + prev_definitive_match = matching_exs[0] + # Reset the definitives count to 0 + definitives_since_breakpoint = 0 + + # Increment the counter of definitives + definitives_since_breakpoint += 1 + + # more than one, but not all examples match - can't provide proper color + elif len(matching_exs) < len(examples): + # bg = 'on_blue' + alleles.append( + ""{}|{}|{}"".format(coord, "";"".join(matching_exs), text) + ) + attrs = [""bold"", ""underline""] + + # all examples match + else: + if args.ignore_shared: + continue + else: + alleles.append( + ""{}|{}|{}"".format(coord, "";"".join(matching_exs), text) + ) + + output += colored(text, fg, bg, attrs=attrs) + + # ------------------------------------------------------------- + # Not a Substitution + else: + + # Find examples that have the reference allele + matching_exs = [] + for ex in examples: + if not ex[""subs_dict""].get(coord): + matching_exs.append(ex[""name""]) + + text = dot_character + fg = ""white"" + bg = None + attrs = [] + ref_allele = reference[coord - 1] + + # Option 1: none of the examples match - private reverse mutation + if len(matching_exs) == 0: + alleles.append(""{}|{}|{}"".format(coord, ""Private"", ref_allele)) + bg = ""on_magenta"" + + elif len(matching_exs) == 1: + # exactly one of the examples match - definite match + alleles.append( + ""{}|{}|{}"".format(coord, matching_exs[0], ref_allele) + ) + fg = color_by_name[matching_exs[0]] + # If we haven't found a definitive match yet, this is the start coord + if not prev_definitive_match: + start_coord = coord + + if matching_exs[0] != prev_definitive_match: + if prev_definitive_match: + breakpoints += 1 + regions.append( + (start_coord, last_coord, prev_definitive_match) + ) + start_coord = coord # start of a new region + + if definitives_since_breakpoint: + definitives_count.append( + ( + prev_definitive_match, + definitives_since_breakpoint, + ) + ) + + prev_definitive_match = matching_exs[0] + definitives_since_breakpoint = 0 + + definitives_since_breakpoint += 1 + + elif len(matching_exs) < len(examples): + # more than one, but not all examples match - can't provide proper color + # bg = 'on_yellow' + attrs = [""underline""] + # Output the base, then skip to the next record + # ie. don't save the current coords as a last coord for breakpoints + alleles.append( + ""{}|{}|{}"".format(coord, "";"".join(matching_exs), ref_allele) + ) + output += colored(text, fg, bg, attrs=attrs) + continue + + else: + # all examples match (which means this is a private mutation in another sample) + # Output the base, then skip to the next record + # ie. don't save the current coords as a last coord for breakpoints + alleles.append( + ""{}|{}|{}"".format(coord, "";"".join(matching_exs), ref_allele) + ) + output += colored(text, fg, bg, attrs=attrs) + continue + + output += colored(text, fg, bg, attrs=attrs) + + last_coord = coord # save current coord before iterating to next + + # Finish iterating through all coords for a sample + + # output last region, if it wasn't missing + if prev_definitive_match: + regions.append((start_coord, last_coord, prev_definitive_match)) + + if definitives_since_breakpoint: + definitives_count.append( + (prev_definitive_match, definitives_since_breakpoint) + ) + + # now transform definitive streaks: every sequence like ..., X, S, Y, ... where S is a small numer into ..., (X+Y), ... + + reduced = list( + filter( + lambda ex_count: ex_count[1] > args.max_intermission_length, + definitives_count, + ) + ) + num_intermissions = len(definitives_count) - len(reduced) + + further_reduced = [] + + if len(reduced): + last_ex = reduced[0][0] + last_count = 0 + for (ex, count) in reduced: + if ex != last_ex: + further_reduced.append(last_count) + last_count = count + last_ex = ex + else: + last_count += count + if last_count: + further_reduced.append(last_count) + + postfix = """" + num_breakpoints = len(further_reduced) - 1 + if num_intermissions > args.max_intermission_count: + postfix = ""/"" + str(num_intermissions) + num_breakpoints += (num_intermissions - args.max_intermission_count) * 2 + num_intermissions = args.max_intermission_count + + output += f"" {num_breakpoints} BP"" + if num_intermissions: + output += ( + f"", {num_intermissions}{postfix} I <= {args.max_intermission_length}"" + ) + + if args.breakpoints.matches(num_breakpoints): + if ( + args.sort_by_id + and args.sort_by_id != 999 + and last_id + != sa[""name""][: args.sort_by_id] + != last_id[: args.sort_by_id] + ): + collected_outputs.append(""---"") + + last_id = sa[""name""] + collected_outputs.append(output) + if writer: + row = { + ""sample"": last_id, + ""examples"": examples_str.replace("" "", """"), + ""intermissions"": num_intermissions, + ""breakpoints"": num_breakpoints, + ""regions"": "","".join( + [ + f""{start}:{stop}|{ex.replace(' ', '')}"" + for start, stop, ex in regions + ] + ), + ""unique_subs"": "","".join(unique_subs).replace("" "", """"), + ""alleles"": "","".join(alleles).replace("" "", """"), + } + if args.show_private_mutations: + row.update( + { + ""privates"": "","".join( + [f""{ps.ref}{ps.coordinate}{ps.mut}"" for ps in privates] + ) + } + ) + writer.writerow(row) + + if len(collected_outputs) == 0: + print( + f""\n\nSecond pass scan found no potential recombinants between {[ex['name'] for ex in examples]}.\n"" + ) + else: + print( + f""\n\nPotential recombinants between {[ex['name'] for ex in examples]}:\n"" + ) + + ###### SHOW COORDS + + for exp in range(5, 0, -1): + div = 10 ** (exp - 1) + + if exp == 5: + prunt(fixed_len(""coordinates"", ml + 1)) + else: + prunt("" "" * (ml + 1)) + + for c, coord in enumerate(ordered_coords): + if args.add_spaces and c % args.add_spaces == 0: + prunt("" "") + if coord // div > 0: + prunt((coord // div) % 10) + else: + prunt("" "") + # print(f""{coord} // {div} = {(coord//div)}"") + print() + print() + + ###### SHOW GENES + prunt(fixed_len(""genes"", ml + 1)) + + current_name = """" + color_index = 0 + current_color = get_color(color_index) + text_index = 0 + + for c, coord in enumerate(ordered_coords): + for name, limits in genes.items(): + if coord >= limits[0] and coord <= limits[1]: + if current_name != name: + current_name = name + color_index += 1 + current_color = get_color(color_index) + text_index = 0 + + # Do this once or twice, depending on space insertion + for i in range(1 + (args.add_spaces and c % args.add_spaces == 0)): + char = "" "" + if len(current_name) > text_index: + char = current_name[text_index] + cprint(char, ""grey"", ""on_"" + current_color, end="""") + text_index += 1 + + print("" "") + + if args.primers: + ###### SHOW PRIMERS + + prunt(""\n"") + for name, primer_set in primer_sets.items(): + for index, pool in primer_set.items(): + prunt(fixed_len(f""{name}, pool {index}"", ml + 1)) + + for c, coord in enumerate(ordered_coords): + char = "" "" + for amplicon in pool.values(): + + if args.primer_intervals: + amplicon_matches = False + for interval in args.primer_intervals: + if amplicon.overlaps_interval(interval): + amplicon_matches = True + break + if not amplicon_matches: + continue + + if amplicon.overlaps_coord(coord, False): + char = amplicon.get_char(coord) + if current_name != str(amplicon.number): + current_name = str(amplicon.number) + text_index = 0 + current_color = amplicon.color + + if args.add_spaces and c % args.add_spaces == 0: + prunt("" "") + + if char == ""-"" and len(current_name) > text_index: + char = current_name[text_index] + text_index += 1 + cprint(char, current_color, end="""") + + print("" "") + + print() + + ###### SHOW REF + + prunt(fixed_len(""ref"", ml + 1)) + for c, coord in enumerate(ordered_coords): + if args.add_spaces and c % args.add_spaces == 0: + prunt("" "") + prunt(reference[coord - 1]) + print() + print() + + ###### SHOW EXAMPLES + + for ex in examples: + current_color = color_by_name[ex[""name""]] + prunt(fixed_len(ex[""name""], ml) + "" "", current_color) + for c, coord in enumerate(ordered_coords): + if args.add_spaces and c % args.add_spaces == 0: + prunt("" "") + if ex[""subs_dict""].get(coord): + prunt(ex[""subs_dict""][coord].mut, current_color) + else: + prunt(dot_character) + print() + print() + + for output in collected_outputs: + print(output) + + print() + cprint( + ""made with Sc2rf - available at https://github.com/lenaschimmel/sc2rf"", + ""white"", + ) + print() + + +def get_color(color_index): + return colors[color_index % len(colors)] + + +def read_mappings(path): + with open(path, newline="""") as csvfile: + mappings = {""by_clade"": dict(), ""by_lineage"": dict(), ""list"": list()} + reader = csv.DictReader(csvfile) + line_count = 0 + for row in reader: + if len(row[""NextstrainClade""]): + mappings[""by_clade""][row[""NextstrainClade""]] = row + if len(row[""PangoLineage""]): + mappings[""by_lineage""][row[""PangoLineage""]] = row + mappings[""list""].append(row) + return mappings + + +def read_subs(path, delimiter="","", max_lines=-1): + with open(path, newline="""") as csvfile: + sequences = {} + reader = csv.DictReader(csvfile, delimiter=delimiter) + line_count = 0 + for row in reader: + subs_dict = dict() + missings = list() + for s in row[""substitutions""].split("",""): + s = s.strip() + if len(s) > 0: + sub = parse_sub(s) + subs_dict[sub.coordinate] = sub + + for m in row[""missing""].split("",""): + m = m.strip() + if len(m) > 0: + parts = m.split(""-"") + if len(parts) == 1: + missings.append((int(parts[0]), int(parts[0]))) + else: + missings.append((int(parts[0]), int(parts[1]))) + + sequences[row[""seqName""]] = { + ""name"": row[""seqName""], + ""subs_dict"": subs_dict, + ""subs_list"": list(subs_dict.values()), + ""subs_set"": set(subs_dict.values()), + ""missings"": missings, + } + + line_count += 1 + if max_lines != -1 and line_count == max_lines: + break + return sequences + + +def is_missing(coordinate, missings): + for missing in missings: + if coordinate >= missing[0] and coordinate <= missing[1]: + return True + return False + + +def calculate_relations(examples): + """""" """""" + for example in examples: + union = set() + for other in examples: + if other is not example: + union = union | (other[""subs_set""]) + example[""unique_subs_set""] = example[""subs_set""] - union + unique_count = len(example[""unique_subs_set""]) + color = None + if unique_count < 5: + color = ""yellow"" + if unique_count < 3: + color = ""red"" + vprint( + colored( + f""Clade {example['name']} has {len(example['subs_set'])} mutations, of which {unique_count} are unique."", + color, + ) + ) + + +def to_ranges(iterable): + """""" + Credits: @luca, https://stackoverflow.com/a/43091576 + """""" + iterable = sorted(set(iterable)) + for key, group in itertools.groupby(enumerate(iterable), lambda t: t[1] - t[0]): + group = list(group) + yield group[0][1], group[-1][1] + + +class ArgumentAdvancedDefaultsHelpFormatter(argparse.HelpFormatter): + """"""In contrast to ArgumentDefaultsHelpFormatter from argparse, + this formatter also shows 'const' values if they are present, and + adds blank lines between actions. + """""" + + def __init__(self, prog, indent_increment=2, max_help_position=24, width=None): + + global width_override + + if width_override: + width = width_override + + super().__init__(prog, indent_increment, max_help_position, width) + + def _get_help_string(self, action): + help = action.help + if ""%(default)"" not in action.help and not isinstance( + action, argparse._StoreConstAction + ): + if action.default is not argparse.SUPPRESS: + defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE] + if action.option_strings or action.nargs in defaulting_nargs: + if action.const: + help += "" (default without flag: %(default)s, default with flag: %(const)s)"" + else: + help += "" (default: %(default)s)"" + return help + + def _format_action(self, action): + return super()._format_action(action) + ""\n"" + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","sc2rf/postprocess.py",".py","55244","1455","#!/usr/bin/env python3 + +import pandas as pd +import click +import os +import logging +import requests +import sys +import time +from Bio import Phylo + +NO_DATA_CHAR = ""NA"" + +LAPIS_LINEAGE_COL = ""pangoLineage"" +LAPIS_OPEN_BASE = ( + ""https://lapis.cov-spectrum.org/open/v1/sample/aggregated"" + + ""?fields={lineage_col}"".format(lineage_col=LAPIS_LINEAGE_COL) + + ""&nucMutations={mutations}"" +) + +LAPIS_GISAID_BASE = ( + ""https://lapis.cov-spectrum.org/gisaid/v1/sample/aggregated"" + + ""?accessKey={access_key}"" + + ""&fields={lineage_col}"".format(lineage_col=LAPIS_LINEAGE_COL) + + ""&nucMutations={mutations}"" +) + +LINEAGE_PROP_THRESHOLD = 0.01 +LAPIS_SLEEP_TIME = 0 +# Consider a breakpoint match if within 50 base pairs +BREAKPOINT_APPROX_BP = 50 + +DATAFRAME_COLS = [ + ""sc2rf_status"", + ""sc2rf_details"", + ""sc2rf_lineage"", + ""sc2rf_clades_filter"", + ""sc2rf_regions_filter"", + ""sc2rf_regions_length"", + ""sc2rf_breakpoints_filter"", + ""sc2rf_num_breakpoints_filter"", + ""sc2rf_breakpoints_motif"", + ""sc2rf_unique_subs_filter"", + ""sc2rf_alleles_filter"", + ""sc2rf_intermission_allele_ratio"", + ""cov-spectrum_parents"", + ""cov-spectrum_parents_confidence"", + ""cov-spectrum_parents_subs"", + ""sc2rf_parents_conflict"", +] + + +def create_logger(logfile=None): + # create logger + logger = logging.getLogger() + logger.setLevel(logging.DEBUG) + + # create file handler which logs even debug messages + if logfile: + handler = logging.FileHandler(logfile) + else: + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.DEBUG) + logger.addHandler(handler) + return logger + + +def reverse_iter_collapse( + regions, + min_len, + max_breakpoint_len, + start_coord, + end_coord, + clade, +): + """"""Collapse adjacent regions from the same parent into one region."""""" + + coord_list = list(regions.keys()) + coord_list.reverse() + + for coord in coord_list: + prev_start_coord = coord + prev_end_coord = regions[prev_start_coord][""end""] + prev_region_len = (prev_end_coord - prev_start_coord) + 1 + prev_clade = regions[coord][""clade""] + breakpoint_len = start_coord - prev_end_coord + + # If the previous region was too short AND from a different clade + # Delete that previous region, it's an intermission + if prev_region_len < min_len and clade != prev_clade: + del regions[prev_start_coord] + + # If the previous breakpoint was too long AND from a different clade + # Don't add the current region + elif ( + start_coord != prev_start_coord + and clade != prev_clade + and (max_breakpoint_len != -1 and breakpoint_len > max_breakpoint_len) + ): + break + + # Collapse the current region into the previous one + elif clade == prev_clade: + regions[prev_start_coord][""end""] = end_coord + break + + # Otherwise, clades differ and this is the start of a new region + else: + regions[start_coord] = {""clade"": clade, ""end"": end_coord} + break + + # Check if the reveres iter collapse wound up deleting all the regions + if len(regions) == 0: + regions[start_coord] = {""clade"": clade, ""end"": end_coord} + + +@click.command() +@click.option( + ""--csv"", + help=""CSV output from sc2rf, multiple files separate by commas."", + required=True, +) +@click.option( + ""--ansi"", + help=""ANSI output from sc2rf, multiple files separate by commas."", + required=False, +) +@click.option(""--motifs"", help=""TSV of breakpoint motifs"", required=False) +@click.option( + ""--prefix"", + help=""Prefix for output files."", + required=False, + default=""sc2rf.recombinants"", +) +@click.option( + ""--min-len"", + help=""Minimum region length (-1 to disable filter)."", + required=False, + default=-1, +) +@click.option( + ""--min-consec-allele"", + help=""Minimum number of consecutive alleles in a region (-1 to disable filter)."", + required=False, + default=-1, +) +@click.option( + ""--max-breakpoint-len"", + help=""Maximum breakpoint length (-1 to disable filter)."", + required=False, + default=-1, +) +@click.option( + ""--max-parents"", + help=""Maximum number of parents (-1 to disable filter)."", + required=False, + default=-1, +) +@click.option(""--outdir"", help=""Output directory"", required=False, default=""."") +@click.option( + ""--aligned"", + help=""Extract recombinants from this alignment (Note: requires seqkit)"", + required=False, +) +@click.option( + ""--nextclade"", + help=""Nextclade TSV output from the sars-cov-2."", + required=False, +) +@click.option( + ""--nextclade-no-recomb"", + help=""Nextclade TSV output from the sars-cov-2-no-recomb dataset."", + required=False, +) +@click.option( + ""--nextclade-auto-pass"", + help=""CSV list of lineage assignments that will be called positive"", + required=False, +) +@click.option( + ""--max-breakpoints"", + help=""The maximum number of breakpoints (-1 to disable breakpoint filtering)"", + required=False, + default=-1, +) +@click.option( + ""--lapis"", + help=""Enable the LAPIS API to identify parental lineages from covSPECTRUM."", + is_flag=True, + required=False, + default=False, +) +@click.option( + ""--gisaid-access-key"", + help=""The accessKey to query GISAID data with LAPIS"", + required=False, +) +@click.option( + ""--issues"", + help=""Issues TSV metadata from pango-designation"", + required=False, +) +@click.option( + ""--lineage-tree"", + help=""Newick tree of pangolin lineage hierarchies"", + required=False, +) +@click.option( + ""--metadata"", + help=""Sample metadata TSV, used to include negative samples in the final output."", + required=False, +) +@click.option(""--log"", help=""Path to a log file"", required=False) +@click.option( + ""--dup-method"", + help=( + ""Method for resolving duplicate results:\n"" + + ""\nfirst: Use first positive results found.\n"" + + ""\nlast: Use last positive results found.\n"" + + ""\nmin_bp: Use fewest breakpoints."" + + ""\nmin_uncertainty: Use small breakpoint intervals."" + ), + type=click.Choice( + [""first"", ""last"", ""min_bp"", ""min_uncertainty""], + case_sensitive=False, + ), + required=False, + default=""lineage"", +) +def main( + csv, + ansi, + prefix, + min_len, + min_consec_allele, + max_breakpoint_len, + outdir, + aligned, + nextclade, + nextclade_auto_pass, + nextclade_no_recomb, + max_parents, + issues, + max_breakpoints, + motifs, + log, + lineage_tree, + metadata, + dup_method, + lapis, + gisaid_access_key, +): + """"""Detect recombinant seqences from sc2rf. Dependencies: pandas, click"""""" + + # Check for directory + if not os.path.exists(outdir): + os.mkdir(outdir) + + # create logger + logger = create_logger(logfile=log) + + # ----------------------------------------------------------------------------- + # Import Optional Data Files + + # (Optional) issues.tsv of pango-designation issues + # lineage assignment by parent+breakpoint matching + if issues: + + logger.info(""Parsing issues: {}"".format(issues)) + + breakpoint_col = ""breakpoints_curated"" + parents_col = ""parents_curated"" + breakpoint_df = pd.read_csv(issues, sep=""\t"") + breakpoint_df.fillna(NO_DATA_CHAR, inplace=True) + drop_rows = breakpoint_df[breakpoint_df[breakpoint_col] == NO_DATA_CHAR].index + breakpoint_df.drop(drop_rows, inplace=True) + + # Convert CSV to lists + breakpoint_df[breakpoint_col] = [ + bp.split("","") for bp in breakpoint_df[breakpoint_col] + ] + breakpoint_df[parents_col] = [p.split("","") for p in breakpoint_df[parents_col]] + + # (Optional) motifs dataframe + if motifs: + logger.info(""Parsing motifs: {}"".format(motifs)) + motifs_df = pd.read_csv(motifs, sep=""\t"") + + # (Optional) nextclade tsv dataframe + if nextclade: + logger.info(""Parsing nextclade: {}"".format(nextclade)) + nextclade_df = pd.read_csv(nextclade, sep=""\t"") + nextclade_df[""seqName""] = [str(s) for s in nextclade_df[""seqName""]] + nextclade_df.set_index(""seqName"", inplace=True) + nextclade_df.fillna(NO_DATA_CHAR, inplace=True) + + if nextclade_auto_pass: + nextclade_auto_pass_lineages = nextclade_auto_pass.split("","") + # Identify samples to autopass + auto_pass_df = nextclade_df[ + (nextclade_df[""Nextclade_pango""] != NO_DATA_CHAR) + & (nextclade_df[""Nextclade_pango""].isin(nextclade_auto_pass_lineages)) + ] + + # (Optional) nextclade tsv dataframe no-recomb dataset + if nextclade_no_recomb: + logger.info( + ""Parsing nextclade no-recomb output: {}"".format(nextclade_no_recomb) + ) + nextclade_no_recomb_df = pd.read_csv(nextclade_no_recomb, sep=""\t"") + nextclade_no_recomb_df[""seqName""] = [ + str(s) for s in nextclade_no_recomb_df[""seqName""] + ] + nextclade_no_recomb_df.set_index(""seqName"", inplace=True) + nextclade_no_recomb_df.fillna(NO_DATA_CHAR, inplace=True) + + # (Optional) metadata tsv dataframe to find negatives missing from sc2rf + if metadata: + logger.info(""Parsing metadata tsv: {}"".format(metadata)) + metadata_df = pd.read_csv(metadata, sep=""\t"") + metadata_df[""strain""] = [str(s) for s in metadata_df[""strain""]] + metadata_df.fillna(NO_DATA_CHAR, inplace=True) + + # (Optional) phylogenetic tree of pangolineage lineages + if lineage_tree: + logger.info(""Parsing lineage tree: {}"".format(lineage_tree)) + tree = Phylo.read(lineage_tree, ""newick"") + + # ----------------------------------------------------------------------------- + # Import Dataframes of Potential Positive Recombinants + + # note: Add the end of this section, only positives and false positives will + # be in the dataframe. + + # sc2rf csv output (required) + df = pd.DataFrame() + csv_split = csv.split("","") + # Store a dict of duplicate strains + duplicate_strains = {} + + for csv_file in csv_split: + logger.info(""Parsing csv: {}"".format(csv_file)) + + try: + temp_df = pd.read_csv(csv_file, sep="","") + except pd.errors.EmptyDataError: + logger.warning(""No records in csv: {}"".format(csv_file)) + temp_df = pd.DataFrame() + + # Add column to indicate which csv file results come from (debugging) + temp_df.insert( + loc=len(temp_df.columns), + column=""csv_file"", + value=os.path.basename(csv_file), + ) + + # Convert to str type + temp_df[""sample""] = [str(s) for s in temp_df[""sample""]] + temp_df.set_index(""sample"", inplace=True) + + # Add column to hold original strain name before marking duplicates + temp_df.insert( + loc=len(temp_df.columns), + column=""strain"", + value=temp_df.index, + ) + + # If the df has no records, this is the first csv + if len(df) == 0: + df = temp_df + else: + # Keep all dups for now, only retain best results at end + for strain in temp_df.index: + if strain in list(df[""strain""]): + if strain not in duplicate_strains: + duplicate_strains[strain] = 1 + + # add suffix ""_dup"", remove at the end of scripts + dup_1 = strain + ""_dup{}"".format(duplicate_strains[strain]) + df.rename(index={strain: dup_1}, inplace=True) + + duplicate_strains[strain] += 1 + + dup_2 = strain + ""_dup{}"".format(duplicate_strains[strain]) + temp_df.rename(index={strain: dup_2}, inplace=True) + + # Combine primary and secondary data frames + df = pd.concat([df, temp_df]) + + df.fillna("""", inplace=True) + + # ------------------------------------------------------------------------- + # Initialize new stat columns to NA + + # note: Add the end of this section, only positives and false positives will + # be in the sc2rf_details_dict + + for col in DATAFRAME_COLS: + df[col] = [NO_DATA_CHAR] * len(df) + + # Initialize a dictionary of sc2rf details and false positives + # key: strain, value: list of reasons + false_positives_dict = {} + sc2rf_details_dict = {strain: [] for strain in df.index} + + # ------------------------------------------------------------------------- + # Add in the Negatives (if metadata was specified) + # Avoiding the Bio module, I just need names not sequences + + if metadata: + + logger.info(""Reporting non-recombinants in metadata as negatives"") + for strain in list(metadata_df[""strain""]): + # Ignore this strain if it's already in dataframe (it's a recombinant) + if strain in list(df[""strain""]): + continue + # Otherwise add it, with no data as default + df.loc[strain] = NO_DATA_CHAR + df.at[strain, ""strain""] = strain + df.at[strain, ""sc2rf_status""] = ""negative"" + sc2rf_details_dict[strain] = [] + + # --------------------------------------------------------------------- + # Auto-pass lineages from nextclade assignment, that were also detected by sc2rf + + if nextclade and nextclade_auto_pass: + + logger.info( + ""Auto-passing lineages: {}"".format("","".join(nextclade_auto_pass_lineages)) + ) + + for rec in auto_pass_df.iterrows(): + + # Note the strain is the true strain, not _dup suffix + strain = rec[0] + + lineage = auto_pass_df.loc[strain][""Nextclade_pango""] + details = ""nextclade-auto-pass {}"".format(lineage) + + # Case 1 : In df with NO DUPS, set the status to positive, update details + if strain in list(df.index): + + sc2rf_details_dict[strain].append(details) + df.at[strain, ""sc2rf_status""] = ""positive"" + df.at[strain, ""sc2rf_details""] = "";"".join(sc2rf_details_dict[strain]) + + # Case 2: In df WITH DUPS, set the dups status to positive, update details + elif strain in list(df[""strain""]): + + dup_strains = list(df[df[""strain""] == strain].index) + for dup in dup_strains: + + sc2rf_details_dict[dup].append(details) + df.at[dup, ""sc2rf_status""] = ""positive"" + df.at[dup, ""sc2rf_details""] = "";"".join(sc2rf_details_dict[dup]) + + # Case 3: If it's not in the dataframe add it + else: + sc2rf_details_dict[strain] = [details] + + # new row + row_dict = {col: [NO_DATA_CHAR] for col in df.columns} + row_dict[""strain""] = strain + row_dict[""sc2rf_status""] = ""positive"" + row_dict[""sc2rf_details""] = "";"".join(sc2rf_details_dict[strain]) + + row_df = pd.DataFrame(row_dict).set_index(""strain"") + df = pd.concat([df, row_df], ignore_index=False) + + # ------------------------------------------------------------------------- + # Begin Post-Processing + logger.info(""Post-processing table"") + + # Iterate through all positive and negative recombinantions + for rec in df.iterrows(): + + # Skip over negative recombinants + if rec[1][""sc2rf_status""] == ""negative"": + continue + + strain = rec[0] + + # Check if this strain was auto-passed + strain_auto_pass = False + for detail in sc2rf_details_dict[strain]: + if ""auto-pass"" in detail: + strain_auto_pass = True + + regions_str = rec[1][""regions""] + regions_split = regions_str.split("","") + + alleles_str = rec[1][""alleles""] + alleles_split = alleles_str.split("","") + + unique_subs_str = rec[1][""unique_subs""] + unique_subs_split = unique_subs_str.split("","") + + # Keys are going to be the start coord of the region + regions_filter = {} + unique_subs_filter = [] + alleles_filter = [] + breakpoints_filter = [] + + # Store alleles for filtering + intermission_alleles = [] + alleles_by_parent = {} + + prev_clade = None + prev_start_coord = 0 + prev_end_coord = 0 + + # --------------------------------------------------------------------- + # FIRST PASS + + # If the region is NA, this is an auto-passed recombinant + # and sc2rf couldn't find any breakpoints, skip the rest of processing + # and continue on to next strain + + if regions_split == [NO_DATA_CHAR]: + continue + + for region in regions_split: + + coords = region.split(""|"")[0] + clade = region.split(""|"")[1] + start_coord = int(coords.split("":"")[0]) + end_coord = int(coords.split("":"")[1]) + region_len = (end_coord - start_coord) + 1 + coord_list = list(regions_filter) + coord_list.reverse() + + # Just ignore singletons, no calculation necessary + if region_len == 1: + continue + + # Is this the first region? + if not prev_clade: + regions_filter[start_coord] = {""clade"": clade, ""end"": end_coord} + prev_clade = clade + prev_start_coord = start_coord + + # Moving 3' to 5', collapse adjacent regions from the same parent + # Modifies regions in place + reverse_iter_collapse( + regions=regions_filter, + min_len=min_len, + max_breakpoint_len=max_breakpoint_len, + start_coord=start_coord, + end_coord=end_coord, + clade=clade, + ) + + # These get updated regardless of condition + prev_clade = clade + prev_end_coord = end_coord + + # Check the last region for length + if len(regions_filter) > 1: + start_coord = list(regions_filter)[-1] + end_coord = regions_filter[start_coord][""end""] + region_len = end_coord - start_coord + if region_len < min_len: + del regions_filter[start_coord] + + # ----------------------------------------------------------------- + # SECOND PASS: UNIQUE SUBSTITUTIONS + + regions_filter_collapse = {} + + for start_coord in list(regions_filter): + clade = regions_filter[start_coord][""clade""] + end_coord = regions_filter[start_coord][""end""] + + region_contains_unique_sub = False + + for sub in unique_subs_split: + + sub_coord = int(sub.split(""|"")[0]) + sub_parent = sub.split(""|"")[1] + + if ( + sub_coord >= start_coord + and sub_coord <= end_coord + and sub_parent == clade + ): + region_contains_unique_sub = True + unique_subs_filter.append(sub) + + # If it contains a unique sub, check if we should + # collapse into previous parental region + if region_contains_unique_sub: + reverse_iter_collapse( + regions=regions_filter_collapse, + min_len=min_len, + max_breakpoint_len=max_breakpoint_len, + start_coord=start_coord, + end_coord=end_coord, + clade=clade, + ) + + regions_filter = regions_filter_collapse + + # ----------------------------------------------------------------- + # THIRD PASS: CONSECUTIVE ALLELES + + regions_filter_collapse = {} + + for start_coord in list(regions_filter): + clade = regions_filter[start_coord][""clade""] + end_coord = regions_filter[start_coord][""end""] + + num_consec_allele = 0 + + for allele in alleles_split: + + allele_coord = int(allele.split(""|"")[0]) + allele_parent = allele.split(""|"")[1] + + if ( + allele_coord >= start_coord + and allele_coord <= end_coord + and allele_parent == clade + ): + num_consec_allele += 1 + alleles_filter.append(allele) + + # If there are sufficient consecutive alleles, check if we should + # collapse into previous parental region + if num_consec_allele >= min_consec_allele: + reverse_iter_collapse( + regions=regions_filter_collapse, + min_len=min_len, + max_breakpoint_len=max_breakpoint_len, + start_coord=start_coord, + end_coord=end_coord, + clade=clade, + ) + + regions_filter = regions_filter_collapse + + # ----------------------------------------------------------------- + # Check if all the regions were collapsed + if len(regions_filter) < 2: + sc2rf_details_dict[strain].append(""single parent"") + # if this is an auto-pass lineage, don't add to false positives + if not strain_auto_pass: + false_positives_dict[strain] = """" + + # ----------------------------------------------------------------- + # FOURTH PASS: BREAKPOINT DETECTION + + prev_start_coord = None + for start_coord in regions_filter: + + end_coord = regions_filter[start_coord][""end""] + + # Skip the first record for breakpoints + if prev_start_coord: + breakpoint_start = prev_end_coord + 1 + breakpoint_end = start_coord - 1 + breakpoint = ""{}:{}"".format(breakpoint_start, breakpoint_end) + breakpoints_filter.append(breakpoint) + + prev_start_coord = start_coord + prev_end_coord = end_coord + + # check if the number of breakpoints changed + # the filtered breakpoints should only ever be equal or less + # 2022-06-17: Why? Under what conditions does the filtered breakpoints increase? + # Except! If the breakpoints were initially 0 + # num_breakpoints = df[""breakpoints""][strain] + num_breakpoints_filter = len(breakpoints_filter) + + # Check for too many breakpoints + if max_breakpoints != -1: + if num_breakpoints_filter > max_breakpoints: + details = ""{} breakpoints > {} max breakpoints"".format( + num_breakpoints_filter, + max_breakpoints, + ) + sc2rf_details_dict[strain].append(details) + # if this is an auto-pass lineage, don't add to false positives + if not strain_auto_pass: + false_positives_dict[strain] = """" + + # Identify the new filtered clades + clades_filter = [regions_filter[s][""clade""] for s in regions_filter] + # clades_filter_csv = "","".join(clades_filter) + num_parents = len(set(clades_filter)) + if max_parents != -1: + if num_parents > max_parents: + details = ""{} parents > {}"".format(num_parents, max_parents) + sc2rf_details_dict[strain].append(details) + # if this is an auto-pass lineage, don't add to false positives + if not strain_auto_pass: + false_positives_dict[strain] = """" + + # --------------------------------------------------------------------- + # Intermission/Minor Parent Allele Ratio + # ie. alleles that conflict with the parental region + # be lenient if there were more parents initially reported by sc2rf (ex. >2) + # because this wil lead to large numbers of unresolved intermissions + + original_parents = rec[1][""examples""] + num_original_parents = len(original_parents.split("","")) + + if num_original_parents > num_parents: + intermission_allele_ratio = ""NA"" + else: + for start_coord in regions_filter: + end_coord = regions_filter[start_coord][""end""] + clade = regions_filter[start_coord][""clade""] + + for allele in alleles_split: + + allele_coord = int(allele.split(""|"")[0]) + allele_clade = allele.split(""|"")[1] + allele_nuc = allele.split(""|"")[2] + + # Skip if this allele is not found in the current region + if allele_coord < start_coord or allele_coord > end_coord: + continue + + # Skip missing data + if allele_nuc == ""N"": + continue + + # Check if this allele's origins conflicts with the parental region + if allele_clade != clade: + intermission_alleles.append(allele) + else: + if clade not in alleles_by_parent: + alleles_by_parent[clade] = [] + alleles_by_parent[clade].append(allele) + + # Add in alleles that were not assigned to any region + for allele in alleles_split: + allele_nuc = allele.split(""|"")[2] + # Skip missing data + if allele_nuc == ""N"": + continue + + allele_coord = int(allele.split(""|"")[0]) + allele_in_region = False + for start_coord in regions_filter: + end_coord = regions_filter[start_coord][""end""] + if allele_coord >= start_coord and allele_coord <= end_coord: + allele_in_region = True + + # Alleles not assigned to any region are counted as intermissions + if not allele_in_region: + intermission_alleles.append(allele) + + # Identify the ""minor"" parent (least number of alleles) + # minor_parent = None + minor_num_alleles = len(alleles_split) + + for parent in alleles_by_parent: + num_alleles = len(alleles_by_parent[parent]) + if num_alleles <= minor_num_alleles: + # minor_parent = parent + minor_num_alleles = num_alleles + + intermission_allele_ratio = len(intermission_alleles) / minor_num_alleles + + # When the ratio is above 1, that means there are more intermission than + # minor parent alleles. But don't override the false_positive status + # if this strain was already flagged as a false_positive previously + if intermission_allele_ratio >= 1: + sc2rf_details_dict[strain].append(""intermission_allele_ratio >= 1"") + # if this is an auto-pass lineage, don't add to false positives + if not strain_auto_pass: + false_positives_dict[strain] = """" + + # -------------------------------------------------------------------------- + # Extract the lengths of each region + regions_length = [str(regions_filter[s][""end""] - s) for s in regions_filter] + + # Construct the new filtered regions + regions_filter = [ + ""{}:{}|{}"".format(s, regions_filter[s][""end""], regions_filter[s][""clade""]) + for s in regions_filter + ] + + # -------------------------------------------------------------------------- + # Identify lineage based on breakpoint and parents! + # But only if we've suppled the issues.tsv for pango-designation + if issues: + sc2rf_lineage = """" + sc2rf_lineages = {bp_s: [] for bp_s in breakpoints_filter} + + for bp_s in breakpoints_filter: + start_s = int(bp_s.split("":"")[0]) + end_s = int(bp_s.split("":"")[1]) + + match_found = False + + for bp_rec in breakpoint_df.iterrows(): + + # Skip over this potential lineage if parents are wrong + bp_parents = bp_rec[1][parents_col] + if bp_parents != clades_filter: + continue + + for bp_i in bp_rec[1][breakpoint_col]: + + start_i = int(bp_i.split("":"")[0]) + end_i = int(bp_i.split("":"")[1]) + start_diff = abs(start_s - start_i) + end_diff = abs(end_s - end_i) + + if ( + start_diff <= BREAKPOINT_APPROX_BP + and end_diff <= BREAKPOINT_APPROX_BP + ): + + sc2rf_lineages[bp_s].append(bp_rec[1][""lineage""]) + match_found = True + + if not match_found: + sc2rf_lineages[bp_s].append(NO_DATA_CHAR) + + # if len(sc2rf_lineages) == num_breakpoints_filter: + collapse_lineages = [] + for bp in sc2rf_lineages.values(): + for lineage in bp: + collapse_lineages.append(lineage) + + collapse_lineages = list(set(collapse_lineages)) + + # When there are multiple breakpoint, a match must be the same for all! + collapse_lineages_filter = [] + for lin in collapse_lineages: + + if lin == NO_DATA_CHAR: + continue + # By default, assume they all match + matches_all_bp = True + for bp_s in sc2rf_lineages: + # If the lineage is missing, it's not in all bp + if lin not in sc2rf_lineages[bp_s]: + matches_all_bp = False + break + + # Check if we should drop it + if matches_all_bp: + collapse_lineages_filter.append(lin) + + if len(collapse_lineages_filter) == 0: + collapse_lineages_filter = [NO_DATA_CHAR] + + sc2rf_lineage = "","".join(collapse_lineages_filter) + df.at[strain, ""sc2rf_lineage""] = sc2rf_lineage + + # check for breakpoint motifs, to override lineage call + # all breakpoints must include a motif! + # --------------------------------------------------------------------- + if motifs: + breakpoints_motifs = [] + for bp in breakpoints_filter: + bp_motif = False + bp_start = int(bp.split("":"")[0]) + bp_end = int(bp.split("":"")[1]) + + # Add buffers + bp_start = bp_start - BREAKPOINT_APPROX_BP + bp_end = bp_end + BREAKPOINT_APPROX_BP + + for motif_rec in motifs_df.iterrows(): + motif_start = motif_rec[1][""start""] + motif_end = motif_rec[1][""end""] + + # Is motif contained within the breakpoint + # Allow fuzzy matching + if motif_start >= bp_start and motif_end <= bp_end: + # print(""\t\t"", motif_start, motif_end) + bp_motif = True + + breakpoints_motifs.append(bp_motif) + + # If there's a lone ""False"" value, it gets re-coded to an + # empty string on export. To prevent that, force it to be + # the NO_DATA_CHAR (ex. 'NA') + if len(breakpoints_motifs) == 0: + breakpoints_motifs_str = [NO_DATA_CHAR] + else: + breakpoints_motifs_str = [str(m) for m in breakpoints_motifs] + + df.at[strain, ""sc2rf_breakpoints_motif""] = "","".join(breakpoints_motifs_str) + + # Override the linaege call if one breakpoint had no motif + if False in breakpoints_motifs: + sc2rf_details_dict[strain].append(""missing breakpoint motif"") + # if this is an auto-pass lineage, don't add to false positives + if not strain_auto_pass: + false_positives_dict[strain] = """" + + df.at[strain, ""sc2rf_clades_filter""] = "","".join(clades_filter) + df.at[strain, ""sc2rf_regions_filter""] = "","".join(regions_filter) + df.at[strain, ""sc2rf_regions_length""] = "","".join(regions_length) + df.at[strain, ""sc2rf_breakpoints_filter""] = "","".join(breakpoints_filter) + df.at[strain, ""sc2rf_num_breakpoints_filter""] = num_breakpoints_filter + df.at[strain, ""sc2rf_unique_subs_filter""] = "","".join(unique_subs_filter) + df.at[strain, ""sc2rf_alleles_filter""] = "","".join(alleles_filter) + df.at[strain, ""sc2rf_intermission_allele_ratio""] = intermission_allele_ratio + + if strain not in false_positives_dict: + df.at[strain, ""sc2rf_status""] = ""positive"" + # A sample can be positive with no breakpoints, if auto-pass + if len(breakpoints_filter) != 0: + sc2rf_details_dict[strain] = [""recombination detected""] + # For auto-pass negatives, update the csv_file + else: + df.at[strain, ""csv_file""] = NO_DATA_CHAR + else: + df.at[strain, ""sc2rf_status""] = ""false_positive"" + + df.at[strain, ""sc2rf_details""] = "";"".join(sc2rf_details_dict[strain]) + + # --------------------------------------------------------------------- + # Resolve strains with duplicate results + + logger.info(""Reconciling duplicate results with method: {}"".format(dup_method)) + for strain in duplicate_strains: + + # Check if this strain was auto-passed + strain_auto_pass = True if strain in auto_pass_df.index else False + strain_df = df[df[""strain""] == strain] + strain_bp = list(set(strain_df[""sc2rf_breakpoints_filter""])) + + num_dups = duplicate_strains[strain] + # Which duplicates should we keep (1), which should we remove (many) + keep_dups = [] + remove_dups = [] + + for i in range(1, num_dups + 1): + dup_strain = strain + ""_dup{}"".format(i) + dup_status = df[""sc2rf_status""][dup_strain] + + if dup_status == ""positive"": + keep_dups.append(dup_strain) + else: + remove_dups.append(dup_strain) + + # Case 1. No keep dups were found, retain first removal dup, remove all else + if len(keep_dups) == 0: + keep_strain = remove_dups[0] + keep_dups.append(keep_strain) + remove_dups.remove(keep_strain) + + # Case 2. Multiple keeps found, but it's an auto-pass and they're all negative + # Just take the first csv + elif strain_auto_pass and strain_bp == [""""]: + remove_dups += keep_dups[1:] + keep_dups = [keep_dups[0]] + + # Case 3. Multiple keeps found, use dup_method + elif len(keep_dups) > 1: + + # First try to match to a published lineage + # Key = dup_strain, value = csv of lineages + lineage_strains = {} + + for dup_strain in keep_dups: + dup_lineage = df[""sc2rf_lineage""][dup_strain] + + if dup_lineage != NO_DATA_CHAR: + lineage_strains[dup_strain] = dup_lineage + + lineage_strains_matches = list(set(lineage_strains.values())) + + # Check if a match was found, but not more than 1 candidate lineage + if len(lineage_strains) > 0 and len(lineage_strains_matches) < 2: + keep_strain = list(lineage_strains)[0] + # Remove all strains except the min one + remove_dups = keep_dups + remove_dups + remove_dups.remove(keep_strain) + keep_dups = [keep_strain] + + # Otherwise, use a duplicate resolving method + elif dup_method == ""first"": + remove_dups += keep_dups[1:] + keep_dups = [keep_dups[0]] + + elif dup_method == ""last"": + remove_dups += keep_dups[0:-1] + keep_dups = [keep_dups[-1]] + + elif dup_method == ""min_bp"": + min_bp = None + min_bp_strain = None + for dup_strain in keep_dups: + num_bp = df[""sc2rf_num_breakpoints_filter""][dup_strain] + if not min_bp: + min_bp = num_bp + min_bp_strain = dup_strain + elif num_bp < min_bp: + min_bp = num_bp + min_bp_strain = dup_strain + # Remove all strains except the min one + remove_dups = keep_dups + remove_dups + remove_dups.remove(min_bp_strain) + keep_dups = [min_bp_strain] + + elif dup_method == ""min_uncertainty"": + + min_uncertainty = None + min_uncertainty_strain = None + + for dup_strain in keep_dups: + + # '8394:12879,13758:22000' + bp = df[""sc2rf_breakpoints_filter""][dup_strain] + # ['8394:12879','13758:22000'] + # Skip if this is an auto-pass lineage with no breakpoints + if bp == """": + continue + bp = bp.split("","") + # [4485, 8242] + bp = [int(c.split("":"")[1]) - int(c.split("":"")[0]) for c in bp] + bp_uncertainty = sum(bp) + + # Set to the first strain by default + if not min_uncertainty: + min_uncertainty_strain = dup_strain + min_uncertainty = bp_uncertainty + elif bp_uncertainty < min_uncertainty: + min_uncertainty_strain = dup_strain + min_uncertainty = bp_uncertainty + + # Remove all strains except the min one + remove_dups = keep_dups + remove_dups + remove_dups.remove(min_uncertainty_strain) + keep_dups = [min_uncertainty_strain] + + # If this is an auto-pass negative, indicate no csvfile was used + if strain_bp == [""""]: + keep_csv_file = NO_DATA_CHAR + else: + keep_csv_file = df[""csv_file""][keep_dups[0]] + logger.info( + ""Reconciling duplicate results for {}, retaining output from: {}"".format( + strain, keep_csv_file + ) + ) + # Rename the accepted duplicate + df.rename(index={keep_dups[0]: strain}, inplace=True) + # Drop the rejected duplicates + df.drop(labels=remove_dups, inplace=True) + + # --------------------------------------------------------------------- + # Fix up duplicate strain names in false_positives + + false_positives_filter = {} + for strain in false_positives_dict: + + strain_orig = strain.split(""_dup"")[0] + status = df[""sc2rf_status""][strain_orig] + # If the original strain isn't positive + # All duplicates were false positives and should be removed + if status != ""positive"": + false_positives_filter[strain_orig] = false_positives_dict[strain] + sc2rf_details_dict[strain_orig] = sc2rf_details_dict[strain] + + false_positives_dict = false_positives_filter + + # --------------------------------------------------------------------- + # Identify parent lineages by querying cov-spectrum mutations + + # We can only do this if: + # 1. A nextclade no-recomb tsv file was specified with mutations + # 2. Multiple regions were detected (not collapsed down to one parent region) + # 3. The lapis API was enabled (--lapis) + + if nextclade_no_recomb and lapis: + + logger.info( + ""Identifying parent lineages based on nextclade no-recomb substitutions"" + ) + + # Check if we're using open data or GISAID + if gisaid_access_key: + lapis_url_base = LAPIS_GISAID_BASE.format( + access_key=gisaid_access_key, mutations=""{mutations}"" + ) + else: + lapis_url_base = LAPIS_OPEN_BASE + + positive_df = df[df[""sc2rf_status""] == ""positive""] + total_positives = len(positive_df) + progress_i = 0 + + # keys = query, value = json + query_subs_dict = {} + + for rec in positive_df.iterrows(): + + strain = rec[0] + strain_bp = rec[1][""sc2rf_breakpoints_filter""] + + # If this was an auto-pass negative strain, no regions for us to query + if strain_bp == NO_DATA_CHAR: + continue + + parent_clades = rec[1][""sc2rf_clades_filter""].split("","") + + progress_i += 1 + logger.info(""{} / {}: {}"".format(progress_i, total_positives, strain)) + + regions_filter = positive_df[""sc2rf_regions_filter""][strain].split("","") + + parent_lineages = [] + parent_lineages_confidence = [] + parent_lineages_subs = [] + + substitutions = nextclade_no_recomb_df[""substitutions""][strain].split("","") + unlabeled_privates = nextclade_no_recomb_df[ + ""privateNucMutations.unlabeledSubstitutions"" + ][strain].split("","") + + # Remove NA char + if NO_DATA_CHAR in substitutions: + substitutions.remove(NO_DATA_CHAR) + if NO_DATA_CHAR in unlabeled_privates: + unlabeled_privates.remove(NO_DATA_CHAR) + + # Exclude privates from mutations to query + for private in unlabeled_privates: + # Might not be in there if it's an indel + if private in substitutions: + substitutions.remove(private) + + # Split mutations by region + for region, parent_clade in zip(regions_filter, parent_clades): + + # If the parental clade is a recombinant, we'll allow the covlineages + # to be recombinants + parent_clade_is_recombinant = False + for label in parent_clade.split(""/""): + if label.startswith(""X""): + parent_clade_is_recombinant = True + + region_coords = region.split(""|"")[0] + region_start = int(region_coords.split("":"")[0]) + region_end = int(region_coords.split("":"")[1]) + region_subs = [] + + for sub in substitutions: + sub_coord = int(sub[1:-1]) + if sub_coord >= region_start and sub_coord <= region_end: + region_subs.append(sub) + + region_subs_csv = "","".join(region_subs) + + # Check if we already fetched this subs combo + if region_subs_csv in query_subs_dict: + logger.info(""\tUsing cache for region {}"".format(region_coords)) + lineage_data = query_subs_dict[region_subs_csv] + # Otherwise, query cov-spectrum for these subs + else: + query_subs_dict[region_subs_csv] = """" + url = lapis_url_base.format(mutations=region_subs_csv) + logger.info( + ""Querying cov-spectrum for region {}"".format(region_coords) + ) + r = requests.get(url) + # Sleep after fetching + time.sleep(LAPIS_SLEEP_TIME) + result = r.json() + lineage_data = result[""data""] + query_subs_dict[region_subs_csv] = lineage_data + + # Have keys be counts + lineage_dict = {} + + for rec in lineage_data: + lineage = rec[LAPIS_LINEAGE_COL] + + # Ignore None lineages + if not lineage: + continue + + # If parent clade is not a recombinant, don't include + # recombinant lineages in final dict and count + if lineage.startswith(""X"") and not parent_clade_is_recombinant: + continue + + count = rec[""count""] + lineage_dict[count] = lineage + + # Sort in order + lineage_dict = { + k: lineage_dict[k] for k in sorted(lineage_dict, reverse=True) + } + + # If no matches were found, report NA for lineage + if len(lineage_dict) == 0: + max_lineage = NO_DATA_CHAR + max_prop = NO_DATA_CHAR + else: + # Temporarily set to fake data + total_count = sum(lineage_dict.keys()) + max_count = max(lineage_dict.keys()) + max_prop = max_count / total_count + max_lineage = lineage_dict[max_count] + + # Don't want to report recombinants as parents + # UNLESS, the parental clade is a recombinant (ex. XBB) + while ( + max_lineage is None + or max_lineage.startswith(""X"") + or max_lineage == ""Unassigned"" + ): + + # Allow the max_lineage to be recombinant if clade is also + if max_lineage.startswith(""X"") and parent_clade_is_recombinant: + break + lineage_dict = { + count: lineage + for count, lineage in lineage_dict.items() + if lineage != max_lineage + } + # If there are no other options, set to NA + if len(lineage_dict) == 0: + max_lineage = NO_DATA_CHAR + break + # Otherwise try again! + else: + # For now, deliberately don't update total_count + max_count = max(lineage_dict.keys()) + max_prop = max_count / total_count + max_lineage = lineage_dict[max_count] + + # If we ended with an empty dictionary, + # there were not usable lineages + if len(lineage_dict) == 0: + max_lineage = NO_DATA_CHAR + max_prop = NO_DATA_CHAR + + # Combine counts of sublineages into the max lineage total + # This requires the pangolin lineage tree! + if lineage_tree: + max_lineage_tree = [c for c in tree.find_clades(max_lineage)] + # Make sure we found this lineage in the tree + if len(max_lineage_tree) == 1: + max_lineage_tree = max_lineage_tree[0] + max_lineage_children = [ + c.name for c in max_lineage_tree.find_clades() + ] + + # Search for counts in the lapis data that + # descend from the max lineage + for count, lineage in lineage_dict.items(): + if ( + lineage in max_lineage_children + and lineage != max_lineage + ): + max_count += count + max_prop = max_count / total_count + + # Add a ""*"" suffix to the max lineage, to indicate + # this includes descendant counts + max_lineage = max_lineage + ""*"" + + parent_lineages_sub_str = ""{}|{}"".format(region_subs_csv, max_lineage) + + parent_lineages.append(max_lineage) + parent_lineages_confidence.append(max_prop) + parent_lineages_subs.append(parent_lineages_sub_str) + + # Update the dataframe columns + df.at[strain, ""cov-spectrum_parents""] = "","".join(parent_lineages) + df.at[strain, ""cov-spectrum_parents_confidence""] = "","".join( + str(round(c, 3)) if type(c) == float else NO_DATA_CHAR + for c in parent_lineages_confidence + ) + df.at[strain, ""cov-spectrum_parents_subs""] = "";"".join(parent_lineages_subs) + + # --------------------------------------------------------------------- + # Identify parent conflict + + if nextclade_no_recomb and lapis and lineage_tree: + + logger.info(""Identifying parental conflict between lineage and clade."") + + positive_df = df[df[""sc2rf_status""] == ""positive""] + + for rec in positive_df.iterrows(): + + strain = rec[0] + parent_clades = rec[1][""sc2rf_clades_filter""].split("","") + parent_lineages = rec[1][""cov-spectrum_parents""].split("","") + conflict = False + lineage_is_descendant = False + lineage_is_ancestor = False + + # Clade format can be: + # Lineage (BA.2.3.20) + # WHO_LABEL/Nextstrain clade (Delta/21J) + # WHO_LABEL/Lineage/Nextstrain clade (Omicron/BA.1/21K) + # WHO_LABEL/Lineage/Nextstrain clade (Omicron/XBB/22F) + # Lineage/Nextstrain clade (B.1.177/20E) + + for i, labels in enumerate(parent_clades): + parent = NO_DATA_CHAR + labels_split = labels.split(""/"") + for label in labels_split: + # Need to find the lineage which contains ""."" + if ""."" in label: + parent = label + # Or a recombinant, which doesn't have a ""."" + elif label.startswith(""X""): + parent = label + parent_clades[i] = parent + + for c, l in zip(parent_clades, parent_lineages): + + # We can't compare to NA + if c == NO_DATA_CHAR or l == NO_DATA_CHAR: + continue + # Remove the asterisk indicating all descendants + l = l.replace(""*"", """") + # If they are the same, there is no conflict, continue + if c == l: + continue + + # Check if parents_lineage is descendant of parents_clade + c_node = [c for c in tree.find_clades(c)][0] + l_node = [c for c in c_node.find_clades(l)] + if len(l_node) != 1: + lineage_is_descendant = True + + # Check if parents_lineage is ancestor of parents_clade + l_node = [c for c in tree.find_clades(l)][0] + c_node = [c for c in l_node.find_clades(c)] + if len(c_node) != 1: + lineage_is_ancestor = True + + if not lineage_is_descendant and not lineage_is_ancestor: + conflict = True + + df.at[strain, ""sc2rf_parents_conflict""] = conflict + + # --------------------------------------------------------------------- + # Write exclude strains (false positives) + + outpath_exclude = os.path.join(outdir, prefix + "".exclude.tsv"") + logger.info(""Writing strains to exclude: {}"".format(outpath_exclude)) + if len(false_positives_dict) > 0: + with open(outpath_exclude, ""w"") as outfile: + for strain in false_positives_dict: + details = "";"".join(sc2rf_details_dict[strain]) + outfile.write(strain + ""\t"" + details + ""\n"") + else: + cmd = ""touch {outpath}"".format(outpath=outpath_exclude) + os.system(cmd) + + # ------------------------------------------------------------------------- + # write output table + + # Drop old columns, if there were only negative samples, these columns don't exist + logger.info(""Formatting output columns."") + if set(df[""sc2rf_status""]) != set([""negative""]): + df.drop( + [ + ""examples"", + ""intermissions"", + ""breakpoints"", + ""regions"", + ""unique_subs"", + ""alleles"", + ], + axis=""columns"", + inplace=True, + ) + + # Move the strain column to the beginning + df.drop(columns=""strain"", inplace=True) + df.insert(loc=0, column=""strain"", value=df.index) + df.rename( + { + ""sc2rf_clades_filter"": ""sc2rf_parents"", + ""sc2rf_regions_filter"": ""sc2rf_regions"", + ""sc2rf_breakpoints_filter"": ""sc2rf_breakpoints"", + ""sc2rf_num_breakpoints_filter"": ""sc2rf_num_breakpoints"", + ""sc2rf_unique_subs_filter"": ""sc2rf_unique_subs"", + ""sc2rf_alleles_filter"": ""sc2rf_alleles"", + }, + axis=""columns"", + inplace=True, + ) + # Sort by status + df.sort_values(by=[""sc2rf_status"", ""sc2rf_lineage""], inplace=True, ascending=False) + outpath_rec = os.path.join(outdir, prefix + "".tsv"") + + logger.info(""Writing the output table: {}"".format(outpath_rec)) + df.to_csv(outpath_rec, sep=""\t"", index=False) + + # ------------------------------------------------------------------------- + # write output strains + outpath_strains = os.path.join(outdir, prefix + "".txt"") + strains_df = df[ + (df[""sc2rf_status""] != ""negative"") & (df[""sc2rf_status""] != ""false_positive"") + ] + strains = list(strains_df.index) + strains_txt = ""\n"".join(strains) + with open(outpath_strains, ""w"") as outfile: + outfile.write(strains_txt) + + # ------------------------------------------------------------------------- + # filter the ansi output + if ansi: + + ansi_split = ansi.split("","") + outpath_ansi = os.path.join(outdir, prefix + "".ansi.txt"") + + for i, ansi_file in enumerate(ansi_split): + logger.info(""Parsing ansi: {}"".format(ansi_file)) + if len(false_positives_dict) > 0: + cmd = ( + ""cut -f 1 "" + + ""{exclude} | grep -v -f - {inpath} {operator} {outpath}"".format( + exclude=outpath_exclude, + inpath=ansi_file, + operator="">"" if i == 0 else "">>"", + outpath=outpath_ansi, + ) + ) + else: + cmd = ""cat {inpath} {operator} {outpath}"".format( + inpath=ansi_file, + operator="">"" if i == 0 else "">>"", + outpath=outpath_ansi, + ) + logger.info(""Writing filtered ansi: {}"".format(outpath_ansi)) + # logger.info(cmd) + os.system(cmd) + + # ------------------------------------------------------------------------- + # write alignment + if aligned: + outpath_fasta = os.path.join(outdir, prefix + "".fasta"") + logger.info(""Writing filtered alignment: {}"".format(outpath_fasta)) + + cmd = ""seqkit grep -f {outpath_strains} {aligned} > {outpath_fasta};"".format( + outpath_strains=outpath_strains, + aligned=aligned, + outpath_fasta=outpath_fasta, + ) + os.system(cmd) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_Development.md",".md","14","2","# Development +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.5.1.md",".md","487","17","# v0.5.1 + +## Workflow + +- [Issue #169](https://github.com/ktmeaton/ncov-recombinant/issues/169): AttributeError: 'str' object has no attribute 'name' + +## Resources + +- [Issue #167](https://github.com/ktmeaton/ncov-recombinant/issues/167): Alias key out of date, change source + +## Validate + +### Proposed Lineages + +- [Issue #166](https://github.com/ktmeaton/ncov-recombinant/issues/166): `proposed1138` +- [Issue #165](https://github.com/ktmeaton/ncov-recombinant/issues/165): `proposed1139` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.6.0.md",".md","6788","78","# v0.6.0 + +This is a major release that includes the following changes: + +- Detection of all recombinants in [Nextclade dataset 2022-10-27](https://github.com/nextstrain/nextclade_data/releases/tag/2022-10-31--11-48-49--UTC): `XA` to `XBE`. +- Implementation of recombinant sublineages (ex. `XBB.1`). +- Implementation of immune-related statistics (`rbd_level`, `immune_escape`, `ace2_binding`) from `nextclade`, the `Nextstrain` team, and Jesse Bloom's group: + + - https://github.com/nextstrain/ncov/blob/master/defaults/rbd_levels.yaml + - https://jbloomlab.github.io/SARS-CoV-2-RBD_DMS_Omicron/epistatic-shifts/ + - https://jbloomlab.github.io/SARS2_RBD_Ab_escape_maps/escape-calc/ + - https://doi.org/10.1093/ve/veac021 + - https://doi.org/10.1101/2022.09.15.507787 + - https://doi.org/10.1101/2022.09.20.508745 + +## Dataset + +- [Issue #168](https://github.com/ktmeaton/ncov-recombinant/issues/168): NULL collection dates and NULL country is implemented. +- `controls` was updated to in include 1 strain from `XBB` for a total of 22 positive controls. The 28 negative controls were unchanged from `v0.5.1`. +- `controls-gisaid` strain list was updated to include `XA` through to `XBE` for a total of 528 positive controls. This includes sublineages such as `XBB.1` and `XBB.1.2` which synchronizes with [Nextclade Dataset 2022-10-19](https://github.com/nextstrain/nextclade_data/releases/tag/2022-10-19). The 187 negatives controls were unchanged from `v0.5.1`. + +## Nextclade + +- [Issue #176](https://github.com/ktmeaton/ncov-recombinant/issues/176): Upgrade Nextclade dataset to tag `2022-10-27` and upgrade Nextclade to `v2.8.0`. +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Use the nextclade dataset `sars-cov-2-21L` to calculate `immune_escape` and `ace2_binding`. + +## RBD Levels + +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Create new rule `rbd_levels` to calculate the number of key receptor binding domain (RBD) mutations. + +## Lineage Tree + +- [Issue #185](https://github.com/ktmeaton/ncov-recombinant/issues/185): Use nextclade dataset Auspice tree for lineage hierarchy. Previously, the phylogeny of lineages was constructed from the [cov-lineages website YAML](https://github.com/cov-lineages/lineages-website/blob/master/_data/lineages.yml). Instead, we now use the tree provided with nextclade datasets, to better synchronize the lineage model with the output. + +Rather than creating the output tree in `resources/lineages.nwk`, the lineage tree will output to `data/sars-cov-2_/tree.nwk`. This is because different builts might use different nextclade datasets, and so are dataset specific output. + +## sc2rf + +- [Issue #179](https://github.com/ktmeaton/ncov-recombinant/issues/179): Fix bug where `sc2rf/recombinants.ansi.txt` is truncated. +- [Issue #180](https://github.com/ktmeaton/ncov-recombinant/issues/180): Fix recombinant sublineages (ex. XAY.1) missing their derived mutations in the `cov-spectrum_query`. Previously, the `cov-spectrum_query` mutations were only based on the parental alleles (before recombination). This led to sublinaeges (ex. `XAY.1`, `XAY.2`) all having the exact same query. Now, the `cov-spectrum_query` will include _all_ substitutions shared between all sequences in the `cluster_id`. +- [Issue #187](https://github.com/ktmeaton/ncov-recombinant/issues/187): Document bug that occurs if duplicate sequences are present, and the initial validation was skipped by not running `scripts/create_profile.sh`. +- [Issue #191](https://github.com/ktmeaton/ncov-recombinant/issues/191) and [Issue #192](https://github.com/ktmeaton/ncov-recombinant/issues/192): Reduce false positives by ensuring that each mode of sc2rf has at least one additional parental population that serves as the alternative hypothesis. +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Implement a filter on the ratio of intermissions to alleles. Sequences will be marked as false positives if the number of intermissions (i.e. alleles that conflict with the identified parental region) is greater than or equal to the number of alleles contributed by the minor parent. This ratio indicates that there is more evidence that conflicts with recombination than there is allele evidence that supports a recombinant origin. + +## Linelist + +- [Issue #183](https://github.com/ktmeaton/ncov-recombinant/issues/183): Recombinant sublineages. When nextclade calls a lineage (ex. `XAY.1`) which is a sublineage of a sc2rf lineage (`XAY`), we prioritize the nextclade assignment. +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Add immune-related statistics: `rbd_levels`, `rbd_substitutions`, `immune_escape`, and `ace2_binding`. + +## Plot + +- [Issue #57](https://github.com/ktmeaton/ncov-recombinant/issues/57): Include substitutions within breakpoint intervals for breakpoint plots. This is a product of [Issue #180](https://github.com/ktmeaton/ncov-recombinant/issues/180) which provides access to _all_ substitutions. +- [Issue #112](https://github.com/ktmeaton/ncov-recombinant/issues/112): Fix bug where breakpoints plot image was out of bounds. +- [Issue #188](https://github.com/ktmeaton/ncov-recombinant/issues/188): Remove the breakpoints distribution axis (ex. `breakpoints_clade.png`) in favor of putting the legend at the top. This significant reduces plotting issues (ex. [Issue #112](https://github.com/ktmeaton/ncov-recombinant/issues/112)). +- [Issue #193](https://github.com/ktmeaton/ncov-recombinant/issues/193): Create new plot `rbd_level`. + +## Validate + +### Designated Lineages + +- [Issue #85](https://github.com/ktmeaton/ncov-recombinant/issues/85): `XAY`, updated controls +- [Issue #178](https://github.com/ktmeaton/ncov-recombinant/issues/178): `XAY.1` +- [Issue #172](https://github.com/ktmeaton/ncov-recombinant/issues/172): `XBB.1` +- [Issue #175](https://github.com/ktmeaton/ncov-recombinant/issues/175): `XBB.1.1` +- [Issue #184](https://github.com/ktmeaton/ncov-recombinant/issues/184): `XBB.1.2` +- [Issue #173](https://github.com/ktmeaton/ncov-recombinant/issues/173): `XBB.2` +- [Issue #174](https://github.com/ktmeaton/ncov-recombinant/issues/174): `XBB.3` +- [Issue #181](https://github.com/ktmeaton/ncov-recombinant/issues/181): `XBC.1` +- [Issue #182](https://github.com/ktmeaton/ncov-recombinant/issues/182): `XBC.2` +- [Issue #171](https://github.com/ktmeaton/ncov-recombinant/issues/171): `XBD` +- [Issue #177](https://github.com/ktmeaton/ncov-recombinant/issues/177): `XBE` + +### Proposed Lineages + +- [Issue #198](https://github.com/ktmeaton/ncov-recombinant/issues/198): `proposed1229` +- [Issue #199](https://github.com/ktmeaton/ncov-recombinant/issues/199): `proposed1268` +- [Issue #197](https://github.com/ktmeaton/ncov-recombinant/issues/197): `proposed1296` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.1.1.md",".md","675","22","# v0.1.1 + +1. Add lineage `XD` to controls. + + - There are now publicly available samples. + +1. Add lineage `XQ` to controls. + + - Has only 1 diagnostic substitution: 2832. + +1. Add lineage `XS` to controls. +1. Exclude lineage `XR` because it has no public genomes. + + - `XR` decends from `XQ` in the UShER tree. + +1. Test `sc2rf` dev to ignore clade regions that are ambiguous. +1. Add column `usher_pango_lineage_map` that maps github issues to recombinant lineages. +1. Add new rule `report`. +1. Filter non-recombinants from `sc2rf` ansi output. +1. Fix `subtrees_collapse` failing if only 1 tree specified +1. Add new rule `usher_metadata` for merge metadata for subtrees. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.3.0.md",".md","3339","100","# v0.3.0 + +## Major Changes + +1. Default parameters have been updated! Please regenerate your profiles/builds with: + + ```bash + bash scripts/create_profile.sh --data data/custom + ``` + +1. Rule outputs are now in sub-directories for a cleaner `results` directory. +1. The in-text report (`report.pptx`) statistics are no longer cumulative counts of all sequences. Instead they, will match the reporting period in the accompanying plots. + +## Bug Fixes + +1. Improve subtree collapse effiency (#35). +1. Improve subtree aesthetics and filters (#20). +1. Fix issues rendering as float (#29). +1. Explicitly control the dimensions of plots for powerpoint embedding. +1. Remove hard-coded `extra_cols` (#26). +1. Fix mismatch in lineages plot and description (#21). +1. Downstream steps no longer fail if there are no recombinant sequences (#7). + +## Workflow + +1. Add new rule `usher_columns` to augment the base usher metadata. +1. Add new script `parents.py`, plots, and report slide to summarize recombinant sequences by parent. +1. Make rules `plot` and `report` more dynamic with regards to plots creation. +1. Exclude the reference genome from alignment until `faToVcf`. +1. Include the log path and expected outputs in the message for each rule. +1. Use sub-functions to better control optional parameters. +1. Make sure all rules write to a log if possible (#34). +1. Convert all rule inputs to snakemake rule variables. +1. Create and document a `create_profile.sh` script. +1. Implement the `--low-memory` mode parameter within the script `usher_metadata.sh`. + +## Data + +1. Create new controls datasets: + + - `controls-negatives` + - `controls-positives` + - `controls` + +1. Add versions to `genbank_accessions` for `controls`. + +## Programs + +1. Upgrade UShER to v0.5.4 (possibly this was done in a prior ver). +1. Remove `taxonium` and `chronumental` from the conda env. + +## Parameters + +1. Add parameters to control whether negatives and false_positives should be excluded: + + - `exclude_negatives: false` + - `false_positives: false` + +1. Add new optional param `max_placements` to rule `linelist`. +1. Remove `--show-private-mutations` from `debug_args` of rule `sc2rf`. +1. Add optional param `--sc2rf-dir` to `sc2rf` to enable execution outside of `sc2rf` dir. +1. Add params `--output-csv` and `--output-ansi` to the wrapper `scripts/sc2rf.sh`. +1. Remove params `nextclade_ref` and `custom_ref` from rule `nextclade`. +1. Change `--breakpoints 0-10` in `sc2rf`. + +## Continuous Integration + +1. Re-rename tutorial action to pipeline, and add different jobs for different profiles: + + - Tutorial + - Controls (Positive) + - Controls (Negative) + - Controls (All) + +## Output + +1. Output new `_historical` plots and slides for plotting all data over time. +1. Output new file `parents.tsv` to summarize recombinant sequences by parent. +1. Order the colors/legend of the stacked bar `plots` by number of sequences. +1. Include lineage and cluster id in filepaths of largest plots and tables. +1. Rename the linelist output: + + - `linelist.tsv` + - `positives.tsv` + - `negatives.tsv` + - `false_positives.tsv` + - `lineages.tsv` + - `parents.tsv` + +1. The `report.xlsx` now includes the following tables: + + - lineages + - parents + - linelist + - positives + - negatives + - false_positives + - summary + - issues +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.4.1.md",".md","541","8","# v0.4.1 + +This is a minor bug fix release with the following changes: + +- [Issue #63](https://github.com/ktmeaton/ncov-recombinant/issues/63): Remove `usher` and `protobuf` from the conda environment. +- [Issue #68](https://github.com/ktmeaton/ncov-recombinant/issues/68): Remove [ncov](https://github.com/nextstrain/ncov) as a submodule. +- [Issue #69](https://github.com/ktmeaton/ncov-recombinant/issues/69): Remove 22C and 22D from `sc2rf/mapping.csv` and `sc2rf/virus_properties.json`, as these interfere with breakpoint detection for XAN. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.7.0.md",".md","4492","65","# Development + +This is a minor release aimed towards a `nextclade` dataset upgrade from `2022-10-27` to `2023-01-09` which adds nomenclature for newly designated recombinants `XBH` - `XBP`. This release also adds initial support for the detection of ""recursive recombination"" including `XBL` and `XBN` which are recombinants of `XBB`. + +## Documentation + +- [Issue #24](https://github.com/ktmeaton/ncov-recombinant/issues/24): Create documentation on [Read The Docs](https://ncov-recombinant.readthedocs.io/en/stable/) + +## Dataset + +- [Issue #210](https://github.com/ktmeaton/ncov-recombinant/issues/210): Handle numeric strain names. + +## Resources + +- [Issue #185](https://github.com/ktmeaton/ncov-recombinant/issues/185): Simplify creation of the pango-lineage nomenclature phylogeny to use the [lineage_notes.txt](https://github.com/cov-lineages/pango-designation/blob/master/lineage_notes.txt) file and the [pango_aliasor](https://github.com/corneliusroemer/pango_aliasor) library. + +## sc2rf + +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Add bypass to intermission allele ratio for edge cases. +- [Issue #204](https://github.com/ktmeaton/ncov-recombinant/issues/204): Add special handling for XBB sequenced with ARTIC v4.1 and dropout regions. +- [Issue #205](https://github.com/ktmeaton/ncov-recombinant/issues/205): Add new column `parents_conflict` to indicate whether the reported lineages from covSPECTRUM conflict with the reported parental clades from `sc2rf. +- [Issue #213](https://github.com/ktmeaton/ncov-recombinant/issues/213): Add `XBK` to auto-pass lineages. +- [Issue #222](https://github.com/ktmeaton/ncov-recombinant/issues/222): Add new parameter `--gisaid-access-key` to `sc2rf` and `sc2rf_recombinants`. +- [Issue #229](https://github.com/ktmeaton/ncov-recombinant/issues/229): Fix bug where auto-pass lineages are missing when exclude_negatives is set to true. +- [Issue #231](https://github.com/ktmeaton/ncov-recombinant/issues/231): Fix bug where 'null' lineages in covSPECTRUM caused error in `sc2rf` postprocess. +- The order of the `postprocessing.py` was rearranged to have more comprehensive details for auto-pass lineages. +- Add `XAN` to auto-pass lineages. + +## Plot + +- [Issue #209](https://github.com/ktmeaton/ncov-recombinant/issues/209): Restrict the palette for `rbd_level` to the range of `0:12`. +- [Issue #218](https://github.com/ktmeaton/ncov-recombinant/issues/218): Fix bug concerning data fragmentation with large numbers of sequences. +- [Issue #221](https://github.com/ktmeaton/ncov-recombinant/issues/221): Remove parameter `--singletons` in favor of `--min-cluster-size` to control cluster size in plots. +- [Issue #224](https://github.com/ktmeaton/ncov-recombinant/issues/224): Fix bug where plot crashed with extremely large datasets. +- Combine `plot` and `plot_historical` into one snakemake rule. Also at custom pattern `plot_NX` (ex. `plot_N10`) to adjust min cluster size. + +## Report + +- Combine `report` and `report_historical` into one snakemake rule. + +## Validate + +- [Issue #225](https://github.com/ktmeaton/ncov-recombinant/issues/225): Fix bug where false negatives passed validation because the status column wasn't checked. + +### Designated Lineages + +- [Issue #217](https://github.com/ktmeaton/ncov-recombinant/issues/217): `XBB.1.5` +- [Issue #196](https://github.com/ktmeaton/ncov-recombinant/issues/196): `XBF` +- [Issue #206](https://github.com/ktmeaton/ncov-recombinant/issues/206): `XBG` +- [Issue #196](https://github.com/ktmeaton/ncov-recombinant/issues/198): `XBH` +- [Issue #199](https://github.com/ktmeaton/ncov-recombinant/issues/199): `XBJ` +- [Issue #213](https://github.com/ktmeaton/ncov-recombinant/issues/213): `XBK` +- [Issue #219](https://github.com/ktmeaton/ncov-recombinant/issues/219): `XBL` +- [Issue #215](https://github.com/ktmeaton/ncov-recombinant/issues/215): `XBM` +- [Issue #197](https://github.com/ktmeaton/ncov-recombinant/issues/197): `XBN` + +### Proposed Lineages + +- [Issue #203](https://github.com/ktmeaton/ncov-recombinant/issues/203): `proposed1305` +- [Issue #208](https://github.com/ktmeaton/ncov-recombinant/issues/208): `proposed1340` +- [Issue #212](https://github.com/ktmeaton/ncov-recombinant/issues/212): `proposed1425` +- [Issue #214](https://github.com/ktmeaton/ncov-recombinant/issues/214): `proposed1440` +- [Issue #216](https://github.com/ktmeaton/ncov-recombinant/issues/216): `proposed1444` +- [Issue #220](https://github.com/ktmeaton/ncov-recombinant/issues/220): `proposed1576` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.4.2.md",".md","1622","17","# v0.4.2 + +This is a minor bug fix and enhancement release with the following changes: + +## Linelist + +- [Issue #70](https://github.com/ktmeaton/ncov-recombinant/issues/70): Fix missing `sc2rf` version from `recombinant_classifier_dataset` +- [Issue #74](https://github.com/ktmeaton/ncov-recombinant/issues/74): Correctly identify `XN-like` and `XP-like`. Previously, these were just assigned `XN`/`XP` regardless of whether the estimated breakpoints conflicted with the curated ones. +- [Issue #76](https://github.com/ktmeaton/ncov-recombinant/issues/76): Mark undesignated lineages with no matching sc2rf lineage as `unpublished`. + +## Plot + +- [Issue #71](https://github.com/ktmeaton/ncov-recombinant/issues/71): Only truncate `cluster_id` while plotting, not in table generation. +- [Issue #72](https://github.com/ktmeaton/ncov-recombinant/issues/72): For all plots, truncate the legend labels to a set number of characters. The exception to this are parent labels (clade,lineage) because the full label is informative. +- [Issue #73](https://github.com/ktmeaton/ncov-recombinant/issues/73), [#75](https://github.com/ktmeaton/ncov-recombinant/issues/75): For all plots except breakpoints, lineages will be defined by the column `recombinant_lineage_curated`. Previously it was defined by the combination of `recombinant_lineage_curated` and `cluster_id`, which made cluttered plots that were too difficult to interpret. +- New parameter `--lineage-col` was added to `scripts/plot_breakpoints.py` to have more control on whether we want to plot the raw lineage (`lineage`) or the curated lineage (`recombinant_lineage_curated`). +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.4.0.md",".md","13355","102","# v0.4.0 + +## General + +v0.4.0 has been trained and validated on the latest generation of SARS-CoV-2 Omicron clades (ex. 22A/BA.4 and 22B/BA.5). Recombinant sequences involving BA.4 and BA.5 can now be detected, unlike in v0.3.0 where they were not included in the `sc2rf` models. + +v0.4.0 is also a **major** update to how sequences are categorized into lineages/clusters. A recombinant lineage is now defined as a group of sequences with a unique combination of: + +- Lineage assignment (ex. `XM`) +- Parental clades (ex. `Omicron/21K,Omicron/21L`) +- Breakpoints (ex. `17411:21617`) +- **NEW**: Parental lineages (ex. `BA.1.1,BA.2.12.1`) + +Novel recombinants (i.e. undesignated) can be identified by a lineage assignment that does not start with `X*` (ex. `BA.1.1`) _or_ with a lineage assignment that contains `-like` (ex. `XM-like`). A cluster of sequences may be flagged as `-like` if one of the following criteria apply: + +1. The lineage assignment by [Nextclade](https://github.com/nextstrain/nextclade) conflicts with the published breakpoints for a designated lineage (`resources/breakpoints.tsv`). + + - Ex. An `XE` assigned sample has breakpoint `11538:12879`, which conflicts with the published `XE` breakpoint (`ex. 8394:12879`). This will be renamed `XE-like`. + +1. The cluster has 10 or more sequences, which share at least 3 private mutations in common. + + - Ex. A large cluster of sequences (N=50) are assigned `XM`. However, these 50 samples share 5 private mutations `T2470C,C4586T,C9857T,C12085T,C26577G` which do not appear in true `XM` sequences. These will be renamed `XM-like`. Upon further review of the reported matching [pango-designation issues](https://github.com/cov-lineages/pango-designation/issues) (`460,757,781,472,798`), we find this cluster to be a match to `proposed798`. + +The ability to identify parental lineages and private mutations is largely due to improvements in the [newly released nextclade datasets](https://github.com/nextstrain/nextclade_data/releases/tag/2022-07-26--13-04-52--UTC), , which have increased recombinant lineage accuracy. As novel recombinants can now be identified without the use of the custom UShER annotations (ex. proposed771), all UShER rules and output have been removed. This significantly improves runtime, and reduces the need to drop non-recombinant samples for performance. The result is more comparable output between different dataset sizes (4 samples vs. 400,000 samples). + +> **Note!** Default parameters have been updated! Please regenerate your profiles/builds with: +> +> ```bash +> scripts/create_profile.sh --data data/custom +> ``` + +## Datasets + +- [Issue #49](https://github.com/ktmeaton/ncov-recombinant/issues/49): The tutorial lineages were changed from `XM`,`proposed467`, `miscBA1BA2Post17k`, to `XD`, `XH`, `XAN`. The previous tutorial sequences had genome quality issues. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Add `XAN` to the controls dataset. This is BA.2/BA.5 recombinant. +- [Issue #62](https://github.com/ktmeaton/ncov-recombinant/issues/62): Add `XAK` to the controls dataset. This is BA.2/BA.1 VUM recombinant monitored by the ECDC. + +## Nextclade + +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): `nextclade` is now run twice. Once with the regular `sars-cov-2` dataset and once with the `sars-cov-2-no-recomb` dataset. The `sars-cov-2-no-recomb` dataset is used to get the nucleotide substitutions before recombination occurred. These are identified by taking the `substitutions` column, and excluding the substitutions found in `privateNucMutations.unlabeledSubstitutions`. The pre-recombination substitutions allow us to identify the parental lineages by querying [cov-spectrum](https://cov-spectrum.org/). +- [Issue #48](https://github.com/ktmeaton/ncov-recombinant/issues/48): Make the `exclude_clades` completely optional. Otherwise an error would be raised if the user didn't specify any. +- [Issue #50](https://github.com/ktmeaton/ncov-recombinant/issues/50): Upgrade from `v1.11.0` to `v2.3.0`. Also upgrade the default dataset tags to [2022-07-26T12:00:00Z](https://github.com/nextstrain/nextclade_data/releases/tag/2022-07-26--13-04-52--UTC) which had significant bug fixes. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Relax the recombinant criteria, by flagging sequences with ANY labelled private mutations as a potential recombinant for further downstream analysis. This was specifically for BA.5 recombinants (ex. `XAN`) as no other columns from the `nextclade` output indicated this could be a recombinant. +- Restrict `nextclade` output to `fasta,tsv` (alignment and QC table). This saves on file storage, as the other default output is not used. + +## sc2rf + +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): `sc2rf` is now run twice. First, to detect recombination between clades (ex. `Delta/21J` & `Omicron/21K`). Second, to detect recombination within Omicron (ex. `Omicron/BA.2/21L` & `Omicron/BA.5/22B`). It was not possible to define universal parameters for `sc2rf` that worked for both distantly related clades, and the closely related Omicron lineages. +- [Issue #51](https://github.com/ktmeaton/ncov-recombinant/issues/51): Rename parameter `clades` to `primary_clades` and add new parameter `secondary_clades` for detecting BA.5. +- [Issue #53](https://github.com/ktmeaton/ncov-recombinant/issues/53): Identify the parental lineages by splitting up the observed mutations (from `nextclade`) into regions by breakpoint. Then query the list of mutations in and report the lineage with the highest prevalence. +- Tested out `--enable-deletions` again, which caused issues for `XD`. This confirms that using deletions is still ineffective for defining breakpoints. +- Add `B.1.631` and `B.1.634` to `sc2rf/mapping.tsv` and as potential clades in the default parameters. These are parents for `XB`. +- Add `B.1.438.1` to `sc2rf/mapping.tsv` and as a otential clade in the default parameters. This is a parent for [`proposed808`](https://github.com/cov-lineages/pango-designation/issues/808). +- Require a recombinant region to have at least one substitution unique to the parent (i.e. diagnostic). This reduces false positives. +- Remove the debugging mode, as it produced overly verbose output. It is more efficient to rerun manually with custom parameters tailored to the kind of debugging required. +- Change parent clade nomenclature from `Omicron/21K` to the more comprehensive `Omicron/BA.1/21K`. This makes it clear which lineage is involved, since it's not always obvious how Nextclade clades map to pango lineages. + +## UShER + +- [Issue #63](https://github.com/ktmeaton/ncov-recombinant/issues/63): All UShER rules and output have been removed. First, because the latest releases of nextclade datasets (tag `2022-07-26T12:00:00Z`) have dramatically improved lineage assignment accuracy for recombinants. Second, was to improve runtime and simplicity of the workflow, as UShER adds significantly to runtime. + +## Linelist + +- [Issue #30](https://github.com/ktmeaton/ncov-recombinant/issues/30): Fixed the bug where distinct recombinant lineages would occasionally be grouped into one `cluster_id`. This is due to the new definition for recombinant lineages (see General) section, which now includes parental _lineages_ and have sufficient resolving power. +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): Added new column `parents_subs`, which are the substitutions found in the parental lineages _before_ recombination occurred using the `sars-cov-2-no-recomb` nextclade dataset. Also added new columns: `parents_lineage`, `parents_lineage_confidence`, based on querying `cov-spectrum` for the substitutions found in `parents_subs`. +- [Issue #53](https://github.com/ktmeaton/ncov-recombinant/issues/53): Added new column `cov-spectrum_query` which includes the substitutions that are shared by ALL sequences of the recombinant lineage. +- Added new column `cluster_privates` which includes the private substitutions shared by ALL sequences of the recombinant lineage. +- Renamed `parents` column to `parents_clade`, to differentiate it from the new column `parents_lineage`. + +## Plot + +- [Issue #4](https://github.com/ktmeaton/ncov-recombinant/issues/4), [Issue #57](https://github.com/ktmeaton/ncov-recombinant/issues/57): Plot distributions of each parent separately, rather than stacking on one axis. Also plot the substitutions as ticks on the breakpoints figure. + +| v0.3.0 | v0.4.0 | +| -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| ![breakpoints_clade_v0.3.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/4fbde4b90/images/breakpoints_clade_v0.3.0.png) | ![breakpoints_clade_v0.4.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/4fbde4b90/images/breakpoints_clade_v0.4.0.png) | + +- [Issue #46](https://github.com/ktmeaton/ncov-recombinant/issues/46): Plot breakpoints separately by clade _and_ lineage. In addition, distinct clusters within the same recombinant lineage are noted by including their cluster ID as a suffix. As an example, please see `XM (USA) and X (England)` below. Where the lineage is the same (`XM`), but the breakpoints differ, as do the parental lineages (`BA.2` vs `BA.2.12.1`). These clusters are distinct because `XM (England)` lacks substitutions occurring around position 20000. + +| Clade | Lineage | +|:--------------------------------------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------------------------:| +| ![breakpoints_clade](https://github.com/ktmeaton/ncov-recombinant/raw/432b6b79/images/breakpoints_clade_v0.4.0.png) | ![breakpoints_clade](https://github.com/ktmeaton/ncov-recombinant/raw/432b6b79/images/breakpoints_lineage_v0.4.0.png) | + +- [Issue #58](https://github.com/ktmeaton/ncov-recombinant/issues/58): Fix breakpoint plotting from all lineages to just those observed in the reporting period. Except for the breakpoint plots in `plots_historical`. +- [Issue #59](https://github.com/ktmeaton/ncov-recombinant/issues/59): Improved error handling of breakpoint plotting when a breakpoint could not be identified by `sc2rf`. This is possible if `nextclade` was the only program to detect recombination (and thus, we have no breakpoint data from `sc2rf`). +- [Issue #64](https://github.com/ktmeaton/ncov-recombinant/issues/64): Improved error handling for when the lag period (ex. 4 weeks) falls outside the range of collection dates (ex. 2 weeks). +- [Issue #65](https://github.com/ktmeaton/ncov-recombinant/issues/65): Improved error handling of distribution plotting when only one sequence is present. +- [Issue #67](https://github.com/ktmeaton/ncov-recombinant/issues/67): Plot legends are placed above the figure and are dynamically sized. + +| v0.3.0 | v0.4.0 | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ![lineages_output_v0.3.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/af2f25d3c5e7c1d56244390ee90bec405b23949a/images/lineages_output_v0.3.0.png) | ![lineages_output_v0.4.0](https://raw.githubusercontent.com/ktmeaton/ncov-recombinant/af2f25d3c5e7c1d56244390ee90bec405b23949a/images/lineages_output_v0.4.0.png) | + +## Report + +- [Issue #60](https://github.com/ktmeaton/ncov-recombinant/issues/60): Remove changelog from final slide, as this content did not display correctly +- [Issue #61](https://github.com/ktmeaton/ncov-recombinant/issues/61): Fixed bug in the `report.xlsx` where the number of proposed and unpublished recombinant lineages/sequences was incorrect. + +## Validation + +- [Issue #58](https://github.com/ktmeaton/ncov-recombinant/issues/58): New rule (`validate`) to validate the number of positives in controlled datasets (ex. controls, tutorials) against `defaults/validation.tsv`. If validation fails based on an incorrect number of positives, the pipeline will exit with an error. This is to make it more obvious when results have changed during Continuous Integration (CI) +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.2.0.md",".md","2874","82","# v0.2.0 + +## Bugs + +1. Fix bug in `sc2rf_recombinants` regions/breakpoints logic. +1. Fix bug in `sc2rf` where a sample has no definitive substitutions. + +## Params + +1. Allow `--breakpoints 0-4`, for XN. We'll determine the breakpoints in post-processing. +1. Bump up the `min_len` of `sc2rf_recombinants` to 1000 bp. +1. Add param `mutation_threshold` to `sc2rf`. +1. Reduce default `mutation_threshold` to 0.25 to catch [Issue #591](https://github.com/cov-lineages/pango-designation/issues/591_. +1. Bump up subtree size from 100 sequences to 500 sequences. + + - Trying to future proof against XE growth (200+ sequences) + +1. Discovered that `--primers` interferes with breakpoint detection, use only for debugging. +1. Only use `--enable-deletions` in `sc2rf` for debug mode. Otherwise it changes breakpoints. +1. Only use `--private-mutations` to `sc2rf` for debug mode. Unreadable output for bulk sample processing. + +## Report + +1. Change `sc2rf_lineage` column to use NA for no lineage found. + + - This is to troubleshot when only one breakpoint matches a lineage. + +1. Add `sc2rf_mutations_version` to summary based on a datestamp of `virus_properties.json`. +1. Allow multiple issues in report. +1. Use three status categories of recombinants: + + - Designated + - Proposed + - Unpublished + +1. Add column `status` to recombinants. +1. Add column `usher_extra` to `usher_metadata` for 2022-05-06 tree. +1. Separate out columns lineage and issue in `report`. +1. Add optional columns to report. +1. Fixed growth calculations in report. +1. Add a Definitions section to the markdown/pdf report. +1. Use parent order for breakpoint matching, as we see same breakpoint different parents. +1. Add the number of usher placements to the summary. + +## Output + +1. Set Auspice default coloring to `lineage_usher` where possible. +1. Remove nwk output from `usher` and `usher_subtrees`: + + - Pull subtree sample names from json instead + +1. Output `linelist.exclude.tsv` of false-positive recombinants. + +## Programs + +1. Update `nextclade_dataset` to 2022-04-28. +1. Add `taxoniumtools` and `chronumental` to environment. +1. Separate nextclade clades and pango lineage allele frequences in `sc2rf`. +1. Exclude BA.3, BA.4, and BA.5 for now, as their global prevalence is low and they are descendants of BA.2. + +## Profiles + +1. Add a `tutorial` profile. + + - (N=2) Designated Recombinants (pango-designation) + - (N=2) Proposed Recombinants (issues, UCSC) + - (N=2) Unpublished Recombinants + +1. Add XL to `controls`. +1. Add XN to `controls`. +1. Add XR to `controls`. +1. Add XP to `controls`. + +## Workflow + +1. Split `usher_subtree` and `usher_subtree_collapse` into separate rules. + + - This speeds up testing for collapsing trees and styling the Auspice JSON. + +1. Force include `Nextclade` recombinants (auto-pass through `sc2rf`). +1. Split `usher` and `usher_stats` into separate rules. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.1.0.md",".md","647","15","# v0.1.0 + +1. Add Stage 1: Nextclade. +1. Add Stage 2: sc2rf. +1. Add Stage 3: UShER. +1. Add Stage 4: Summary. +1. Add Continuous Integration workflows: `lint`, `test`, `pipeline`, and `release`. +1. New representative controls dataset: + + - Exclude XA because this is an Alpha recombinant (poor lineage accuracy). + - Exclude XB because of [current issue](https://github.com/summercms/covid19-pango-designation/commit/26b7359e34a0b2f122215332b6495fea97ff3fe7) + - Exclude XC because this is an Alpha recombinant (poor lineage accuracy). + - Exclude XD because there are no public genomes. + - Exclude XK because there are no public genomes. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.6.1.md",".md","719","10","# v0.6.1 + +This is a minor bugfix release aimed towards resolving network connectivity errors and catching false positives. + +## sc2rf + +- [Issue #195](https://github.com/ktmeaton/ncov-recombinant/issues/195): Consider alleles outside of parental regions as intermissions (conflicts) to catch false positives. +- [Issue #201](https://github.com/ktmeaton/ncov-recombinant/issues/201): Make LAPIS query of covSPECTRUM optional, to help with users with network connectivity issues. This can be set with the flag `lapis: false` in builds under the rule `sc2rf_recombinants`. +- [Issue #202](https://github.com/ktmeaton/ncov-recombinant/issues/202): Document connection errors related to LAPIS and provide options for solutions. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.1.2.md",".md","1893","49","# v0.1.2 + +1. Add lineage `XM` to controls. + + - There are now publicly available samples. + +1. Correct `XF` and `XJ` controls to match issues. +1. Create a markdown report with program versions. +1. Fix `sc2rf_recombinants` bug where samples with >2 breakpoints were being excluded. +1. Summarize recombinants by parents and dates observed. +1. Change `report.tsv` to `linelist.tsv`. +1. Use `date_to_decimal.py` to create `num_date` for auspice subtrees. +1. Add an `--exclude-clades` param to `sc2rf_recombinants.py`. +1. Add param `--ignore-shared-subs` to `sc2rf`. + + - This makes regions detection more conservative. + - The result is that regions/clade will be smaller and breakpoints larger. + - These breakpoints more closely match pango-designation issues. + +1. Update breakpoints in controls metadata to reflect the output with `--ignore-shared-subs`. +1. Bump up `min_len` for `sc2rf_recombinants` to 200 bp. +1. Add column `sc2rf_lineage` to `sc2rf_recombinants` output. + + - Takes the form of X*, or proposed{issue} to follow UShER. + +1. Consolidate lineage assignments into a single column. + + - sc2rf takes priority if a single lineage is identified. + - usher is next, to resolve ties or if sc2rf had no lineage. + +1. Slim down the conda environment and remove unnecessary programs. + + - `augur` + - `seaborn` + - `snipit` + - `bedtools` + - Comment out dev tools: `git` and `pre-commit`. + +1. Use github api to pull recombinant issues. +1. Consolidate \*_to_\* files into `resources/issues.tsv`. +1. Use the `--clades` param of `sc2rf` rather than using `exclude_clades`. +1. Disabled `--rebuild-examples` in `sc2rf` because of requests error. +1. Add column `issue` to `recombinants.tsv`. +1. Get `ncov-recombinant` version using tag. +1. Add documentation to the report. + + - What the sequences column format means: X (+X) + - What the different lineage classifers. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.5.0.md",".md","11578","131","# v0.5.0 + +> Please check out the `v0.5.0` [Testing Summary Package](https://ktmeaton.github.io/ncov-recombinant/docs/testing_summary_package/ncov-recombinant_v0.4.2_v0.5.0.html) for a comprehensive report. + +This is a minor release that includes the following changes: + +1. Detection of all recombinants in [Nextclade dataset 2022-09-27](https://github.com/nextstrain/nextclade_data/releases/tag/2022-09-28--16-01-10--UTC): `XA` to `XBC`. +1. Create any number of custom `sc2rf` modes with CLI arguments. + +## Resources + +- [Issue #96](https://github.com/ktmeaton/ncov-recombinant/issues/96): Create newick phylogeny of pango lineage parent child relationships, to get accurate sublineages including aliases. +- [Issue #118](https://github.com/ktmeaton/ncov-recombinant/issues/118): Fix missing pango-designation issues for XAY and XBA. + +## Datasets + +- [Issue #25](https://github.com/ktmeaton/ncov-recombinant/issues/25): Reduce positive controls to one sequence per clade. Add new positive controls `XAL`, `XAP`, `XAS`, `XAU`, and `XAZ`. +- [Issue #92](https://github.com/ktmeaton/ncov-recombinant/issues/92): Reduce negative controls to one sequence per clade. Add negative control for `22D (Omicron) / BA.2.75`. +- [Issue #155](https://github.com/ktmeaton/ncov-recombinant/issues/155): Add new profile and dataset `controls-gisaid`. Only a list of strains is provided, as GISAID policy prohibits public sharing of sequences and metadata. + +## Profile Creation + +- [Issue #77](https://github.com/ktmeaton/ncov-recombinant/issues/77): Report slurm command for `--hpc` profiles in `scripts/create_profiles.sh`. +- [Issue #153](https://github.com/ktmeaton/ncov-recombinant/issues/153): Fix bug where build parameters `metadata` and `sequences` were not implemented. + +## Nextclade + +- [Issue #81](https://github.com/ktmeaton/ncov-recombinant/issues/81): Upgrade Nextclade datasets to 2022-09-27 +- [Issue #91](https://github.com/ktmeaton/ncov-recombinant/issues/91): Upgrade Nextclade to v2.5.0 + +## sc2rf + +- [Issue #78](https://github.com/ktmeaton/ncov-recombinant/issues/78): Add new parameter `max_breakpoint_len` to `sc2rf_recombinants` to mark samples with two much uncertainty in the breakpoint interval as false positives. +- [Issue #79](https://github.com/ktmeaton/ncov-recombinant/issues/79): Add new parameter `min_consec_allele` to `sc2rf_recombinants` to ignore recombinant regions with less than this number of consecutive alleles (both diagnostic SNPs and diganostic reference alleles). +- [Issue #80](https://github.com/ktmeaton/ncov-recombinant/issues/80): Migrate [sc2rf](https://github.com/lenaschimmel/sc2rf) froma submodule to a subdirectory (including LICENSE!). This is to simplify the updating process and avoid errors where submodules became out of sync with the main pipeline. +- [Issue #83](https://github.com/ktmeaton/ncov-recombinant/issues/83): Improve error handling in `sc2rf_recombinants` when the input stats files are empty. +- [Issue #89](https://github.com/ktmeaton/ncov-recombinant/issues/89): Reduce the default value of the parameter `min_len` in `sc2rf_recombinants` from `1000` to `500`.This is to handle `XAP` and `XAJ`. +- [Issue #90](https://github.com/ktmeaton/ncov-recombinant/issues/90): Auto-pass select nextclade lineages through `sc2rf`: `XN`, `XP`, `XAR`, `XAS`, and `XAZ`. This requires differentiating the nextclade inputs as separate parameters `--nextclade` and `--nextclade-no-recom`. + + `XN`,`XP`, and `XAR` have extremely small recombinant regions at the terminal ends of the genome. Depending on sequencing coverage, `sc2rf` may not reliably detect these lineages. + + The newly designated `XAS` and `XAZ` pose a challenge for recombinant detection using diagnostic alleles. The first region of `XAS` could be either `BA.5` or `BA.4` based on subsitutions, but is mostly likely `BA.5` based on deletions. Since the region contains no diagnostic alleles to discriminate `BA.5` vs. `BA.4`, breakpoints cannot be detected by `sc2rf`. + + Similarly for `XAZ`, the `BA.2` segments do not contain any `BA.2` diagnostic alleles, but instead are all reversion from `BA.5` alleles. The `BA.2` parent was discovered by deep, manual investigation in the corresponding pango-designation issue. Since the `BA.2` regions contain no diagnostic for `BA.2`, breakpoints cannot be detected by `sc2rf`. + +- [Issue #95](https://github.com/ktmeaton/ncov-recombinant/issues/95): Generalize `sc2rf_recombinants` to take any number of ansi and csv input files. This allows greater flexibility in command-line arguments to `sc2rf` and are not locked into the hardcoded `primary` and `secondary` parameter sets. +- [Issue #96](https://github.com/ktmeaton/ncov-recombinant/issues/96): Include sub-lineage proportions in the `parents_lineage_confidence`. This reduces underestimating the confidence of a parental lineage. +- [Issue #150](https://github.com/ktmeaton/ncov-recombinant/issues/150): Fix bug where `sc2rf` would write empty output csvfiles if no recombinants were found. +- [Issue #151](https://github.com/ktmeaton/ncov-recombinant/issues/151): Fix bug where samples that failed to align were missing from the linelists. +- [Issue #158](https://github.com/ktmeaton/ncov-recombinant/issues/158): Reduce `sc2rf` param `--max-intermission-length` from `3` to `2` to be consistent with [Issue #79](https://github.com/ktmeaton/ncov-recombinant/issues/79). +- [Issue #161](https://github.com/ktmeaton/ncov-recombinant/issues/161): Implement selection method to pick best results from various `sc2rf` modes. +- [Issue #162](https://github.com/ktmeaton/ncov-recombinant/issues/162): Upgrade `sc2rf/virus_properties.json`. +- [Issue #163](https://github.com/ktmeaton/ncov-recombinant/issues/163): Use LAPIS `nextcladePangoLineage` instead of `pangoLineage`. Also disable default filter `max_breakpoint_len` for `XAN`. +- [Issue #164](https://github.com/ktmeaton/ncov-recombinant/issues/164): Fix bug where false positives would appear in the filter `sc2rf` ansi output (`recombinants.ansi.txt`). +- The optional `lapis` parameter for `sc2rf_recombinants` has been removed. Querying [LAPIS](https://lapis.cov-spectrum.org/) for parental lineages is no longer experimental and is now an essential component (cannot be disabled). +- The mandatory `mutation_threshold` parameter for `sc2rf` has been removed. Instead, `--mutation-threshold` can be set independently in each of the `scrf` modes. + +## Linelist + +- [Issue #157](https://github.com/ktmeaton/ncov-recombinant/issues/157]): Create new parameters `min_lineage_size` and `min_private_muts` to control lineage splitting into `X*-like`. + +## Plot + +- [Issue #17](https://github.com/ktmeaton/ncov-recombinant/issues/17]): Create script to plot lineage assignment changes between versions using a Sankey diagram. +- [Issue #82](https://github.com/ktmeaton/ncov-recombinant/issues/82]): Change epiweek start from Monday to Sunday. +- [Issue #111](https://github.com/ktmeaton/ncov-recombinant/issues/111]): Fix breakpoint distribution axis that was empty for clade. +- [Issue #152](https://github.com/ktmeaton/ncov-recombinant/issues/152): Fix file saving bug when largest lineage has `/` characters. + +## Report + +- [Issue #88](https://github.com/ktmeaton/ncov-recombinant/issues/88): Add pipeline and nextclade versions to powerpoint slides as footer. This required adding `--summary` as param to `report`. + +## Validate + +- [Issue #56](https://github.com/ktmeaton/ncov-recombinant/issues/56): Change rule `validate` from simply counting the number of positives to validating the fields `lineage`, `breakpoints`, `parents_clade`. This involves adding a new default parameter `expected` for rule `validate` in `defaults/parameters.yaml`. + +### Designated Lineages + +- [Issue #149](https://github.com/ktmeaton/ncov-recombinant/issues/149): `XA` +- [Issue #148](https://github.com/ktmeaton/ncov-recombinant/issues/148): `XB` +- [Issue #147](https://github.com/ktmeaton/ncov-recombinant/issues/147): `XC` +- [Issue #146](https://github.com/ktmeaton/ncov-recombinant/issues/146): `XD` +- [Issue #145](https://github.com/ktmeaton/ncov-recombinant/issues/145): `XE` +- [Issue #144](https://github.com/ktmeaton/ncov-recombinant/issues/144): `XF` +- [Issue #143](https://github.com/ktmeaton/ncov-recombinant/issues/143): `XG` +- [Issue #141](https://github.com/ktmeaton/ncov-recombinant/issues/141): `XH` +- [Issue #142](https://github.com/ktmeaton/ncov-recombinant/issues/142): `XJ` +- [Issue #140](https://github.com/ktmeaton/ncov-recombinant/issues/140): `XK` +- [Issue #139](https://github.com/ktmeaton/ncov-recombinant/issues/139): `XL` +- [Issue #138](https://github.com/ktmeaton/ncov-recombinant/issues/138): `XM` +- [Issue #137](https://github.com/ktmeaton/ncov-recombinant/issues/137): `XN` +- [Issue #136](https://github.com/ktmeaton/ncov-recombinant/issues/136): `XP` +- [Issue #135](https://github.com/ktmeaton/ncov-recombinant/issues/135): `XQ` +- [Issue #134](https://github.com/ktmeaton/ncov-recombinant/issues/134): `XR` +- [Issue #133](https://github.com/ktmeaton/ncov-recombinant/issues/133): `XS` +- [Issue #132](https://github.com/ktmeaton/ncov-recombinant/issues/132): `XT` +- [Issue #131](https://github.com/ktmeaton/ncov-recombinant/issues/131): `XU` +- [Issue #130](https://github.com/ktmeaton/ncov-recombinant/issues/130): `XV` +- [Issue #129](https://github.com/ktmeaton/ncov-recombinant/issues/129): `XW` +- [Issue #128](https://github.com/ktmeaton/ncov-recombinant/issues/128): `XY` +- [Issue #127](https://github.com/ktmeaton/ncov-recombinant/issues/127): `XZ` +- [Issue #126](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAA` +- [Issue #125](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAB` +- [Issue #124](https://github.com/ktmeaton/ncov-recombinant/issues/124): `XAC` +- [Issue #123](https://github.com/ktmeaton/ncov-recombinant/issues/123): `XAD` +- [Issue #122](https://github.com/ktmeaton/ncov-recombinant/issues/122): `XAE` +- [Issue #120](https://github.com/ktmeaton/ncov-recombinant/issues/120): `XAF` +- [Issue #121](https://github.com/ktmeaton/ncov-recombinant/issues/119): `XAG` +- [Issue #119](https://github.com/ktmeaton/ncov-recombinant/issues/119): `XAH` +- [Issue #117](https://github.com/ktmeaton/ncov-recombinant/issues/117): `XAJ` +- [Issue #116](https://github.com/ktmeaton/ncov-recombinant/issues/116): `XAK` +- [Issue #115](https://github.com/ktmeaton/ncov-recombinant/issues/115): `XAL` +- [Issue #110](https://github.com/ktmeaton/ncov-recombinant/issues/110): `XAM` +- [Issue #109](https://github.com/ktmeaton/ncov-recombinant/issues/109): `XAN` +- [Issue #108](https://github.com/ktmeaton/ncov-recombinant/issues/108): `XAP` +- [Issue #107](https://github.com/ktmeaton/ncov-recombinant/issues/107): `XAQ` +- [Issue #87](https://github.com/ktmeaton/ncov-recombinant/issues/87): `XAS` +- [Issue #105](https://github.com/ktmeaton/ncov-recombinant/issues/102): `XAT` +- [Issue #103](https://github.com/ktmeaton/ncov-recombinant/issues/103): `XAU` +- [Issue #104](https://github.com/ktmeaton/ncov-recombinant/issues/104): `XAV` +- [Issue #105](https://github.com/ktmeaton/ncov-recombinant/issues/105): `XAW` +- [Issue #85](https://github.com/ktmeaton/ncov-recombinant/issues/85): `XAY` +- [Issue #87](https://github.com/ktmeaton/ncov-recombinant/issues/87): `XAZ` +- [Issue #94](https://github.com/ktmeaton/ncov-recombinant/issues/94): `XBA` +- [Issue #114](https://github.com/ktmeaton/ncov-recombinant/issues/14): `XBB` +- [Issue #160](https://github.com/ktmeaton/ncov-recombinant/issues/160): `XBC` + +### Proposed Lineages + +- [Issue #99](https://github.com/ktmeaton/ncov-recombinant/issues/99): `proposed808` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/notes/Notes_v0.2.1.md",".md","1554","37","# v0.2.1 + +## Params + +1. New optional param `motifs` for rule `sc2rf_recombinants`. +1. New param `weeks` for new rule `plot`. +1. Removed `prev_linelist` param. + +## Output + +1. Switch from a pdf `report` to powerpoint slides for better automation. +1. Create summary plots. +1. Split `report` rule into `linelist` and `report`. +1. Output `svg` plots. + +## Workflow + +1. New rule `plot`. +1. Changed growth calculation from a comparison to the previous week to a score of sequences per day. +1. Assign a `cluster_id` according to the first sequence observed in the recombinant lineage. +1. Define a recombinant lineage as a group of sequences that share the same: + - Lineage assignment + - Parents + - Breakpoints or phylogenetic placement (subtree) +1. For some sequences, the breakpoints are inaccurate and shifted slightly due to ambiguous bases. These sequences can be assigned to their corresponding cluster because they belong to the same subtree. +1. For some lineages, global prevalence has exceeded 500 sequences (which is the subtree size used). Sequences of these lineages are split into different subtrees. However, they can be assigned to the correct cluster/lineage, because they have the same breakpoints. +1. Confirmed not to use deletions define recombinants and breakpoints (differs from published)? + +## Programs + +1. Move `sc2rf_recombinants.py` to `postprocess.py` in ktmeaton fork of `sc2rf`. +1. Add false positives filtering to `sc2rf_recombinants` based on parents and breakpoints. + +## Docs + +1. Add section `Configuration` to `README.md`. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/faq.md",".md","7555","134","## FAQ + +1. **What do I do if the workflow won't run because the directory is ""locked""?** + + ```bash + snakemake --profile profiles/tutorial --unlock + ``` + +1. **How do I troubleshoot workflow errors?** + + - Start with investigating the logfile of the rule that failed. + + ![rule_log_output](../../../images/rule_log_output.png) + + - [Issue submissions](https://github.com/ktmeaton/ncov-recombinant/issues) are welcome and greatly appreciated! + +1. **How do I troubleshoot SLURM errors?** + + - If the workflow was dispatched with `scripts/slurm.sh`, the master log will be stored at: `logs/ncov-recombinant/ncov-recombinant__.log` + + > - **Tip**: Display log of most recent workflow: `cat $(ls -t logs/ncov-recombinant/*.log | head -n 1)` + +1. **Why is the pipeline exiting with `ConnectionError` or `HTTPSError`?** + + Network connection issues can occur in the rule `sc2rf_recombinants`, where the [LAPIS API](https://lapis-docs.readthedocs.io/en/latest/) is used to query [covSPECTRUM](https://cov-spectrum.org/explore/World) in order to identify the most likely parental lineages. For troubleshooting and solutions, please see [Issue #202](https://github.com/ktmeaton/ncov-recombinant/issues/202) and [Issue #201](https://github.com/ktmeaton/ncov-recombinant/issues/201). + +1. **How do I cleanup all the output from a previous run?** + + ```bash + snakemake --profile profiles/tutorial --delete-all-output + ``` + +1. **Why are some lineages called `X*-like`?** + + A cluster of sequences may be flagged as `-like` if one of following criteria apply: + + 1. The lineage assignment by [Nextclade](https://github.com/nextstrain/nextclade) conflicts with the published breakpoints for a designated lineage (`resources/breakpoints.tsv`). + + - Ex. An `XE` assigned sample has breakpoint `11538:12879` which conflicts with the published `XE` breakpoint (`ex. 8394:12879`). This will be renamed `XE-like`. + + 1. The cluster has 10 or more sequences, which share at least 3 private mutations in common. + + - Ex. A large cluster of sequences (N=50) are assigned `XM`. However, these 50 samples share 5 private mutations `T2470C,C4586T,C9857T,C12085T,C26577G` which do not appear in true `XM` sequences. This will be renamed `XM-like`. Upon further review of the reported matching [pango-designation issues](https://github.com/cov-lineages/pango-designation/issues) (`460,757,781,472,798`), we find this cluster to be a match to `proposed798`. + +1. **Why are some lineages classified as ""positive"" recombinants but have no information about their parents or breakpoints?** + + There are 8 recombinant lineages that _can_ be identified by `nextclade` but _cannot_ be verified by `sc2rf`. When sequences of these lineages are detected by `nextclade`, they will be automatically passed (""autopass"") through `sc2rf` as positives. As a result, these sequences will typically have `NA` values under columns such as `parents_clade` and `breakpoints`. + + 1. `XN` | [Issue #137](https://github.com/ktmeaton/ncov-recombinant/issues/137) | Breakpoints lie at the extreme 5' end of the genome. + 1. `XP` | [Issue #136](https://github.com/ktmeaton/ncov-recombinant/issues/137) | Breakpoints lie at the extreme 3' end of the genome. + 1. `XAN` | [Issue #109](https://github.com/ktmeaton/ncov-recombinant/issues/109) | Excessive noise/intermissions from conflicting reversions, fails intermission-allele ratio. + 1. `XAR` | [Issue #106](https://github.com/ktmeaton/ncov-recombinant/issues/106) | Breakpoints lie at the extreme 5' end of the genome. + 1. `XAS` | [Issue #86](https://github.com/ktmeaton/ncov-recombinant/issues/86) | The first parent cannot be differentiated between `BA.5` and `BA.4` (without using deletions). + 1. `XAV` | [Issue #104](https://github.com/ktmeaton/ncov-recombinant/issues/104) | Excessive noise/intermissions from conflicting reversions, fails intermission-allele ratio. + 1. `XAZ` | [Issue #87](https://github.com/ktmeaton/ncov-recombinant/issues/87) | There are no ""diagnostic"" mutations from the second parent (`BA.2`). + 1. `XBK` | [Issue #106](https://github.com/ktmeaton/ncov-recombinant/issues/106) | Breakpoints lie at the extreme 5' end of the genome. + + The setting for auto-passing certain lineages is located in `defaults/parameters.yaml` under the section `sc2rf_recombinants` and `auto_pass`. + +1. **How are the immune-related statistics calculated (ex. `rbd_level`, `immune_escape`, `ace2_binding`)?** + + These are obtained from `nextclade`, the `Nextstrain` team, and Jesse Bloom's group: + + - + - + - + - + - + - + +1. **How do I change the parameters for a rule?** + + - Find the rule you are interested in customizing in `defaults/parameters.yaml`. For example, maybe you want recombinants visualized by `division` rather than `country`. + + ```yaml + # --------------------------------------------------------------------------- + # geo : Column to use for a geographic summary (typically region, country, or division) + - name: linelist + geo: country + ``` + + - Then copy over the defaults into your custom profile (`my_profiles/custom/builds.yaml`), and adjust the yaml formatting. Note that `- name: linelist` has become `linelist:` which is idented to be flush with the `sequences:` parameter. + + ```yaml + - name: custom + metadata: data/custom/metadata.tsv + sequences: data/custom/sequences.fasta + + linelist: + geo: division + ``` + +1. **How do I include more of my custom metadata columns into the linelists?** + + - By default, the mandatory columns `strain`, `date`, and `country` will appear from your metadata. + - Extra columns can be supplied as a parameter to `summary` in your `builds.yaml` file. + - In the following example, the columns `division`, and `genbank_accession` will be extracted from your input `metadata.tsv` file and included in the final linelists. + + ```yaml + - name: controls + metadata: data/controls/metadata.tsv + sequences: data/controls/sequences.fasta + + summary: + extra_cols: + - genbank_accession + - division + ``` + +1. **Where can I find the plotting data?** + + - A data table is provided for each plot: + + - Plot: `results/tutorial/plots/lineage.png` + - Table: `results/tutorial/plots/lineage.tsv` + - The rows are the epiweek, and the columns are the categories (ex. lineages) + +1. **Why are ""positive"" sequences missing from the plots and slides?** + + - First check and see if they are in `plots_historical` and `report_historical` which summarize all sequences regardless of collection date. + - The most likely reason is that these sequences fall outside of the reporting period. + - The default reporting period is set to 16 weeks before the present. + - To change it for a build, add custom `plot` parameters to your `builds.yaml` file. + + ```yaml + - name: custom + metadata: data/custom/metadata.tsv + sequences: data/custom/sequences.fasta + + plot: + min_date: ""2022-01-10"" + max_date: ""2022-04-25"" # Optional, can be left blank to use current date + ``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/controls.md",".md","1810","41","## Controls + +### Genbank + +- After completing the tutorial, a good next step is to run the `controls` build. +- This build analyzes publicly available sequences in [`data/controls`](https://github.com/ktmeaton/ncov-recombinant/tree/master/data/controls), which include recombinant (""positive"") and non-recombinant (""negative"") sequences. +- Instructions for how to include the `controls` in your custom build are in the [configuration](https://github.com/ktmeaton/ncov-recombinant#configuration) Configuration section. + +1. Run the workflow. + + ```bash + snakemake --profile profiles/controls + ``` + +### GISAID + +- For GISAID users, a [comprehensive strain list](https://github.com/ktmeaton/ncov-recombinant/blob/master/data/controls-gisaid/strains.txt) is provided that includes all designated recombinants to date (`XA` - `XBE`). This dataset includes 600+ sequences, and can be used for in-depth validation and testing. +- It is recommended to use the ""Input for the Augur pipeline"" option, to download a `tar` compressed archive of metadata and sequences to `data/controls-gisaid/`. + [![gisaid_download](../../../images/gisaid_download.png)](https://www.epicov.org/) + +1. Prep the input metadata and sequences. + + ```bash + cd data/controls-gisaid + tar -xvf gisaid_auspice_input_hcov-19_*.tar + mv *sequences.fasta sequences.fasta + # Retain minimal metadata columns, to avoid non-ascii characters + csvtk cut -t -l -f 'strain,date,country,gisaid_epi_isl,pangolin_lineage' *.metadata.tsv > metadata.tsv + cd ../.. + ``` + +1. Run the workflow. + + ```bash + # Option 1: Local testing + snakemake --profile profiles/controls-gisaid + + # Option 2: High Performance Computing with SLURM + scripts/slurm.sh --profile profiles/controls-gisaid + ``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/install.md",".md","327","16","## Install + +1. Clone the repository: + + ```bash + git clone https://github.com/ktmeaton/ncov-recombinant.git + cd ncov-recombinant + ``` + +2. Install dependencies in a conda environment (`ncov-recombinant`): + + ```bash + mamba env create -f workflow/envs/environment.yaml + conda activate ncov-recombinant + ``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/output.md",".md","1898","35","## Output + +### Tables + +Linelists are collated into a spreadsheet for excel/google sheets: + +1. `lineage`: The recombinant lineages observed. +1. `parents`: The parental combinations observed. +1. `linelist`: Results from all input sequences (minimal statistics). +1. `summary`: Results from all input sequences (all possible statistics, for troubleshooting). +1. `positives`: Results from sequences classified as a recombinant, as verified by breakpoint detection with [sc2rf](https://github.com/lenaschimmel/sc2rf). +1. `false_positives`: Results from sequences flagged as recombinants by Nextclade, that were not verified by [sc2rf](https://github.com/lenaschimmel/sc2rf). +1. `negatives`: Results from sequences classifed as a non-recombinant by nextclade. +1. `issues`: Metadata of issues related to recombinant lineages posted in the [pango-designation](https://github.com/cov-lineages/pango-designation/issues) repository. + +![excel_output](../../../images/excel_output.png) + +### Slides + +Powerpoint/google slides with plots embedded for presenting. + +![powerpoint_output](../../../images/powerpoint_output.png) + +### Breakpoints + +Visualization of breakpoints by parental clade and parental lineage. + +| Clade | Lineage | +|:--------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------------:| +| ![breakpoints_clade_v0.7.0](../../../images/breakpoints_clade_v0.7.0.png) | ![breakpoints_lineage_v0.7.0](../../../images/breakpoints_lineage_v0.7.0.png) | + +Visualization of parental alleles and mutations from [sc2rf](https://github.com/lenaschimmel/sc2rf). + +![sc2rf_output](../../../images/sc2rf_output.png) +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/description.md",".md","1005","11","[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/ktmeaton/ncov-recombinant/blob/master/LICENSE) +[![GitHub issues](https://img.shields.io/github/issues/ktmeaton/ncov-recombinant.svg)](https://github.com/ktmeaton/ncov-recombinant/issues) +[![Install CI](https://github.com/ktmeaton/ncov-recombinant/actions/workflows/install.yaml/badge.svg)](https://github.com/ktmeaton/ncov-recombinant/actions/workflows/install.yaml) +[![Pipeline CI](https://github.com/ktmeaton/ncov-recombinant/actions/workflows/pipeline.yaml/badge.svg)](https://github.com/ktmeaton/ncov-recombinant/actions/workflows/pipeline.yaml) + +Reproducible workflow for SARS-CoV-2 recombinant sequence detection. + +1. Align sequences and perform clade/lineage assignments with [Nextclade](https://github.com/nextstrain/nextclade). +1. Identify parental clades and plot recombination breakpoints with [sc2rf](https://github.com/lenaschimmel/sc2rf). +1. Create tables, plots, and powerpoint slides for reporting. +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/high-performance-computing.md",".md","3357","82","## High Performance Computing + +`ncov-recombinant` can alternatively be dispatched using the SLURM job submission system. + +1. Create an HPC-compatible profile to store your build configuration. + + ```bash + scripts/create_profile.sh --data data/custom --hpc + ``` + + ```text + 2022-06-17 09:16:55 Searching for metadata (data/custom/metadata.tsv) + 2022-06-17 09:16:55 SUCCESS: metadata found + 2022-06-17 09:16:55 Checking for 3 required metadata columns (strain date country) + 2022-06-17 09:16:55 SUCCESS: 3 columns found. + 2022-06-17 09:16:55 Searching for sequences (data/custom/sequences.fasta) + 2022-06-17 09:16:55 SUCCESS: Sequences found + 2022-06-17 09:16:55 Checking that the metadata strains match the sequence names + 2022-06-17 09:16:55 SUCCESS: Strain column matches sequence names + 2022-06-17 09:16:55 Creating new profile directory (my_profiles/custom-hpc) + 2022-06-17 09:16:55 Creating build file (my_profiles/custom-hpc/builds.yaml) + 2022-06-17 09:16:55 Adding default input data (defaults/inputs.yaml) + 2022-06-17 09:16:55 Adding custom input data (data/custom) + 2022-06-17 09:16:55 Adding `custom` as a build + 2022-06-17 09:16:55 Creating system configuration (my_profiles/custom-hpc/config.yaml) + 2022-06-17 09:16:55 Adding default HPC system resources + 2022-06-17 09:16:55 System resources can be further configured in: + + my_profiles/custom-hpc/config.yaml + + 2022-06-17 09:16:55 Builds can be configured in: + + my_profiles/custom-hpc/builds.yaml + + 2022-06-17 09:16:55 The custom-hpc profile is ready to be run with: + + scripts/slurm.sh --profile my_profiles/custom-hpc + ``` + +2. Edit `my_profiles/custom-hpc/config.yaml` to specify the number of `jobs` and `default-resources` to use. + + ```yaml + # Maximum number of jobs to run simultaneously + jobs : 4 + + # Default resources for a SINGLE JOB + default-resources: + - cpus=64 + - mem_mb=64000 + - time_min=720 + ``` + +3. Dispatch the workflow using the slurm wrapper script: + + ```bash + scripts/slurm.sh --profile my_profiles/custom-hpc + ``` + + > - **Tip**: Display log of most recent workflow: `cat $(ls -t logs/ncov-recombinant/*.log | head -n 1)` + +4. Use the `--help` parameter to get additional options for SLURM dispatch. + + ```bash + scripts/slurm.sh --help + ``` + + ```text + usage: bash slurm.sh [-h] [--profile PROFILE] [--conda-env CONDA_ENV] [--target TARGET] [--cpus CPUS] [--mem MEM] + + Dispatch a Snakemake pipeline using SLURM. + + Required arguments: + --profile PROFILE Snakemake profile to execute (ex. profiles/tutorial-hpc) + + Optional arguments: + --conda-env CONDA_ENV Conda environment to use. (default: ncov-recombinant) + --target TARGET Snakemake target(s) to execute (default: all) + --cpus CPUS CPUS to use for the main pipeline. (default: 1) + --mem MEM Memory to use for the ain pipeline. (default: 4GB) + -h, --help Show this help message and exit. + ``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/what_is_a_recombinant.md",".md","2782","31","## What is recombination? + +Recombination is an evolutionary mechanism where two distinct organisms exchange genetic code to produce a chimeric genome ([VanInsberghe et al. 2021](https://https://doi.org/10.1093/ve/veab059)). This manifests as a novel combination of alleles into blocks or ""chunks"" across the genome (Figure 1). + +Recombination is of particular concern for genomic surveillance, because it can lead to _substantial genetic change_ over a _short period of time_. Public health programs take into account this _rate of genetic change_ to inform policy recommendations, such as vaccine effectiveness and booster frequency ([Malik et al. 2022](https://doi.org/10.1016/j.jiph.2021.12.014)). + +SARS-CoV-2 has an estimated _substitution rate_ of 2 substitutions/month or 24 substitutions/year ([Tay et al. 2022](https://doi.org/10.1093/molbev/msac013)). However, the _recombination_ event that led to the Delta-Omicron recombinant `XD` produced a chimeric Delta genome with 25 new substitutions originating from Omicron (Figure 1). This single event produced the same amount of mutations as would have been expected over the course of a year. While more mutations are not necessarily beneficial to the organism, there remains the concerning possibility that recombination can rapidly increase the infectivity and severity of a pathogen. + +![breakpoints_XD_v0.7.0](../../../images/breakpoints_XD_v0.7.0.png) + +Figure 1. Genomic composition of the Delta-Omicron recombinant `XD`. + +### Pipeline Definition + +A recombinant SARS-CoV-2 lineage is defined as sequences with unique combinations of: + +1. Lineage assignment (ex. `XD`) +1. Parental clades (ex. `Delta`/`Omicron`/`Delta`) +1. Parental lineages (ex. `AY.4`/`BA.1`/`AY.4`) +1. Breakpoint intervals (ex. Breakpoint 1: `21988-22672`, Breakpoint 2: `25470-25583`) + +If two sequences share the same lineage assignment (`XD`) and parental clades (ex. `Delta`/`Omicron`) but differ in their parental lineages (`AY.4`/`BA.1`/`AY.4` vs. `AY.44`/`BA.1`/`AY.44`), they will be classified as distinct recombinant lineages. The sequence with parental lineages `AY.44`/`BA.1`/`AY.444` will be renamed `XD-like`. This indicates that its closest known lineage is `XD` but that it differs from the expected genomic composition of true `XD`. + +### Designated Recombinants + +Designated recombinants from [pango-designation](https://github.com/cov-lineages/pango-designation) can be identified in the ""positives"" pipeline output by a lineage assignment that starts with `X` (ex. `XD`, `XBB`). + +### Novel Recombinants + +Novel recombinants (i.e. undesignated) can be identified in the ""positives"" pipeline output by a lineage assignment that _does not_ start with `X*` (ex. `BA.1.1`) _or_ with a lineage assignment that contains `-like` (ex. `XM-like`). +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/update.md",".md","1398","28","## Update + +> **Tip**: It is recommended to do a fresh install in a separate directory to test a newer version. + +After pulling a fresh copy of the git repository, don't forget to update your conda environment! + +```bash +mamba env update -f workflow/envs/environment.yaml +``` + +After running the newly installed version, you can compare lineage assignment changes using the following script: + +```bash +python3 scripts/compare_positives.py \ + --positives-1 old_pipeline_ver/results/controls/linelists/positives.tsv \ + --positives-2 new_pipeline_ver/results/controls/linelists/positives.tsv \ + --ver-1 ""old_ver"" \ + --ver-2 ""new_ver"" \ + --outdir compare/controls \ + --node-order alphabetical +``` + +A comparative report is provided for each major or minor release: + +- `v0.6.1` → `v0.7.0` : [docs/testing_summary_package/ncov-recombinant_v0.6.1_v0.7.0.html](https://ktmeaton.github.io/ncov-recombinant/docs/testing_summary_package/ncov-recombinant_v0.6.1_v0.7.0.html) +- `v0.5.1` → `v0.6.0` : [docs/testing_summary_package/ncov-recombinant_v0.5.1_v0.6.0.html](https://ktmeaton.github.io/ncov-recombinant/docs/testing_summary_package/ncov-recombinant_v0.5.1_v0.6.0.html) +- `v0.4.2` → `v0.5.0` : [docs/testing_summary_package/ncov-recombinant_v0.4.2_v0.5.0.html](https://ktmeaton.github.io/ncov-recombinant/docs/testing_summary_package/ncov-recombinant_v0.4.2_v0.5.0.html) +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/tutorial.md",".md","1142","31","## Tutorial + +> **Tip**: Remember to run `conda activate ncov-recombinant` first! + +1. Preview the steps that are going to be run. + + ```bash + snakemake --profile profiles/tutorial --dryrun + ``` + +1. Run the workflow. + + ```bash + snakemake --profile profiles/tutorial + ``` + +1. Explore the Output. + + - Slides | `results/tutorial/report/report.pptx` + - Tables* | `results/tutorial/report/report.xlsx` + - Plots + - Reporting Period (default: last 16 weeks): `results/tutorial/plots` + - All sequences: `results/tutorial/plots_historical` + - Breakpoints + - By parental clade: `results/tutorial/plots_historical/breakpoints_clade.png` + - By parental lineage: `results/tutorial/plots_historical/breakpoints_lineage.png` + - Alleles | `results/tutorial/sc2rf/recombinants.ansi.txt` + +* Individual tables are available as TSV linelists in `results/tutorial/linelists`. + Visualize sc2rf mutations with `less -S` or [Visual Studio ANSI Colors](https://marketplace.visualstudio.com/items?itemName=iliazeus.vscode-ansi). +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/credits.md",".md","5367","39","## Credits + +[ncov-recombinant](https://github.com/ktmeaton/ncov-recombinant) is built and maintained by [Katherine Eaton](https://ktmeaton.github.io/) at the [National Microbiology Laboratory (NML)](https://github.com/phac-nml) of the Public Health Agency of Canada (PHAC). + + + + + +

Katherine Eaton

💻 📖 🎨 🤔 🚇 🚧
+ +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + + + + + + + + + +

Nextstrain (Nextclade)

🔣 🔌

Lena Schimmel (sc2rf)

🔌

Yatish Turakhia (UShER)

🔣 🔌

Angie Hinrichs (UShER)

🔣 🔌

Benjamin Delisle

🐛 ⚠️

Vani Priyadarsini Ikkurthi

🐛 ⚠️

Mark Horsman

🤔 🎨

Jesse Bloom Lab

🔣 🔌

Dan Fornika

🤔 ⚠️

Tara Newman
🤔 ⚠️
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/developers_guide.md",".md","8590","205","## Developer's Guide + +There are three main triggers to initate new development: + +1. A new [lineage dataset](https://github.com/nextstrain/nextclade_data/releases) has been released. +1. A new [nextclade-cli](https://github.com/nextstrain/nextclade/releases) has been released. +1. A new [recombinant lineage has been proposed](https://github.com/cov-lineages/pango-designation/issues?q=recombinant). +1. A new [recombinant lineage has been designated](https://github.com/cov-lineages/pango-designation/milestones). + - New designations _should_ be labelled as milestones. + +Beging by creating a development conda environment. + +```bash +mamba env create -f workflow/envs/environment.yaml -n ncov-recombinant-dev +``` + +> **Note**: After completing a development trigger, proceed with the Validation section. + +### Trigger 1 | New Lineage Dataset + +1. Obtain the new dataset tag from . + +1. Update all 3 dataset tags in `defaults/parameters.yaml`. + + For example, change all strings of `""2022-10-27T12:00:00Z""` to the new dataset tag for November such as `""2022-11-27T12:00:00Z""`. + + ```yaml + - name: nextclade_dataset + dataset: sars-cov-2 + tag: ""2022-10-27T12:00:00Z"" + dataset_no-recomb: sars-cov-2-no-recomb + tag_no-recomb: ""2022-10-27T12:00:00Z"" + dataset_immune-escape: sars-cov-2-21L + tag_immune-escape: ""2022-10-27T12:00:00Z"" + ``` + +### Trigger 2 | New Nextclade CLI + +1. Check that the new nextclade-cli has been made available on conda: +1. Update the following line in `workflow/envs/environment.yaml` to the newest version: + + ```yaml + - bioconda::nextclade=2.8.0 + ``` + +1. Update the development conda environment. + + ```bash + mamba env update -f workflow/envs/environment.yaml -n ncov-recombinant-dev + ``` + +### Trigger 3 | New Proposed Lineage + +1. Create a new data directory. + + ```bash + mkdir -p data/proposedXXX + ``` + +1. Check the corresponding [pango-designation issue](https://github.com/cov-lineages/pango-designation/issues?q=recombinant) for a list of GISAID accessions. + +1. Download 10 of these GISAID accessions from . Please review the GISAID Download section to ensure the sequences and metadata are correctly formatted. + +1. Create a new pipeline profile for this lineage. + + ```bash + scripts/create_profile.sh --data data/proposedXXX + ``` + +1. Run the pipeline up to `sc2rf` breakpoint detection. + + ```bash + snakemake --profile my_profiles/proposedXXX results/proposedXXX/sc2rf/stats.tsv + ``` + + When finished, check the stats file and confirm whether `sc2rf_status` is `positive`, `sc2rf_parents` match the pango-designation issue information. If so, skip to the Validation section. + + ```bash + csvtk pretty -t results/proposedXXX/sc2rf/stats.tsv | less -S + + # Or + csvtk cut -t -f ""strain,sc2rf_status,sc2rf_parents,sc2rf_breakpoints"" results/XBB/sc2rf/stats.tsv + ``` + +1. Update/create `sc2rf` modes. + + If `sc2rf_status` is not `positive`, command-line parameters for `sc2rf` will need to be tweaked. To begin with, run `sc2rf` manually with the following debugging parameters. And changing `--clades BA.2 BA.5.2` to a space separated list of potential parents. + + ```bash + python3 sc2rf/sc2rf.py results/proposedXXX/nextclade/alignment.fasta \ + --ansi \ + --max-ambiguous 20 \ + --max-intermission-length 2 \ + --ignore-shared \ + --mutation-threshold 0.25 \ + --max-intermission-count 20 \ + --parents 0-10 \ + --breakpoints 0-10 \ + --unique 0 \ + --clades BA.2 BA.5.2 + ``` + + If the potential parents don't appear in the output, they will need to be added to `sc2rf/mapping.csv` and the allele frequency database updated with: + + ```bash + cd sc2rf/ + python3 sc2rf.py --rebuild-examples + cd .. + ``` + + Then rerun the previous command and verify that the parents appear in the output. The next step is to increase the stringency of `--parents`, `--breakpoints`, `--unique`, and `--max-intermission-count` as much as possible. + + Once a parameter set is found, review the existing `sc2rf` modes in `defaults/parameters.yaml`. It is ideal to have as few modes as possible, so the first check is to see whether the new parameter set can be integrated into an existing mode. Failing that, a new mode should be created in the list to capture this recombinant. + + ```yaml + - name: sc2rf + mode: + # Lineage specific validation) + - XA: ""--clades 20I 20E 20F 20D --ansi --parents 2 --breakpoints 1-3 --unique 2 --max-ambiguous 20 --max-intermission-length 2 --max-intermission-count 3 --ignore-shared --mutation-threshold 0.25"" + ... + # Current Variants of Concern and Dominant Lineages + - voc: ""--clades BA.2.10 BA.2.3.17 BA.2.3.20 BA.2.75 BA.4.6 BA.5.2 BA.5.3 XBB --ansi --parents 2-4 --breakpoints 1-5 --unique 1 --max-ambiguous 20 --max-intermission-length 2 --max-intermission-count 3 --ignore-shared --mutation-threshold 0.25"" + ``` + +1. Repeat steps 5 and 6, until the recombinant is successully identified by `sc2rf`. + +### Trigger 4 | New Designated Lineage + +1. Complete all steps for Trigger 3 | New Proposed Lineage except: + + - Include no more than 10 representative sequences. + - Make the data directory `data/X*` instead of `data/proposed*`. + +1. Add the new designated lineage to the `controls-gisaid` dataset. + + ```bash + data_dir=""data/XBM"" + + # Add in new control strains + csvtk cut -t -f ""strain"" ${data_dir}/metadata.tsv | tail -n+2 >> data/controls-gisaid/strains.txt + + # Add in new control metadata + cols=$(csvtk headers -t data/controls-gisaid/metadata.tsv | tr ""\n"" "","" | sed 's/,$/\n/g') + csvtk cut -t -f ""$cols"" ${data_dir}/metadata.tsv | tail -n+2 >> data/controls-gisaid/metadata.tsv + + # Add in new control sequences + cat ${data_dir}/sequences.fasta >> data/controls-gisaid/sequences.fasta + ``` + +### Validation + +Run the following profiles to validate the new changes. These profiles all contain strains with expected pipeline output in `defaults/validation.tsv`. + +1. Tutorial + + ```bash + scripts/slurm.sh --profile profiles/tutorial --conda-env ncov-recombinant-dev + ``` + +2. Genbank Controls + + ```bash + scripts/slurm.sh --profile profiles/controls-hpc --conda-env ncov-recombinant-dev + ``` + +3. GISAID Controls + + ```bash + scripts/slurm.sh --profile profiles/controls-gisaid-hpc --conda-env ncov-recombinant-dev + ``` + +If the pipeline failed validation, check the end of the log for details. + +```bash +less -S logs/ncov-recombinant/tutorial_$(date +'%Y-%m-%d').log +``` + +If the column that failed is only `lineage`, because lineage assignments have changed with the new nextclade dataset, simply update the values in `defaults/validation.tsv`. This is expected when upgrading nextclade-cli or the nextclade dataset. + +If the column that failed is `breakpoints` or `parents_clade`, this indicates a more complicated issue with breakpoint detection. The most common reason is because `sc2rf` modes has been changed to capture a new lineage (see Trigger 3 for more information). This presents an optimization challenge, and is solved by working through steps 5 and 6 of Trigger 3 | New Proposed Lineage until sensitivity and specificity are restore for all lineages. + +Once validation is completed successfully for all profiles, update `defaults/validation.tsv` as follows: + +```bash +# Construct headers +echo -e ""strain\tstatus\tlineage\tbreakpoints\tparents_clade\tdataset"" > defaults/validation.tsv + +# Tutorial +csvtk cut -t -f ""strain,status,lineage,breakpoints,parents_clade"" results/tutorial/linelists/linelist.tsv \ + | tail -n+2 \ + >> defaults/validation.tsv + +# Controls Genbank +csvtk cut -t -f ""strain,status,lineage,breakpoints,parents_clade"" results/controls/linelists/linelist.tsv \ + | csvtk mutate2 -t -n ""dataset"" -e '""controls""' \ + | tail -n+2 \ + >> defaults/validation.tsv + +# Controls GISAID +csvtk cut -t -f ""strain,status,lineage,breakpoints,parents_clade"" results/controls-gisaid/linelists/linelist.tsv \ + | csvtk mutate2 -t -n ""dataset"" -e '""controls-gisaid""' \ + | tail -n+2 \ + >> defaults/validation.tsv +``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/conf.py",".py","1034","31","# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +import sphinx_rtd_theme + +project = ""ncov-recombinant"" +copyright = ""2023, Katherine Eaton"" +author = ""Katherine Eaton"" +release = ""v0.7.0"" + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [""myst_parser"", ""sphinx_rtd_theme""] + +templates_path = [""_templates""] +exclude_patterns = [] + + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +# html_theme = ""alabaster"" +html_theme = ""sphinx_rtd_theme"" +html_static_path = [""_static""] +","Python" +"Microbiology","ktmeaton/ncov-recombinant","docs/sphinx/source/configuration.md",".md","3298","84","## Configuration + +1. Create a new directory for your data. + + ```bash + mkdir -p data/custom + ``` + +1. Copy over your unaligned `sequences.fasta` and `metadata.tsv` to `data/custom`. + + > - **Note**: GISAID sequences and metadata can be downloaded using the ""Input for the Augur pipeline"" option on . + > - `metadata.tsv` MUST have at minimum the columns `strain`, `date`, `country`. + > If collection dates or country are unknown, these fields can be left empty or filled with ""NA"". + > - The first column MUST be `strain`. + +1. Create a profile for your custom build. + + ```bash + scripts/create_profile.sh --data data/custom + ``` + + ```text + 2022-06-17 09:15:06 Searching for metadata (data/custom/metadata.tsv) + 2022-06-17 09:15:06 SUCCESS: metadata found + 2022-06-17 09:15:06 Checking for 3 required metadata columns (strain date country) + 2022-06-17 09:15:06 SUCCESS: 3 columns found. + 2022-06-17 09:15:06 Searching for sequences (data/custom/sequences.fasta) + 2022-06-17 09:15:06 SUCCESS: Sequences found + 2022-06-17 09:15:06 Checking that the metadata strains match the sequence names + 2022-06-17 09:15:06 SUCCESS: Strain column matches sequence names + 2022-06-17 09:15:06 Creating new profile directory (my_profiles/custom) + 2022-06-17 09:15:06 Creating build file (my_profiles/custom/builds.yaml) + 2022-06-17 09:15:06 Adding default input data (defaults/inputs.yaml) + 2022-06-17 09:15:06 Adding custom input data (data/custom) + 2022-06-17 09:15:06 Adding `custom` as a build + 2022-06-17 09:15:06 Creating system configuration (my_profiles/custom/config.yaml) + 2022-06-17 09:15:06 Adding default system resources + 2022-06-17 09:15:06 Done! The custom profile is ready to be run with: + + snakemake --profile my_profiles/custom + ``` + + > - **Note**: you can add the param `--controls` to add the `controls` build that will run in parallel. + +1. Edit `my_profiles/custom/config.yaml`, so that the `jobs` and `default-resources` match your system. + + > **Note**: For HPC environments, see the High Performance Computing section. + + ```yaml + #------------------------------------------------------------------------------# + # System config + #------------------------------------------------------------------------------# + + # Maximum number of jobs to run simultaneously + jobs : 1 + + # Default resources for a SINGLE JOB + default-resources: + - cpus=1 + - mem_mb=4000 + - time_min=60 + ``` + +1. Do a ""dry run"" to confirm setup. + + ```bash + snakemake --profile my_profiles/custom --dry-run + ``` + +1. Run your custom profile. + + ```bash + snakemake --profile my_profiles/custom + ``` + +--- + +> **Important**: If you are doing routine production analyses, it is recommend to first delete all previous output before running your profile. This will force `ncov-recombinant` to download fresh copies of the pango-designation issues (`resources/issues.tsv`) and the lineage phylogeny (`resources/tree.nwk`). + +```bash +snakemake --profile my_profiles/custom --delete-all-output +snakemake --profile my_profiles/custom +``` +","Markdown" +"Microbiology","ktmeaton/ncov-recombinant","scripts/compare_positives.py",".py","14094","461","#!/usr/bin/env python3 + +import click +import pandas as pd +import plotly.graph_objects as go +import plotly.io as pio +from matplotlib import colors +import os +from functions import create_logger +import copy + +NO_DATA_CHAR = ""NA"" +SOURCE_CHAR = ""*"" +TARGET_CHAR = ""†"" +UNKNOWN_COLOR = ""dimgrey"" +UNKNOWN_RGB = colors.to_rgb(UNKNOWN_COLOR) + +LINEAGE_COLS = [""recombinant_lineage_curated"", ""lineage"", ""pango_lineage""] + + +def create_sankey_data(df, node_order=""default"", min_y=0.001, min_link_size=1): + + # ------------------------------------------------------------------------- + # Links + + link_data = { + ""source"": [], + ""target"": [], + ""value"": [], + ""color"": None, + } + + for rec in df.iterrows(): + source = rec[1][""source""] + target = rec[1][""target""] + + # Iterate through source/target to find a match + match_found = False + + for i in range(0, len(link_data[""source""])): + s = link_data[""source""][i] + t = link_data[""target""][i] + + # Found a match + if s == source and t == target: + match_found = True + link_data[""value""][i] += 1 + + # If a match wasn't found + if not match_found: + link_data[""source""].append(source) + link_data[""target""].append(target) + link_data[""value""].append(1) + + # ------------------------------------------------------------------------- + # Filter on minimum link size + + remove_link_i = [] + for i, v in enumerate(link_data[""value""]): + s = link_data[""source""][i] + t = link_data[""target""][i] + + if v < min_link_size: + remove_link_i.append(i) + + # Delete links in reverse index order + for i in sorted(remove_link_i, reverse=True): + del link_data[""source""][i] + del link_data[""target""][i] + del link_data[""value""][i] + + # Create source and target nodes links + source_node_links = {} + target_node_links = {} + for source, target, value in zip( + link_data[""source""], link_data[""target""], link_data[""value""] + ): + if source not in source_node_links: + source_node_links[source] = 0 + if target not in target_node_links: + target_node_links[target] = 0 + + # Incrememnt count of these nodes + source_node_links[source] += value + target_node_links[target] += value + + # ------------------------------------------------------------------------- + # Node Palette + + # labels = list(set(list(df[""source""]) + list(df[""target""]))) + labels = list(set(list(source_node_links.keys()) + list(target_node_links.keys()))) + labels_i = {label: i for i, label in enumerate(labels)} + + node_palette = [] + for label in labels: + if label.startswith(NO_DATA_CHAR): + node_palette.append(UNKNOWN_COLOR) + else: + node_palette.append(""#1f77b4"") + + # ------------------------------------------------------------------------- + # Nodes + + node_data = { + ""pad"": 15, + ""thickness"": 20, + ""line"": dict(color=""black"", width=0.5), + ""label"": labels, + ""color"": node_palette, + ""x"": [], + ""y"": [], + } + + # ------------------------------------------------------------------------- + # Link Palette + link_palette = [] + for s, t in zip(link_data[""source""], link_data[""target""]): + + # No change + color = ""rgba(212,212,212,0.8)"" # light grey + + # New (green) + if s == NO_DATA_CHAR + SOURCE_CHAR: + color = ""rgba(44,160,44,0.5)"" + + # Dropped (red) + elif t == NO_DATA_CHAR + TARGET_CHAR: + color = ""rgba(214,39,40,0.5)"" + + # Changed (orange) + elif s.rstrip(SOURCE_CHAR) != t.rstrip(TARGET_CHAR): + color = ""rgba(255,127,14,0.5)"" + + link_palette.append(color) + link_data[""color""] = link_palette + + # ------------------------------------------------------------------------- + # Node Ordering + + source_node_order = list(source_node_links.keys()) + + # Source: Order Y position alphabetically + if node_order.startswith(""alphabetical""): + source_node_no_suffix = [node[0:-1] for node in source_node_links.keys()] + source_node_order = [ + node + SOURCE_CHAR for node in sorted(source_node_no_suffix) + ] + + # Source: Order Y position by link size + elif node_order.startswith(""size""): + # List of tuples, lineage and size: [('XAW*', 1), ('XAY*', 4), ... ] + source_node_order = sorted(source_node_links.items(), key=lambda x: x[1]) + source_node_order = [kv[0] for kv in source_node_order[::-1]] + + if node_order.endswith(""rev""): + source_node_order.reverse() + + # Put NA at the end + if NO_DATA_CHAR + TARGET_CHAR in source_node_order: + source_node_order.remove(NO_DATA_CHAR + SOURCE_CHAR) + source_node_order.append(NO_DATA_CHAR + SOURCE_CHAR) + + source_node_y = {} + + if len(source_node_links) > 1: + y_buff = 1 / (len(source_node_links) - 1) + else: + y_buff = 1 + + for i, label in enumerate(source_node_order): + if i == 0: + y = min_y + elif i == len(source_node_links) - 1: + y = 0.999 + else: + y = min_y + (i * y_buff) + + source_node_y[label] = y + + # Target: Order Y position alphabetically + target_node_order = list(target_node_links.keys()) + + if node_order.startswith(""alphabetical""): + target_node_no_suffix = [node[0:-1] for node in target_node_links.keys()] + target_node_order = [ + node + TARGET_CHAR for node in sorted(target_node_no_suffix) + ] + + # Source: Order Y position by link size + elif node_order.startswith(""size""): + # List of tuples, lineage and size: [('XAW*', 1), ('XAY*', 4), ... ] + target_node_order = sorted(target_node_links.items(), key=lambda x: x[1]) + target_node_order = [kv[0] for kv in target_node_order[::-1]] + + if node_order.endswith(""rev""): + target_node_order.reverse() + + # Put NA at the end + if NO_DATA_CHAR + TARGET_CHAR in target_node_order: + target_node_order.remove(NO_DATA_CHAR + TARGET_CHAR) + target_node_order.append(NO_DATA_CHAR + TARGET_CHAR) + + target_node_y = {} + + if len(target_node_links) > 1: + y_buff = 1 / (len(target_node_links) - 1) + else: + y_buff = 1 + + for i, label in enumerate(target_node_order): + if i == 0: + y = min_y + elif i == len(target_node_links) - 1: + y = 0.999 + else: + y = min_y + (i * y_buff) + + target_node_y[label] = y + + node_x = [] + node_y = [] + + for label in labels: + if label in source_node_y: + x = 0.001 + y = source_node_y[label] + + elif label in target_node_y: + x = 0.999 + y = target_node_y[label] + + node_x.append(x) + node_y.append(y) + + # This doesn't work yet + if node_order != ""default"": + node_data[""x""] = node_x + node_data[""y""] = node_y + + # ------------------------------------------------------------------------- + + # Convert source/target to numeric ID + for i in range(0, len(link_data[""source""])): + s = link_data[""source""][i] + t = link_data[""target""][i] + + s_i = labels_i[s] + s_t = labels_i[t] + + link_data[""source""][i] = s_i + link_data[""target""][i] = s_t + + data = { + ""node"": node_data, + ""link"": link_data, + } + return data + + +def create_sankey_plot(sankey_data, node_order=""default""): + + # if node_order == ""default"": + # arrangement = ""snap"" + # else: + # arrangement = ""fixed"" + + fig = go.Figure( + data=[ + go.Sankey( + node=sankey_data[""node""], + link=sankey_data[""link""], + # arrangement=arrangement, + ) + ] + ) + return fig + + +@click.command() +@click.option(""--positives-1"", help=""First positives table (TSV)"", required=True) +@click.option(""--positives-2"", help=""Second positives table (TSV)"", required=True) +@click.option(""--ver-1"", help=""First version for title"", required=True) +@click.option(""--ver-2"", help=""Second version for title"", required=True) +@click.option(""--outdir"", help=""Output directory"", required=True) +@click.option(""--log"", help=""Logfile"", required=False) +@click.option( + ""--node-order"", + help=""Method of sorting the order of nodes"", + type=click.Choice( + [""default"", ""size"", ""alphabetical"", ""size-rev"", ""alphabetical-rev""], + case_sensitive=True, + ), + required=False, + default=""alphabetical"", +) +@click.option( + ""--min-y"", help=""Increase if nodes overlap the title"", required=False, default=0.001 +) +@click.option( + ""--min-link-size"", + help=""Remove links smaller than this"", + required=False, + default=1, +) +def main( + positives_1, + positives_2, + ver_1, + ver_2, + outdir, + log, + node_order, + min_y, + min_link_size, +): + """"""Compare positive recombinants between two tables."""""" + + # create output directory + if not os.path.exists(outdir): + os.makedirs(outdir) + # create logger + logger = create_logger(logfile=log) + + logger.info(""Parsing table: {}"".format(positives_1)) + positives_1_df = pd.read_csv(positives_1, sep=""\t"") + logger.info(""Parsing table: {}"".format(positives_2)) + positives_2_df = pd.read_csv(positives_2, sep=""\t"") + + # Try to find the lineage col for each df + for col in LINEAGE_COLS: + if col in positives_1_df.columns: + lineages_1 = positives_1_df[[""strain"", col]] + lineages_1 = lineages_1.rename(columns={col: ""source""}) + break + + for col in LINEAGE_COLS: + if col in positives_2_df.columns: + lineages_2 = positives_2_df[[""strain"", col]] + lineages_2 = lineages_2.rename(columns={col: ""target""}) + break + + logger.info(""Merging tables."") + lineages_df = pd.merge(lineages_1, lineages_2, how=""outer"", on=""strain"") + lineages_df.rename(columns={""strain"": ""id""}, inplace=True) + + # Convert NA + for rec in lineages_df.iterrows(): + source = rec[1][""source""] + target = rec[1][""target""] + + # Check for NA, which is float + if type(source) == float: + lineages_df.loc[rec[0], ""source""] = NO_DATA_CHAR + if type(target) == float: + lineages_df.loc[rec[0], ""target""] = NO_DATA_CHAR + + lineages_df.fillna(NO_DATA_CHAR, inplace=True) + + logger.info(""Calculating statistics."") + # Why all the copy statements? pandas throws errors unless we make + # a proper different copy. + new_df = copy.copy(lineages_df[lineages_df[""source""] == NO_DATA_CHAR]) + drop_df = copy.copy(lineages_df[lineages_df[""target""] == NO_DATA_CHAR]) + no_change_df = copy.copy( + lineages_df[lineages_df[""source""] == lineages_df[""target""]] + ) + change_df = copy.copy( + lineages_df[ + (lineages_df[""source""] != lineages_df[""target""]) + & (lineages_df[""source""] != NO_DATA_CHAR) + & (lineages_df[""target""] != NO_DATA_CHAR) + ] + ) + + num_sequences = len(lineages_df) + num_new = len(new_df) + num_drop = len(drop_df) + num_change = len(change_df) + num_no_change = len(no_change_df) + num_net = num_new - num_drop + + summary_df = pd.DataFrame( + { + ""statistic"": [ + ""all"", + ""no-change"", + ""change"", + ""new"", + ""drop"", + ""net"", + ], + ""count"": [ + num_sequences, + num_no_change, + num_change, + num_new, + num_drop, + num_net, + ], + } + ) + + # Put suffix char on end to separate source and target + lineages_df[""source""] = [s + SOURCE_CHAR for s in lineages_df[""source""]] + lineages_df[""target""] = [t + TARGET_CHAR for t in lineages_df[""target""]] + + title = ""ncov-recombinant {ver_1}{ver_1_char} to "".format( + ver_1=ver_1, + ver_1_char=SOURCE_CHAR, + ) + ""{ver_2}{ver_2_char}"".format( + ver_2=ver_2, + ver_2_char=TARGET_CHAR, + ) + title += ( + ""
"" + + ""Sequences: {}"".format(num_sequences) + + "", Unchanged (grey): {}"".format(num_no_change) + + "", Changed (orange): {}"".format(num_change) + + "", New (green): {}"".format(num_new) + + "", Dropped (red): {}"".format(num_drop) + + """" + ) + + # Create sankey data and plot + logger.info(""Creating sankey data."") + sankey_data = create_sankey_data( + lineages_df, node_order=node_order, min_y=min_y, min_link_size=min_link_size + ) + logger.info(""Creating sankey plot."") + sankey_fig = create_sankey_plot(sankey_data, node_order=node_order) + sankey_fig.update_layout(title_text=title, font_size=12, width=1000, height=800) + + # Rename columns in output tables from source/target to version numbers + for df in [new_df, change_df, no_change_df, drop_df]: + + df.rename(columns={""source"": ver_1}, inplace=True) + df.rename(columns={""target"": ver_2}, inplace=True) + + # ------------------------------------------------------------------------- + # Output + + prefix = os.path.join(outdir, ""ncov-recombinant_{}_{}"".format(ver_1, ver_2)) + + # Tables + logger.info(""Writing output tables to: {}"".format(outdir)) + summary_df.to_csv(prefix + ""_summary.tsv"", sep=""\t"", index=False) + new_df.to_csv(prefix + ""_new.tsv"", sep=""\t"", index=False) + drop_df.to_csv(prefix + ""_drop.tsv"", sep=""\t"", index=False) + no_change_df.to_csv(prefix + ""_no-change.tsv"", sep=""\t"", index=False) + change_df.to_csv(prefix + ""_change.tsv"", sep=""\t"", index=False) + + # Figures + logger.info(""Writing output figures to: {}"".format(outdir)) + sankey_fig.write_html(prefix + "".html"") + pio.write_image(sankey_fig, prefix + "".png"", format=""png"", scale=2) + pio.write_image(sankey_fig, prefix + "".svg"", format=""svg"", scale=2) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/rbd_levels.py",".py","3827","122","#!/usr/bin/env python3 +import click +import pandas as pd +import os +import yaml +from functions import create_logger + +NO_DATA_CHAR = ""NA"" + + +@click.command() +@click.option( + ""--rbd-definition"", help=""Key RBD mutation definitions (yaml)."", required=True +) +@click.option(""--nextclade"", help=""Nextclade qc table (tsv)."", required=True) +@click.option(""--output"", help=""Ouptut table of RBD level (tsv)."", required=True) +@click.option(""--log"", help=""Output log file."", required=False) +def main( + rbd_definition, + nextclade, + output, + log, +): + """"""Calculate the number of key RBD mutations."""""" + + # create logger + logger = create_logger(logfile=log) + + # Create output directory + outdir = os.path.dirname(output) + if not os.path.exists(outdir) and outdir != ""."" and outdir != """": + os.makedirs(outdir) + + # ------------------------------------------------------------------------- + # RBD Mutation Definitions + + # Import file + logger.info(""Parsing RBD mutation definitions: {}"".format(rbd_definition)) + with open(rbd_definition) as infile: + rbd_dict = yaml.safe_load(infile) + + # Parse into dataframe + rbd_data = {""gene"": [], ""coord"": [], ""ref"": [], ""alt"": []} + for mut in rbd_dict[""rbd_mutations""]: + rbd_data[""gene""].append(""S"") + rbd_data[""coord""].append(int(mut[1])) + rbd_data[""ref""].append(mut[0]) + rbd_data[""alt""].append(mut[2]) + + rbd_df = pd.DataFrame(rbd_data) + + # ------------------------------------------------------------------------- + # Nextclade QC + + logger.info(""Parsing nextclade QC: {}"".format(nextclade)) + nextclade_df = pd.read_csv(nextclade, sep=""\t"") + nextclade_df.fillna(""NA"", inplace=True) + + # ------------------------------------------------------------------------- + # RBD Calculations from Amino Acid Substitutions + + logger.info(""Calculating RBD levels."") + # Initialize the columns that will be in the output table + output_data = { + ""strain"": [], + ""rbd_level"": [], + ""rbd_substitutions"": [], + ""immune_escape"": [], + ""ace2_binding"": [], + } + + # Initialize at 0 + # nextclade_df.at[nextclade_df.index, ""rbd_level""] = [0] * len(nextclade_df) + nextclade_df[""rbd_level""] = [0] * len(nextclade_df) + + # Assign RBD level to each sample + for rec in nextclade_df.iterrows(): + strain = rec[1][""seqName""] + aa_subs = rec[1][""aaSubstitutions""].split("","") + + rbd_level = 0 + rbd_subs = [] + + for s in aa_subs: + gene = s.split("":"")[0] + # RBD Mutations only involve spike + if gene != ""S"": + continue + coord = int(s.split("":"")[1][1:-1]) + alt = s.split("":"")[1][-1] + + # Check if the position is a RBD mutation + if coord in list(rbd_df[""coord""]): + rbd_coord_alts = list(rbd_df[rbd_df[""coord""] == coord][""alt""])[0] + if alt in rbd_coord_alts: + rbd_level += 1 + rbd_subs.append(s) + + immune_escape = NO_DATA_CHAR + ace2_binding = NO_DATA_CHAR + if ""immune_escape"" in nextclade_df.columns: + immune_escape = rec[1][""immune_escape""] + ace2_binding = rec[1][""ace2_binding""] + + output_data[""strain""].append(strain) + output_data[""rbd_level""].append(rbd_level) + output_data[""rbd_substitutions""].append("","".join(rbd_subs)) + output_data[""immune_escape""].append(immune_escape) + output_data[""ace2_binding""].append(ace2_binding) + + output_df = pd.DataFrame(output_data) + + # ------------------------------------------------------------------------- + # Export + + logger.info(""Exporting table: {}"".format(output)) + output_df.to_csv(output, sep=""\t"", index=False) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/sc2rf.sh",".sh","1857","87","#!/bin/bash + +# ----------------------------------------------------------------------------- +# Argument Parsing + +sc2rf_args=() + +while [[ $# -gt 0 ]]; do + case $1 in + --alignment) + alignment=$2 + shift # past argument + shift # past value + ;; + --primers) + primers=$2 + shift # past argument + shift # past value + ;; + --primers-name) + primers_name=$2 + shift # past argument + shift # past value + ;; + --output-ansi) + output_ansi=$2 + shift # past argument + shift # past value + ;; + --output-csv) + output_csv=$2 + shift # past argument + shift # past value + ;; + --log) + log=$2 + shift # past argument + shift # past value + ;; + -*|--*) + arg=$1 + value=$2 + sc2rf_args+=(""$arg"") + shift # past argument + if [[ ${value:0:1} != ""-"" ]]; then + sc2rf_args+=(""$value"") + shift # past value + fi + ;; + *) + # This is a risky way to parse the clades for sc2rf + value=$1 + sc2rf_args+=(""$value"") + shift # past value + ;; + esac +done + +# Prep the Output Directory +outdir=$(dirname $output_csv) +mkdir -p $outdir + +# Location of sc2rf executable +sc2rf=""sc2rf/sc2rf.py"" + +# Add optional params to sc2rf_args +primers_name=${primers_name:-primers} +sc2rf_args+=(""--csvfile $output_csv"") + +# Add primers +if [[ ""${primers}"" ]]; then + cp $primers sc2rf/${primers_name}.bed + sc2rf_args+=(""--primers ${primers_name}.bed"") +fi + +# rebuild examples +#log_rebuild=${log%.*}_rebuild +#python3 sc2rf.py --rebuild-examples 1> ${log_rebuild}.log 2> ${log_rebuild}.err + +echo ""python3 $sc2rf ${alignment} ${sc2rf_args[@]}"" > ${output_ansi} +python3 $sc2rf ${alignment} ${sc2rf_args[@]} 1>> ${output_ansi} 2> ${log}; + +# Clean up primers +if [[ ""${primers}"" ]]; then + rm -f sc2rf/${primers_name}.bed +fi +","Shell" +"Microbiology","ktmeaton/ncov-recombinant","scripts/report.py",".py","18884","582","#!/usr/bin/env python3 +import click +import pptx +from pptx.enum.shapes import MSO_SHAPE +from datetime import date +import os +import pandas as pd + +NO_DATA_CHAR = ""NA"" +TITLE = ""SARS-CoV-2 Recombinants"" +FONT_SIZE_PARAGRAPH = 20 + +RECOMBINANT_STATUS = [ + ""designated"", + ""proposed"", + ""unpublished"", +] + +"""""" Ref for slide types: +0 -> title and subtitle +1 -> title and content +2 -> section header +3 -> two content +4 -> Comparison +5 -> Title only +6 -> Blank +7 -> Content with caption +8 -> Pic with caption +"""""" + + +@click.command() +@click.option(""--linelist"", help=""Linelist TSV"", required=True) +@click.option(""--plot-dir"", help=""Plotting directory"", required=True) +@click.option(""--output"", help=""Output PPTX path"", required=True) +@click.option( + ""--geo"", help=""Geography column to summarize"", required=False, default=""country"" +) +@click.option( + ""--min-cluster-size"", + help=""The minimum size of clusters included in the plots"", + default=1, +) +@click.option( + ""--template"", + help=""Powerpoint template"", + required=False, + default=""resources/template.pptx"", +) +def main( + linelist, + plot_dir, + template, + geo, + output, + min_cluster_size, +): + """"""Create a report of powerpoint slides"""""" + + # Parse build name from plot_dir path + build = os.path.basename(os.path.dirname(plot_dir)) + outdir = os.path.dirname(output) + if not os.path.exists(outdir): + os.mkdir(outdir) + subtitle = ""{}\n{}"".format(build.title(), date.today()) + + # Import dataframes + linelist_df = pd.read_csv(linelist, sep=""\t"") + + plot_suffix = "".png"" + df_suffix = "".tsv"" + labels = [ + f.replace(df_suffix, """") for f in os.listdir(plot_dir) if f.endswith(df_suffix) + ] + + plot_dict = {} + for label in labels: + plot_dict[label] = {} + plot_dict[label][""plot_path""] = os.path.join(plot_dir, label + plot_suffix) + plot_dict[label][""df_path""] = os.path.join(plot_dir, label + df_suffix) + plot_dict[label][""df""] = pd.read_csv(plot_dict[label][""df_path""], sep=""\t"") + + # Breakpoints df isn't over time, but by lineage + if ""epiweek"" in plot_dict[label][""df""].columns: + plot_dict[label][""df""].index = plot_dict[label][""df""][""epiweek""] + + # Largest is special, as it takes the form largest_.* + if label.startswith(""largest_""): + + largest_lineage = ""_"".join(label.split(""_"")[1:]) + # Replace the _DELIM_ character we added for saving files + largest_lineage = largest_lineage.replace(""_DELIM_"", ""/"") + + plot_dict[""largest""] = plot_dict[label] + plot_dict[""largest""][""lineage""] = largest_lineage + + del plot_dict[label] + + # --------------------------------------------------------------------- + # Presentation + # --------------------------------------------------------------------- + presentation = pptx.Presentation(template) + + # --------------------------------------------------------------------- + # Title Slide + title_slide_layout = presentation.slide_layouts[0] + slide = presentation.slides.add_slide(title_slide_layout) + slide.shapes.title.text = TITLE + slide.placeholders[1].text = subtitle + + # --------------------------------------------------------------------- + # General Summary + + # Slide setup + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + title.text_frame.text = ""Status"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""lineage""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + # Stats + + lineages_df = plot_dict[""lineage""][""df""] + lineages = list(lineages_df.columns) + lineages.remove(""epiweek"") + + status_counts = { + status: {""sequences"": 0, ""lineages"": 0} for status in RECOMBINANT_STATUS + } + + status_seq_df = plot_dict[""status""][""df""] + statuses = list(status_seq_df.columns) + statuses.remove(""epiweek"") + + for status in statuses: + status = status.lower() + status_lin_df = plot_dict[status][""df""] + status_lin = list(status_lin_df.columns) + status_lin.remove(""epiweek"") + + num_status_lin = len(status_lin) + status_counts[status][""lineages""] += num_status_lin + + for lin in status_lin: + num_status_seq = int(sum(lineages_df[lin])) + status_counts[status][""sequences""] += num_status_seq + + # Number of lineages and sequences + total_sequences = int(sum([status_counts[s][""sequences""] for s in status_counts])) + total_lineages = int(sum([status_counts[s][""lineages""] for s in status_counts])) + + # Construct the summary text + summary = ""\n"" + + summary += ""There are {total_lineages} recombinant lineages*.\n"".format( + total_lineages=total_lineages + ) + + for status in RECOMBINANT_STATUS: + if status in status_counts: + count = status_counts[status][""lineages""] + else: + count = 0 + summary += "" - {lineages} lineages are {status}.\n"".format( + lineages=count, status=status + ) + + summary += ""\n"" + summary += ""There are {total_sequences} recombinant sequences*.\n"".format( + total_sequences=total_sequences + ) + + for status in RECOMBINANT_STATUS: + if status in status_counts: + count = status_counts[status][""sequences""] + else: + count = 0 + summary += "" - {sequences} sequences are {status}.\n"".format( + sequences=count, status=status + ) + + # Add a footnote to indicate cluster size + summary += ""*Excluding small lineages (N<{})"".format(min_cluster_size) + + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Status Summary + + for status in RECOMBINANT_STATUS: + + status = status.lower() + if status not in plot_dict: + continue + + # Slide setup + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = status.title() + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[status][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + + body = slide.placeholders[2] + + # Stats + status_df = plot_dict[status][""df""] + status_lineages = list(status_df.columns) + status_lineages.remove(""epiweek"") + + # Order columns + status_counts = { + lineage: int(sum(status_df[lineage])) for lineage in status_lineages + } + status_lineages = sorted(status_counts, key=status_counts.get, reverse=True) + num_status_lineages = len(status_lineages) + + summary = ""\n"" + summary += ""There are {num_status_lineages} {status} lineages*.\n"".format( + status=status, num_status_lineages=num_status_lineages + ) + + for lineage in status_lineages: + seq_count = int(sum(status_df[lineage].dropna())) + summary += "" - {lineage} ({seq_count})\n"".format( + lineage=lineage, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Geographic Summary + + geo_df = plot_dict[""geography""][""df""] + geos = list(geo_df.columns) + geos.remove(""epiweek"") + # Order columns + geos_counts = {region: int(sum(geo_df[region])) for region in geos} + geos = sorted(geos_counts, key=geos_counts.get, reverse=True) + + num_geos = len(geos) + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Geography"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""geography""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + + body = slide.placeholders[2] + + summary = ""\n"" + summary += ""Recombinants are observed in {num_geos} {geo}*.\n"".format( + num_geos=num_geos, geo=geo + ) + + for region in geos: + seq_count = int(sum(geo_df[region].dropna())) + summary += "" - {region} ({seq_count})\n"".format( + region=region, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Largest Summary + + largest_df = plot_dict[""largest""][""df""] + + largest_geos = list(largest_df.columns) + largest_geos.remove(""epiweek"") + + # Order columns + largest_geos_counts = { + region: int(sum(largest_df[region])) for region in largest_geos + } + largest_geos = sorted( + largest_geos_counts, key=largest_geos_counts.get, reverse=True + ) + + num_geos = len(largest_geos) + + largest_lineage = plot_dict[""largest""][""lineage""] + largest_lineage_size = 0 + + for lineage in lineages: + seq_count = int(sum(lineages_df[lineage].dropna())) + if seq_count > largest_lineage_size: + largest_lineage_size = seq_count + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Largest"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""largest""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + summary = ""\n"" + summary += ""The largest lineage is {lineage} (N={size})*.\n"".format( + lineage=largest_lineage, + size=largest_lineage_size, + ) + + summary += ""{lineage} is observed in {num_geo} {geo}.\n"".format( + lineage=largest_lineage, num_geo=num_geos, geo=geo + ) + + for region in largest_geos: + seq_count = int(sum(largest_df[region].dropna())) + summary += "" - {region} ({seq_count})\n"".format( + region=region, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # RBD Levels + + rbd_df = plot_dict[""rbd_level""][""df""] + rbd_levels = list(rbd_df.columns) + rbd_levels.remove(""epiweek"") + # Order columns + rbd_counts = { + level: int(sum(rbd_df[level])) + for level in rbd_levels + if int(sum(rbd_df[level])) > 0 + } + rbd_levels = dict(sorted(rbd_counts.items())) + + num_rbd_levels = len(rbd_levels) + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Receptor Binding Domain"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""rbd_level""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + summary = ""\n"" + summary += ""{num_rbd_levels} RBD levels are observed*.\n"".format( + num_rbd_levels=num_rbd_levels, + ) + + for level in rbd_levels: + seq_count = int(sum(rbd_df[level].dropna())) + summary += "" - Level {level} ({seq_count})\n"".format( + level=level, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Parents Summary (Clade) + + parents_df = plot_dict[""parents_clade""][""df""] + + parents = list(parents_df.columns) + parents.remove(""epiweek"") + + parents_counts = {p: int(sum(parents_df[p])) for p in parents} + parents = sorted(parents_counts, key=parents_counts.get, reverse=True) + + num_parents = len(parents) + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Parents (Clade)"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""parents_clade""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + summary = ""\n"" + summary += ""There are {num_parents} clade combinations*.\n"".format( + num_parents=num_parents + ) + + for parent in parents: + seq_count = int(sum(parents_df[parent].dropna())) + summary += "" - {parent} ({seq_count})\n"".format( + parent=parent, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Parents Summary (Lineage) + + parents_df = plot_dict[""parents_lineage""][""df""] + + parents = list(parents_df.columns) + parents.remove(""epiweek"") + + parents_counts = {p: int(sum(parents_df[p])) for p in parents} + parents = sorted(parents_counts, key=parents_counts.get, reverse=True) + + num_parents = len(parents) + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Parents (Lineage)"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""parents_lineage""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + summary = ""\n"" + summary += ""There are {num_parents} lineage combinations*.\n"".format( + num_parents=num_parents + ) + + for parent in parents: + seq_count = int(sum(parents_df[parent].dropna())) + summary += "" - {parent} ({seq_count})\n"".format( + parent=parent, seq_count=seq_count + ) + + summary += ""\n*Excluding small lineages (N<{})"".format(min_cluster_size) + body.text_frame.text = summary + + # Adjust font size of body + for paragraph in body.text_frame.paragraphs: + for run in paragraph.runs: + run.font.size = pptx.util.Pt(14) + + # --------------------------------------------------------------------- + # Breakpoints Clade Summary + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Breakpoints (Clade)"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""breakpoints_clade""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + # --------------------------------------------------------------------- + # Breakpoints Lineage Summary + + graph_slide_layout = presentation.slide_layouts[8] + slide = presentation.slides.add_slide(graph_slide_layout) + title = slide.shapes.title + + title.text_frame.text = ""Breakpoints (Lineage)"" + title.text_frame.paragraphs[0].font.bold = True + + chart_placeholder = slide.placeholders[1] + # Plotting may have failed to create an individual figure + plot_path = plot_dict[""breakpoints_lineage""][""plot_path""] + if os.path.exists(plot_path): + chart_placeholder.insert_picture(plot_path) + body = slide.placeholders[2] + + # --------------------------------------------------------------------- + # Footer + + # Versions + pipeline_version = linelist_df[""pipeline_version""].values[0] + recombinant_classifier_dataset = linelist_df[ + ""recombinant_classifier_dataset"" + ].values[0] + + for slide in presentation.slides: + + # Don't add footer to title slide + if slide.slide_layout == presentation.slide_layouts[0]: + continue + + footer = slide.shapes.add_shape( + autoshape_type_id=MSO_SHAPE.RECTANGLE, + left=pptx.util.Cm(3), + top=pptx.util.Cm(17), + width=pptx.util.Pt(800), + height=pptx.util.Pt(30), + ) + + footer.fill.solid() + footer.fill.fore_color.rgb = pptx.dml.color.RGBColor(255, 255, 255) + footer.line.color.rgb = pptx.dml.color.RGBColor(0, 0, 0) + p = footer.text_frame.paragraphs[0] + p.text = ""{} {} {}"".format( + pipeline_version, "" "" * 20, recombinant_classifier_dataset + ) + p.font.size = pptx.util.Pt(14) + p.font.color.rgb = pptx.dml.color.RGBColor(0, 0, 0) + + # --------------------------------------------------------------------- + # Saving file + presentation.save(output) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/date_to_decimal.py",".py","1436","52","#!/usr/bin/env python3 + +import pandas as pd +from datetime import datetime +import sys + + +def decimal_date(date): + """""" + Convert datetime (%Y-%m-%d) to decimal date. + Credit: Matthias Fripp + Source: https://stackoverflow.com/a/36949905 + """""" + # if type(date) != str: + # return ""?"" + + try: + date = datetime.strptime(date, ""%Y-%m-%d"") + except (ValueError, TypeError) as error: + # nan vals will be flagged as a TypeError + if type(error) == TypeError: + return ""?"" + try: + date = datetime.strptime(date, ""%Y-%m"") + except ValueError: + try: + date = datetime.strptime(date, ""%Y"") + except ValueError: + return ""?"" + + decimal_date = float(date.year) + return decimal_date + + date_ord = date.toordinal() + year_start = datetime(date.year, 1, 1).toordinal() + year_end = datetime(date.year + 1, 1, 1).toordinal() + year_length = year_end - year_start + year_fraction = float(date_ord - year_start) / year_length + decimal_date = date.year + year_fraction + return decimal_date + + +if __name__ == ""__main__"": + df_path = sys.argv[1] + df_out_path = sys.argv[2] + df = pd.read_csv(df_path, sep=""\t"", low_memory=False, encoding=""unicode_escape"") + + if ""date"" in df.columns: + df[""num_date""] = [decimal_date(d) for d in df[""date""]] + + df.to_csv(df_out_path, sep=""\t"", index=False) +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/__init__.py",".py","0","0","","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/download_issues.py",".py","8822","272","#!/usr/bin/env python3 + +import requests +import click +import pandas as pd +import numpy as np +import sys +from datetime import datetime + +NO_DATA_CHAR = ""NA"" +rate_limit_url = ""https://api.github.com/rate_limit"" +base_url = ""https://api.github.com/repos/cov-lineages/pango-designation/issues"" +params = ""?state=all&per_page=100&page={page_num}"" +query_url = base_url + params + +# These issues have problems, and are manually curated in the breakpoints file +# Typically, they describe multiple lineages in a single issue +EXCLUDE_ISSUES = [ + 808, # Chronic B.1.438.1 recombinant with BA.1.1.16 + 844, # XAY and XBA +] + + +@click.command() +@click.option(""--token"", help=""Github API Token"", required=False) +@click.option( + ""--breakpoints"", + help=( + ""TSV of curated breakpoints with columns 'lineage', 'issue', and 'breakpoints'"" + ), + required=False, +) +def main(token, breakpoints): + """"""Fetch pango-designation issues"""""" + + breakpoints_curated = breakpoints + + # Construct the header + header_cols = [ + ""issue"", + ""lineage"", + ""status"", + ""status_description"", + ""countries"", + ""breakpoints"", + ""title"", + ""date_created"", + ""date_updated"", + ""date_closed"", + ] + df = pd.DataFrame(columns=header_cols) + + # Iterate through the pages of issues + pages = range(1, 100) + for page_num in pages: + + # Is the user supplied an API token, use it + headers = """" + if token: + headers = {""Authorization"": ""token {}"".format(token)} + + # Check the current rate limt + r = requests.get(rate_limit_url, headers=headers) + api_stats = r.json() + requests_limit = api_stats[""resources""][""core""][""limit""] + requests_remaining = api_stats[""resources""][""core""][""remaining""] + + reset_time = api_stats[""resources""][""core""][""reset""] + reset_date = datetime.fromtimestamp(reset_time) + + if requests_remaining == 0: + msg = ""ERROR: Hourly API limit of {} requests exceeded,"".format( + requests_limit + ) + msg += "" rate limit will reset after {}."".format(reset_date) + print(msg, file=sys.stderr) + sys.exit(1) + + # We're under the rate limit, and can proceed + r = requests.get(query_url.format(page_num=page_num), headers=headers) + issues_json = r.json() + + # The issues json will be empty if we ran out of pages + if len(issues_json) == 0: + break + + # Iterate through issues + for issue in issues_json: + + # Assume not a recombinant + recombinant = False + number = issue[""number""] + + # Check for excluded issues + if number in EXCLUDE_ISSUES: + continue + + # sanitize quotes out of title + title = issue[""title""].replace('""', """") + # sanitize markdown formatters + title = title.replace(""*"", """") + + # If title includes recombinant or recombinantion + if ""recombinant"" in title.lower() or ""recombination"" in title.lower(): + recombinant = True + + # Designated lineages are stored under the milestone title + lineage = """" + milestone = issue[""milestone""] + if milestone: + lineage = milestone[""title""] + + # Detect recombinant by lineage nomenclature (X) + if lineage: + if lineage.startswith(""X""): + recombinant = True + else: + continue + + # Parse labels + labels = issue[""labels""] + + # labels are a our last chance, so if it doesn't have any skip + if not recombinant and len(labels) == 0: + continue + + status = """" + status_description = """" + if len(labels) > 0: + status = labels[0][""name""] + status_description = labels[0][""description""] + + # Check if the label (status) includes recombinant + if ""recombinant"" in status.lower(): + recombinant = True + + # Skip to the next record if this is not a recombinant issue + if not recombinant: + continue + + # If a lineage hasn't been assigned, + # use the propose# nomenclature from UShER + if not lineage: + lineage = ""proposed{}"".format(number) + + # Try to extract info from the body + body = issue[""body""] + breakpoints = [] + countries = [] + + # Skip issues without a body + if not body: + continue + + for line in body.split(""\n""): + + line = line.strip().replace(""*"", """") + + # Breakpoints + if ""breakpoint:"" in line.lower(): + breakpoints.append(line) + elif ""breakpoint"" in line.lower(): + breakpoints.append(line) + + # Countries (nicely structures) + if ""countries circulating"" in line.lower(): + line = line.replace(""Countries circulating:"", """") + countries.append(line) + + breakpoints = "";"".join(breakpoints) + countries = "";"".join(countries) + + # Dates + date_created = issue[""created_at""] + date_updated = issue[""updated_at""] + date_closed = issue[""closed_at""] + + if not date_closed: + date_closed = NO_DATA_CHAR + + # Create the output data + data = {col: """" for col in header_cols} + data[""issue""] = number + data[""lineage""] = lineage + data[""status""] = status + data[""status_description""] = status_description + data[""title""] = title + data[""countries""] = countries + data[""breakpoints""] = breakpoints + data[""date_created""] = date_created + data[""date_updated""] = date_updated + data[""date_closed""] = date_closed + + # Change data vals to lists for pandas + data = {k: [v] for k, v in data.items()} + # Convert dict to dataframe + df_data = pd.DataFrame(data) + # Add data to the main dataframe + df = pd.concat([df, df_data], ignore_index=True) + + # ------------------------------------------------------------------------- + # Curate breakpoints + + if breakpoints_curated: + df_breakpoints = pd.read_csv(breakpoints_curated, sep=""\t"") + + if ( + ""breakpoints"" in df_breakpoints.columns + and ""breakpoints_curated"" not in df.columns + ): + df.insert(5, ""breakpoints_curated"", [""""] * len(df)) + + if ""parents"" in df_breakpoints.columns and ""parents_curated"" not in df.columns: + df.insert(5, ""parents_curated"", [""""] * len(df)) + + for rec in df.iterrows(): + issue = rec[1][""issue""] + lineage = rec[1][""lineage""] + + if issue not in list(df_breakpoints[""issue""]): + continue + + match = df_breakpoints[df_breakpoints[""issue""] == issue] + bp = list(match[""breakpoints""])[0] + parents = list(match[""parents""])[0] + + if bp != np.nan: + df.at[rec[0], ""breakpoints_curated""] = bp + if parents != np.nan: + df.at[rec[0], ""parents_curated""] = parents + + # Check for lineages with curated breakpoints that are missing + # Ex. ""XAY"" and ""XBA"" were grouped into one issue + for rec in df_breakpoints.iterrows(): + lineage = rec[1][""lineage""] + + if lineage in list(df[""lineage""]): + continue + + issue = rec[1][""issue""] + breakpoints = rec[1][""breakpoints""] + parents = rec[1][""parents""] + + row_data = {col: [""""] for col in df.columns} + row_data[""lineage""][0] = lineage + row_data[""issue""][0] = rec[1][""issue""] + row_data[""breakpoints_curated""][0] = rec[1][""breakpoints""] + row_data[""parents_curated""][0] = rec[1][""parents""] + + row_df = pd.DataFrame(row_data) + df = pd.concat([df, row_df]) + + # ------------------------------------------------------------------------- + # Sort the final dataframe + status_order = {""designated"": 0, ""recombinant"": 1, ""monitor"": 2, ""not accepted"": 3} + + # Change empty cells to NaN so they'll be sorted to the end + df = df.replace({""lineage"": """", ""status"": """"}, np.nan) + df.sort_values( + [ + ""status"", + ""lineage"", + ], + inplace=True, + key=lambda x: x.map(status_order), + ) + df.to_csv(sys.stdout, sep=""\t"", index=False) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/plot_breakpoints.py",".py","14940","484","#!/usr/bin/env python3 + +import click +import os +import pandas as pd +import matplotlib.pyplot as plt +from matplotlib import patches, colors, lines, collections +from functions import categorical_palette +import math + +NO_DATA_CHAR = ""NA"" +# This is the aspect ratio/dpi for ppt embeds +# The dimensions are set in the powerpoint template (resources/template.pttx) +DPI = 96 * 2 +FIGSIZE = [6.75, 5.33] +FIG_Y_PER_LINEAGE = 1 + +# Breakpoint Plotting +GENOME_LENGTH = 29903 +X_BUFF = 1000 +BREAKPOINT_COLOR = ""lightgrey"" +UNKNOWN_COLOR = ""dimgrey"" +COORD_ITER = 5000 + +# This is the number of characters than can fit width-wise across the legend +LEGEND_FONTSIZE = 6 +LEGEND_CHAR_WIDTH = 90 +# The maximum columns in the legend is dictated by the char width, but more +# importantly, in the categorical_palette function, we restrict it to the +# first 5 colors of the tap10 palette, and make different shades within it +LEGEND_MAX_COL = 5 + +# Show the first N char of the label in the plot +LEGEND_LABEL_MAX_LEN = 15 + +# Select and rename columns from linelist +LINEAGES_COLS = [ + ""cluster_id"", + ""status"", + ""lineage"", + ""parents_clade"", + ""parents_lineage"", + ""breakpoints"", + ""issue"", + ""sequences"", + ""growth_score"", + ""earliest_date"", + ""latest_date"", +] + +plt.rcParams[""svg.fonttype""] = ""none"" + + +@click.command() +@click.option(""--lineages"", help=""Recombinant lineages (tsv)"", required=True) +@click.option(""--outdir"", help=""Output directory"", required=False, default=""."") +@click.option( + ""--lineage-col"", help=""Column name of lineage"", required=False, default=""lineage"" +) +@click.option( + ""--breakpoint-col"", + help=""Column name of breakpoints"", + required=False, + default=""breakpoints"", +) +@click.option( + ""--parent-col"", help=""Column name of parents"", required=False, default=""parents"" +) +@click.option( + ""--parent-type"", + help=""Parent type (ex. clade, lineage)"", + required=False, + default=""clade"", +) +@click.option( + ""--cluster-col"", help=""Column name of cluster ID (ex. cluster_id)"", required=False +) +@click.option( + ""--clusters"", help=""Restrict plotting to only these cluster IDs"", required=False +) +@click.option( + ""--figsize"", + help=""Figure dimensions as h,w in inches (ex. 6.75,5.33)"", + default="","".join([str(d) for d in FIGSIZE]), +) +@click.option( + ""--autoscale"", + help=""Autoscale plot dimensions to the number of lineages (overrides --figsize)"", + is_flag=True, +) +@click.option( + ""--positives"", + help=""Table of positive recombinants"", + required=False, +) +def main( + lineages, + outdir, + lineage_col, + parent_col, + breakpoint_col, + cluster_col, + clusters, + parent_type, + autoscale, + figsize, + positives, +): + """"""Plot recombinant lineage breakpoints"""""" + + # Creat output directory if it doesn't exist + if not os.path.exists(outdir): + os.mkdir(outdir) + + # ------------------------------------------------------------------------- + # Import dataframes + lineages_df = pd.read_csv(lineages, sep=""\t"") + lineages_df.fillna(NO_DATA_CHAR, inplace=True) + + if cluster_col: + + lineages_df[cluster_col] = [str(c) for c in lineages_df[cluster_col]] + # Filter dataframe on cluster IDs + if clusters: + clusters_list = clusters.split("","") + lineages_df = lineages_df[lineages_df[cluster_col].isin(clusters_list)] + + # Which lineages have the same name but different cluster ID? + lineages_seen = [] + lineages_dup = [] + for lineage in list(lineages_df[lineage_col]): + if lineage not in lineages_seen: + lineages_seen.append(lineage) + else: + lineages_dup.append(lineage) + + else: + lineages_dup = [] + + if positives: + positives_df = pd.read_csv(positives, sep=""\t"") + positives_df[""strain""] = [str(s) for s in positives_df[""strain""]] + if cluster_col: + positives_df[cluster_col] = [str(s) for s in positives_df[cluster_col]] + positives_df.fillna(NO_DATA_CHAR, inplace=True) + + # Figsize format back to list + figsize = [float(d) for d in figsize.split("","")] + + # ------------------------------------------------------------------------- + + # Create a dataframe to hold plot data + # Lineage (y axis, categorical) + # Coordinate (x axis, numeric) + + breakpoints_data = { + ""lineage"": [], + ""parent"": [], + ""start"": [], + ""end"": [], + } + + parents_colors = {} + + # ------------------------------------------------------------------------- + # Create a dataframe to hold plot data + + # Iterate through lineages + for rec in lineages_df.iterrows(): + lineage = rec[1][lineage_col] + + if cluster_col: + cluster_id = rec[1][cluster_col] + lineage = ""{} {}"".format(lineage, cluster_id) + + parents = rec[1][parent_col] + breakpoints = rec[1][breakpoint_col] + + parents_split = parents.split("","") + breakpoints_split = breakpoints.split("","") + + prev_start_coord = 0 + + # Iterate through the parents + for i in range(0, len(parents_split)): + parent = parents_split[i] + + # Convert NA parents to Unknown + if parent == NO_DATA_CHAR: + parent = ""Unknown"" + if parent not in parents_colors: + parents_colors[parent] = """" + + if i < (len(parents_split) - 1): + breakpoint = breakpoints_split[i] + # Check that we actually found a breakpoint + if "":"" not in breakpoint: + continue + + breakpoint_start_coord = int(breakpoint.split("":"")[0]) + breakpoint_end_coord = int(breakpoint.split("":"")[1]) + + # Give this coordinate to both parents + parent_next = parents_split[i + 1] + if parent_next == NO_DATA_CHAR: + parent_next = ""Unknown"" + + start_coord = prev_start_coord + end_coord = int(breakpoint.split("":"")[0]) - 1 + # Update start coord + prev_start_coord = int(breakpoint.split("":"")[1]) + 1 + + # Add record for breakpoint + breakpoints_data[""lineage""].append(lineage) + breakpoints_data[""parent""].append(""breakpoint"") + breakpoints_data[""start""].append(breakpoint_start_coord) + breakpoints_data[""end""].append(breakpoint_end_coord) + + else: + start_coord = prev_start_coord + end_coord = GENOME_LENGTH + + # Add record for parent + breakpoints_data[""lineage""].append(lineage) + breakpoints_data[""parent""].append(parent) + breakpoints_data[""start""].append(start_coord) + breakpoints_data[""end""].append(end_coord) + + # Convert the dictionary to a dataframe + breakpoints_df = pd.DataFrame(breakpoints_data) + + # Sort by coordinates + breakpoints_df.sort_values(by=[""parent"", ""start"", ""end""], inplace=True) + + # ------------------------------------------------------------------------- + # Colors + + # Pick paletted based on number of parents + parents_palette = categorical_palette(num_cat=len(parents_colors)) + + i = 0 + + for parent in parents_colors: + if parent == ""Unknown"": + # We'll sort this out after, so it will be at the end + continue + + color_rgb = parents_palette[i] + color = colors.to_hex(color_rgb) + parents_colors[parent] = color + i += 1 + + # Reorder unknown parents to the end + if ""Unknown"" in parents_colors: + del parents_colors[""Unknown""] + parents_colors[""Unknown""] = UNKNOWN_COLOR + parents_colors[""breakpoint""] = BREAKPOINT_COLOR + + # ------------------------------------------------------------------------- + # Plot Setup + + # When dynamically setting the aspect ratio, the height is + # multiplied by the number of lineages + num_lineages = len(set(list(breakpoints_df[""lineage""]))) + if autoscale: + # This is the minimum size it can be for 1 lineage with two parents + figsize = [figsize[0], 2] + # Adjusted for other sizes of lineages, mirrors fontsize detection later + if num_lineages >= 40: + figsize = [figsize[0], 0.1 * num_lineages] + elif num_lineages >= 30: + figsize = [figsize[0], 0.2 * num_lineages] + elif num_lineages >= 20: + figsize = [figsize[0], 0.3 * num_lineages] + elif num_lineages >= 10: + figsize = [figsize[0], 0.5 * num_lineages] + elif num_lineages > 1: + figsize = [figsize[0], 1 * num_lineages] + + fig, ax = plt.subplots( + 1, + 1, + dpi=DPI, + figsize=figsize, + ) + + # ------------------------------------------------------------------------- + # Plot Breakpoint Regions + + rect_height = 1 + start_y = 0 + y_buff = 1 + y = start_y + y_increment = rect_height + y_buff + y_tick_locs = [] + y_tick_labs_lineage = [] + + num_lineages = len(set(breakpoints_df[""lineage""])) + lineages_seen = [] + + # Iterate through lineages to plot + for rec in breakpoints_df.iterrows(): + lineage = rec[1][""lineage""] + if lineage in lineages_seen: + continue + lineages_seen.append(lineage) + + y_tick_locs.append(y + (rect_height / 2)) + lineage_label = lineage.split("" "")[0] + if cluster_col: + + cluster_id_label = lineage.split("" "")[1] + + # Non-unique, use cluster ID in y axis + if lineage_label in lineages_dup: + ylabel = ""{} ({})"".format(lineage_label, cluster_id_label) + else: + ylabel = lineage_label + + y_tick_labs_lineage.append(ylabel) + + lineage_df = breakpoints_df[breakpoints_df[""lineage""] == lineage] + + # Iterate through regions to plot + for rec in lineage_df.iterrows(): + parent = rec[1][""parent""] + start = rec[1][""start""] + end = rec[1][""end""] + + color = parents_colors[parent] + + region_rect = patches.Rectangle( + xy=[start, y], + width=end - start, + height=rect_height, + linewidth=1, + edgecolor=""none"", + facecolor=color, + ) + ax.add_patch(region_rect) + + # Iterate through substitutions to plot + if positives: + positive_rec = positives_df[(positives_df[lineage_col] == lineage_label)] + # If we're using a cluster id col, further filter on that + if cluster_col: + positive_rec = positive_rec[ + (positive_rec[cluster_col] == cluster_id_label) + ] + + # Extract the substitutions, just taking the first as representative + cov_spectrum_subs = list(positive_rec[""cov-spectrum_query""])[0] + + if cov_spectrum_subs != NO_DATA_CHAR: + # Split into a list, and extract coordinates + coord_list = [int(s[1:-1]) for s in cov_spectrum_subs.split("","")] + subs_lines = [] + # Create vertical bars for each sub + for coord in coord_list: + sub_line = [(coord, y), (coord, y + rect_height)] + subs_lines.append(sub_line) + # Combine all bars into a collection + collection_subs = collections.LineCollection( + subs_lines, color=""black"", linewidth=0.25 + ) + # Add the subs bars to the plot + ax.add_collection(collection_subs) + + # Jump to the next y coordinate + y -= y_increment + + # Axis Limits + ax.set_xlim(0 - X_BUFF, GENOME_LENGTH + X_BUFF) + ax.set_ylim( + 0 - ((num_lineages * y_increment) - (y_increment / 2)), + 0 + (rect_height * 2), + ) + + # This is the default fontisze to use + y_tick_fontsize = 10 + if num_lineages >= 20: + y_tick_fontsize = 8 + if num_lineages >= 30: + y_tick_fontsize = 6 + if num_lineages >= 40: + y_tick_fontsize = 4 + + # Axis ticks + ax.set_yticks(y_tick_locs) + + # Truncate long labels + for i in range(0, len(y_tick_labs_lineage)): + + y_label = y_tick_labs_lineage[i] + + if len(y_label) > LEGEND_LABEL_MAX_LEN: + y_label = y_label[0:LEGEND_LABEL_MAX_LEN] + if ""("" in y_label and "")"" not in y_label: + y_label = y_label + ""...)"" + else: + y_label = y_label + ""..."" + + y_tick_labs_lineage[i] = y_label + + ax.set_yticklabels(y_tick_labs_lineage, fontsize=y_tick_fontsize) + + # Axis Labels + ax.set_ylabel(""Lineage"") + ax.set_xlabel(""Genomic Coordinate"") + + # ------------------------------------------------------------------------- + # Manually create legend + + legend_handles = [] + legend_labels = [] + + for parent in parents_colors: + handle = lines.Line2D([0], [0], color=parents_colors[parent], lw=4) + legend_handles.append(handle) + if parent == ""breakpoint"": + legend_labels.append(parent.title()) + else: + legend_labels.append(parent) + + subs_handle = lines.Line2D( + [], + [], + color=""black"", + marker=""|"", + linestyle=""None"", + markersize=10, + markeredgewidth=1, + ) + legend_handles.append(subs_handle) + legend_labels.append(""Substitution"") + + # Dynamically set the number of columns in the legend based on how + # how much space the labels will take up (in characters) + max_char_len = 0 + for label in legend_labels: + if len(label) >= max_char_len: + max_char_len = len(label) + + legend_ncol = math.floor(LEGEND_CHAR_WIDTH / max_char_len) + # we don't want too many columns + if legend_ncol > LEGEND_MAX_COL: + legend_ncol = LEGEND_MAX_COL + elif legend_ncol > len(parents_colors): + legend_ncol = len(parents_colors) + + legend = ax.legend( + handles=legend_handles, + labels=legend_labels, + title=parent_type.title(), + edgecolor=""black"", + fontsize=LEGEND_FONTSIZE, + ncol=legend_ncol, + loc=""lower center"", + mode=""expand"", + bbox_to_anchor=(0, 1.02, 1, 0.2), + borderaxespad=0, + borderpad=1, + ) + + legend.get_frame().set_linewidth(1) + legend.get_title().set_fontweight(""bold"") + # legend.get_frame().set_boxstyle(""Square"", pad=0.2) + + # ------------------------------------------------------------------------- + # Export + + # plt.suptitle(""Recombination Breakpoints by Lineage"") + if num_lineages > 0: + plt.tight_layout() + + outpath = os.path.join(outdir, ""breakpoints_{}"".format(parent_type)) + breakpoints_df.to_csv(outpath + "".tsv"", sep=""\t"", index=False) + plt.savefig(outpath + "".png"") + plt.savefig(outpath + "".svg"") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/linelist.py",".py","21469","596","#!/usr/bin/env python3 +import click +import os +import pandas as pd +import copy +from datetime import datetime +import numpy as np +from functions import create_logger +from Bio import Phylo + +# Hard-coded constants + +NO_DATA_CHAR = ""NA"" + +PIPELINE = ""ncov-recombinant"" + +# There are alternative lineage names for sequencing dropouts +SC2RF_LINEAGE_ALT = { + ""XBB_ARTICv4.1"": ""XBB"", + ""XAY_dropout"": ""XAY"", +} + +# Select and rename columns from summary +LINELIST_COLS = { + ""strain"": ""strain"", + ""sc2rf_lineage"": ""lineage_sc2rf"", + ""sc2rf_status"": ""status_sc2rf"", + ""Nextclade_pango"": ""lineage_nextclade"", + ""Nextclade_clade"": ""clade_nextclade"", + ""sc2rf_parents"": ""parents_clade"", + ""cov-spectrum_parents"": ""parents_lineage"", + ""sc2rf_parents_conflict"": ""parents_conflict"", + ""cov-spectrum_parents_confidence"": ""parents_lineage_confidence"", + ""cov-spectrum_parents_subs"": ""parents_subs"", + ""sc2rf_breakpoints"": ""breakpoints"", + ""sc2rf_regions"": ""regions"", + ""date"": ""date"", + ""country"": ""country"", + ""privateNucMutations.reversionSubstitutions"": ""subs_reversion"", + ""privateNucMutations.unlabeledSubstitutions"": ""subs_unlabeled"", + ""privateNucMutations.labeledSubstitutions"": ""subs_labeled"", + ""substitutions"": ""subs"", + ""rbd_level"": ""rbd_level"", + ""rbd_substitutions"": ""rbd_substitutions"", + ""immune_escape"": ""immune_escape"", + ""ace2_binding"": ""ace2_binding"", + ""ncov-recombinant_version"": ""ncov-recombinant_version"", + ""nextclade_version"": ""nextclade_version"", + ""nextclade_dataset"": ""nextclade_dataset"", +} + + +@click.command() +@click.option(""--input"", help=""Summary (tsv)."", required=True) +@click.option( + ""--issues"", + help=""pango-designation issues table"", + required=True, + default=""resources/issues.tsv"", +) +@click.option( + ""--extra-cols"", + help=""Extra columns (csv) to extract from the summary"", + required=False, +) +@click.option( + ""--outdir"", + help=""Output directory for linelists"", + required=True, +) +@click.option( + ""--min-lineage-size"", + help=""For lineage sizes larger than this, investigate -like status."", + default=10, + required=False, +) +@click.option( + ""--min-private-muts"", + help=""If more than this number of private mutations, investigate -like status."", + required=False, + default=3, +) +@click.option( + ""--lineage-tree"", + help=""Newick tree of pangolin lineage hierarchies"", + required=False, +) +@click.option(""--log"", help=""Logfile"", required=False) +def main( + input, + issues, + extra_cols, + outdir, + log, + min_lineage_size, + min_private_muts, + lineage_tree, +): + """"""Create a linelist and recombinant report"""""" + + # ------------------------------------------------------------------------- + # Setup + # ------------------------------------------------------------------------- + + # create logger + logger = create_logger(logfile=log) + + # Misc variables + if not os.path.exists(outdir): + os.mkdir(outdir) + + # Import Summary Dataframe + logger.info(""Parsing table: {}"".format(input)) + summary_df = pd.read_csv(input, sep=""\t"") + summary_df.fillna(NO_DATA_CHAR, inplace=True) + + # Import Issues Summary Dataframe + logger.info(""Parsing issues: {}"".format(issues)) + issues_df = pd.read_csv(issues, sep=""\t"") + issues_df.fillna(NO_DATA_CHAR, inplace=True) + + # (Optional) Extract columns from summary + if extra_cols: + for col in extra_cols.split("",""): + LINELIST_COLS[col] = col + + # (Optional) phylogenetic tree of pangolineage lineages + if lineage_tree: + logger.info(""Parsing lineage tree: {}"".format(lineage_tree)) + tree = Phylo.read(lineage_tree, ""newick"") + + cols_list = list(LINELIST_COLS.keys()) + + # Setup the linelist dataframe + linelist_df = copy.deepcopy(summary_df[cols_list]) + linelist_df.rename(columns=LINELIST_COLS, inplace=True) + + # The nature of the rbd_level values (0, 1, ...) causes issues with dataframe + # issues later in this script. A bandaid solution is to convert to strings. + linelist_df[""rbd_level""] = [str(l) for l in list(linelist_df[""rbd_level""])] + + # Initialize columns + linelist_df.insert(1, ""status"", [NO_DATA_CHAR] * len(linelist_df)) + linelist_df.insert(2, ""lineage"", [NO_DATA_CHAR] * len(linelist_df)) + linelist_df.insert(3, ""issue"", [NO_DATA_CHAR] * len(linelist_df)) + linelist_df[""privates""] = [NO_DATA_CHAR] * len(linelist_df) + linelist_df[""cov-spectrum_query""] = [NO_DATA_CHAR] * len(linelist_df) + + # ------------------------------------------------------------------------- + # Lineage Consensus + # ------------------------------------------------------------------------- + + # Use lineage calls by sc2rf and nextclade to classify recombinants status + + logger.info(""Comparing lineage assignments across tools"") + + for rec in linelist_df.iterrows(): + strain = rec[1][""strain""] + status = rec[1][""status_sc2rf""] + breakpoints = rec[1][""breakpoints""] + + issue = NO_DATA_CHAR + is_recombinant = False + lineage = NO_DATA_CHAR + + # --------------------------------------------------------------------- + # Lineage Assignments (Designated) + + # Nextclade can only have one lineage assignment + lineage_nextclade = rec[1][""lineage_nextclade""] + + # sc2rf can be multiple lineages, same breakpoint, multiple possible lineages + lineages_sc2rf = rec[1][""lineage_sc2rf""].split("","") + status = rec[1][""status_sc2rf""] + + # Rename sc2rf lineages for alts (ex. ARTIC XBB) + for i, l_sc2rf in enumerate(lineages_sc2rf): + if l_sc2rf in SC2RF_LINEAGE_ALT: + lineages_sc2rf[i] = SC2RF_LINEAGE_ALT[l_sc2rf] + + # Save a flag to indicate whether nextclade is sublineage of sc2rf + nextclade_is_sublineage = False + + # Check if sc2rf confirmed its a recombinant + if status == ""positive"": + is_recombinant = True + + # Case #1: By default use nextclade + lineage = lineage_nextclade + classifier = ""nextclade"" + + # Case #2: unless sc2rf found a definitive match, that is not a ""proposed"" + if ( + lineages_sc2rf[0] != NO_DATA_CHAR + and len(lineages_sc2rf) == 1 + and not lineages_sc2rf[0].startswith(""proposed"") + ): + + # Case #2a. nextclade is a sublineage of sc2rf + if lineage_tree: + sc2rf_lineage_tree = [c for c in tree.find_clades(lineages_sc2rf[0])] + # Make sure we found this lineage in the tree + if len(sc2rf_lineage_tree) == 1: + sc2rf_lineage_tree = sc2rf_lineage_tree[0] + sc2rf_lineage_children = [ + c.name for c in sc2rf_lineage_tree.find_clades() + ] + # check if nextclade is sublineage of sc2rf + if lineage_nextclade in sc2rf_lineage_children: + nextclade_is_sublineage = True + # We don't need to update the lineage, since we + # use nextclade by default + + # Case #2b. nextclade is not a sublineage of sc2rf + if not nextclade_is_sublineage: + lineage = lineages_sc2rf[0] + classifier = ""sc2rf"" + + # Case #1: designated recombinants called as false_positive + # As of v0.4.0, sometimes XN and XP will be detected by sc2rf, but then labeled + # as a false positive, since all parental regions are collapsed + parents_clade = rec[1][""parents_clade""] + if (lineage == ""XN"" or lineage == ""XP"") and parents_clade != NO_DATA_CHAR: + status = ""positive"" + is_recombinant = True + + # If we actually found breakpoints but not sc2rf lineage, this is a ""-like"" + if breakpoints != NO_DATA_CHAR and lineages_sc2rf[0] == NO_DATA_CHAR: + lineage = lineage + ""-like"" + + # Case #2: designated recombinants that sc2rf cannot detect + # As of v0.4.2, XAS cannot be detected by sc2rf + elif parents_clade == NO_DATA_CHAR and (lineage == ""XAS""): + status = ""positive"" + is_recombinant = True + + # Case #3: nextclade thinks it's a recombinant but sc2rf doesn't + elif lineage.startswith(""X"") and breakpoints == NO_DATA_CHAR: + status = ""false_positive"" + + # Case #4: nextclade and sc2rf disagree, flag it as X*-like + elif ( + len(lineages_sc2rf) >= 1 + and lineage.startswith(""X"") + and lineage not in lineages_sc2rf + and not nextclade_is_sublineage + ): + lineage = lineage + ""-like"" + + # --------------------------------------------------------------------- + # Issue + + # Identify the possible pango-designation issue this is related to + issues = [] + + for lin in set(lineages_sc2rf + [lineage_nextclade]): + # There are two weird examples in sc2rf lineages + # which are proposed808-1 and proposed808-2 + # because two lineages got the same issue post + # Transform proposed808-1 to proposed808 + if lin.startswith(""proposed"") and ""-"" in lin: + lin = lin.split(""-"")[0] + + if lin in list(issues_df[""lineage""]): + match = issues_df[issues_df[""lineage""] == lin] + issue = match[""issue""].values[0] + issues.append(issue) + + if len(issues) >= 1: + issue = "","".join([str(iss) for iss in issues]) + else: + issue = NO_DATA_CHAR + + # --------------------------------------------------------------------- + # Private Substitutions + + privates = [] + + # The private subs are only informative if we're using the nextclade lineage + if classifier == ""nextclade"": + reversions = rec[1][""subs_reversion""].split("","") + labeled = rec[1][""subs_labeled""].split("","") + unlabeled = rec[1][""subs_unlabeled""].split("","") + + privates_dict = {} + + for sub in reversions + labeled + unlabeled: + if sub == NO_DATA_CHAR: + continue + # Labeled subs have special formatting + if ""|"" in sub: + sub = sub.split(""|"")[0] + coord = int(sub[1:-1]) + privates_dict[coord] = sub + + # Convert back to sorted list + for coord in sorted(privates_dict): + sub = privates_dict[coord] + privates.append(sub) + + # --------------------------------------------------------------------- + # Status + + # Fine-tune the status of a positive recombinant + if is_recombinant: + if lineage.startswith(""X"") and not lineage.endswith(""like""): + status = ""designated"" + elif issue != NO_DATA_CHAR: + status = ""proposed"" + else: + status = ""unpublished"" + + # --------------------------------------------------------------------- + # Update Dataframe + + linelist_df.at[rec[0], ""lineage""] = lineage + linelist_df.at[rec[0], ""status""] = str(status) + linelist_df.at[rec[0], ""issue""] = str(issue) + linelist_df.at[rec[0], ""privates""] = privates + + # ------------------------------------------------------------------------- + # Lineage Assignment (Undesignated) + # ------------------------------------------------------------------------- + + # Group sequences into potential lineages that have a unique combination of + # 1. Lineage + # 2. Parent clades (sc2rf) + # 3. Parent lineages (sc2rf, lapis cov-spectrum) + # 4. Breakpoints (sc2rf) + # 5. Private substitutions (nextclade) + + logger.info(""Grouping sequences into lineages."") + + # Create a dictionary of recombinant lineages seen + rec_seen = {} + seen_i = 0 + + for rec in linelist_df.iterrows(): + + strain = rec[1][""strain""] + status = rec[1][""status""] + + if status == ""negative"" or status == ""false_positive"": + continue + + # 1. Lineage assignment (nextclade or sc2rf) + # 2. Parents by clade (ex. 21K,21L) + # 3. Parents by lineage (ex. BA.1.1,BA.2.3) + # 4. Breakpoints + lineage = rec[1][""lineage""] + parents_clade = rec[1][""parents_clade""] + parents_lineage = rec[1][""parents_lineage""] + breakpoints = rec[1][""breakpoints""] + privates = rec[1][""privates""] + + # in v0.5.1, we used the parents subs + # Format substitutions into a tidy list + # ""C234T,A54354G|Omicron/BA.1/21K;A423T|Omicron/BA.2/21L"" + # parents_subs_raw = rec[1][""parents_subs""].split("";"") + # # [""C234T,A54354G|Omicron/BA.1/21K"", ""A423T|Omicron/BA.2/21L""] + # parents_subs_csv = [sub.split(""|"")[0] for sub in parents_subs_raw] + # # [""C234T,A54354G"", ""A423T""] + # parents_subs_str = "","".join(parents_subs_csv) + # # ""C234T,A54354G,A423T"" + # parents_subs_list = parents_subs_str.split("","") + # # [""C234T"",""A54354G"",""A423T""] + + # in v0.5.2, we use all subs + # ""C241T,A385G,G407A,..."" + subs_list = rec[1][""subs""].split("","") + # [""C241T"",""A385G"",""G407A"", ...] + + match = None + + for i in rec_seen: + rec_lin = rec_seen[i] + # lineage, parents, breakpoints, and subs have to match + if ( + rec_lin[""lineage""] == lineage + and rec_lin[""parents_clade""] == parents_clade + and rec_lin[""parents_lineage""] == parents_lineage + and rec_lin[""breakpoints""] == breakpoints + ): + match = i + break + + # If we found a match, increment our dict + if match is not None: + # Add the strain to this lineage + rec_seen[match][""strains""].append(strain) + + # Adjust the cov-spectrum subs /parents subs to include the new strain + + # in v0.5.1, cov-spectrum_query was based only on parental subs (pre-recomb) + # See issue #180: https://github.com/ktmeaton/ncov-recombinant/issues/180 + # lineage_parents_subs = rec_seen[match][""cov-spectrum_query""] + # for sub in lineage_parents_subs: + # if sub not in parents_subs_list: + # rec_seen[match][""cov-spectrum_query""].remove(sub) + + # in v0.5.2, cov-spectrum_query is based on all subs + subs = rec_seen[match][""cov-spectrum_query""] + for sub in subs: + if sub not in subs_list: + rec_seen[match][""cov-spectrum_query""].remove(sub) + + # Adjust the private subs to include the new strain + lineage_private_subs = rec_seen[match][""privates""] + for sub in lineage_private_subs: + if sub not in privates: + rec_seen[match][""privates""].remove(sub) + + # This is the first appearance, initialize values + else: + rec_seen[seen_i] = { + ""lineage"": lineage, + ""breakpoints"": breakpoints, + ""parents_clade"": parents_clade, + ""parents_lineage"": parents_lineage, + ""strains"": [strain], + ""cov-spectrum_query"": subs_list, + ""privates"": privates, + } + seen_i += 1 + + # ------------------------------------------------------------------------- + # Cluster ID + # Assign an id to each lineage based on the first sequence collected + + logger.info(""Assigning cluster IDs to lineages."") + + linelist_df[""cluster_id""] = [NO_DATA_CHAR] * len(linelist_df) + linelist_df[""cluster_privates""] = [NO_DATA_CHAR] * len(linelist_df) + + for i in rec_seen: + earliest_datetime = datetime.today() + earliest_strain = None + + rec_strains = rec_seen[i][""strains""] + rec_privates = "","".join(rec_seen[i][""privates""]) + rec_df = linelist_df[linelist_df[""strain""].isin(rec_strains)] + + earliest_datetime = min(rec_df[""date""]) + earliest_strain = rec_df[rec_df[""date""] == earliest_datetime][""strain""].values[ + 0 + ] + subs_query = rec_seen[i][""cov-spectrum_query""] + if subs_query != NO_DATA_CHAR: + subs_query = "","".join(subs_query) + + # indices are preserved from the original linelist_df + for strain in rec_strains: + strain_i = rec_df[rec_df[""strain""] == strain].index[0] + + linelist_df.loc[strain_i, ""cluster_id""] = earliest_strain + linelist_df.loc[strain_i, ""cov-spectrum_query""] = subs_query + linelist_df.loc[strain_i, ""cluster_privates""] = rec_privates + + # ------------------------------------------------------------------------- + # Mimics + + logger.info(""Checking for mimics with too many private mutations."") + # Check for designated lineages that have too many private mutations + # This may indicate this is a novel lineage + for i in rec_seen: + lineage = rec_seen[i][""lineage""] + rec_strains = rec_seen[i][""strains""] + lineage_size = len(rec_strains) + num_privates = len(rec_seen[i][""privates""]) + + # Mark these lineages as ""X*-like"" + if ( + lineage.startswith(""X"") + and not lineage.endswith(""like"") + and lineage_size >= min_lineage_size + and num_privates >= min_private_muts + ): + lineage = lineage + ""-like"" + rec_rename = linelist_df[""strain""].isin(rec_strains) + linelist_df.loc[rec_rename, ""lineage""] = lineage + linelist_df.loc[rec_rename, ""status""] = ""proposed"" + + # ------------------------------------------------------------------------- + # Assign status and curated lineage + + logger.info(""Assigning curated recombinant lineages."") + + for rec in linelist_df.iterrows(): + lineage = rec[1][""lineage""] + status = rec[1][""status""] + cluster_id = rec[1][""cluster_id""] + + # By default use cluster ID for curated lineage + linelist_df.at[rec[0], ""recombinant_lineage_curated""] = cluster_id + + if status == ""negative"": + linelist_df.at[rec[0], ""recombinant_lineage_curated""] = ""negative"" + + elif status == ""false_positive"": + linelist_df.at[rec[0], ""recombinant_lineage_curated""] = ""false_positive"" + + # If designated or ""-like"", override with actual lineage + elif status == ""designated"" or lineage.endswith(""like""): + linelist_df.at[rec[0], ""recombinant_lineage_curated""] = lineage + + # ------------------------------------------------------------------------- + # Pipeline Versions + logger.info(""Recording pipeline versions."") + + pipeline_ver = linelist_df[""ncov-recombinant_version""].values[0] + linelist_df.loc[linelist_df.index, ""pipeline_version""] = ""{pipeline}"".format( + pipeline=""ncov-recombinant:{}"".format(pipeline_ver) + ) + nextclade_ver = linelist_df[""nextclade_version""].values[0] + nextclade_dataset = linelist_df[""nextclade_dataset""].values[0] + linelist_df.loc[ + linelist_df.index, ""recombinant_classifier_dataset"" + ] = ""{nextclade}:{dataset}"".format( + nextclade=""nextclade:{}"".format(nextclade_ver), + dataset=nextclade_dataset, + ) + + # ------------------------------------------------------------------------- + # Save to File + + logger.info(""Sorting output tables."") + + # Drop Unnecessary columns + linelist_df.drop( + columns=[ + ""status_sc2rf"", + ""clade_nextclade"", + ""subs_reversion"", + ""subs_labeled"", + ""subs_unlabeled"", + ""subs"", + ], + inplace=True, + ) + + # Convert privates from list to csv + linelist_df[""privates""] = ["","".join(p) for p in linelist_df[""privates""]] + + # Recode NA + linelist_df.fillna(NO_DATA_CHAR, inplace=True) + + # Sort + status_order = { + ""designated"": 0, + ""proposed"": 1, + ""unpublished"": 2, + ""false_positive"": 3, + ""negative"": 4, + } + + # Change empty cells to NaN so they'll be sorted to the end + linelist_df = linelist_df.replace({""lineage"": """", ""status"": """"}, np.nan) + linelist_df.sort_values( + [ + ""status"", + ""lineage"", + ], + inplace=True, + key=lambda x: x.map(status_order), + ) + + # All + outpath = os.path.join(outdir, ""linelist.tsv"") + logger.info(""Writing output: {}"".format(outpath)) + linelist_df.to_csv(outpath, sep=""\t"", index=False) + + # Positives + positive_df = linelist_df[ + (linelist_df[""status""] != ""false_positive"") + & (linelist_df[""status""] != ""negative"") + ] + outpath = os.path.join(outdir, ""positives.tsv"") + logger.info(""Writing output: {}"".format(outpath)) + positive_df.to_csv(outpath, sep=""\t"", index=False) + + # False Positives + false_positive_df = linelist_df[linelist_df[""status""] == ""false_positive""] + outpath = os.path.join(outdir, ""false_positives.tsv"") + logger.info(""Writing output: {}"".format(outpath)) + false_positive_df.to_csv(outpath, sep=""\t"", index=False) + + # Negatives + negative_df = linelist_df[linelist_df[""status""] == ""negative""] + outpath = os.path.join(outdir, ""negatives.tsv"") + logger.info(""Writing output: {}"".format(outpath)) + negative_df.to_csv(outpath, sep=""\t"", index=False) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/functions.py",".py","2230","77","import math +import matplotlib.pyplot as plt +import numpy as np +from matplotlib import colors +import logging +import sys + + +def create_logger(logfile=None): + # create logger + logger = logging.getLogger() + logger.setLevel(logging.DEBUG) + + # create file handler which logs even debug messages + if logfile: + handler = logging.FileHandler(logfile) + else: + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.DEBUG) + logger.addHandler(handler) + return logger + + +def categorical_palette(num_cat=9, continuous=False, cmap=""tab10"", cmap_num_cat=5): + """""" + Author: ImportanceOfBeingEarnest + Link: https://stackoverflow.com/a/47232942 + """""" + + num_sub_cat = 1 + + # if there are more data categories than cmap categories + if num_cat > cmap_num_cat: + # Determine subcategories + num_sub_cat = math.ceil(num_cat / cmap_num_cat) + + # Main palette for the categories + cat_cmap = plt.get_cmap(cmap) + + if continuous: + cat_colors = cat_cmap(np.linspace(0, 1, num_cat)) + else: + cat_colors = cat_cmap(np.arange(num_cat, dtype=int)) + + # Template out empty matrix to hold colors + color_palette = np.zeros((num_cat * num_sub_cat, 3)) + + # Iterate through the main colors + for i, color in enumerate(cat_colors): + + # Convert the rgb color to hsv + color_rgb = color[:3] + color_hsv = colors.rgb_to_hsv(color_rgb) + + # Create the colors for the sub-categories + color_hsv_subcat = np.tile(color_hsv, num_sub_cat).reshape(num_sub_cat, 3) + + # Keep hue the same + # Decrease saturation to a minimum of 0.25 + saturation = np.linspace(color_hsv[1], 0.25, num_sub_cat) + # Increase lightness to a maximum of 1.0 + lightness = np.linspace(color_hsv[2], 1, num_sub_cat) + + # Update the subcat hsv + color_hsv_subcat[:, 1] = saturation + color_hsv_subcat[:, 2] = lightness + + # Convert back to rgb + rgb = colors.hsv_to_rgb(color_hsv_subcat) + + # Update the template color palette + matrix_start = i * num_sub_cat + matrix_end = (i + 1) * num_sub_cat + color_palette[matrix_start:matrix_end, :] = rgb + + return color_palette +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/slurm.sh",".sh","2489","107","#!/bin/bash + +# ----------------------------------------------------------------------------- +# Argument Parsing + +num_args=""$#"" + +while [[ $# -gt 0 ]]; do + case $1 in + --profile) + profile=$2 + shift # past argument + shift # past value + ;; + --conda-env) + conda_env=$2 + shift # past argument + shift # past value + ;; + --target) + target=$2 + shift # past argument + shift # past value + ;; + --cpus) + cpus=$2 + shift # past argument + shift # past value + ;; + --mem) + mem=$2 + shift # past argument + shift # past value + ;; + -h|--help) + help=""true"" + shift # past argument + ;; + *) + echo ""Unknown option: $1"" + exit 1 + ;; + esac +done + +# ----------------------------------------------------------------------------- +# Usage + +if [[ $help || $num_args -eq 0 ]]; then + usage="" + usage: bash slurm.sh [-h] [--profile PROFILE] [--conda-env CONDA_ENV] [--target TARGET] [--partition PARTITION] [--cpus CPUS] [--mem MEM]\n\n + + \tDispatch a Snakemake pipeline using SLURM.\n\n + + \tRequired arguments:\n + \t\t--profile PROFILE \t\t Snakemake profile to execute (ex. profiles/tutorial-hpc)\n\n + + \tOptional arguments:\n + \t\t--conda-env CONDA_ENV \t\t Conda environment to use. (default: ncov-recombinant)\n + \t\t--target TARGET \t\t Snakemake target(s) to execute (default: all)\n + \t\t--cpus CPUS \t\t\t CPUS to use for the main pipeline. (default: 1)\n + \t\t--mem MEM \t\t\t Memory to use for the ain pipeline. (default: 4GB)\n + \t\t-h, --help \t\t\t Show this help message and exit. + "" + echo -e $usage + exit 0 +fi + +if [[ -z $profile ]]; then + echo ""ERROR: A profile must be specified with --profile "" + exit 1 +fi + +# Default arguments +conda_env=""${conda_env:-ncov-recombinant}"" +target=""${target:-all}"" +cpus=""${cpus:-1}"" +mem=""${mem:-4GB}"" + +today=$(date +""%Y-%m-%d"") +log_dir=""logs/ncov-recombinant"" + +if [[ $partition ]]; then + partition=""--partition $partition"" +fi + +# ----------------------------------------------------------------------------- +# Run the Workflow + +mkdir -p $log_dir + +# Just in case the conda_env is an absolute path +job_name=$(basename $conda_env) + +cmd="" +sbatch + --parsable + -c ${cpus} + --mem=${mem} + -J ${job_name} + -o ${log_dir}/%x_${today}_%j.log + --wrap=\""source activate $conda_env && snakemake --profile $profile $target\"" +"" + +echo $cmd +eval $cmd +","Shell" +"Microbiology","ktmeaton/ncov-recombinant","scripts/validate.py",".py","3016","101","#!/usr/bin/env python3 +import click +import pandas as pd +import os + +NO_DATA_CHAR = ""NA"" +VALIDATE_COLS = [""status"", ""lineage"", ""parents_clade"", ""breakpoints""] + + +@click.command() +@click.option(""--expected"", help=""Expected linelist (TSV)"", required=True) +@click.option(""--observed"", help=""Observed linelist (TSV)"", required=True) +@click.option(""--outdir"", help=""Output directory"", required=True) +def main( + expected, + observed, + outdir, +): + """"""Validate output"""""" + + # Check for output directory + if not os.path.exists(outdir): + os.makedirs(outdir) + + # Import Dataframes + expected_df = pd.read_csv(expected, sep=""\t"") + observed_df = pd.read_csv(observed, sep=""\t"") + + expected_df.fillna(NO_DATA_CHAR, inplace=True) + observed_df.fillna(NO_DATA_CHAR, inplace=True) + + output_data = { + ""strain"": [], + ""status"": [], + ""fail_cols"": [], + ""expected"": [], + ""observed"": [], + } + + # Validate observed values + for rec in observed_df.iterrows(): + strain = rec[1][""strain""] + fail_cols = [] + expected_vals = [] + observed_vals = [] + + # Check if this in the validation table + if strain not in expected_df[""strain""].values: + status = ""No Expected Values"" + else: + + # Check if all observed values match the expected values + match = True + + for col in VALIDATE_COLS: + exp_val = expected_df[expected_df[""strain""] == strain][col].values[0] + obs_val = observed_df[observed_df[""strain""] == strain][col].values[0] + + if exp_val != obs_val: + match = False + fail_cols.append(col) + expected_vals.append(exp_val) + observed_vals.append(obs_val) + + # Check if any columns failed matching + if match: + status = ""Pass"" + else: + status = ""Fail"" + + output_data[""strain""].append(strain) + output_data[""status""].append(status) + output_data[""fail_cols""].append("";"".join(fail_cols)) + output_data[""expected""].append("";"".join(expected_vals)) + output_data[""observed""].append("";"".join(observed_vals)) + + # Table of validation + output_df = pd.DataFrame(output_data) + outpath = os.path.join(outdir, ""validation.tsv"") + output_df.to_csv(outpath, sep=""\t"", index=False) + + # Overall build validation status + build_status = ""Pass"" + # Option 1. Fail if one sample failed + if ""Fail"" in output_data[""status""]: + build_status = ""Fail"" + # Option 2. Pass if values are all ""Pass"" or ""No Expected Values"" + elif ""Pass"" in output_data[""status""]: + build_status = ""Pass"" + # Option 2. No Expected Values + elif len(output_df) == 0: + build_status = ""No Expected Values"" + + outpath = os.path.join(outdir, ""status.txt"") + with open(outpath, ""w"") as outfile: + outfile.write(build_status + ""\n"") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/lineages.py",".py","5722","177","#!/usr/bin/env python3 +import click +import os +import pandas as pd +from datetime import datetime, date +import statistics + +# Hard-coded constants + +NO_DATA_CHAR = ""NA"" + + +# Select and rename columns from linelist +LINEAGE_COLS = [ + ""cluster_id"", + ""status"", + ""lineage"", + ""recombinant_lineage_curated"", + ""parents_clade"", + ""parents_lineage"", + ""parents_lineage_confidence"", + ""breakpoints"", + ""issue"", + ""sequences"", + ""growth_score"", + ""earliest_date"", + ""latest_date"", + ""rbd_level"", + ""immune_escape"", + ""ace2_binding"", + ""cluster_privates"", + ""cov-spectrum_query"", +] + + +@click.command() +@click.option( + ""--input"", help=""Input file of recombinant sequences (tsv)."", required=True +) +@click.option( + ""--output"", help=""Output file of recombinant lineages (tsv)"", required=True +) +@click.option(""--geo"", help=""Geography column"", required=False, default=""country"") +def main( + input, + output, + geo, +): + """"""Create a table of recombinant lineages"""""" + + # ------------------------------------------------------------------------- + # Setup + # ------------------------------------------------------------------------- + + # Misc variables + outdir = os.path.dirname(output) + if not os.path.exists(outdir): + os.mkdir(outdir) + + df = pd.read_csv(input, sep=""\t"") + df.fillna(NO_DATA_CHAR, inplace=True) + + issues_format = [] + + for issue in df[""issue""]: + if type(issue) == int: + issues_format.append(int(issue)) + elif type(issue) == float: + issue = str(int(issue)) + issues_format.append(issue) + elif type(issue) == str: + issues_format.append(issue) + + df[""issue""] = issues_format + + # Issue #168 NULL dates are allowed + # Set to today instead + # https://github.com/ktmeaton/ncov-recombinant/issues/168 + seq_date = [] + for d in list(df[""date""]): + try: + d = datetime.strptime(d, ""%Y-%m-%d"").date() + except ValueError: + # Set NA dates to today + d = date.today() + + seq_date.append(d) + df[""datetime""] = seq_date + + # ------------------------------------------------------------------------- + # Create the recombinants table (recombinants.tsv) + # ------------------------------------------------------------------------- + + recombinants_data = {col: [] for col in LINEAGE_COLS} + recombinants_data[geo] = [] + + for cluster_id in set(df[""cluster_id""]): + + match_df = df[df[""cluster_id""] == cluster_id] + + earliest_date = min(match_df[""datetime""]) + latest_date = max(match_df[""datetime""]) + sequences = len(match_df) + + # Summaize rbd_level by the mode + rbd_level = statistics.mode(match_df[""rbd_level""]) + # Summarize immune escape by mean, Immune escape can be NA + immune_escape = [ + val for val in match_df[""immune_escape""].values if val != NO_DATA_CHAR + ] + if len(immune_escape) > 0: + immune_escape = statistics.mean(match_df[""immune_escape""].values) + else: + immune_escape = NO_DATA_CHAR + + # Summarize ace2_binding by mean, ace2_binding can be NA + ace2_binding = [ + val for val in match_df[""ace2_binding""].values if val != NO_DATA_CHAR + ] + if len(ace2_binding) > 0: + ace2_binding = statistics.mean(match_df[""ace2_binding""].values) + else: + ace2_binding = NO_DATA_CHAR + + recombinants_data[""cluster_id""].append(cluster_id) + recombinants_data[""status""].append(match_df[""status""].values[0]) + recombinants_data[""lineage""].append(match_df[""lineage""].values[0]) + recombinants_data[""recombinant_lineage_curated""].append( + match_df[""recombinant_lineage_curated""].values[0] + ) + recombinants_data[""parents_clade""].append(match_df[""parents_clade""].values[0]) + recombinants_data[""parents_lineage""].append( + match_df[""parents_lineage""].values[0] + ) + recombinants_data[""parents_lineage_confidence""].append( + match_df[""parents_lineage_confidence""].values[0] + ) + recombinants_data[""breakpoints""].append(match_df[""breakpoints""].values[0]) + recombinants_data[""issue""].append(match_df[""issue""].values[0]) + recombinants_data[""sequences""].append(sequences) + recombinants_data[""earliest_date""].append(earliest_date) + recombinants_data[""latest_date""].append(latest_date) + recombinants_data[""cluster_privates""].append( + match_df[""cluster_privates""].values[0] + ) + recombinants_data[""cov-spectrum_query""].append( + match_df[""cov-spectrum_query""].values[0] + ) + # Immune stats + recombinants_data[""rbd_level""].append(rbd_level) + recombinants_data[""immune_escape""].append(immune_escape) + recombinants_data[""ace2_binding""].append(ace2_binding) + + geo_list = list(set(match_df[geo])) + geo_list.sort() + geo_counts = [] + for loc in geo_list: + loc_df = match_df[match_df[geo] == loc] + num_sequences = len(loc_df) + geo_counts.append(""{} ({})"".format(loc, num_sequences)) + + recombinants_data[geo].append("", "".join(geo_counts)) + + # Growth Calculation + growth_score = 0 + duration = (latest_date - earliest_date).days + 1 + growth_score = round(sequences / duration, 2) + recombinants_data[""growth_score""].append(growth_score) + + recombinants_df = pd.DataFrame(recombinants_data) + recombinants_df.sort_values(by=""sequences"", ascending=False, inplace=True) + recombinants_df.to_csv(output, index=False, sep=""\t"") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/lineage_tree.py",".py","2827","94","#!/usr/bin/env python3 + +import click +import os +from Bio import Phylo +from Bio.Phylo.BaseTree import Clade +import requests +from pango_aliasor.aliasor import Aliasor + +LINEAGES_URL = ( + ""https://raw.githubusercontent.com/cov-lineages/pango-designation/master/"" + + ""lineage_notes.txt"" +) + + +@click.command() +@click.option(""--output"", help=""Output newick phylogeny."", required=True) +def main(output): + """"""Create a nomenclature tree of pango lineages."""""" + + # Create output directory if it doesn't exist + outdir = os.path.dirname(output) + if not os.path.exists(outdir) and outdir != """": + os.mkdir(outdir) + + # ------------------------------------------------------------------------- + # Download Latest designated lineages from pango-designation + + print(""Downloading list of lineages: {}"".format(LINEAGES_URL)) + r = requests.get(LINEAGES_URL) + lineage_text = r.text + + # Convert the text table to list + lineages = [] + for line in lineage_text.split(""\n""): + if ""Withdrawn"" in line or line.startswith(""Lineage""): + continue + + lineage = line.split(""\t"")[0] + if lineage == """": + continue + lineages.append(lineage) + + # Initialize the aliasor, which will download the latest aliases + aliasor = Aliasor() + + # ------------------------------------------------------------------------- + # Construct Tree + + print(""Constructing tree."") + + # Create a tree with a root node ""MRCA"" + tree = Clade(name=""MRCA"", clades=[], branch_length=1) + # Add an ""X"" parent for recombinants + clade = Clade(name=""X"", clades=[], branch_length=1) + tree.clades.append(clade) + + for lineage in lineages: + + # Identify the parent + lineage_uncompress = aliasor.uncompress(lineage) + parent_uncompress = ""."".join(lineage_uncompress.split(""."")[0:-1]) + parent = aliasor.compress(parent_uncompress) + + # Manual parents setting for A and B + if lineage == ""A"": + parent = ""MRCA"" + + elif lineage == ""B"": + parent = ""A"" + + # Special handling for recombinants + elif lineage.startswith(""X"") and parent == """": + parent = ""X"" + + parent_clade = [c for c in tree.find_clades(parent)] + # If we found a parent, as long as the input list is formatted correctly + # this should always be true + if len(parent_clade) == 1: + parent_clade = parent_clade[0] + clade = Clade(name=lineage, clades=[], branch_length=1) + parent_clade.clades.append(clade) + + # ------------------------------------------------------------------------- + # Export + + tree_outpath = os.path.join(output) + print(""Exporting tree: {}"".format(tree_outpath)) + Phylo.write(tree, tree_outpath, ""newick"") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/parents.py",".py","2399","91","#!/usr/bin/env python3 +import click +import os +import pandas as pd +from datetime import datetime, date + +# Hard-coded constants + +NO_DATA_CHAR = ""NA"" + + +# Select and rename columns from linelist +PARENTS_COLS = [ + ""parents_clade"", + ""sequences"", + ""earliest_date"", + ""latest_date"", +] + + +@click.command() +@click.option( + ""--input"", help=""Input file of recombinant sequences (tsv)."", required=True +) +@click.option( + ""--output"", help=""Output file of recombinant lineages (tsv)"", required=True +) +def main( + input, + output, +): + """"""Create a table of recombinant sequences by parent"""""" + + # ------------------------------------------------------------------------- + # Setup + # ------------------------------------------------------------------------- + + # Misc variables + outdir = os.path.dirname(input) + if not os.path.exists(outdir): + os.mkdir(outdir) + + df = pd.read_csv(input, sep=""\t"") + df.fillna(NO_DATA_CHAR, inplace=True) + + # Issue #168 NULL dates are allowed + # Set to today instead + # https://github.com/ktmeaton/ncov-recombinant/issues/168 + seq_date = [] + for d in list(df[""date""]): + try: + d = datetime.strptime(d, ""%Y-%m-%d"").date() + except ValueError: + # Set NA dates to today + d = date.today() + + seq_date.append(d) + df[""datetime""] = seq_date + + # ------------------------------------------------------------------------- + # Create the parents table (parents.tsv) + # ------------------------------------------------------------------------- + + data = {col: [] for col in PARENTS_COLS} + + for parents_clade in set(df[""parents_clade""]): + + match_df = df[df[""parents_clade""] == parents_clade] + + if parents_clade == NO_DATA_CHAR: + parents_clade = ""Unknown"" + + earliest_date = min(match_df[""datetime""]) + latest_date = max(match_df[""datetime""]) + sequences = len(match_df) + + data[""parents_clade""].append(parents_clade) + data[""sequences""].append(sequences) + data[""earliest_date""].append(earliest_date) + data[""latest_date""].append(latest_date) + + parents_df = pd.DataFrame(data) + parents_df.sort_values(by=""sequences"", ascending=False, inplace=True) + + outpath = os.path.join(outdir, ""parents.tsv"") + parents_df.to_csv(outpath, index=False, sep=""\t"") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/plot.py",".py","19892","608","#!/usr/bin/env python3 +import click +import os +import pandas as pd +import numpy as np +import epiweeks +import matplotlib.pyplot as plt +from matplotlib import patches, colors +from datetime import datetime, timedelta, date +import sys +import copy +from functions import categorical_palette +import math +import warnings +from functions import create_logger +import logging + +logging.getLogger(""matplotlib.font_manager"").disabled = True + +warnings.filterwarnings(""error"") + +NO_DATA_CHAR = ""NA"" +ALPHA_LAG = 0.25 +ALPHA_BAR = 1.00 +WIDTH_BAR = 0.75 +EPIWEEK_MAX_BUFF_FACTOR = 1.1 +# This is the aspect ratio/dpi for ppt embeds +# The dimensions are set in the powerpoint template (resources/template.pttx) +DPI = 96 * 2 +FIGSIZE = [6.75, 5.33] +# The maximum number of epiweeks we can comfortably plot, otherwise +# the figsize needs to be upscaled +FIGSIZE_MAX_WEEKS = 65 + +UNKNOWN_COLOR = ""dimgrey"" +UNKNOWN_RGB = colors.to_rgb(UNKNOWN_COLOR) + +# This is the number of characters than can fit width-wise across the legend +LEGEND_FONTSIZE = 6 +LEGEND_CHAR_WIDTH = 90 +# The maximum columns in the legend is dictated by the char width, but more +# importantly, in the categorical_palette function, we restrict it to the +# first 5 colors of the tap10 palette, and make different shades within it +LEGEND_MAX_COL = 5 + +# Show the first N char of the label in the plot +LEGEND_LABEL_MAX_LEN = 15 + +# This is the maximum number of key RBD mutations. +MAX_RBD_LEVEL = 12 + +# Select and rename columns from linelist +LINEAGES_COLS = [ + ""cluster_id"", + ""status"", + ""lineage"", + ""parents_clade"", + ""parents_lineage"", + ""breakpoints"", + ""issue"", + ""sequences"", + ""growth_score"", + ""earliest_date"", + ""latest_date"", +] + +plt.rcParams[""svg.fonttype""] = ""none"" + + +@click.command() +@click.option(""--input"", help=""Recombinant sequences (TSV)"", required=True) +@click.option(""--outdir"", help=""Output directory"", required=False, default=""."") +@click.option( + ""--weeks"", + help=""Number of weeks in retrospect to plot"", + required=False, +) +@click.option( + ""--min-date"", + help=""Ignore sequences before this date (yyyy-mm-dd, overrides --weeks)"", + required=False, +) +@click.option(""--max-date"", help=""Ignore sequences after this date"", required=False) +@click.option( + ""--geo"", + help=""Geography column to use when plotting"", + required=False, + default=""country"", +) +@click.option( + ""--lag"", help=""Reporting lag weeks to draw a grey box"", required=False, default=4 +) +@click.option( + ""--min-cluster-size"", + help=""Only plot clusters/lineages with at least this many sequences."", + default=1, +) +@click.option(""--log"", help=""Output log file."", required=False) +def main( + input, + outdir, + weeks, + geo, + lag, + min_date, + max_date, + min_cluster_size, + log, +): + """"""Plot recombinant lineages"""""" + + # create logger + logger = create_logger(logfile=log) + + # Creat output directory if it doesn't exist + if not os.path.exists(outdir): + os.mkdir(outdir) + + # ------------------------------------------------------------------------- + # Import dataframes + logger.info(""Importing linelist: {}"".format(input)) + df = pd.read_csv(input, sep=""\t"") + df.fillna(NO_DATA_CHAR, inplace=True) + + # Issue #168 NULL dates are allowed + # Set to today instead + # https://github.com/ktmeaton/ncov-recombinant/issues/168 + seq_date = [] + for d in list(df[""date""]): + try: + d = datetime.strptime(d, ""%Y-%m-%d"").date() + except ValueError: + # Set NA dates to today + d = date.today() + + seq_date.append(d) + df[""datetime""] = seq_date + + df[""year""] = [d.year for d in df[""datetime""]] + df[""epiweek""] = [ + epiweeks.Week.fromdate(d, system=""cdc"").startdate() for d in df[""datetime""] + ] + + # Filter on weeks reporting + logger.info(""Filtering on data"") + if max_date: + max_datetime = datetime.strptime(max_date, ""%Y-%m-%d"") + max_epiweek = epiweeks.Week.fromdate(max_datetime, system=""cdc"").startdate() + else: + max_epiweek = epiweeks.Week.fromdate(datetime.today(), system=""cdc"").startdate() + + if min_date: + min_datetime = datetime.strptime(min_date, ""%Y-%m-%d"") + min_epiweek = epiweeks.Week.fromdate(min_datetime, system=""cdc"").startdate() + elif weeks: + weeks = int(weeks) + min_epiweek = max_epiweek - timedelta(weeks=(weeks - 1)) + elif len(df) == 0: + # Just need something for empty plots + min_epiweek = max_epiweek - timedelta(weeks=16) + else: + min_epiweek = epiweeks.Week.fromdate( + min(df[""epiweek""]), system=""cdc"" + ).startdate() + + weeks = int((max_epiweek - min_epiweek).days / 7) + + # Dummy data outside of plotting range when empty + one_week_prev = min_epiweek - timedelta(weeks=1) + + df = copy.deepcopy( + df[(df[""epiweek""] >= min_epiweek) & (df[""epiweek""] <= max_epiweek)] + ) + + # Change status to title case + df[""status""] = [s.title() for s in df[""status""]] + + # Get largest lineage + largest_lineage = NO_DATA_CHAR + largest_lineage_size = 0 + + # All record cluster sizes to decided which should be dropped + drop_small_clusters_ids = [] + + for lineage in set(df[""recombinant_lineage_curated""]): + match_df = df[df[""recombinant_lineage_curated""] == lineage] + lineage_size = len(match_df) + if lineage_size >= largest_lineage_size: + largest_lineage = match_df[""recombinant_lineage_curated""].values[0] + largest_lineage_size = lineage_size + + if lineage_size < min_cluster_size: + for i in match_df.index: + drop_small_clusters_ids.append(i) + + df.drop(labels=drop_small_clusters_ids, axis=""rows"", inplace=True) + + df[""parents_clade""] = df[""parents_clade""].fillna(""Unknown"") + df[""parents_lineage""] = df[""parents_lineage""].fillna(""Unknown"") + + # ------------------------------------------------------------------------- + # Pivot Tables + # ------------------------------------------------------------------------- + + logger.info(""Creating pivot tables"") + # ------------------------------------------------------------------------- + # All + all_df = pd.pivot_table( + data=df.sort_values(by=""epiweek""), + values=""strain"", + index=[""epiweek""], + aggfunc=""count"", + ) + all_df.index.name = None + all_df.fillna(0, inplace=True) + all_df.insert(0, ""epiweek"", all_df.index) + # Check if it was empty + if len(all_df) == 0: + all_df.insert(1, ""sequences"", []) + max_epiweek_sequences = 0 + else: + all_df.rename(columns={""strain"": ""sequences""}, inplace=True) + max_epiweek_sequences = max(all_df[""sequences""]) + + # Attempt to dynamically create pivot tables + plot_dict = { + ""lineage"": { + ""legend_title"": ""lineage"", + ""cols"": [""recombinant_lineage_curated""], + ""y"": ""recombinant_lineage_curated"", + }, + ""status"": {""legend_title"": ""status"", ""cols"": [""status""]}, + ""geography"": {""legend_title"": geo, ""cols"": [geo]}, + ""largest"": { + ""legend_title"": geo, + ""cols"": [geo], + ""filter"": ""recombinant_lineage_curated"", + ""value"": largest_lineage, + }, + ""designated"": { + ""legend_title"": ""lineage"", + ""cols"": [""recombinant_lineage_curated""], + ""filter"": ""status"", + ""value"": ""Designated"", + }, + ""proposed"": { + ""legend_title"": ""lineage"", + ""cols"": [""recombinant_lineage_curated""], + ""filter"": ""status"", + ""value"": ""Proposed"", + }, + ""unpublished"": { + ""legend_title"": ""lineage"", + ""cols"": [""recombinant_lineage_curated""], + ""filter"": ""status"", + ""value"": ""Unpublished"", + }, + ""parents_clade"": {""legend_title"": ""Parents (Clade)"", ""cols"": [""parents_clade""]}, + ""parents_lineage"": { + ""legend_title"": ""Parents (Lineage)"", + ""cols"": [""parents_lineage""], + }, + ""cluster_id"": {""legend_title"": ""Cluster ID"", ""cols"": [""cluster_id""]}, + ""rbd_level"": { + ""legend_title"": ""Receptor Binding Domain Mutations"", + ""cols"": [""rbd_level""], + }, + } + + for plot in plot_dict: + + logger.info(""Creating plot data: {}"".format(plot)) + columns = plot_dict[plot][""cols""] + + # Several plots need special filtering + if ""filter"" in plot_dict[plot]: + filter = plot_dict[plot][""filter""] + value = plot_dict[plot][""value""] + + plot_df = pd.pivot_table( + data=df[df[filter] == value].sort_values(by=""epiweek""), + values=""strain"", + index=[""epiweek""], + columns=columns, + aggfunc=""count"", + ) + + # Otherwise no filtering required + else: + plot_df = pd.pivot_table( + data=df.sort_values(by=""epiweek""), + index=[""epiweek""], + values=""strain"", + aggfunc=""count"", + columns=columns, + ) + + plot_df.index.name = None + plot_df.fillna(0, inplace=True) + + # Convert counts from floats to integers + plot_df[plot_df.columns] = plot_df[plot_df.columns].astype(int) + + # Fill in missing levels for RBD + if plot == ""rbd_level"" and len(plot_df) > 0: + # min_level = min(plot_df.columns) + # max_level = max(plot_df.columns) + min_level = 0 + max_level = MAX_RBD_LEVEL + + for level in range(min_level, max_level + 1, 1): + if level not in plot_df.columns: + plot_df[level] = 0 + + # Defragment dataframe for Issue #218 + plot_df = copy.copy(plot_df) + + # Add epiweeks column + plot_df.insert(0, ""epiweek"", plot_df.index) + + plot_dict[plot][""df""] = plot_df + + # ---------------------------------------------------------- + # Filter for Reporting Period + # ------------------------------------------------------------------------- + + # Add empty data for weeks if needed + epiweek_map = {} + iter_week = min_epiweek + iter_i = 0 + df_list = [plot_dict[plot][""df""] for plot in plot_dict] + while iter_week <= max_epiweek: + + for plot_df in df_list: + + if iter_week not in plot_df[""epiweek""]: + plot_df.at[iter_week, ""epiweek""] = iter_week + + # Check if its the largest + epiweek_map[iter_week] = iter_i + iter_week += timedelta(weeks=1) + iter_i += 1 + + for plot_df in df_list: + plot_df.fillna(0, inplace=True) + plot_df.sort_values(by=""epiweek"", axis=""index"", inplace=True) + + lag_epiweek = max_epiweek - timedelta(weeks=lag) + + # ------------------------------------------------------------------------- + # Plot + # ------------------------------------------------------------------------- + + for plot in plot_dict: + + logger.info(""Creating plot figure: {}"".format(plot)) + + plot_df = plot_dict[plot][""df""] + + x = ""epiweek"" + label = plot + legend_title = plot_dict[plot][""legend_title""] + out_path = os.path.join(outdir, label) + + # Save plotting dataframe to file + # for the largest, we need to replace the slashes in the filename + if label == ""largest"": + largest_lineage_fmt = largest_lineage.replace(""/"", ""_DELIM_"") + out_path += ""_{lineage}"".format(lineage=largest_lineage_fmt) + + plot_df.to_csv(out_path + "".tsv"", sep=""\t"", index=False) + + # --------------------------------------------------------------------- + # Sort categories by count + + # The df is sorted by time (epiweek) + # But we want colors to be sorted by number of sequences + df_count_dict = {} + for col in plot_df.columns: + if col == ""epiweek"": + continue + df_count_dict[col] = sum([c for c in plot_df[col] if not np.isnan(c)]) + + # Sort by counts, except for RBD level, want sorted by value itself + if label == ""rbd_level"": + df_count_dict = dict(sorted(df_count_dict.items())) + else: + df_count_dict = dict( + sorted(df_count_dict.items(), key=lambda item: item[1], reverse=True) + ) + # Reorder the columns in the data frame + cols = list(df_count_dict.keys()) + + # Place Unknown at the end, for better color palettes + if ""Unknown"" in cols: + cols.remove(""Unknown"") + ordered_cols = cols + [""Unknown""] + [""epiweek""] + else: + ordered_cols = cols + [""epiweek""] + + plot_df = plot_df[ordered_cols] + + # --------------------------------------------------------------------- + # Dynamically create the color palette + + num_cat = len(plot_df.columns) - 1 + + if label == ""rbd_level"" and len(plot_df.columns) > 1: + num_cat = len(range(min(cols), max(cols) + 1, 1)) + plot_palette = categorical_palette( + num_cat=num_cat, cmap=""RdYlGn_r"", continuous=True, cmap_num_cat=999 + ) + + # Otherwise use default form function + else: + plot_palette = categorical_palette(num_cat=num_cat) + + # Recolor unknown + if ""Unknown"" in plot_df.columns: + unknown_i = list(plot_df.columns).index(""Unknown"") + plot_palette[unknown_i] = list(UNKNOWN_RGB) + + # Setup up Figure + fig, ax = plt.subplots(1, figsize=FIGSIZE, dpi=DPI) + + # --------------------------------------------------------------------- + # Stacked bar charts + + # Check if we dropped all records + if len(plot_df.columns) <= 1: + error_msg = ( + ""WARNING: No records to plot between"" + + "" {min_epiweek} and {max_epiweek} for dataframe: {plot}"".format( + plot=plot, + min_epiweek=min_epiweek, + max_epiweek=max_epiweek, + ) + ) + print(error_msg, file=sys.stderr) + # Add dummy data to force an empty plot + plot_df[""dummy""] = [None] * len(plot_df) + plot_df.at[one_week_prev, ""epiweek""] = one_week_prev + plot_df.at[one_week_prev, ""dummy""] = 1 + plot_df.sort_values(by=""epiweek"", inplace=True) + + plot_palette = categorical_palette(num_cat=1) + + plot_df.plot.bar( + stacked=True, + ax=ax, + x=x, + color=plot_palette, + edgecolor=""none"", + width=WIDTH_BAR, + alpha=ALPHA_BAR, + ) + + # --------------------------------------------------------------------- + # Axis limits + + xlim = ax.get_xlim() + # If plotting 16 weeks, the x-axis will be (-0.625, 16.625) + # If we added dummy data, need to correct start date + x_start = xlim[1] - weeks - 1.25 + ax.set_xlim(x_start, xlim[1]) + + if max_epiweek_sequences == 0: + ylim = [0, 1] + else: + ylim = [0, round(max_epiweek_sequences * EPIWEEK_MAX_BUFF_FACTOR, 1)] + ax.set_ylim(ylim[0], ylim[1]) + + # --------------------------------------------------------------------- + # Reporting Lag + + # If the scope of the data is smaller than the lag + if lag_epiweek in epiweek_map: + lag_i = epiweek_map[lag_epiweek] + else: + lag_i = epiweek_map[max_epiweek] + + lag_rect_height = ylim[1] + + # If we had to use dummy data for an empty dataframe, shift lag by 1 + if ""dummy"" in plot_df.columns: + lag_i += 1 + + ax.axvline(x=lag_i + (1 - (WIDTH_BAR) / 2), color=""black"", linestyle=""--"", lw=1) + lag_rect_xy = [lag_i + (1 - (WIDTH_BAR) / 2), 0] + lag_rect = patches.Rectangle( + xy=lag_rect_xy, + width=lag + (1 - (WIDTH_BAR) / 2), + height=lag_rect_height, + linewidth=1, + edgecolor=""none"", + facecolor=""grey"", + alpha=ALPHA_LAG, + zorder=0, + ) + ax.add_patch(lag_rect) + + # Label the lag rectangle + text_props = dict(facecolor=""white"") + ax.text( + x=lag_rect_xy[0], + y=ylim[1] / 2, + s=""Reporting Lag"", + fontsize=6, + fontweight=""bold"", + rotation=90, + bbox=text_props, + va=""center"", + ha=""center"", + ) + + # --------------------------------------------------------------------- + # Legend + + # Dynamically set the number of columns in the legend based on how + # how much space the labels will take up (in characters) + max_char_len = 0 + for col in ordered_cols: + if len(str(col)) >= max_char_len: + max_char_len = len(str(col)) + + legend_ncol = math.floor(LEGEND_CHAR_WIDTH / max_char_len) + + # we don't want too many columns + if legend_ncol > LEGEND_MAX_COL: + legend_ncol = LEGEND_MAX_COL + elif legend_ncol > num_cat: + legend_ncol = num_cat + elif legend_ncol == 0: + legend_ncol = 1 + + legend = ax.legend( + title=legend_title.title(), + edgecolor=""black"", + fontsize=LEGEND_FONTSIZE, + ncol=legend_ncol, + loc=""lower center"", + mode=""expand"", + bbox_to_anchor=(0, 1.02, 1, 0.2), + borderaxespad=0, + ) + + # Truncate long labels in the legend + # But only if this plots does not involve plotting parents! + # Because we need to see the 2+ parent listed at the end + if ( + ""parents"" not in label + and ""geography"" not in label + and ""largest"" not in label + ): + for i in range(0, len(legend.get_texts())): + + l_label = legend.get_texts()[i].get_text() + + if len(l_label) > LEGEND_LABEL_MAX_LEN: + l_label = l_label[0:LEGEND_LABEL_MAX_LEN] + if ""("" in l_label and "")"" not in l_label: + l_label = l_label + ""...)"" + else: + l_label = l_label + ""..."" + + legend.get_texts()[i].set_text(l_label) + + legend.get_frame().set_linewidth(1) + legend.get_title().set_fontweight(""bold"") + + # If dummy is a column, there were no records and added fake data for plot + if ""dummy"" in plot_df.columns: + legend.remove() + + # --------------------------------------------------------------------- + # Axes + + xlim = ax.get_xlim() + # If plotting 16 weeks, the x-axis will be (-0.625, 16.625) + # If we added dummy data, need to correct start date + x_start = xlim[1] - weeks - 1.25 + ax.set_xlim(x_start, xlim[1]) + ax.set_ylim(ylim[0], ylim[1]) + ax.set_ylabel(""Number of Sequences"", fontweight=""bold"") + ax.set_xlabel(""Start of Week"", fontweight=""bold"") + # ax.xaxis.set_label_coords(0.5, -0.30) + ax.set_xticklabels(ax.get_xticklabels(), rotation=90, ha=""center"", fontsize=6) + + # Upscale plot dimensions if there are too many weeks + if len(plot_df) > FIGSIZE_MAX_WEEKS: + upscale_factor = len(plot_df) / FIGSIZE_MAX_WEEKS + fig.set_size_inches( + FIGSIZE[0] * upscale_factor, + FIGSIZE[1] * upscale_factor, + ) + + # Attempt to see whether we can apply a tight layout + try: + plt.tight_layout() + plt.savefig(out_path + "".png"") + plt.savefig(out_path + "".svg"") + except UserWarning: + logger.info(""Unable to apply tight_layout, plot will not be saved."") + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","ktmeaton/ncov-recombinant","scripts/create_profile.sh",".sh","6869","221","#!/bin/bash + +# ----------------------------------------------------------------------------- +# Argument Parsing + +num_args=""$#"" + +while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + help=""true"" + shift # past argument + ;; + --hpc) + hpc=""true"" + shift # past argument + ;; + --controls) + controls=""true"" + shift # past argument + ;; + --profile-dir) + profile_dir=$2 + shift # past argument + shift # past value + ;; + --data) + data=$2 + shift # past argument + shift # past value + ;; + *) + echo ""Unknown option: $1"" + exit 1 + ;; + esac +done + +# ----------------------------------------------------------------------------- +# Usage + +if [[ $help || $num_args -eq 0 ]]; then + usage="" + usage: bash template_build.sh [-h,--help] [--data DATA] [--hpc] [--profile-dir]\n\n + + \tCreate a template build for the ncov-recombinant Snakemake pipeline.\n\n + + \tRequired arguments:\n + \t\t--data DATA \t\t Path to the directory where sequences and metadata are stored (ex. data/custom)\n\n + + \tOptional arguments:\n + \t\t--hpc \t\t\t Configure build for HPC execution using SLURM.\n + \t\t--profile-dir \t\t\t Directory to create the profile in (default: my_profiles)\n + \t\t--controls \t\t\t Add the controls build\n + \t\t-h, --help \t\t Show this help message and exit. + "" + echo -e $usage + exit 0 +fi + +if [[ -z $data ]]; then + echo ""ERROR: A data directory must be specified with --data "" + exit 1 +fi + + +NUM_REQUIRED_COLS=3 +REQUIRED_COLS=""strain|date|country"" +FIRST_COL=""strain"" +DEFAULT_PARAMS=""defaults/parameters.yaml"" +DEFAULT_BUILDS=""defaults/builds.yaml"" +EXCLUDE_CONTROLS_BUILDS=""defaults/builds-exclude-controls.yaml"" +DEFAULT_CONFIG=""profiles/controls/config.yaml"" +DEFAULT_CONFIG_HPC=""profiles/controls-hpc/config.yaml"" + +profile_dir=${profile_dir:-my_profiles} +profile=$(basename $data) + +if [[ $controls ]]; then + profile=""${profile}-controls"" +fi + +if [[ $hpc ]]; then + profile=""${profile}-hpc"" +fi + +mkdir -p $profile_dir + +# ----------------------------------------------------------------------------- +# Validate Inputs + +# Metadata Check +echo -e ""$(date ""+%Y-%m-%d %T"")\tSearching for metadata ($data/metadata.tsv)"" +check=$(ls $data/metadata.tsv 2> /dev/null) +if [[ $check ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tSUCCESS: metadata found"" +else + echo -e ""$(date ""+%Y-%m-%d %T"")\tFAIL: Metadata not found!"" + exit 1 +fi + +# Metadata Validate +echo -e ""$(date ""+%Y-%m-%d %T"")\tChecking for $NUM_REQUIRED_COLS required metadata columns ($(echo $REQUIRED_COLS | tr ""|"" "" "" ))"" +num_required_cols=$(head -n 1 $data/metadata.tsv | tr ""\t"" ""\n"" | grep -w -E ""$REQUIRED_COLS"" | wc -l) +first_col=$(head -n 1 $data/metadata.tsv | cut -f 1) + + +if [[ $num_required_cols -eq $NUM_REQUIRED_COLS ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tSUCCESS: $NUM_REQUIRED_COLS columns found."" +elif [[ ""$first_col"" != ""$FIRST_COL"" ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tFAIL: First column ($first_col) is not '$FIRST_COL'"" +elif [[ ! $num_required_cols -eq $NUM_REQUIRED_COLS ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tFAIL: $NUM_REQUIRED_COLS columns not found!"" + exit 1 +fi + +# Sequences Check +echo -e ""$(date ""+%Y-%m-%d %T"")\tSearching for sequences ($data/sequences.fasta)"" +check=$(ls $data/sequences.fasta 2> /dev/null) +if [[ $check ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tSUCCESS: Sequences found"" +else + echo -e ""$(date ""+%Y-%m-%d %T"")\tFAIL: Sequences not found!"" + exit 1 +fi + +# Match seqs and metadata +echo -e ""$(date ""+%Y-%m-%d %T"")\tChecking that the metadata strains match the sequence names"" +grep "">"" $data/sequences.fasta | sed 's/>//g' > tmp.seq_names +cut -f 1 $data/metadata.tsv | tail -n+2 > tmp.meta_names +diff_names=$(cat tmp.seq_names tmp.meta_names | sort | uniq -u) +# Reminder, var name is delib differently from input +seq_missing=$(echo $diff_names | tr "" "" ""\n"" | grep -f - tmp.meta_names) +meta_missing=$(echo $diff_names | tr "" "" ""\n"" | grep -f - tmp.seq_names) + +# Cleanup tmp files +rm -f tmp.seq_names +rm -f tmp.meta_names + +if [[ -z ""$diff_names"" ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tSUCCESS: Strain column matches sequence names"" +else + echo -e ""$(date ""+%Y-%m-%d %T"")\tFAIL: Strain column does not match the sequence names!"" + echo -e ""$(date ""+%Y-%m-%d %T"")\tStrains missing from $data/sequences.fasta:"" + echo $seq_missing | tr "" "" ""\n"" | sed 's/^/\t\t\t\t/g' + echo -e ""$(date ""+%Y-%m-%d %T"")\tStrains missing from $data/metadata.tsv:"" + echo $meta_missing | tr "" "" ""\n"" | sed 's/^/\t\t\t\t/g' + exit 1 +fi + + +# ----------------------------------------------------------------------------- +# Profile + +# Create profile directory +echo -e ""$(date ""+%Y-%m-%d %T"")\tCreating new profile directory ($profile_dir/$profile)"" +mkdir -p $profile_dir/$profile + +# ----------------------------------------------------------------------------- +# Build + +# Create builds.yaml +echo -e ""$(date ""+%Y-%m-%d %T"")\tCreating build file ($profile_dir/$profile/builds.yaml)"" + +# Add controls build, unless excluded +if [[ $controls == ""true"" ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tAdding \`controls\` as a build"" + cat $DEFAULT_BUILDS > $profile_dir/$profile/builds.yaml +else + cat $EXCLUDE_CONTROLS_BUILDS > $profile_dir/$profile/builds.yaml +fi + +#Add custom build +echo -e ""$(date ""+%Y-%m-%d %T"")\tAdding \`$(basename $data)\` as a build"" + +echo -e ""\n + # --------------------------------------------------------------------------- + # $(basename $data) build\n + - name: $(basename $data) + metadata: $data/metadata.tsv + sequences: $data/sequences.fasta +"" >> $profile_dir/$profile/builds.yaml + +# ----------------------------------------------------------------------------- +# Config + +# Create config.yaml +echo -e ""$(date ""+%Y-%m-%d %T"")\tCreating system configuration ($profile_dir/$profile/config.yaml)"" +if [[ $hpc ]]; then + echo -e ""$(date ""+%Y-%m-%d %T"")\tAdding default HPC system resources"" + cp -f $DEFAULT_CONFIG_HPC $profile_dir/$profile/config.yaml +else + echo -e ""$(date ""+%Y-%m-%d %T"")\tAdding default system resources"" + cp -f $DEFAULT_CONFIG $profile_dir/$profile/config.yaml +fi +sed -i ""s|profiles/controls/builds.yaml|$profile_dir/$profile/builds.yaml|g"" $profile_dir/$profile/config.yaml + + +echo -e ""$(date ""+%Y-%m-%d %T"")\tDone!"" + +echo -e ""$(date ""+%Y-%m-%d %T"")\tSystem resources can be further configured in:"" +echo -e "" +\t\t\t$profile_dir/$profile/config.yaml +"" + +echo -e ""$(date ""+%Y-%m-%d %T"")\tBuilds can be configured in:"" +echo -e "" +\t\t\t$profile_dir/$profile/builds.yaml +"" + +echo -e ""$(date ""+%Y-%m-%d %T"")\tThe $profile profile is ready to be run with:"" +if [[ $hpc ]]; then + echo -e "" + \t\t\tscripts/slurm.sh --profile $profile_dir/$profile + "" +else + echo -e "" + \t\t\tsnakemake --profile $profile_dir/$profile + "" +fi +","Shell" +"Microbiology","ktmeaton/ncov-recombinant","scripts/summary.sh",".sh","1960","74","#!/bin/bash + +# ----------------------------------------------------------------------------- +# Argument Parsing + +while [[ $# -gt 0 ]]; do + + case $1 in + --output) + output=$2 + shift # past argument + shift # past value + ;; + --nextclade) + nextclade=$2 + shift # past argument + shift # past value + ;; + --nextclade-dataset) + nextclade_dataset=$2 + shift # past argument + shift # past value + ;; + --sc2rf) + sc2rf=$2 + shift # past argument + shift # past value + ;; + --rbd-levels) + rbd_levels=$2 + shift # past argument + shift # past value + ;; + --extra-cols) + extra_cols=$2 + shift # past argument + shift # past value + ;; + -*|--*) + echo ""Unknown option $1"" + exit 1 + ;; + esac +done + +# ncov-recombinant pipeline version +git_commit_hash=$(git rev-parse HEAD) +git_commit=${git_commit_hash:0:8} +git_tag=$(git tag | tail -n1) +ncov_recombinant_ver=""${git_tag}:${git_commit}"" + +# Nextclade version +nextclade_ver=$(nextclade --version | cut -d "" "" -f 2) + +sort_col=""Nextclade_pango"" +default_cols=""strain,date,country"" +nextclade_cols=""privateNucMutations.reversionSubstitutions,privateNucMutations.unlabeledSubstitutions,privateNucMutations.labeledSubstitutions,substitutions"" + +# Hack to fix commas if extra_cols is empty +cols=""${default_cols},${nextclade_cols}"" +if [[ $extra_cols ]]; then + cols=""${cols},${extra_cols}"" +fi + +csvtk cut -t -f ""${cols},clade,Nextclade_pango"" ${nextclade} \ + | csvtk rename -t -f ""clade"" -n ""Nextclade_clade"" \ + | csvtk merge -t --na ""NA"" -f ""strain"" - ${sc2rf} \ + | csvtk merge -t --na ""NA"" -f ""strain"" - ${rbd_levels} \ + | csvtk sort -t -k ""$sort_col"" \ + | csvtk mutate2 -t -n ""ncov-recombinant_version"" -e ""\""$ncov_recombinant_ver\"""" \ + | csvtk mutate2 -t -n ""nextclade_version"" -e ""\""$nextclade_ver\"""" \ + | csvtk mutate2 -t -n ""nextclade_dataset"" -e ""\""$nextclade_dataset\"""" \ + > $output +","Shell" +"Microbiology","ethz-institute-of-microbiology/fisher_py","RawFileReaderLicense.md",".md","8007","67"," +This license covers the following files which are distributed with the RawTools software package: +- ThermoFisher.CommonCore.BackgroundSubtraction.dll +- ThermoFisher.CommonCore.BackgroundSubtraction.pdb +- ThermoFisher.CommonCore.BackgroundSubtraction.xml +- ThermoFisher.CommonCore.Data.dll +- ThermoFisher.CommonCore.Data.pdb +- ThermoFisher.CommonCore.Data.xml +- ThermoFisher.CommonCore.MassPrecisionEstimator.dll +- ThermoFisher.CommonCore.MassPrecisionEstimator.pdb +- ThermoFisher.CommonCore.MassPrecisionEstimator.xml +- ThermoFisher.CommonCore.RawFileReader.dll +- ThermoFisher.CommonCore.RawFileReader.pdb +- ThermoFisher.CommonCore.RawFileReader.xml + +Users who recieve a copy of RawFileReader as software accompanying a larger distribution are considered ""end users"" under section 3.3, and thus have no rights to redistribute RawFileReader. Stated plainly, and in the current context, if you recieve a copy of RawFileReader in a distribution or other release of fisher_py (Copyright 2021 ethz-institute-of-microbiology), you are free to use it as part of that software, but you cannot give it to anyone else. +If you wish to modify and redistribute fisher_py, you are required to delete the above mentioned RawFileReader files before doing so, or receive a License from Thermo Fisher affording you rights to distribute RawFileReader. To inquire about getting a license for redistribution, visit https://www.thermofisher.com/. + +# SOFTWARE LICENSE AGREEMENT (“License”) FOR RawFileReader +These License terms are an agreement between you and Thermo Finnigan LLC (""Licensor""). They apply to Licensor’s MSFileReader software program (“Software”), which includes documentation and any media on which you received it. These terms also apply to any updates or supplements for this Software, unless other terms accompany those items, in which case those terms apply. If you use this Software, you accept this License. If you do not accept this License, you are prohibited from using this software. If you comply with these License terms, you have the rights set forth below. + +1. Rights Granted: + + 1.1. You may install and use this Software on any of your computing devices. + + 1.2. You may distribute this Software to others, but only in combination with other software components and/or programs that you provide and subject to the distribution requirements and restrictions below. + +2. Use Restrictions: + + 2.1. You may not decompile, disassemble, reverse engineer, use reflection or modify this Software. + +3. Distribution Requirements: + If you distribute this Software to others, you agree to: + + 3.1. Indemnify, defend and hold harmless the Licensor from any claims, including attorneys’ fees, related to the distribution or use of this Software; + + 3.2. Display the following text in your software’s “About” box: “RawFileReader reading tool. Copyright © 2016 by Thermo Fisher Scientific, Inc. All rights reserved.”; + + 3.3. Require your end users to agree to a license agreement that prohibits them from redistributing this Software to others. + +4. Distribution Restrictions: + + 4.1. You may not use the Licensor’s trademarks in a way that suggests your software components and/or programs are provided by or are endorsed by the Licensor; and + + 4.2. You may not commercially exploit this Software or products that incorporate this Software without the prior written consent of Licensor. Commercial exploitation includes, but is not limited to, charging a purchase price, license fee, maintenance fee, or subscription fee; or licensing, transferring or redistributing the Software in exchange for consideration of any kind. + + 4.3. Your rights to this Software do not include any license, right, power or authority to subject this Software in whole or in part to any of the terms of an Excluded License. ""Excluded License"" means any license that requires as a condition of use, modification and/or distribution of software subject to the Excluded License, that such software or other software combined and/or distributed with such software be (a) disclosed or distributed in source code form; or (b) licensed for the purpose of making derivative works. Without limiting the foregoing obligation, you are specifically prohibited from distributing this Software with any software that is subject to the General Public License (GPL) or similar license in a manner that would create a combined work. + +5. Additional Terms Applicable to Software: + + 5.1. This Software is licensed, not sold. This License only gives you some rights to use this Software; the Licensor reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use this Software only as expressly permitted in this License. + + 5.2. Licensor has no obligation to fix, update, supplement or support this Software. + + 5.3. This Software is not designed, manufactured or intended for any use requiring fail-safe performance in which the failure of this Software could lead to death, serious personal injury or severe physical and environmental damage (“High Risk Activities”), such as the operation of aircraft, medical or nuclear facilities. You agree not to use, or license the use of, this Software in connection with any High Risk Activities. + + 5.4. Your rights under this License terminate automatically if you breach this License in any way. Termination of this License will not affect any of your obligations or liabilities arising prior to termination. The following sections of this License shall survive termination: 2.1, 3.1, 3.2, 3.3, 4.1, 4.2, 4.3, 5.1, 5.2, 5.3, 5.5, 5.6, 5.7, 5.8, and 5.9. + + 5.5. This Software is subject to United States export laws and regulations. You agree to comply with all domestic and international export laws and regulations that apply to this Software. These laws include restrictions on destinations, end users and end use. + + 5.6. This License shall be construed and controlled by the laws of the State of California, U.S.A., without regard to conflicts of law. You consent to the jurisdiction of the state and federal courts situated in the State of California in any action arising under this License. The application of the U.N. Convention on Contracts for the International Sale of Goods to this License is hereby expressly excluded. If any provision of this License shall be deemed unenforceable or contrary to law, the rest of this License shall remain in full effect and interpreted in an enforceable manner that most nearly captures the intent of the original language. + + 5.7. THIS SOFTWARE IS LICENSED ""AS IS"". YOU BEAR ALL RISKS OF USING IT. LICENSOR GIVES NO AND DISCLAIMS ALL EXPRESS AND IMPLIED WARRANTIES, REPRESENTATIONS OR GUARANTEES. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS LICENSE CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, LICENSOR EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + + 5.8. LICENSOR’S TOTAL LIABILITY TO YOU FOR DIRECT DAMAGES ARISING UNDER THIS LICENSE IS LIMITED TO U.S. $1.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES, EVEN IF LICENSOR IS EXPRESSLY MADE AWARE OF THE POSSIBILITY THEREOF OR IS NEGLIGENT. THIS LIMITATION APPLIES TO ANYTHING RELATED TO THIS SOFTWARE, SERVICES, CONTENT (INCLUDING CODE) ON THIRD PARTY INTERNET SITES, OR THIRD PARTY PROGRAMS, AND CLAIMS FOR BREACH OF CONTRACT, BREACH OF WARRANTY, GUARANTEE OR CONDITION, STRICT LIABILITY, NEGLIGENCE, OR OTHER TORT TO THE EXTENT PERMITTED BY APPLICABLE LAW. + + 5.9. Use, duplication or disclosure of this Software by the U.S. Government is subject to the restricted rights applicable to commercial computer software (under FAR 52.227019 and DFARS 252.227-7013 or parallel regulations). The manufacturer for this purpose is Thermo Finnigan LLC, 355 River Oaks Parkway, San Jose, California 95134, U.S.A.","Markdown" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file.py",".py","17873","369","from typing import Tuple, List +from fisher_py.raw_file_reader import RawFileReaderAdapter +from fisher_py.data.filter_enums import MsOrderType, MassAnalyzerType +from fisher_py.data.business import TraceType, ChromatogramTraceSettings, Range, MassOptions +from fisher_py.data import ToleranceUnits, FtAverageOptions, Device +import numpy as np + + +class RawFile(object): + """""" + Allows to access *.RAW files used by ThermoFisher to store MS measurements. + NOTE: This class only provides limited access to all the functionalities and can serve as + an example how to use the module wihtin a project. For full access use RawFileReaderAdapter.file_factory() + """""" + + @property + def path(self) -> str: + """""" + Path of the raw file + """""" + return self._raw_file_access.path + + @property + def number_of_scans(self) -> int: + """""" + Number of scans / spectra + """""" + return self._raw_file_access.run_header_ex.spectra_count + + @property + def first_scan(self) -> int: + """""" + First scan number + """""" + return self._raw_file_access.run_header.first_spectrum + + @property + def last_scan(self) -> int: + """""" + Last scan number + """""" + return self._raw_file_access.run_header.last_spectrum + + @property + def total_time_min(self) -> float: + """""" + Total time of experiment in minutes + """""" + return self._raw_file_access.run_header.end_time + + @property + def ms2_filter_masses(self) -> np.ndarray: + """""" + Available masses for MS2 filtering (precursor masses) + """""" + return self._ms2_filter_unique_filter_masses + + def __init__(self, path: str): + self._path = path + self._raw_file_access = RawFileReaderAdapter.file_factory(path) + self._raw_file_access.select_instrument(Device.MS, 1) + + # fetch retention times and scan numbers + scan_numbers, rt = self._get_scan_numbers_and_retention_times_() + self._scan_numbers = scan_numbers + self._retention_times = rt + self._spectrum_cache = dict() + self._result_string_cache = dict() + + # fetch retention times and scan numbers for MS1 only + scan_numbers, rt = self._get_ms_scan_numbers_and_retention_times_(MsOrderType.Ms) + self._ms1_scan_numbers = scan_numbers + self._ms1_retention_times = rt + + # fetch retention times and scan numbers for MS2 only + scan_numbers, rt = self._get_ms_scan_numbers_and_retention_times_(MsOrderType.Ms2) + self._ms2_scan_numbers = scan_numbers + self._ms2_retention_times = rt + + # fetch filters for MS2 + scan_numbers, filter_masses = self._get_ms2_scan_numbers_and_masses_() + self._ms2_filter_scan_numbers = scan_numbers + self._ms2_filter_masses = filter_masses + self._ms2_filter_unique_filter_masses = np.array(sorted(list(set(self._ms2_filter_masses)))) + + def _get_scan_numbers_and_retention_times_(self) -> Tuple[List[int], List[float]]: + first_scan = self.first_scan + scan_numbers = list() + retention_times = list() + + for i in range(self.number_of_scans): + scan_number = i + first_scan + rt = self._raw_file_access.retention_time_from_scan_number(scan_number) + scan_numbers.append(scan_number) + retention_times.append(rt) + + return np.array(scan_numbers), np.array(retention_times) + + def _get_ms2_scan_numbers_and_masses_(self) -> Tuple[List[float], List[float]]: + first_scan = self.first_scan + scan_numbers = list() + filter_mass_values = list() + scan_events = self._raw_file_access.get_scan_events(self.first_scan, self.last_scan) + + for i, scan_event in enumerate(scan_events): + if scan_event.ms_order != MsOrderType.Ms2: + continue + scan_number = i + first_scan + precursor_mass = self._get_scan_filter_precursor_mass_(scan_number) + if precursor_mass is None: + continue + + scan_numbers.append(scan_number) + filter_mass_values.append(precursor_mass) + + return np.array(scan_numbers), np.array(filter_mass_values) + + + def _get_ms_scan_numbers_and_retention_times_(self, ms_order: MsOrderType) -> Tuple[List[int], List[float]]: + first_scan = self.first_scan + scan_numbers = list() + retention_times = list() + scan_events = self._raw_file_access.get_scan_events(self.first_scan, self.last_scan) + + for i, scan_event in enumerate(scan_events): + if scan_event.ms_order != ms_order: + continue + scan_number = i + first_scan + scan_numbers.append(scan_number) + retention_times.append(self._raw_file_access.retention_time_from_scan_number(scan_number)) + + return np.array(scan_numbers), np.array(retention_times) + + def _get_scan_filter_precursor_mass_(self, scan_number: int) -> float: + scan_event = self._raw_file_access.get_scan_event_for_scan_number(scan_number) + if scan_event.ms_order != MsOrderType.Ms2: + return None + return scan_event.get_reaction(0).precursor_mass + + def _get_scan_(self, scan_number: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + mass_analyzer = self._raw_file_access.get_scan_event_for_scan_number(scan_number).mass_analyzer + + if mass_analyzer == MassAnalyzerType.MassAnalyzerFTMS: + spectrum = self._raw_file_access.get_centroid_stream(scan_number, False) + positions = np.array(spectrum.masses) + intensities = np.array(spectrum.intensities) + charges = np.array(spectrum.charges) + else: + stats = self._raw_file_access.get_scan_stats_for_scan_number(scan_number) + spectrum = self._raw_file_access.get_segmented_scan_from_scan_number(scan_number, stats) + positions = np.array(spectrum.positions) + intensities = np.array(spectrum.intensities) + charges = np.zeros(positions.shape) + return positions, intensities, charges + + def get_chromatogram(self, mz: float, tolerance: float, trace_type: TraceType=TraceType.MassRange, tolerance_units: ToleranceUnits=ToleranceUnits.ppm, ms_filter: str='ms') -> Tuple[np.ndarray, np.ndarray]: + """""" + Gets chromatogram + :param mz: Mass/Charge value for mass range chromatogram + :param tolerace: Tolerance for mass range chromatogram + :param tolerance_units: Units of the mass tolerance (ppm by default) + :param ms_filter: Type of MS data (ms or ms2) + :param trace_type: Type of chromatogram (BasePeek, TIC (total ion current), MassRange (XIC)) + + :return: array containing retention times and array containing intensity values + """""" + + trace_settings = ChromatogramTraceSettings(trace_type) + trace_settings.filter = ms_filter + tolerance_arg = None + + if trace_type == TraceType.MassRange: + trace_settings.mass_ranges = [Range(mz, mz)] + tolerance_arg = MassOptions(tolerance, tolerance_units) + + chromatogram_raw = self._raw_file_access.get_chromatogram_data([trace_settings], -1, -1, tolerance_arg) + return np.array(chromatogram_raw.positions_array[0]), np.array(chromatogram_raw.intensities_array[0]) + + def get_tic_ms2(self, precursor_mz: float, tolerance: float=10e-3) -> Tuple[np.ndarray, np.ndarray]: + """""" + Get total ion current in MS2 for a given precursor mass. + NOTE: This method does not yet support all mass tolerance units + :param precursor_mz: Precursor mass + :param tolerance: Mass tolerance (in ppm) + :returns: Tuple of (retention_times, total_ion_current_intensities) + """""" + tic_rt, tic_intensities = list(), list() + for n in range(self.first_scan, self.last_scan+1): + scan_event = self._raw_file_access.get_scan_event_for_scan_number(n) + precursor_mass = self._get_scan_filter_precursor_mass_(n) + + # skip scan if not MS2 or the precursor mass does not match the filter criteria + if scan_event.ms_order != MsOrderType.Ms2 or precursor_mass is None or abs(precursor_mass - precursor_mz) > tolerance: + continue + + _, y, _ = self._get_scan_(n) + tic_rt.append(self._raw_file_access.retention_time_from_scan_number(n)) + tic_intensities.append(np.sum(y)) + + return np.array(tic_rt), np.array(tic_intensities) + + def get_scan_ms1(self, rt: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]: + """""" + Gets MS1 (MS) spectrum for a given retention time value in minutes + :param rt: retention time value in minutes + + :returns: Three arrays containing Mass/Charge values, intensity values and charge values as well as the actual retention time + """""" + scan_number, found_rt = self.get_ms1_scan_number_from_retention_time(rt) + rts, intensities, charges, _ = self.get_scan_from_scan_number(scan_number) + return rts, intensities, charges, found_rt + + def get_scan_ms2(self, rt: float, precursor_mz: float=None) -> Tuple[np.ndarray, np.ndarray, float]: + """""" + Gets MS2 spectrum for a given retention time value in minutes + :param rt: retention time value in minutes + :param recursor_mz: Optional precursor mass value to filter spectra + + :returns: Three arrays containing Mass/Charge values, intensity values and charge values as well as the actual retention time + """""" + scan_number, found_rt = self.get_ms2_scan_number_from_retention_time(rt, precursor_mz) + rts, intensities, charges, _ = self.get_scan_from_scan_number(scan_number) + return rts, intensities, charges, found_rt + + def get_scan(self, rt: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, str]: + return self.get_scan_from_scan_number(self.get_scan_number_from_retention_time(rt)) + + + def get_average_ms2_scans_by_rt(self, rt_from: float, rt_to: float, precursor_mass: float, tolerance: float=10, tolerance_units: ToleranceUnits=ToleranceUnits.ppm) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """""" + Averages MS spectra over a given range using a precursor filter + :param rt_from: Retention time start in minutes + :param rt_to: Retention time end in minutes + :param precursor_mass: Precursor mass for filtering + :param tolerance: Mass tolerance for binning + :param tolerance_units: Mass tolerance units + :returns: Three arrays containing mass/charge, intensities and charges + """""" + start_scan, _ = self.get_ms2_scan_number_from_retention_time(rt_from) + end_scan, _ = self.get_ms2_scan_number_from_retention_time(rt_to) + return self.get_averaged_ms2_scans(start_scan, end_scan, precursor_mass, tolerance, tolerance_units) + + def get_averaged_ms2_scans(self, start_scan: int, end_scan: int, precursor_mass: float, tolerance: float=10, tolerance_units: ToleranceUnits=ToleranceUnits.ppm) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """""" + Averages MS spectra over a given range using a precursor filter + :param start_scan: Number of start scan + :param end_scan: Number of end scan + :param precursor_mass: Precursor mass for filtering + :param tolerance: Mass tolerance for binning + :param tolerance_units: Mass tolerance units + :returns: Three arrays containing mass/charge, intensities and charges + """""" + + rounded_precursor = round(precursor_mass, 4) + template_string = self._raw_file_access.get_scan_event_string_for_scan_number(start_scan) + filter_string = f'FTMS + p ESI d Full ms2 {rounded_precursor}@{template_string.split(""@"")[1]}' + mass_options = MassOptions(tolerance, tolerance_units, 4) + average_options = FtAverageOptions() + + averaged_scans = self._raw_file_access.average_scans_in_scan_range(start_scan, end_scan, filter_string, mass_options, average_options) + masses = np.array(averaged_scans.preferred_masses) + intensities = np.array(averaged_scans.preferred_intensities) + charges = averaged_scans.centroid_scan.charges if averaged_scans.has_centroid_stream else np.zeros(masses.shape) + + return masses, intensities, charges + + def get_scan_from_scan_number(self, scan_number: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, str]: + """""" + Get scan data from a scan number. The data returned is structured in a tuple as follows: + (masses, intensities, ion_charges, scan_event_descriptions) + + :param scan_number: The number of the scan + :returns: Tuple organized as (masses, intensities, ion_charges, scan_event_descriptions) + """""" + if scan_number < self.first_scan or scan_number > self.last_scan: + raise ValueError(f'The scan number {scan_number} is out of bounds. Valid range {self.first_scan} - {self.last_scan}.') + + if scan_number in self._spectrum_cache: + return self._spectrum_cache[scan_number][0], self._spectrum_cache[scan_number][1], self._spectrum_cache[scan_number][2], self._result_string_cache[scan_number] + + positions, intensities, charges = self._get_scan_(scan_number) + scan_event_str = self._raw_file_access.get_scan_event_string_for_scan_number(scan_number) + return positions, intensities, charges, scan_event_str + + def get_retention_time_from_scan_number(self, scan_number: int) -> float: + """""" + Get the retention time (in minutes) from a scan number + :param scan_number: The number of the scan + :returns: Retention time in minutes + """""" + if scan_number < self.first_scan or scan_number > self.last_scan: + raise ValueError(f'The scan number {scan_number} is out of bounds. Valid range {self.first_scan} - {self.last_scan}.') + + idx = np.argmin(np.abs(self._scan_numbers - scan_number)) + return self._retention_times[idx] + + def get_scan_number_from_retention_time(self, rt: float) -> int: + """""" + Get the closest scan number from a given retention time (in minutes). If the retention time is smaller than zero + this will always return the first scan number and if it is larger than the latest entry it will return the biggest + scan number. + :param rt: Retention time (in minutes) + :returns: Scan number + """""" + if rt < 0 or rt > self.total_time_min: + raise ValueError(f'The retiontion time {rt} is out of bounds. Valid range 0 - {self.total_time_min}.') + + idx = np.argmin(np.abs(self._retention_times - rt)) + return int(self._scan_numbers[idx]) + + def get_ms1_scan_number_from_retention_time(self, rt: float) -> Tuple[int, float]: + """""" + Get the closest scan number in MS1 spectra from a given retention time (in minutes). If the retention time is smaller than zero + this will always return the first scan number and if it is larger than the latest entry it will return the biggest + scan number. + :param rt: Retention time (in minutes) + :returns: Scan number + """""" + if rt < 0 or rt > self.total_time_min: + raise ValueError(f'The retiontion time {rt} is out of bounds. Valid range 0 - {self.total_time_min}.') + + idx = np.argmin(np.abs(self._ms1_retention_times - rt)) + found_rt = self._ms1_retention_times[idx] + found_scan_nr = self._ms1_scan_numbers[idx] + return int(found_scan_nr), found_rt + + def get_ms2_scan_number_from_retention_time(self, rt: float, precursor_mz: float=None, tolerance_ppm = 10e-3) -> Tuple[int, float]: + """""" + Get the closest scan number in MS2 spectra from a given retention time (in minutes). If the retention time is smaller than zero + this will always return the first scan number and if it is larger than the latest entry it will return the biggest + scan number. + NOTE: This method does not yet support all mass tolerance units + :param rt: Retention time (in minutes) + :param precursor_mz: Precursor mass + :param tolerance: Mass tolerance to precursor (in ppm) + :returns: Scan number + """""" + if rt < 0 or rt > self.total_time_min: + raise ValueError(f'The retiontion time {rt} is out of bounds. Valid range 0 - {self.total_time_min}.') + + if precursor_mz is None: + idx = np.argmin(np.abs(self._ms2_retention_times - rt)) + found_rt = self._ms2_retention_times[idx] + found_scan_nr = int(self._ms2_scan_numbers[idx]) + return found_scan_nr, found_rt + else: + ms2_idxs = np.abs(self._ms2_filter_masses - precursor_mz) <= tolerance_ppm + ms2_scans = self._ms2_filter_scan_numbers[ms2_idxs] + ms2_rts = self._retention_times[ms2_scans.astype(int) + self.first_scan] + idx = np.argmin(np.abs(ms2_rts - rt)) + found_rt = ms2_rts[idx] + found_scan_nr = int(ms2_scans[idx]) + return found_scan_nr, found_rt + + def get_scan_event_str_from_scan_number(self, scan_number: int) -> str: + """""" + Get the scan event description text from a scan number. + :param scan_number: Scan number to retrieve the description from + :returns: Scan event description + """""" + if scan_number < self.first_scan or scan_number > self.last_scan: + raise ValueError(f'The scan number {scan_number} is out of bounds. Valid range {self.first_scan} - {self.last_scan}.') + + if scan_number in self._result_string_cache: + return self._result_string_cache[scan_number] + + _, _, _, event_str = self.get_scan_from_scan_number(scan_number) + return event_str +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/__init__.py",".py","39","2","from fisher_py.raw_file import RawFile +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/utils.py",".py","1486","55","from typing import Any, List +from datetime import datetime +import clr + +clr.AddReference('System') +from System import DateTime, Double, Array +import System.Collections.Generic as generic + +def is_number(arg: Any) -> bool: + return type(arg) is int or type(arg) is float + + +def datetime_net_to_py(net_date_time: DateTime) -> datetime: + """""" + Convert .NET DateTime to python datetime + """""" + return datetime(net_date_time.Year, net_date_time.Month, net_date_time.Day, net_date_time.Hour, net_date_time.Minute, net_date_time.Second, int(net_date_time.Millisecond * 1e3)) + + +def datetime_py_to_net(py_date_time: datetime) -> DateTime: + """""" + Convert python datetime to .NET DateTime + """""" + return DateTime(py_date_time.year, py_date_time.month, py_date_time.day, py_date_time.hour, py_date_time.minute, py_date_time.second, int(float(py_date_time.microsecond) / 1e3)) + + +def to_net_list(py_list: List[Any], t) -> Any: + """""" + Convert to .NET list + """""" + if type(t) is float: + t = Double + + # return generic.List[t](py_list) + net_list = generic.List[t]() + for item in py_list: + net_list.Add(item) + return net_list + +def to_net_array(py_list: list, t) -> Any: + """""" + Convert to .NET array + """""" + if type(t) is float: + t = Double + + net_array = Array[t](len(py_list)) + for i, item in enumerate(py_list): + net_array[i] = item + return net_array + + +def to_py_list(net_list) -> list: + return [i for i in net_list] +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/net_wrapping/wrapped_net_array.py",".py","1679","50","from typing import TypeVar, Generic, Union +import clr + +clr.AddReference('System') +import System +import System.Collections.Generic as generic + +T = TypeVar('T') + +class WrappedNetArray(Generic[T], list): + + def __getitem__(self, index: Union[int, slice]) -> T: + if type(index) is slice: + start, step, stop = index.start, index.step, index.stop + if step is None: + step = 1 + start, step, stop = map(self.__ensure_positive_index__, [start, step, stop]) + sublist = [] + for i in range(start, stop, step): + sublist.append(self.__wrapped_iterable[i]) + return sublist + index = self.__ensure_positive_index__(index) + return self.__wrapped_iterable[index] + + def __setitem__(self, index: int, value: T): + index = self.__ensure_positive_index__(index) + super().__setitem__(index, value) + self.__wrapped_iterable[index] = value + + def append(self, obj): + raise NotImplementedError('Appending not allowed on arrays.') + + def insert(self, index, obj): + raise NotImplementedError('Appending not allowed on arrays.') + + def remove(self, value): + raise NotImplementedError('Removing not allowed on arrays.') + + def clear(self): + raise NotImplementedError('Removing not allowed on arrays.') + + def __init__(self, net_iterable): + super().__init__([i for i in net_iterable]) + self.__wrapped_iterable = net_iterable + + def __ensure_positive_index__(self, index: int) -> int: + if index < 0: + index = len(self.__wrapped_iterable) + index + return index +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/net_wrapping/net_wrapper_base.py",".py","612","24","from __future__ import annotations +from typing import Any +from fisher_py.exceptions import CoreException + + +class NetWrapperBase(object): + + _wrapped_type = None + + def __init__(self): + self._wrapped_object = None + + def _get_wrapped_object_(self) -> Any: + if self._wrapped_object is None: + raise CoreException('This object was not initialized properly.') + + return self._wrapped_object + + @classmethod + def _get_wrapper_(cls: type, net_obj: Any) -> NetWrapperBase: + wrapper_obj = cls() + wrapper_obj._wrapped_object = net_obj + return wrapper_obj +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/net_wrapping/__init__.py",".py","2801","74","import pythonnet + +# Load dotnet before clr import. See https://pythonnet.github.io/pythonnet/python.html#loading-a-runtime +try: + pythonnet.load() # Try default (i.e. 'mono' or PYTHONNET_RUNTIME) +except: + pythonnet.load('coreclr') # Fallback on coreclr + +import clr +import os +from fisher_py.net_wrapping.net_wrapper_base import NetWrapperBase +from System import Environment + +# codecs for implicit enum conversion +import Python.Runtime + +Python.Runtime.PyObjectConversions.RegisterEncoder(Python.Runtime.Codecs.EnumPyIntCodec.Instance) +Python.Runtime.PyObjectConversions.RegisterDecoder(Python.Runtime.Codecs.EnumPyIntCodec.Instance) + + +# access .net standard dlls +dotnet_version = Environment.Version.get_Major() +dll_base_path = os.path.join(os.path.split(__file__)[0], '..', 'dll') + +if dotnet_version >= 8: + dll_path = os.path.join(dll_base_path, 'net8') +elif dotnet_version >= 5: + dll_path = os.path.join(dll_base_path, 'net5') +else: + dll_path = os.path.join(dll_base_path, 'net4') + +clr.AddReference('System') +clr.AddReference('System.Core') +clr.AddReference('System.Data') +clr.AddReference('System.Configuration') +clr.AddReference('System.Xml') +clr.AddReference('mscorlib') + +clr.AddReference(os.path.join(dll_path, 'ThermoFisher.CommonCore.Data.dll')) +clr.AddReference(os.path.join(dll_path, 'ThermoFisher.CommonCore.RawFileReader.dll')) +clr.AddReference(os.path.join(dll_path, 'ThermoFisher.CommonCore.MassPrecisionEstimator.dll')) +clr.AddReference(os.path.join(dll_path, 'ThermoFisher.CommonCore.BackgroundSubtraction.dll')) +try: + clr.AddReference(os.path.join(dll_path, 'OpenMcdf.dll')) +except Exception as e: + pass # avoid duplicate load + +# import .net standard libaries +import ThermoFisher.CommonCore.Data as thermo_fisher_data +from ThermoFisher.CommonCore.Data import Extensions +import ThermoFisher.CommonCore.Data.Business as thermo_fisher_data_business +import ThermoFisher.CommonCore.Data.FilterEnums as thermo_fisher_data_filter_enums +import ThermoFisher.CommonCore.Data.Interfaces as thermo_fisher_data_interfaces +import ThermoFisher.CommonCore.MassPrecisionEstimator as thermo_fisher_mass_precision_estimator +import ThermoFisher.CommonCore.RawFileReader as thermo_fisher_raw_file_reader +import ThermoFisher.CommonCore.MassPrecisionEstimator as thermo_fisher_mass_precision_estimator + +# expose .net libraries in a friendly manner +class _Data: + + Business = thermo_fisher_data_business + FilterEnums = thermo_fisher_data_filter_enums + Interfaces = thermo_fisher_data_interfaces + Extensions = Extensions + + +class ThermoFisher: + + class CommonCore: + Data = _Data() + MassPrecisionEstimator = thermo_fisher_mass_precision_estimator + RawFileReader = thermo_fisher_raw_file_reader + MassPrecisionEstimator = thermo_fisher_mass_precision_estimator +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/net_wrapping/wrapped_net_list.py",".py","1659","51","from typing import TypeVar, Generic, Union +import clr + +clr.AddReference('System') +import System +import System.Collections.Generic as generic + +T = TypeVar('T') + +class WrappedNetList(Generic[T], list): + + def __getitem__(self, index: Union[int, slice]) -> T: + if type(index) is slice: + start, step, stop = index.start, index.step, index.stop + if step is None: + step = 1 + start, step, stop = map(self.__ensure_positive_index__, [start, step, stop]) + sublist = [] + for i in range(start, stop, step): + sublist.append(self.__wrapped_iterable[i]) + return sublist + index = self.__ensure_positive_index__(index) + return self.__wrapped_iterable[index] + + def __setitem__(self, index: int, value: T): + index = self.__ensure_positive_index__(index) + super().__setitem__(index, value) + self.__wrapped_iterable[index] = value + + def append(self, obj): + super().append(obj) + self.__wrapped_iterable.Add(obj) + + def insert(self, index, obj): + index = self.__ensure_positive_index__(index) + super().insert(index, obj) + self.__wrapped_iterable.Insert(index, obj) + + def remove(self, value): + super().remove(value) + self.__wrapped_iterable.Remove(value) + + def __init__(self, net_iterable): + super().__init__([i for i in net_iterable]) + self.__wrapped_iterable = net_iterable + + def __ensure_positive_index__(self, index: int) -> int: + if index < 0: + index = len(self.__wrapped_iterable) + index + return index +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/mass_precision_estimator/precision_estimate.py",".py","4140","125","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.filter_enums import MassAnalyzerType +from fisher_py.data.business import Scan +from fisher_py.raw_file_reader import RawFileAccess +from fisher_py.mass_precision_estimator import EstimatorResults +from fisher_py.utils import to_net_list +from typing import List + + +class PrecisionEstimate(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.MassPrecisionEstimator.PrecisionEstimate + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + self._raw_file = None + + @property + def raw_file(self) -> RawFileAccess: + """""" + Gets the raw file as an open IRawData objects. + """""" + return self._raw_file + + @raw_file.setter + def raw_file(self, value: RawFileAccess): + """""" + Sets the raw file as an open IRawData objects. + """""" + assert type(value) is RawFileAccess + self._raw_file = value + self._get_wrapped_object_().Rawfile = value._get_wrapped_object_() + + @property + def scan_number(self) -> int: + """""" + Gets the scan number of the scan to be analyzed + + Value: + The scan number. + """""" + return self._get_wrapped_object_().ScanNumber + + @scan_number.setter + def scan_number(self, value: int): + """""" + Sets the scan number of the scan to be analyzed + + Value: + The scan number. + """""" + assert type(value) is int + self._get_wrapped_object_().ScanNumber = value + + def dispose(self): + """""" + Performs application-defined tasks associated with freeing, releasing, or resetting + unmanaged resources. + """""" + self._get_wrapped_object_().Dispose() + + def get_ion_time(self, analyzer_type: MassAnalyzerType, scan: Scan, trailer_headings: List[str], trailer_values: List[str]) -> float: + """""" + Calculate the ion time (fill (traps and FT) or dwell time (quads)) + + Parameters: + analyzerType: + The analyzer type + + scan: + The scan to process + + trailerHeadings: + The trailer extra data headings + + trailerValues: + The trailer extra data values + + Returns: + The calculated ion time + """""" + assert type(analyzer_type) is MassAnalyzerType + assert type(scan) is Scan + assert type(trailer_headings) is list + assert type(trailer_values) is list + trailer_headings = to_net_list(trailer_headings, str) + trailer_values = to_net_list(trailer_values, str) + return self._get_wrapped_object_().GetIonTime(analyzer_type.value, scan._get_wrapped_object_(), trailer_headings, trailer_values) + + def get_mass_precision_estimate(self, scan: Scan, analyzer_type: MassAnalyzerType, ion_time: float, resolution: float) -> List[EstimatorResults]: + """""" + Gets mass precision estimate and stores them in a class property list of classes + This method will throw an Exception or ArgumentException if a problem occurs + during processing. + + Parameters: + scan: + The scan to process + + analyzerType: + The analyzer type for the scan + + ionTime: + The ion time for the scan + + resolution: + The resolution for the scan + + Returns: + Returns the list of Mass Precision Estimation results + """""" + return self._get_wrapped_object_().GetMassPrecisionEstimate(scan, analyzer_type, ion_time, resolution) + + def get_mass_precision_estimate(self) -> List[EstimatorResults]: + """""" + Gets mass precision estimate and stores them in a class property list of classes + This method will throw an Exception or ArgumentException if a problem occurs + during processing. + + Returns: + Returns the list of Mass Precision Estimation results + """""" + return [EstimatorResults._get_wrapper_(e) for e in self._get_wrapped_object_().GetMassPrecisionEstimate()] +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/mass_precision_estimator/__init__.py",".py","166","3","from fisher_py.mass_precision_estimator.estimator_results import EstimatorResults +from fisher_py.mass_precision_estimator.precision_estimate import PrecisionEstimate +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/mass_precision_estimator/estimator_results.py",".py","2500","91","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.utils import is_number + + +class EstimatorResults(NetWrapperBase): + """""" + Class to hold mass precision estimator results for individual mass/intensity + points in a scan. + """""" + + _wrapped_type = ThermoFisher.CommonCore.MassPrecisionEstimator.EstimatorResults + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_object() + + @property + def intensity(self) -> float: + """""" + Gets or sets the intensity value + """""" + return self._get_wrapped_object_().Intensity + + @intensity.setter + def intensity(self, value: float): + """""" + Gets or sets the intensity value + """""" + assert type(value) is float + self._get_wrapped_object_().Intensity = value + + @property + def mass(self) -> float: + """""" + Gets or sets the mass value + """""" + return self._get_wrapped_object_().Mass + + @mass.setter + def mass(self, value: float): + """""" + Gets or sets the mass value + """""" + assert is_number(value) + self._get_wrapped_object_().Mass = float(value) + + @property + def mass_accuracy_in_mmu(self) -> float: + """""" + Gets or sets the mass accuracy in MMU value + """""" + return self._get_wrapped_object_().MassAccuracyInMmu + + @mass_accuracy_in_mmu.setter + def mass_accuracy_in_mmu(self, value: float): + """""" + Gets or sets the mass accuracy in MMU value + """""" + assert is_number(value) + self._get_wrapped_object_().MassAccuracyInMmu = float(value) + + @property + def mass_accuracy_in_ppm(self) -> float: + """""" + Gets or sets the mass accuracy in PPM value + """""" + return self._get_wrapped_object_().MassAccuracyInPpm + + @mass_accuracy_in_ppm.setter + def mass_accuracy_in_ppm(self, value: float): + """""" + Gets or sets the mass accuracy in PPM value + """""" + assert is_number(value) + self._get_wrapped_object_().MassAccuracyInPpm = float(value) + + @property + def resolution(self) -> float: + """""" + Gets or sets the resolution value + """""" + return self._get_wrapped_object_().Resolution + + @resolution.setter + def resolution(self, value: float): + """""" + Gets or sets the resolution value + """""" + assert is_number(value) + self._get_wrapped_object_().Resolution = float(value) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/exceptions/raw_file_exception.py",".py","284","15","class RawFileException(Exception): + + def __init__(self, message: str): + super().__init__(message) + + +class NoSelectedDeviceException(Exception): + pass + + +class NoSelectedMsDeviceException(Exception): + + def __init__(self, message: str): + super().__init__(message) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/exceptions/__init__.py",".py","131","3","from fisher_py.exceptions.raw_file_exception import RawFileException +from fisher_py.exceptions.core_exception import CoreException +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/exceptions/core_exception.py",".py","105","5","class CoreException(Exception): + + def __init__(self, message: str): + super().__init__(message) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/__init__.py",".py","220","4","from fisher_py.raw_file_reader.scan_dependents import ScanDependents +from fisher_py.raw_file_reader.raw_file_access import RawFileAccess +from fisher_py.raw_file_reader.raw_file_reader_adapter import RawFileReaderAdapter +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/scan_dependents.py",".py","1955","56","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data import RawFileClassification, ScanDependentDetails +from fisher_py.utils import to_net_list +from typing import List + + +class ScanDependents(NetWrapperBase): + """""" + The ScanDependents interface. Result of call to ""GetScanDependents"" Provides + a set of scan numbers which were created form a particular master scan. + """""" + + @property + def raw_file_instrument_type(self) -> RawFileClassification: + """""" + Gets or sets the type of the raw file instrument. + + Value: + The type of the raw file instrument. + """""" + return RawFileClassification(self._get_wrapped_object_().RawFileInstrumentType) + + @raw_file_instrument_type.setter + def raw_file_instrument_type(self, value: RawFileClassification): + """""" + Gets or sets the type of the raw file instrument. + + Value: + The type of the raw file instrument. + """""" + assert type(value) is RawFileClassification + self._get_wrapped_object_().RawFileInstrumentType = value.value + + @property + def scan_dependent_detail_array(self) -> List[ScanDependentDetails]: + """""" + Gets or sets the scan dependent detail array. + + Value: + The scan dependent detail array. + """""" + return [ScanDependentDetails._get_wrapper_(s) for s in self._get_wrapped_object_().ScanDependentDetailArray] + + @scan_dependent_detail_array.setter + def scan_dependent_detail_array(self, value: List[ScanDependentDetails]): + """""" + Gets or sets the scan dependent detail array. + + Value: + The scan dependent detail array. + """""" + assert type(value) is list + value = to_net_list(value, type(value[0]._get_wrapped_object_()) if len(value) > 0 else object) + self._get_wrapped_object_().ScanDependentDetailArray = [s._get_wrapped_object_() for s in value] + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/raw_file_reader_adapter.py",".py","406","18","from fisher_py.raw_file_reader import RawFileAccess + + +class RawFileReaderAdapter(object): + """""" + Utility to load raw files + """""" + + @staticmethod + def file_factory(raw_file: str): + """""" + Create an IRawDataExtended interface to read data from a raw file + + :param raw_file: Path to raw file + :return: Returns raw file + """""" + return RawFileAccess(raw_file) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/raw_file_access.py",".py","43764","1079","from __future__ import annotations +from typing import List, Tuple +from fisher_py.data.auto_sampler_information import AutoSamplerInformation +from fisher_py.exceptions.raw_file_exception import NoSelectedDeviceException, NoSelectedMsDeviceException +from fisher_py.raw_file_reader import ScanDependents +from fisher_py.utils import datetime_net_to_py, is_number, to_net_list +from fisher_py.data.business import ( + RunHeader, InstrumentSelection, SampleInformation, CentroidStream, ChromatogramTraceSettings, + MassOptions, InstrumentData, ScanStatistics, SegmentedScan, LogEntry, HeaderItem, StatusLogValues, + TuneDataValues, Scan +) +from fisher_py.data.business.chromatogram_signal import ChromatogramData +from fisher_py.raw_file_reader.data_model import WrappedRunHeader +from fisher_py.data import ( + Device, ScanFilter, ScanEvent, FtAverageOptions, FileError, FileHeader, ScanEvents, ErrorLogEntry +) +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.exceptions import RawFileException +from datetime import datetime +import os +import System + + +class RawFileAccess(NetWrapperBase): + """""" + Enables access to raw files + """""" + + def __init__(self, file_path: str=None): + """""" + Create raw file access for given file path + + :param file_path: Path to the raw file + """""" + super().__init__() + + self._run_header = None + self._instrument_selection = None + self._sample_information = None + + if file_path is None: + return + + if not os.path.isfile(file_path): + raise FileNotFoundError(f'No raw file with path ""{file_path}"" found.') + + # try to load file + try: + self._wrapped_object = ThermoFisher.CommonCore.RawFileReader.RawFileReaderAdapter.FileFactory(file_path) + except Exception as e: + raise RawFileException(f'Raw file import failed. {e}') + + # determine if import generated an error without raising an exception + if self.file_error.has_error: + raise RawFileException(self.file_error.error_message) + + # properties + + @property + def auto_sampler_information(self) -> AutoSamplerInformation: + """""" + Gets the auto sampler (tray) information. + """""" + wrapped_object = self._get_wrapped_object_() + if hasattr(wrapped_object, 'AutoSamplerInformation'): + return AutoSamplerInformation._get_wrapper_(wrapped_object.AutoSamplerInformation) + return None + + @property + def computer_name(self) -> str: + """""" + Gets the name of the computer, used to create this file. + """""" + return self._get_wrapped_object_().ComputerName + + @property + def user_label(self) -> List[str]: + """""" + Gets the user labels of this raw file. + """""" + wrapped_object = self._get_wrapped_object_() + if hasattr(wrapped_object, 'UserLabel'): + return tuple(wrapped_object.UserLabel) + return None + + @property + def include_reference_and_exception_data(self) -> bool: + """""" + Gets or sets a value indicating whether reference and exception peaks should + be returned (by default they are not). Reference and exception peaks are internal + mass calibration data within a scan. + """""" + return self._get_wrapped_object_().IncludeReferenceAndExceptionData + + @include_reference_and_exception_data.setter + def include_reference_and_exception_data(self, value: bool): + """""" + Gets or sets a value indicating whether reference and exception peaks should + be returned (by default they are not). Reference and exception peaks are internal + mass calibration data within a scan. + """""" + assert type(value) is bool + self._get_wrapped_object_().IncludeReferenceAndExceptionData = value + + @property + def run_header(self) -> RunHeader: + """""" + Gets the current instrument's run header. The run header records information + related to all data acquired by this instrument (such as the highest scan number + ""LastSpectrum"") + """""" + if self._run_header is None: + try: + self._run_header = RunHeader._get_wrapper_(self._get_wrapped_object_().RunHeader) + except ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + raise NoSelectedDeviceException() + return self._run_header + + @property + def run_header_ex(self) -> WrappedRunHeader: + """""" + Information about the file stream + """""" + try: + return WrappedRunHeader._get_wrapper_(self._get_wrapped_object_().RunHeaderEx) + except ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + raise NoSelectedDeviceException() + + @property + def instrument_methods_count(self) -> int: + """""" + Gets the number of instruments which have saved method data, within the instrument + method embedded in this file. + """""" + #TODO: This call fails on POSIX systems but not on Windows. + # Once new DLLs are available that fix the problem, this + # try-block can be removed. + try: + return self._get_wrapped_object_().InstrumentMethodsCount + except System.NullReferenceException: + return None + + @property + def path(self) -> str: + """""" + Gets the path to original data. A raw file may have been moved or translated + to other formats. This property always returns the path (folder) where the file + was created (acquired) + """""" + return self._get_wrapped_object_().Path + + @property + def file_name(self) -> str: + """""" + Gets the name of acquired file (excluding path). + """""" + return self._get_wrapped_object_().FileName + + @property + def creation_date(self) -> datetime: + """""" + Gets the date when this data was created. + """""" + return datetime_net_to_py(self._get_wrapped_object_().CreationDate) + + @property + def selected_instrument(self) -> InstrumentSelection: + """""" + Gets the instrument as last set by a call to ThermoFisher.CommonCore.Data.Interfaces.IRawData.SelectInstrument(ThermoFisher.CommonCore.Data.Business.Device,System.Int32). + If this has never been set, returns null. + """""" + selected_instrument = self._get_wrapped_object_().SelectedInstrument + self._instrument_selection = InstrumentSelection(selected_instrument.InstrumentIndex, Device(selected_instrument.DeviceType)) + return self._instrument_selection + + @property + def sample_information(self) -> SampleInformation: + """""" + Gets various details about the sample (such as comments). + """""" + if self._sample_information is None: + self._sample_information = SampleInformation._get_wrapper_(self._get_wrapped_object_().SampleInformation) + return self._sample_information + + @property + def instrument_count(self) -> int: + """""" + Gets the number of instruments (data streams) in this file. For example, a file + with an MS detector and a 4 channel UV may have an instrument count of 2. To + find out how many instruments there are of a particular category call ThermoFisher.CommonCore.Data.Interfaces.IRawData.GetInstrumentCountOfType(ThermoFisher.CommonCore.Data.Business.Device) + with the desired instrument type. Instrument count related methods could, for + example, be used to format a list of instruments available to select in the UI + of an application. To start reading data from a particular instrument, call ThermoFisher.CommonCore.Data.Interfaces.IRawData.SelectInstrument(ThermoFisher.CommonCore.Data.Business.Device,System.Int32). + """""" + return self._get_wrapped_object_().InstrumentCount + + @property + def is_error(self) -> bool: + """""" + Gets a value indicating whether the last file operation caused an error. + """""" + return self._get_wrapped_object_().IsError + + @property + def in_acquisition(self) -> bool: + """""" + Gets a value indicating whether the file is being acquired (not complete). + """""" + return self._get_wrapped_object_().InAcquisition + + @property + def creator_id(self) -> str: + """""" + Gets the name of person creating data. + """""" + return self._get_wrapped_object_().CreatorId + + @property + def file_error(self) -> FileError: + """""" + Gets the file error state. + """""" + wrapped_object = self._get_wrapped_object_() + if hasattr(wrapped_object, 'FileError'): + return FileError._get_wrapper_(wrapped_object.FileError) + return None + + @property + def file_header(self) -> FileHeader: + """""" + Gets the raw file header. + """""" + wrapped_object = self._get_wrapped_object_() + if hasattr(wrapped_object, 'FileHeader'): + return FileHeader._get_wrapper_(wrapped_object.FileHeader) + return None + + @property + def is_open(self) -> bool: + """""" + Gets a value indicating whether the data file was successfully opened. + """""" + return self._get_wrapped_object_().IsOpen + + @property + def has_instrument_method(self) -> bool: + """""" + Gets a value indicating whether this file has an instrument method. + """""" + return self._get_wrapped_object_().HasInstrumentMethod + + @property + def has_ms_data(self) -> bool: + """""" + Gets a value indicating whether this file has MS data. + """""" + return self._get_wrapped_object_().HasMsData + + @property + def scan_events(self) -> ScanEvents: + """""" + Gets the scan events. This is the set of events which have been programmed in + advance of collecting data (based on the MS method). This does not analyze any + scan data. + """""" + try: + return ScanEvents._get_wrapper_(self._get_wrapped_object_().ScanEvents) + except ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException as e: + raise NoSelectedMsDeviceException(e.Message) + + @property + def status_log_plottable_data(self) -> List[Tuple[str, int]]: + """""" + Gets the labels and index positions of the status log items which may be plotted. + That is, the numeric items. Index is a zero based index into the log record (the + array returned by GetStatusLogHeaderInformation) Labels names are returned by + ""Key"" and the index into the log record is ""Value"". + """""" + try: + kv_list = self._get_wrapped_object_().StatusLogPlottableData + return tuple((kv.Key, kv.Value) for kv in kv_list) + except ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + raise NoSelectedDeviceException() + + def get_scan_events(self, first_scan_number: int, last_scan_number: int) -> List[ScanEvent]: + """""" + Summary: + This method permits events to be read as a block for a range of scans, which + may reduce overheads involved in requesting one by one. Events define how scans + were acquired. Potentially, in some data models, the same ""event"" may apply to + several scans so it is permissible for the same reference to appear multiple + times. + + Parameters: + firstScanNumber: + The first scan whose event is needed + + lastScanNumber: + The last scan + + Returns: + An array of scan events + """""" + assert type(first_scan_number) is int + assert type(last_scan_number) is int + return [ScanEvent._get_wrapper_(e) for e in self._get_wrapped_object_().GetScanEvents(first_scan_number, last_scan_number)] + + def get_scan_event_string_for_scan_number(self, scan: int) -> List[str]: + """""" + Summary: + Gets the scan event as a string for a scan. + + Parameters: + scan: + The scan number. + + Returns: + The event as a string. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(scan) is int + return self._get_wrapped_object_().GetScanEventStringForScanNumber(scan) + + def get_all_instrument_names_from_instrument_method(self) -> List[str]: + """""" + Gets names of all instruments, which have a method stored in the raw file's copy + of the instrument method file. These names are ""Device internal names"" which + map to storage names within an instrument method, and other instrument data (such + as registry keys). Use ""GetAllInstrumentFriendlyNamesFromInstrumentMethod"" (in + IRawDataPlus) to get display names for instruments. + + Returns: + The instrument names. + """""" + #TODO: This call fails on POSIX systems but not on Windows. + # Once new DLLs are available that fix the problem, this + # try-block can be removed. + try: + return self._get_wrapped_object_().GetAllInstrumentNamesFromInstrumentMethod() + except System.NullReferenceException: + return None + + def get_auto_filters(self) -> List[str]: + """""" + Gets the filter strings for this file. This analyses all scans types in the file. + It may take some time, especially with data dependent files. Filters are grouped, + within tolerance (as defined by the MS detector). + + Returns: + A string for each auto filter from the raw file + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if this is called without first selecting an MS detector + """""" + return self._get_wrapped_object_().GetAutoFilters() + + def get_filters(self): + """""" + Summary: + Calculate the filters for this raw file, and return as an array. + + Returns: + Auto generated list of unique filters + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return [ScanFilter(f) for f in self._get_wrapped_object_().GetFilters()] + + def get_filter_for_scan_number(self, scan: int) -> ScanFilter: + """""" + Summary: + Get the filter (scanning method) for a scan number. This returns the scanning + method in the form of a filter rule set, so that it can be used to select similar + scans (for example in a chromatogram). This method is only defined for MS detectors. + Calling for other detectors or with no selected detector is a coding error which + may result in a null return or exceptions, depending on the implementation. + + Parameters: + scan: + The scan number. + + Returns: + The ThermoFisher.CommonCore.Data.Interfaces.IScanFilter. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return ScanFilter(self._get_wrapped_object_().GetFilterForScanNumber(scan)) + + def get_scan_event_for_scan_number(self, scan: int) -> ScanEvent: + """""" + Summary: + Gets the scan event details for a scan. Determines how this scan was programmed. + + Parameters: + scan: + The scan number. + + Returns: + The ThermoFisher.CommonCore.Data.Interfaces.IScanEvent interface, to get detailed + information about a scan. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return ScanEvent._get_wrapper_(self._get_wrapped_object_().GetScanEventForScanNumber(scan)) + + def get_centroid_stream(self, scan_number: int, include_reference_and_exception_peaks: bool) -> CentroidStream: + """""" + Get the centroids saved with a profile scan. This is only valid for data types + which support multiple sets of data per scan (such as Orbitrap data). This method + does not ""Centroid profile data"". + + Parameters: + scanNumber: + Scan number + + includeReferenceAndExceptionPeaks: + determines if peaks flagged as ref should be returned + + Returns: + centroid stream for specified scanNumber. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return CentroidStream._get_wrapper_(self._get_wrapped_object_().GetCentroidStream(scan_number, include_reference_and_exception_peaks)) + + def get_chromatogram_data(self, settings: List[ChromatogramTraceSettings], start_scan: int, end_scan: int, tolerance_options: MassOptions=None) -> ChromatogramData: + """""" + Create a chromatogram from the data stream + + Parameters: + settings: + Definition of how the chromatogram is read + + startScan: + First scan to read from. -1 for ""all data"" + + endScan: + Last scan to read from. -1 for ""all data"" + + toleranceOptions: + For mass range or base peak chromatograms, if the ranges have equal low and high + mass values (within 1.0E-6), then toleranceOptions are used to determine a band + subtracted from low and added to high to search for matching masses. if this + is set to ""null"" then the tolerance is defaulted to +/- 0.5. + + Returns: + Chromatogram points + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.RequiresChromatographicDeviceException: + Thrown if the selected device is of a type that does not support chromatogram + generation + + T:ThermoFisher.CommonCore.Data.Business.InvalidFilterFormatException: + Thrown if filters are sent (for MS chromatograms) which cannot be parsed + """""" + net_settings = [s._get_wrapped_object_() for s in settings] + + if tolerance_options is None: + return ChromatogramData._get_wrapper_(self._get_wrapped_object_().GetChromatogramData(net_settings, start_scan, end_scan)) + else: + net_options = tolerance_options._get_wrapped_object_() + return ChromatogramData._get_wrapper_(self._get_wrapped_object_().GetChromatogramData(net_settings, start_scan, end_scan, net_options)) + + def get_instrument_count_of_type(self, type_: Device) -> int: + """""" + Get the number of instruments (data streams) of a certain classification. For + example: the number of UV devices which logged data into this file. + + Parameters: + type: + The device type to count + + Returns: + The number of devices of this type + """""" + assert type(type_) is Device + return self._get_wrapped_object_().GetInstrumentCountOfType(type_.value) + + def get_instrument_data(self) -> InstrumentData: + """""" + Gets the definition of the selected instrument. + + Returns: + data about the selected instrument, for example the instrument name + """""" + return InstrumentData._get_wrapper_(self._get_wrapped_object_().GetInstrumentData()) + + def get_instrument_method(self, index: int) -> str: + """""" + Gets a text form of an instrument method, for a specific instrument. + + Parameters: + index: + The index into the count of available instruments. The property ""InstrumentMethodsCount"", + determines the valid range of ""index"" for this call. + + Returns: + A text version of the method. Some instruments do not log this data. Always test + ""string.IsNullOrEmpty"" on the returned value. + """""" + assert type(index) is int + + #TODO: This call fails on POSIX systems but not on Windows. + # Once new DLLs are available that fix the problem, this + # try-block can be removed. + try: + return self._get_wrapped_object_().GetInstrumentMethod(index) + except System.NullReferenceException: + return None + + def get_instrument_type(self, index: int) -> Device: + """""" + Gets the device type for an instrument data stream + + Parameters: + index: + The data stream + + Returns: + The device at type the index + """""" + assert type(index) is int + return Device(self._get_wrapped_object_().GetInstrumentType(index)) + + def get_scan_stats_for_scan_number(self, scan_number: int) -> ScanStatistics: + """""" + Get the scan statistics for a scan. For example: The retention time of the scan. + + Parameters: + scanNumber: + scan number + + Returns: + Statistics for scan + """""" + assert type(scan_number) is int + return ScanStatistics._get_wrapper_(self._get_wrapped_object_().GetScanStatsForScanNumber(scan_number)) + + def get_scan_type(self, scan_number: int) -> str: + """""" + Get a string representing the scan type (for filtering). For more complete tests + on filters, consider using the IScanFilter interface. If reading data using IRawDataPlus, + you may use ThermoFisher.CommonCore.Data.Interfaces.IRawDataPlus.GetFilterForScanNumber(System.Int32) + A filter string (possibly entered from the UI) may be parsed using ThermoFisher.CommonCore.Data.Interfaces.IRawDataPlus.GetFilterFromString(System.String) + If the RT is known, and not the scan number, use ScanNumberFromRetentionTime + to convert the time to a scan number. + + Parameters: + scanNumber: + Scan number whose type is needed + + Returns: + Type of scan, in string format. To compare individual filter fields, the ScanDefinition + class can be used. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(scan_number) is int + return self._get_wrapped_object_().GetScanType(scan_number) + + def get_segmented_scan_from_scan_number(self, scan_number: int, stats: ScanStatistics) -> SegmentedScan: + """""" + Gets scan data for the given scan number. It will also fill stats object, if + any supplied. For most detector types, this is the only data for the scan, and + contains either profile or centroid information (depending on the type of scan + performed). For Orbitrap data (FT packet formats), this returns the first set + of data for the scan (typically profile). The second set of data (centroids) + are available from the GetCentroidStream method. The ""Segmented"" format is used + for SIM and SRM modes, where there may be multiple mass ranges (segments) of + a scan. Full scan data has only one segment. + + Parameters: + scanNumber: + The scan number. + + stats: + statistics for the scan + + Returns: + The segmented scan + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + assert type(scan_number) is int + assert type(stats) is ScanStatistics + return SegmentedScan._get_wrapper_(self._get_wrapped_object_().GetSegmentedScanFromScanNumber(scan_number, stats._get_wrapped_object_())) + + def get_segment_event_table(self) -> List[List[str]]: + """""" + Gets the segment event table for the current instrument. This table indicates + planned scan types for the MS detector. It is usually created from an instrument + method, by the detector. With data dependent or custom scan types, this will + not be a complete list of scan types used within the file. If this object implements + the derived IRawDataPlus interface, then This same data can be obtained in object + format (instead of string) with the IRawDataPlus property ""ScanEvents"" + + Returns: + A two dimensional array of events. The first index is segment index (segment + number-1). The second is event index (event number -1) within the segment. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return self._get_wrapped_object_().GetSegmentEventTable() + + def get_status_log_entries_count(self) -> int: + """""" + returns the number of entries in the current instrument's status log + + Returns: + The number of available status log entries. + """""" + return self._get_wrapped_object_().GetStatusLogEntriesCount() + + def get_status_log_for_retention_time(self, retention_time: float) -> LogEntry: + """""" + Gets the status log nearest to a retention time. + + Parameters: + retentionTime: + The retention time. + + Returns: + ThermoFisher.CommonCore.Data.Business.LogEntry object containing status log information. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + assert is_number(retention_time) + return LogEntry._get_wrapper_(self._get_wrapped_object_().GetStatusLogForRetentionTime(float(retention_time))) + + def get_status_log_header_information(self) -> List[HeaderItem]: + """""" + Returns the header information for the current instrument's status log. This + defines the format of the log entries. + + Returns: + The headers (list of prefixes for the strings). + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + return [HeaderItem._get_wrapper_(i) for i in self._get_wrapped_object_().GetStatusLogHeaderInformation()] + + def get_status_log_values(self, status_log_index: int, if_formatted: bool) -> StatusLogValues: + """""" + Returns the Status log values for the current instrument, for the given status + record. This is most likely for diagnostics or archiving. Applications which + need logged data near a scan should use ""GetStatusLogForRetentionTime"". Note + that this does not return the ""labels"" for the fields. + + Parameters: + statusLogIndex: + Index into table of status logs + + ifFormatted: + true if they should be formatted as per the data definition for this field (recommended + for display). Unformatted values may be returned with default precision (for + float or double) Which may be better for graphing or archiving + + Returns: + The status log values. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + assert type(status_log_index) is int + assert type(if_formatted) is bool + return StatusLogValues._get_wrapper_(self._get_wrapped_object_().GetStatusLogValues(status_log_index, if_formatted)) + + def get_trailer_extra_header_information(self) -> List[HeaderItem]: + """""" + Gets the trailer extra header information. This is common across all scan numbers. + This defines the format of additional data logged by an MS detector, at each + scan. For example, a particular detector may wish to record ""analyzer 3 temperature"" + at each scan, for diagnostic purposes. Since this is not a defined field in ""ScanHeader"" + it would be created as a custom ""trailer"" field for a given instrument. The field + definitions occur only once, and apply to all trailer extra records in the file. + In the example given, only the numeric value of ""analyzer 3 temperature"" would + be logged with each scan, without repeating the label. + + Returns: + The headers defining the ""trailer extra"" record format. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return [HeaderItem._get_wrapper_(h) for h in self._get_wrapped_object_().GetTrailerExtraHeaderInformation()] + + def get_trailer_extra_information(self, scan_number: int) -> LogEntry: + """""" + Gets the array of headers and values for this scan number. The values are formatted + as per the header settings. + + Parameters: + scanNumber: + The scan for which this information is needed + + Returns: + Extra information about the scan + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(scan_number) is int + return LogEntry._get_wrapper_(self._get_wrapped_object_().GetTrailerExtraInformation(scan_number)) + + def get_trailer_extra_values(self, scan_number: int, if_formatted: bool) -> List[str]: + """""" + Gets the Trailer Extra values for the specified scan number. If ifFormatted = + true, then the values will be formatted as per the header settings. + + Parameters: + scanNumber: + scan whose trailer data is needed + + ifFormatted: + true if the data should be formatted + + Returns: + The strings representing trailer data. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(scan_number) is int + assert type(if_formatted) is bool + return self._get_wrapped_object_().GetTrailerExtraValues(scan_number, if_formatted) + + def get_scan_dependents(self, scan_number: int, filter_precision_decimals: int) -> ScanDependents: + """""" + Summary: + Get scan dependents. Returns a list of scans, for which this scan was the parent. + + Parameters: + scanNumber: + The scan number. + + filterPrecisionDecimals: + The filter precision decimals. + + Returns: + Information about how data dependent scanning was performed. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(scan_number) is int + assert type(filter_precision_decimals) is int + return ScanDependents._get_wrapper_(self._get_wrapped_object_().GetScanDependents(scan_number, filter_precision_decimals)) + + def get_tune_data(self, tune_data_index: int) -> LogEntry: + """""" + Gets a text form of the instrument tuning method, at a given index. The number + of available tune methods can be obtained from GetTuneDataCount. + + Parameters: + tuneDataIndex: + tune data index + + Returns: + ThermoFisher.CommonCore.Data.Business.LogEntry object containing tune data for + specified tuneDataIndex. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(tune_data_index) is int + return LogEntry._get_wrapper_(self._get_wrapped_object_().GetTuneData(tune_data_index)) + + def get_tune_data_count(self) -> int: + """""" + Return the number of tune data entries. Each entry describes MS tuning conditions, + used to acquire this file. + + Returns: + The number of tune methods saved in the raw file>. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return self._get_wrapped_object_().GetTuneDataCount() + + def get_tune_data_header_information(self) -> List[HeaderItem]: + """""" + Return the header information for the current instrument's tune data. This defines + the fields used for a record which defines how the instrument was tuned. This + method only applies to MS detectors. These items can be paired with the ""TuneDataValues"" + to correctly display each tune record in the file. + + Returns: + The headers/>. + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + return [HeaderItem._get_wrapper_(i) for i in self._get_wrapped_object_().GetTuneDataHeaderInformation()] + + def get_tune_data_values(self, tune_data_index: int, if_formatted: bool) -> TuneDataValues: + """""" + Return tune data values for the specified index. This method only applies to + MS detectors. This contains only the data values, and not the headers. + + Parameters: + tuneDataIndex: + index into tune tables + + ifFormatted: + true if formatting should be done. Normally you would set ""ifFormatted"" to true, + to format based on the precision defined in the header. Setting this to false + uses default number formatting. This may be better for diagnostic charting, as + numbers may have higher precision than the default format. + + Returns: + The tune data + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedMsDeviceException: + Thrown if the selected device is not of type MS + """""" + assert type(tune_data_index) is int + assert type(if_formatted) is bool + return TuneDataValues._get_wrapper_(self._get_wrapped_object_().GetTuneDataValues(tune_data_index, if_formatted)) + + def is_centroid_scan_from_scan_number(self, scan_number: int) -> bool: + """""" + Test if a scan is centroid format + + Parameters: + scanNumber: + Number of the scan + + Returns: + True if the scan is centroid format + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + assert type(scan_number) is int + return self._get_wrapped_object_().IsCentroidScanFromScanNumber(scan_number) + + def refresh_view_of_file(self) -> bool: + """""" + Re-read the current file, to get the latest data. Only meaningful when the raw + file is InAcquisition when opened, or on the last refresh call. After acquisition + is completed further calls have no effect. + For example, the value of ""LastSpectrum"" in the Run Header of a detector may + be 60 after a refresh call. Even after new scans become acquired, this value + will remain at 60, from the application's view of the data, until RefreshViewOfFile + is called again. If GetRunHeader is called again, the number of scans may now + be a larger value, such as 100 + + Returns: + true, if refresh was OK. + """""" + return self._get_wrapped_object_().RefreshViewOfFile() + + def retention_time_from_scan_number(self, scan_number: int) -> float: + """""" + Get the retention time (minutes) from a scan number + + Parameters: + scanNumber: + Scan number + + Returns: + Retention time (start time) of scan + + Exceptions: + T:ThermoFisher.CommonCore.Data.Business.NoSelectedDeviceException: + Thrown if no device has been selected + """""" + assert type(scan_number) is int + return self._get_wrapped_object_().RetentionTimeFromScanNumber(scan_number) + + def scan_number_from_retention_time(self, time: float) -> int: + """""" + Get the nearest scan number to a retention time + + Parameters: + time: + Retention time (minutes) + + Returns: + Scan number in the selected instrument which is closest to this time. If there + are no scans, -1 is returned. + """""" + assert is_number(time) + return self._get_wrapped_object_().ScanNumberFromRetentionTime(float(time)) + + def select_instrument(self, instrument_type: Device, instrument_index: int): + """""" + Choose the data stream from the data source. This must be called before reading + data from a detector (such as chromatograms or scans). You may call ThermoFisher.CommonCore.Data.Interfaces.IRawData.GetInstrumentCountOfType(ThermoFisher.CommonCore.Data.Business.Device) + to determine if there is at least one instrument of the required device type. + + Parameters: + instrumentType: + Type of instrument + + instrumentIndex: + Stream number (1 based) + """""" + assert type(instrument_type) is Device + assert type(instrument_index) is int + self._get_wrapped_object_().SelectInstrument(instrument_type.value, instrument_index) + + def default_mass_options(self) -> MassOptions: + """""" + Summary: + Get the mass tolerance and precision values from a raw file + + Parameters: + rawData: + Raw file + + Returns: + The default tolerance and filter precision + """""" + return MassOptions._get_wrapper_(ThermoFisher.CommonCore.Data.Extensions.DefaultMassOptions(self._get_wrapped_object_())) + + def average_scans_in_scan_range(self, start_scan: int, end_scan: int, scan_filter: ScanFilter, options: MassOptions=None, average_options: FtAverageOptions=None) -> Scan: + """""" + Summary: + Gets the average of scans between the given scan numbers, which match the supplied + filter rules. + + Parameters: + data: + File to read from + + startScan: + start scan + + endScan: + end scan + + filter: + filter rules + + options: + mass tolerance settings. If not supplied, these are default from the raw file + + averageOptions: + The average Options (for FT format data). + + Returns: + the averaged scan. Use Scan.ScansCombined to find how many scans were averaged. + """""" + assert type(start_scan) is int + assert type(end_scan) is int + assert type(scan_filter) is ScanFilter or type(scan_filter) is str + + if type(scan_filter) is ScanFilter: + scan_filter = scan_filter._get_wrapped_object_() + + if options is not None: + assert type(options) is MassOptions + options = options._get_wrapped_object_() + if average_options is not None: + assert type(average_options) is FtAverageOptions + average_options = average_options._get_wrapped_object_() + + averaged_scan = ThermoFisher.CommonCore.Data.Extensions.AverageScansInScanRange(self._get_wrapped_object_(), start_scan, end_scan, scan_filter, options, average_options) + return Scan._get_wrapper_(averaged_scan) if averaged_scan is not None else None + + def average_scans(self, scans: List[int], options: MassOptions=None, average_options: FtAverageOptions=None, always_merge_segments: bool=False) -> Scan: + """""" + Summary: + Calculates the average spectra based upon the list supplied. The application + should filter the data before making this code, to ensure that the scans are + of equivalent format. The result, when the list contains scans of different formats + (such as linear trap MS centroid data added to orbitrap MS/MS profile data) is + undefined. If the first scan in the list contains ""FT Profile"", then the FT data + profile is averaged for each scan in the list. The combined profile is then centroided. + If the first scan is profile data, but not orbitrap data: All scans are summed, + starting from the final scan in this list, moving back to the first scan in the + list, and the average is then computed. For simple centroid data formats: The + scan stats ""TIC"" value is used to find the ""most abundant scan"". This scan is + then used as the ""first scan of the average"". Scans are then added to this average, + taking scans alternatively before and after the apex, merging data within tolerance. + + Parameters: + data: + File to read from + + scans: + list of scans to average + + options: + mass tolerance settings. If not supplied, these are default from the raw file + + averageOptions: + The average Options (for FT format data). + + alwaysMergeSegments: + Merge segments, even if mass ranges are not similar. Only applies to data with + 1 mass segment + + Returns: + The average of the listed scans. Use Scan.ScansCombined to find how many scans + were averaged. + """""" + assert type(scans) is list + assert type(always_merge_segments) is bool + if options is not None: + assert type(options) is MassOptions + options = options._get_wrapped_object_() + if average_options is not None: + assert type(average_options) is FtAverageOptions + average_options = average_options._get_wrapped_object_() + scans = to_net_list(scans, int) + return Scan._get_wrapper_(ThermoFisher.CommonCore.Data.Extensions.AverageScans(self._get_wrapped_object_(), scans, options, average_options, always_merge_segments)) + + def get_error_log_item(self, index: int) -> ErrorLogEntry: + """""" + Summary: + Gets an entry from the instrument error log. + + Parameters: + index: + Zero based index. The number of records available is RunHeaderEx.ErrorLogCount + + Returns: + An interface to read a specific log entry + """""" + assert type(index) is int + net_entry = self._get_wrapped_object_().GetErrorLogItem(index) + return ErrorLogEntry._get_wrapper_(net_entry) if net_entry else None + + def __enter__(self) -> RawFileAccess: + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.dispose() + + def dispose(self): + """""" + Dispose object + """""" + self._get_wrapped_object_().Dispose() + + +if __name__ == '__main__': + raw_file_path = r""D:\Nextcloud\Shared\MS\data\00_raw\00_corrected_ion_mass\20210407_15mer_bleomycin.raw"" + + with RawFileAccess(raw_file_path) as raw_file: + raw_file.select_instrument(Device.MS, 1) + print(raw_file.creator_id) + ","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/data_model/__init__.py",".py","85","2","from fisher_py.raw_file_reader.data_model.wrapped_run_header import WrappedRunHeader +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/raw_file_reader/data_model/wrapped_run_header.py",".py","4601","169","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data import ToleranceUnits + + +class WrappedRunHeader(NetWrapperBase): + """""" + Information about the file stream + """""" + + def __init__(self): + super().__init__() + # can only be used for wrapping (no Python side instantiation + + @property + def spectra_count(self) -> int: + """""" + Gets the count of recorded spectra + """""" + return self._get_wrapped_object_().SpectraCount + + @property + def high_mass(self) -> float: + """""" + Gets the highest recorded mass in file + """""" + return self._get_wrapped_object_().HighMass + + @property + def low_mass(self) -> float: + """""" + Gets the lowest recorded mass in file + """""" + return self._get_wrapped_object_().LowMass + + @property + def end_time(self) -> float: + """""" + Gets the time of last scan in file + """""" + return self._get_wrapped_object_().EndTime + + @property + def start_time(self) -> float: + """""" + Gets the time of first scan in file + """""" + return self._get_wrapped_object_().StartTime + + @property + def last_spectrum(self) -> int: + """""" + Gets the last spectrum (scan) number. If this is less than 1, then there are + no scans acquired yet. + """""" + return self._get_wrapped_object_().LastSpectrum + + @property + def first_spectrum(self) -> int: + """""" + Gets the first spectrum (scan) number (typically 1). + """""" + return self._get_wrapped_object_().FirstSpectrum + + @property + def comment_2(self) -> str: + """""" + Gets the second comment about this data stream. + """""" + return self._get_wrapped_object_().Comment2 + + @property + def comment_1(self) -> str: + """""" + Gets the first comment about this data stream. + """""" + return self._get_wrapped_object_().Comment1 + + @property + def max_intensity(self) -> float: + """""" + Gets the max intensity. + """""" + return self._get_wrapped_object_().MaxIntensity + + @property + def filter_mass_precision(self) -> int: + """""" + Gets the number of digits of precision suggested for formatting masses in the + filters. + """""" + return self._get_wrapped_object_().FilterMassPrecision + + @property + def expected_run_time(self) -> float: + """""" + Gets the expected data acquisition time. + """""" + return self._get_wrapped_object_().ExpectedRunTime + + @property + def mass_resolution(self) -> float: + """""" + Gets the mass resolution of this instrument. + """""" + return self._get_wrapped_object_().MassResolution + + @property + def in_acquisition(self) -> int: + """""" + Gets a value indicating whether this file is being created. 0: File is complete. + All other positive values: The file is in acquisition. Negative values are undefined. + """""" + return self._get_wrapped_object_().InAcquisition + + @property + def trailer_extra_count(self) -> int: + """""" + Gets the count of ""trailer extra"" records. Typically, same as the count of scans. + """""" + return self._get_wrapped_object_().TrailerExtraCount + + @property + def trailer_scan_event_count(self) -> int: + """""" + Gets the count of ""scan events"" + """""" + return self._get_wrapped_object_().TrailerScanEventCount + + @property + def error_log_count(self) -> int: + """""" + Gets the count of error log entries + """""" + return self._get_wrapped_object_().ErrorLogCount + + @property + def tune_data_count(self) -> int: + """""" + Gets the count of tune data entries + """""" + return self._get_wrapped_object_().TuneDataCount + + @property + def error_log_count(self) -> int: + """""" + Gets the count of status log entries + """""" + return self._get_wrapped_object_().ErrorLogCount + + @property + def status_log_count(self) -> int: + """""" + Gets the count of status log entries + """""" + return self._get_wrapped_object_().StatusLogCount + + @property + def tolerance_unit(self) -> ToleranceUnits: + """""" + Gets the tolerance units + """""" + return ToleranceUnits(self._get_wrapped_object_().ToleranceUnit) + + @property + def max_integrated_intensity(self) -> float: + """""" + Gets the max integrated intensity. + """""" + return self._get_wrapped_object_().MaxIntegratedIntensity","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/scan_dependent_details.py",".py","1048","47","from fisher_py.net_wrapping import NetWrapperBase +from typing import List + + +class ScanDependentDetails(NetWrapperBase): + + @property + def scan_index(self) -> int: + """""" + Gets the index of the scan. + + Value: + The index of the scan. + """""" + return self._get_wrapped_object_().ScanIndex + + @property + def filter_string(self) -> str: + """""" + Gets the filter string. + + Value: + The filter string. + """""" + return self._get_wrapped_object_().FilterString + + @property + def precursor_mass_array(self) -> List[float]: + """""" + Gets the precursor array. + + Value: + The precursor mass array. + """""" + return self._get_wrapped_object_().PrecursorMassArray + + @property + def isolation_width_array(self) -> List[float]: + """""" + Gets the isolation width array. + + Value: + The isolation width array. + """""" + return self._get_wrapped_object_().IsolationWidthArray + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/device.py",".py","176","14","import enum + +class Device(enum.Enum): + """""" + Data acquisition device + """""" + none = -1 + MS = 0 + MSAnalog = 1 + Analog = 2 + UV = 3 + Pda = 4 + Other = 5 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/error_log_entry.py",".py","430","18","from fisher_py.net_wrapping import NetWrapperBase + + +class ErrorLogEntry(NetWrapperBase): + """""" + The ErrorLogEntry interface. + """""" + + @property + def retention_time(self) -> float: + """"""Gets the retention time."""""" + return self._get_wrapped_object_().RetentionTime + + @property + def message(self) -> str: + """"""Gets the error message."""""" + return self._get_wrapped_object_().Message +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_accurate_mass.py",".py","175","13","import enum + + +class FilterAccurateMass(enum.Enum): + """""" + The filter rule for accurate mass. + """""" + Off = 0 + On = 1 + Internal = 2 + External = 3 + Any = 4 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/tolerance_units.py",".py","156","11","import enum + + +class ToleranceUnits(enum.Enum): + """""" + The units that you can associate with mass tolerance + """""" + mmu = 0 + ppm = 1 + amu = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/source_fragmentation_info_valid_type.py",".py","170","10","import enum + + +class SourceFragmentationInfoValidType(enum.Enum): + """""" + Specified whether the source fragmentation info is valid. + """""" + Energy = 0 + Any = 1 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/file_error.py",".py","1482","46","from fisher_py.net_wrapping import NetWrapperBase + + +class FileError(NetWrapperBase): + + @property + def has_error(self) -> bool: + """""" + Gets a value indicating whether this file has detected an error. If this is false: + Other error properties in this interface have no meaning. Applications should + not continue with processing data from any file which indicates an error. + """""" + return self._get_wrapped_object_().HasError + + @property + def has_warning(self) -> bool: + """""" + Gets a value indicating whether this file has detected a warning. If this is + false: Other warning properties in this interface have no meaning. + """""" + return self._get_wrapped_object_().HasWarning + + @property + def error_code(self) -> int: + """""" + Gets the error code number. Typically this is a windows system error number. + The lowest valid windows error is: 0x00030200 Errors detected within our files + will have codes below 100. + """""" + return self._get_wrapped_object_().ErrorCode + + @property + def error_message(self) -> str: + """""" + Gets the error message. For ""unknown exceptions"" this may include a stack trace. + """""" + return self._get_wrapped_object_().ErrorMessage + + @property + def warning_message(self) -> str: + """""" + Gets the warning message. + """""" + return self._get_wrapped_object_().WarningMessage + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/__init__.py",".py","1187","21","from fisher_py.data.ft_average_options import FtAverageOptions +from fisher_py.data.raw_file_classification import RawFileClassification +from fisher_py.data.tray_shape import TrayShape +from fisher_py.data.error_log_entry import ErrorLogEntry +from fisher_py.data.auto_sampler_information import AutoSamplerInformation +from fisher_py.data.file_type import FileType +from fisher_py.data.file_header import FileHeader +from fisher_py.data.source_fragmentation_info_valid_type import SourceFragmentationInfoValidType +from fisher_py.data.scan_dependent_details import ScanDependentDetails +from fisher_py.data.filter_accurate_mass import FilterAccurateMass +from fisher_py.data.scan_filter import ScanFilter +from fisher_py.data.tolerance_units import ToleranceUnits +from fisher_py.data.device import Device +from fisher_py.data.peak_options import PeakOptions +from fisher_py.data.common_core_data_object import CommonCoreDataObject +from fisher_py.data.file_error import FileError +from fisher_py.data.sequence_info import SequenceInfo +from fisher_py.data.sequence_file_writer import SequenceFileWriter +from fisher_py.data.scan_event import ScanEvent +from fisher_py.data.scan_events import ScanEvents +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/file_header.py",".py","7080","215","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data import FileType +from fisher_py.utils import datetime_net_to_py, datetime_py_to_net +from datetime import datetime + + +class FileHeader(NetWrapperBase): + @property + def who_created_id(self) -> str: + """""" + Gets or sets the creator Id. The creator Id is the full text user name of the + user when the file is created. + """""" + return self._get_wrapped_object_().WhoCreatedId + + @who_created_id.setter + def who_created_id(self, value: str): + """""" + Gets or sets the creator Id. The creator Id is the full text user name of the + user when the file is created. + """""" + assert type(value) is str + self._get_wrapped_object_().WhoCreatedId = value + + @property + def who_created_logon(self) -> str: + """""" + Gets or sets the creator Login name. The creator login name is the user name + of the user when the file is created, as entered at the ""user name, password"" + screen in windows. + """""" + return self._get_wrapped_object_().WhoCreatedLogon + + @who_created_logon.setter + def who_created_logon(self, value: str): + """""" + Gets or sets the creator Login name. The creator login name is the user name + of the user when the file is created, as entered at the ""user name, password"" + screen in windows. + """""" + assert type(value) is str + self._get_wrapped_object_().WhoCreatedLogon = value + + @property + def who_modified_id(self) -> str: + """""" + Gets or sets the creator Id. The creator Id is the full text user name of the + user when the file is created. + """""" + return self._get_wrapped_object_().WhoModifiedId + + @who_modified_id.setter + def who_modified_id(self, value: str): + """""" + Gets or sets the creator Id. The creator Id is the full text user name of the + user when the file is created. + """""" + assert type(value) is str + self._get_wrapped_object_().WhoModifiedId = value + + @property + def who_modified_logon(self) -> str: + """""" + Gets or sets the creator Login name. The creator login name is the user name + of the user when the file is created, as entered at the ""user name, password"" + screen in windows. + """""" + return self._get_wrapped_object_().WhoModifiedLogon + + @who_modified_logon.setter + def who_modified_logon(self, value: str): + """""" + Gets or sets the creator Login name. The creator login name is the user name + of the user when the file is created, as entered at the ""user name, password"" + screen in windows. + """""" + assert type(value) is str + self._get_wrapped_object_().WhoModifiedLogon = value + + @property + def file_type(self) -> FileType: + """""" + Gets or sets the type of the file. If the file is not recognized, the value of + the FileType will be set to ""Not Supported"" + """""" + return FileType(self._get_wrapped_object_().FileType) + + @file_type.setter + def file_type(self, value: FileType): + """""" + Gets or sets the type of the file. If the file is not recognized, the value of + the FileType will be set to ""Not Supported"" + """""" + assert type(value) is FileType + self._get_wrapped_object_().FileType = value.value + + @property + def revision(self) -> int: + """""" + Gets or sets the file format revision Note: this does not refer to revisions + of the content. It defines revisions of the binary files structure. + """""" + return self._get_wrapped_object_().Revision + + @revision.setter + def revision(self, value: int): + """""" + Gets or sets the file format revision Note: this does not refer to revisions + of the content. It defines revisions of the binary files structure. + """""" + assert type(value) is int + self._get_wrapped_object_().Revision = value + + @property + def creation_date(self) -> datetime: + """""" + Gets or sets the file creation date. + """""" + return datetime_net_to_py(self._get_wrapped_object_().CreationDate) + + @creation_date.setter + def creation_date(self, value: datetime): + """""" + Gets or sets the file creation date. + """""" + assert type(value) is datetime + self._get_wrapped_object_().CreationDate = datetime_py_to_net(value) + + @property + def modified_date(self) -> datetime: + """""" + Gets or sets the modified date. File changed audit information (most recent change) + + Value: + The modified date. + """""" + return datetime_net_to_py(self._get_wrapped_object_().ModifiedDate) + + @modified_date.setter + def modified_date(self, value: datetime): + """""" + Gets or sets the modified date. File changed audit information (most recent change) + + Value: + The modified date. + """""" + assert type(value) is datetime + self._get_wrapped_object_().ModifiedDate = datetime_py_to_net(value) + + @property + def number_of_times_modified(self) -> int: + """""" + Gets or sets the number of times modified. + + Value: + The number of times the file has been modified. + """""" + return self._get_wrapped_object_().NumberOfTimesModified + + @number_of_times_modified.setter + def number_of_times_modified(self, value: int): + """""" + Gets or sets the number of times modified. + + Value: + The number of times the file has been modified. + """""" + assert type(value) is int + self._get_wrapped_object_().NumberOfTimesModified = value + + @property + def number_of_times_calibrated(self) -> int: + """""" + Gets or sets the number of times calibrated. + + Value: + The number of times calibrated. + """""" + return self._get_wrapped_object_().NumberOfTimesCalibrated + + @number_of_times_calibrated.setter + def number_of_times_calibrated(self, value: int): + """""" + Gets or sets the number of times calibrated. + + Value: + The number of times calibrated. + """""" + assert type(value) is int + self._get_wrapped_object_().NumberOfTimesCalibrated = value + + @property + def file_description(self) -> str: + """""" + Gets or sets the file description. User's narrative description of the file, + 512 unicode characters (1024 bytes) + + Value: + The file description. + """""" + return self._get_wrapped_object_().FileDescription + + @file_description.setter + def file_description(self, value: str): + """""" + Gets or sets the file description. User's narrative description of the file, + 512 unicode characters (1024 bytes) + + Value: + The file description. + """""" + assert type(value) is str + self._get_wrapped_object_().FileDescription = value + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/file_type.py",".py","513","26","import enum + + +class FileType(enum.Enum): + """""" + The type of the file. + """""" + NotSupported = 0 + ExperimentMethod = 1 + SampleList = 2 + ProcessingMethod = 4 + RawFile = 8 + TuneMethod = 16 + ResultsFile = 32 + QuanFile = 64 + CalibrationFile = 128 + MethodFile = 256 + XqnFile = 512 + LayoutFile = 4096 + MethodEditorLayout = 4160 + SampleListEditorLayout = 4224 + ProcessingMethodEditLayout = 4352 + QualBrowserLayout = 4608 + TuneLayout = 5120 + ResultsLayout = 6144 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/scan_event.py",".py","21036","696","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data.business import Range, Reaction +from fisher_py.data.filter_enums import ( + EventAccurateMass, FieldFreeRegionType, TriState, CompensationVoltageType, SectorScanType, ActivationType, + PolarityType, MsOrderType, SourceFragmentationValueType, ScanModeType, ScanDataType, IonizationModeType, + DetectorType, MassAnalyzerType, EnergyType +) + + +class ScanEvent(NetWrapperBase): + """""" + The ScanEvent interface. Determines how scans are done. + """""" + + @property + def field_free_region(self) -> FieldFreeRegionType: + """""" + Gets the field free region setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.FieldFreeRegionType for possible + values + """""" + return FieldFreeRegionType(self._get_wrapped_object_().FieldFreeRegion) + + @property + def enhanced(self) -> TriState: + """""" + Gets the enhanced scan setting. + """""" + return TriState(self._get_wrapped_object_().Enhanced) + + @property + def multiple_photon_dissociation(self) -> TriState: + """""" + Gets the multi-photon dissociation setting. + """""" + return TriState(self._get_wrapped_object_().MultiplePhotonDissociation) + + @property + def multiple_photon_dissociation_value(self) -> float: + """""" + Gets the multi-photon dissociation value. + + Value: + Floating point multi-photon dissociation value + """""" + return self._get_wrapped_object_().MultiplePhotonDissociationValue + + @property + def electron_capture_dissociation(self) -> TriState: + """""" + Gets the electron capture dissociation setting. + """""" + return TriState(self._get_wrapped_object_().ElectronCaptureDissociation) + + @property + def electron_capture_dissociation_value(self) -> float: + """""" + Gets the electron capture dissociation value. + + Value: + Floating point electron capture dissociation value + """""" + return self._get_wrapped_object_().ElectronCaptureDissociationValue + + @property + def photo_ionization(self) -> TriState: + """""" + Gets the photo ionization setting. + """""" + return TriState(self._get_wrapped_object_().PhotoIonization) + + @property + def pulsed_q_dissociation(self) -> TriState: + """""" + Gets pulsed dissociation setting. + """""" + return TriState(self._get_wrapped_object_().PulsedQDissociation) + + @property + def pulsed_q_dissociation_value(self) -> float: + """""" + Gets the pulsed dissociation value. + + Value: + Floating point pulsed dissociation value + """""" + return self._get_wrapped_object_().PulsedQDissociationValue + + @property + def electron_transfer_dissociation(self) -> TriState: + """""" + Gets the electron transfer dissociation setting. + """""" + return TriState(self._get_wrapped_object_().ElectronTransferDissociation) + + @property + def electron_transfer_dissociation_value(self) -> float: + """""" + Gets the electron transfer dissociation value. + + Value: + Floating point electron transfer dissociation value + """""" + return self._get_wrapped_object_().ElectronTransferDissociationValue + + @property + def higher_energy_ci_d(self) -> TriState: + """""" + Gets the higher energy CID setting. + """""" + return TriState(self._get_wrapped_object_().HigherEnergyCiD) + + @property + def higher_energy_ci_d_value(self) -> float: + """""" + Gets the higher energy CID value. + + Value: + Floating point higher energy CID value + """""" + return self._get_wrapped_object_().HigherEnergyCiDValue + + @property + def ultra(self) -> TriState: + """""" + Gets the ultra scan setting. + """""" + return TriState(self._get_wrapped_object_().Ultra) + + @property + def multiplex(self) -> TriState: + """""" + Gets the Multiplex type + """""" + return TriState(self._get_wrapped_object_().Multiplex) + + @property + def param_b(self) -> TriState: + """""" + Gets the parameter b. + """""" + return TriState(self._get_wrapped_object_().ParamB) + + @property + def param_f(self) -> TriState: + """""" + Gets the parameter f. + """""" + return TriState(self._get_wrapped_object_().ParamF) + + @property + def multi_notch(self) -> TriState: + """""" + Gets the Multi notch (Synchronous Precursor Selection) type + """""" + return TriState(self._get_wrapped_object_().MultiNotch) + + @property + def param_r(self) -> TriState: + """""" + Gets the parameter r. + """""" + return TriState(self._get_wrapped_object_().ParamR) + + @property + def param_v(self) -> TriState: + """""" + Gets the parameter v. + """""" + return TriState(self._get_wrapped_object_().ParamV) + + @property + def name(self) -> str: + """""" + Gets the event Name. + """""" + return self._get_wrapped_object_().Name + + @property + def supplemental_activation(self) -> TriState: + """""" + Gets supplemental activation type setting. + """""" + return TriState(self._get_wrapped_object_().SupplementalActivation) + + @property + def multi_state_activation(self) -> TriState: + """""" + Gets MultiStateActivation type setting. + """""" + return TriState(self._get_wrapped_object_().MultiStateActivation) + + @property + def compensation_voltage(self) -> TriState: + """""" + Gets Compensation Voltage Option setting. + """""" + return TriState(self._get_wrapped_object_().CompensationVoltage) + + @property + def compensation_volt_type(self) -> CompensationVoltageType: + """""" + Gets Compensation Voltage type setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.CompensationVoltageType for possible + values + """""" + return CompensationVoltageType(self._get_wrapped_object_().CompensationVoltType) + + @property + def scan_type_index(self) -> int: + """""" + Gets encoded form of segment and scan event number. + + Value: + HIWORD == segment, LOWORD == scan type + """""" + return self._get_wrapped_object_().ScanTypeIndex + + @property + def mass_count(self) -> int: + """""" + Gets number of (precursor) masses + + Value: + The size of mass array + """""" + return self._get_wrapped_object_().MassCount + + @property + def param_a(self) -> TriState: + """""" + Gets the parameter a. + """""" + return TriState(self._get_wrapped_object_().ParamA) + + @property + def mass_range_count(self) -> int: + """""" + Gets the number of mass ranges for final scan + + Value: + The size of mass range array + """""" + return self._get_wrapped_object_().MassRangeCount + + @property + def source_fragmentation_info_count(self) -> int: + """""" + Gets the number of source fragmentation info values + + Value: + The size of source fragmentation info array + """""" + return self._get_wrapped_object_().SourceFragmentationInfoCount + + @property + def sector_scan(self) -> SectorScanType: + """""" + Gets the sector scan setting. Applies to 2 sector (Magnetic, electrostatic) Mass + spectrometers, or hybrids. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SectorScanType for possible values + """""" + return SectorScanType(self._get_wrapped_object_().SectorScan) + + @property + def lock(self) -> TriState: + """""" + Gets the lock scan setting. + """""" + return TriState(self._get_wrapped_object_().Lock) + + @property + def polarity(self) -> PolarityType: + """""" + Gets the polarity of the scan. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.PolarityType for possible values + """""" + return PolarityType(self._get_wrapped_object_().Polarity) + + @property + def ms_order(self) -> MsOrderType: + """""" + Gets the scan MS/MS power setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MSOrderType for possible values + """""" + return MsOrderType(self._get_wrapped_object_().MSOrder) + + @property + def dependent(self) -> TriState: + """""" + Gets the dependent scan setting. A scan is ""dependent"" if the scanning method + is based on analysis of data from a previous scan. + """""" + return TriState(self._get_wrapped_object_().Dependent) + + @property + def source_fragmentation(self) -> TriState: + """""" + Gets source fragmentation scan setting. + """""" + return TriState(self._get_wrapped_object_().SourceFragmentation) + + @property + def source_fragmentation_type(self) -> SourceFragmentationValueType: + """""" + Gets the source fragmentation type setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SourceFragmentationValueType for + possible values + """""" + return SourceFragmentationValueType(self._get_wrapped_object_().SourceFragmentationType) + + @property + def scan_mode(self) -> ScanModeType: + """""" + Gets the scan type setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.ScanModeType for possible values + """""" + return ScanModeType(self._get_wrapped_object_().ScanMode) + + @property + def scan_data(self) -> ScanDataType: + """""" + Gets the scan data format (profile or centroid). + """""" + return ScanDataType(self._get_wrapped_object_().ScanData) + + @property + def ionization_mode(self) -> IonizationModeType: + """""" + Gets the ionization mode scan setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.IonizationModeType for possible + values + """""" + return IonizationModeType(self._get_wrapped_object_().IonizationMode) + + @property + def corona(self) -> TriState: + """""" + Gets the corona scan setting. + """""" + return TriState(self._get_wrapped_object_().Corona) + + @property + def detector(self) -> DetectorType: + """""" + Gets the detector validity setting. The property ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.DetectorValue + only contains valid information when this is set to ""DetectorType.Valid"" + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.DetectorType for possible values + """""" + return DetectorType(self._get_wrapped_object_().Detector) + + @property + def detector_value(self) -> float: + """""" + Gets the detector value. This should only be used when valid. ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.Detector + + Value: + Floating point detector value + """""" + return self._get_wrapped_object_().DetectorValue + + @property + def wideband(self) -> TriState: + """""" + Gets the wideband scan setting. + """""" + return TriState(self._get_wrapped_object_().Wideband) + + @property + def mass_analyzer(self) -> MassAnalyzerType: + """""" + Gets the mass analyzer scan setting. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MassAnalyzerType for possible values + """""" + return MassAnalyzerType(self._get_wrapped_object_().MassAnalyzer) + + @property + def turbo_scan(self) -> TriState: + """""" + Gets the turbo scan setting. + """""" + return TriState(self._get_wrapped_object_().TurboScan) + + def get_activation(self, index: int) -> ActivationType: + """""" + Retrieves activation type at 0-based index. + + Parameters: + index: + Index of activation to be retrieved + + Returns: + activation of MS step; See ThermoFisher.CommonCore.Data.FilterEnums.ActivationType + for possible values + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassCount to get the + count of activations. + """""" + return ActivationType(self._get_wrapped_object_().GetActivation(index)) + + def get_energy(self, index: int) -> float: + """""" + Retrieves precursor(collision) energy value for MS step at 0-based index. + + Parameters: + index: + Index of precursor(collision) energy to be retrieved + + Returns: + precursor(collision) energy of MS step + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassCount to get the + count of energies. + """""" + return self._get_wrapped_object_().GetEnergy(index) + + def get_energy_valid(self, index: int) -> EnergyType: + """""" + Retrieves precursor(collision) energy validation flag at 0-based index. + + Parameters: + index: + Index of precursor(collision) energy validation to be retrieved + + Returns: + precursor(collision) energy validation of MS step; See ThermoFisher.CommonCore.Data.FilterEnums.EnergyType + for possible values + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassCount to get the + count of precursor(collision) energy validations. + """""" + return EnergyType(self._get_wrapped_object_().GetEnergyValid(index)) + + def get_first_precursor_mass(self, index: int) -> float: + """""" + Gets the first precursor mass. This is only valid data where ""GetPrecursorRangeValidity"" + returns true for the same index. + + Parameters: + index: + The index. + + Returns: + The first mass + """""" + return self._get_wrapped_object_().GetFirstPrecursorMass(index) + + def get_is_multiple_activation(self, index: int) -> bool: + """""" + Retrieves multiple activations flag at 0-based index of masses. + + Parameters: + index: + Index of flag to be retrieved + + Returns: + true if mass at given index has multiple activations; false otherwise + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassCount to get the + count of masses. + """""" + return self._get_wrapped_object_().GetIsMultipleActivation(index) + + def get_isolation_width(self, index: int) -> float: + """""" + Gets the isolation width. + + Parameters: + index: + The index. + + Returns: + The isolation width + """""" + return self._get_wrapped_object_().GetIsolationWidth(index) + + def get_isolation_width_offset(self, index: int) -> float: + """""" + Gets the isolation width offset. + + Parameters: + index: + The index. + + Returns: + The isolation width offset + """""" + return self._get_wrapped_object_().GetIsolationWidthOffset(index) + + def get_last_precursor_mass(self, index: int) -> float: + """""" + Gets the last precursor mass. This is only valid data where ""GetPrecursorRangeValidity"" + returns true for the same index. + + Parameters: + index: + The index. + + Returns: + The last mass + """""" + return self._get_wrapped_object_().GetLastPrecursorMass(index) + + def get_mass(self, index: int) -> float: + """""" + Retrieves mass value for MS step at 0-based index. + + Parameters: + index: + Index of mass value to be retrieved + + Returns: + Mass value of MS step + + Exceptions: + T:System.IndexOutOfRangeException: + Will be thrown when index >= MassCount + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassCount to get the + count of mass values. + """""" + return self._get_wrapped_object_().GetMass(index) + + def get_mass_range(self, index: int) -> Range: + """""" + Retrieves mass range for final scan at 0-based index. + + Parameters: + index: + Index of mass range to be retrieved + + Returns: + Mass range for final scan at 0-based index + + Exceptions: + T:System.IndexOutOfRangeException: + Will be thrown when index >= MassRangeCount + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.MassRangeCount to + get the count of mass ranges. + """""" + return Range._get_wrapper_(self._get_wrapped_object_().GetMassRange(index)) + + def get_precursor_range_validity(self, index: int) -> bool: + """""" + Determine if a precursor range is valid. + + Parameters: + index: + The index. + + Returns: + true if valid + """""" + return self._get_wrapped_object_().GetPrecursorRangeValidity(index) + + def get_reaction(self, index: int) -> Reaction: + """""" + Gets the reaction data for the mass at 0 based index. Descries how a particular + MS/MS precursor mass is fragmented. Equivalent to calling GetMass, GetEnergy, + GetPrecursorRangeValidity, GetFirstPrecursorMass GetLastPrecursorMass, GetIsolationWidth, + GetIsolationWidthOffset, GetEnergyValid GetActivation, GetIsMultipleActivation. + Depending on the implementation of the interface, this call may be more efficient + than calling several of the methods listed. + + Parameters: + index: + index of reaction + + Returns: + reaction details + """""" + return Reaction(self._get_wrapped_object_().GetReaction(index)) + + def get_source_fragmentation_info(self, index: int) -> float: + """""" + Retrieves a source fragmentation info value at 0-based index. + + Parameters: + index: + Index of source fragmentation info to be retrieved + + Returns: + Source Fragmentation info value at 0-based index + + Exceptions: + T:System.IndexOutOfRangeException: + Will be thrown when index >= SourceFragmentationInfoCount + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanEventBase.SourceFragmentationInfoCount + to get the count of source fragmentation info values. + """""" + return self._get_wrapped_object_().GetSourceFragmentationInfo(index) + + @property + def accurate_mass(self) -> EventAccurateMass: + """""" + Gets the accurate mass setting. + """""" + return EventAccurateMass(self._get_wrapped_object_().AccurateMass) + + @property + def is_valid(self) -> bool: + """""" + Gets a value indicating whether this event is valid. + """""" + return self._get_wrapped_object_().IsValid + + @property + def is_custom(self) -> bool: + """""" + Gets a value indicating whether this is a custom event. A custom event implies + that any scan derived from this event could be different. The scan type must + be inspected to determine the scanning mode, and not the event. + """""" + return self._get_wrapped_object_().IsCustom + + @property + def source_fragmentation_mass_range_count(self) -> int: + """""" + Gets the source fragmentation mass range count. + """""" + return self._get_wrapped_object_().SourceFragmentationMassRangeCount + + @property + def mass_calibrator_count(self) -> int: + """""" + Gets the mass calibrator count. + """""" + return self._get_wrapped_object_().MassCalibratorCount + + def get_mass_calibrator(self, index: int) -> float: + """""" + Get the mass calibrator, at a given index. + + Parameters: + index: + The index, which should be from 0 to MassCalibratorCount -1 + + Returns: + The mass calibrator. + + Exceptions: + T:System.IndexOutOfRangeException: + Thrown when requesting calibrator above count + """""" + return self._get_wrapped_object_().GetMassCalibrator(index) + + def get_source_fragmentation_mass_range(self, index: int) -> Range: + """""" + Get the source fragmentation mass range, at a given index. + + Parameters: + index: + The index. + + Returns: + The mass range. + """""" + return Range._get_wrapper_(self._get_wrapped_object_().GetSourceFragmentationMassRange(index)) + + def __str__(self) -> str: + """""" + Convert to string. + + Returns: + The converted scanning method. + """""" + return self._get_wrapped_object_().ToString()","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/tray_shape.py",".py","594","24","import enum + + +class TrayShape(enum.Enum): + """"""The auto sampler tray shape."""""" + + """"""Vials or wells are arranged in a rectangle on the tray"""""" + Rectangular = 0 + + """"""Vials are arranged in a circle."""""" + Circular = 1 + + """"""Vials are staggered on odd numbered positions on the tray."""""" + StaggeredOdd = 2 + + """"""Vials are staggered on even numbered positions on the tray."""""" + StaggeredEven = 3 + + """"""The layout is unknown."""""" + Unknown = 4 + + """"""The layout information is invalid. No other tray layout data should be displayed."""""" + Invalid = 5 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/scan_filter.py",".py","31090","935","from typing import List +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.utils import is_number, to_net_list +from fisher_py.data.filter_enums import ( + SectorScanType, FieldFreeRegionType, TriState, CompensationVoltageType, ScanDataType, + PolarityType, SourceFragmentationValueType, ScanModeType, MassAnalyzerType, DetectorType, + IonizationModeType, MsOrderType +) +from fisher_py.data import FilterAccurateMass, SourceFragmentationInfoValidType + + +class ScanFilter(NetWrapperBase): + """""" + The ScanFilter interface defines a set of rules for selecting scans. For example: + Testing if a scan should be included in a chromatogram. Many if the rules include + an ""Any"" choice, which implies that this rule will not be tested. Testing logic + is included in the class ThermoFisher.CommonCore.Data.Business.ScanFilterHelper + The class ThermoFisher.CommonCore.Data.Extensions contains methods related to + filters, the filter helper and raw data. + """""" + + def __init__(self, scan_filter_net): + super().__init__() + self._wrapped_object = scan_filter_net + + @property + def sector_scan(self) -> SectorScanType: + """""" + Gets or sets the sector scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SectorScanType for possible values + """""" + return SectorScanType(self._get_wrapped_object_().SectorScan) + + @sector_scan.setter + def sector_scan(self, value: SectorScanType): + """""" + Gets or sets the sector scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SectorScanType for possible values + """""" + assert type(value) is SectorScanType + self._get_wrapped_object_().SectorScan = value.value + + @property + def field_free_region(self) -> FieldFreeRegionType: + """""" + Gets or sets the field free region filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.FieldFreeRegionType for possible + values + """""" + return FieldFreeRegionType(self._get_wrapped_object_().FieldFreeRegion) + + @field_free_region.setter + def field_free_region(self, value: FieldFreeRegionType): + """""" + Gets or sets the field free region filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.FieldFreeRegionType for possible + values + """""" + assert type(value) is FieldFreeRegionType + self._get_wrapped_object_().FieldFreeRegion = value.value + + @property + def ultra(self) -> TriState: + """""" + Gets or sets the ultra scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().Ultra) + + @ultra.setter + def ultra(self, value: TriState): + """""" + Gets or sets the ultra scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Ultra = value.value + + @property + def enhanced(self) -> TriState: + """""" + Gets or sets the enhanced scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().Enhanced) + + @enhanced.setter + def enhanced(self, value: TriState): + """""" + Gets or sets the enhanced scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Enhanced = value.value + + @property + def multiple_photon_dissociation(self) -> TriState: + """""" + Gets or sets the multi-photon dissociation filtering rule. + """""" + return TriState(self._get_wrapped_object_().MultiplePhotonDissociation) + + @multiple_photon_dissociation.setter + def multiple_photon_dissociation(self, value: TriState): + """""" + Gets or sets the multi-photon dissociation filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().MultiplePhotonDissociation = value.value + + @property + def multiple_photon_dissociation_value(self) -> float: + """""" + Gets or sets the multi-photon dissociation value. + + Value: + Floating point multi-photon dissociation value + """""" + return self._get_wrapped_object_().MultiplePhotonDissociationValue + + @multiple_photon_dissociation_value.setter + def multiple_photon_dissociation_value(self, value: float): + """""" + Gets or sets the multi-photon dissociation value. + + Value: + Floating point multi-photon dissociation value + """""" + assert is_number(value) + self._get_wrapped_object_().MultiplePhotonDissociationValue = float(value) + + @property + def electron_capture_dissociation(self) -> TriState: + """""" + Gets or sets the electron capture dissociation filtering rule. + """""" + return TriState(self._get_wrapped_object_().ElectronCaptureDissociation) + + @electron_capture_dissociation.setter + def electron_capture_dissociation(self, value: TriState): + """""" + Gets or sets the electron capture dissociation filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ElectronCaptureDissociation = value.value + + @property + def electron_capture_dissociation_value(self) -> float: + """""" + Gets or sets the electron capture dissociation value. + + Value: + Floating point electron capture dissociation value + """""" + return self._get_wrapped_object_().ElectronCaptureDissociationValue + + @electron_capture_dissociation_value.setter + def electron_capture_dissociation_value(self, value: float): + """""" + Gets or sets the electron capture dissociation value. + + Value: + Floating point electron capture dissociation value + """""" + assert is_number(value) + self._get_wrapped_object_().ElectronCaptureDissociationValue = float(value) + + @property + def photo_ionization(self) -> TriState: + """""" + Gets or sets the photo ionization filtering rule. + """""" + return TriState(self._get_wrapped_object_().PhotoIonization) + + @photo_ionization.setter + def photo_ionization(self, value: TriState): + """""" + Gets or sets the photo ionization filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().PhotoIonization = value.value + + @property + def pulsed_q_dissociation(self) -> TriState: + """""" + Gets or sets pulsed dissociation filtering rule. + """""" + return TriState(self._get_wrapped_object_().PulsedQDissociation) + + @pulsed_q_dissociation.setter + def pulsed_q_dissociation(self, value: TriState): + """""" + Gets or sets pulsed dissociation filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().PulsedQDissociation = value.value + + @property + def pulsed_q_dissociation_value(self) -> float: + """""" + Gets or sets the pulsed dissociation value. Only applies when the PulsedQDissociation + rule is used. + + Value: + Floating point pulsed dissociation value + """""" + return self._get_wrapped_object_().PulsedQDissociationValue + + @pulsed_q_dissociation_value.setter + def pulsed_q_dissociation_value(self, value: float): + """""" + Gets or sets the pulsed dissociation value. Only applies when the PulsedQDissociation + rule is used. + + Value: + Floating point pulsed dissociation value + """""" + assert is_number(value) + self._get_wrapped_object_().PulsedQDissociationValue = float(value) + + @property + def electron_transfer_dissociation(self) -> TriState: + """""" + Gets or sets the electron transfer dissociation filtering rule. + """""" + return TriState(self._get_wrapped_object_().ElectronTransferDissociation) + + @electron_transfer_dissociation.setter + def electron_transfer_dissociation(self, value: TriState): + """""" + Gets or sets the electron transfer dissociation filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ElectronTransferDissociation = value.value + + @property + def lock(self) -> TriState: + """""" + Gets or sets the lock scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().Lock) + + @lock.setter + def lock(self, value: TriState): + """""" + Gets or sets the lock scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Lock = value.value + + @property + def electron_transfer_dissociation_value(self) -> float: + """""" + Gets or sets the electron transfer dissociation value. Only used when the ""ElectronTransferDissociation"" + rule is used. + + Value: + Floating point electron transfer dissociation value + """""" + return self._get_wrapped_object_().ElectronTransferDissociationValue + + @electron_transfer_dissociation_value.setter + def electron_transfer_dissociation_value(self, value: float): + """""" + Gets or sets the electron transfer dissociation value. Only used when the ""ElectronTransferDissociation"" + rule is used. + + Value: + Floating point electron transfer dissociation value + """""" + assert is_number(value) + self._get_wrapped_object_().ElectronTransferDissociationValue = float(value) + + @property + def higher_energy_ci_d_value(self) -> float: + """""" + Gets or sets the higher energy CID value. Only applies when the ""HigherEnergyCiD"" + rule is used. + """""" + return self._get_wrapped_object_().HigherEnergyCiDValue + + @higher_energy_ci_d_value.setter + def higher_energy_ci_d_value(self, value: float): + """""" + Gets or sets the higher energy CID value. Only applies when the ""HigherEnergyCiD"" + rule is used. + """""" + assert is_number(value) + self._get_wrapped_object_().HigherEnergyCiDValue = float(value) + + @property + def multiplex(self) -> TriState: + """""" + Gets or sets the Multiplex type filtering rule. + """""" + return TriState(self._get_wrapped_object_().Multiplex) + + @multiplex.setter + def multiplex(self, value: TriState): + """""" + Gets or sets the Multiplex type filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Multiplex = value.value + + @property + def param_a(self) -> TriState: + """""" + Gets or sets the parameter a filtering rule.. + """""" + return TriState(self._get_wrapped_object_().ParamA) + + @param_a.setter + def param_a(self, value: TriState): + """""" + Gets or sets the parameter a filtering rule.. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ParamA = value.value + + @property + def param_b(self) -> TriState: + """""" + Gets or sets the parameter b filtering rule.. + """""" + return TriState(self._get_wrapped_object_().ParamB) + + @param_b.setter + def param_b(self, value: TriState): + """""" + Gets or sets the parameter b filtering rule.. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ParamB = value.value + + @property + def param_f(self) -> TriState: + """""" + Gets or sets the parameter f filtering rule.. + """""" + return TriState(self._get_wrapped_object_().ParamF) + + @param_f.setter + def param_f(self, value: TriState): + """""" + Gets or sets the parameter f filtering rule.. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ParamF = value.value + + @property + def multi_notch(self) -> TriState: + """""" + Gets or sets the SPS (Synchronous Precursor Selection) Multi notch filtering + rule. + """""" + return TriState(self._get_wrapped_object_().MultiNotch) + + @multi_notch.setter + def multi_notch(self, value: TriState): + """""" + Gets or sets the SPS (Synchronous Precursor Selection) Multi notch filtering + rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().MultiNotch = value.value + + @property + def param_r(self) -> TriState: + """""" + Gets or sets the parameter r filtering rule.. + """""" + return TriState(self._get_wrapped_object_().ParamR) + + @param_r.setter + def param_r(self, value: TriState): + """""" + Gets or sets the parameter r filtering rule.. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ParamR = value.value + + @property + def param_v(self) -> TriState: + """""" + Gets or sets the parameter v filtering rule.. + """""" + return TriState(self._get_wrapped_object_().ParamV) + + @param_v.setter + def param_v(self, value: TriState): + """""" + Gets or sets the parameter v filtering rule.. + """""" + assert type(value) is TriState + self._get_wrapped_object_().ParamV = value.value + + @property + def name(self) -> str: + """""" + Gets or sets the event Name. Used for ""compound name"" filtering. + """""" + return self._get_wrapped_object_().Name + + @name.setter + def name(self, value: str): + """""" + Gets or sets the event Name. Used for ""compound name"" filtering. + """""" + assert type(value) is str + self._get_wrapped_object_().Name = value + + @property + def supplemental_activation(self) -> TriState: + """""" + Gets or sets supplemental activation type filter rule. + """""" + return TriState(self._get_wrapped_object_().SupplementalActivation) + + @supplemental_activation.setter + def supplemental_activation(self, value: TriState): + """""" + Gets or sets supplemental activation type filter rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().SupplementalActivation = value.value + + @property + def multi_state_activation(self) -> TriState: + """""" + Gets or sets MultiStateActivation type filtering rule. + """""" + return TriState(self._get_wrapped_object_().MultiStateActivation) + + @multi_state_activation.setter + def multi_state_activation(self, value: TriState): + """""" + Gets or sets MultiStateActivation type filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().MultiStateActivation = value.value + + @property + def higher_energy_ci_d(self) -> TriState: + """""" + Gets or sets the higher energy CID filtering rule. + """""" + return TriState(self._get_wrapped_object_().HigherEnergyCiD) + + @higher_energy_ci_d.setter + def higher_energy_ci_d(self, value: TriState): + """""" + Gets or sets the higher energy CID filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().HigherEnergyCiD = value.value + + @property + def compensation_voltage(self) -> TriState: + """""" + Gets or sets Compensation Voltage filtering rule. + """""" + return TriState(self._get_wrapped_object_().CompensationVoltage) + + @compensation_voltage.setter + def compensation_voltage(self, value: TriState): + """""" + Gets or sets Compensation Voltage filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().CompensationVoltage = value.value + + @property + def compensation_volt_type(self) -> CompensationVoltageType: + """""" + Gets or sets Compensation Voltage type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.CompensationVoltageType for possible + values + """""" + return CompensationVoltageType(self._get_wrapped_object_().CompensationVoltType) + + @compensation_volt_type.setter + def compensation_volt_type(self, value: CompensationVoltageType): + """""" + Gets or sets Compensation Voltage type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.CompensationVoltageType for possible + values + """""" + assert type(value) is CompensationVoltageType + self._get_wrapped_object_().CompensationVoltType = value.value + + @property + def detector_value(self) -> float: + """""" + Gets or sets the detector value. This is used for filtering when the Detector + filter is enabled. + + Value: + Floating point detector value + """""" + return self._get_wrapped_object_().DetectorValue + + @detector_value.setter + def detector_value(self, value: float): + """""" + Gets or sets the detector value. This is used for filtering when the Detector + filter is enabled. + + Value: + Floating point detector value + """""" + assert is_number(value) + self._get_wrapped_object_().DetectorValue = float(value) + + @property + def accurate_mass(self) -> FilterAccurateMass: + """""" + Gets the accurate mass filter rule. + """""" + return FilterAccurateMass(self._get_wrapped_object_().AccurateMass) + + @property + def mass_precision(self) -> int: + """""" + Gets or sets the mass precision, which is used to format the filter (in ToString). + """""" + return self._get_wrapped_object_().MassPrecision + + @mass_precision.setter + def mass_precision(self, value: int): + """""" + Gets or sets the mass precision, which is used to format the filter (in ToString). + """""" + assert type(value) is int + self._get_wrapped_object_().MassPrecision = value + + @property + def meta_filters(self) -> int: + """""" + Gets or sets additional instrument defined filters (these are bit flags). See + enum MetaFilterType. + """""" + return self._get_wrapped_object_().MetaFilters + + @meta_filters.setter + def meta_filters(self, value: int): + """""" + Gets or sets additional instrument defined filters (these are bit flags). See + enum MetaFilterType. + """""" + assert type(value) is int + self._get_wrapped_object_().MetaFilters = value + + @property + def unique_mass_count(self) -> int: + """""" + Gets the number of unique masses, taking into account multiple activations. For + example: If this is MS3 data, there are two ""parent masses"", but they may have + multiple reactions applied. If the first stage has two reactions, then there + are a total of 3 reactions, for the 2 ""unique masses"" + """""" + return self._get_wrapped_object_().UniqueMassCount + + @property + def source_fragmentation_info_valid(self) -> List[SourceFragmentationInfoValidType]: + """""" + Gets or sets an array of values which determines if the source fragmentation + values are valid. + """""" + return [SourceFragmentationInfoValidType(i) for i in self._get_wrapped_object_().SourceFragmentationInfoValid] + + @source_fragmentation_info_valid.setter + def source_fragmentation_info_valid(self, value: List[SourceFragmentationInfoValidType]): + """""" + Gets or sets an array of values which determines if the source fragmentation + values are valid. + """""" + assert type(value) is list + value = to_net_list([i._get_wrapped_object_() for i in value], type(value[0]._get_wrapped_object_())) + self._get_wrapped_object_().SourceFragmentationInfoValid = value + + @property + def locale_name(self) -> str: + """""" + Gets or sets the locale name. This can be used to affect string conversion. + """""" + return self._get_wrapped_object_().LocaleName + + @locale_name.setter + def locale_name(self, value: str): + """""" + Gets or sets the locale name. This can be used to affect string conversion. + """""" + assert type(value) is str + self._get_wrapped_object_().LocaleName = value + + @property + def compensation_voltage_count(self) -> int: + """""" + Gets the number of compensation voltage values. This is the number of values + related to cv mode. 1 for ""single value"", 2 for ""ramp"" and 1 per mass range for + ""SIM"". + """""" + return self._get_wrapped_object_().CompensationVoltageCount + + @property + def wideband(self) -> TriState: + """""" + Gets or sets the wideband filtering rule. + """""" + return TriState(self._get_wrapped_object_().Wideband) + + @wideband.setter + def wideband(self, value: TriState): + """""" + Gets or sets the wideband filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Wideband = value.value + + @property + def scan_data(self) -> ScanDataType: + """""" + Gets or sets the scan data type (centroid or profile) filtering rule. + """""" + return ScanDataType(self._get_wrapped_object_().ScanData) + + @scan_data.setter + def scan_data(self, value: ScanDataType): + """""" + Gets or sets the scan data type (centroid or profile) filtering rule. + """""" + assert type(value) is ScanDataType + self._get_wrapped_object_().ScanData = value.value + + @property + def polarity(self) -> PolarityType: + """""" + Gets or sets the polarity (+/-) filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.PolarityType for possible values + """""" + return PolarityType(self._get_wrapped_object_().Polarity) + + @polarity.setter + def polarity(self, value: PolarityType): + """""" + Gets or sets the polarity (+/-) filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.PolarityType for possible values + """""" + assert type(value) is PolarityType + self._get_wrapped_object_().Polarity = value.value + + @property + def souce_fragmentaion_value_count(self) -> int: + """""" + Gets the number of Source Fragmentation values. This is the number of values + related to sid mode. 1 for ""single value"", 2 for ""ramp"" and 1 per mass range + for ""SIM"". + """""" + return self._get_wrapped_object_().SouceFragmentaionValueCount + + @property + def dependent(self) -> TriState: + """""" + Gets or sets the dependent scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().Dependent) + + @dependent.setter + def dependent(self, value: TriState): + """""" + Gets or sets the dependent scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Dependent = value.value + + @property + def source_fragmentation(self) -> TriState: + """""" + Gets or sets source fragmentation scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().SourceFragmentation) + + @source_fragmentation.setter + def source_fragmentation(self, value: TriState): + """""" + Gets or sets source fragmentation scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().SourceFragmentation = value.value + + @property + def source_fragmentation_type(self) -> SourceFragmentationValueType: + """""" + Gets or sets the source fragmentation type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SourceFragmentationValueType for + possible values + """""" + return SourceFragmentationInfoValidType(self._get_wrapped_object_().SourceFragmentationType) + + @source_fragmentation_type.setter + def source_fragmentation_type(self, value: SourceFragmentationValueType): + """""" + Gets or sets the source fragmentation type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.SourceFragmentationValueType for + possible values + """""" + assert type(value) is SourceFragmentationValueType + self._get_wrapped_object_().SourceFragmentationType = value.value + + @property + def scan_mode(self) -> ScanModeType: + """""" + Gets or sets the scan type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.ScanModeType for possible values + """""" + return ScanModeType(self._get_wrapped_object_().ScanMode) + + @scan_mode.setter + def scan_mode(self, value: ScanModeType): + """""" + Gets or sets the scan type filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.ScanModeType for possible values + """""" + assert type(value) is ScanModeType + self._get_wrapped_object_().ScanMode = value.value + + @property + def mass_analyzer(self) -> MassAnalyzerType: + """""" + Gets or sets the mass analyzer scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MassAnalyzerType for possible values + """""" + return MassAnalyzerType(self._get_wrapped_object_().MassAnalyzer) + + @mass_analyzer.setter + def mass_analyzer(self, value: MassAnalyzerType): + """""" + Gets or sets the mass analyzer scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MassAnalyzerType for possible values + """""" + assert type(value) is MassAnalyzerType + self._get_wrapped_object_().MassAnalyzer = value.value + + @property + def detector(self) -> DetectorType: + """""" + Gets or sets the detector scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.DetectorType for possible values + """""" + return DetectorType(self._get_wrapped_object_().Detector) + + @detector.setter + def detector(self, value: DetectorType): + """""" + Gets or sets the detector scan filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.DetectorType for possible values + """""" + assert type(value) is DetectorType + self._get_wrapped_object_().Detector = value.value + + @property + def turbo_scan(self) -> TriState: + """""" + Gets or sets the turbo scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().TurboScan) + + @turbo_scan.setter + def turbo_scan(self, value: TriState): + """""" + Gets or sets the turbo scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().TurboScan = value.value + + @property + def ionization_mode(self) -> IonizationModeType: + """""" + Gets or sets the ionization mode filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.IonizationModeType for possible + values + """""" + return IonizationModeType(self._get_wrapped_object_().IonizationMode) + + @ionization_mode.setter + def ionization_mode(self, value: IonizationModeType): + """""" + Gets or sets the ionization mode filtering rule. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.IonizationModeType for possible + values + """""" + assert type(value) is IonizationModeType + self._get_wrapped_object_().IonizationMode = value.value + + @property + def corona(self) -> TriState: + """""" + Gets or sets the corona scan filtering rule. + """""" + return TriState(self._get_wrapped_object_().Corona) + + @corona.setter + def corona(self, value: TriState): + """""" + Gets or sets the corona scan filtering rule. + """""" + assert type(value) is TriState + self._get_wrapped_object_().Corona = value.value + + @property + def ms_order(self) -> MsOrderType: + """""" + Gets or sets the scan power or MS/MS mode filtering rule, such as MS3 or Parent + scan. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MSOrderType for possible values + """""" + return MsOrderType(self._get_wrapped_object_().MSOrder) + + @ms_order.setter + def ms_order(self, value: MsOrderType): + """""" + Gets or sets the scan power or MS/MS mode filtering rule, such as MS3 or Parent + scan. + + Value: + See ThermoFisher.CommonCore.Data.FilterEnums.MSOrderType for possible values + """""" + assert type(value) is MsOrderType + self._get_wrapped_object_().MSOrder = value.value + + def compensation_voltage_value(self, index: int) -> float: + """""" + Retrieves a compensation voltage (cv) value at 0-based index. + + Parameters: + index: + Index of compensation voltage to be retrieved + + Returns: + Compensation voltage value (cv) at 0-based index + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanFilter.CompensationVoltageCount + to get the count of compensation voltage values. + """""" + return self._get_wrapped_object_().CompensationVoltageValue(index) + + def get_source_fragmentation_info_valid(self, index: int) -> SourceFragmentationInfoValidType: + """""" + Get source fragmentation info valid, at zero based index. + + Parameters: + index: + The index. + + Returns: + The ThermoFisher.CommonCore.Data.Interfaces.SourceFragmentationInfoValidType. + """""" + return self._get_wrapped_object_().GetSourceFragmentationInfoValid(index) + + def index_to_multiple_activation_index(self, index: int) -> int: + """""" + Convert an index to multiple activation index. Converts a simple mass index to + the index to the unique mass, taking into account multiple activations. + + Parameters: + index: + The index to convert. + + Returns: + The index of the unique mass. + """""" + return self._get_wrapped_object_().IndexToMultipleActivationIndex(index) + + def source_fragmentation_value(self, index: int) -> float: + """""" + Retrieves a source fragmentation value (sid) at 0-based index. + + Parameters: + index: + Index of source fragmentation value to be retrieved + + Returns: + Source Fragmentation Value (sid) at 0-based index + + Remarks: + Use ThermoFisher.CommonCore.Data.Interfaces.IScanFilter.SouceFragmentaionValueCount + to get the count of source fragmentation values. + """""" + return self._get_wrapped_object_().SourceFragmentationValue(index) + + def __str__(self) -> str: + """""" + Convert to string. Mass values are converted as per the precision. + + Returns: + The System.String. + """""" + return self._get_wrapped_object_().ToString() +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/common_core_data_object.py",".py","1964","60","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher + + +class CommonCoreDataObject(NetWrapperBase): + """""" + CommonCoreData object is an abstract class. It includes a deep equals feature + """""" + + def __init__(self): + super().__init__() + + def deep_equals(self, value_to_compare: object) -> bool: + """""" + Provides a custom deep equality operation when checking for equality. + + Parameters: + valueToCompare: + The value to compare. + + Returns: + True if the items are equal, false if they are not. + """""" + return self._get_wrapped_object().DeepEquals(value_to_compare._get_wrapped_object_()) + + def equals(self, obj: object) -> bool: + """""" + Compares this object with another. Traverse the set of member variables to compare + against the object that was passed in. Determines whether the specified System.Object + is equal to the current System.Object. + + Parameters: + obj: + The System.Object to compare with the current System.Object. + + Returns: + true if the specified System.Object is equal to the current System.Object; otherwise, + false. + + Exceptions: + T:System.NullReferenceException: + The obj parameter is null. + """""" + return self._get_wrapped_object().Equals(obj._get_wrapped_object_()) + + def get_hash_code(self) -> int: + """""" + Serves as a hash function for a particular type. + + Returns: + A hash code for the current System.Object. + """""" + return self._get_wrapped_object().GetHashCode() + + def perform_default_settings(self): + """""" + Performs the default settings for the data object. This can overridden in each + data object that implements the interface to perform initialization settings. + """""" + self._get_wrapped_object().PerformDefaultSettings() +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/sequence_file_writer.py",".py","4550","152","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data import FileHeader, FileError, SequenceInfo +from fisher_py.data.business import SampleInformation, BracketType +from typing import List + + +class SequenceFileWriter(NetWrapperBase): + + def __init__(self): + super().__init__() + self._file_header = None + self._file_error = None + self._sequence_info = None + + @property + def file_header(self) -> FileHeader: + """""" + Gets the file header for the sequence + """""" + if self._file_header is None: + self._file_header = FileHeader._get_wrapper_(self._get_wrapped_object_().FileHeader) + + return self._file_header + + @property + def file_error(self) -> FileError: + """""" + Gets the file error state. + """""" + if self._file_error is None: + self._file_error = FileError._get_wrapper_(self._get_wrapped_object_().FileError) + + return self._file_error + + @property + def is_error(self) -> bool: + """""" + Gets a value indicating whether the last file operation caused an error + """""" + return self._get_wrapped_object_().IsError + + @property + def info(self) -> SequenceInfo: + """""" + Gets or sets additional information about a sequence + """""" + if self._sequence_info is None: + self._sequence_info = SequenceInfo._get_wrapper_(self._get_wrapped_object_().Info) + return self._sequence_info + + @info.setter + def info(self, value: SequenceInfo): + """""" + Gets or sets additional information about a sequence + """""" + assert type(value) is SequenceInfo + self._sequence_info = value + self._get_wrapped_object_().Info = value._get_wrapped_object_() + + @property + def samples(self) -> List[SampleInformation]: + """""" + Gets the set of samples in the sequence + """""" + return [SampleInformation._get_wrapper_(s) for s in self._get_wrapped_object_().Samples] + + @property + def file_name(self) -> str: + """""" + Gets the name of the sequence file. + """""" + return self._get_wrapped_object_().FileName + + @property + def bracket(self) -> BracketType: + """""" + Gets or sets the sequence bracket type. This determines which groups of samples + use the same calibration curve. + """""" + return BracketType(self._get_wrapped_object_().Bracket) + + @bracket.setter + def bracket(self, value: BracketType): + """""" + Gets or sets the sequence bracket type. This determines which groups of samples + use the same calibration curve. + """""" + assert type(value) is BracketType + self._get_wrapped_object_().Bracket = value.value + + @property + def tray_configuration(self) -> str: + """""" + Gets or sets a description of the auto-sampler tray + """""" + return self._get_wrapped_object_().TrayConfiguration + + @tray_configuration.setter + def tray_configuration(self, value: str): + """""" + Gets or sets a description of the auto-sampler tray + """""" + assert type(value) is str + self._get_wrapped_object_().TrayConfiguration = value + + def get_user_column_label(self, index: int) -> str: + """""" + Retrieves the user label at given 0-based label index. + + Parameters: + index: + Index of user label to be retrieved + + Returns: + String containing the user label at given index + + Remarks: + SampleInformation.MaxUserTextColumnCount determines the maximum number of user + column labels. + """""" + return self._get_wrapped_object_().GetUserColumnLabel(index) + + def save(self) -> bool: + """""" + Saves Sequence data to disk. + + Returns: + True saved data to disk; false otherwise. + """""" + return self._get_wrapped_object_().Save() + + def set_user_column_label(self, index: int, label: str) -> bool: + """""" + Sets the user label at given 0-based label index. + + Parameters: + index: + Index of user label to be set + + label: + New string value for user label to be set + + Returns: + true if successful; false otherwise + + Remarks: + SampleInformation.MaxUserTextColumnCount determines the maximum number of user + column labels. + """""" + return self._get_wrapped_object_().SetUserColumnLabel(index, label) + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/auto_sampler_information.py",".py","3756","97","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data.tray_shape import TrayShape + + +class AutoSamplerInformation(NetWrapperBase): + """""" + The AutoSamplerInformation interface. + """""" + + @property + def tray_index(self) -> int: + """"""Gets or sets the tray index, -1 for 'not recorded'"""""" + return self._get_wrapped_object_().TrayIndex + + @tray_index.setter + def tray_index(self, value: int): + """"""Gets or sets the tray index, -1 for 'not recorded'"""""" + assert type(value) is int + self._get_wrapped_object_().TrayIndex = value + + @property + def vial_index(self) -> int: + """"""Gets or sets the vial index, -1 for 'not recorded'"""""" + return self._get_wrapped_object_().VialIndex + + @vial_index.setter + def vial_index(self, value: int): + """"""Gets or sets the vial index, -1 for 'not recorded'"""""" + assert type(value) is int + self._get_wrapped_object_().VialIndex = value + + @property + def vials_per_tray(self) -> int: + """"""Gets or sets the number of vials (or wells) per tray. -1 for 'not recorded'"""""" + return self._get_wrapped_object_().VialsPerTray + + @vials_per_tray.setter + def vials_per_tray(self, value: int): + """"""Gets or sets the number of vials (or wells) per tray. -1 for 'not recorded'"""""" + assert type(value) is int + self._get_wrapped_object_().VialsPerTray = value + + @property + def vials_per_tray_x(self) -> int: + """"""Gets or sets the number of vials (or wells) per tray, across the tray. -1 for 'not recorded'"""""" + return self._get_wrapped_object_().VialsPerTrayX + + @vials_per_tray_x.setter + def vials_per_tray_x(self, value: int): + """"""Gets or sets the number of vials (or wells) per tray, across the tray. -1 for 'not recorded'"""""" + assert type(value) is int + self._get_wrapped_object_().VialsPerTrayX = value + + @property + def vials_per_tray_y(self) -> int: + """"""Gets or sets the number of vials (or wells) per tray, across the tray. -1 for 'not recorded'"""""" + return self._get_wrapped_object_().VialsPerTrayY + + @vials_per_tray_y.setter + def vials_per_tray_y(self, value: int): + """"""Gets or sets the number of vials (or wells) per tray, across the tray. -1 for 'not recorded'"""""" + assert type(value) is int + self._get_wrapped_object_().VialsPerTrayY = value + + @property + def tray_shape(self) -> TrayShape: + """"""Gets or sets the shape. If this property returns ""Invalid"", no other values in + this object contain usable information. Invalid data can occur for older raw + file formats, before auto sampler data was added. + """""" + return TrayShape(self._get_wrapped_object_().TrayShape) + + @tray_shape.setter + def tray_shape(self, value: TrayShape): + """"""Gets or sets the shape. If this property returns ""Invalid"", no other values in + this object contain usable information. Invalid data can occur for older raw + file formats, before auto sampler data was added. + """""" + assert type(value) is TrayShape + self._get_wrapped_object_().TrayShape = value.value + + @property + def tray_shape_as_string(self) -> int: + """"""Gets the tray shape as a string"""""" + return self._get_wrapped_object_().TrayShapeAsString + + @property + def tray_name(self) -> int: + """"""Gets or sets the tray name."""""" + return self._get_wrapped_object_().TrayName + + @tray_name.setter + def tray_name(self, value: str): + """"""Gets or sets the tray name."""""" + assert type(value) is str + self._get_wrapped_object_().TrayName = value + ","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/scan_events.py",".py","1973","64","from fisher_py.data.scan_event import ScanEvent +from fisher_py.net_wrapping import NetWrapperBase + + +class ScanEvents(NetWrapperBase): + """""" + The ScanEvents interface. + """""" + + @property + def segments(self) -> int: + """"""Gets the number segments."""""" + return self._get_wrapped_object_().Segments + + @property + def scan_events(self) -> int: + """"""Gets the total number of scan events, in all segments"""""" + return self._get_wrapped_object_().ScanEvents + + def get_event_by_segment(self, segment: int, event_number: int) -> ScanEvent: + """"""Get an event, indexed by the segment and event numbers (zero based). + + Args: + segment (int): The segment. + event_number (int): The event number. + + Returns: + ScanEvent: The event. + """""" + assert type(event_number) is int + assert type(segment) is int + + net_type = self._get_wrapped_object_().GetEvent(segment, event_number) + + return ScanEvent._get_wrapper_(net_type) + + def get_event(self, event_number: int) -> ScanEvent: + """"""Get an event, using indexed event number (zero based). This gets events from + all segments in order, use ""ScanEvents"" to get the total count of events. + + Args: + event_number (int): The event number. + + Returns: + ScanEvent: The event. + """""" + assert type(event_number) is int + + net_type = self._get_wrapped_object_().GetEvent(event_number) + + return ScanEvent._get_wrapper_(net_type) + + def get_event_count(self, segment: int) -> int: + """"""Gets the number of events in a specific segment (0 based) + + Args: + segment (int): The segment number + + Returns: + int: The number of events in this segment + """""" + assert type(segment) is int + self._get_wrapped_object_().GetEventCount(segment) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/peak_options.py",".py","267","16","import enum + + +class PeakOptions(enum.Enum): + """""" + Features which can be set per peak, such as ""reference compound"" + """""" + none = 0 + Saturated = 1 + Fragmented = 2 + Merged = 4 + Exception = 8 + Reference = 16 + Modified = 32 + LockPeak = 64 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/raw_file_thread_accessor.py",".py","1208","27","from fisher_py.net_wrapping.net_wrapper_base import NetWrapperBase +from fisher_py.raw_file_reader.raw_file_access import RawFileAccess + + +class RawFileThreadAccessor(NetWrapperBase): + """""" + Summary: + Defines an object which can create accessors for multiple threads to access the + same raw data. + """""" + + def create_thread_accessor(self) -> RawFileAccess: + """""" + Summary: + This interface method creates a thread safe access to raw data, for use by a + single thread. Each time a new thread (async call etc.) is made for accessing + raw data, this method must be used to create a private object for that thread + to use. This interface does not require that the application performs any locking. + In some implementations this may have internal locking (such as when based on + a real time file, which is continually changing in size), and in some implementations + it may be lockless. + + Returns: + An interface which can be used by a thread to access raw data + """""" + return RawFileAccess._get_wrapper_(self._wrapped_object.CreateThreadAccessor()) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/sequence_info.py",".py","1400","49","from typing import List +from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data.business import BracketType + + +class SequenceInfo(NetWrapperBase): + @property + def column_width(self) -> List[int]: + """""" + Gets the display width of each sequence column + """""" + return self._get_wrapped_object_().ColumnWidth + + @property + def type_to_column_position(self) -> List[int]: + """""" + Gets the column order (see home page?) + """""" + return self._get_wrapped_object_().TypeToColumnPosition + + @property + def bracket(self) -> BracketType: + """""" + Gets the sequence bracket type. This determines which groups of samples use the + same calibration curve. + """""" + return BracketType(self._get_wrapped_object_().Bracket) + + @property + def user_private_label(self) -> List[str]: + """""" + Gets the set of column names for application specific columns + """""" + return self._get_wrapped_object_().UserPrivateLabel + + @property + def tray_configuration(self) -> str: + """""" + Gets a description of the auto-sampler tray + """""" + return self._get_wrapped_object_().TrayConfiguration + + @property + def user_label(self) -> List[str]: + """""" + Gets the user configurable column names + """""" + return self._get_wrapped_object_().UserLabel +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/raw_file_classification.py",".py","167","11","import enum + + +class RawFileClassification(enum.Enum): + """""" + RawFile Classification + """""" + Indeterminate = 0 + StandardRaw = 1 + MasterScanNumberRaw = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/ft_average_options.py",".py","6372","134","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher + + +class FtAverageOptions(NetWrapperBase): + """""" + Options which can be used to control the Ft / Orbitrap averaging + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Interfaces.FtAverageOptions + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def max_charge_determinations(self) -> int: + """""" + Gets or sets the maximum number of ions which are sent to the charge pattern + calculation (starting from most intense) + """""" + return self._get_wrapped_object_().MaxChargeDeterminations + + @max_charge_determinations.setter + def max_charge_determinations(self, value: int): + """""" + Gets or sets the maximum number of ions which are sent to the charge pattern + calculation (starting from most intense) + """""" + assert type(value) is int + self._get_wrapped_object_().MaxChargeDeterminations = value + + @property + def merge_in_parallel(self) -> bool: + """""" + Gets or sets a value indicating whether parallel code may be used for resampling + and merging scans. Tuning option: Permit separate threads to be used for resampling + profiles. + """""" + return self._get_wrapped_object_().MergeInParallel + + @merge_in_parallel.setter + def merge_in_parallel(self, value: bool): + """""" + Gets or sets a value indicating whether parallel code may be used for resampling + and merging scans. Tuning option: Permit separate threads to be used for resampling + profiles. + """""" + assert type(value) is bool + self._get_wrapped_object_().MergeInParallel = value + + @property + def max_scans_merged(self) -> int: + """""" + Gets or sets the maximum number of scans which can be merged at once. This feature + is currently not yet implemented, and the value is ignored. When MergeInParallel + is enabled: this restricts the number of scans which are merged in each group. + Setting this too large may result in more memory allocation for ""arrays of results + to merge"" Default: 10 + """""" + return self._get_wrapped_object_().MaxScansMerged + + @max_scans_merged.setter + def max_scans_merged(self, value: int): + """""" + Gets or sets the maximum number of scans which can be merged at once. This feature + is currently not yet implemented, and the value is ignored. When MergeInParallel + is enabled: this restricts the number of scans which are merged in each group. + Setting this too large may result in more memory allocation for ""arrays of results + to merge"" Default: 10 + """""" + assert type(value) is int + self._get_wrapped_object_().MaxScansMerged = value + + @property + def merge_task_batching(self) -> int: + """""" + Gets or sets the minimum number of Re-sample tasks per thread. Tuning parameter + when MergeInParallel is set. Each scan is analyzed: Determining mass regions + which contain non-zero data, and re-sampling the intensity data aligned to a + set of output bins. After all scans have been re-sampled, the re-sampled data + has to be merged into the final output. Creating re-sampled data for profiles + is a fairly fast task. It may be inefficient to queue workers to created the + merged data for each scan in the batch. Setting this >1 will reduce threading + overheads, when averaging small batches of scans with low intensity peaks. Default: + 2. This feature only affects the re-sampling, as the final merge of the re-sampled + data is single threaded. + """""" + return self._get_wrapped_object_().MergeTaskBatching + + @merge_task_batching.setter + def merge_task_batching(self, value: int): + """""" + Gets or sets the minimum number of Re-sample tasks per thread. Tuning parameter + when MergeInParallel is set. Each scan is analyzed: Determining mass regions + which contain non-zero data, and re-sampling the intensity data aligned to a + set of output bins. After all scans have been re-sampled, the re-sampled data + has to be merged into the final output. Creating re-sampled data for profiles + is a fairly fast task. It may be inefficient to queue workers to created the + merged data for each scan in the batch. Setting this >1 will reduce threading + overheads, when averaging small batches of scans with low intensity peaks. Default: + 2. This feature only affects the re-sampling, as the final merge of the re-sampled + data is single threaded. + """""" + assert type(value) is int + self._get_wrapped_object_().MergeTaskBatching = value + + @property + def use_noise_table_when_available(self) -> bool: + """""" + Gets or sets a value indicating whether to use the noise and baseline table. + When set: The averaging algorithm calculates average noise based on a noise table + obtained (separately) from the raw file. The ""IRawData"" interface doe not have + methods to obtain this ""noise and baseline table"" from the raw file. So: The + scan averaging algorithm (by default) uses noise information saved with centroid + peaks when calculating the averaged noise. This option is only effective when + data is read via the IRawDataPlus interface. + """""" + return self._get_wrapped_object_().UseNoiseTableWhenAvailable + + @use_noise_table_when_available.setter + def use_noise_table_when_available(self, value: bool): + """""" + Gets or sets a value indicating whether to use the noise and baseline table. + When set: The averaging algorithm calculates average noise based on a noise table + obtained (separately) from the raw file. The ""IRawData"" interface doe not have + methods to obtain this ""noise and baseline table"" from the raw file. So: The + scan averaging algorithm (by default) uses noise information saved with centroid + peaks when calculating the averaged noise. This option is only effective when + data is read via the IRawDataPlus interface. + """""" + assert type(value) is bool + self._get_wrapped_object_().UseNoiseTableWhenAvailable = value + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/mass_analyzer_type.py",".py","276","15","import enum + + +class MassAnalyzerType(enum.Enum): + """""" + Specifies type of mass analyzer in scans. + """""" + MassAnalyzerITMS = 0 + MassAnalyzerTQMS = 1 + MassAnalyzerSQMS = 2 + MassAnalyzerTOFMS = 3 + MassAnalyzerFTMS = 4 + MassAnalyzerSector = 5 + Any = 6 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/energy_type.py",".py","144","10","import enum + + +class EnergyType(enum.Enum): + """""" + Specifies precursor(collision) energy validation type. + """""" + Valid = 0 + Any = 1 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/detector_type.py",".py","164","11","import enum + + +class DetectorType(enum.Enum): + """""" + Specifies inclusion or exclusion of the detector value. + """""" + Valid = 0 + Any = 1 + NotValid = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/ionization_mode_type.py",".py","713","31","import enum + + +class IonizationModeType(enum.Enum): + """""" + Specifies ionization mode in scans. + """""" + ElectronImpact = 0 + ChemicalIonization = 1 + FastAtomBombardment = 2 + ElectroSpray = 3 + AtmosphericPressureChemicalIonization = 4 + NanoSpray = 5 + ThermoSpray = 6 + FieldDesorption = 7 + MatrixAssistedLaserDesorptionIonization = 8 + GlowDischarge = 9 + Any = 10 + PaperSprayIonization = 11 + CardNanoSprayIonization = 12 + IonizationMode1 = 13 + IonizationMode2 = 14 + IonizationMode3 = 15 + IonizationMode4 = 16 + IonizationMode5 = 17 + IonizationMode6 = 18 + IonizationMode7 = 19 + IonizationMode8 = 20 + IonizationMode9 = 21 + IonModeBeyondKnown = 22 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/__init__.py",".py","1109","16","from fisher_py.data.filter_enums.activation_type import ActivationType +from fisher_py.data.filter_enums.compensation_voltage_type import CompensationVoltageType +from fisher_py.data.filter_enums.detector_type import DetectorType +from fisher_py.data.filter_enums.field_free_region_type import FieldFreeRegionType +from fisher_py.data.filter_enums.ionization_mode_type import IonizationModeType +from fisher_py.data.filter_enums.mass_analyzer_type import MassAnalyzerType +from fisher_py.data.filter_enums.ms_order_type import MsOrderType +from fisher_py.data.filter_enums.polarity_type import PolarityType +from fisher_py.data.filter_enums.scan_data_type import ScanDataType +from fisher_py.data.filter_enums.scan_mode_type import ScanModeType +from fisher_py.data.filter_enums.sector_scan_type import SectorScanType +from fisher_py.data.filter_enums.event_accurate_mass import EventAccurateMass +from fisher_py.data.filter_enums.source_fragmentation_value_type import SourceFragmentationValueType +from fisher_py.data.filter_enums.tri_state import TriState +from fisher_py.data.filter_enums.energy_type import EnergyType +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/tri_state.py",".py","177","11","import enum + + +class TriState(enum.Enum): + """""" + The feature state. By default: On. This tri-state enum is designed for filtering + """""" + On = 0 + Off = 1 + Any = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/sector_scan_type.py",".py","150","11","import enum + + +class SectorScanType(enum.Enum): + """""" + Specifies type of sector scan. + """""" + SectorBScan = 0 + SectorEScan = 1 + Any = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/ms_order_type.py",".py","265","22","import enum + + +class MsOrderType(enum.Enum): + """""" + Specifies scan power in scans. + """""" + Ng = -3 + Nl = -2 + Par = -1 + Any = 0 + Ms = 1 + Ms2 = 2 + Ms3 = 3 + Ms4 = 4 + Ms5 = 5 + Ms6 = 6 + Ms7 = 7 + Ms8 = 8 + Ms9 = 9 + Ms10 = 10 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/source_fragmentation_value_type.py",".py","213","13","import enum + + +class SourceFragmentationValueType(enum.Enum): + """""" + Specifies how source fragmentation values are interpreted. + """""" + NoValue = 0 + SingleValue = 1 + Ramp = 2 + SIM = 3 + Any = 4 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/activation_type.py",".py","1025","47","import enum + + +class ActivationType(enum.Enum): + """""" + The activation types are used to link a specific precursor mass with an activation + type. There are 26 possible mode values, including some reserved values. + """""" + CollisionInducedDissociation = 0 + MultiPhotonDissociation = 1 + ElectronCaptureDissociation = 2 + PQD = 3 + ElectronTransferDissociation = 4 + HigherEnergyCollisionalDissociation = 5 + Any = 6 + SAactivation = 7 + ProtonTransferReaction = 8 + NegativeElectronTransferDissociation = 9 + NegativeProtonTransferReaction = 10 + UltraVioletPhotoDissociation = 11 + ModeA = 12 + ModeB = 13 + ModeC = 14 + ModeD = 15 + ModeE = 16 + ModeF = 17 + ModeG = 18 + ModeH = 19 + ModeI = 20 + ModeJ = 21 + ModeK = 22 + ModeL = 23 + ModeM = 24 + ModeN = 25 + ModeO = 26 + ModeP = 27 + ModeQ = 28 + ModeR = 29 + ModeS = 30 + ModeT = 31 + ModeU = 32 + ModeV = 33 + ModeW = 34 + ModeX = 35 + ModeY = 36 + ModeZ = 37 + LastActivation = 38","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/polarity_type.py",".py","139","11","import enum + + +class PolarityType(enum.Enum): + """""" + Specifies polarity of scan. + """""" + Negative = 0 + Positive = 1 + Any = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/scan_data_type.py",".py","139","11","import enum + + +class ScanDataType(enum.Enum): + """""" + Specifies data type of scan. + """""" + Centroid = 0 + Profile = 1 + Any = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/scan_mode_type.py",".py","195","16","import enum + + +class ScanModeType(enum.Enum): + """""" + Specifies scan mode in scans. + """""" + Full = 0 + Zoom = 1 + Sim = 2 + Srm = 3 + Crm = 4 + Any = 5 + Q1Ms = 6 + Q3Ms = 7 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/compensation_voltage_type.py",".py","186","13","import enum + + +class CompensationVoltageType(enum.Enum): + """""" + Specifies compensation voltage type. + """""" + NoValue = 0 + SingleValue = 1 + Ramp = 2 + SIM = 3 + Any = 4 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/field_free_region_type.py",".py","180","11","import enum + + +class FieldFreeRegionType(enum.Enum): + """""" + Specifies type of field free region in scans. + """""" + FieldFreeRegion1 = 0 + FieldFreeRegion2 = 1 + Any = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/filter_enums/event_accurate_mass.py",".py","167","11","import enum + + +class EventAccurateMass(enum.Enum): + """""" + Determines how accurate mass calibration was done. + """""" + Internal = 0 + External = 1 + Off = 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/generic_data_types.py",".py","466","24","import enum + + +class GenericDataTypes(enum.Enum): + """""" + enumeration for data type for the fields used by records of TuneData, StatusLog, + TrailerExtra These are upper case names, so that they don't clash with standard + type names. + """""" + NULL = 0 + CHAR = 1 + TRUEFALSE = 2 + YESNO = 3 + ONOFF = 4 + UCHAR = 5 + SHORT = 6 + USHORT = 7 + LONG = 8 + ULONG = 9 + FLOAT = 10 + DOUBLE = 11 + CHAR_STRING = 12 + WCHAR_STRING = 13 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/scan_statistics.py",".py","11751","385","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import SpectrumPacketType + + +class ScanStatistics(NetWrapperBase): + """""" + Summary information about a scan. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.ScanStatistics + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def wavelength_step(self) -> float: + """""" + Gets or sets the wave length step. + """""" + return self._get_wrapped_object_().WavelengthStep + + @wavelength_step.setter + def wavelength_step(self, value: float): + """""" + Gets or sets the wave length step. + """""" + assert type(value) is float + self._get_wrapped_object_().WavelengthStep = value + + @property + def absorbance_unit_scale(self) -> float: + """""" + Gets or sets the absorbance unit scale. + """""" + return self._get_wrapped_object_().AbsorbanceUnitScale + + @absorbance_unit_scale.setter + def absorbance_unit_scale(self, value: float): + """""" + Gets or sets the absorbance unit scale. + """""" + assert type(value) is float + self._get_wrapped_object_().AbsorbanceUnitScale = value + + @property + def is_uniform_time(self) -> bool: + """""" + Gets or sets a value indicating whether is uniform time. + """""" + return self._get_wrapped_object_().IsUniformTime + + @is_uniform_time.setter + def is_uniform_time(self, value: bool): + """""" + Gets or sets a value indicating whether is uniform time. + """""" + assert type(value) is bool + self._get_wrapped_object_().IsUniformTime = value + + @property + def frequency(self) -> float: + """""" + Gets or sets the frequency. + """""" + return self._get_wrapped_object_().Frequency + + @frequency.setter + def frequency(self, value: float): + """""" + Gets or sets the frequency. + """""" + assert type(value) is float + self._get_wrapped_object_().Frequency = value + + @property + def is_centroid_scan(self) -> bool: + """""" + Gets or sets a value indicating whether this scan contains centroid data (else + profile) + """""" + return self._get_wrapped_object_().IsCentroidScan + + @is_centroid_scan.setter + def is_centroid_scan(self, value: bool): + """""" + Gets or sets a value indicating whether this scan contains centroid data (else + profile) + """""" + assert type(value) is bool + self._get_wrapped_object_().IsCentroidScan = value + + @property + def segment_number(self) -> int: + """""" + Gets or sets the time segment number for this event + """""" + return self._get_wrapped_object_().SegmentNumber + + @segment_number.setter + def segment_number(self, value: int): + """""" + Gets or sets the time segment number for this event + """""" + assert type(value) is int + self._get_wrapped_object_().SegmentNumber = value + + @property + def scan_event_number(self) -> int: + """""" + Gets or sets the event (scan type) number within segment + """""" + return self._get_wrapped_object_().ScanEventNumber + + @scan_event_number.setter + def scan_event_number(self, value: int): + """""" + Gets or sets the event (scan type) number within segment + """""" + assert type(value) is int + self._get_wrapped_object_().ScanEventNumber = value + + @property + def scan_number(self) -> int: + """""" + Gets or sets the number of the scan + """""" + return self._get_wrapped_object_().ScanNumber + + @scan_number.setter + def scan_number(self, value: int): + """""" + Gets or sets the number of the scan + """""" + assert type(value) is int + self._get_wrapped_object_().ScanNumber = value + + @property + def number_of_channels(self) -> int: + """""" + Gets or sets the number of channels acquired in this scan, if this is UV or analog + data, + """""" + return self._get_wrapped_object_().NumberOfChannels + + @number_of_channels.setter + def number_of_channels(self, value: int): + """""" + Gets or sets the number of channels acquired in this scan, if this is UV or analog + data, + """""" + assert type(value) is int + self._get_wrapped_object_().NumberOfChannels = value + + @property + def packet_count(self) -> int: + """""" + Gets or sets the Number of point in scan + """""" + return self._get_wrapped_object_().PacketCount + + @packet_count.setter + def packet_count(self, value: int): + """""" + Gets or sets the Number of point in scan + """""" + assert type(value) is int + self._get_wrapped_object_().PacketCount = value + + @property + def start_time(self) -> float: + """""" + Gets or sets the time at start of scan (minutes) + """""" + return self._get_wrapped_object_().StartTime + + @start_time.setter + def start_time(self, value: float): + """""" + Gets or sets the time at start of scan (minutes) + """""" + assert type(value) is float + self._get_wrapped_object_().StartTime = value + + @property + def tic(self) -> float: + """""" + Gets or sets the total Ion Current for scan + """""" + return self._get_wrapped_object_().TIC + + @tic.setter + def tic(self, value: float): + """""" + Gets or sets the total Ion Current for scan + """""" + assert type(value) is float + self._get_wrapped_object_().TIC = value + + @property + def base_peak_mass(self) -> float: + """""" + Gets or sets the mass of largest peak in scan + """""" + return self._get_wrapped_object_().BasePeakMass + + @base_peak_mass.setter + def base_peak_mass(self, value: float): + """""" + Gets or sets the mass of largest peak in scan + """""" + assert type(value) is float + self._get_wrapped_object_().BasePeakMass = value + + @property + def base_peak_intensity(self) -> float: + """""" + Gets or sets the intensity of highest peak in scan + """""" + return self._get_wrapped_object_().BasePeakIntensity + + @base_peak_intensity.setter + def base_peak_intensity(self, value: float): + """""" + Gets or sets the intensity of highest peak in scan + """""" + assert type(value) is float + self._get_wrapped_object_().BasePeakIntensity = value + + @property + def short_wavelength(self) -> float: + """""" + Gets or sets the shortest wavelength in PDA scan + """""" + return self._get_wrapped_object_().ShortWavelength + + @short_wavelength.setter + def short_wavelength(self, value: float): + """""" + Gets or sets the shortest wavelength in PDA scan + """""" + assert type(value) is float + self._get_wrapped_object_().ShortWavelength = value + + @property + def long_wavelength(self) -> float: + """""" + Gets or sets the longest wavelength in PDA scan + """""" + return self._get_wrapped_object_().LongWavelength + + @long_wavelength.setter + def long_wavelength(self, value: float): + """""" + Gets or sets the longest wavelength in PDA scan + """""" + assert type(value) is float + self._get_wrapped_object_().LongWavelength = value + + @property + def low_mass(self) -> float: + """""" + Gets or sets the lowest mass in scan + """""" + return self._get_wrapped_object_().LowMass + + @low_mass.setter + def low_mass(self, value: float): + """""" + Gets or sets the lowest mass in scan + """""" + assert type(value) is float + self._get_wrapped_object_().LowMass = value + + @property + def high_mass(self) -> float: + """""" + Gets or sets the highest mass in scan + """""" + return self._get_wrapped_object_().HighMass + + @high_mass.setter + def high_mass(self, value: float): + """""" + Gets or sets the highest mass in scan + """""" + assert type(value) is float + self._get_wrapped_object_().HighMass = value + + @property + def spectrum_packet_type(self) -> SpectrumPacketType: + """""" + Gets the packet format used in this scan. (read only). Value can be set using + the ""PacketType"" property. + """""" + return SpectrumPacketType(self._get_wrapped_object_().SpectrumPacketType) + + @property + def packet_type(self) -> int: + """""" + Gets or sets the indication of data format used by this scan. See also SpectrumPacketType + for decoding to an enum. + """""" + return self._get_wrapped_object_().PacketType + + @packet_type.setter + def packet_type(self, value: int): + """""" + Gets or sets the indication of data format used by this scan. See also SpectrumPacketType + for decoding to an enum. + """""" + assert type(value) is int + self._get_wrapped_object_().PacketType = value + + @property + def scan_type(self) -> str: + """""" + Gets or sets a String defining the scan type, for filtering + """""" + return self._get_wrapped_object_().ScanType + + @scan_type.setter + def scan_type(self, value: str): + """""" + Gets or sets a String defining the scan type, for filtering + """""" + assert type(value) is str + self._get_wrapped_object_().ScanType = value + + @property + def cycle_number(self) -> int: + """""" + Gets or sets the cycle number. Cycle number used to associate events within a + scan event cycle. For example, on the first cycle of scan events, all the events + would set this to '1'. On the second cycle, all the events would set this to + '2'. This field must be set by devices if supporting compound names for filtering. + However, it may be set in all acquisitions to help processing algorithms. + """""" + return self._get_wrapped_object_().CycleNumber + + @cycle_number.setter + def cycle_number(self, value: int): + """""" + Gets or sets the cycle number. Cycle number used to associate events within a + scan event cycle. For example, on the first cycle of scan events, all the events + would set this to '1'. On the second cycle, all the events would set this to + '2'. This field must be set by devices if supporting compound names for filtering. + However, it may be set in all acquisitions to help processing algorithms. + """""" + assert type(value) is int + self._get_wrapped_object_().CycleNumber = value + + def clone(self) -> ScanStatistics: + """""" + Creates a new object that is a copy of the current instance. + + Returns: + A new object that is a copy of this instance. + """""" + return ScanStatistics._get_wrapper_(self._get_wrapped_object().Clone()) + + def copy_to(self, stats: ScanStatistics, deep: bool): + """""" + Copy all fields + + Parameters: + stats: + Copy into this object + + deep: + If set, make a ""deep copy"" which will evaluate any lazy items and ensure no internal + source references + """""" + self._get_wrapped_object().CopyTo(stats._get_wrapped_object_(), deep) + + def deep_clone(self) -> ScanStatistics: + """""" + Produce a deep copy of an object. Must not contain any references into the original. + + Returns: + A deep clone of all objects in this + """""" + return ScanStatistics._get_wrapper_(self._get_wrapped_object().DeepClone()) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/scan.py",".py","21095","539","from __future__ import annotations +from fisher_py.data.business.range import Range +from typing import List, Any, TYPE_CHECKING +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import PeakOptions +from fisher_py.data.business import ( + MassToFrequencyConverter, NoiseAndBaseline, ScanStatistics, SegmentedScan, ToleranceMode, + CentroidStream, CachedScanProvider +) +from fisher_py.utils import to_net_list + +if TYPE_CHECKING: + from fisher_py.raw_file_reader import RawFileAccess + + +class Scan(NetWrapperBase): + """""" + Class to represent a scan + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.Scan + + def __init__(self, *args): + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + else: + if len(args) == 1: + converter = args[0] + raw_file_noise = None + elif len(args) == 2: + converter, raw_file_noise = args + assert type(raw_file_noise) is list + if len(raw_file_noise) > 0: + assert type(raw_file_noise[0]) is NoiseAndBaseline + raw_file_noise = to_net_list(raw_file_noise, NoiseAndBaseline._wrapped_type) + else: + raise ValueError('Unable to create Scan.') + + assert type(converter) is MassToFrequencyConverter + self._wrapped_object(converter._get_wrapped_object_(), [o._get_wrapped_object_() for o in raw_file_noise]) + + @property + def preferred_base_peak_mass(self) -> float: + """""" + Gets Mass of base peak default data stream (usually centroid stream, if present). + Falls back to ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan data if + centroid stream is not preferred or not present + """""" + return self._get_wrapped_object_().PreferredBasePeakMass + + @property + def preferred_base_peak_noise(self) -> float: + """""" + Gets Noise of base peak for default data stream (usually centroid stream, if + present). Falls back to zero if centroid stream is not preferred or not present + """""" + return self._get_wrapped_object_().PreferredBasePeakNoise + + @property + def preferred_base_peak_resolution(self) -> float: + """""" + Gets Resolution of base peak for default data stream (usually centroid stream, + if present). Falls back to zero if centroid stream is not preferred or not present + """""" + return self._get_wrapped_object_().PreferredBasePeakResolution + + @property + def preferred_flags(self) -> List[PeakOptions]: + """""" + Gets peak flags (such as saturated) for default data stream (usually centroid + stream, if present). Falls back to ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan + data if centroid stream is not preferred or not present + """""" + return list(self._get_wrapped_object_().PreferredFlags) + + @property + def preferred_intensities(self) -> List[float]: + """""" + Gets Intensity for default data stream (usually centroid stream, if present). + Falls back to ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan data if + centroid stream is not preferred or not present + """""" + return list(self._get_wrapped_object_().PreferredIntensities) + + @property + def preferred_masses(self) -> List[float]: + """""" + Gets the Mass for default data stream (usually centroid stream, if present). + Falls back to ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan data if + centroid stream is not preferred or not present + """""" + return list(self._get_wrapped_object_().PreferredMasses) + + @property + def preferred_noises(self) -> List[float]: + """""" + Gets Noises for default data stream (usually centroid stream, if present). Returns + an empty array if centroid stream is not preferred or not present + """""" + return list(self._get_wrapped_object_().PreferredNoises) + + @property + def preferred_baselines(self) -> List[float]: + """""" + Gets Baselines for default data stream (usually centroid stream, if present). + Returns an empty array if centroid stream is not preferred or not present + """""" + return list(self._get_wrapped_object_().PreferredBaselines) + + @property + def scans_combined(self) -> int: + """""" + Gets or sets the number of scans which were combined to create this scan. For + example: By the scan averager. This can be zero if this is a ""scan read from + a file"" + """""" + return self._get_wrapped_object_().ScansCombined + + @scans_combined.setter + def scans_combined(self, value: int): + """""" + Gets or sets the number of scans which were combined to create this scan. For + example: By the scan averager. This can be zero if this is a ""scan read from + a file"" + """""" + assert type(value) is int + self._get_wrapped_object_().ScansCombined = value + + @property + def preferred_base_peak_intensity(self) -> float: + """""" + Gets peak flags (such as saturated) for default data stream (usually centroid + stream, if present). Falls back to ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan + data if centroid stream is not preferred or not present + """""" + return self._get_wrapped_object_().PreferredBasePeakIntensity + + @property + def scan_statistics(self) -> ScanStatistics: + """""" + Gets or sets Header information for the scan + """""" + return ScanStatistics._get_wrapper_(self._get_wrapped_object_().ScanStatistics) + + @scan_statistics.setter + def scan_statistics(self, value: ScanStatistics): + """""" + Gets or sets Header information for the scan + """""" + assert type(value) is ScanStatistics + self._get_wrapped_object_().ScanStatistics = value._get_wrapped_object_() + + @property + def scan_statistics_access(self) -> ScanStatistics: + """""" + Gets Header information for the scan + """""" + return ScanStatistics._get_wrapper_(self._get_wrapped_object_().ScanStatisticsAccess) + + @property + def scan_type(self) -> str: + """""" + Gets or sets Type of scan (for filtering) + """""" + return self._get_wrapped_object_().ScanType + + @scan_type.setter + def scan_type(self, value: str): + """""" + Gets or sets Type of scan (for filtering) + """""" + assert type(value) is str + self._get_wrapped_object_().ScanType = value + + @property + def segmented_scan(self) -> SegmentedScan: + """""" + Gets or sets The data for the scan + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object_().SegmentedScan) + + @segmented_scan.setter + def segmented_scan(self, value: SegmentedScan): + """""" + Gets or sets The data for the scan + """""" + assert type(value) is SegmentedScan + self._get_wrapped_object_().SegmentedScan = value._get_wrapped_object_() + + @property + def segmented_scan_access(self) -> SegmentedScan: + """""" + Gets The data for the scan + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object_().SegmentedScanAccess) + + @property + def subtraction_pointer(self) -> Any: + """""" + Gets or sets IScanSubtract interface pointer. + + Returns: + Interface to perform subtraction + """""" + return self._get_wrapped_object_().SubtractionPointer + + @subtraction_pointer.setter + def subtraction_pointer(self, value: Any): + """""" + Gets or sets IScanSubtract interface pointer. + + Returns: + Interface to perform subtraction + """""" + self._get_wrapped_object_().SubtractionPointer = value + + @property + def scan_adder(self) -> Any: + """""" + Gets or sets IScanAdd interface. This delegates addition of FT profile scans. + + Returns: + Interface to perform addition + """""" + return self._get_wrapped_object_().ScanAdder + + @scan_adder.setter + def scan_adder(self, value: Any): + """""" + Gets or sets IScanAdd interface. This delegates addition of FT profile scans. + + Returns: + Interface to perform addition + """""" + self._get_wrapped_object_().ScanAdder = value + + @property + def preferred_resolutions(self) -> List[float]: + """""" + Gets Resolutions for default data stream (usually centroid stream, if present). + Returns an empty array if centroid stream is not preferred or not present + """""" + return self._get_wrapped_object_().PreferredResolutions + + @property + def prefer_centroids(self) -> bool: + """""" + Gets or sets a value indicating whether, when requesting ""Preferred data"", the + centroid stream will be returned. For example ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredMasses"", + ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredIntensities"". If this property + is false, or there is no centroid stream, then these methods will return the + data from ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan. For greater + efficiency, callers should cache the return of ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredMasses"". + Typically data processing, such as elemental compositions, should use these methods. + """""" + return self._get_wrapped_object_().PreferCentroids + + @prefer_centroids.setter + def prefer_centroids(self, value: bool): + """""" + Gets or sets a value indicating whether, when requesting ""Preferred data"", the + centroid stream will be returned. For example ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredMasses"", + ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredIntensities"". If this property + is false, or there is no centroid stream, then these methods will return the + data from ThermoFisher.CommonCore.Data.Business.Scan.SegmentedScan. For greater + efficiency, callers should cache the return of ""ThermoFisher.CommonCore.Data.Business.Scan.PreferredMasses"". + Typically data processing, such as elemental compositions, should use these methods. + """""" + assert type(value) is bool + self._get_wrapped_object_().PreferCentroids = value + + @property + def is_user_tolerance(self) -> bool: + """""" + Gets or sets a value indicating whether the User Tolerance value is being used. + """""" + return self._get_wrapped_object_().IsUserTolerance + + @is_user_tolerance.setter + def is_user_tolerance(self, value: bool): + """""" + Gets or sets a value indicating whether the User Tolerance value is being used. + """""" + assert type(value) is bool + self._get_wrapped_object_().IsUserTolerance = value + + @property + def tolerance_unit(self) -> ToleranceMode: + """""" + Gets or sets the Tolerance value. + """""" + return ToleranceMode(self._get_wrapped_object_().ToleranceUnit) + + @tolerance_unit.setter + def tolerance_unit(self, value: ToleranceMode): + """""" + Gets or sets the Tolerance value. + """""" + assert type(value) is ToleranceMode + self._get_wrapped_object_().ToleranceUnit = value.value + + @property + def mass_resolution(self) -> float: + """""" + Gets or sets the mass resolution for all scan arithmetic operations + """""" + return self._get_wrapped_object_().MassResolution + + @mass_resolution.setter + def mass_resolution(self, value: float): + """""" + Gets or sets the mass resolution for all scan arithmetic operations + """""" + assert type(value) is float + self._get_wrapped_object_().MassResolution = value + + @property + def centroid_scan(self) -> CentroidStream: + """""" + Gets or sets A second data stream for the scan + """""" + return CentroidStream._get_wrapper_(self._get_wrapped_object_().CentroidScan) + + @centroid_scan.setter + def centroid_scan(self, value: CentroidStream): + """""" + Gets or sets A second data stream for the scan + """""" + assert type(value) is CentroidStream + self._get_wrapped_object_().CentroidScan = value._get_wrapped_object_() + + @property + def always_merge_segments(self) -> bool: + """""" + Get or sets a value indicating whether scan + and - operators will merge data + from scans which were not scanned over a similar range. Only applicable when + scans only have a single segment. By default: Scans are considered incompatible + if: The span of the scanned mass range differs by 10% The start or end of the + scanned mass range differs by 10% If this is set as ""true"" then any mass ranges + will be merged. + """""" + return self._get_wrapped_object_().AlwaysMergeSegments + + @always_merge_segments.setter + def always_merge_segments(self, value: bool): + """""" + Get or sets a value indicating whether scan + and - operators will merge data + from scans which were not scanned over a similar range. Only applicable when + scans only have a single segment. By default: Scans are considered incompatible + if: The span of the scanned mass range differs by 10% The start or end of the + scanned mass range differs by 10% If this is set as ""true"" then any mass ranges + will be merged. + """""" + assert type(value) is bool + self._get_wrapped_object_().AlwaysMergeSegments = value + + @property + def has_centroid_stream(self) -> bool: + """""" + Gets a value indicating whether this scan has a centroid stream. + """""" + return self._get_wrapped_object_().HasCentroidStream + + @property + def centroid_stream_access(self) -> CentroidStream: + """""" + Gets A second data stream for the scan + """""" + return CentroidStream._get_wrapper_(self._get_wrapped_object_().CentroidStreamAccess) + + @property + def has_noise_table(self) -> bool: + """""" + Gets a value indicating whether this scan has a noise table. This will be true + only if the scan was constructed with the overload containing this table. Note + that this is not related to having ""noise and baseline"" values with centroid + stream data. This is a separate table, used for spectrum averaging and subtraction + of orbitrap data + """""" + return self._get_wrapped_object_().HasNoiseTable + + @staticmethod + def at_time(raw_file: RawFileAccess, time: float) -> Scan: + """""" + Create a scan object from a file and a retention time. + + Parameters: + rawFile: + File to read from + + time: + time of Scan number to read + + Returns: + The scan read, or null of the scan number if not valid + """""" + return Scan._get_wrapper_(Scan._wrapped_type.AtTime(raw_file._get_wrapped_object_(), time)) + + @staticmethod + def can_merged_scan( identical_flag: bool, current_scan: Scan, to_merge: Scan) -> bool: + """""" + test if 2 scans can be averaged or subtracted. + + Parameters: + identicalFlag: + Returned as ""true"" if all segments are the same + + currentScan: + Current scan object + + toMerge: + The scan to possibly add + + Returns: + true if scans can be merged + """""" + return Scan._wrapped_type.CanMergeScan(identical_flag, current_scan._get_wrapped_object_(), to_merge._get_wrapped_object_()) + + @staticmethod + def create_scan_reader(cache_size: int) -> CachedScanProvider: + """""" + Create an object which can be used to read scans from a file, with optional caching. + This is valuable if repeated operations (such as averaging) are expected over + the same region of data. Scans returned from each call are unique objects, even + if called repeatedly with the same scan number. + + Parameters: + cacheSize: + Number of scans cached. When set to 1 or more, this creates a FIFO, keeping track + of the most recently read scans. If a scan in the FIFO is requested again, it + is pulled from the cache. If a scan is not in the cache, then a new scan is read + from the file. If the cache is full, the oldest scan is dropped. The newly read + scan is that added to the FIFO cache. If size is set to 0, this makes a trivial + object with no overheads, that directly gets scans from the file. + + Returns: + Object to read scans from a file + """""" + return CachedScanProvider._get_wrapper_(Scan._wrapped_type.CreateScanReader(cache_size)) + + @staticmethod + def from_file(raw_file: RawFileAccess, scan_number: int) -> Scan: + """""" + Create a scan object from a file and a scan number. + + Parameters: + rawFile: + File to read from + + scanNumber: + Scan number to read + + Returns: + The scan read, or null of the scan number if not valid + """""" + assert type(scan_number) is int + return Scan._get_wrapper_(Scan._wrapped_type.FromFile(raw_file._get_wrapped_object_(), scan_number)) + + def to_centroid(current_scan: Scan) -> Scan: + """""" + Converts the segmented scan to centroid scan. Used to centroid profile data. + + Parameters: + currentScan: + The scan to centroid + + Returns: + The centroided version of the scan + """""" + return Scan._get_wrapper_(Scan._wrapped_type.ToCentroid(current_scan._get_wrapped_object_())) + + def deep_clone(self) -> Scan: + """""" + Make a deep clone of this scan. + + Returns: + An object containing all data in the input, and no shared references + """""" + return Scan._get_wrapper_(self._get_wrapped_object().DeepClone()) + + def generate_frequency_table(self) -> List[float]: + """""" + generate frequency table for this scan. This method only applied to ""FT"" format + scans which have mass to frequency calibration data. When a scan in constructed + from processing algorithms, such as averaging, a frequency to mass converter + is used to create this scan. This same converter can be used to create a frequency + table, which would be needed when writing averaged (or subtracted) data to a + raw file. + + Returns: + The frequency table. + """""" + return self._get_wrapped_object().GenerateFrequencyTable() + + def generate_noise_table(self) -> List[NoiseAndBaseline]: + """""" + Generates a ""noise and baseline table"". This table is only relevant to FT format + data. For other data, an empty list is returned. This table is intended for use + when exporting processed (averaged, subtracted) scans to a raw file. If this + scan is the result of a calculation such as ""average of subtract"" it may be constructed + using an overload which includes a noise and baseline table. If so: that tale + is returned. Otherwise, a table is generated by extracting data from the scan. + + Returns: + The nose and baseline data + """""" + return [NoiseAndBaseline._get_wrapper_(n) for n in self._get_wrapped_object().GenerateNoiseTable()] + + def slice(self, mass_ranges: List[Range], trim_mass_range: bool, expand_profiles: bool) -> Scan: + """""" + Return a slice of a scan which only contains data within the supplied mass Range + or ranges. For example: For a scan with data from m/z 200 to 700, and a single + mass range of 300 to 400: This returns a new scan containing all data with the + range 300 to 400. + + Parameters: + massRanges: + The mass ranges, where data should be retained. When multiple ranges are supplied, + all data which is in at least one range is included in the returned scan + + trimMassRange: + If this is true, then the scan will reset the scan's mass range to the bounds + of the supplied mass ranges + + expandProfiles: + This setting only applies when the scan has both profile and centroid data. If + true: When there isa centroid near the start or end of a range, and the first + or final ""above zero"" section of the profile includes that peak, then the profile + is extended, to include the points which contribute to that peak. A maximum of + 10 points may be added + + Returns: + A copy of the scan, with only the data in the supplied ranges + """""" + net_mass_ranges = [r._get_wrapped_object_() for r in mass_ranges] + return Scan._get_wrapper_(self._get_wrapped_object().Slice(net_mass_ranges, trim_mass_range, expand_profiles)) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/status_log_values.py",".py","1287","48","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.utils import to_net_list +from typing import List + + +class StatusLogValues(NetWrapperBase): + """""" + Stores one record of status log values + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.StatusLogValues + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def retention_time(self) -> float: + """""" + Gets or sets the RetentionTime for this log entry + """""" + return self._get_wrapped_object_().RetentionTime + + @retention_time.setter + def retention_time(self, value: float): + """""" + Gets or sets the RetentionTime for this log entry + """""" + assert type(value) is float + self._get_wrapped_object_().RetentionTime = value + + @property + def values(self) -> List[str]: + """""" + Gets or sets the array of status log values + """""" + return self._get_wrapped_object_().Values + + @values.setter + def values(self, value: List[str]): + """""" + Gets or sets the array of status log values + """""" + assert type(value) is list + value = to_net_list(value, str) + self._get_wrapped_object_().Values = value + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/header_item.py",".py","4900","141","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import GenericDataTypes + + +class HeaderItem(NetWrapperBase): + """""" + Defines the format of a log entry, including label (name of the field), data + type, and numeric formatting. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.HeaderItem + + def __init__(self, *args): + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + else: + label, data_type, string_length_or_precision = args[0], args[1], args[2] + assert type(label) is str + assert type(data_type) is GenericDataTypes + assert type(string_length_or_precision) is int + + if len(args) == 3: + is_scientific_notation = False + elif len(args) == 4: + is_scientific_notation = args[3] + assert type(is_scientific_notation) is bool + else: + raise ValueError('Unable to create header item.') + + self._wrapped_object = self._wrapped_type(label, data_type.value, string_length_or_precision, is_scientific_notation) + + @property + def label(self) -> str: + """""" + Gets or sets the display label for the field. For example: If this a temperature, + this label may be ""Temperature"" and the DataType may be ""GenericDataTypes.FLOAT"" + """""" + return self._get_wrapped_object_().Label + + @label.setter + def label(self, value: str): + """""" + Gets or sets the display label for the field. For example: If this a temperature, + this label may be ""Temperature"" and the DataType may be ""GenericDataTypes.FLOAT"" + """""" + assert type(value) is str + self._get_wrapped_object_().Label = value + + @property + def data_type(self) -> GenericDataTypes: + """""" + Gets or sets the data type for the field + """""" + return GenericDataTypes(self._get_wrapped_object_().DataType) + + @data_type.setter + def data_type(self, value: GenericDataTypes): + """""" + Gets or sets the data type for the field + """""" + assert type(value) is GenericDataTypes + self._get_wrapped_object_().DataType = value.value + + @property + def string_length_or_precision(self) -> int: + """""" + Gets or sets the precision, if the data type is float or double, or string length + of string fields. + """""" + return self._get_wrapped_object_().StringLengthOrPrecision + + @string_length_or_precision.setter + def string_length_or_precision(self, value: int): + """""" + Gets or sets the precision, if the data type is float or double, or string length + of string fields. + """""" + assert type(value) is int + self._get_wrapped_object_().StringLengthOrPrecision = value + + @property + def is_scientific_notation(self) -> bool: + """""" + Gets or sets a value indicating whether a number should be displayed in scientific + notation + """""" + return self._get_wrapped_object_().IsScientificNotation + + @is_scientific_notation.setter + def is_scientific_notation(self, value: bool): + """""" + Gets or sets a value indicating whether a number should be displayed in scientific + notation + """""" + assert type(value) is bool + self._get_wrapped_object_().IsScientificNotation = value + + @property + def is_numeric(self) -> bool: + """""" + Gets a value indicating whether this is considered numeric data. This is the + same test as performed for StatusLogPlottableData"". Integer types: short and + long (signed and unsigned) and floating types: float and double are defined as + numeric. + """""" + return self._get_wrapped_object_().IsNumeric + + def format_value(self, value: str) -> str: + """""" + Re-formats the specified value per the current header's settings. + + Parameters: + value: + The value, as a string. + + Returns: + The formatted value. + """""" + return self._get_wrapped_object().FormatValue(value) + + def is_variable_header(self, fields: int) -> bool: + """""" + Tests whether this is a variable header. A ""variable header"", if present as the + first field in a table of headers, defines that each record has a variable number + of valid fields. The first field in each data record will then be converted to + ""validity flags"" which determine which of the fields in a data record have valid + values. + + Parameters: + fields: + The number of fields in the header. + + Returns: + True if this specifies that ""variable length"" records are used. + """""" + return self._get_wrapped_object().IsVariableHeader(fields) + + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/label_peak.py",".py","3213","132","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import PeakOptions + + +class LabelPeak(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.LabelPeak + + def __init__(self): + super().__init__() + self._mass_options = None + + @property + def mass(self) -> float: + """""" + Gets or sets mass. + """""" + return self._get_wrapped_object_().Mass + + @mass.setter + def mass(self, value: float): + """""" + Gets or sets mass. + """""" + assert type(value) is float + self._get_wrapped_object_().Mass = value + + @property + def intensity(self) -> float: + """""" + Gets or sets intensity. + """""" + return self._get_wrapped_object_().Intensity + + @intensity.setter + def intensity(self, value: float): + """""" + Gets or sets intensity. + """""" + assert type(value) is float + self._get_wrapped_object_().Intensity = value + + @property + def resolution(self) -> float: + """""" + Gets or sets resolution. + """""" + return self._get_wrapped_object_().Resolution + + @resolution.setter + def resolution(self, value: float): + """""" + Gets or sets resolution. + """""" + assert type(value) is float + self._get_wrapped_object_().Resolution = value + + @property + def baseline(self) -> float: + """""" + Gets or sets base Line. + """""" + return self._get_wrapped_object_().Baseline + + @baseline.setter + def baseline(self, value: float): + """""" + Gets or sets base Line. + """""" + assert type(value) is float + self._get_wrapped_object_().Baseline = value + + @property + def noise(self) -> float: + """""" + Gets or sets noise. + """""" + return self._get_wrapped_object_().Noise + + @noise.setter + def noise(self, value: float): + """""" + Gets or sets noise. + """""" + assert type(value) is float + self._get_wrapped_object_().Noise = value + + @property + def charge(self) -> float: + """""" + Gets or sets charge. + """""" + return self._get_wrapped_object_().Charge + + @charge.setter + def charge(self, value: float): + """""" + Gets or sets charge. + """""" + assert type(value) is float + self._get_wrapped_object_().Charge = value + + @property + def flag(self) -> PeakOptions: + """""" + Gets or sets Peak Options Flag. + """""" + return PeakOptions(self._get_wrapped_object_().Flag) + + @flag.setter + def flag(self, value: PeakOptions): + """""" + Gets or sets Peak Options Flag. + """""" + assert type(value) is PeakOptions + self._get_wrapped_object_().Flag = value.value + + @property + def signal_to_noise(self) -> float: + """""" + Gets or sets the signal to noise. + """""" + return self._get_wrapped_object_().SignalToNoise + + @signal_to_noise.setter + def signal_to_noise(self, value: float): + """""" + Gets or sets the signal to noise. + """""" + assert type(value) is float + self._get_wrapped_object_().SignalToNoise = value +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/run_header.py",".py","5502","184","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import ToleranceUnits + + +class RunHeader(NetWrapperBase): + """""" + The run header. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.RunHeader + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def first_spectrum(self) -> int: + """""" + Gets or sets the number for the first scan in this stream (usually 1) + """""" + return self._get_wrapped_object_().FirstSpectrum + + @first_spectrum.setter + def first_spectrum(self, value: int): + """""" + Gets or sets the number for the first scan in this stream (usually 1) + """""" + assert type(value) is int + self._get_wrapped_object_().FirstSpectrum = value + + @property + def last_spectrum(self) -> int: + """""" + Gets or sets the number for the last scan in this stream + """""" + return self._get_wrapped_object_().LastSpectrum + + @last_spectrum.setter + def last_spectrum(self, value: int): + """""" + Gets or sets the number for the last scan in this stream + """""" + assert type(value) is int + self._get_wrapped_object_().LastSpectrum = value + + @property + def start_time(self) -> float: + """""" + Gets or sets the time of first scan in file + """""" + return self._get_wrapped_object_().StartTime + + @start_time.setter + def start_time(self, value: float): + """""" + Gets or sets the time of first scan in file + """""" + assert type(value) is float + self._get_wrapped_object_().StartTime = value + + @property + def end_time(self) -> float: + """""" + Gets or sets the time of last scan in file + """""" + return self._get_wrapped_object_().EndTime + + @end_time.setter + def end_time(self, value: float): + """""" + Gets or sets the time of last scan in file + """""" + assert type(value) is float + self._get_wrapped_object_().EndTime = value + + @property + def low_mass(self) -> float: + """""" + Gets or sets the lowest recorded mass in file + """""" + return self._get_wrapped_object_().LowMass + + @low_mass.setter + def low_mass(self, value: float): + """""" + Gets or sets the lowest recorded mass in file + """""" + assert type(value) is float + self._get_wrapped_object_().LowMass = value + + @property + def high_mass(self) -> float: + """""" + Gets or sets the highest recorded mass in file + """""" + return self._get_wrapped_object_().HighMass + + @high_mass.setter + def high_mass(self, value: float): + """""" + Gets or sets the highest recorded mass in file + """""" + assert type(value) is float + self._get_wrapped_object_().HighMass = value + + @property + def mass_resolution(self) -> float: + """""" + Gets or sets the mass resolution value recorded for the current instrument. The + value is returned as one half of the mass resolution. For example, a unit resolution + controller would return a value of 0.5. + """""" + return self._get_wrapped_object_().MassResolution + + @mass_resolution.setter + def mass_resolution(self, value: float): + """""" + Gets or sets the mass resolution value recorded for the current instrument. The + value is returned as one half of the mass resolution. For example, a unit resolution + controller would return a value of 0.5. + """""" + assert type(value) is float + self._get_wrapped_object_().MassResolution = value + + @property + def expected_runtime(self) -> float: + """""" + Gets or sets the expected acquisition run time for the current instrument. + """""" + return self._get_wrapped_object_().ExpectedRuntime + + @expected_runtime.setter + def expected_runtime(self, value: float): + """""" + Gets or sets the expected acquisition run time for the current instrument. + """""" + assert type(value) is float + self._get_wrapped_object_().ExpectedRuntime = value + + @property + def max_integrated_intensity(self) -> float: + """""" + Gets or sets the max integrated intensity. + """""" + return self._get_wrapped_object_().MaxIntegratedIntensity + + @max_integrated_intensity.setter + def max_integrated_intensity(self, value: float): + """""" + Gets or sets the max integrated intensity. + """""" + assert type(value) is float + self._get_wrapped_object_().MaxIntegratedIntensity = value + + @property + def max_intensity(self) -> int: + """""" + Gets or sets the max intensity. + """""" + return self._get_wrapped_object_().MaxIntensity + + @max_intensity.setter + def max_intensity(self, value: int): + """""" + Gets or sets the max intensity. + """""" + assert type(value) is int + self._get_wrapped_object_().MaxIntensity = value + + @property + def tolerance_unit(self) -> ToleranceUnits: + """""" + Gets or sets the tolerance unit. + """""" + return ToleranceUnits(self._get_wrapped_object_().ToleranceUnit) + + @tolerance_unit.setter + def tolerance_unit(self, value: ToleranceUnits): + """""" + Gets or sets the tolerance unit. + """""" + assert type(value) is ToleranceUnits + self._get_wrapped_object_().ToleranceUnit = value.value +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/sequence_file_writer_factory.py",".py","1058","31","from fisher_py.net_wrapping import ThermoFisher +from fisher_py.data.sequence_file_writer import SequenceFileWriter + + +class SequenceFileWriterFactory(object): + """""" + This static factory class provides methods to create and open existing sequence + file. + """""" + + @staticmethod + def create_sequence_file_writer(file_name: str, open_existing: bool) -> SequenceFileWriter: + """""" + Summary: + Creates the sequence file writer. + + Parameters: + fileName: + Name of the file. + + openExisting: + True open an existing sequence file with read/write privilege; false to create + a new unique sequence file + + Returns: + Sequence file writer object + """""" + assert type(file_name) is str + assert type(open_existing) is bool + net_writer = ThermoFisher.CommonCore.Data.Business.SequenceFileWriterFactory.CreateSequenceFileWriter(file_name, open_existing) + return SequenceFileWriter._get_wrapper_(net_writer)","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/sample_information.py",".py","9985","337","from __future__ import annotations +from typing import List +from fisher_py.net_wrapping import ThermoFisher +from fisher_py.data import CommonCoreDataObject +from fisher_py.data.business import SampleType, BarcodeStatusType +from fisher_py.net_wrapping.wrapped_net_array import WrappedNetArray +from fisher_py.utils import to_net_array, to_net_list + + +class SampleInformation(CommonCoreDataObject): + """""" + Encapsulates various information about sample. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.SampleInformation + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + self._user_text = None + + max_user_text_column_count = 20 + + @property + def sample_volume(self) -> float: + """""" + Gets or sets the sample volume of this sequence row. + """""" + return self._get_wrapped_object_().SampleVolume + + @sample_volume.setter + def sample_volume(self, value: float): + """""" + Gets or sets the sample volume of this sequence row. + """""" + assert type(value) is float + self._get_wrapped_object_().SampleVolume = value + + @property + def sample_type(self) -> SampleType: + """""" + Gets or sets the type of the sample. + """""" + return SampleType(self._get_wrapped_object_().SampleType) + + @sample_type.setter + def sample_type(self, value: SampleType): + """""" + Gets or sets the type of the sample. + """""" + assert type(value) is SampleType + self._get_wrapped_object_().SampleType = value.value + + @property + def processing_method_file(self) -> str: + """""" + Gets or sets the processing method filename of this sequence row. + """""" + return self._get_wrapped_object_().ProcessingMethodFile + + @processing_method_file.setter + def processing_method_file(self, value: str): + """""" + Gets or sets the processing method filename of this sequence row. + """""" + assert type(value) is str + self._get_wrapped_object_().ProcessingMethodFile = value + + @property + def path(self) -> str: + """""" + Gets or sets the path to original data. + """""" + return self._get_wrapped_object_().Path + + @path.setter + def path(self, value: str): + """""" + Gets or sets the path to original data. + """""" + assert type(value) is str + self._get_wrapped_object_().Path = value + + @property + def row_number(self) -> int: + """""" + Gets or sets the row number. + """""" + return self._get_wrapped_object_().RowNumber + + @row_number.setter + def row_number(self, value: int): + """""" + Gets or sets the row number. + """""" + assert type(value) is int + self._get_wrapped_object_().RowNumber = value + + @property + def istd_amount(self) -> float: + """""" + Gets or sets the ISTD amount of this sequence row. + """""" + return self._get_wrapped_object_().IstdAmount + + @istd_amount.setter + def istd_amount(self, value: float): + """""" + Gets or sets the ISTD amount of this sequence row. + """""" + assert type(value) is float + self._get_wrapped_object_().IstdAmount = value + + @property + def calibration_file(self) -> str: + """""" + Gets or sets the name of calibration file. + """""" + return self._get_wrapped_object_().CalibrationFile + + @calibration_file.setter + def calibration_file(self, value: str): + """""" + Gets or sets the name of calibration file. + """""" + assert type(value) is str + self._get_wrapped_object_().CalibrationFile = value + + @property + def raw_file_name(self) -> str: + """""" + Gets or sets the name of acquired file (excluding path). + """""" + return self._get_wrapped_object_().RawFileName + + @raw_file_name.setter + def raw_file_name(self, value: str): + """""" + Gets or sets the name of acquired file (excluding path). + """""" + assert type(value) is str + self._get_wrapped_object_().RawFileName = value + + @property + def instrument_method_file(self) -> str: + """""" + Gets or sets the instrument method filename of this sequence row. + """""" + return self._get_wrapped_object_().InstrumentMethodFile + + @instrument_method_file.setter + def instrument_method_file(self, value: str): + """""" + Gets or sets the instrument method filename of this sequence row. + """""" + assert type(value) is str + self._get_wrapped_object_().InstrumentMethodFile = value + + @property + def dilution_factor(self) -> float: + """""" + Gets or sets the bulk dilution factor (volume correction) of this sequence row. + """""" + return self._get_wrapped_object_().DilutionFactor + + @dilution_factor.setter + def dilution_factor(self, value: float): + """""" + Gets or sets the bulk dilution factor (volume correction) of this sequence row. + """""" + assert type(value) is float + self._get_wrapped_object_().DilutionFactor = value + + @property + def calibration_level(self) -> str: + """""" + Gets or sets a name to identify the Calibration or QC level associated with this + sample. Empty if this sample does not contain any calibration compound. + """""" + return self._get_wrapped_object_().CalibrationLevel + + @calibration_level.setter + def calibration_level(self, value: str): + """""" + Gets or sets a name to identify the Calibration or QC level associated with this + sample. Empty if this sample does not contain any calibration compound. + """""" + assert type(value) is str + self._get_wrapped_object_().CalibrationLevel = value + + @property + def barcode_status(self) -> BarcodeStatusType: + """""" + Gets or sets the bar code status. + """""" + return BarcodeStatusType(self._get_wrapped_object_().BarcodeStatus) + + @barcode_status.setter + def barcode_status(self, value: BarcodeStatusType): + """""" + Gets or sets the bar code status. + """""" + assert type(value) is BarcodeStatusType + self._get_wrapped_object_().BarcodeStatus = value.value + + @property + def barcode(self) -> str: + """""" + Gets or sets bar code from scanner (if attached). + """""" + return self._get_wrapped_object_().Barcode + + @barcode.setter + def barcode(self, value: str): + """""" + Gets or sets bar code from scanner (if attached). + """""" + assert type(value) is str + self._get_wrapped_object_().Barcode = value + + @property + def injection_volume(self) -> float: + """""" + Gets or sets the amount of sample injected. + """""" + return self._get_wrapped_object_().InjectionVolume + + @injection_volume.setter + def injection_volume(self, value: float): + """""" + Gets or sets the amount of sample injected. + """""" + assert type(value) is float + self._get_wrapped_object_().InjectionVolume = value + + @property + def vial(self) -> str: + """""" + Gets or sets the vial or well form auto sampler. + """""" + return self._get_wrapped_object_().Vial + + @vial.setter + def vial(self, value: str): + """""" + Gets or sets the vial or well form auto sampler. + """""" + assert type(value) is str + self._get_wrapped_object_().Vial = value + + @property + def sample_name(self) -> str: + """""" + Gets or sets the description of sample. + """""" + return self._get_wrapped_object_().SampleName + + @sample_name.setter + def sample_name(self, value: str): + """""" + Gets or sets the description of sample. + """""" + assert type(value) is str + self._get_wrapped_object_().SampleName = value + + @property + def sample_id(self) -> str: + """""" + Gets or sets the Code to identify sample. + """""" + return self._get_wrapped_object_().SampleId + + @sample_id.setter + def sample_id(self, value: str): + """""" + Gets or sets the Code to identify sample. + """""" + assert type(value) is str + self._get_wrapped_object_().SampleId = value + + @property + def comment(self) -> str: + """""" + Gets or sets the comment about sample (from user). + """""" + return self._get_wrapped_object_().Comment + + @comment.setter + def comment(self, value: str): + """""" + Gets or sets the comment about sample (from user). + """""" + assert type(value) is str + self._get_wrapped_object_().Comment = value + + @property + def sample_weight(self) -> float: + """""" + Gets or sets the sample weight of this sequence row. + """""" + return self._get_wrapped_object_().SampleWeight + + @sample_weight.setter + def sample_weight(self, value: float): + """""" + Gets or sets the sample weight of this sequence row. + """""" + assert type(value) is float + self._get_wrapped_object_().SampleWeight = value + + @property + def user_text(self) -> List[str]: + """""" + Gets or sets the collection of user text. + """""" + if self._user_text is None: + self._user_text = WrappedNetArray[str](self._get_wrapped_object_().UserText) + return self._user_text + + @user_text.setter + def user_text(self, value: List[str]): + """""" + Gets or sets the collection of user text. + """""" + assert type(value) is list + value = to_net_array(value, str) + self._get_wrapped_object_().UserText = value + + def deep_copy(self) -> SampleInformation: + """""" + Create a deep copy of the current object. + + Returns: + A deep copy of the current object. + """""" + return SampleInformation._get_wrapper_(self._get_wrapped_object().DeepCopy()) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/noise_and_baseline.py",".py","1493","61","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.utils import is_number + + +class NoiseAndBaseline(NetWrapperBase): + """""" + Defines noise and baseline at a given mass (Part of support for reading orbitrap data) + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.NoiseAndBaseline + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def mass(self) -> float: + """""" + Gets or sets the mass. + """""" + return self._get_wrapped_object_().Mass + + @mass.setter + def mass(self, value: float): + """""" + Gets or sets the mass. + """""" + assert is_number(value) + self._get_wrapped_object_().Mass = float(value) + + @property + def noise(self) -> float: + """""" + Gets or sets the noise. + """""" + return self._get_wrapped_object_().Noise + + @noise.setter + def noise(self, value: float): + """""" + Gets or sets the noise. + """""" + assert is_number(value) + self._get_wrapped_object_().Noise = float(value) + + @property + def baseline(self) -> float: + """""" + Gets or sets the baseline. + """""" + return self._get_wrapped_object_().Baseline + + @baseline.setter + def baseline(self, value: float): + """""" + Gets or sets the baseline. + """""" + assert is_number(value) + self._get_wrapped_object_().Baseline = float(value) + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/cached_scan_provider.py",".py","1460","48","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from fisher_py.raw_file_reader import RawFileAccess + from fisher_py.data.business import Scan + + +class CachedScanProvider(NetWrapperBase): + + def __init__(self): + super().__init__() + + def get_scan_at_time(self, raw_data: RawFileAccess, time: float) -> Scan: + """""" + Create a scan object from a file and a retention time. + + Parameters: + rawData: + File to read from + + time: + time of Scan number to read + + Returns: + The scan read, or null if no scan was read + """""" + from fisher_py.data.business import Scan + return Scan._get_wrapper_(self._get_wrapped_object().GetScanAtTime(raw_data._get_wrapped_object_(), time)) + + def get_scan_from_scan_number(self, raw_data: RawFileAccess, scan_number: int) -> Scan: + """""" + Create a scan object from a file and a scan number. + + Parameters: + rawData: + File to read from + + scanNumber: + Scan number to read + + Returns: + The scan read, or null of the scan number if not valid + """""" + from fisher_py.data.business import Scan + return Scan._get_wrapper_(self._get_wrapped_object().GetScanFromScanNumber(raw_data._get_wrapped_object_(), scan_number)) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/instrument_selection.py",".py","978","31","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import Device + + +class InstrumentSelection(NetWrapperBase): + """""" + Defines which instrument is selected in a file. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.InstrumentSelection + + def __init__(self, instrument_index: int, device_type: Device): + super().__init__() + assert type(instrument_index) is int + assert type(device_type) is Device + self._wrapped_object = self._wrapped_type(instrument_index, device_type.value) + + @property + def instrument_index(self) -> int: + """""" + Gets the Stream number (instance of this instrument type). Stream numbers start + from 1 + """""" + return self._get_wrapped_object_().InstrumentIndex + + @property + def device_type(self) -> Device: + """""" + Gets the Category of instrument + """""" + return Device(self._get_wrapped_object_().DeviceType)","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/simple_scan.py",".py","664","26","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from typing import List + + +class SimpleScan(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.SimpleScan + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def masses(self) -> List[float]: + """""" + Gets the list of masses of each centroid + """""" + return self._get_wrapped_object_().Masses + + @property + def intensities(self) -> List[float]: + """""" + Gets the list of Intensities for each centroid + """""" + return self._get_wrapped_object_().Intensities +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/tolerance_mode.py",".py","399","14","import enum + +class ToleranceMode(enum.Enum): + """""" + Specifies units for measuring mass tolerance. + Tolerance is used to determine if a results should be kept, in formula search. + If the exact mass of a formula is not within tolerance of a measured mass from + an instrument, then the formula is not considered a valid result. + """""" + none = 0, + Amu = 1, + Mmu = 2, + Ppm = 3 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/bracket_type.py",".py","262","14","import enum + + +class BracketType(enum.Enum): + """""" + Specifies a sequence bracket type. This determines which groups of samples use + the same calibration curve. + """""" + Unspecified = 0 + Overlapped = 1 + none = 2 + NonOverlapped = 3 + Open = 4 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/trace_type.py",".py","1542","57","import enum + + +class TraceType(enum.Enum): + """""" + Enumeration of trace types, for chromatograms. Note: legacy C++ file reader does + not support analog trace numbers above ""4"" or UV above ""channel D"". Traces are + organized in blocks of 10 For example: StartAnalogChromatogramTraces=10 (not + a valid trace type, just a limit) Analog1 to Analog8 = 11 to 18 EndAnalogChromatogramTraces + =19 (not a valid trace type, just a limit) Next block: StartPDAChromatogramTraces + = 20 Etc. + """""" + StartMSChromatogramTraces = -1 + MassRange = 0 + TIC = 1 + BasePeak = 2 + Fragment = 3 + EndMSChromatogramTraces = 4 + StartAnalogChromatogramTraces = 10 + Analog1 = 11 + Analog2 = 12 + Analog3 = 13 + Analog4 = 14 + Analog5 = 15 + Analog6 = 16 + Analog7 = 17 + Analog8 = 18 + EndAnalogChromatogramTraces = 19 + StartPDAChromatogramTraces = 20 + WavelengthRange = 21 + TotalAbsorbance = 22 + SpectrumMax = 23 + EndPDAChromatogramTraces = 24 + StartUVChromatogramTraces = 30 + ChannelA = 31 + ChannelB = 32 + ChannelC = 33 + ChannelD = 34 + ChannelE = 35 + ChannelF = 36 + ChannelG = 37 + ChannelH = 38 + EndUVChromatogramTraces = 39 + StartPCA2DChromatogramTraces = 40 + A2DChannel1 = 41 + A2DChannel2 = 42 + A2DChannel3 = 43 + ChromatogramA2DChannel3 = 43 + A2DChannel4 = 44 + ChromatogramA2DChannel4 = 44 + A2DChannel5 = 45 + A2DChannel6 = 46 + A2DChannel7 = 47 + A2DChannel8 = 48 + EndPCA2DChromatogramTraces = 49 + EndAllChromatogramTraces = 50 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/instrument_data.py",".py","5929","207","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import DataUnits +from fisher_py.utils import to_net_list +from typing import List + + +class InstrumentData(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.InstrumentData + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def name(self) -> str: + """""" + Gets or sets the name of the instrument + """""" + return self._get_wrapped_object_().Name + + @name.setter + def name(self, value: str): + """""" + Gets or sets the name of the instrument + """""" + assert type(value) is str + self._get_wrapped_object_().Name = value + + @property + def model(self) -> str: + """""" + Gets or sets the model of instrument + """""" + return self._get_wrapped_object_().Model + + @model.setter + def model(self, value: str): + """""" + Gets or sets the model of instrument + """""" + assert type(value) is str + self._get_wrapped_object_().Model = value + + @property + def serial_number(self) -> str: + """""" + Gets or sets the serial number of instrument + """""" + return self._get_wrapped_object_().SerialNumber + + @serial_number.setter + def serial_number(self, value: str): + """""" + Gets or sets the serial number of instrument + """""" + assert type(value) is str + self._get_wrapped_object_().SerialNumber = value + + @property + def software_version(self) -> str: + """""" + Gets or sets the software version of instrument + """""" + return self._get_wrapped_object_().SoftwareVersion + + @software_version.setter + def software_version(self, value: str): + """""" + Gets or sets the software version of instrument + """""" + assert type(value) is str + self._get_wrapped_object_().SoftwareVersion = value + + @property + def hardware_version(self) -> str: + """""" + Gets or sets the hardware version of instrument + """""" + return self._get_wrapped_object_().HardwareVersion + + @hardware_version.setter + def hardware_version(self, value: str): + """""" + Gets or sets the hardware version of instrument + """""" + assert type(value) is str + self._get_wrapped_object_().HardwareVersion = value + + @property + def channel_labels(self) -> List[str]: + """""" + Gets or sets the Names for the channels, for UV or analog data: + """""" + return self._get_wrapped_object_().ChannelLabels + + @channel_labels.setter + def channel_labels(self, value: List[str]): + """""" + Gets or sets the Names for the channels, for UV or analog data: + """""" + assert type(value) is list + value = to_net_list(value, str) + self._get_wrapped_object_().ChannelLabels = value + + @property + def units(self) -> DataUnits: + """""" + Gets or sets the units of the Signal, for UV or analog + """""" + return DataUnits(self._get_wrapped_object_().Units) + + @units.setter + def units(self, value: DataUnits): + """""" + Gets or sets the units of the Signal, for UV or analog + """""" + assert type(value) is DataUnits + self._get_wrapped_object_().Units = value.value + + @property + def flags(self) -> str: + """""" + Gets or sets additional information about this instrument. + """""" + return self._get_wrapped_object_().Flags + + @flags.setter + def flags(self, value: str): + """""" + Gets or sets additional information about this instrument. + """""" + assert type(value) is str + self._get_wrapped_object_().Flags = value + + @property + def axis_label_x(self) -> str: + """""" + Gets or sets Device suggested label of X axis + """""" + return self._get_wrapped_object_().AxisLabelX + + @axis_label_x.setter + def axis_label_x(self, value: str): + """""" + Gets or sets Device suggested label of X axis + """""" + assert type(value) is str + self._get_wrapped_object_().AxisLabelX = value + + @property + def axis_label_y(self) -> str: + """""" + Gets or sets Device suggested label of Y axis (name for units of data, such as + ""�C"") + """""" + return self._get_wrapped_object_().AxisLabelY + + @axis_label_y.setter + def axis_label_y(self, value: str): + """""" + Gets or sets Device suggested label of Y axis + """""" + assert type(value) is str + self._get_wrapped_object_().AxisLabelY = value + + @property + def is_valid(self) -> bool: + """""" + Gets or sets a value indicating whether the instrument is valid. + """""" + return self._get_wrapped_object_().IsValid + + @is_valid.setter + def is_valid(self, value: bool): + """""" + Gets or sets a value indicating whether the instrument is valid. + """""" + assert type(value) is bool + self._get_wrapped_object_().IsValid = value + + @property + def has_accurate_mass_precursors(self) -> bool: + """""" + Gets a value indicating whether this file has accurate mass precursors + """""" + return self._get_wrapped_object_().HasAccurateMassPrecursors + + def clone(self) -> object: + """""" + Creates a new object that is a copy of the current instance. + + Returns: + A new object that is a copy of this instance. + """""" + return self._get_wrapped_object().Clone() + + def is_tsq_quantum_file(self) -> bool: + """""" + Test if this is a TSQ quantum series file. Such files may have more accurate + precursor mass selection. + + Returns: + True if this is a raw file from a TSQ Quantum + """""" + return self._get_wrapped_object().IsTsqQuantumFile() +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/data_units.py",".py","263","15","import enum + + +class DataUnits(enum.Enum): + """""" + Units of data from a UV or analog devices (if known). + """""" + none = 0 + AbsorbanceUnits = 1 + MilliAbsorbanceUnits = 2 + MicroAbsorbanceUnits = 3 + Volts = 4 + MilliVolts = 5 + MicroVolts = 6 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/__init__.py",".py","1977","31","from fisher_py.data.business.sample_type import SampleType +from fisher_py.data.business.bracket_type import BracketType +from fisher_py.data.business.barcode_status_type import BarcodeStatusType +from fisher_py.data.business.spectrum_packet_type import SpectrumPacketType +from fisher_py.data.business.tolerance_mode import ToleranceMode +from fisher_py.data.business.trace_type import TraceType +from fisher_py.data.business.data_units import DataUnits +from fisher_py.data.business.generic_data_types import GenericDataTypes +from fisher_py.data.business.tune_data_values import TuneDataValues +from fisher_py.data.business.status_log_values import StatusLogValues +from fisher_py.data.business.header_item import HeaderItem +from fisher_py.data.business.log_entry import LogEntry +from fisher_py.data.business.instrument_data import InstrumentData +from fisher_py.data.business.mass_options import MassOptions +from fisher_py.data.business.range import Range +from fisher_py.data.business.chromatogram_trace_settings import ChromatogramTraceSettings +from fisher_py.data.business.instrument_selection import InstrumentSelection +from fisher_py.data.business.noise_and_baseline import NoiseAndBaseline +from fisher_py.data.business.mass_to_frequency_converter import MassToFrequencyConverter +from fisher_py.data.business.simple_scan import SimpleScan +from fisher_py.data.business.scan_statistics import ScanStatistics +from fisher_py.data.business.label_peak import LabelPeak +from fisher_py.data.business.run_header import RunHeader +from fisher_py.data.business.sample_information import SampleInformation +from fisher_py.data.business.cached_scan_provider import CachedScanProvider +from fisher_py.data.business.segmented_scan import SegmentedScan +from fisher_py.data.business.centroid_stream import CentroidStream +from fisher_py.data.business.scan import Scan +from fisher_py.data.business.reaction import Reaction +from fisher_py.data.business.chromatogram_signal_cls import ChromatogramSignal +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/segmented_scan.py",".py","10979","329","from __future__ import annotations +from typing import List +from fisher_py.utils import is_number, to_net_list +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import Range, MassOptions, SimpleScan +from fisher_py.data import PeakOptions + + +class SegmentedScan(NetWrapperBase): + """""" + Defines a scan with mass range segments. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.SegmentedScan + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def flags(self) -> List[PeakOptions]: + """""" + Gets or sets flags, such as ""saturated"" for each peak. + """""" + return [PeakOptions(v) for v in self._get_wrapped_object_().Flags] + + @flags.setter + def flags(self, value: List[PeakOptions]): + """""" + Gets or sets flags, such as ""saturated"" for each peak. + """""" + assert type(value) is list + value = to_net_list(value, int) + self._get_wrapped_object_().Flags = [v.value for v in value] + + @property + def intensities(self) -> List[float]: + """""" + Gets or sets the Intensity (or absorbance) values for each point in the scan + """""" + return self._get_wrapped_object_().Intensities + + @intensities.setter + def intensities(self, value: List[float]): + """""" + Gets or sets the Intensity (or absorbance) values for each point in the scan + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Intensities = value + + @property + def positions(self) -> List[float]: + """""" + Gets or sets the positions (mass or wavelength) for each point in the scan + """""" + return self._get_wrapped_object_().Positions + + @positions.setter + def positions(self, value: List[float]): + """""" + Gets or sets the positions (mass or wavelength) for each point in the scan + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Positions = value + + @property + def segment_lengths(self) -> List[int]: + """""" + Gets SegmentLengths. + """""" + return self._get_wrapped_object_().SegmentLengths + + @property + def segment_sizes(self) -> List[int]: + """""" + Gets or sets the number of data points in each segment + """""" + return self._get_wrapped_object_().SegmentSizes + + @segment_sizes.setter + def segment_sizes(self, value: List[int]): + """""" + Gets or sets the number of data points in each segment + """""" + assert type(value) is list + value = to_net_list(value, int) + self._get_wrapped_object_().SegmentSizes = value + + @property + def segment_count(self) -> int: + """""" + Gets or sets The number of segments + """""" + return self._get_wrapped_object_().SegmentCount + + @segment_count.setter + def segment_count(self, value: int): + """""" + Gets or sets The number of segments + """""" + assert type(value) is int + value = to_net_list(value, int) + self._get_wrapped_object_().SegmentCount = value + + @property + def ranges(self) -> List[Range]: + """""" + Gets or sets the Mass ranges for each scan segment + """""" + return [Range._get_wrapper_(r) for r in self._get_wrapped_object_().Ranges] + + @ranges.setter + def ranges(self, value: List[Range]): + """""" + Gets or sets the Mass ranges for each scan segment + """""" + assert type(value) is list + value = to_net_list([i._get_wrapped_object_() for i in value], Range._wrapped_type) + self._get_wrapped_object_().Ranges = value + + @property + def mass_ranges(self) -> List[Range]: + """""" + Gets the Mass ranges for each scan segment + """""" + return [Range._get_wrapper_(r) for r in self._get_wrapped_object_().MassRanges] + + @property + def position_count(self) -> int: + """""" + Gets or sets the The size of the position and intensity arrays. The number of + peaks in the scan (total for all segments) + """""" + return self._get_wrapped_object_().PositionCount + + @position_count.setter + def position_count(self, value: int): + """""" + Gets or sets the The size of the position and intensity arrays. The number of + peaks in the scan (total for all segments) + """""" + assert type(value) is int + value = to_net_list(value, int) + self._get_wrapped_object_().PositionCount = value + + @property + def scan_number(self) -> int: + """""" + Gets or sets the he number of this scan. + """""" + return self._get_wrapped_object_().ScanNumber + + @scan_number.setter + def scan_number(self, value: int): + """""" + Gets or sets the he number of this scan. + """""" + assert type(value) is int + value = to_net_list(value, int) + self._get_wrapped_object_().ScanNumber = value + + def from_mass_and_intensities(self, masses: List[float], intensities: List[float]) -> SegmentedScan: + """""" + Create a scan from simple X,Y data. This method creates a scan with one segment. + For efficiency, the references to the mass and intensity data are maintained + within the constructed object. If this is not desired, clone the mass and intensity + arrays on calling this constructor. Masses are assumed to be in ascending order. + + Parameters: + masses: + Mass data for the scan + + intensities: + Intensity data for the scan + + Returns: + A scan with one segment + + Exceptions: + T:System.ArgumentNullException: + masses is null. + + T:System.ArgumentNullException: + intensities is null. + + T:System.ArgumentException: + Intensities must have same length as masses + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object().FromMassesAndIntensities(masses, intensities)) + + def base_intensity(self, ranges: List[Range], tolerance_options: MassOptions) -> float: + """""" + Return the largest intensity (base value) in the ranges supplied + + Parameters: + ranges: + Ranges of positions (masses, wavelengths) + + toleranceOptions: + If the ranges have equal mass values, then toleranceOptions are used to determine + a band subtracted from low and added to high to search for matching masses + + Returns: + Largest intensity in all ranges + """""" + assert type(ranges) is list + assert type(tolerance_options) is MassOptions + net_ranges = to_net_list([r._get_wrapped_object() for r in ranges], Range._wrapped_type) + return self._get_wrapped_object().BaseIntensity(net_ranges, tolerance_options._get_wrapped_object_()) + + def base_intensity(self, ranges: List[Range], tolerance: float) -> float: + """""" + Return the largest intensity (base value) in the ranges supplies + + Parameters: + ranges: + Ranges of positions + + tolerance: + If the ranges have equal mass values, then tolerance is subtracted from low and + added to high to search for matching masses + + Returns: + The largest intensity in all ranges + """""" + assert type(ranges) is list + assert is_number(tolerance) + net_ranges = to_net_list([r._get_wrapped_object() for r in ranges], Range._wrapped_type) + return self._get_wrapped_object().BaseIntensity(net_ranges, float(tolerance)) + + def clone(self) -> SegmentedScan: + """""" + Creates a new object that is a copy of the current instance. + + Returns: + A new object that is a copy of this instance. + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object().Clone()) + + def deep_clone(self) -> SegmentedScan: + """""" + Make a deep clone of this object. + + Returns: + An object containing all data in this, and no shared references + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object().DeepClone()) + + def index_of_segment_start(self, segment: int) -> int: + """""" + Find the index of the first packet in a segment + + Parameters: + segment: + segment number (starting from 0) + + Returns: + the index of the first packet in a segment + """""" + return self._get_wrapped_object().IndexOfSegmentStart(segment) + + def sum_intensities(self, ranges: List[Range], tolerance_options: MassOptions) -> float: + """""" + Sum all masses within the ranges + + Parameters: + ranges: + List of ranges to sum + + toleranceOptions: + If the ranges have equal mass values, then toleranceOptions are used to determine + a band subtracted from low and added to high to search for matching masses + + Returns: + Sum of intensities in all ranges + """""" + assert type(ranges) is list + assert type(tolerance_options) is MassOptions + net_ranges = to_net_list([r._get_wrapped_object() for r in ranges], Range._wrapped_type) + return self._get_wrapped_object().SumIntensities(net_ranges, tolerance_options._get_wrapped_object_()) + + def sum_intensities(self, ranges: List[Range], tolerance: float) -> float: + """""" + Sum all masses within the ranges + + Parameters: + ranges: + List of ranges to sum + + tolerance: + If the ranges have equal mass values, then tolerance is subtracted from low and + added to high to search for matching masses + + Returns: + Sum of intensities in all ranges + """""" + return self._get_wrapped_object().SumIntensities(ranges, tolerance) + + def to_simple_scan(self) -> SimpleScan: + """""" + Convert to simple scan. This permits calling code to free up references to unused + parts of the scan data. + + Returns: + The ThermoFisher.CommonCore.Data.Interfaces.ISimpleScanAccess. + """""" + return SimpleScan._get_wrapper_(self._get_wrapped_object().ToSimpleScan()) + + def try_validate(self) -> bool: + """""" + Test if this is a valid object (all streams are not null. All data has same length) + + Returns: + True if valid. + """""" + return self._get_wrapped_object().TryValidate() + + def validate(self): + """""" + Test if this is a valid object (all streams are not null. All data has same length) + + Exceptions: + T:System.ArgumentException: + is thrown if this instance does not contain valid data. + """""" + self._get_wrapped_object().Validate() +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/centroid_stream.py",".py","14283","420","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import PeakOptions +from fisher_py.data.business import Range, LabelPeak, MassOptions, SimpleScan, SegmentedScan, ScanStatistics +from fisher_py.utils import to_net_list +from typing import List, TYPE_CHECKING + +if TYPE_CHECKING: + from fisher_py.data.business import Scan + + +class CentroidStream(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.CentroidStream + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def noises(self) -> List[float]: + """""" + Gets or sets the list of noise level near peak + """""" + return list(self._get_wrapped_object_().Noises) + + @noises.setter + def noises(self, value: List[float]): + """""" + Gets or sets the list of noise level near peak + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Noises = value + + @property + def masses(self) -> List[float]: + """""" + Gets or sets the list of masses of each centroid + """""" + return list(self._get_wrapped_object_().Masses) + + @masses.setter + def masses(self, value: List[float]): + """""" + Gets or sets the list of masses of each centroid + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Masses = value + + @property + def length(self) -> int: + """""" + Gets or sets the number of centroids + """""" + return self._get_wrapped_object_().Length + + @length.setter + def length(self, value: int): + """""" + Gets or sets the number of centroids + """""" + assert type(value) is int + self._get_wrapped_object_().Length = value + + @property + def intensities(self) -> List[float]: + """""" + Gets or sets the list of Intensities for each centroid + """""" + return list(self._get_wrapped_object_().Intensities) + + @intensities.setter + def intensities(self, value: List[float]): + """""" + Gets or sets the list of Intensities for each centroid + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Intensities = value + + @property + def flags(self) -> List[PeakOptions]: + """""" + Gets or sets the flags for the peaks (such as reference) + """""" + return [PeakOptions(f) for f in self._get_wrapped_object_().Flags] + + @flags.setter + def flags(self, value: List[PeakOptions]): + """""" + Gets or sets the flags for the peaks (such as reference) + """""" + assert type(value) is list + value = to_net_list([v.value for v in value], int) + self._get_wrapped_object_().Flags = value + + @property + def coefficients_count(self) -> int: + """""" + Gets or sets the coefficients count. + """""" + return self._get_wrapped_object_().CoefficientsCount + + @coefficients_count.setter + def coefficients_count(self, value: int): + """""" + Gets or sets the coefficients count. + """""" + assert type(value) is int + self._get_wrapped_object_().CoefficientsCount = value + + @property + def coefficients(self) -> List[float]: + """""" + Gets or sets the calibration Coefficients + """""" + return list(self._get_wrapped_object_().Coefficients) + + @coefficients.setter + def coefficients(self, value: List[float]): + """""" + Gets or sets the calibration Coefficients + """""" + assert type(value) is list + self._get_wrapped_object_().Coefficients = value + + @property + def charges(self) -> List[float]: + """""" + Gets or sets the list of charge calculated for peak + """""" + return list(self._get_wrapped_object_().Charges) + + @charges.setter + def charges(self, value: List[float]): + """""" + Gets or sets the list of charge calculated for peak + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Charges = value + + @property + def base_peak_resolution(self) -> float: + """""" + Gets the resolution of most intense peak + """""" + return self._get_wrapped_object_().BasePeakResolution + + @property + def base_peak_noise(self) -> float: + """""" + Gets the noise of most intense peak + """""" + return self._get_wrapped_object_().BasePeakNoise + + @property + def base_peak_mass(self) -> float: + """""" + Gets the mass of most intense peak + """""" + return self._get_wrapped_object_().BasePeakMass + + @property + def base_peak_intensity(self) -> float: + """""" + Gets the intensity of most intense peak + """""" + return self._get_wrapped_object_().BasePeakIntensity + + @property + def baselines(self) -> List[float]: + """""" + Gets or sets the list of baseline at each peak + """""" + return list(self._get_wrapped_object_().Baselines) + + @baselines.setter + def baselines(self, value: List[float]): + """""" + Gets or sets the list of baseline at each peak + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Baselines = value + + @property + def resolutions(self) -> List[float]: + """""" + Gets or sets resolution of each peak + """""" + return list(self._get_wrapped_object_().Resolutions) + + @resolutions.setter + def resolutions(self, value: List[float]): + """""" + Gets or sets resolution of each peak + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().Resolutions = value + + @property + def scan_number(self) -> int: + """""" + Gets or sets the scan Number + """""" + return self._get_wrapped_object_().ScanNumber + + @scan_number.setter + def scan_number(self, value: int): + """""" + Gets or sets the scan Number + """""" + assert type(value) is int + self._get_wrapped_object_().ScanNumber = value + + def base_intensity(self, ranges: List[Range], tolerance_options: MassOptions) -> float: + """""" + Return the largest intensity (base value) in the ranges supplies + + Parameters: + ranges: + Ranges of masses + + toleranceOptions: + If the ranges have equal mass values, then toleranceOptions are used to determine + a band subtracted from low and added to high to search for matching masses + + Returns: + Largest intensity in all ranges + """""" + net_ranges = [v.value for v in ranges] + return self._get_wrapped_object().BaseIntensity(net_ranges, tolerance_options._get_wrapped_object_()) + + def clear(self): + """""" + Clears all the data. + """""" + self._get_wrapped_object().Clear() + + def clone(self) -> object: + """""" + Creates a new object that is a copy of the current instance. + + Returns: + A new object that is a copy of this instance. + """""" + return self._get_wrapped_object().Clone() + + def deep_clone(self) -> CentroidStream: + """""" + Make a deep clone of this object. + + Returns: + An object containing all data in this, and no shared references + """""" + return CentroidStream._get_wrapper_(self._get_wrapped_object().DeepClone()) + + def get_centroids(self) -> List[LabelPeak]: + """""" + Get the list centroids. + + Returns: + The centroids in the scan + """""" + return [LabelPeak._get_wrapper_(c) for c in self._get_wrapped_object().GetCentroids()] + + def get_label_peak(self, index: int) -> LabelPeak: + """""" + Convert the data for a given peak in this stream into a LabelPeak + + Parameters: + index: + The index of the peak to convert. + + Returns: + Extracted data for the selected peak + """""" + return LabelPeak._get_wrapper_(self._get_wrapped_object().GetLabelPeak(index)) + + def get_label_peaks(self) -> List[LabelPeak]: + """""" + Convert the data into LabelPeak objects + + Returns: + """""" + return [LabelPeak._get_wrapper_(p) for p in self._get_wrapped_object().GetLabelPeaks()] + + def refresh_base_details(self): + """""" + Forces re-computation of Base peaks , intensities. + """""" + self._get_wrapped_object().RefreshBaseDetails() + + def set_label_peaks(self, label_peaks: List[LabelPeak]) -> bool: + """""" + Convert data into this object from an array of LabelPeaks + + Parameters: + labelPeaks: + + Returns: + true on success. False if the labels peaks are null or empty + """""" + return self._get_wrapped_object().SetLabelPeaks([p._wrapped_object for p in label_peaks]) + + def sum_intensities(self, ranges: List[Range], tolerance_options: MassOptions) -> float: + """""" + Sum all masses within the ranges + + Parameters: + ranges: + List of ranges to sum + + toleranceOptions: + If the ranges have equal mass values, then toleranceOptions are used to determine + a band subtracted from low and added to high to search for matching masses + + Returns: + Sum of intensities in all ranges + """""" + net_ranges = to_net_list([v.value for v in ranges], Range._wrapped_type) + return self._get_wrapped_object().SumIntensities(net_ranges, tolerance_options._get_wrapped_object_()) + + def sum_masses(self, ranges: List[Range], tolerance: float) -> float: + """""" + Sum all masses within the ranges + + Parameters: + ranges: + List of ranges to sum + + tolerance: + If the ranges have equal mass values, then tolerance is subtracted from low and + added to high to search for matching masses + + Returns: + Sum of intensities in all ranges + """""" + net_ranges = to_net_list([v.value for v in ranges], Range._wrapped_type) + return self._get_wrapped_object().SumMasses(net_ranges, tolerance) + + def to_scan(self, original_scan_stats: ScanStatistics) -> Scan: + """""" + Convert to Scan. This feature is intended for use where an application or algorithm + needs data in ""Scan"" format, with centroid information in the ""SegmentedScan"" + property of the Scan. (such as typical centroid data from ITMS), but the data + in this scan came from an FTMS detector, which would have the profile data in + ""SegmentedScan"" and the centroid data in this object. The data is first converted + to SegmentedScan format (using ToSegmentedScan) then a new Scan is made containing + that data (with no data in ""CentroidStream). Data from this object is duplicated + (deep copy), such that changing values in the returned object will not affect + data in this object. This initializes the returned scan's ""ScanStatistics"" based + on the returned mass and intensity data. If the (optional) originalScanStats + parameter is included, information from that is used to initialize RT, scan number + and other fields which cannot be calculated from this data. The only values updated + in the scan statistics are ""BasePeakMass"" and ""BasePeakIntenity"". All other values + are either as copied from the supplied parameter, or defaults. Application should + set any other values needed in the Scan, such as ""ScansCombined, ToleranceUnit, + MassResolution"", which cannot be determined from the supplied parameters. + + Parameters: + originalScanStats: + If this is supplied, the scan statistics are initialized as a deep clone of the + supplied object (so that RT etc. get preserved) then the values of BasePeakMass + and BasePeakIntensity are updated from this object + + Returns: + The ThermoFisher.CommonCore.Data.Business.SegmentedScan. + """""" + from fisher_py.data.business import Scan + return Scan._get_wrapper_(self._get_wrapped_object().ToScan(original_scan_stats._get_wrapped_object_())) + + def to_segmented_scan(self) -> SegmentedScan: + """""" + Convert to segmented scan. This feature is intended for use where an application + or algorithm in ""SegmentedScan"" format, such as typical centroid data from ITMS, + but the data in this scan came from an FTMS detector, which would have the profile + data in ""SegmentedScan"" and the centroid data in this object. Data from this + object is duplicated (deep copy), such that changing values in the returned object + will not affect data in this object. + + Returns: + The ThermoFisher.CommonCore.Data.Business.SegmentedScan. + """""" + return SegmentedScan._get_wrapper_(self._get_wrapped_object().ToSegmentedScan()) + + def to_simple_scan(self) -> SimpleScan: + """""" + there can be an advantage in doing this conversion, as when this object goes + out of scope the converted object only holds the mass and intensity refs, and + will need less memory. + + Returns: + The ThermoFisher.CommonCore.Data.Business.SimpleScan. + """""" + return SimpleScan._get_wrapper_(self._get_wrapped_object().ToSimpleScan()) + + def try_validate(self) -> bool: + """""" + Test if this is a valid object (all streams are not null. All data has same length) + + Returns: + true if the object has valid data in it. + """""" + return self._get_wrapped_object().TryValidate() + + def validate(self): + """""" + Test if this is a valid object (all streams are not null. All data has same length) + + Exceptions: + T:System.ArgumentException: + is thrown if this instance does not contain valid data. + """""" + self._get_wrapped_object().Validate() +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/reaction.py",".py","3158","92","from fisher_py.net_wrapping import NetWrapperBase +from fisher_py.data.filter_enums import ActivationType + + +class Reaction(NetWrapperBase): + """""" + The Reaction interface. Defines a reaction for fragmenting an ion (an MS/MS stage). + """""" + + def __init__(self, reaction_net): + super().__init__() + self._wrapped_object = reaction_net + + @property + def precursor_mass(self) -> float: + """""" + Gets the precursor mass (mass acted on) + """""" + return self._get_wrapped_object_().PrecursorMass + + @property + def collision_energy(self) -> float: + """""" + Gets the collision energy of this reaction + """""" + return self._get_wrapped_object_().CollisionEnergy + + @property + def isolation_width(self) -> float: + """""" + Gets the isolation width of the precursor mass + """""" + return self._get_wrapped_object_().IsolationWidth + + @property + def precursor_range_is_valid(self) -> bool: + """""" + Gets a value indicating whether precursor range is valid. If this is true, then + ThermoFisher.CommonCore.Data.Business.IReaction.PrecursorMass is still the center + of the range, but the values ThermoFisher.CommonCore.Data.Business.IReaction.FirstPrecursorMass + and ThermoFisher.CommonCore.Data.Business.IReaction.LastPrecursorMass define + the limits of the precursor mass range + """""" + return self._get_wrapped_object_().PrecursorRangeIsValid + + @property + def first_precursor_mass(self) -> float: + """""" + Gets the start of the precursor mass range (only if ThermoFisher.CommonCore.Data.Business.IReaction.PrecursorRangeIsValid) + """""" + return self._get_wrapped_object_().FirstPrecursorMass + + @property + def last_precursor_mass(self) -> float: + """""" + Gets the end of the precursor mass range (only if ThermoFisher.CommonCore.Data.Business.IReaction.PrecursorRangeIsValid) + """""" + return self._get_wrapped_object_().LastPrecursorMass + + @property + def collision_energy_valid(self) -> bool: + """""" + Gets a value indicating whether collision energy is valid. + """""" + return self._get_wrapped_object_().CollisionEnergyValid + + @property + def activation_type(self) -> ActivationType: + """""" + Gets the activation type. + """""" + return ActivationType(self._get_wrapped_object_().ActivationType) + + @property + def multiple_activation(self) -> bool: + """""" + Gets a value indicating whether this is a multiple activation. In a table of + reactions, a multiple activation is a second, or further, activation (fragmentation + method) applied to the same precursor mass. Precursor mass values should be obtained + from the original activation, and may not be returned by subsequent multiple + activations. + """""" + return self._get_wrapped_object_().MultipleActivation + + @property + def isolation_width_offset(self) -> float: + """""" + Gets the isolation width offset. + """""" + return self._get_wrapped_object_().IsolationWidthOffset + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/chromatogram_signal_cls.py",".py","10753","345","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import Range +from fisher_py.data.business.chromatogram_signal import ChromatogramData +from fisher_py.utils import to_net_list +from typing import List + + +class ChromatogramSignal(NetWrapperBase): + """""" + This represents the data for a chromatogram + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.ChromatogramSignal + + def __init__(self, *args): + """""" + Initializes a new instance of the ThermoFisher.CommonCore.Data.Business.ChromatogramSignal + class. + + Parameters: + signal: + Clone from this interface + """""" + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + elif len(args) == 1: + self._wrapped_object = self._wrapped_type(args[0]) + else: + raise ValueError('Unable to create chromatogram signal') + + @property + def signal_times(self) -> List[float]: + """""" + Gets or sets the signal times. + + Value: + The signal times. + """""" + return self._get_wrapped_object_().SignalTimes + + @signal_times.setter + def signal_times(self, value: List[float]): + """""" + Gets or sets the signal times. + + Value: + The signal times. + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().SignalTimes = value + + @property + def time_range(self) -> Range: + """""" + Gets the time range. + """""" + return Range._get_wrapper_(self._get_wrapped_object_().TimeRange) + + @property + def start_time(self) -> float: + """""" + Gets the time at the start of the signal + """""" + return self._get_wrapped_object_().StartTime + + @property + def end_time(self) -> float: + """""" + Gets the time at the end of the signal + """""" + return self._get_wrapped_object_().EndTime + + @property + def base_peak_masses(self) -> List[float]: + """""" + Gets the signal base peak masses. + + Value: + The signal base peak masses. May be null (should not be used) when HasBasePeakData + returns false + """""" + return self._get_wrapped_object_().BasePeakMasses + + @property + def signal_base_peak_masses(self) -> List[float]: + """""" + Gets or sets the signal base peak masses. + + Value: + The signal times. + """""" + return self._get_wrapped_object_().SignalBasePeakMasses + + @signal_base_peak_masses.setter + def signal_base_peak_masses(self, value: List[float]): + """""" + Gets or sets the signal base peak masses. + + Value: + The signal times. + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().SignalBasePeakMasses = value + + @property + def scans(self) -> List[int]: + """""" + Gets the signal scans. + + Value: + The signal scans. + """""" + return self._get_wrapped_object_().Scans + + @property + def signal_scans(self) -> List[int]: + """""" + Gets or sets the signal scans. + + Value: + The signal scans. + """""" + return self._get_wrapped_object_().SignalScans + + @signal_scans.setter + def signal_scans(self, value: List[int]): + """""" + Gets or sets the signal scans. + + Value: + The signal scans. + """""" + assert type(value) is List[int] + value = to_net_list(value, int) + self._get_wrapped_object_().SignalScans = value + + @property + def intensities(self) -> List[float]: + """""" + Gets the intensities. + + Value: + The signal intensities. + """""" + return self._get_wrapped_object_().Intensities + + @property + def signal_intensities(self) -> List[float]: + """""" + Gets or sets the signal intensities. + + Value: + The signal intensities. + """""" + return self._get_wrapped_object_().SignalIntensities + + @signal_intensities.setter + def signal_intensities(self, value: List[float]): + """""" + Gets or sets the signal intensities. + + Value: + The signal intensities. + """""" + assert type(value) is list + value = to_net_list(value, float) + self._get_wrapped_object_().SignalIntensities = value + + @property + def has_base_peak_data(self) -> bool: + """""" + Gets a value indicating whether there is any base peak data in this signal + """""" + return self._get_wrapped_object_().HasBasePeakData + + @property + def length(self) -> int: + """""" + Gets the number of points in the signal + """""" + return self._get_wrapped_object_().Length + + @property + def times(self) -> List[float]: + """""" + Gets the times. + """""" + return self._get_wrapped_object_().Times + + @staticmethod + def from_chromatogram_data(chromatogram_data: ChromatogramData) -> List[ChromatogramSignal]: + """""" + Create an array of signals from chromatogramData. The Interface ThermoFisher.CommonCore.Data.Interfaces.IChromatogramData + describes data read from a file (if using IRawData). This constructor converts + to an array of type Signal, simplifying use of individual chromatograms with + Peak integration. + + Parameters: + chromatogramData: + data (usually read from file) to convert into signals + + Returns: + The constructed signals, or null if the input is null + """""" + assert type(chromatogram_data) is ChromatogramData + signals = ChromatogramSignal._wrapped_type.FromChromatogramData(chromatogram_data._get_wrapped_object_()) + return [ChromatogramSignal._get_wrapper_(s) for s in signals] + + @staticmethod + def from_time_and_intensity(time: List[float], intensity: List[float]) -> ChromatogramSignal: + """""" + Summary: + Create a Chromatogram signal, from time and intensity arrays + + Parameters: + time: + array of retention times + + intensity: + array of intensities at each time + + Returns: + The constructed signal, or null if either of the inputs are null, or the inputs + are not the same length + """""" + assert type(time) is list + assert type(intensity) is list + time = to_net_list(time, float) + intensity = to_net_list(intensity, float) + return ChromatogramSignal._get_wrapper_(ChromatogramSignal._wrapped_type.FromTimeAndIntensity(time, intensity)) + + @staticmethod + def from_time_intensity_scan(time: List[float], intensity: List[float], scan: List[int]) -> ChromatogramSignal: + """""" + Summary: + Create a Chromatogram signal, from time, intensity and scan arrays + + Parameters: + time: + array of retention times + + intensity: + array of intensities at each time + + scan: + array of scan numbers for each time + + Returns: + The constructed signal, or null if either of the inputs are null, or the inputs + are not the same length + """""" + assert type(time) is list + assert type(intensity) is list + assert type(scan) is list + time = to_net_list(time, float) + intensity = to_net_list(intensity, float) + scan = to_net_list(scan, int) + return ChromatogramSignal._get_wrapper_(ChromatogramSignal._wrapped_type.FromTimeIntensityScan(time, intensity, scan)) + + @staticmethod + def from_time_intensity_scan_base_peak(time: List[float], intensity: List[float], scan: List[int], base_peak: List[float]) -> ChromatogramSignal: + """""" + Summary: + Create a Chromatogram signal, from time, intensity, scan and base peak arrays + + Parameters: + time: + array of retention times + + intensity: + array of intensities at each time + + scan: + array of scan numbers for each time + + basePeak: + Array of base peak masses for each time + + Returns: + The constructed signal, or null if either of the inputs are null, or the inputs + are not the same length + """""" + assert type(time) is list + assert type(intensity) is list + assert type(scan) is list + assert type(base_peak) is list + time = to_net_list(time, float) + intensity = to_net_list(intensity, float) + scan = to_net_list(scan, int) + base_peak = to_net_list(base_peak, float) + return ChromatogramSignal._get_wrapper_(ChromatogramSignal._wrapped_type.FromTimeIntensityScanBasePeak(time, intensity, scan, base_peak)) + + @staticmethod + def to_chromatogram_data(signals: List[ChromatogramSignal]) -> ChromatogramData: + """""" + Summary: + Create chromatogram data interface from signals. The Interface ThermoFisher.CommonCore.Data.Interfaces.IChromatogramData + describes data read from a file (if using IRawData). + // + Parameters: + signals: + data (usually read from file) to convert into signals + // + Returns: + The constructed signals, or null if the input is null + """""" + assert type(signals) is list + net_signals = to_net_list([s._get_wrapped_object_() for s in signals], ChromatogramSignal._wrapped_type) + return ChromatogramData._get_wrapper_(ChromatogramSignal._wrapped_type.ToChromatogramData(net_signals)) + + def clone(self) -> object: + """""" + Creates a new object that is a (deep) copy of the current instance. + + Returns: + A new object that is a copy of this instance. + """""" + return self._get_wrapped_object_().Clone() + + def delay(self, delay: float): + """""" + Add a delay to all times. This is intended to support ""detector delays"" where + multiple detector see the same sample at different times. + + Parameters: + delay: + The delay. + """""" + self._get_wrapped_object_().Delay(delay) + + def valid(self) -> bool: + """""" + Test if the signal is valid + + Returns: + True if both times and intensities have been set, and are the same length + """""" + return self._get_wrapped_object_().Valid() + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/spectrum_packet_type.py",".py","1356","39","import enum + +class SpectrumPacketType(enum.Enum): + """""" + The spectrum packet types. Internally, within raw files, these are defined simply + as ""a short integer packet type"" These are then mapped to ""constants"". It is + possible that types may be returned by from raw data, or other transmissions, + which are outside of this range. These types define original compression formats + from instruments. Note that most data values are returned as ""float"", when using + IRawDataPlus regardless of the compressed file format used. + """""" + NoPacketType = -1 + ProfileSpectrum = 0 + LowResolutionSpectrum = 1 + HighResolutionSpectrum = 2 + ProfileIndex = 3 + CompressedAccurateSpectrum = 4 + StandardAccurateSpectrum = 5 + StandardUncalibratedSpectrum = 6 + AccurateMassProfileSpectrum = 7 + PdaUvDiscreteChannel = 8 + PdaUvDiscreteChannelIndex = 9 + PdaUvScannedSpectrum = 10 + PdaUvScannedSpectrumIndex = 11 + UvChannel = 12 + MassSpecAnalog = 13 + ProfileSpectrumType2 = 14 + LowResolutionSpectrumType2 = 15 + ProfileSpectrumType3 = 16 + LowResolutionSpectrumType3 = 17 + LinearTrapCentroid = 18 + LinearTrapProfile = 19, + FtCentroid = 20 + FtProfile = 21 + HighResolutionCompressedProfile = 22 + LowResolutionCompressedProfile = 23 + LowResolutionSpectrumType4 = 24 + InvalidPacket = 25 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/range_factory.py",".py","2008","65","from fisher_py.net_wrapping import ThermoFisher +from fisher_py.utils import is_number +from fisher_py.data.business import Range, MassOptions + +_range_factory = ThermoFisher.CommonCore.Data.Business.RangeFactory + + +class RangeFactor(object): + """""" + Factory to produce immutable ranges of double + """""" + + @staticmethod + def create(low: float, high: float) -> Range: + """""" + Create an immutable (constant) range from low and high. + + Parameters: + low: + The low. + + high: + The high. + + Returns: + The range. + """""" + assert is_number(low) + assert is_number(high) + return Range._get_wrapper_(_range_factory.Create(float(low), float(high))) + + @staticmethod + def create_from_center_and_delta(center: float, delta: float) -> Range: + """""" + Create an immutable (constant) range from center and delta, such that the range + is center +/- delta. + + Parameters: + center: + The center. + + delta: + The delta. + + Returns: + The ThermoFisher.CommonCore.Data.Business.Range. + """""" + assert is_number(center) + assert is_number(delta) + return Range._get_wrapper_(_range_factory.CreateFromCenterAndDelta(float(center), float(delta))) + + @staticmethod + def create_from_range_and_tolerance(from_: Range, arg) -> Range: + """""" + Construct a range from another range, adding a tolerance if ends are the same + """""" + assert type(from_) is Range + + if type(arg) is MassOptions: + return Range._get_wrapper_(_range_factory.CreateFromRangeAndTolerance(from_._get_wrapped_object_(), arg._get_wrapped_object_())) + elif is_number(arg): + return Range._get_wrapper_(_range_factory.CreateFromRangeAndTolerance(from_._get_wrapped_object_(), float(arg))) + + raise ValueError('Unable to create range.') +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/mass_options.py",".py","4340","134","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data import ToleranceUnits +from fisher_py.utils import is_number + + +class MassOptions(NetWrapperBase): + """""" + Contains the options for displaying and calculating the masses. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.MassOptions + + def __init__(self, *args): + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + elif len(args) == 1: + arg = args[0] + if type(arg) is MassOptions: + self._wrapped_object = self._wrapped_type(arg._get_wrapped_object()) + elif is_number(arg): + self._wrapped_object = self._wrapped_type(float(arg)) + else: + raise ValueError('Unable to create mass options.') + elif len(args) == 2: + tolerance, tolerance_units = args + assert is_number(tolerance) + assert type(tolerance_units) is ToleranceUnits + self._wrapped_object = self._wrapped_type(float(tolerance), tolerance_units.value) + elif len(args) == 3: + tolerance, tolerance_units, precision = args + assert is_number(tolerance) + assert type(tolerance_units) is ToleranceUnits + assert type(precision) is int + self._wrapped_object = self._wrapped_type(float(tolerance), tolerance_units.value, precision) + else: + raise ValueError('Unable to create mass options.') + + @property + def tolerance(self) -> float: + """""" + Gets or sets the tolerance value. + + Value: + The tolerance. + """""" + return self._get_wrapped_object_().Tolerance + + @tolerance.setter + def tolerance(self, value: float): + """""" + Gets or sets the tolerance value. + + Value: + The tolerance. + """""" + assert type(value) is float + self._get_wrapped_object_().Tolerance = value + + @property + def precision(self) -> int: + """""" + Gets or sets the precision (decimal places). + """""" + return self._get_wrapped_object_().Precision + + @precision.setter + def precision(self, value: int): + """""" + Gets or sets the precision (decimal places). + """""" + assert type(value) is int + self._get_wrapped_object_().Precision = value + + @property + def tolerance_units(self) -> ToleranceUnits: + """""" + Gets or sets the tolerance units. + """""" + return ToleranceUnits(self._get_wrapped_object_().ToleranceUnits) + + @tolerance_units.setter + def tolerance_units(self, value: ToleranceUnits): + """""" + Gets or sets the tolerance units. + """""" + assert type(value) is ToleranceUnits + self._get_wrapped_object_().ToleranceUnits = value.value + + @property + def tolerance_string(self) -> str: + """""" + Gets the tolerance string of the current toleranceUnits setting. + """""" + return self._get_wrapped_object_().ToleranceString + + def get_tolerance_string(tolerance_units: ToleranceUnits) -> str: + """""" + Gets the tolerance string from the enumeration strings resource. + + Parameters: + toleranceUnits: + The tolerance units. + + Returns: + The tolerance units as a string. + """""" + return MassOptions._wrapped_type.GetToleranceString(tolerance_units.value) + + def clone(self) -> MassOptions: + """""" + Implementation of ICloneable.Clone method. Creates deep copy of this instance. + + Returns: + An exact copy of the current object. + """""" + return MassOptions._get_wrapper_(self._get_wrapped_object().Clone()) + + def get_tolerance_at_mass(self, mass: float) -> float: + """""" + Get the tolerance window around a specific mass + + Parameters: + mass: + Mass about which window is needed + + Returns: + The distance (in amu) from the mass which is within tolerance. For example: myWindow=GetToleranceAtMass(myMass); + accept data between ""myMass-myWindow"" and ""myMass+myWindow"" + """""" + return self._get_wrapped_object().GetToleranceAtMass(mass) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/chromatogram_trace_settings.py",".py","8287","255","from __future__ import annotations +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from typing import List +from fisher_py.data.business import Range, TraceType +from fisher_py.utils import to_net_list + + +class ChromatogramTraceSettings(NetWrapperBase): + """""" + Setting to define a chromatogram Trace. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings + + def __init__(self, *args): + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + elif len(args) == 1: + arg = args[0] + if type(arg) is ChromatogramTraceSettings: + self._wrapped_object = self._wrapped_type(arg._get_wrapped_object_()) + elif type(arg) is TraceType: + self._wrapped_object = self._wrapped_type(arg.value) + else: + raise ValueError('Unable to create chromatogram trace settings') + elif len(args) == 2: + filter_, range_ = args + assert type(filter_) is str + assert type(range_) is Range + self._wrapped_object = self._wrapped_type(filter_, range_._get_wrapped_object_()) + + @property + def mass_range_count(self) -> int: + """""" + Gets or sets the number of mass ranges, or wavelength ranges for PDA. + + Value: + Numeric count of mass ranges + + Remarks: + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + return self._get_wrapped_object_().MassRangeCount + + @mass_range_count.setter + def mass_range_count(self, value: int): + """""" + Gets or sets the number of mass ranges, or wavelength ranges for PDA. + + Value: + Numeric count of mass ranges + + Remarks: + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + assert type(value) is int + self._get_wrapped_object_().MassRangeCount = value + + @property + def include_reference(self) -> bool: + """""" + Gets or sets a value indicating whether reference and exception peaks are included + in this chromatogram trace + """""" + return self._get_wrapped_object_().IncludeReference + + @include_reference.setter + def include_reference(self, value: bool): + """""" + Gets or sets a value indicating whether reference and exception peaks are included + in this chromatogram trace + """""" + assert type(value) is bool + self._get_wrapped_object_().IncludeReference = value + + @property + def fragment_mass(self) -> float: + """""" + Gets or sets the fragment mass for neutral fragment filters. + + Value: + Floating point fragment mass for neutral fragment filters + """""" + return self._get_wrapped_object_().FragmentMass + + @fragment_mass.setter + def fragment_mass(self, value: float): + """""" + Gets or sets the fragment mass for neutral fragment filters. + + Value: + Floating point fragment mass for neutral fragment filters + """""" + assert type(value) is float + self._get_wrapped_object_().FragmentMass = value + + @property + def filter(self) -> str: + """""" + Gets or sets the filter used in searching scans during trace build + """""" + return self._get_wrapped_object_().Filter + + @filter.setter + def filter(self, value: str): + """""" + Gets or sets the filter used in searching scans during trace build + """""" + assert type(value) is str + self._get_wrapped_object_().Filter = value + + @property + def delay_in_min(self) -> float: + """""" + Gets or sets the delay in minutes. + + Value: + Floating point delay in minutes + """""" + return self._get_wrapped_object_().DelayInMin + + @delay_in_min.setter + def delay_in_min(self, value: float): + """""" + Gets or sets the delay in minutes. + + Value: + Floating point delay in minutes + """""" + assert type(value) is float + self._get_wrapped_object_().DelayInMin = value + + @property + def trace(self) -> TraceType: + """""" + Gets or sets the type of trace to construct + + Value: + see ThermoFisher.CommonCore.Data.Business.TraceType for more details + """""" + return TraceType(self._get_wrapped_object_().Trace) + + @trace.setter + def trace(self, value: TraceType): + """""" + Gets or sets the type of trace to construct + + Value: + see ThermoFisher.CommonCore.Data.Business.TraceType for more details + """""" + assert type(value) is TraceType + self._get_wrapped_object_().Trace = value.value + + @property + def mass_ranges(self) -> List[Range]: + """""" + Gets or sets the mass ranges. + + Value: + Array of mass ranges + + Remarks: + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + return [Range._get_wrapper_(r) for r in self._get_wrapped_object_().MassRanges] + + @mass_ranges.setter + def mass_ranges(self, value: List[Range]): + """""" + Gets or sets the mass ranges. + + Value: + Array of mass ranges + + Remarks: + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + assert type(value) is list + #value = to_net_list([r._get_wrapped_object_() for r in value], Range._wrapped_type) + value = [r._get_wrapped_object_() for r in value] + self._get_wrapped_object_().MassRanges = value + + @property + def compound_names(self) -> List[str]: + """""" + Gets or sets the compound names. + """""" + return self._get_wrapped_object_().CompoundNames + + @compound_names.setter + def compound_names(self, value: List[str]): + """""" + Gets or sets the compound names. + """""" + assert type(value) is list + value = to_net_list(value, str) + self._get_wrapped_object_().CompoundNames = value + + def clone(self) -> ChromatogramTraceSettings: + """""" + Copies all of the items to from this object into the returned object. + + Returns: + The clone. + """""" + return ChromatogramTraceSettings._get_wrapper_(self._get_wrapped_object().Clone()) + + def get_mass_range(self, index: int) -> Range: + """""" + Gets a range value at 0-based index. + + Parameters: + index: + Index at which to retrieve the range + + Returns: + ThermoFisher.CommonCore.Data.Business.Range value at give index + + Remarks: + Use ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.MassRangeCount + to find out the count of mass ranges. + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + assert type(index) is int + return Range._get_wrapper_(self._get_wrapped_object().GetMassRange(index)) + + def set_mass_range(self, index: int, range: Range): + """""" + Sets a range value at 0-based index. + + Parameters: + index: + Index at which new range value is to be set + + range: + New ThermoFisher.CommonCore.Data.Business.Range value to be set + + Remarks: + Set count of mass ranges using ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.MassRangeCount + before setting any mass ranges. + If ThermoFisher.CommonCore.Data.Business.ChromatogramTraceSettings.Trace is MassRange + then mass range values are used to build trace. + """""" + assert type(index) is int + assert type(range) is Range + self._get_wrapped_object().SetMassRange(index, range._get_wrapped_object_()) + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/raw_file_reader_factory.py",".py","1311","40","from fisher_py.data.raw_file_thread_accessor import RawFileThreadAccessor +from fisher_py.net_wrapping import ThermoFisher +from fisher_py.raw_file_reader.raw_file_access import RawFileAccess + + +class RawFileReaderFactory: + + @staticmethod + def read_file(filename: str) -> RawFileAccess: + """""" + Summary: + Open a raw file for reading. + + Parameters: + fileName: + Name of file to read + + Returns: + Access to the contents of the file. + """""" + assert type(filename) is str + return RawFileAccess._get_wrapper_(ThermoFisher.CommonCore.Data.Business.RawFileReaderFactory.ReadFile(filename)) + + @staticmethod + def create_thread_manager(filename: str) -> RawFileThreadAccessor: + """""" + Summary: + Open a raw file for reading, creating a manager tool, such that multiple threads + can access the same open file. + + Parameters: + fileName: + Name of file to read + + Returns: + Access to the contents of the file. + """""" + assert type(filename) is str + return RawFileThreadAccessor._get_wrapper_(ThermoFisher.CommonCore.Data.Business.RawFileReaderFactory.CreateThreadManager(filename)) +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/barcode_status_type.py",".py","191","12","import enum + + +class BarcodeStatusType(enum.Enum): + """""" + Enumeration of possible bar code status values + """""" + NotRead = 0 + Read = 1 + Unreadable = 2 + Error = 3 + Wait = 4","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/range.py",".py","4741","156","from __future__ import annotations +from typing import Any +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import MassOptions +from fisher_py.utils import is_number + + +class Range(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.Range + + def __init__(self, *args): + super().__init__() + + if len(args) == 0: + self._wrapped_object = self._wrapped_type() + elif len(args) == 1: + from_ = args[0] + assert type(from_) is Range + self._wrapped_object = self._wrapped_type(from_._wrapped_object) + elif len(args) == 2: + arg1, arg2 = args + if is_number(arg1) and is_number(arg2): + self._wrapped_object = self._wrapped_type(float(arg1), float(arg2)) + elif type(arg1) is Range and is_number(arg2): + self._wrapped_object = self._wrapped_type(arg1._wrapped_object, float(arg2)) + elif type(arg1) is Range and type(arg2) is MassOptions: + self._wrapped_object = self._wrapped_type(arg1._wrapped_object, arg2._wrapped_object) + + @property + def low(self) -> float: + """""" + Gets or sets the low end of range + """""" + return self._get_wrapped_object_().Low + + @low.setter + def low(self, value: float): + """""" + Gets or sets the low end of range + """""" + assert type(value) is float + self._get_wrapped_object_().Low = value + + @property + def high(self) -> float: + """""" + Gets or sets the high end of range + """""" + return self._get_wrapped_object_().High + + @high.setter + def high(self, value: float): + """""" + Gets or sets the high end of range + """""" + assert type(value) is float + self._get_wrapped_object_().High = value + + @staticmethod + def create(low: float, high: float) -> Range: + """""" + Create an immutable (constant) range from low and high. + + Parameters: + low: + The low. + + high: + The high. + + Returns: + The range. + """""" + assert is_number(low) + assert is_number(high) + return Range._get_wrapper_(Range._wrapped_type.Create(float(low), float(high))) + + def create_from_cetner_and_delta(center: float, delta: float) -> Range: + """""" + Create an immutable (constant) range from center and delta, such that the range + is center +/- delta. + + Parameters: + center: + The center. + + delta: + The delta. + + Returns: + The ThermoFisher.CommonCore.Data.Business.Range. + """""" + assert is_number(center) + assert is_number(delta) + return Range._get_wrapper_(Range._wrapped_type.CreateFromCenterAndDelta(float(center), float(delta))) + + def compare_to(self, other: Range) -> int: + """""" + Compares the current object with another object of the same type. + + Parameters: + other: + An object to compare with this object. + + Returns: + A 32-bit signed integer that indicates the relative order of the objects being + compared. The return value has the following meanings: Value Meaning Less than + zero This object is less than the other parameter. Zero This object is equal + to other. Greater than zero This object is greater than other. + """""" + return self._get_wrapped_object().CompareTo(other._get_wrapped_object_()) + + def equals(self, obj: object) -> bool: + """""" + Indicates whether this instance and a specified object are equal. + + Parameters: + obj: + Another object to compare to. + + Returns: + true if obj and this instance are the same type and represent the same value; + otherwise, false. + """""" + return self._get_wrapped_object().Equals(obj) + + def get_hash_code(self) -> int: + """""" + Returns the hash code for this instance. + + Returns: + A 32-bit signed integer that is the hash code for this instance. + """""" + return self._get_wrapped_object().GetHashCode() + + def includes(self, value: float) -> bool: + """""" + Test for inclusion. + + Parameters: + value: + The value. + + Returns: + True if in range + """""" + assert is_number(value) + return self._get_wrapped_object().Includes(float(value)) + + def __eq__(self, o: Range) -> bool: + return self._get_wrapped_object_() == o._get_wrapped_object_() + + def __ne__(self, o: Range) -> bool: + return not self == o +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/sample_type.py",".py","340","20","import enum + +class SampleType(enum.Enum): + """""" + Enumeration of sample types + """""" + Unknown = 0 + Blank = 1 + QC = 2 + StdClear = 3 + StdUpdate = 4 + StdBracket = 5 + StdBracketStart = 6 + StdBracketEnd = 7 + Program = 8 + SolventBlank = 9 + MatrixBlank = 10 + MatrixSpike = 11 + MatrixSpikeDuplicate = 12 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/tune_data_values.py",".py","1194","45","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.utils import to_net_list +from typing import List + + +class TuneDataValues(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.TuneDataValues + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def id(self) -> int: + """""" + Gets or sets the index number of the tune record + """""" + return self._get_wrapped_object_().ID + + @id.setter + def id(self, value: int): + """""" + Gets or sets the index number of the tune record + """""" + assert type(value) is int + self._get_wrapped_object_().ID = value + + @property + def values(self) -> List[str]: + """""" + Gets or sets the array of tune data values for an instrument + """""" + return self._get_wrapped_object_().Values + + @values.setter + def values(self, value: List[str]): + """""" + Gets or sets the array of tune data values for an instrument + """""" + assert type(value) is list + value = to_net_list(value, str) + self._get_wrapped_object_().Values = value + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/log_entry.py",".py","1396","58"," +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from typing import List + + +class LogEntry(NetWrapperBase): + """""" + Represents a single log. + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.LogEntry + + @property + def labels(self) -> List[str]: + """""" + Gets or sets the labels in this log. + """""" + return list(self._get_wrapped_object_().Labels) + + @labels.setter + def labels(self, value: List[str]): + """""" + Gets or sets the labels in this log. + """""" + assert type(value) is List[str] + self._get_wrapped_object_().Labels = value + + @property + def values(self) -> List[str]: + """""" + Gets or sets the values in this log. + """""" + return list(self._get_wrapped_object_().Values) + + @values.setter + def values(self, value: List[str]): + """""" + Gets or sets the values in this log. + """""" + assert type(value) is List[str] + self._get_wrapped_object_().Values = value + + @property + def length(self) -> int: + """""" + Gets or sets the length of the log. + """""" + return self._get_wrapped_object_().Length + + @length.setter + def length(self, value: int): + """""" + Gets or sets the length of the log. + """""" + assert type(value) is int + self._get_wrapped_object_().Length = value + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/mass_to_frequency_converter.py",".py","4196","151","from fisher_py.utils import is_number +from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from fisher_py.data.business import Range + + +class MassToFrequencyConverter(NetWrapperBase): + """""" + Class which includes the coefficients for mass calibration from a particular + scan, and means to convert between mass and frequency + """""" + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.MassToFrequencyConverter + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def coefficient_1(self) -> float: + """""" + Gets or sets the coefficient 1. + """""" + return self._get_wrapped_object_().Coefficient1 + + @coefficient_1.setter + def coefficient_1(self, value: float): + """""" + Gets or sets the coefficient 1. + """""" + assert is_number(value) + self._get_wrapped_object_().Coefficient1 = float(value) + + @property + def coefficient_2(self) -> float: + """""" + Gets or sets the coefficient 2. + """""" + return self._get_wrapped_object_().Coefficient2 + + @coefficient_2.setter + def coefficient_2(self, value: float): + """""" + Gets or sets the coefficient 2. + """""" + assert is_number(value) + self._get_wrapped_object_().Coefficient2 = float(value) + + @property + def coefficient_3(self) -> float: + """""" + Gets or sets the coefficient 3. + """""" + return self._get_wrapped_object_().Coefficient3 + + @coefficient_3.setter + def coefficient_3(self, value: float): + """""" + Gets or sets the coefficient 3. + """""" + assert is_number(value) + self._get_wrapped_object_().Coefficient3 = float(value) + + @property + def base_frequency(self) -> float: + """""" + Gets or sets the base frequency. + """""" + return self._get_wrapped_object_().BaseFrequency + + @base_frequency.setter + def base_frequency(self, value: float): + """""" + Gets or sets the base frequency. + """""" + assert is_number(value) + self._get_wrapped_object_().BaseFrequency = float(value) + + @property + def delta_frequency(self) -> float: + """""" + Gets or sets the delta frequency. + """""" + return self._get_wrapped_object_().DeltaFrequency + + @delta_frequency.setter + def delta_frequency(self, value: float): + """""" + Gets or sets the delta frequency. + """""" + assert is_number(value) + self._get_wrapped_object_().DeltaFrequency = float(value) + + @property + def highest_mass(self) -> float: + """""" + Gets or sets the highest mass. + """""" + return self._get_wrapped_object_().HighestMass + + @highest_mass.setter + def highest_mass(self, value: float): + """""" + Gets or sets the highest mass. + """""" + assert is_number(value) + self._get_wrapped_object_().HighestMass = float(value) + + @property + def segment_range(self) -> Range: + """""" + Gets or sets the (largest) segment range of the scans processed. + """""" + return self._get_wrapped_object_().SegmentRange + + @segment_range.setter + def segment_range(self, value: Range): + """""" + Gets or sets the (largest) segment range of the scans processed. + """""" + assert is_number(value) + self._get_wrapped_object_().SegmentRange = float(value) + + def convert_frequence_to_mass(self, sample: int) -> float: + """""" + Converts the given frequency to it's corresponding mass. + + Parameters: + sample: + sample number to convert + + Returns: + converted mass. + """""" + assert type(sample) is int + return self._get_wrapped_object().ConvertFrequenceToMass(sample) + + def convert_mass_to_frequency(self, mass: float) -> float: + """""" + Converts the given mass to frequency. + + Parameters: + mass: + The mass to convert + + Returns: + converted frequency + """""" + assert is_number(mass) + return self._get_wrapped_object().ConvertMassToFrequency(float(mass)) + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/chromatogram_signal/chromatogram_data.py",".py","1216","40","from fisher_py.net_wrapping import NetWrapperBase, ThermoFisher +from typing import List + + +class ChromatogramData(NetWrapperBase): + + _wrapped_type = ThermoFisher.CommonCore.Data.Business.ChromatogramSignal + + def __init__(self): + super().__init__() + self._wrapped_object = self._wrapped_type() + + @property + def positions_array(self) -> List[List[float]]: + """""" + Gets Times in minutes for each chromatogram + """""" + return [[n for n in sublist] for sublist in self._get_wrapped_object_().PositionsArray] + + @property + def scan_numbers_array(self) -> List[List[int]]: + """""" + Gets Scan numbers for data points in each chromatogram + """""" + return [[n for n in sublist] for sublist in self._get_wrapped_object_().ScanNumbersArray] + + @property + def intensities_array(self) -> List[List[float]]: + """""" + Gets Intensities for each chromatogram + """""" + return [[n for n in sublist] for sublist in self._get_wrapped_object_().IntensitiesArray] + + @property + def length(self) -> int: + """""" + Gets The number of chromatograms in this object + """""" + return self._get_wrapped_object_().Length +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","src/fisher_py/data/business/chromatogram_signal/__init__.py",".py","91","2","from fisher_py.data.business.chromatogram_signal.chromatogram_data import ChromatogramData +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","examples/raw_file_access_example.py",".py","541","17"," +from fisher_py.data import Device, TrayShape +from fisher_py.raw_file_reader import RawFileReaderAdapter + + +if __name__ == '__main__': + # Check to see if the RAW file name was supplied as an argument to the program + filename = ""my_file.raw"" + + # Create the RawFileAccess object for accessing the RAW file + raw_file = RawFileReaderAdapter.file_factory(filename) + + raw_file.select_instrument(Device.MS, 1) + + print(f'User labels: {"", "".join(raw_file.user_label)}') + print(raw_file.scan_events) + print(raw_file)","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","examples/__init__.py",".py","39","2","from fisher_py.raw_file import RawFile +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","examples/generate_mgf_file_example.py",".py","10424","250",""""""" +A Python example program showing how to use RAWFileReader. More information on the RAWFileReader methods used +in this example and the other methods available in RAWFileReader can be found in the RAWFileReader user +documentation, that is installed with the RAWFileReader software. + +The code of this example is based on the following GitHub repository: https://github.com/compomics/ThermoRawFileParser +It was added to provide users a way of doing what ThermoRawFileParser does in Python. +"""""" + +from typing import List, Union + +from numpy import float64 +from fisher_py.data import Device +from fisher_py.data import ScanEvent +from fisher_py.data.filter_enums import MsOrderType, PolarityType, ScanDataType +from fisher_py.raw_file_reader import RawFileReaderAdapter +from fisher_py.data.business import Scan, Reaction, LogEntry +import os +import re + + +## Configuration (Use this section to select the input file and the output folder as well as setting other parameters) +RAW_FILE_PATH = r""my_file.raw"" +OUTPUT_FOLDER = r""output_folder"" +MS_LEVEL = { MsOrderType.Ms2 } +DISABLE_NATIVE_PEAK_SEARCHING = True +INCLUDE_REF_AND_EX_DATA = True +#-- + +# Constants +PROGRESS_STEP = 10 +ZERO_DELTA = 0.0001 +PRECURSOR_MZ_DELTA = 0.0001 +DEFAULT_ISOLATION_WINDOW_LOWER_OFFSET = 1.5 +DEFAULT_ISOLATION_WINDOW_UPPER_OFFSET = 2.5 +FILTER_STRING_ISOLATION_MZ_PATTERN = 'ms2 (.*?)@' +_isolation_mz_to_precursor_scan_number_mapping = dict() +_precursor_ms1_scan_number = 0 +_last_scan_progress = 0 + + +def construct_spectrum_title(instrument_type: int, instrument_number: int, scan_number: int) -> str: + return f'controllerType={instrument_type} controllerNumber={instrument_number} scan={scan_number}' + + +def construct_precursor_reference(ms_order: MsOrderType, scan_number: int, scan_event: ScanEvent) -> str: + global _isolation_mz_to_precursor_scan_number_mapping, _precursor_ms1_scan_number + + if ms_order == MsOrderType.Ms2: + # Keep track of the MS2 scan number and isolation m/z for precursor reference + result = re.match(str(scan_event), FILTER_STRING_ISOLATION_MZ_PATTERN) + if result: + res = result.groups()[0] + if res in _isolation_mz_to_precursor_scan_number_mapping: + del _isolation_mz_to_precursor_scan_number_mapping[res] + _isolation_mz_to_precursor_scan_number_mapping[res] = scan_number + + precursor_reference = construct_spectrum_title(Device.MS.value, 1, _precursor_ms1_scan_number) + + elif ms_order == MsOrderType.Ms3: + precursor_scan_number = next(filter(lambda isolation_mz: isolation_mz in str(scan_event), _isolation_mz_to_precursor_scan_number_mapping.keys()), None) + if precursor_scan_number: + precursor_reference = construct_precursor_reference(Device.MS.value, 1, _isolation_mz_to_precursor_scan_number_mapping[precursor_scan_number]) + else: + raise ValueError(f""Couldn't find a MS2 precursor scan for MS3 scan {scan_event}"") + + return precursor_reference + + +def get_reaction(scan_event: ScanEvent, scan_number: int) -> Reaction: + try: + order = scan_event.ms_order.value + return scan_event.get_reaction(order - 2) + except: + print(f'No reaction found for scan {scan_number}') + return None + + +class ScanTrailer(object): + + @property + def length(self) -> int: + return len(self._data) + + @property + def labels(self) -> List[str]: + return list(self._data.keys()) + + @property + def values(self) -> List[str]: + return list(self._data.values()) + + def as_bool(self, key: str) -> Union[bool, None]: + if key in self._data: + str_value = self._data[key].lower() + + if str_value in { 'on', 'true', 'yes' }: + return True + return False + return None + + def as_double(self, key: str) -> float64: + if key in self._data: + try: + return float64(self._data[key]) + except: + pass + return None + + def as_int(self, key: str) -> int: + if key in self._data: + try: + return int(self._data[key]) + except: + pass + return None + + def as_positive_int(self, key: str) -> int: + if key in self._data: + try: + result = int(self._data[key]) + return result if result >= 0 else None + except: + pass + return None + + def as_string(self, key: str) -> str: + return self.get(key) + + def get(self, key: str) -> str: + if key in self._data: + try: + return self._data[key] + except: + pass + return None + + def has(self, key: str) -> bool: + return key in self._data + + def __init__(self, trailer_data: LogEntry): + self._data = {trailer_data.labels[i]: trailer_data.values[i] for i in range(trailer_data.length)} + + +def calculate_selected_ion_mz(reaction: Reaction, monoisotopic_mz: float64, isolation_width: float64) -> float64: + selected_ion_mz = reaction.precursor_mass + + # take the isolation width from the reaction if no value was found in the trailer data + if isolation_width is None or isolation_width < ZERO_DELTA: + isolation_width = reaction.isolation_width + + isolation_width *= 0.5 + + if monoisotopic_mz and monoisotopic_mz > ZERO_DELTA and abs(reaction.precursor_mass - monoisotopic_mz) > PRECURSOR_MZ_DELTA: + selected_ion_mz = monoisotopic_mz + + # check if the monoisotopic mass lies in the precursor mass isolation window + # otherwise take the precursor mass + if isolation_width <= 2: + if (selected_ion_mz < (reaction.precursor_mass - DEFAULT_ISOLATION_WINDOW_LOWER_OFFSET * 2)) or (selected_ion_mz > (reaction.precursor_mass + DEFAULT_ISOLATION_WINDOW_UPPER_OFFSET)): + selected_ion_mz = reaction.precursor_mass + elif (selected_ion_mz < (reaction.precursor_mass - isolation_width)) or (selected_ion_mz > (reaction.precursor_mass + isolation_width)): + selected_ion_mz = reaction.precursor_mass + + return selected_ion_mz + + +if __name__ == '__main__': + raw_file = RawFileReaderAdapter.file_factory(RAW_FILE_PATH) + raw_file.select_instrument(Device.MS, 1) + raw_file.include_reference_and_exception_data = INCLUDE_REF_AND_EX_DATA + + file_name = os.path.splitext(os.path.split(RAW_FILE_PATH)[-1])[0] + OUTPUT_FILE = os.path.join(OUTPUT_FOLDER, f'{file_name}.mgf') + + # Get the first and last scan from the RAW file + first_scan_number = raw_file.run_header_ex.first_spectrum + last_scan_number = raw_file.run_header_ex.last_spectrum + + + with open(OUTPUT_FILE, 'w') as mgf_file: + for scan_number in range(first_scan_number, last_scan_number + 1): + + # report progress + scan_progress = int(scan_number / (last_scan_number - first_scan_number + 1) * 100) + if scan_progress % PROGRESS_STEP == 0: + if scan_progress != _last_scan_progress: + print(f'{scan_progress} %') + _last_scan_progress = scan_progress + + # Get the scan from the RAW file + scan: Scan = Scan.from_file(raw_file, scan_number) + + # Get the retention time + retention_time = raw_file.retention_time_from_scan_number(scan_number) + + # Get the scan filter for this scan number + scan_filter = raw_file.get_filter_for_scan_number(scan_number) + + # Get the scan event for this scan number + scan_event = raw_file.get_scan_event_for_scan_number(scan_number) + + # Don't include MS1 spectra + if scan_filter.ms_order in MS_LEVEL: + reaction = get_reaction(scan_event, scan_number) + + mgf_file.write(f'BEGIN IONS\n') + mgf_file.write(f'TITLE={construct_spectrum_title(Device.MS.value, 1, scan_number)}\n') + + mgf_file.write(f'SCANS={scan_number}\n') + mgf_file.write(f'RTINSECONDS={(retention_time * 60)}\n') + + # Trailer extra data list + trailer_data = ScanTrailer(raw_file.get_trailer_extra_information(scan_number)) + charge = trailer_data.as_positive_int('Charge State:') + monoisotopic_mz = trailer_data.as_double('Monoisotopic M/Z:') + isolation_width = trailer_data.as_double(f'MS{scan_filter.ms_order.value} Isolation Width:') + + if reaction: + selected_ion_mz = calculate_selected_ion_mz(reaction, monoisotopic_mz, isolation_width) + mgf_file.write(f'PEPMASS={selected_ion_mz}\n') + + # Charge + if charge: + # Scan polarity + polarity = '+' if scan_filter.polarity == PolarityType.Positive else '-' + mgf_file.write(f'CHARGE={charge}{polarity}\n') + + if not DISABLE_NATIVE_PEAK_SEARCHING: + # Check if the scan has a centroid stream + if scan.has_centroid_stream: + masses = scan.centroid_scan.masses + intensities = scan.centroid_scan.intensities + else: # Otherwise take segmented (low res) scan data + segmented_scan = Scan.to_centroid(scan) if scan_event.scan_data == ScanDataType.Profile else scan.segmented_scan + masses = segmented_scan.positions + intensities = segmented_scan.intensities + else: # Use the segmented data as is + masses = scan.segmented_scan.positions + intensities = scan.segmented_scan.intensities + + if masses and len(masses): + masses, intensities = [l for l in zip(*sorted(zip(masses, intensities)))] + + for i in range(len(masses)): + mgf_file.write(f'{masses[i]:.5f} {intensities[i]:.3f}\n') + + mgf_file.write('END IONS\n') + +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","examples/raw_file_reader_example.py",".py","25617","566",""""""" +A Python example program showing how to use RAWFileReader. More information on the RAWFileReader methods used +in this example and the other methods available in RAWFileReader can be found in the RAWFileReader user +documentation, that is installed with the RAWFileReader software. +This program has been tested with RAWFileReader 4.0.22 Changes maybe necessary with other versions +of RAWFileReader. +"""""" + +import sys +import os +import traceback +from typing import List +from fisher_py.raw_file_reader import RawFileReaderAdapter, RawFileAccess +from fisher_py.data.business import GenericDataTypes, ChromatogramTraceSettings, TraceType, ChromatogramSignal, SpectrumPacketType, Scan +from fisher_py.data.filter_enums import MsOrderType +from fisher_py.data import Device, ToleranceUnits +from fisher_py.mass_precision_estimator import PrecisionEstimate + + +class InclusionListItem(object): + """""" + The object used to store the inclusion/exclusion list items. + """""" + def __init__(self, descriptor: str, mass: float, threshold: float): + self.descriptor = descriptor + self.mass = mass + self.threshold = threshold + self.scan_number = 0 + + +def list_trailer_extra_fields(raw_file: RawFileAccess): + """""" + Reads and reports the trailer extra data fields present in the RAW file. + """""" + # Get the Trailer Extra data fields present in the RAW file + trailer_fields = raw_file.get_trailer_extra_header_information() + + # Display each value + i = 0 + print('Trailer Extra Data Information:') + + for field in trailer_fields: + print(f' Field {i} = {field.label} storing data of type {field.data_type}') + i += 1 + print('') + + +def list_status_log(raw_file: RawFileAccess, start_scan: int, end_scan: int): + """""" + Reads and reports the status log data fields present in the RAW file. + """""" + # Get the status log header information + status_log = raw_file.get_status_log_header_information() + + # Display each value that is part of the status log. They are stored as label/data type pairs + i = 0 + print('Status Log Information:') + + for field in status_log: + if field.label is not None and field != '' and field.data_type != GenericDataTypes.NULL: + print(f' Field {i} = {field.label} storing data of type {field.data_type}') + i += 1 + print('') + + # Display the value for item 10 in the status log for each scan + print('Status Information for item 10:') + + for scan in range(start_scan, end_scan): + # Get the status log for this scan + time = raw_file.retention_time_from_scan_number(scan) + log_entry = raw_file.get_status_log_for_retention_time(time) + + # Print the values for one item + print(f' Scan {scan} = {log_entry.values[10]}') + print('') + + +def get_inclusion_exclusion_list(raw_file: RawFileAccess, mass_tolerance: float) -> List[InclusionListItem]: + """""" + Reads the inclusion/exclusion list from the mass spectrometer method in the RAW file + """""" + # Select the MS instrument + raw_file.select_instrument(Device.MS, 1) + + # Get the instrument method item(s) and look for the inclusion/exclusion list + # which will be flagged by the ""Mass List Table"" + inclusion_strings = list() + + for i in range(raw_file.instrument_methods_count): + method_text = raw_file.get_instrument_method(i) + if method_text is not None and 'Mass List Table' in method_text: + save_line = False + split_method = method_text.split('\n') + + for line in split_method: + if 'Mass List Table' in line: + save_line = True + elif 'End Mass List Table' in line: + save_line = False + elif save_line: + inclusion_strings.append(line) + + # Create the inclusion/exclusion list + inclusion_list = list() + + # Convert each line from the inclusion/exclusion mass table into InclusionListItem objects + # and add them to the inclusion/exclusion list. + for line in inclusion_strings: + # Skip the title line + if 'CompoundName' in line: + continue + + # Split the line into its separate fields + fields = line.split('|') + + if len(fields) == 4: + inclusion_list.append(InclusionListItem(*fields)) + + # Get the actual scan number for each mass in the inclusion list + for scan in range(raw_file.run_header_ex.first_spectrum, raw_file.run_header_ex.last_spectrum): + # Get the scan filter and event for this scan number + scan_filter = raw_file.get_filter_for_scan_number(scan) + scan_event = raw_file.get_scan_event_for_scan_number(scan) + + # Only consider MS2 scans when looking for the spectrum corr3e + if scan_filter.ms_order == MsOrderType.Ms2: + # Get the reaction information in order to get the precursor mass for this spectrum + reaction = scan_event.get_reaction(0) + precursor_mass = reaction.precursor_mass + tolerance = precursor_mass * mass_tolerance + + for item in inclusion_list: + if item.mass >= precursor_mass - tolerance and item.mass <= precursor_mass + tolerance: + item.scan_numer = scan + break + + return inclusion_list + + +def get_chromatogram(raw_file: RawFileAccess, start_scan: int, end_scan: int, output_data: bool): + """""" + Reads the base peak chromatogram for the RAW file + """""" + # Define the settings for getting the Base Peak chromatogram + settings = ChromatogramTraceSettings(TraceType.BasePeak) + + # Get the chromatogram from the RAW file. + data = raw_file.get_chromatogram_data([settings], start_scan, end_scan) + + # Split the data into the chromatograms + trace = ChromatogramSignal.from_chromatogram_data(data) + + if trace[0].length > 0: + # Print the chromatogram data (time, intensity values) + print(f'Base Peak chromatogram ({trace[0].length} points)') + + if output_data: + for i in range(trace[0].length): + print(f' {i} - {trace[0].times[i]}, {trace[0].intensities[i]}') + print('') + + +def read_scan_information(raw_file: RawFileAccess, first_scan_number: int, last_scan_number: int, output_data: bool): + """""" + Reads the general scan information for each scan in the RAW file using the scan filter object and also the + trailer extra data section for that same scan. + """""" + # Read each scan in the RAW File + for scan in range(first_scan_number, last_scan_number+1): + # Get the retention time for this scan number. This is one of two comparable functions that will + # convert between retention time and scan number. + time = raw_file.retention_time_from_scan_number(scan) + + # Get the scan filter for this scan number + # NOTE: A scan filter can also be created from the filter string using the GetFilterFromString in the + # RawFileAccess. + scan_filter = raw_file.get_filter_for_scan_number(scan) + + # Get the scan event for this scan number + scan_event = raw_file.get_scan_event_for_scan_number(scan) + + # Get the ionizationMode, MS2 precursor mass, collision energy, and isolation width for each scan + if scan_filter.ms_order == MsOrderType.Ms2: + # Get the reaction information for the first precursor + reaction = scan_event.get_reaction(0) + + precursor_mass = reaction.precursor_mass + collision_energy = reaction.collision_energy + isolation_width = reaction.isolation_width + monoisotopic_mass = 0.0 + master_scan = 0 + ionization_mode = scan_filter.ionization_mode + order = scan_filter.ms_order + + # Get the trailer extra data for this scan and then look for the monoisotopic m/z value in the + # trailer extra data list + trailer_data = raw_file.get_trailer_extra_information(scan) + + for i in range(trailer_data.length): + if trailer_data.labels[i] == 'Monoisotopic M/Z:': + monoisotopic_mass = float(trailer_data.values[i]) + if trailer_data.labels[i] == 'Master Scan Number:' or trailer_data.labels[i] == 'Master Index:': + master_scan = int(trailer_data.values[i]) + + if output_data: + print(f'Scan number {scan} @ time {time} - Master scan = {master_scan}, Ionization mode={ionization_mode}, MS Order={order}, Precursor mass={precursor_mass}, Monoisotopic Mass = {monoisotopic_mass}, Collision energy={collision_energy}, Isolation width={isolation_width}') + elif scan_filter.ms_order == MsOrderType.Ms: + scan_dependents = raw_file.get_scan_dependents(scan, 5) + if scan_dependents is not None: + print(f'Scan number {scan} @ time {time} - Instrument type={scan_dependents.raw_file_instrument_type}, Number dependent scans={len(scan_dependents.scan_dependent_detail_array)}') + + +def get_spectrum(raw_file: RawFileAccess, scan_number: int, output_data: bool): + """""" + Gets the spectrum from the RAW file. + """""" + # Get the scan statistics from the RAW file for this scan number + scan_statistics = raw_file.get_scan_stats_for_scan_number(scan_number) + + # Check to see if the scan has centroid data or profile data. Depending upon the + # type of data, different methods will be used to read the data. While the ReadAllSpectra + # method demonstrates reading the data using the Scan.FromFile method, generating the + # Scan object takes more time and memory to do, so that method isn't optimum. + if scan_statistics.is_centroid_scan and scan_statistics.spectrum_packet_type == SpectrumPacketType.FtCentroid: + # Get the centroid (label) data from the RAW file for this scan + centroid_stream = raw_file.get_centroid_stream(scan_number, False) + print(f'Spectrum (centroid/label) {scan_number} - {centroid_stream.length} points') + + # Print the spectral data (mass, intensity, charge values). Not all of the information in the high resolution centroid + # (label data) object is reported in this example. Please check the documentation for more information about what is + # available in high resolution centroid (label) data. + if output_data: + for i in range(centroid_stream.length): + print(f' {i} - {centroid_stream.masses[i]}, {centroid_stream.intensities[i]}, {centroid_stream.charges[i]}') + print('') + else: + # Get the segmented (low res and profile) scan data + segmented_scan = raw_file.get_segmented_scan_from_scan_number(scan_number, scan_statistics) + print(f'Spectrum (normal data) {scan_number} - {len(segmented_scan.positions)} points') + + # Print the spectral data (mass, intensity values) + if output_data: + for i in range(len(segmented_scan.positions)): + print(f' {i} - {segmented_scan.positions[i]}, {segmented_scan.intensities[i]}') + print('') + + +def get_average_spectrum(raw_file: RawFileAccess, first_scan_number: int, last_scan_number: int, output_data: bool): + """""" + Gets the average spectrum from the RAW file. + """""" + # Create the mass options object that will be used when averaging the scans + options = raw_file.default_mass_options() + options.tolerance_units = ToleranceUnits.ppm + options.tolerance = 5.0 + + # Get the scan filter for the first scan. This scan filter will be used to located + # scans within the given scan range of the same type + scan_filter = raw_file.get_filter_for_scan_number(first_scan_number) + + # Get the average mass spectrum for the provided scan range. In addition to getting the + # average scan using a scan range, the library also provides a similar method that takes + # a time range. + average_scan = raw_file.average_scans_in_scan_range(first_scan_number, last_scan_number, scan_filter, options) + + if average_scan.has_centroid_stream: + print(f'Average spectrum ({average_scan.centroid_scan.length} points)') + + # Print the spectral data (mass, intensity values) + if output_data: + for i in range(average_scan.centroid_scan.length): + print(f' {average_scan.centroid_scan.masses[i]} {average_scan.centroid_scan.intensities[i]}') + + # This example uses a different method to get the same average spectrum that was calculated in the + # previous portion of this method. Instead of passing the start and end scan, a list of scans will + # be passed to the GetAveragedMassSpectrum function. + scans = [1, 6, 7, 9, 11, 12, 14] + + average_scan = raw_file.average_scans(scans, options) + + if average_scan.has_centroid_stream: + print(f'Average spectrum ({average_scan.centroid_scan.length} points)') + # Print the spectral data (mass, intensity values) + if output_data: + for i in range(average_scan.centroid_scan.length): + print(f' {average_scan.centroid_scan.masses[i]} {average_scan.centroid_scan.intensities[i]}') + print('') + + +def read_all_spectra(raw_file: RawFileAccess, first_scan_number: int, last_scan_number: int, output_data: bool): + """""" + Read all spectra in the RAW file. + """""" + for scan_number in range(first_scan_number, last_scan_number + 1): + try: + # Get the scan filter for the spectrum + scan_filter = raw_file.get_filter_for_scan_number(scan_number) + + if scan_filter is None or str(scan_filter) == '': + continue + + # Get the scan from the RAW file. This method uses the Scan.FromFile method which returns a + # Scan object that contains both the segmented and centroid (label) data from an FTMS scan + # or just the segmented data in non-FTMS scans. The GetSpectrum method demonstrates an + # alternative method for reading scans. + scan = Scan.from_file(raw_file, scan_number) + + # If that scan contains FTMS data then Centroid stream will be populated so check to see if it is present. + label_size = 0 + if scan.has_centroid_stream: + label_size = scan.centroid_scan.length + + # For non-FTMS data, the preferred data will be populated + data_size = len(scan.preferred_masses) + if output_data: + print(f'Spectrum {scan_number} - {scan_filter}: normal {data_size}, label {label_size} points') + + except Exception as ex: + print(f'Error reading spectrum {scan_number} - {ex}') + + +def calculate_mass_precision(raw_file: RawFileAccess, scan_number: int): + """""" + Calculates the mass precision for a spectrum. + """""" + # Get the scan from the RAW file + scan = Scan.from_file(raw_file, scan_number) + + # Get the scan event and from the scan event get the analyzer type for this scan + scan_event = raw_file.get_scan_event_for_scan_number(scan_number) + + # Get the trailer extra data to get the ion time for this file + log_entry = raw_file.get_trailer_extra_information(scan_number) + + trailer_headings = list() + trailer_values = list() + for i in range(log_entry.length): + trailer_headings.append(log_entry.labels[i]) + trailer_values.append(log_entry.values[i]) + + # Create the mass precision estimate object + precision_estimate = PrecisionEstimate() + + # Get the ion time from the trailer extra data values + ion_time = precision_estimate.get_ion_time(scan_event.mass_analyzer, scan, trailer_headings, trailer_values) + + # Calculate the mass precision for the scan + list_results = precision_estimate.get_mass_precision_estimate(scan, scan_event.mass_analyzer, ion_time, raw_file.run_header.mass_resolution) + + # Output the mass precision results + if len(list_results) > 0: + print('Mass Precision Results:') + for result in list_results: + print(f'Mass {result.mass}, mmu = {result.mass_accuracy_in_mmu}, ppm = {result.mass_accuracy_in_ppm}') + + +def analyze_all_scans(raw_file: RawFileAccess, first_scan_number: int, last_scan_number: int): + """""" + Reads all of the scans in the RAW and looks for out of order data + """""" + # Test the preferred (normal) data and centroid (high resolution/label) data + failed_centroid = 0 + failed_preferred = 0 + + for scan_number in range(first_scan_number, last_scan_number+1): + # Get each scan from the RAW file + scan = Scan.from_file(raw_file, scan_number) + + # Check to see if the RAW file contains label (high-res) data and if it is present + # then look for any data that is out of order + if scan.has_centroid_stream: + if scan.centroid_scan.length: + current_mass = scan.centroid_scan.masses[0] + + for index in range(1, scan.centroid_scan.length): + if scan.centroid_scan.masses[index] > current_mass: + current_mass = scan.centroid_scan.masses[index] + else: + if failed_centroid == 0: + print(f'First failure: Failed in scan data at: Scan: {scan_number} Mass: {current_mass}') + failed_centroid += 1 + + # Check the normal (non-label) data in the RAW file for any out-of-order data + if len(scan.preferred_masses) > 0: + current_mass = scan.preferred_masses[0] + for index in range(1, len(scan.preferred_masses)): + if scan.preferred_masses[index] > current_mass: + current_mass = scan.preferred_masses[index] + else: + if failed_preferred == 0: + print(f'First failure: Failed in scan data at: Scan: {scan_number} Mass: {current_mass}') + failed_preferred += 1 + + # Display a message indicating if any of the scans had data that was ""out of order"" + print('') + if failed_preferred == 0 and failed_centroid == 0: + print('Analysis completed: No out of order data found') + else: + print(f'Analysis completed: Preferred data failed: {failed_preferred} Centroid data failed: {failed_centroid}') + + +if __name__ == '__main__': + # This local variables controls if certain operations are performed. Change any of them to true to read and output that + # information section from the RAW file. + analyze_scans = True#False + average_scans = False + do_calculate_mass_precision = False + do_get_chromatogram = True + do_get_inclusion_exclusion_list = True#False + get_status_log = True + get_trailer_extra = True + read_all_scans = True + do_read_scan_information = False + read_spectrum = True + + try: + # Check to see if the RAW file name was supplied as an argument to the program + filename = 'my_file.raw' + + args = sys.argv[1:] + if len(args) > 0: + filename = args[0] + + if filename == '': + print('No RAW file specified!') + sys.exit(0) + + # Check to see if the specified RAW file exists + if not os.path.exists(filename): + print(f""The file doesn't exist in the specified location - {filename}"") + sys.exit(0) + + # Create the RawFileAccess object for accessing the RAW file + raw_file = RawFileReaderAdapter.file_factory(filename) + + if not raw_file.is_open or raw_file.is_error: + print('Unable to access the RAW file using the RawFileReader class!') + sys.exit(0) + + # Check if the RAW file is being acquired + if raw_file.in_acquisition: + print(f'RAW file still being acquired - {filename}') + sys.exit(0) + + # Get the number of instruments (controllers) present in the RAW file and set the + # selected instrument to the MS instrument, first instance of it + print(f'The RAW file has data from {raw_file.instrument_count} instruments') + + raw_file.select_instrument(Device.MS, 1) + + # Get the first and last scan from the RAW file + first_scan_number = raw_file.run_header_ex.first_spectrum + last_scan_number = raw_file.run_header_ex.last_spectrum + + # get the start and end time from the RAW file + start_time = raw_file.run_header_ex.start_time + end_time = raw_file.run_header_ex.end_time + + # Get some information from the header portions of the RAW file and display that information. + # The information is general information pertaining to the RAW file. + print('General File Information:') + print(f' RAW file: {raw_file.file_name}') + #print(f' RAW file version: {raw_file.file_header.revision}') + #print(f' Creation date: {raw_file.file_header.creation_date}') + #print(f' Operator: {raw_file.file_header.who_created_id}') + print(f' Number of instruments: {raw_file.instrument_count}') + #print(f' Description: {raw_file.file_header.file_description}') + print(f' Instrument model: {raw_file.get_instrument_data().model}') + print(f' Instrument name: {raw_file.get_instrument_data().name}') + print(f' Serial number: {raw_file.get_instrument_data().serial_number}') + print(f' Software version: {raw_file.get_instrument_data().software_version}') + print(f' Firmware version: {raw_file.get_instrument_data().hardware_version}') + print(f' Units: {raw_file.get_instrument_data().units}') + print(f' Mass resolution: {raw_file.run_header_ex.mass_resolution}') + print(f' Number of scans: {raw_file.run_header_ex.spectra_count}') + print(f' Scan range: {first_scan_number} - {last_scan_number}') + print(f' Time range: {start_time} - {end_time}') + print(f' Mass range: {raw_file.run_header_ex.low_mass} - {raw_file.run_header_ex.high_mass}') + print('') + + # Get information related to the sample that was processed + print('Sample Information:') + print(f' Sample name: {raw_file.sample_information.sample_name}') + print(f' Sample id: {raw_file.sample_information.sample_id}') + print(f' Sample type: {raw_file.sample_information.sample_type}') + print(f' Sample comment: {raw_file.sample_information.comment}') + print(f' Sample vial: {raw_file.sample_information.vial}') + print(f' Sample volume: {raw_file.sample_information.sample_volume}') + print(f' Sample injection volume: {raw_file.sample_information.injection_volume}') + print(f' Sample row number: {raw_file.sample_information.row_number}') + print(f' Sample dilution factor: {raw_file.sample_information.dilution_factor}') + print('') + + # Display all of the trailer extra data fields present in the RAW file + if get_trailer_extra: + list_trailer_extra_fields(raw_file) + + # Get the status log items + if get_status_log: + list_status_log(raw_file, first_scan_number, last_scan_number) + + # Get the inclusion/exclusion list + if do_get_inclusion_exclusion_list: + inclusion_list = get_inclusion_exclusion_list(raw_file, 1e-5) + + # Output the saved inclusion/exclusion list + count = 0 + + for item in inclusion_list: + print(f' {count} - {item.descriptor}, {item.mass}, {item.threshold}, {item.scan_number}') + count += 1 + print('') + + # Get the number of filters present in the RAW file + number_filters = len(raw_file.get_filters()) + + # Get the scan filter for the first and last spectrum in the RAW file + first_filter = raw_file.get_filter_for_scan_number(first_scan_number) + last_filter = raw_file.get_filter_for_scan_number(last_scan_number) + + print('Filter Information:') + print(f' Scan filter (first scan): {str(first_filter)}') + print(f' Scan filter (last scan): {str(last_filter)}') + print(f' Total number of filters:{number_filters}') + print('') + + # Get the BasePeak chromatogram for the MS data + if do_get_chromatogram: + get_chromatogram(raw_file, first_scan_number, last_scan_number, True) + + # Read the scan information for each scan in the RAW file + if do_read_scan_information: + read_scan_information(raw_file, first_scan_number, last_scan_number, True) + + # Get a spectrum from the RAW file. + if read_spectrum: + get_spectrum(raw_file, first_scan_number, False) + + # Get a average spectrum from the RAW file for the first 15 scans in the file. + if average_scans: + get_average_spectrum(raw_file, 1, 15, True) + + # Read each spectrum + if read_all_scans: + read_all_spectra(raw_file, first_scan_number, last_scan_number, True) + + # Calculate the mass precision for a spectrum + if do_calculate_mass_precision: + calculate_mass_precision(raw_file, 1) + + # Check all of the scans for out of order data. This method isn't enabled by + # default because it is very, very time consuming. If you would like to + # call this method change the value of _analyzeScans to true. + if analyze_scans: + analyze_all_scans(raw_file, first_scan_number, last_scan_number) + + # Close (dispose) the RAW file + print('') + print(f'Closing {filename}') + raw_file.dispose() + + except Exception as e: + print(e) + print(traceback.print_exc()) + pass +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/__init__.py",".py","5227","141","import datetime +from enum import Enum +from pathlib import Path +import inspect +import requests +import os +import json + +TEST_DIR = os.path.dirname(__file__) + +def download_if_required(path: str): + """"""Downloads a file if not present in the filesystem"""""" + # do nothing if file already exists + if os.path.isfile(path): + return + + # check if there exists a .ftp file to fetch the target file + file_path = Path(path) + ftp_file_path = file_path.with_name(f'{os.path.splitext(file_path.name)[0]}.ftp') + + if not os.path.isfile(ftp_file_path): + raise FileNotFoundError(f'Unable to find either file or download source for ""{path}"".') + + # read the .ftp file + with open(ftp_file_path, 'r', encoding='utf-8') as f: + url = f.read().replace('\n', '').strip() + + # try to download missing file + result = requests.get(url) + if result.status_code != 200: + raise Exception(f'Unable to download ""{path}"" from ""{url}"".') + + with open(path, 'wb') as f: + f.write(result.content) + + +def path_for(file: str) -> str: + """"""Returns path to test data"""""" + path = os.path.join(TEST_DIR, 'data', file) + download_if_required(path) + return path + +def info_json_for(file: str) -> str: + name = os.path.splitext(os.path.split(file)[-1])[0] + return path_for(f'{name}.info.json') + + +def assert_attribute(actual, expected): + """"""Asserts that the given attribute matches the expected value"""""" + if type(expected) is dict: + keys = expected.keys() + if len(keys) == 2 and 'type' in keys and 'value' in keys: + type_name = expected['type'] + assert type(actual).__name__ == type_name, f'Expected value to have ""{type_name}"" type' + + value = expected['value'] + if type_name == 'datetime': + value = datetime.datetime.fromisoformat(value) + elif isinstance(actual, Enum): + actual = actual.value + + assert actual == value, f'Expected value to be ""{value}""' + else: + for attribute_name, attribute_value in expected.items(): + assert hasattr(actual, attribute_name), f'Expected attribute ""{attribute_name}""' + assert_attribute(getattr(actual, attribute_name), attribute_value) + elif isinstance(expected, list): + assert isinstance(actual, list), 'Expected value to be list' + assert len(actual) == len(expected), f'Expected list value to have length {len(expected)}' + + for expected_item, actual_item in zip(expected, actual): + assert_attribute(actual_item, expected_item) + elif type(expected) is float: + assert type(actual) is float, f'Expected value to be float' + assert abs(actual - expected) < 1e-9 + else: + assert actual == expected, f'Expected value to be ""{expected}""' + +def assert_attributes(access, path: str): + """"""Asserts object attributes against *.info.json file."""""" + + # load info json for .raw file + info_json_path = info_json_for(access.file_name) + + if not os.path.isfile(info_json_path): + raise FileNotFoundError(f'The info.json file ""{info_json_path}"" does not exist.') + + with open(info_json_path, 'r', encoding='utf-8') as f: + info_json = json.load(f) + + # locate node of interest in info json + path_parts = path.split('.') if '.' in path else [path] + expected_node = info_json + actual_node = access + for attr in path_parts: + expected_node = expected_node[attr] + actual_node = getattr(actual_node, attr) + + assert_attribute(actual_node, expected_node) + +def capture_attribute_as_dict(access, path: str): + """"""Capture object attribute and output to dictionary"""""" + + # locate node of interest in info json + path_parts = path.split('.') if '.' in path else [path] + node = access + for attr in path_parts: + node = getattr(node, attr) + + # generate dictionary + capture = dict() + for attribute_name, attribute_value in inspect.getmembers(node): + if attribute_name.startswith('_'): + continue + + if type(attribute_value) is dict: + capture[attribute_name] = capture_attribute_as_dict(attribute_value) + elif type(attribute_value) is list: + list_value = list() + for item in attribute_value: + if type(item) is dict: + list_value.append(capture_attribute_as_dict(item)) + else: + list_value.append(item) + capture[attribute_name] = list_value + elif isinstance(attribute_value, Enum): + capture[attribute_name] = { 'type': type(attribute_value).__name__, 'value': attribute_value.value } + elif type(attribute_value) is datetime.datetime: + capture[attribute_name] = { 'type': 'datetime', 'value': str(attribute_value) } + elif type(attribute_value).__name__ == 'method': + continue + else: + capture[attribute_name] = attribute_value + + return capture + +def capture_attribute(access, path: str): + """"""Capture object attribute and output to console"""""" + capture = capture_attribute_as_dict(access, path) + print(json.dumps(capture, indent=4)) + ","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/test_raw_file.py",".py","3956","101"," +from fisher_py.exceptions.raw_file_exception import RawFileException +from fisher_py.raw_file import RawFile +from tests import path_for + +TEST_FILE = 'Angiotensin_325-CID.raw' +PRECURSOR_MZ = 325 +TOLERANCE = 1e-6 +TIMES = [0.00213759, 0.00539962, 0.00867493, 0.01190376, 0.01514103, 0.0183659 , 0.02165696, 0.02493226, 0.02813163, 0.0314831] + +def test_raw_file_initialization_fails_on_nonexisting_path(): + try: + RawFile('non-existent.raw') + assert False, 'Expected error when trying to load nonexistent file' + except FileNotFoundError: + pass + +def test_raw_file_initialization_fails_on_invalid_file(): + try: + RawFile(path_for('invalid.raw')) + assert False, 'Expected error when trying to load invalid file' + except RawFileException: + pass + +def test_raw_file_initialization_succeeds_on_valid_file(): + RawFile(path_for(TEST_FILE)) + +def test_raw_file_number_of_scans_matches_expected_value(): + file = RawFile(path_for(TEST_FILE)) + assert file.number_of_scans == 10 + +def test_raw_file_first_scan_matches_expected_value(): + file = RawFile(path_for(TEST_FILE)) + assert file.first_scan == 1 + +def test_raw_file_last_scan_matches_expected_value(): + file = RawFile(path_for(TEST_FILE)) + assert file.last_scan == 10 + +def test_raw_file_total_time_min_matches_expected_value(): + file = RawFile(path_for(TEST_FILE)) + assert abs(file.total_time_min - 0.031483095733333334) < TOLERANCE + +def test_raw_file_ms2_filter_masses_matches_expected_value(): + file = RawFile(path_for(TEST_FILE)) + assert len(file.ms2_filter_masses) == 1 + assert abs(file.ms2_filter_masses[0] - PRECURSOR_MZ) < TOLERANCE + +def test_raw_file_chromatogram_can_be_retrieved(): + file = RawFile(path_for(TEST_FILE)) + t, c = file.get_chromatogram(PRECURSOR_MZ, TOLERANCE) + assert len(t) == 0 + assert len(c) == 0 + +def test_raw_file_tic_ms2_can_be_retrieved(): + file = RawFile(path_for(TEST_FILE)) + times, total_ion_current = file.get_tic_ms2(PRECURSOR_MZ, TOLERANCE) + + expected_ion_currents = [37451832.53613281, 37663065.91699219, 45855594.28125, 30816050.90820312, 41055303.14746094, 34280428.34375, 35895350.90429688, 33482430.11523438, 36745244.81738281, 35045496.85644531] + for t_actual, t_expected, tic_actual, tic_expected in zip(times, TIMES, total_ion_current, expected_ion_currents): + assert abs(t_actual - t_expected) < TOLERANCE + assert abs(tic_actual - tic_expected) < TOLERANCE + +def test_raw_file_scan_ms2_can_be_retrieved(): + file = RawFile(path_for(TEST_FILE)) + lenths = [175, 199, 163, 150, 142, 186, 174, 114, 203] + + for rt, l in zip(TIMES, lenths): + masses, charges, intensities, _ = file.get_scan_ms2(rt) + assert len(masses) == l + assert len(charges) == l + assert len(intensities) == l + +def test_raw_file_getting_scan_from_number_works_as_expected(): + file = RawFile(path_for(TEST_FILE)) + lenths = [175, 199, 163, 150, 142, 186, 174, 114, 203] + + for i, l in zip(range(1, 11), lenths): + masses, charges, intensities, _ = file.get_scan_from_scan_number(i) + assert len(masses) == l + assert len(charges) == l + assert len(intensities) == l + +def test_raw_file_getting_scan_number_from_retention_time_works_as_expected(): + file = RawFile(path_for(TEST_FILE)) + + for i, rt in enumerate(TIMES[:-1]): + sn = file.get_scan_number_from_retention_time(rt) + assert sn == i + 1 + +def test_raw_file_ms2_getting_scan_number_from_retention_time_works_as_expected(): + file = RawFile(path_for(TEST_FILE)) + + for i, rt in enumerate(TIMES[:-1]): + sn, _ = file.get_ms2_scan_number_from_retention_time(rt) + assert sn == i + 1 + +def test_raw_file_get_scan_event_str_from_scan_number_works_as_expected(): + file = RawFile(path_for(TEST_FILE)) + desc = file.get_scan_event_str_from_scan_number(1) + assert desc == 'FTMS + p ESI Full ms2 325.0000@cid35.00 [150.0000-2000.0000]'","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/conftest.py",".py","130","7","import sys +import os + +TEST_DIR = os.path.dirname(__file__) +SRC_DIR = os.path.join(TEST_DIR, '..', 'src') + +sys.path.append(SRC_DIR)","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/net_wrapping/test_wrapped_arrays.py",".py","2802","88"," +from fisher_py.net_wrapping.wrapped_net_array import WrappedNetArray +from fisher_py.utils import to_net_array +import json + +EPS = 1e-16 + +def test_wrapped_arrays_can_be_created(): + net_list = to_net_array([1, 2, 3], int) + wrapped_list = WrappedNetArray[int](net_list) + assert len(wrapped_list) == 3 + +def test_wrapped_arrays_support_floats(): + values = [6.4, 7.7, 34.23, 1e-9, 13e12] + net_list = to_net_array(values, float) + wrapped_list = WrappedNetArray[float](net_list) + + for actual, expected in zip(values, wrapped_list): + assert abs(actual - expected) < EPS, f'Expected value ""{expected}"" but actual value was ""{actual}""' + +def test_wrapped_arrays_support_strings(): + values = ['This is a string', 'another string', 'still more strings'] + net_list = to_net_array(values, str) + wrapped_list = WrappedNetArray[str](net_list) + + for actual, expected in zip(values, wrapped_list): + assert actual == expected, f'Expected value ""{expected}"" but actual value was ""{actual}""' + +def test_wrapped_arrays_can_be_serialized(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + json_str = json.dumps(wrapped_list) + assert json_str == '[3, 6, 8, 2]' + +def test_wrapped_arrays_items_cannot_be_added(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + + try: + wrapped_list.append(77) + assert False, 'Adding items should not be possible' + except NotImplementedError: + pass + +def test_wrapped_arrays_items_cannot_be_inserted(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + + try: + wrapped_list.insert(2, 77) + assert False, 'Inserting items should not be possible' + except NotImplementedError: + pass + +def test_wrapped_arrays_items_cannot_be_removed(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + + try: + wrapped_list.remove(8) + assert False, 'Removing items should not be possible' + except NotImplementedError: + pass + +def test_wrapped_arrays_cannot_be_cleared(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + + try: + wrapped_list.clear() + assert False, 'Removing items should not be possible' + except NotImplementedError: + pass + +def test_wrapped_arrays_can_use_python_indexing(): + values = [3, 6, 8, 2] + net_list = to_net_array(values, int) + wrapped_list = WrappedNetArray[int](net_list) + result = wrapped_list[1:4] + assert result[0] == 6 + assert result[1] == 8 + assert result[2] == 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/net_wrapping/test_wrapped_lists.py",".py","2644","79"," +from fisher_py.net_wrapping.wrapped_net_list import WrappedNetList +from fisher_py.utils import to_net_list +import json + +EPS = 1e-16 + +def test_wrapped_lists_can_be_created(): + net_list = to_net_list([1, 2, 3], int) + wrapped_list = WrappedNetList[int](net_list) + assert len(wrapped_list) == 3 + +def test_wrapped_lists_support_floats(): + values = [6.4, 7.7, 34.23, 1e-9, 13e12] + net_list = to_net_list(values, float) + wrapped_list = WrappedNetList[float](net_list) + + for actual, expected in zip(values, wrapped_list): + assert abs(actual - expected) < EPS, f'Expected value ""{expected}"" but actual value was ""{actual}""' + +def test_wrapped_lists_support_strings(): + values = ['This is a string', 'another string', 'still more strings'] + net_list = to_net_list(values, str) + wrapped_list = WrappedNetList[str](net_list) + + for actual, expected in zip(values, wrapped_list): + assert actual == expected, f'Expected value ""{expected}"" but actual value was ""{actual}""' + +def test_wrapped_lists_can_be_serialized(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + json_str = json.dumps(wrapped_list) + assert json_str == '[3, 6, 8, 2]' + +def test_wrapped_lists_items_can_be_added(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + wrapped_list.append(77) + wrapped_list.append(80) + assert wrapped_list[-2] == 77 + assert wrapped_list[-1] == 80 + +def test_wrapped_lists_items_can_be_inserted(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + wrapped_list.insert(1, 10) + wrapped_list.insert(-2, 7) + assert wrapped_list[1] == 10 + assert wrapped_list[3] == 7 + +def test_wrapped_lists_items_can_be_removed(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + wrapped_list.remove(8) + wrapped_list.remove(3) + assert len(wrapped_list) == len(values) - 2 + assert 8 not in wrapped_list + assert 3 not in wrapped_list + +def test_wrapped_lists_can_be_cleared(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + wrapped_list.clear() + assert len(wrapped_list) == 0 + +def test_wrapped_lists_can_use_python_indexing(): + values = [3, 6, 8, 2] + net_list = to_net_list(values, int) + wrapped_list = WrappedNetList[int](net_list) + result = wrapped_list[1:4] + assert result[0] == 6 + assert result[1] == 8 + assert result[2] == 2 +","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/raw_file_reader/test_raw_file_access.py",".py","2303","55","import pytest +from fisher_py.data.device import Device +from fisher_py.exceptions import RawFileException +from fisher_py.exceptions.raw_file_exception import NoSelectedDeviceException, NoSelectedMsDeviceException +from fisher_py.raw_file_reader import RawFileAccess +from tests import assert_attributes, path_for + +REFERENCE_RAW_FILE = 'Angiotensin_325-CID.raw' + +def test_raw_file_import_fails_for_invalid_path(): + try: + RawFileAccess('does-not-exist.raw') + assert False, 'FileNotFoundError should have been thrown' + except FileNotFoundError: + pass + +def test_raw_file_import_fails_for_invalid_file(): + try: + RawFileAccess(path_for('invalid.raw')) + assert False, 'RawFileException should have been thrown' + except RawFileException: + pass + +def test_raw_file_import_succeeds_with_valid_file(): + access = RawFileAccess(path_for(REFERENCE_RAW_FILE)) + assert access.file_error.has_error == False, 'Import should succeed' + +@pytest.mark.parametrize('attribute', ['run_header', 'run_header_ex', 'scan_events', 'status_log_plottable_data']) +def test_access_to_instrument_dependent_attributes_fails_without_instrument_selection(attribute: str): + access = RawFileAccess(path_for(REFERENCE_RAW_FILE)) + try: + getattr(access, attribute) + assert False, 'Access should fail' + except (NoSelectedDeviceException, NoSelectedMsDeviceException): + pass + +@pytest.mark.parametrize('attribute', ['file_header', 'sample_information']) +def test_attribute_available_without_instrument_selection_is_as_expected(attribute: str): + access = RawFileAccess(path_for(REFERENCE_RAW_FILE)) + assert_attributes(access, attribute) + +def test_device_selection_works(): + access = RawFileAccess(path_for(REFERENCE_RAW_FILE)) + assert access.selected_instrument.device_type == Device.none + + access.select_instrument(Device.MS, 1) + assert access.selected_instrument.device_type == Device.MS + assert access.selected_instrument.instrument_index == 1 + +@pytest.mark.parametrize('attribute', ['run_header', 'run_header_ex']) +def test_instrument_dependent_attribute_matches_expected_data(attribute: str): + access = RawFileAccess(path_for(REFERENCE_RAW_FILE)) + access.select_instrument(Device.MS, 1) + assert_attributes(access, attribute) + ","Python" +"Microbiology","ethz-institute-of-microbiology/fisher_py","tests/raw_file_reader/test_raw_file_reader_adapter.py",".py","237","7"," +from fisher_py.raw_file_reader.raw_file_reader_adapter import RawFileReaderAdapter +from tests import path_for + + +def test_raw_file_adapter_can_load_file(): + file = RawFileReaderAdapter.file_factory(path_for('Angiotensin_325-CID.raw'))","Python" +"Microbiology","phac-nml/rebar","src/lib.rs",".rs","166","11","pub mod cli; +pub mod dataset; +pub mod export; +pub mod phylogeny; +pub mod plot; +pub mod recombination; +pub mod run; +pub mod sequence; +pub mod simulate; +pub mod utils; +","Rust" +"Microbiology","phac-nml/rebar","src/main.rs",".rs","1315","42","use clap::Parser; +use color_eyre::eyre::{Report, Result}; +use rebar::cli::{dataset, Cli, Command}; + +#[tokio::main] +async fn main() -> Result<(), Report> { + // ------------------------------------------------------------------------ + // CLI Setup + + // Parse CLI parameters + let args = Cli::parse(); + + // initialize color_eyre crate for colorized logs + color_eyre::install()?; + + // Set logging/verbosity level via RUST_LOG + std::env::set_var(""RUST_LOG"", args.verbosity.to_string()); + //std::env::set_var(""RUST_LOG_COLOR"", ""auto"".to_string()); + + // initialize env_logger crate for logging/verbosity level + env_logger::init(); + + // check which CLI command we're running (dataset, run, plot) + match args.command { + // Dataset + Command::Dataset(args) => match args.command { + dataset::Command::List(args) => rebar::dataset::list::datasets(&args)?, + dataset::Command::Download(mut args) => { + rebar::dataset::download::dataset(&mut args).await? + } + }, + // Run + Command::Run(mut args) => rebar::run::run(&mut args)?, + // Plot + Command::Plot(args) => rebar::plot::plot(&args)?, + // Simulate + Command::Simulate(args) => rebar::simulate::simulate(&args)?, + } + + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/mod.rs",".rs","1789","64","pub mod dataset; +pub mod plot; +pub mod run; +pub mod simulate; + +use clap::{Parser, Subcommand, ValueEnum}; +use serde::Serialize; +use std::default::Default; + +// ---------------------------------------------------------------------------- +// CLI Entry Point +// ---------------------------------------------------------------------------- + +/// Rebar command-line interface (CLI) +#[derive(Parser, Debug)] +#[clap(name = ""rebar"", trailing_var_arg = true)] +#[clap(author, version)] +#[clap(verbatim_doc_comment)] +pub struct Cli { + #[clap(subcommand)] + // rebar command (dataset, run, help) + pub command: Command, + + // ------------------------------------------------------------------------ + // Global Options + /// Control output verbosity level. + #[clap(short = 'v', long)] + #[clap(value_enum, default_value_t = Verbosity::default())] + #[clap(hide_possible_values = false)] + #[clap(global = true)] + pub verbosity: Verbosity, +} + +/// Rebar CLI commands (dataset, run, plot). +#[derive(Subcommand, Debug)] +#[clap(verbatim_doc_comment)] +pub enum Command { + Dataset(Box), + Run(Box), + Plot(Box), + Simulate(Box), +} + +// ----------------------------------------------------------------------------- +// Verbosity +// ----------------------------------------------------------------------------- + +#[derive(Clone, Debug, Default, Serialize, ValueEnum)] +pub enum Verbosity { + #[default] + Info, + Warn, + Debug, + Error, +} + +impl std::fmt::Display for Verbosity { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + // Convert to lowercase for RUST_LOG env var compatibility + let lowercase = format!(""{:?}"", self).to_lowercase(); + write!(f, ""{lowercase}"") + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/simulate.rs",".rs","1121","48","use clap::Parser; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// Simulate recombination. +#[derive(Clone, Debug, Deserialize, Parser, Serialize)] +#[clap(verbatim_doc_comment)] +pub struct Args { + /// Dataset directory. + #[clap(short = 'd', long, required = true)] + pub dataset_dir: PathBuf, + + /// Simulate recombination between these parents. + /// + /// 5' -> 3' + #[arg(long, value_delimiter = ',', required = true)] + pub parents: Vec, + + /// Specify the breakpoints. + /// + /// If not provided, will be random. + #[arg(long, value_delimiter = ',')] + pub breakpoints: Option>, + + /// Output directory. + /// + /// If the directory does not exist, it will be created. + #[clap(short = 'o', long, required = true)] + pub output_dir: PathBuf, +} + +impl Default for Args { + fn default() -> Self { + Self::new() + } +} + +impl Args { + pub fn new() -> Self { + Args { + breakpoints: None, + dataset_dir: PathBuf::new(), + output_dir: PathBuf::new(), + parents: Vec::new(), + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/run.rs",".rs","6782","225","use clap::{Args as ClapArgs, Parser}; +use color_eyre::eyre::{Report, Result, WrapErr}; +use either::*; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// Detect recombination in a dataset population and/or input alignment. +#[derive(Clone, Debug, Deserialize, Parser, Serialize)] +#[clap(verbatim_doc_comment)] +pub struct Args { + /// Dataset directory. + #[clap(short = 'd', long, required = true)] + #[serde( + skip_serializing_if = ""Args::is_default_dataset_dir"", + skip_deserializing + )] + pub dataset_dir: PathBuf, + + #[command(flatten)] + #[serde(skip_serializing_if = ""Args::is_default_input"", skip_deserializing)] + pub input: Input, + + // Hidden attribute, will be used for edge cases. + #[arg(hide = true)] + pub population: Option, + + /// Restrict parent search to just these candidate parents. + #[arg(long, value_delimiter = ',')] + pub parents: Option>, + + /// Remove these populations from the dataset. + /// + /// Regardless of whether you use '*' or not, all descendants of the + /// specified populations will be removed. + #[arg(short = 'k', long)] + pub knockout: Option>, + + /// Number of bases to mask at the 5' and 3' ends. + /// + /// Comma separated. Use --mask 0,0 to disable masking. + #[arg(short = 'm', long, default_values_t = Args::default().mask)] + #[arg(long, value_delimiter = ',')] + pub mask: Vec, + + /// Maximum number of search iterations to find each parent. + #[arg(short = 'i', long, default_value_t = Args::default().max_iter)] + pub max_iter: usize, + + /// Maximum number of parents. + #[arg(long, default_value_t = Args::default().max_parents)] + pub max_parents: usize, + + /// Minimum number of parents. + #[arg(long, default_value_t = Args::default().min_parents)] + pub min_parents: usize, + + /// Minimum number of consecutive bases in a parental region. + #[arg(short = 'c', long, default_value_t = Args::default().min_consecutive)] + pub min_consecutive: usize, + + /// Minimum length of a parental region. + #[arg(short = 'l', long, default_value_t = Args::default().min_length)] + pub min_length: usize, + + /// Minimum number of substitutions in a parental region. + #[arg(short = 's', long, default_value_t = Args::default().min_subs)] + pub min_subs: usize, + + /// Run a naive search, which does not use information about edge cases or known recombinant parents. + #[arg(short = 'u', long, default_value_t = Args::default().naive)] + pub naive: bool, + + /// Output directory. + /// + /// If the directory does not exist, it will be created. + #[clap(short = 'o', long, required = true)] + #[serde( + skip_serializing_if = ""Args::is_default_output_dir"", + skip_deserializing + )] + pub output_dir: PathBuf, + + /// Number of CPU threads to use. + #[clap(short = 't', long, default_value_t = Args::default().threads)] + #[serde(skip)] + pub threads: usize, +} + +impl Default for Args { + fn default() -> Self { + Args { + dataset_dir: PathBuf::new(), + input: Input::default(), + knockout: None, + mask: vec![100, 200], + max_iter: 3, + min_parents: 2, + max_parents: 2, + min_consecutive: 3, + min_length: 500, + min_subs: 1, + naive: false, + output_dir: PathBuf::new(), + parents: None, + population: None, + threads: 1, + } + } +} + +impl Args { + pub fn new() -> Self { + Args { + dataset_dir: PathBuf::new(), + input: Input::default(), + knockout: None, + mask: vec![0, 0], + max_iter: 0, + min_parents: 0, + max_parents: 0, + min_consecutive: 0, + min_length: 0, + min_subs: 0, + output_dir: PathBuf::new(), + parents: None, + population: None, + threads: 0, + naive: false, + } + } + + /// Check if input is default. + pub fn is_default_dataset_dir(path: &Path) -> bool { + path == Args::default().dataset_dir + } + + /// Check if input is default. + pub fn is_default_input(input: &Input) -> bool { + input == &Args::default().input + } + /// Check if output directory is default. + pub fn is_default_output_dir(path: &Path) -> bool { + path == Args::default().output_dir + } + + /// Override Args for edge case handling of particular recombinants. + pub fn apply_edge_case(&self, new: &Args) -> Result { + let mut output = self.clone(); + + output.max_iter = new.max_iter; + output.max_parents = new.max_parents; + output.min_consecutive = new.min_consecutive; + output.min_length = new.min_length; + output.min_subs = new.min_subs; + output.parents = new.parents.clone(); + output.naive = new.naive; + + Ok(output) + } + + /// Read args from file. + /// + /// Returns an Either with options: + /// Left: Args + /// Right: Vec + pub fn read(path: &Path, multiple: bool) -> Result>, Report> { + let input = std::fs::read_to_string(path) + .wrap_err_with(|| format!(""Failed to read file: {path:?}.""))?; + let output: Vec = serde_json::from_str(&input) + .wrap_err_with(|| format!(""Failed to parse file: {path:?}""))?; + + if multiple { + Ok(Right(output)) + } else { + Ok(Left(output[0].clone())) + } + } + + /// Write args to file. + pub fn write(args: &[Args], path: &Path) -> Result<(), Report> { + // create file + let mut file = File::create(path) + .wrap_err_with(|| format!(""Failed to create file: {path:?}""))?; + + // parse to string + let args = serde_json::to_string_pretty(args) + .wrap_err_with(|| format!(""Failed to parse: {args:?}""))?; + + // write to file + file.write_all(format!(""{}\n"", args).as_bytes()) + .wrap_err_with(|| format!(""Failed to write file: {path:?}""))?; + + Ok(()) + } +} + +#[derive(ClapArgs, Clone, Debug, Deserialize, Serialize, PartialEq)] +#[group(required = true, multiple = true)] +pub struct Input { + /// Input fasta alignment. + #[arg(long, value_delimiter = ',')] + pub populations: Option>, + + /// Input dataset population. + #[arg(long)] + pub alignment: Option, +} + +impl Default for Input { + fn default() -> Self { + Self::new() + } +} + +impl Input { + pub fn new() -> Self { + Input { + populations: None, + alignment: None, + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/plot.rs",".rs","1525","55","use clap::Parser; +use std::path::PathBuf; + +/// Plot recombination from 'run' output. +#[derive(Clone, Debug, Parser)] +#[clap(verbatim_doc_comment)] +pub struct Args { + /// Output directory from rebar run. + /// + /// Will plot all TSV files under barcodes/ + #[clap(short = 'r', long, required = true)] + pub run_dir: PathBuf, + + /// A single barcodes TSV file to plot. + #[clap(short = 'b', long)] + pub barcodes_file: Option, + + /// Dataset genome annotations. + #[clap(short = 'a', long)] + pub annotations: Option, + + /// Output directory for plots. + /// + /// Otherwise will default to 'plots/' under the --run-dir + #[clap(short = 'o', long)] + pub output_dir: Option, + + /// Draw all coordinates in barcodes file. + /// + /// By default, rebar wil only draw coordinates where the parent populations have different bases. + /// As a result, private mutations at these coordinates will not be visualized. + /// This flag will forcibly draw all coordinates in the barcodes file, but be warned, depending on + /// the genome size and number of samples, this may cause a crash. + #[clap(short = 'p', long)] + pub all_coords: bool, +} + +impl Default for Args { + fn default() -> Self { + Self::new() + } +} + +impl Args { + pub fn new() -> Self { + Args { + annotations: None, + run_dir: PathBuf::new(), + barcodes_file: None, + output_dir: None, + all_coords: false, + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/dataset/mod.rs",".rs","436","24","pub mod download; +pub mod list; + +use clap::{Parser, Subcommand}; + +/// List or download datasets. +#[derive(Parser, Debug)] +#[clap(verbatim_doc_comment)] +pub struct Args { + #[clap(subcommand)] + pub command: Command, +} + +/// List or download datasets. +#[derive(Subcommand, Debug)] +#[clap(verbatim_doc_comment)] +pub enum Command { + /// List datasets. + List(list::Args), + + /// Download dataset. + Download(download::Args), +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/dataset/list.rs",".rs","330","15","use crate::dataset::attributes::Name; +use clap::Parser; + +// ----------------------------------------------------------------------------- +// Dataset List + +/// List datasets. +#[derive(Parser, Debug)] +#[clap(verbatim_doc_comment)] +pub struct Args { + /// Dataset name. + #[clap(short = 'n', long)] + pub name: Option, +} +","Rust" +"Microbiology","phac-nml/rebar","src/cli/dataset/download.rs",".rs","720","29","use crate::dataset::attributes::{Name, Tag}; +use clap::Parser; +use std::path::PathBuf; + +/// Download dataset. +#[derive(Parser, Debug)] +#[clap(verbatim_doc_comment)] +pub struct Args { + /// Dataset name. + #[clap(short = 'r', long, required = true)] + pub name: Name, + + /// Dataset tag. + /// + /// A date (YYYY-MM-DD), or 'nightly', or 'custom' + #[clap(short = 't', long, required = true)] + pub tag: Tag, + + /// Output directory. + /// + /// If the directory does not exist, it will be created. + #[clap(short = 'o', long, required = true)] + pub output_dir: PathBuf, + + /// Download dataset from a summary.json snapshot. + #[clap(short = 's', long)] + pub summary: Option, +} +","Rust" +"Microbiology","phac-nml/rebar","src/utils/mod.rs",".rs","9260","273","pub mod remote_file; +pub mod table; + +use crate::dataset::attributes::Tag; +use crate::utils::remote_file::RemoteFile; +use chrono::prelude::*; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use color_eyre::Help; +use itertools::Itertools; +use log::{debug, warn}; +use reqwest::header::{ACCESS_CONTROL_EXPOSE_HEADERS, USER_AGENT}; +use std::collections::BTreeMap; +use std::fs::{remove_file, write, File}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use tempfile::TempDir; +//use zip::ZipArchive; +use zstd::stream::read::Decoder; + +/// Download file from url to path, with optional decompression. +pub async fn download_file( + url: &str, + output_path: &Path, + decompress: bool, +) -> Result<(), Report> { + let ext = Path::new(&url).extension().unwrap().to_str().unwrap(); + + let response = reqwest::get(url).await?; + if response.status() != 200 { + return Err(eyre!( + ""Unable to download file: {url}\nStatus code {}."", + response.status() + )); + } + + if decompress { + // Write bytes to a tmp file + let tmp_dir = TempDir::new()?; + let tmp_path = PathBuf::from(tmp_dir.path()).join(format!(""tmpfile.{ext}"")); + let content = response.bytes().await?; + write(&tmp_path, content) + .wrap_err_with(|| eyre!(""Unable to write file: {tmp_path:?}""))?; + decompress_file(&tmp_path, output_path, true)?; + } else { + let content = response.text().await?; + write(output_path, content) + .wrap_err_with(|| eyre!(""Unable to write file: {output_path:?}""))?; + } + + Ok(()) +} + +pub fn check_github_response(response: &reqwest::Response) -> Result<(), Report> { + let url = response.url().to_string(); + + if !response.status().is_success() { + // -------------------------------------------------------------------- + // Check if the API rate limit was exceeded + + // todo!() this is some pretty risky unwrapping here + let rate_limit_remaining: u32 = response + .headers() + .get(""x-ratelimit-remaining"") + .unwrap() + .to_str()? + .parse() + .unwrap(); + if rate_limit_remaining == 0 { + let rate_limit_reset: i64 = response + .headers() + .get(""x-ratelimit-reset"") + .unwrap() + .to_str()? + .parse() + .unwrap(); + let rate_limit_reset: DateTime = + DateTime::::from_timestamp(rate_limit_reset, 0) + .expect(""invalid timestamp"") + .into(); + + return Err( + eyre!(""GitHub API rate limit has been exceeded."") + .suggestion(format!(""Please wait for the rate limit to reset at: {rate_limit_reset:?}"")) + .suggestion(""Alternatively, set the environment variables GITHUB_USERNAME and GITHUB_TOKEN."") + .suggestion(""https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens"") + ); + } + // -------------------------------------------------------------------- + // Other unhandled errors + else { + return Err(eyre!( + ""GitHub query had status code {status}: {url}"", + status = response.status() + )); + } + } + + Ok(()) +} + +/// Query and download files using the GitHub API +pub async fn download_github( + repo: &str, + tag: &Tag, + remote_path: &str, + output_path: &Path, + sha: &Option, +) -> Result { + // GitHub API Setup + let github_token: Option = std::env::var(""GITHUB_TOKEN"").ok(); + let github_username = std::env::var(""GITHUB_USERNAME"").unwrap_or("""".to_string()); + let github_api_version = ""2022-11-28""; + let user_agent = format!(""{} {}"", env!(""CARGO_PKG_NAME""), env!(""CARGO_PKG_VERSION"")); + let client = reqwest::Client::new(); + + // GitHub API Query + let mut query = vec![(""path"", remote_path), (""per_page"", ""1""), (""page"", ""1"")]; + // if manual SHA was specified + if let Some(sha) = sha { + query.push((""sha"", sha)); + } + + // convert to string + let mut query = + query.into_iter().map(|(k, v)| (String::from(k), String::from(v))).collect_vec(); + + // Note: the reqwest::RequestBuilder doesn't implement Clone for the + // non-blocking (asynchronous) version :( we're going to have to full + // define the request over and over again. + + // -------------------------------------------------------------------------- + // STEP 1: Archive Pagination + + // Use the Archive Tag as a maximum date filter (&until=...) + if matches!(tag, Tag::Archive(_)) { + query.push((""until"".to_string(), tag.to_string())); + } + + let request = client + .get(format!(""https://api.github.com/repos/{repo}/commits"")) + .query(&query) + .header(USER_AGENT, &user_agent) + .header(ACCESS_CONTROL_EXPOSE_HEADERS, ""Link"") + .header(""X-GitHub-Api-Version"", github_api_version) + .basic_auth(&github_username, github_token.clone()); + let response = request.send().await?; + check_github_response(&response)?; + + let url = response.url().to_string(); + + // extract the ""sha"" and ""date"" key from the json body + let body: Vec> = response.json().await?; + if body.is_empty() { + return Err(eyre!(""No GitHub commits were found for: {}"", url) + .suggestion(format!( + ""Does your dataset tag ({tag}) predate the creation of this file?"" + )) + .suggestion(format!( + ""Repository: https://github.com/{repo}, File: {remote_path:?}"" + ))); + } + + let sha = body[0][""sha""].to_string().replace('""', """"); + let commit_date = body[0][""commit""][""author""][""date""].to_string().replace('""', """"); + let date_created: DateTime = DateTime::parse_from_rfc3339(&commit_date)?.into(); + + // -------------------------------------------------------------------------- + // STEP 2: DOWNLOAD + + let download_url = + format!(""https://raw.githubusercontent.com/{repo}/{sha}/{remote_path}""); + + // Identify decompression mode + // TBD! todo!() make this an enum of implemented decompression types + let ext = path_to_ext(Path::new(&download_url))?; + let decompress = ext == ""zst""; + + // Download the file + debug!(""Downloading file: {download_url} to {output_path:?}""); + download_file(&download_url, output_path, decompress).await?; + + // Store all the information about the remote file for the dataset summary + let remote_file = RemoteFile { + url: download_url, + sha, + local_path: output_path.to_path_buf(), + date_created, + date_downloaded: Utc::now(), + }; + debug!(""Downloaded file: {remote_file:?}""); + + Ok(remote_file) +} + +/// Decompress file, optionally inplace +pub fn decompress_file(input: &Path, output: &Path, inplace: bool) -> Result<(), Report> { + let ext = input + .extension() + .ok_or_else(|| eyre!(""Unable to parse extension from file: {input:?}""))?; + + match ext.to_str().unwrap() { + ""zst"" => { + let reader = File::open(input)?; + let mut decoder = Decoder::new(reader)?; + let mut buffer = String::new(); + decoder.read_to_string(&mut buffer)?; + write(output, buffer) + .wrap_err(format!(""Unable to write file: {:?}"", output))?; + + if inplace { + remove_file(input)?; + } + } + // ""zip"" => { + // let file = File::open(input)?; + // let mut archive = ZipArchive::new(file)?; + // archive.extract(output) + // .wrap_err(format!(""Unable to write file: {:?}"", output))?; + // } + _ => return Err(eyre!(""Decompression for .{ext:?} is not implemented yet."")), + }; + + Ok(()) +} + +pub fn ext_to_delim(ext: &str) -> Result { + let delim = match ext { + ""tsv"" => '\t', + ""csv"" => ',', + ""txt"" => { + warn!(""File extension .txt is assumed to be tab-delimited.""); + '\t' + } + _ => { + return Err(eyre!(""Unknown file extension: {ext:?}"") + .suggestion(""Options are tsv or csv."")) + } + }; + + Ok(delim) +} + +pub fn path_to_delim(path: &Path) -> Result { + // get the path extension + let ext = path_to_ext(path)?; + + // convert extension to the expected delimiter + let delim = match ext.as_str() { + ""tsv"" => '\t', + ""csv"" => ',', + ""txt"" => { + warn!(""File extension .txt is assumed to be tab-delimited: {path:?}""); + '\t' + } + _ => { + return Err(eyre!(""Unknown file extension: {ext:?}"") + .suggestion(""Options are tsv or csv."")) + } + }; + + Ok(delim) +} + +pub fn path_to_ext(path: &Path) -> Result { + let result = path.extension(); + let ext = match result { + Some(ext) => ext.to_os_string().into_string().unwrap(), + None => return Err(eyre!(""Unable to parse extension from file: {path:?}"")), + }; + + Ok(ext) +} +","Rust" +"Microbiology","phac-nml/rebar","src/utils/remote_file.rs",".rs","707","32","use chrono::prelude::*; +use serde::{Deserialize, Serialize}; +use std::default::Default; +use std::path::PathBuf; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct RemoteFile { + pub url: String, + pub sha: String, + pub local_path: PathBuf, + pub date_created: DateTime, + pub date_downloaded: DateTime, +} + +impl Default for RemoteFile { + fn default() -> Self { + Self::new() + } +} + +impl RemoteFile { + pub fn new() -> Self { + RemoteFile { + url: String::new(), + sha: String::new(), + local_path: PathBuf::new(), + date_created: DateTime::default(), + date_downloaded: DateTime::default(), + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/utils/table.rs",".rs","5225","170","use crate::utils; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use itertools::Itertools; +use std::default::Default; +use std::fs::File; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone)] +pub struct Table { + pub headers: Vec, + pub rows: Vec>, + pub path: PathBuf, +} + +impl Default for Table { + fn default() -> Self { + Self::new() + } +} + +impl Table { + pub fn new() -> Self { + Table { + path: PathBuf::new(), + headers: Vec::new(), + rows: Vec::new(), + } + } + + pub fn read(path: &Path) -> Result { + let mut table = Table::new(); + + // lookup delimiter from file extension + let delim = utils::path_to_delim(path)?; + + // attempt to open the file path + let file = + File::open(path).wrap_err_with(|| eyre!(""Failed to read file: {path:?}""))?; + // read in the lines + let lines = BufReader::new(file).lines(); + //.map_err(|e| eyre!(e)) + //.wrap_err_with(|| eyre!(""Failed to parse file: {path:?}""))?; + + for line in lines.flatten() { + let row = line + .split(delim) + .collect_vec() + .into_iter() + .map(String::from) + .collect_vec(); + // if headers are empty, this is the first line, write headers + if table.headers.is_empty() { + table.headers = row; + } + // otherwise regular row + else { + table.rows.push(row); + } + } + + table.path = path.to_path_buf(); + + Ok(table) + } + + pub fn header_position(&self, header: &str) -> Result { + let pos = self.headers.iter().position(|h| h == header).ok_or_else(|| { + eyre!(""Column '{header}' was not found in table: {:?}."", self.path) + })?; + + Ok(pos) + } + + pub fn filter(&self, header: &str, pattern: &str) -> Result { + let mut table = Table::new(); + let header_i = self.header_position(header)?; + table.headers = self.headers.clone(); + table.rows = self + .rows + .iter() + .filter(|row| row[header_i] == pattern) + .cloned() + .collect_vec(); + Ok(table) + } + + /// write to file + pub fn write(&self, path: &Path) -> Result<(), Report> { + let mut file = File::create(path) + .wrap_err_with(|| format!(""Unable to create file: {path:?}""))?; + + // Parse line delimiter from file extension + let delim = utils::path_to_delim(path)?.to_string(); + + // write headers + let line = format!(""{}\n"", self.headers.iter().join(&delim)); + file.write_all(line.as_bytes()) + .wrap_err_with(|| format!(""Unable to write table headers: {line}""))?; + + // write regular rows + for row in &self.rows { + let line = format!(""{}\n"", row.iter().join(&delim)); + file.write_all(line.as_bytes()) + .wrap_err_with(|| format!(""Unable to write table rows: {line}""))?; + } + + Ok(()) + } + + /// Convert table to markdown format + /// + /// TBD: error handling for empty rows! + pub fn to_markdown(&self) -> Result { + // get the maximum width of each column + let col_widths = self + // iterate through columns/headers + .headers + .iter() + .enumerate() + .map(|(col_i, header)| { + self + // iterate through this column's rows, + // get max string width, +2 to add space on either side + .rows + .iter() + .map(|row| { + let cell_width = (*row[col_i]).len(); + if cell_width >= header.len() { + cell_width + 2 + } else { + header.len() + 2 + } + }) + .max() + .unwrap_or(header.len() + 2) + }) + .collect_vec(); + + let mut markdown = String::from(""|""); + // frame in between headers and rows + let mut header_frame = String::from(""|""); + + // Create the header line + for it in self.headers.iter().zip(col_widths.iter()) { + let (header, col_width) = it; + let cell = format!(""{:^width$}|"", header, width = col_width); + markdown.push_str(&cell); + + let frame = format!(""{}|"", ""-"".repeat(*col_width)); + header_frame.push_str(&frame); + } + markdown.push('\n'); + markdown.push_str(&header_frame); + markdown.push('\n'); + + // Create the row lines + for row in &self.rows { + markdown.push('|'); + for (col_i, col_width) in col_widths.iter().enumerate() { + let cell = format!(""{:^width$}|"", row[col_i], width = col_width); + markdown.push_str(&cell); + } + markdown.push('\n'); + } + + Ok(markdown) + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/recombination/mod.rs",".rs","32126","903","pub mod search; +pub mod validate; + +use crate::cli::run; +use crate::dataset::SearchResult; +use crate::sequence::{Sequence, Substitution}; +use crate::utils::table::Table; +use color_eyre::eyre::{eyre, Report, Result}; +use color_eyre::Help; +use indoc::formatdoc; +use itertools::Itertools; +use log::debug; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use strum::{EnumIter, EnumProperty}; + +// ---------------------------------------------------------------------------- +// Structs +// ---------------------------------------------------------------------------- + +// ---------------------------------------------------------------------------- +// Recombination + +#[derive(Clone, Debug, Serialize)] +pub struct Recombination<'seq> { + pub sequence: &'seq Sequence, + pub unique_key: String, + pub recombinant: Option, + pub parents: Vec, + pub breakpoints: Vec, + pub regions: BTreeMap, + pub genome_length: usize, + pub edge_case: bool, + pub hypothesis: Option, + pub support: BTreeMap>, + pub conflict_ref: BTreeMap>, + pub conflict_alt: BTreeMap>, + pub private: BTreeMap>, + pub score: BTreeMap, + #[serde(skip_serializing)] + pub table: Table, +} + +impl<'seq> Recombination<'seq> { + pub fn new(sequence: &'seq Sequence) -> Self { + Recombination { + sequence, + unique_key: String::new(), + recombinant: None, + parents: Vec::new(), + breakpoints: Vec::new(), + regions: BTreeMap::new(), + table: Table::new(), + genome_length: sequence.genome_length, + edge_case: false, + hypothesis: None, + support: BTreeMap::new(), + conflict_ref: BTreeMap::new(), + conflict_alt: BTreeMap::new(), + private: BTreeMap::new(), + score: BTreeMap::new(), + } + } + + pub fn pretty_print_parsimony(&self) -> String { + let mut score = String::new(); + let mut support = String::new(); + let mut conflict_ref = String::new(); + let mut conflict_alt = String::new(); + let mut private = String::new(); + + self.parents.iter().for_each(|pop| { + // score + let msg = format!("" - {pop}: {}\n"", &self.score[pop]); + score.push_str(&msg); + + // support + let subs = self.support.get(pop).unwrap(); + let msg = format!("" - {pop} ({}): {}\n"", subs.len(), subs.iter().join("", "")); + support.push_str(&msg); + + // conflict_ref + let subs = self.conflict_ref.get(pop).unwrap(); + let msg = format!("" - {pop} ({}): {}\n"", subs.len(), subs.iter().join("", "")); + conflict_ref.push_str(&msg); + + // conflict_alt + let subs = self.conflict_alt.get(pop).unwrap(); + let msg = format!("" - {pop} ({}): {}\n"", subs.len(), subs.iter().join("", "")); + conflict_alt.push_str(&msg); + + // private + let subs = self.private.get(pop).unwrap(); + let msg = format!("" - {pop} ({}): {}\n"", subs.len(), subs.iter().join("", "")); + private.push_str(&msg); + }); + + formatdoc!( + ""score:\n{score} + support:\n{support} + conflict_ref:\n{conflict_ref} + conflict_alt:\n{conflict_alt} + private:\n{private} + "" + ) + } + + pub fn get_substitution_origins( + &self, + best_match: &SearchResult, + ) -> Result>, Report> { + // todo!() think about if we want reversions in here or not... + let mut subs_by_origin = BTreeMap::new(); + + // recombination parents + if self.recombinant.is_some() { + self.parents.iter().for_each(|p| { + let subs = self.support.get(p).cloned().unwrap_or_default(); + subs_by_origin.insert(p.clone(), subs); + }); + } + + // consensus/best match and private + let p = &best_match.consensus_population; + + let support = best_match.support.get(p).cloned().unwrap_or_default(); + + let (best_match_subs, private_subs) = if self.recombinant.is_some() { + // Ex. XBB (XBB consensus, BJ.1 and BA.2.75 as parents) + // Ex. XBB --knockout XBB, (BJ.1 consensus, BJ.1 and BA.2.75 as parents) + // A19326G comes from parent XBB + // Ex. XBB.1 --knockout XBB.1, (XBB consensus, BJ.1 and BA.2.75 as parents) + // A19326G comes from parent XBB + // G22317T will be private (XBB.1 specific) + + // check the private recombination subs against best match + let mut private_subs = + self.private.values().flatten().sorted().cloned().collect_vec(); + let mut best_match_subs = private_subs.clone(); + best_match_subs.retain(|s| support.contains(s)); + // private subs are the remaining ones not found in best match + private_subs.retain(|s| !best_match_subs.contains(s)); + (best_match_subs, private_subs) + } else { + let best_match_subs = best_match.support.get(p).cloned().unwrap_or_default(); + let private_subs = best_match.private.clone(); + (best_match_subs, private_subs) + }; + + // best match subs, if not parent already added + if !subs_by_origin.contains_key(p) { + subs_by_origin.insert(p.clone(), best_match_subs); + } + + // private + subs_by_origin.insert(""private"".to_string(), private_subs); + + Ok(subs_by_origin) + } +} + +// ---------------------------------------------------------------------------- +// Hypthoses + +#[derive( + Clone, + Debug, + Deserialize, + Eq, + EnumIter, + EnumProperty, + Ord, + PartialOrd, + PartialEq, + Serialize, +)] +pub enum Hypothesis { + NonRecombinant, + DesignatedRecombinant, + RecursiveRecombinant, + NonRecursiveRecombinant, +} + +impl std::fmt::Display for Hypothesis { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + let hypothesis = match self { + Hypothesis::NonRecombinant => ""non_recombinant"", + Hypothesis::DesignatedRecombinant => ""designated_recombinant"", + Hypothesis::RecursiveRecombinant => ""recursive_recombinant"", + Hypothesis::NonRecursiveRecombinant => ""non_recursive_recombinant"", + }; + write!(f, ""{hypothesis}"") + } +} + +// ---------------------------------------------------------------------------- +// Breakpoint + +/// Recombination breakpoint intervals (left and right inclusive) +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Breakpoint { + pub start: usize, + pub end: usize, +} + +impl std::fmt::Display for Breakpoint { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, ""{}-{}"", self.start, self.end) + } +} + +// ---------------------------------------------------------------------------- +// Direction + +/// Genomic reading direction as forward (5' -> 3') or reverse (3' -> 5') +pub enum Direction { + Forward, + Reverse, +} + +// ---------------------------------------------------------------------------- +// Region + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[allow(dead_code)] +pub struct Region { + pub start: usize, + pub end: usize, + pub origin: String, + #[serde(skip_serializing)] + pub substitutions: Vec, +} + +impl std::fmt::Display for Region { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, ""{}-{}|{}"", self.start, self.end, self.origin) + } +} + +// ---------------------------------------------------------------------------- +// Functions +// ---------------------------------------------------------------------------- + +/// Detect recombination in a query sequence. +/// +/// +/// # Arguments +/// +/// * `sequence` | `&'seq Sequence` | Query sequence. +/// * `parents` | `&Vec` | Any known recombination parents so far. +/// * `parent_candidate` | Option<&SearchResult> | An unknown recombination parent to evaluate. +/// * `reference` | +/// * `args` | &run::Args | CLI run parameters. +/// +pub fn detect_recombination<'seq>( + sequence: &'seq Sequence, + parents: &Vec, + parent_candidate: Option<&SearchResult>, + reference: &Sequence, + args: &run::Args, +) -> Result, Report> { + let mut recombination = Recombination::new(sequence); + + // if no parent candidates were provided, just use the first parent + let parent_candidate = match parent_candidate { + Some(search_result) => search_result, + None => { + if !parents.is_empty() { + &parents[0] + } else { + return Err(eyre!( + ""No parents were provided for recombination detection."" + ) + .suggestion( + ""Please check the parents and parents_candidate variables."", + )); + } + } + }; + + // Combine previously known parents and new candidates + let mut parents = parents.clone(); + parents.push(parent_candidate.clone()); + + // -------------------------------------------------------------------- + // Init Table + // -------------------------------------------------------------------- + + // Create a table where rows are coordinates and columns are + // coord, parent, Reference, , + + let mut table = Table::new(); + table.headers = + vec![""coord"", ""origin"", ""Reference""].into_iter().map(String::from).collect_vec(); + for parent in &parents { + table.headers.push(parent.consensus_population.to_string()); + } + table.headers.push(sequence.id.to_string()); + table.rows = Vec::new(); + + // get the column position of each header, trying to avoid hard-coding + let coord_col_i = table.header_position(""coord"")?; + let origin_col_i = table.header_position(""origin"")?; + let ref_col_i = table.header_position(""Reference"")?; + let seq_col_i = table.header_position(&sequence.id)?; + + // -------------------------------------------------------------------- + // Identify Substitution Parental Origins + // -------------------------------------------------------------------- + + // Deduplicate coords (might be non-bi-allelic) + let mut coords = parents + .iter() + .flat_map(|p| p.substitutions.iter().map(|s| s.coord).collect_vec()) + .collect_vec(); + + // add sequence substitutions (to check for privates) + coords = coords + .into_iter() + .chain(sequence.substitutions.iter().map(|s| s.coord).collect_vec()) + .unique() + .sorted() + .collect_vec(); + + for coord in coords { + // init row with columns + let mut row = vec![String::new(); table.headers.len()]; + + // add coord to row + row[coord_col_i] = coord.to_string(); + + // Keep track of base diversity, if they're all the same, this + // isn't an informative/differentiating site + let mut bases = Vec::new(); + + // get Reference base directly from sequence + let ref_base = &reference.seq[coord - 1]; + row[ref_col_i] = ref_base.to_string(); + + // get Sample base directly form sequence + let seq_base = &sequence.seq[coord - 1]; + row[seq_col_i] = seq_base.to_string(); + bases.push(*seq_base); + + // init sequence base origins (could be multiple) + let mut origins = Vec::new(); + + for parent in &parents { + let parent_base = parent + .substitutions + .iter() + .filter(|sub| sub.coord == coord) + .map(|sub| sub.alt) + .next() + // Assume reference if no substitution, perhaps risky + .unwrap_or(*ref_base); + + if parent_base == *seq_base { + origins.push(parent.consensus_population.clone()); + } + + // Add bases to table + let parent_col_i = table.header_position(&parent.consensus_population)?; + row[parent_col_i] = parent_base.to_string(); + bases.push(parent_base); + } + + // Is this coord a discriminating site? + // Remove subs that are identical between all parents + bases = bases.into_iter().unique().collect(); + + // If only 1 unique parent base was found, non-discriminating + if bases.len() == 1 { + continue; + } + + // No known origins, is private mutation + if origins.is_empty() { + origins.push(""private"".to_string()); + } + // Is fully descriminating (only 1 parent matches) or private + if origins.len() == 1 { + // add origins to row + row[origin_col_i] = origins.iter().join("",""); + table.rows.push(row); + } + // Non-discriminating + // todo!() revisit this when we test >= 3 parents + else { + continue; + } + } + + let mut table_no_private = table.clone(); + table_no_private.rows.retain(|row| row[origin_col_i] != ""private""); + + // Debugging Table + debug!( + ""Recombination table:\n\n{}"", + table_no_private.to_markdown()? + ); + + // -------------------------------------------------------------------- + // Group Substitutions into Parental Regions + // -------------------------------------------------------------------- + + // First: 5' -> 3', filter separately on min_consecutive then min_length + let mut regions_5p = identify_regions(&table_no_private)?; + regions_5p = filter_regions( + ®ions_5p, + Direction::Forward, + args.min_consecutive, + 0_usize, + )?; + regions_5p = + filter_regions(®ions_5p, Direction::Forward, 0_usize, args.min_length)?; + debug!( + ""regions_5p: {}"", + serde_json::to_string(®ions_5p).unwrap() + ); + + // Second: 3' -> 5', filter separately on min_consecutive then min_length + let mut regions_3p = identify_regions(&table_no_private)?; + regions_3p = filter_regions( + ®ions_3p, + Direction::Reverse, + args.min_consecutive, + 0_usize, + )?; + regions_3p = + filter_regions(®ions_3p, Direction::Reverse, 0_usize, args.min_length)?; + debug!( + ""regions_3p: {}"", + serde_json::to_string(®ions_3p).unwrap() + ); + + // Take the intersect of the 5' and 3' regions (ie. where they both agree) + let mut regions_intersect = intersect_regions(®ions_5p, ®ions_3p)?; + // During intersection, it's possible that a region from 1 single parent + // got broken up into multiple adjacent sections. Put it through the + // filter again to collapse it. Direction doesn't matter now + regions_intersect = filter_regions( + ®ions_intersect, + Direction::Forward, + args.min_consecutive, + args.min_length, + )?; + debug!( + ""regions_intersect: {}"", + serde_json::to_string(®ions_intersect).unwrap() + ); + + // Make sure all the prev_parents + parent_candidate have at least 1 region + let region_origins = regions_intersect + .values() + .map(|region| region.origin.to_owned()) + .unique() + .collect_vec(); + + for parent in &parents { + if !region_origins.contains(&parent.consensus_population) { + return Err(eyre!( + ""No recombination detected for parent {}."", + &parent.consensus_population + )); + } + } + if !region_origins.contains(&parent_candidate.consensus_population) { + return Err(eyre!( + ""No recombination detected for parent {}."", + &parent_candidate.consensus_population + )); + } + + // -------------------------------------------------------------------- + // Minimum Substitutions Filter + // -------------------------------------------------------------------- + + // Check for the minimum number of subs from each parent + let mut uniq_subs_count: BTreeMap = BTreeMap::new(); + // first count up uniq subs by parent + for region in regions_intersect.values() { + let origin = ®ion.origin; + uniq_subs_count.entry(origin.clone()).or_insert(0); + for sub in ®ion.substitutions { + if sub.reference == sub.alt { + continue; + } + *uniq_subs_count.entry(origin.clone()).or_default() += 1; + } + } + debug!(""uniq_subs_count: {uniq_subs_count:?}""); + // check if any parent failed the filter + let mut min_subs_fail = false; + for (parent, count) in uniq_subs_count { + if count < args.min_subs { + debug!( + ""Parent {} subs ({count}) do not meet the min_subs filter ({})."", + parent, args.min_subs, + ); + min_subs_fail = true; + } + } + if min_subs_fail { + return Err(eyre!( + ""No recombination detected, min_subs filter was not satisfied by all parents."" + )); + } + + // -------------------------------------------------------------------- + // Breakpoints + // -------------------------------------------------------------------- + + let breakpoints = identify_breakpoints(®ions_intersect)?; + debug!( + ""breakpoints: {}"", + serde_json::to_string(&breakpoints).unwrap() + ); + + // -------------------------------------------------------------------- + // Update + // -------------------------------------------------------------------- + + // update all the attributes + recombination.parents = region_origins; + recombination.regions = regions_intersect; + recombination.breakpoints = breakpoints; + // pre-filter or post-filter table? + recombination.table = table; + + // compound recombination parsimony score + for pop in &recombination.parents { + // Which coordinate ranges are attributed to this parent + let coordinates = recombination + .regions + .values() + .filter(|region| ®ion.origin == pop) + .flat_map(|region| ((region.start)..=(region.end)).collect_vec()) + .collect_vec(); + + let search_result = + parents.iter().find(|r| *pop == r.consensus_population).unwrap(); + // support + let mut support = search_result.support[pop].clone(); + support.retain(|s| coordinates.contains(&s.coord)); + // conflict_alt + let mut conflict_alt = search_result.conflict_alt[pop].clone(); + conflict_alt.retain(|s| coordinates.contains(&s.coord)); + // conflict_ref + let mut conflict_ref = search_result.conflict_ref[pop].clone(); + conflict_ref.retain(|s| coordinates.contains(&s.coord)); + // private + let mut private = search_result.private.clone(); + private.retain(|s| coordinates.contains(&s.coord)); + // score + let score = support.len() as isize + - conflict_alt.len() as isize + - conflict_ref.len() as isize; + + recombination.support.insert(pop.to_owned(), support); + recombination.conflict_ref.insert(pop.to_owned(), conflict_ref); + recombination.conflict_alt.insert(pop.to_owned(), conflict_alt); + recombination.private.insert(pop.to_owned(), private); + recombination.score.insert(pop.to_owned(), score); + } + + // record the substitutions+reversions that are unresolved by any parent + + // convoluted debug message + debug!( + ""Parsimony Summary:\n{}"", + recombination.pretty_print_parsimony() + ); + + Ok(recombination) +} + +pub fn identify_regions(table: &Table) -> Result, Report> { + let mut origin_prev: Option = None; + let mut regions = BTreeMap::new(); + let mut start = 0; + + let coord_col_i = table.header_position(""coord"")?; + let origin_col_i = table.header_position(""origin"")?; + let ref_col_i = table.header_position(""Reference"")?; + // sequence for alt is last column + let seq_col_i = table.headers.len() - 1; + + for row in table.rows.iter() { + let coord = row[coord_col_i].parse::().unwrap(); + let origin = row[origin_col_i].to_string(); + let reference = row[ref_col_i].chars().next().unwrap(); + let alt = row[seq_col_i].chars().next().unwrap(); + let substitutions = vec![Substitution { + coord, + reference, + alt, + }]; + + // start of new region, either first or origin changes + if origin_prev.is_none() || origin_prev != Some(origin.clone()) { + start = coord; + let region = Region { + start, + end: coord, + origin: origin.clone(), + substitutions, + }; + regions.insert(start, region); + } + // same origin, region continues. update end and subs + else { + let region = regions.get_mut(&start).unwrap(); + region.end = coord; + region.substitutions.extend(substitutions) + } + + origin_prev = Some(origin); + } + + Ok(regions) +} + +/// Filter recombinant regions based on the length and consecutive bases. +pub fn filter_regions( + regions: &BTreeMap, + direction: Direction, + min_consecutive: usize, + min_length: usize, +) -> Result, Report> { + let mut regions_filter = BTreeMap::new(); + let mut origin_prev: Option = None; + let mut start_prev: Option = None; + + let start_coords = match direction { + Direction::Forward => regions.keys().collect::>(), + Direction::Reverse => regions.keys().rev().collect::>(), + }; + + for start in start_coords { + let region = regions.get(start).unwrap(); + let num_consecutive = region.substitutions.len(); + let region_length = (region.end - region.start) + 1; + + // start of new region, either first or origin changes + if origin_prev.is_none() || origin_prev != Some(region.origin.clone()) { + // is the new parental region long enough? + if num_consecutive >= min_consecutive && region_length >= min_length { + regions_filter.insert(region.start, region.to_owned()); + origin_prev = Some(region.origin.clone()); + start_prev = Some(region.start); + } + } + // same origin, region continues. update subs and start or end + else { + match direction { + // when going forward, we update the region + Direction::Forward => { + if let Some(start_prev) = start_prev { + let region_update = regions_filter.get_mut(&start_prev).unwrap(); + region_update.substitutions.extend(region.substitutions.clone()); + region_update.end = region.end; + } + } + // when going backward, we remove and replace regions + Direction::Reverse => { + if let Some(start_prev) = start_prev { + let mut region_new = + regions_filter.get(&start_prev).unwrap().to_owned(); + region_new.substitutions.extend(region.substitutions.clone()); + region_new.substitutions.sort(); + region_new.start = region.start; + + // remove old region from filtered map + regions_filter.remove(&start_prev); + // add new region with updated start coord + regions_filter.insert(region.start, region_new); + } + + // for reverse, update new start position + start_prev = Some(region.start); + } + } + } + } + + Ok(regions_filter) +} + +/// Find the intersect between two regions. +pub fn intersect_regions( + regions_1: &BTreeMap, + regions_2: &BTreeMap, +) -> Result, Report> { + let mut regions_intersect = BTreeMap::new(); + + for r1 in regions_1.values() { + for r2 in regions_2.values() { + // don't intersect regions of different origins + if r1.origin != r2.origin { + continue; + } + + // find the shared substitutions + let subs_intersect = r1 + .substitutions + .iter() + .filter(|sub| r2.substitutions.contains(sub)) + .map(|sub| sub.to_owned()) + .collect::>(); + + // if no shared subs, an intersection is not possible + if subs_intersect.is_empty() { + continue; + } + + // start coordinate is the min sub, end is the max sub + let start = subs_intersect.iter().min().map(|sub| sub.coord).unwrap(); + let end = subs_intersect.iter().max().map(|sub| sub.coord).unwrap(); + + let region = Region { + start, + end, + origin: r1.origin.clone(), + substitutions: subs_intersect, + }; + regions_intersect.insert(start, region); + } + } + + // Do we need to go back the other way at all? + + Ok(regions_intersect) +} + +/// Identify breakpoint intervals in recombination regions. +pub fn identify_breakpoints( + regions: &BTreeMap, +) -> Result, Report> { + let mut breakpoints: Vec = Vec::new(); + let mut end_prev: Option = None; + + for region in regions.values() { + // a breakpoint is only possible if we already found a prev region + if let Some(end_prev) = end_prev { + // breakpoint intervals are non-inclusive of regions + // but what happens if we know the precise bases... + let start = end_prev + 1; + let end = region.start - 1; + let breakpoint = if start < end { + Breakpoint { start, end } + } else { + Breakpoint { start, end: start } + }; + breakpoints.push(breakpoint); + } + + end_prev = Some(region.end); + } + + Ok(breakpoints) +} + +/// Combine recombination tables. +pub fn combine_tables( + recombinations: &[Recombination], + reference: &Sequence, +) -> Result { + // ------------------------------------------------------------------------ + // Input Checking + + // was recombination detected? + let parents = recombinations.iter().map(|rec| &rec.parents).collect_vec(); + if parents.is_empty() { + return Err(eyre!(""Cannot combine tables, no recombination detected."")); + } + + // are all parents the same? + for parent in &parents { + if parent != &parents[0] { + return Err(eyre!( + ""Cannot combine tables, not all parents are the same."" + )); + } + } + + // identify sequence IDs to combine + let sequence_ids = recombinations.iter().map(|rec| &rec.sequence.id).collect_vec(); + + // identify parents to combine, just use first, since we verified all same + let parents = recombinations.iter().map(|rec| &rec.parents).next().unwrap(); + + // ------------------------------------------------------------------------ + // Construct Table Headers + + // final result to mutate and return + let mut combine_table = Table::new(); + + // Mandatory headers + // convert to String, &str won't work here, since we're going to create + // table row values within a for loop scope later + combine_table.headers = + vec![""coord"", ""origin"", ""Reference""].into_iter().map(String::from).collect_vec(); + + // Dynamic headers (parents and sequence IDs) + for parent in parents { + combine_table.headers.push(parent.clone()) + } + for sequence_id in sequence_ids { + combine_table.headers.push(sequence_id.clone()) + } + + // get output col idx of mandatory columns + let coord_output_i = combine_table.header_position(""coord"")?; + let origin_output_i = combine_table.header_position(""origin"")?; + let ref_output_i = combine_table.header_position(""Reference"")?; + + // ------------------------------------------------------------------------ + // Combine Coordinate Bases + + // identify all coords in all samples, convert from string to numeric + // so they can be sorted nicely + let mut coords = recombinations + .iter() + .flat_map(|rec| rec.table.rows.iter().map(|row| &row[0]).collect_vec()) + .unique() + .filter(|c| c.as_str() != ""coord"") + .map(|c| c.parse::().unwrap()) + .collect_vec(); + coords.sort(); + + // combine tables, row by row (coord by coord) + for coord in &coords { + // init row with empty strings for all columns + let mut row = vec![String::new(); combine_table.headers.len()]; + // get reference base directly from sequence + let ref_base = reference.seq[coord - 1].to_string(); + row[ref_output_i] = ref_base.to_string(); + + // it's possible origins will be ambiguous, if mutation occurred after recombintation + // in that case, code as '?' + let mut origins = vec![]; + + // iterate through recombinants, identifying ref, parents, seq bases + for recombination in recombinations { + // get sequence base directly from sequence + let rec_base = recombination.sequence.seq[coord - 1].to_string(); + let rec_output_i = + combine_table.header_position(&recombination.sequence.id)?; + row[rec_output_i] = rec_base; + + // check which coords appeared in this sample + let coord_input_i = recombination.table.header_position(""coord"")?; + let rec_coords = recombination + .table + .rows + .iter() + .map(|row| row[coord_input_i].parse::().unwrap()) + .collect_vec(); + + // get table index of these coords + let row_input_i = rec_coords.iter().position(|c| c == coord); + + // if this sample has the coord + if let Some(row_input_i) = row_input_i { + // get origin of the particular sample's base + let origin_input_i = recombination.table.header_position(""origin"")?; + let origin = &recombination.table.rows[row_input_i][origin_input_i]; + origins.push(origin.to_string()); + + // if it's the first sample encountered add the coord, + // Reference base and parent bases + if row[coord_output_i] == String::new() { + // Add the coord to the output table + row[coord_output_i] = coord.to_string(); + + // Add parents bases to the output table + for parent in parents { + let parent_input_i = + recombination.table.header_position(parent)?; + let parent_output_i = combine_table.header_position(parent)?; + let parent_base = + &recombination.table.rows[row_input_i][parent_input_i]; + row[parent_output_i] = parent_base.to_string(); + } + } + } + } + + // Dedup, and summarise the origins, code as ""?"" if ambiguous + let origins = origins.into_iter().unique().collect_vec(); + if origins.len() > 1 { + row[origin_output_i] = ""?"".to_string() + } else { + row[origin_output_i] = origins[0].clone(); + } + // Add processed row to table + combine_table.rows.push(row); + } + + Ok(combine_table) +} +","Rust" +"Microbiology","phac-nml/rebar","src/recombination/search.rs",".rs","26115","627","use crate::cli::run; +use crate::dataset::{Dataset, SearchResult}; +use crate::recombination::{detect_recombination, validate, Hypothesis, Recombination}; +use crate::sequence::Sequence; +use color_eyre::eyre::{eyre, Report, Result}; +use itertools::Itertools; +use log::{debug, warn}; +use std::collections::BTreeMap; +use strum::IntoEnumIterator; + +// ---------------------------------------------------------------------------- +// Functions +// ---------------------------------------------------------------------------- + +/// Search for primary and secondary recombination parents. +/// +/// Uses a recursion_limit for safety. It is not intended to +/// run this wrapper function more than once recursively. +#[allow(clippy::needless_if)] +pub fn all_parents<'seq>( + sequence: &'seq Sequence, + dataset: &Dataset, + best_match: &mut SearchResult, + populations: &[&String], + args: &run::Args, +) -> Result, Report> { + // copy args, we don't want to modify the original global parameters + let mut args = args.clone(); + // copy search populations, we will refine these based on edge cases and + // different hypotheses concerning the mechanism of recombination + let mut populations = populations.to_vec(); + + let consensus_population = &best_match.consensus_population; + + // ------------------------------------------------------------------------ + // Edge Case + // ------------------------------------------------------------------------ + + // // Edge Cases: Manually specified in the organism's dataset. + let mut edge_case = false; + + // only apply edge cases if the user didn't request a naive search + if !args.naive { + let edge_case_search = dataset + .edge_cases + .iter() + .find(|e| e.population.as_ref() == best_match.recombinant.as_ref()); + + if let Some(edge_case_args) = edge_case_search { + debug!(""Applying edge case parameters: {edge_case_args:?}""); + edge_case = true; + args = args.apply_edge_case(edge_case_args)?; + + if let Some(parents) = &edge_case_args.parents { + let parents_expand = dataset.expand_populations(parents)?; + populations.retain(|pop| parents_expand.contains(pop)); + } + if let Some(knockout) = &edge_case_args.knockout { + let knockout = dataset.expand_populations(knockout)?; + populations.retain(|pop| !knockout.contains(pop)); + } + } + } + + // ---------------------------------------------------------------------------- + // Hypothesis Testing + // ---------------------------------------------------------------------------- + + // Store the results of our hypothesis testing + // Hyp: (Recombination, Parents, score, conflict) + let mut hypotheses: BTreeMap< + Hypothesis, + (Option, Vec, isize, usize), + > = BTreeMap::new(); + + // iterate through the potential hypotheses + for hypothesis in Hypothesis::iter() { + debug!(""Testing Hypothesis: {hypothesis:?}""); + + // ---------------------------------------------------------------------------- + // Hypothesis: Non-Recombinant + // The sequence is simply it's best match (consensus population) + // + conflict_alt mutations and + conflict_ref reversions + if hypothesis == Hypothesis::NonRecombinant { + if best_match.recombinant.is_none() { + let score = best_match.score[consensus_population]; + let conflict = best_match.conflict_alt[consensus_population].len() + + best_match.conflict_ref[consensus_population].len(); + hypotheses.insert( + Hypothesis::NonRecombinant, + (None, Vec::new(), score, conflict), + ); + } + continue; + } + + let mut hyp_populations: Vec<&String> = populations.clone(); + + // ---------------------------------------------------------------------------- + // Hypothesis: Designated Recombinant. + // The best match (consensus) population is a known recombinant (or descendant of) + // Search for parents based on the known list of parents. + + if hypothesis == Hypothesis::DesignatedRecombinant { + // skip this hypothesis if user requested naive search + if args.naive || best_match.recombinant.is_none() { + continue; + } + if let Some(recombinant) = &best_match.recombinant { + let mut designated_parents = + dataset.phylogeny.get_parents(recombinant)?; + debug!(""Designated parents: {designated_parents:?}""); + // we might not have sequence data for all designated parents. + let designated_parents_filter = designated_parents + .iter() + .filter_map(|p| dataset.get_ancestor_with_sequence(p).ok()) + .collect_vec(); + + if designated_parents != designated_parents_filter { + debug!(""Designated parents with sequence data: {designated_parents_filter:?}""); + // if the filter yielded a different length, one parent is unsearchable + if designated_parents.len() != designated_parents_filter.len() { + debug!(""DesignatedRecombinant hypothesis is impossible to test! At least one parent has no ancestor with sequence data!""); + continue; + } + designated_parents = designated_parents_filter; + } + hyp_populations.retain(|pop| designated_parents.contains(pop)); + } + } + + // ---------------------------------------------------------------------------- + // Hypothesis: Recombinant, Allow Recursion. + // One or more parent(s) are recombinants or recombinant descendants + // This is a default search, no filter edits needed + if hypothesis == Hypothesis::RecursiveRecombinant {} + + // ---------------------------------------------------------------------------- + // Hypothesis: Non Recursive Recombinant, Disallow Recursion. + // No parent(s) are recombinants or recombinant descendants + if hypothesis == Hypothesis::NonRecursiveRecombinant { + // skip this hypothesis if + if hypotheses.contains_key(&Hypothesis::NonRecursiveRecombinant) { + continue; + } + hyp_populations + .retain(|pop| !dataset.phylogeny.recombinants_all.contains(pop)); + } + + // ---------------------------------------------------------------------------- + // Hypothesis Test Time! + // Search for primary and scondary parents + + debug!(""Primary Parent Search.""); + if hyp_populations.is_empty() { + debug!(""No parent populations fit this hypothesis.""); + continue; + } + // we only need to rerun the primary parent search if the search populations + // DOES NOT contain the hyp_populations + let primary_search: Result = + if hyp_populations.contains(&&best_match.consensus_population) { + Ok(best_match.clone()) + } else { + dataset.search(sequence, Some(&hyp_populations), None) + }; + + // exclude is inverse of + //let hyp_exclude = dataset.populations.keys().filter(|pop| !hyp_populations.contains(collect_vec() + let mut hyp_args = args.clone(); + hyp_args.parents = Some(hyp_populations.into_iter().cloned().collect_vec()); + + // Check if primary search found anything + if let Ok(primary_parent) = primary_search { + debug!(""Primary Parent Search was successful.""); + debug!(""Secondary Parent(s) Search.""); + let secondary_search = + secondary_parents(sequence, dataset, &[primary_parent], &hyp_args); + + if let Ok((recombination, parents)) = secondary_search { + debug!(""Secondary Parent(s) Search was successful.""); + let score: isize = recombination.score.values().sum(); + let conflict_alt: usize = + recombination.conflict_alt.values().map(|subs| subs.len()).sum(); + let conflict_ref: usize = + recombination.conflict_ref.values().map(|subs| subs.len()).sum(); + let conflict = conflict_alt + conflict_ref; + + // adjust the hypothesis, in case it wasn't actually recursive + let hypothesis = if hypothesis == Hypothesis::RecursiveRecombinant { + let mut is_recursive = false; + recombination.parents.iter().for_each(|pop| { + let recombinant_ancestor = dataset + .phylogeny + .get_recombinant_ancestor(pop) + .unwrap_or(None); + if recombinant_ancestor.is_some() { + is_recursive = true + } + }); + + if is_recursive { + Hypothesis::RecursiveRecombinant + } else { + Hypothesis::NonRecursiveRecombinant + } + } else { + hypothesis + }; + + hypotheses + .insert(hypothesis, (Some(recombination), parents, score, conflict)); + } else { + debug!(""Secondary Parent(s) Search was unsuccessful.""); + } + } else { + debug!(""Primary Parent Search was unsuccessful.""); + } + + debug!( + ""Hypotheses: {}"", + hypotheses + .iter() + .map(|(hyp, (_r, _p, score, conflict))| format!( + ""{hyp:?}: score={score}, conflict={conflict}"" + )) + .join("", "") + ); + } + + // ---------------------------------------------------------------------------- + // Best Hypothesis + + // No evidence at all, return error + if hypotheses.is_empty() { + return Err(eyre!(""No evidence for any recombination hypotheses."")); + } + // single hypothesis + let best_hypothesis = if hypotheses.len() == 1 { + hypotheses.first_key_value().unwrap().0.clone() + } + // evidence for multiple hypotheses + else { + // max_score: Sometimes the hypothesis with the highest score is 'correct' + // Ex. XBB.1.18: DesignatedRecombinant: score=77, conflict=5, NonRecursiveRecombinant: score=64, conflict=4 + + // min_conflict: Sometimes the hypothesis with the least conflict is 'correct' + // This seems to be generally the XBB* recursive recombinants, + // the original recombination (BJ.1 x CJ.1) has high support, + // but lots of conflict. + // Ex. XCW: DesignatedRecombinant: score=55, conflict=6, NonRecursiveRecombinant: score=65, conflict=17 + + let min_conflict = + hypotheses.iter().map(|(_hyp, (_r, _p, _s, c))| c).min().unwrap(); + let max_conflict = + hypotheses.iter().map(|(_hyp, (_r, _p, _s, c))| c).max().unwrap(); + let conflict_range = max_conflict - min_conflict; + let conflict_threshold = 5; + + // if the conflict range between hypotheses is large (>=10), prefer min_conflict + // otherwise, prefer max_score + let best_hypotheses = if conflict_range >= conflict_threshold { + debug!(""Best hypothesis selected by MIN CONFLICT. Conflict range ({conflict_range}) >= threshold ({conflict_threshold}).""); + hypotheses + .iter() + .filter_map(|(hyp, (_r, _p, _s, c))| (c == min_conflict).then_some(hyp)) + .collect_vec() + } else { + debug!(""Best hypothesis selected by MAX SCORE. Conflict range ({conflict_range}) < threshold ({conflict_threshold})""); + let max_score = + hypotheses.iter().map(|(_hyp, (_r, _p, s, _c))| s).max().unwrap(); + hypotheses + .iter() + .filter_map(|(hyp, (_r, _p, s, _c))| (s == max_score).then_some(hyp)) + .collect_vec() + }; + + // if hypotheses are tied, prefer them in enum order (first before last) + // note: this currently means Designated is preferred over non-designated. + // prefer this for now, since we can use --naive to disable designated + let hypothesis_ranks: BTreeMap = + Hypothesis::iter().enumerate().map(|(i, h)| (h, i)).collect(); + let best_hyp_rank = best_hypotheses + .iter() + .map(|hyp| { + hypothesis_ranks + .get(hyp) + .expect(""Hypothesis ranks does not contain hypothesis {hyp:?}"") + }) + .min() + .unwrap(); + let best_hypothesis = hypothesis_ranks + .iter() + .filter_map(|(hyp, r)| (r == best_hyp_rank).then_some(hyp)) + .next() + .unwrap(); + + best_hypothesis.to_owned() + }; + + debug!(""best_hypothesis: {best_hypothesis:?}""); + + // non-recombinant means that the parent search ""failed"" + if best_hypothesis == Hypothesis::NonRecombinant { + return Err(eyre!(""Best hypothesis is Non-Recombinant."")); + } + let result = hypotheses + .remove(&best_hypothesis) + .expect(""Hypotheses does not contain the best hypothesis {best_hypothesis:?}""); + let mut recombination = result.0.unwrap(); + let primary_parent = result.1[0].clone(); + + // ------------------------------------------------------------------------ + // Recombinant attributes + + recombination.edge_case = edge_case; + + // Decide on novel vs known recombinant at this point + recombination.recombinant = if let Some(recombinant) = &best_match.recombinant { + // check if expected parents match observed + let observed = &recombination.parents; + let expected = dataset.phylogeny.get_parents(recombinant)?; + let parents_match = validate::compare_parents(observed, &expected, dataset)?; + + if parents_match { + Some(recombinant.clone()) + } else { + *best_match = primary_parent; + debug!( + ""Changing best match consensus to primary parent:\n{}"", + best_match.pretty_print() + ); + Some(""novel"".to_string()) + } + } else { + Some(""novel"".to_string()) + }; + + recombination.unique_key = format!( + ""{}_{}_{}"", + &recombination.recombinant.clone().unwrap(), + &recombination.parents.iter().join(""_""), + &recombination.breakpoints.iter().join(""_""), + ); + + recombination.hypothesis = Some(best_hypothesis); + + Ok(recombination) +} + +// Search for the secondary recombination parent(s). +pub fn secondary_parents<'seq>( + sequence: &'seq Sequence, + dataset: &Dataset, + parents: &[SearchResult], + args: &run::Args, +) -> Result<(Recombination<'seq>, Vec), Report> { + // Initialize our 'Recombination' result, that we will modify and update + // as we iterate through potential parents + let mut recombination = Recombination::new(sequence); + + // All the parents we know of when the function is starting + // Will probably just be the primary parent (1)? + // todo!() test with more than 2 parents + let mut parents = parents.to_vec(); + let mut num_parents = parents.len(); + + // The inclusion parents may have been set by the args + // Otherwise, use all populations in dataset + let mut include_populations = if let Some(parents) = &args.parents { + parents.iter().collect_vec() + } else { + dataset.populations.keys().collect_vec() + }; + + // Keep track of how many parent search iterations we've done + let mut num_iter = 0; + + loop { + // -------------------------------------------------------------------- + // Loop Break Check: Simple + // -------------------------------------------------------------------- + + // Check if we can break out of the loop based on simple checks like the + // max number of iterations max number of parents achieved. + + if num_parents >= args.max_parents { + // Maxing out the number of parents is a SUCCESS + debug!(""Maximum parents reached ({num_parents}).""); + return Ok((recombination, parents)); + } + if num_iter >= args.max_iter { + debug!(""Maximum iterations reached ({num_iter}).""); + + // Finding minimum parents is a SUCCESS + if num_parents >= args.min_parents { + return Ok((recombination, parents)); + } + // otherwise FAILURE + else { + return Err(eyre!( + ""Number of parents ({num_parents}) is less than the minimum ({})."", + args.min_parents + )); + } + } + + num_iter += 1; + debug!(""Parent #{}: Iteration {num_iter}"", num_parents + 1); + + // -------------------------------------------------------------------- + // Conflict Checks + // -------------------------------------------------------------------- + + // Check for ALT or REF bases present in the sequence that are not resolved + // by a recombination parent found so far. + + // identify all substitutions found in all parents so far + let parent_substitutions = parents + .iter() + .flat_map(|parent| &parent.substitutions) + .unique() + .collect_vec(); + + // -------------------------------------------------------------------- + // Conflict ALT + + let conflict_alt = sequence + .substitutions + .iter() + .filter(|sub| !parent_substitutions.contains(sub)) + .collect_vec(); + + debug!(""conflict_alt: {}"", conflict_alt.iter().join("", "")); + + // Loop Break Check + if conflict_alt.len() < args.min_subs { + debug!(""Sufficient conflict_alt resolution reached, stopping parent search.""); + // Finding minimum parents is a SUCCESS + if num_parents >= args.min_parents { + return Ok((recombination, parents)); + } + // Otherwise FAILURE + else { + return Err(eyre!( + ""Number of parents ({num_parents}) is less than the minimum ({})."", + args.min_parents + )); + } + } + + // -------------------------------------------------------------------- + // Conflict REF + + // Conflict ref is slightly more complicated, because we don't store + // REF bases in the dataset. Instead we assume lack of ALT bases means + // the REF base is present. This is problematic, as it doesn't yet + // account for indels, missing data, multiallelic sites, etc. + + let conflict_ref = parents + .iter() + // get conflict REF between this parent and the sequence + .flat_map(|p| { + if !p.conflict_ref.contains_key(&p.consensus_population) { + warn!( + ""Parent {:?} has no conflict_ref recorded for it's consensus population {:?}"", + &p.sequence_id, + &p.consensus_population, + ); + } + p.conflict_ref.get(&p.consensus_population).cloned().unwrap_or_default() + }) + .unique() + // search for parents that have the REF base (no ALT) + .filter(|sub| { + let parents_with_ref = parents + .iter() + .filter(|p| !p.substitutions.contains(sub)) + .collect_vec(); + // No parents have REF base = unresolved + parents_with_ref.is_empty() + }) + .collect_vec(); + debug!(""conflict_ref: {}"", conflict_ref.iter().join("", "")); + + // -------------------------------------------------------------------- + // Conflict Combine + + // Combine the conflict REF and conflict ALT coordinates + // We will focus our parent search on populations that match + // the query sequence at these coordinates. + let mut coordinates = conflict_alt + .iter() + .map(|sub| sub.coord) + .chain(conflict_ref.iter().map(|sub| sub.coord)) + .collect_vec(); + coordinates.sort(); + debug!(""coordinates: {coordinates:?}""); + + if coordinates.is_empty() { + return Err(eyre!(""No coordinates left to search."")); + } + + // -------------------------------------------------------------------- + // EXCLUDE POPULATIONS + + // Remove currently known parents from the search list + let current_parents = + parents.iter().map(|result| &result.consensus_population).collect_vec(); + include_populations.retain(|pop| !current_parents.contains(pop)); + + // Exclude populations that have substitutions at ALL of the conflict_ref + if !conflict_ref.is_empty() { + let conflict_ref_populations = dataset + .populations + .iter() + .filter(|(pop, _seq)| include_populations.contains(pop)) + .filter_map(|(pop, seq)| { + let count = seq + .substitutions + .iter() + .filter(|sub| conflict_ref.contains(sub)) + .collect_vec() + .len(); + (count == conflict_ref.len()).then_some(pop) + }) + .collect_vec(); + include_populations.retain(|pop| !conflict_ref_populations.contains(pop)); + } + // -------------------------------------------------------------------- + // INCLUDE POPULATIONS + + // prioritize populations that have min_subs conflict_alt + // ie. help resolve the conflict_alt + + let conflict_alt_populations = dataset + .populations + .iter() + .filter(|(pop, _seq)| include_populations.contains(pop)) + .filter_map(|(pop, seq)| { + let count = seq + .substitutions + .iter() + .filter(|sub| conflict_alt.contains(sub)) + .collect_vec() + .len(); + (count >= args.min_subs).then_some(pop) + }) + .collect_vec(); + + include_populations.retain(|pop| conflict_alt_populations.contains(pop)); + + // trunclate list for display + let display_populations = if include_populations.len() <= 10 { + include_populations.iter().join("", "") + } else { + format!(""{} ..."", include_populations[0..10].iter().join("", ""),) + }; + debug!(""Prioritizing conflict_alt resolution: {display_populations:?}""); + + // If every single population in the dataset has been excluded, exit here + // This might because we supplied args.parents that were not actually + // good hypotheses. + if include_populations.is_empty() { + return Err(eyre!(""No populations left to search."")); + } + + // -------------------------------------------------------------------- + // Search Dataset #1 and #2 (Coordinate Range vs Precise) + // -------------------------------------------------------------------- + + //let search_modes = vec![""range"", ""precise""]; + let search_modes = vec![""precise"", ""range""]; + // In what cases do we want to search the full coordinate range first vs + // after the specific coordinates? + // When there is a very small number of subs to check, a precise search + // actually takes a very long time, because there are so many matches. + + for mode in search_modes { + let search_coords = if mode == ""precise"" { + debug!(""Searching based on precise coordinates: {coordinates:?}""); + coordinates.clone() + } else { + let coord_min = coordinates.iter().min().unwrap(); + let coord_max = coordinates.iter().max().unwrap(); + debug!(""Searching based on coordinate range: {coord_min} - {coord_max}""); + (coord_min.to_owned()..coord_max.to_owned()).collect_vec() + }; + + //debug!(""dataset.search""); + + let parent_candidate = dataset.search( + sequence, + Some(&include_populations), + Some(&search_coords), + ); + + // if the search found parents, check for recombination + if let Ok(parent_candidate) = parent_candidate { + // remove this parent from future searches + include_populations + .retain(|pop| **pop != parent_candidate.consensus_population); + + // check for recombination + let detect_result = detect_recombination( + sequence, + &parents, + Some(&parent_candidate), + &dataset.reference, + args, + ); + + // if successful, add this parent to the list and update recombination + // break out of the search mode loop + if let Ok(detect_result) = detect_result { + num_parents += 1; + // reset the iter counter + num_iter = 0; + parents.push(parent_candidate); + recombination = detect_result; + break; + } + } + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/recombination/validate.rs",".rs","10332","292","use crate::dataset::{Dataset, SearchResult}; +use crate::recombination::Recombination; +use color_eyre::eyre::{eyre, Report, Result}; +use itertools::Itertools; +use log::{debug, warn}; +use petgraph::Direction; +use std::fmt; +use std::str::FromStr; + +// ---------------------------------------------------------------------------- +// Validate + +#[derive(Clone, Debug)] +pub struct Validate { + pub status: Status, + pub details: Vec
, +} + +// ---------------------------------------------------------------------------- +// Status + +#[derive(Clone, Debug)] +pub enum Status { + Pass, + Fail, +} + +impl fmt::Display for Status { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let result = match self { + Status::Pass => ""pass"", + Status::Fail => ""fail"", + }; + write!(f, ""{}"", result) + } +} + +impl FromStr for Status { + type Err = Report; + fn from_str(input: &str) -> Result { + let result = match input { + ""pass"" => Status::Pass, + ""fail"" => Status::Fail, + _ => return Err(eyre!(""Unknown status: {input}"")), + }; + Ok(result) + } +} + +// ---------------------------------------------------------------------------- +// Details + +#[derive(Clone, Debug, PartialEq)] +pub enum Details { + IncorrectRecombinant, + IncorrectParent, + IncorrectPopulation, + NoRecombinationDetected, +} + +impl fmt::Display for Details { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let result = match self { + Details::IncorrectRecombinant => ""incorrect_recombinant"", + Details::IncorrectParent => ""incorrect_parent"", + Details::IncorrectPopulation => ""incorrect_population"", + Details::NoRecombinationDetected => ""no_recombination_detected"", + }; + write!(f, ""{}"", result) + } +} + +impl FromStr for Details { + type Err = Report; + fn from_str(input: &str) -> Result { + let result = match input { + ""incorrect_recombinant"" => Details::IncorrectRecombinant, + ""incorrect_parent"" => Details::IncorrectParent, + ""incorrect_population"" => Details::IncorrectPopulation, + ""no_recombination_detected"" => Details::NoRecombinationDetected, + _ => return Err(eyre!(""Unknown details: {input}"")), + }; + Ok(result) + } +} + +// ---------------------------------------------------------------------------- +// Functions +// ---------------------------------------------------------------------------- + +/// Validate a best match and recombination to expected dataset values. +pub fn validate( + dataset: &Dataset, + best_match: &SearchResult, + recombination: &Recombination, +) -> Result, Report> { + // Use the sequence ID as the expected population + let expected_population = best_match.sequence_id.replace(""population_"", """"); + + // If the sequence ID was not in the dataset, return no validation results + if !dataset.populations.contains_key(&expected_population) { + let validate: Option = None; + Ok(validate) + } else { + // ---------------------------------------------------------------- + // Population + // + // Is the expected population (sequence id) exactly the same as + // the best match (consensus population)? + + let observed_population = &best_match.consensus_population; + let validate_population = expected_population == *observed_population; + + // ---------------------------------------------------------------- + // Recombinant + // + // Is this a recombinant, and if so, is the recombinant ancestor + // exactly as expected? + + let observed_recombinant = &recombination.recombinant; + let expected_recombinant = + dataset.phylogeny.get_recombinant_ancestor(&expected_population)?; + + let validate_recombinant = expected_recombinant == *observed_recombinant; + + // ---------------------------------------------------------------- + // Parent Validation + + let observed_parents = &recombination.parents; + let expected_parents = if let Some(expected_recombinant) = expected_recombinant { + dataset.phylogeny.get_parents(&expected_recombinant)? + } else { + Vec::new() + }; + + // parent validation is already done in recombination::detect_recombination + // to decide whether it's a novel variant or not. It seems wasteful to run it again... + + let validate_parent = + compare_parents(observed_parents, &expected_parents, dataset)?; + + // ---------------------------------------------------------------- + // Recombination Validation + // Were parents and breakpoints detected at all? + + // ---------------------------------------------------------------- + // Summary + + let validate = if validate_population && validate_recombinant && validate_parent { + Validate { + status: Status::Pass, + details: Vec::new(), + } + } else { + let mut validate = Validate { + status: Status::Fail, + details: Vec::new(), + }; + if !validate_population { + validate.details.push(Details::IncorrectPopulation); + } + if !validate_parent { + // Were parents and breakpoints detected at all? + if !expected_parents.is_empty() && observed_parents.is_empty() { + validate.details.push(Details::NoRecombinationDetected); + } else { + validate.details.push(Details::IncorrectParent); + } + } + if !validate_recombinant + && !validate.details.contains(&Details::NoRecombinationDetected) + { + validate.details.push(Details::IncorrectRecombinant); + } + warn!( + ""{expected_population} failed validation: {details}"", + details = validate.details.iter().join("", "") + ); + validate + }; + + Ok(Some(validate)) + } +} + +/// Compare expected and observed recombination parents. +pub fn compare_parents( + observed: &Vec, + expected: &[String], + dataset: &Dataset, +) -> Result { + debug!(""Observed parents: {observed:?}""); + debug!(""Expected parents: {expected:?}""); + + // check if the expected parents are actually in the dataset populations + // ie. we actually have sequence data for them + let expected_filter = expected + .iter() + .map(|p| dataset.get_ancestor_with_sequence(p).unwrap_or(p.clone())) + .collect_vec(); + + let expected = &expected_filter; + + // one is empty, other is not + if (observed.is_empty() && !expected.is_empty()) + || (!observed.is_empty() && expected.is_empty()) + { + return Ok(false); + } + // exact match + let mut observed_exact = observed.clone(); + observed_exact.retain(|p| expected.contains(p)); + if observed_exact.len() == expected.len() { + return Ok(true); + } + + // expected is parent of observed, but no recombinant descendants + // Ex. XE: expected = BA.1,BA.2; observed=BA.1.17.2.1,BA.2 + // for each observed parent, walk towards the root, stopping a path + // if a recombinant node is encountered + let mut observed_parents = Vec::new(); + observed.iter().for_each(|pop| { + // get all possible paths from parent population to root + // ex. BA.1 (single path), XE, (two paths, through BA.1, BA.2), XBL (four paths, recursive) + let paths = dataset + .phylogeny + .get_paths(pop, ""root"", Direction::Incoming) + .unwrap_or_default(); + paths.iter().for_each(|populations| { + for p in populations { + observed_parents.push(p.clone()); + // after we hit the first recombinant, break + if dataset.phylogeny.is_recombinant(p).unwrap_or(false) { + break; + } + } + }); + }); + observed_parents = observed_parents.into_iter().unique().collect(); + debug!(""Parents of observed: {observed_parents:?}""); + observed_parents.retain(|p| expected.contains(p) || observed.contains(p)); + debug!(""Parents of observed that match: {observed_parents:?}""); + if observed_parents.len() == expected.len() { + return Ok(true); + } + + // observed is a parent of expected, but no recombinant descendants + // Ex. XCU: expected = BQ.1; observed=BA.5 + // for each observed parent, walk away from the root, stopping a path + // if a recombinant node is encountered + let mut expected_parents = Vec::new(); + expected.iter().for_each(|pop| { + // get all possible paths from parent population to root + // ex. BA.1 (single path), XE, (two paths, through BA.1, BA.2), XBL (four paths, recursive) + let paths = dataset + .phylogeny + .get_paths(pop, ""root"", Direction::Incoming) + .unwrap_or_default(); + paths.iter().for_each(|populations| { + for p in populations { + expected_parents.push(p.clone()); + // after we hit the first recombinant, break + if dataset.phylogeny.is_recombinant(p).unwrap_or(false) { + break; + } + } + }); + }); + + debug!(""Parents of expected: {expected_parents:?}""); + expected_parents.retain(|p| observed.contains(p) || expected.contains(p)); + debug!(""Parents of expected that match: {expected_parents:?}""); + if expected_parents.len() == observed.len() { + return Ok(true); + } + + // combine + // XBE: expected [""BA.5.2"",""BE.4.1""], observed: [""BA.5.2.6"",""BE.4""] + let mut combine = observed.clone(); + combine.append(&mut observed_parents); + combine.append(&mut expected_parents); + combine = combine.into_iter().unique().collect(); + debug!(""Observed children and parents: {combine:?}""); + combine.retain(|pop| expected.contains(pop)); + debug!(""Observed children and parents that match expected: {combine:?}""); + if combine.len() == expected.len() { + return Ok(true); + } + + Ok(false) +} +","Rust" +"Microbiology","phac-nml/rebar","src/run/mod.rs",".rs","12773","324","use crate::cli; +use crate::dataset; +use crate::export; +use crate::recombination; + +use crate::dataset::{attributes::Name, SearchResult}; +use crate::recombination::Recombination; +use crate::sequence::Sequence; +use bio::io::fasta; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use indicatif::{style::ProgressStyle, ProgressBar}; +use itertools::Itertools; +use log::{debug, info, warn}; +use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; +use std::fs::{create_dir_all, File}; +use std::io::Write; + +/// Run rebar on input alignment and/or dataset population(s) +pub fn run(args: &mut cli::run::Args) -> Result<(), Report> { + // copy args for export/seralizing + let args_export = args.clone(); + + // Warn if the directory already exists + if !args.output_dir.exists() { + info!(""Creating output directory: {:?}"", &args.output_dir); + create_dir_all(&args.output_dir)?; + } else { + warn!( + ""Proceed with caution! --output-dir {:?} already exists."", + args.output_dir + ); + } + + // check how many threads are available on the system + let default_thread_pool = + rayon::ThreadPoolBuilder::new().build().expect(""Failed to build thread pool.""); + info!( + ""Number of threads available: {}"", + default_thread_pool.current_num_threads() + ); + + // warn the user if they requested more than their system has available + // if so, default to the system threads + let mut num_threads = args.threads; + if args.threads > default_thread_pool.current_num_threads() { + warn!( + ""Requested --threads {} is greater than the available threads."", + args.threads + ); + num_threads = default_thread_pool.current_num_threads(); + } + + // configure the global thread pool + info!(""Using {} thread(s)."", num_threads); + let result = rayon::ThreadPoolBuilder::new().num_threads(num_threads).build_global(); + + if result.is_err() { + warn!(""Failed to build global thread pool.""); + } + + // configure progress bar style + let progress_bar_style = ProgressStyle::with_template( + ""{bar:40} {pos}/{len} ({percent}%) | Sequences / Second: {per_sec} | Elapsed: {elapsed_precise} | ETA: {eta_precise}"" + ).expect(""Failed to create progress bar from template.""); + + // Collect files in dataset_dir into a dataset object + // This mainly includes parent populations sequences + // and optionally a phylogenetic representation. + let mut dataset = dataset::load::dataset(&args.dataset_dir, &args.mask)?; + + // init a container to hold query sequences, dataset + // populations and/or sequences from an input alignment + let mut sequences = Vec::new(); + // keep track of ids we've seen to remove duplicates later + let mut ids_seen = Vec::new(); + + // ------------------------------------------------------------------------ + // Parse Input Populations + // ------------------------------------------------------------------------ + + // this step is pretty fast, don't really need a progress bar here + + if let Some(populations) = &args.input.populations { + info!(""Parsing input populations: {populations:?}""); + + // limit the amount of warnings emitted + let mut num_warnings = 0; + let max_warnings = 10; + + dataset.expand_populations(populations)?.into_iter().for_each(|p| { + if !dataset.populations.contains_key(&p) { + if num_warnings < max_warnings { + warn!(""Population {p} is not in the dataset populations fasta.""); + } else { + warn!(""... (Additional warnings ommitted)""); + } + num_warnings += 1; + } else { + debug!(""Adding population {p} to query sequences.""); + let mut sequence = dataset.populations.get(&p).unwrap().clone(); + sequence.id = format!(""population_{}"", sequence.id); + ids_seen.push(sequence.id.clone()); + sequences.push(sequence.clone()); + } + }); + } + + // ------------------------------------------------------------------------ + // Parse Input Alignment + // ------------------------------------------------------------------------ + + if let Some(alignment) = &args.input.alignment { + info!(""Loading query alignment: {:?}"", alignment); + let alignment_reader = fasta::Reader::from_file(alignment) + .map_err(|e| eyre!(e)) + .wrap_err(""Failed to read file: {alignment:?}"")?; + + for result in alignment_reader.records() { + let record = result.wrap_err(""Unable to parse alignment: {alignment:?}"")?; + let sequence = + Sequence::from_record(record, Some(&dataset.reference), &args.mask)?; + + // check for duplicates + if ids_seen.contains(&sequence.id) { + warn!( + ""Sequence {} is duplicated, retaining first one."", + sequence.id + ); + continue; + } else { + ids_seen.push(sequence.id.clone()); + sequences.push(sequence); + } + } + } + + // ------------------------------------------------------------------------ + // Parse and expand input parents + + if let Some(parents) = &args.parents { + info!(""Parsing input parents: {:?}"", &parents); + args.parents = Some(dataset.expand_populations(parents)?); + } + + // ------------------------------------------------------------------------ + // Dataset Knockout + // ------------------------------------------------------------------------ + + if let Some(knockout) = &args.knockout { + info!(""Performing dataset knockout: {knockout:?}""); + + // Check to make sure wildcards are used in all knockouts + // Weird things happend if you don't! + let knockout_no_wildcard = + knockout.iter().filter(|p| !p.contains('*')).collect_vec(); + if !knockout_no_wildcard.is_empty() { + warn!(""Proceed with caution! Weird things can happen when you run a knockout without descendants (no '*'): {knockout_no_wildcard:?}."") + } + + // Expanded populations (in case wildcard * is provided) + let knockout_expanded = dataset.expand_populations(knockout)?; + debug!(""Expanded dataset knockout: {knockout:?}""); + debug!(""Removing knockout populations from the fasta.""); + dataset.populations.retain(|id, _| !knockout_expanded.contains(id)); + + debug!(""Removing knockout populations from the mutations.""); + dataset.mutations.iter_mut().for_each(|(_sub, populations)| { + populations.retain(|p| !knockout_expanded.contains(p)); + }); + + if !dataset.phylogeny.is_empty() { + for p in &knockout_expanded { + dataset.phylogeny.remove(p)?; + } + } + + args.knockout = Some(knockout_expanded); + } + + // ------------------------------------------------------------------------ + // Recombination Search + // ------------------------------------------------------------------------ + + info!(""Running recombination search.""); + + // this step is the slowest, use progress bar and parallel threads + let progress_bar = ProgressBar::new(sequences.len() as u64); + progress_bar.set_style(progress_bar_style); + + // adjust search populations based on args.parents and args.knockout + let mut parent_search_populations = dataset.populations.keys().collect_vec(); + // if args.parents supplied on the CLI + if let Some(populations) = &args.parents { + parent_search_populations.retain(|pop| populations.contains(pop)) + } + // if args.knockout supplied on the CLI + if let Some(populations) = &args.knockout { + parent_search_populations.retain(|pop| !populations.contains(pop)) + } + + // Search for the best match and recombination parents for each sequence. + // This loop/closure is structured weirdly for rayon compatability, and the + // fact that we need to return multiple types of objects + let results: Vec<(SearchResult, Recombination)> = sequences + .par_iter() + .map(|sequence| { + // initialize with default results, regardless of whether our + // searches ""succeed"", we're going to return standardized data + // structures to build our exports upon (ex. linelist columns) + // which will include the ""negative"" results + let mut best_match = SearchResult::new(sequence); + let mut recombination = Recombination::new(sequence); + + // ------------------------------------------------------------------------ + // Best Match (Consensus) + // + // search for the best match in the dataset to this sequence. + // this will represent the consensus population call. + + debug!(""Identifying best match (consensus population).""); + let search_result = dataset.search(sequence, None, None); + + // if we found a match, proceed with recombinant search + if let Ok(search_result) = search_result { + best_match = search_result; + + debug!(""Searching for recombination parents.""); + let parent_search = recombination::search::all_parents( + sequence, + &dataset, + &mut best_match, + &parent_search_populations, + args, + ); + match parent_search { + Ok(search_result) => recombination = search_result, + Err(e) => debug!(""Parent search did not succeed. {e}""), + } + } + // what to do if not a single population matched? + else { + // temporary handling for root population B + if dataset.name == Name::SarsCov2 { + if sequence.id == ""population_B"" { + best_match.consensus_population = ""B"".to_string(); + } + } else { + debug!(""No matches found.""); + } + } + + progress_bar.inc(1); + + (best_match, recombination) + }) + .collect(); + + progress_bar.finish(); + + // ------------------------------------------------------------------------ + // Export CLI args + + let outpath_args = args.output_dir.join(""run_args.json""); + info!(""Exporting CLI Run Args: {outpath_args:?}""); + // create output file + let mut file = File::create(&outpath_args) + .wrap_err_with(|| format!(""Failed to create file: {outpath_args:?}""))?; + + // parse to string + let output = serde_json::to_string_pretty(&args_export) + .wrap_err_with(|| ""Failed to parse mutations."".to_string())?; + + // write to file + file.write_all(format!(""{}\n"", output).as_bytes()) + .wrap_err_with(|| format!(""Failed to write file: {outpath_args:?}""))?; + + // ------------------------------------------------------------------------ + // Export Linelist (single) + + let outpath_linelist = args.output_dir.join(""linelist.tsv""); + info!(""Exporting linelist: {outpath_linelist:?}""); + + let linelist_table = export::linelist(&results, &dataset)?; + //let linelist_table = export::linelist(&best_matches, &recombinations, &dataset)?; + linelist_table.write(&outpath_linelist)?; + + // ------------------------------------------------------------------------ + // Export Barcodes (multiple, collected by recombinant) + + let outdir_barcodes = args.output_dir.join(""barcodes""); + + create_dir_all(&outdir_barcodes)?; + + // get unique keys of recombinants identified + let unique_keys = results + .iter() + .filter_map(|(_b, r)| (*r.unique_key != String::new()).then_some(&r.unique_key)) + .unique() + .collect_vec(); + + if unique_keys.is_empty() { + warn!(""No recombination detected, no barcodes will be outputted.""); + } else { + info!(""Exporting recombination barcodes: {outdir_barcodes:?}""); + } + + for unique_key in unique_keys { + // filter recombinations down to just this recombinant unique_key + let unique_rec = results + .iter() + .filter_map(|(_b, r)| (r.unique_key == *unique_key).then_some(r)) + .cloned() + .collect_vec(); + // combine all the sample barcode tables + let barcode_table = + recombination::combine_tables(&unique_rec, &dataset.reference)?; + let barcode_table_path = outdir_barcodes.join(format!(""{unique_key}.tsv"")); + barcode_table.write(&barcode_table_path)?; + } + + info!(""Done.""); + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/mod.rs",".rs","19892","540","pub mod attributes; +pub mod download; +pub mod list; +pub mod load; +pub mod sarscov2; +pub mod toy1; + +use crate::cli::run; +use crate::phylogeny::Phylogeny; +use crate::sequence::{parsimony, Sequence, Substitution}; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use indoc::formatdoc; +use itertools::Itertools; +use log::debug; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::default::Default; +use std::fmt; +use std::fs::File; +use std::io::Write; +use std::path::Path; + +// ---------------------------------------------------------------------------- +// Dataset + +#[derive(Debug, Deserialize, Serialize)] +pub struct Dataset { + pub name: attributes::Name, + pub tag: attributes::Tag, + pub reference: Sequence, + pub populations: BTreeMap, + pub mutations: BTreeMap>, + pub phylogeny: Phylogeny, + pub edge_cases: Vec, +} + +impl fmt::Display for Dataset { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, ""name: {}, tag: {}"", self.name, self.tag) + } +} + +impl Default for Dataset { + fn default() -> Self { + Self::new() + } +} + +impl Dataset { + pub fn new() -> Self { + Dataset { + name: attributes::Name::Custom, + tag: attributes::Tag::Custom, + reference: Sequence::new(), + populations: BTreeMap::new(), + mutations: BTreeMap::new(), + phylogeny: Phylogeny::new(), + edge_cases: Vec::new(), + } + } + + pub fn create_consensus( + &self, + name: &str, + populations: &[&str], + ) -> Result { + // collect individual population sequences + let sequences = populations + .iter() + .filter_map(|pop| { + (self.populations.contains_key(*pop)).then_some(&self.populations[*pop]) + }) + .collect_vec(); + + // construct consensus + let consensus = (0..self.reference.genome_length) + .map(|coord| { + let bases = sequences.iter().map(|s| s.seq[coord]).unique().collect_vec(); + if bases.len() == 1 { + bases[0] + } else { + 'N' + } + }) + .join(""""); + + // create bio record + let description = None; + let record = + bio::io::fasta::Record::with_attrs(name, description, consensus.as_bytes()); + // parse and create Sequence record + // dataset is already masked, no need + let mask = Vec::new(); + let sequence = Sequence::from_record(record, Some(&self.reference), &mask)?; + + Ok(sequence) + } + + /// Expand list of populations with wildcarding. + pub fn expand_populations( + &self, + populations: &[String], + ) -> Result, Report> { + // expand '*' to get descendants + let expanded = populations + .iter() + .map(|p| { + // if population is '*', use all populations in dataset + if p == ""*"" { + Ok(self.populations.keys().cloned().collect_vec()) + } + // if population is 'X*', use all recombinants in dataset + else if p == ""X*"" { + Ok(self.phylogeny.get_recombinants_all()?) + } + // if population ends with '*' expand descendants + else if p.ends_with('*') { + let p = p.replace('*', """"); + self.phylogeny.get_descendants(&p) + } + // simple population name, that is in the dataset + else if self.populations.contains_key(p) { + Ok(vec![p.to_string()]) + } else { + Err(eyre!(""{p} is not present in the dataset."")) + } + }) + // flatten and handle the `Result` layer + .collect::, Report>>()? + .into_iter() + // flatten and handle the `Vec` layer + .flatten() + .unique() + .collect_vec(); + + Ok(expanded) + } + + /// Search dataset for a population parsimony match to the sequence. + pub fn search( + &self, + sequence: &Sequence, + populations: Option<&Vec<&String>>, + coordinates: Option<&[usize]>, + ) -> Result { + // initialize an empty result, this will be the final product of this function + let mut result = SearchResult::new(sequence); + + // -------------------------------------------------------------------- + // Candidate Matches + + // Identify preliminary candidate matches, based on populations that have + // the greatest number of matching substitutions. + // NOTE: This is a efficiency shortcut, but the true population is not + // guaranteed to be in this initial candidate pool. + + // optionally filter subs to the requested coordinates + let search_subs = if let Some(coordinates) = &coordinates { + sequence + .substitutions + .iter() + .filter(|sub| coordinates.contains(&sub.coord)) + .collect_vec() + } else { + sequence.substitutions.iter().collect() + }; + + // Count up all matching population subs (""support"") + let mut max_support = 0; + let population_support_counts: BTreeMap<&String, usize> = self + .populations + .iter() + .filter(|(pop, _seq)| { + if let Some(populations) = populations { + populations.contains(pop) + } else { + true + } + }) + .filter_map(|(pop, seq)| { + let count = seq + .substitutions + .iter() + .filter(|sub| search_subs.contains(sub)) + .collect_vec() + .len(); + if count >= max_support { + max_support = count + } + (count > 0).then_some((pop, count)) + }) + .collect(); + + // todo!() decide how much wiggle room we want to give in max support + // if we want to do max_support - 10, we might need to alter pretty_print + // so that it only displays the first N candidates (ex. 5,10) + // this will also cause slow downs + let population_matches = population_support_counts + .into_iter() + .filter_map(|(pop, count)| (count == max_support).then_some(pop)) + //.filter(|(_pop, count)| *count >= (max_support - 10)) + .collect_vec(); + + if population_matches.is_empty() { + return Err(eyre!(""No mutations matched a population in the dataset."")); + } + + // -------------------------------------------------------------------- + // Conflict + + // check which populations have extra subs/lacking subs + population_matches.into_iter().for_each(|pop| { + // calculate the parsimony score, and store results in map by population + let pop_seq = &self.populations[pop]; + let summary = + parsimony::Summary::from_sequence(sequence, pop_seq, coordinates) + .unwrap_or_else(|_| { + panic!(""Failed to create summary from sequence {}"", &sequence.id) + }); + result.support.insert(pop.to_owned(), summary.support); + result.conflict_ref.insert(pop.to_owned(), summary.conflict_ref); + result.conflict_alt.insert(pop.to_owned(), summary.conflict_alt); + result.score.insert(pop.to_owned(), summary.score); + }); + + // -------------------------------------------------------------------- + // Top Populations + // Tie breaking, prefer matches with the highest score (support - conflict) + // beyond that, prefer matches with highest support or lowest conflict? + // Ex. XCU parent #1 could be FL.23 (highest support) or XBC.1 (lowest conflict) + + // which population(s) has the highest score? + // reminder: it can be negative when extreme recombinant genomic size + let max_score = + result.score.values().max().expect(""Failed to get max score of result.""); + + let max_score_populations = result + .score + .iter() + .filter_map(|(pop, count)| (count == max_score).then_some(pop)) + .collect_vec(); + + // break additional ties by max support + let max_support = result + .support + .iter() + .filter_map(|(pop, subs)| { + (max_score_populations.contains(&pop)).then_some(subs.len()) + }) + .max() + .unwrap_or(0); + + result.top_populations = result + .score + .iter() + .zip(result.support.iter()) + .filter_map(|((pop, score), (_, subs))| { + (score == max_score && subs.len() == max_support).then_some(pop) + }) + .cloned() + .collect_vec(); + + // -------------------------------------------------------------------- + // Consensus Population + // summarize top populations by common ancestor + let consensus_population = if self.phylogeny.is_empty() { + //result.top_populations.iter().join(""|"") + // just take first? + result.top_populations[0].clone() + } else { + self.phylogeny.get_common_ancestor(&result.top_populations)? + }; + result.consensus_population = consensus_population.clone(); + + // if the common_ancestor was not in the populations list, add it + let consensus_sequence = if !result + .top_populations + .contains(&consensus_population) + { + let pop = &consensus_population; + + // // Option #1. Actual sequence of the internal MRCA node? + // let pop_seq = &self.populations[pop]; + // let summary = parsimony::Summary::from_sequence(sequence, pop_seq, coordinates)?; + + // Option #2. Consensus sequence of top populations? + let top_populations = + result.top_populations.iter().map(|s| s.as_ref()).collect_vec(); + debug!(""Creating {pop} consensus genome from top populations.""); + let pop_seq = self.create_consensus(pop, &top_populations)?; + let summary = + parsimony::Summary::from_sequence(sequence, &pop_seq, coordinates)?; + + // Add consensus summary to search result + result.support.insert(pop.to_owned(), summary.support); + result.conflict_ref.insert(pop.to_owned(), summary.conflict_ref); + result.conflict_alt.insert(pop.to_owned(), summary.conflict_alt); + result.score.insert(pop.to_owned(), summary.score); + + pop_seq + } else { + self + .populations + .get(&consensus_population) + .cloned() + .unwrap_or_else(|| panic!(""Consensus population {consensus_population} is not in the dataset populations."")) + }; + + // Filter out non-top populations + // helps cut down on verbosity in debug log and data stored + // Ex. XE, lots of BA.2 candidates + result.score.retain(|p, _| { + result.top_populations.contains(p) || p == &consensus_population + }); + result.support.retain(|p, _| { + result.top_populations.contains(p) || p == &consensus_population + }); + result.conflict_ref.retain(|p, _| { + result.top_populations.contains(p) || p == &consensus_population + }); + result.conflict_alt.retain(|p, _| { + result.top_populations.contains(p) || p == &consensus_population + }); + + // Check if the consensus population is a known recombinant or descendant of one + result.recombinant = if self.phylogeny.is_empty() { + None + } else { + self.phylogeny.get_recombinant_ancestor(&consensus_population)? + }; + + // -------------------------------------------------------------------- + // Substitutions + // -------------------------------------------------------------------- + + // set consensus population subs + result.substitutions = consensus_sequence + .substitutions + .into_iter() + .filter(|sub| { + !sequence.missing.contains(&sub.coord) + && !sequence.deletions.contains(&sub.to_deletion()) + }) + .collect_vec(); + + // private subs (conflict_alt and conflict_ref reversed) + result.private = + result.conflict_alt.get(&consensus_population).cloned().unwrap_or_default(); + result + .conflict_ref + .get(&consensus_population) + .cloned() + .unwrap_or_default() + .iter() + .for_each(|sub| { + let mut sub = *sub; + std::mem::swap(&mut sub.alt, &mut sub.reference); + result.private.push(sub); + }); + result.private.sort(); + + debug!(""Search Result:\n{}"", result.pretty_print()); + Ok(result) + } + + /// If a population name is in the phylogeny but not in the sequences, + /// find the closest parent that is in the sequences. Might be itself! + /// + /// I don't love this function name, need better! + pub fn get_ancestor_with_sequence(&self, population: &str) -> Result { + if self.populations.contains_key(population) { + return Ok(population.to_string()); + } + // ancestors can have multiple paths to root, because of recombination + let ancestors = self.phylogeny.get_ancestors(population)?; + // filter the ancestor paths to just populations we have sequences for + // prefer the ancestor path that is the longest + let ancestors_filter = ancestors + .into_iter() + .map(|path| { + path.into_iter() + .filter(|p| self.populations.contains_key(p)) + .collect_vec() + }) + .max_by(|a, b| a.len().cmp(&b.len())) + .unwrap_or_default(); + + // use the last element in the path (closest parent) + let ancestor = ancestors_filter.last(); + if let Some(ancestor) = ancestor { + Ok(ancestor.clone()) + } else { + Err(eyre!(""No ancestor of {population} has sequence data."")) + } + } +} + +// ---------------------------------------------------------------------------- +// Dataset Search Result + +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +pub struct SearchResult { + pub sequence_id: String, + pub consensus_population: String, + pub top_populations: Vec, + pub substitutions: Vec, + pub support: BTreeMap>, + pub private: Vec, + pub conflict_ref: BTreeMap>, + pub conflict_alt: BTreeMap>, + pub score: BTreeMap, + pub recombinant: Option, +} + +impl SearchResult { + pub fn new(sequence: &Sequence) -> Self { + SearchResult { + sequence_id: sequence.id.clone(), + consensus_population: String::new(), + top_populations: Vec::new(), + support: BTreeMap::new(), + private: Vec::new(), + conflict_ref: BTreeMap::new(), + conflict_alt: BTreeMap::new(), + substitutions: Vec::new(), + score: BTreeMap::new(), + recombinant: None, + } + } + + pub fn pretty_print(&self) -> String { + // Order the population lists from 'best' to 'worst' + + let max_display_items = 10; + + // score + let mut score_order: Vec<(String, isize)> = + self.score.clone().into_iter().collect(); + score_order.sort_by(|a, b| b.1.cmp(&a.1)); + + // put consensus population first, regardless of score + let consensus_score: (String, isize) = score_order + .iter() + .find(|(pop, _score)| *pop == self.consensus_population) + .cloned() + .expect(""Failed to order consensus populations by score.""); + + score_order.retain(|(pop, _score)| *pop != self.consensus_population); + score_order.insert(0, consensus_score); + + // restrict display items for brevity + let display_suffix = if score_order.len() > max_display_items { + score_order = score_order[0..max_display_items].to_vec(); + ""\n ..."" + } else { + """" + }; + + let mut support_order: Vec = Vec::new(); + let mut conflict_ref_order: Vec = Vec::new(); + let mut conflict_alt_order: Vec = Vec::new(); + + score_order.iter().for_each(|(pop, _count)| { + let subs = &self.support[pop]; + let count = subs.len(); + support_order.push(format!(""- {pop} ({count}): {}"", subs.iter().join("", ""))); + + let subs = &self.conflict_ref[pop]; + let count = subs.len(); + conflict_ref_order + .push(format!(""- {pop} ({count}): {}"", subs.iter().join("", ""))); + + let subs = &self.conflict_alt[pop]; + let count = subs.len(); + conflict_alt_order + .push(format!(""- {pop} ({count}): {}"", subs.iter().join("", ""))); + }); + + // Pretty string formatting for yaml + let score_order = score_order + .iter() + .map(|(pop, count)| format!(""- {}: {}"", &pop, &count)) + .collect::>(); + + formatdoc!( + ""sequence_id: {} + consensus_population: {} + top_populations: {} + recombinant: {} + substitutions: {} + score:\n {}{display_suffix} + support:\n {}{display_suffix} + conflict_ref:\n {}{display_suffix} + conflict_alt:\n {}{display_suffix} + private: {}"", + self.sequence_id, + self.consensus_population, + self.top_populations.join("", ""), + self.recombinant.clone().unwrap_or(""None"".to_string()), + self.substitutions.iter().join("", ""), + score_order.join(""\n ""), + support_order.join(""\n ""), + conflict_ref_order.join(""\n ""), + conflict_alt_order.join(""\n ""), + self.private.iter().join("", "") + ) + } +} + +// ---------------------------------------------------------------------------- +// Functions +// ---------------------------------------------------------------------------- + +/// Write mapping of mutations to populations, coordinate sorted. +pub fn write_mutations( + mutations: &BTreeMap>, + path: &Path, +) -> Result<(), Report> { + // convert to vector for coordinate sorting + let mut mutations = mutations.iter().collect_vec(); + mutations.sort_by(|a, b| a.0.coord.cmp(&b.0.coord)); + + // convert substitution to string for serde pretty + let mutations = + mutations.iter().map(|(sub, pops)| (sub.to_string(), pops)).collect_vec(); + // create output file + let mut file = File::create(path) + .wrap_err_with(|| format!(""Failed to create file: {path:?}""))?; + + // parse to string + let output = serde_json::to_string_pretty(&mutations) + .wrap_err_with(|| ""Failed to parse mutations."".to_string())?; + + // write to file + file.write_all(format!(""{}\n"", output).as_bytes()) + .wrap_err_with(|| format!(""Failed to write file: {path:?}""))?; + + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/load.rs",".rs","3617","113","use crate::cli::run; +use crate::dataset::attributes::{Name, Summary, Tag}; +use crate::dataset::Dataset; +use crate::phylogeny::Phylogeny; +use crate::sequence::{read_reference, Sequence, Substitution}; +use bio::io::fasta; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use log::{info, warn}; +use std::collections::BTreeMap; +use std::path::Path; + +// ---------------------------------------------------------------------------- +// Dataset +// ---------------------------------------------------------------------------- + +/// Load dataset. +pub fn dataset(dataset_dir: &Path, mask: &Vec) -> Result { + info!(""Loading dataset: {:?}"", dataset_dir); + + let mut dataset = Dataset::new(); + + // ------------------------------------------------------------------------ + // Mandatory + + // Reference + let reference_path = dataset_dir.join(""reference.fasta""); + dataset.reference = read_reference(&reference_path, mask)?; + + // Populations and Mutations + let populations_path = dataset_dir.join(""populations.fasta""); + (dataset.populations, dataset.mutations) = + parse_populations(&populations_path, &reference_path, mask)?; + + // ------------------------------------------------------------------------ + // Optional + + // Summary + let summary_path = dataset_dir.join(""summary.json""); + if summary_path.exists() { + let summary = Summary::read(&summary_path)?; + dataset.name = summary.name; + dataset.tag = summary.tag; + } else { + warn!(""No summary was found: {summary_path:?}""); + dataset.name = Name::Custom; + dataset.tag = Tag::Custom; + } + + // Edge Cases + let edge_cases_path = dataset_dir.join(""edge_cases.json""); + dataset.edge_cases = if edge_cases_path.exists() { + let multiple = true; + run::Args::read(&edge_cases_path, multiple)?.unwrap_right() + } else { + warn!(""No edge cases were found: {edge_cases_path:?}""); + Vec::new() + }; + + // Phylogeny + let phylogeny_path = dataset_dir.join(""phylogeny.json""); + dataset.phylogeny = if phylogeny_path.exists() { + Phylogeny::read(&phylogeny_path)? + } else { + warn!(""No phylogeny was found: {phylogeny_path:?}""); + Phylogeny::new() + }; + + // -------------------------------------------------------------------- + // Done + + Ok(dataset) +} + +// ---------------------------------------------------------------------------- +// Parse Populations +// ---------------------------------------------------------------------------- + +#[allow(clippy::type_complexity)] +pub fn parse_populations( + populations_path: &Path, + reference_path: &Path, + mask: &Vec, +) -> Result< + ( + BTreeMap, + BTreeMap>, + ), + Report, +> { + // read in populations from fasta + let populations_reader = fasta::Reader::from_file(populations_path) + .map_err(|e| eyre!(e)) + .wrap_err(format!(""Failed to read file: {populations_path:?}""))?; + + // read in reference from fasta + let reference = read_reference(reference_path, mask)?; + + let mut populations = BTreeMap::new(); + let mut mutations = BTreeMap::new(); + + for result in populations_reader.records() { + let record = result?; + let sequence = Sequence::from_record(record, Some(&reference), mask)?; + populations.insert(sequence.id.clone(), sequence.clone()); + + for sub in sequence.substitutions { + mutations.entry(sub).or_insert(Vec::new()).push(sequence.id.clone()); + } + } + + Ok((populations, mutations)) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/attributes.rs",".rs","9964","353","use crate::utils::remote_file::RemoteFile; +use chrono::prelude::*; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use color_eyre::Help; +use indoc::formatdoc; +use semver::{Version, VersionReq}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::default::Default; +use std::fmt; +use std::fs::File; +use std::io::Write; +use std::path::Path; +use std::str::FromStr; +use strum::{EnumIter, EnumProperty}; + +// ---------------------------------------------------------------------------- +// Dataset Name + +#[derive( + Clone, Copy, Debug, Default, EnumIter, EnumProperty, Serialize, Deserialize, PartialEq, +)] +pub enum Name { + #[serde(rename = ""sars-cov-2"")] + #[strum(props(implemented = ""true""))] + SarsCov2, + #[serde(rename = ""toy1"")] + #[strum(props(implemented = ""true""))] + Toy1, + #[serde(rename = ""rsv-a"")] + #[strum(props(implemented = ""false""))] + RsvA, + #[serde(rename = ""rsv-b"")] + #[strum(props(implemented = ""false""))] + RsvB, + #[default] + #[serde(rename = ""custom"")] + #[strum(props(implemented = ""false""))] + Custom, +} + +impl Name { + pub fn compatibility(&self) -> Result { + let mut compatibility = Compatibility::new(); + #[allow(clippy::single_match)] + match self { + Name::SarsCov2 => { + compatibility.dataset.min_date = + Some(NaiveDate::parse_from_str(""2023-02-09"", ""%Y-%m-%d"")?); + } + Name::Toy1 => compatibility.cli.version = Some("">=0.2.0"".to_string()), + _ => compatibility.cli.version = Some("">=1.0.0"".to_string()), + } + Ok(compatibility) + } +} + +impl fmt::Display for Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Name::SarsCov2 => String::from(""sars-cov-2""), + Name::Toy1 => String::from(""toy1""), + Name::RsvA => String::from(""rsv-a""), + Name::RsvB => String::from(""rsv-b""), + Name::Custom => String::from(""custom""), + }; + + write!(f, ""{}"", name) + } +} + +impl FromStr for Name { + type Err = Report; + + fn from_str(name: &str) -> Result { + let name = match name { + ""sars-cov-2"" => Name::SarsCov2, + ""toy1"" => Name::Toy1, + ""rsv-a"" => Name::RsvA, + ""rsv-b"" => Name::RsvB, + ""custom"" => Name::Custom, + _ => Err(eyre!(""Unknown dataset name: {name}"")) + .suggestion(""Please choose from:"")?, + }; + + Ok(name) + } +} + +// ---------------------------------------------------------------------------- +// Dataset Tag + +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +pub enum Tag { + Nightly, + Archive(String), + #[default] + Custom, +} + +impl fmt::Display for Tag { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let tag = match self { + Tag::Nightly => String::from(""nightly""), + Tag::Archive(tag) => tag.to_owned(), + Tag::Custom => String::from(""custom""), + }; + + write!(f, ""{}"", tag) + } +} + +impl FromStr for Tag { + type Err = Report; + + fn from_str(tag: &str) -> Result { + let tag = match tag { + ""nightly"" => Tag::Nightly, + ""custom"" => Tag::Custom, + _ => { + // check if it's an archival date string + let tag_date = NaiveDate::parse_from_str(tag, ""%Y-%m-%d"") + .wrap_err_with(|| eyre!(""Archive tag date is invalid: {tag:?}. Example of a valid Archive tag: 2023-08-17""))?; + // is it in the future? + let today = Local::now().date_naive(); + if tag_date > today { + return Err(eyre!(""Archive tag date is in the future: {tag:?}. Please pick a date on or before today: {today:?}""))?; + } + Tag::Archive(tag.to_string()) + } + }; + + Ok(tag) + } +} + +// ---------------------------------------------------------------------------- +// Dataset Compatibility + +pub fn check_compatibility(name: &Name, tag: &Tag) -> Result<(), Report> { + let compatibility = name.compatibility()?; + + // Check CLI Version + if let Some(cli_version) = compatibility.cli.version { + let current_version = Version::parse(env!(""CARGO_PKG_VERSION""))?; + let required_version = VersionReq::parse(&cli_version)?; + if !required_version.matches(¤t_version) { + return Err(eyre!(formatdoc!( + ""CLI version incompatibility. + Current version {current_version} does not satisfy the {name} dataset requirement {required_version}"", + current_version=current_version.to_string() + ))); + } + } + // Check Tag Dates + if matches!(tag, Tag::Archive(_)) { + let tag_date = NaiveDate::parse_from_str(&tag.to_string(), ""%Y-%m-%d"")?; + + // Minimum Date + if let Some(min_date) = compatibility.dataset.min_date { + if tag_date < min_date { + return Err(eyre!(formatdoc!( + ""Date incompatibility. + Tag {tag_date:?} does not satisfy the {name} dataset minimum date {min_date:?}"" + ))); + } + } + // Maximum Date + if let Some(max_date) = compatibility.dataset.max_date { + if tag_date > max_date { + return Err(eyre!(formatdoc!( + ""Date incompatibility. + Tag {tag_date:?} does not satisfy the {name} dataset maximum date {max_date:?}"" + ))); + } + } + } + + Ok(()) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Compatibility { + pub dataset: DateCompatibility, + pub cli: CliCompatibility, +} + +impl Default for Compatibility { + fn default() -> Self { + Self::new() + } +} + +impl Compatibility { + pub fn new() -> Self { + Compatibility { + dataset: DateCompatibility::new(), + cli: CliCompatibility::new(), + } + } +} + +// ---------------------------------------------------------------------------- +// Date Compatibility + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DateCompatibility { + pub min_date: Option, + pub max_date: Option, +} + +impl Default for DateCompatibility { + fn default() -> Self { + Self::new() + } +} + +impl DateCompatibility { + pub fn new() -> Self { + DateCompatibility { + min_date: None, + max_date: None, + } + } +} + +// ---------------------------------------------------------------------------- +// CLI Compatibility + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CliCompatibility { + pub version: Option, +} + +impl Default for CliCompatibility { + fn default() -> Self { + Self::new() + } +} + +impl CliCompatibility { + pub fn new() -> Self { + CliCompatibility { + version: Some("">=0.1.0"".to_string()), + } + } +} + +// ---------------------------------------------------------------------------- +// Dataset Summary + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Summary { + pub version: String, + pub tag: Tag, + pub name: Name, + pub reference: RemoteFile, + pub populations: RemoteFile, + pub misc: BTreeMap, +} + +impl Default for Summary { + fn default() -> Self { + Self::new() + } +} +impl Summary { + pub fn new() -> Self { + Summary { + version: format!(""{} {}"", env!(""CARGO_PKG_NAME""), env!(""CARGO_PKG_VERSION"")), + tag: Tag::Custom, + name: Name::Custom, + reference: RemoteFile::new(), + populations: RemoteFile::new(), + misc: BTreeMap::new(), + } + } + /// Read summary from file. + pub fn read(path: &Path) -> Result { + let summary = std::fs::read_to_string(path) + .wrap_err_with(|| format!(""Failed to read file: {path:?}.""))?; + let summary = serde_json::from_str(&summary) + .wrap_err_with(|| format!(""Failed to parse file: {path:?}""))?; + + Ok(summary) + } + + /// Write summary to file. + pub fn write(&self, path: &Path) -> Result<(), Report> { + // create output file + let mut file = File::create(path) + .wrap_err_with(|| format!(""Failed to create file: {path:?}""))?; + + // parse to string + let output = serde_json::to_string_pretty(self) + .wrap_err_with(|| format!(""Failed to parse: {self:?}""))?; + + // write to file + file.write_all(format!(""{}\n"", output).as_bytes()) + .wrap_err_with(|| format!(""Failed to write file: {path:?}""))?; + + Ok(()) + } +} + +// ---------------------------------------------------------------------------- +// Dataset Summary Export Format + +pub enum SummaryExportFormat { + Json, +} + +impl SummaryExportFormat { + /// get extension from format + pub fn extension(&self) -> String { + match self { + SummaryExportFormat::Json => String::from(""json""), + } + } +} + +impl std::fmt::Display for SummaryExportFormat { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + SummaryExportFormat::Json => write!(f, ""json""), + } + } +} + +// ---------------------------------------------------------------------------- +// Dataset Summary Import Format + +pub enum SummaryImportFormat { + Json, +} + +impl SummaryImportFormat { + /// get extension from format + pub fn extension(&self) -> String { + match self { + SummaryImportFormat::Json => String::from(""json""), + } + } +} + +impl std::fmt::Display for SummaryImportFormat { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + SummaryImportFormat::Json => write!(f, ""json""), + } + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/list.rs",".rs","1802","64","use crate::cli; +use crate::dataset::attributes::Name; +use crate::utils::table::Table; +use color_eyre::eyre::{Report, Result}; +use itertools::Itertools; +use strum::{EnumProperty, IntoEnumIterator}; + +/// List datasets +pub fn datasets(args: &cli::dataset::list::Args) -> Result<(), Report> { + // table of name, tag, cli_version + let mut table = Table::new(); + table.headers = vec![ + ""Name"", + ""CLI Version"", + ""Minimum Tag Date"", + ""Maximum Tag Date"", + ] + .into_iter() + .map(String::from) + .collect_vec(); + + for name in Name::iter() { + // Check if this was not the name requested by CLI args + if let Some(args_name) = &args.name { + if &name != args_name { + continue; + } + } + + // check if this datset name is actually implemented currently + if name.get_str(""implemented"").unwrap_or(""false"") != ""true"" { + continue; + } + + // Extract compatibility attributes + let compatibility = name.compatibility()?; + + let cli_version = compatibility.cli.version.unwrap_or(String::new()); + let min_date = if let Some(min_date) = compatibility.dataset.min_date { + min_date.format(""%Y-%m-%d"").to_string() + } else { + ""nightly"".to_string() + }; + let max_date = if let Some(max_date) = compatibility.dataset.max_date { + max_date.format(""%Y-%m-%d"").to_string() + } else { + ""nightly"".to_string() + }; + + // Add to row + let row = vec![ + name.to_string(), + cli_version.to_string(), + min_date.to_string(), + max_date.to_string(), + ]; + table.rows.push(row); + } + + println!(""\n{}"", table.to_markdown()?); + + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/download.rs",".rs","7116","205","use crate::cli; +use crate::dataset; +use crate::dataset::attributes::{check_compatibility, Name, Summary}; +use crate::dataset::{sarscov2, toy1}; +use crate::{utils, utils::remote_file::RemoteFile}; +use color_eyre::eyre::{Report, Result}; +use itertools::Itertools; +use log::{info, warn}; +use std::fs::create_dir_all; +use std::path::Path; + +/// Download dataset +pub async fn dataset(args: &mut cli::dataset::download::Args) -> Result<(), Report> { + info!(""Downloading dataset: {} {}"", &args.name, &args.tag); + + // -------------------------------------------------------------------- + // Optional Input Summary Snapshot + + let mut summary: Summary = if let Some(summary_path) = &args.summary { + info!(""Importing summary: {summary_path:?}""); + let summary = Summary::read(summary_path)?; + + // Warn if summary conflicts with any CLI args + if summary.name != args.name || summary.tag != args.tag { + warn!( + ""Dataset has been changed by summary to: {} {}"", + &summary.name, &summary.tag + ); + } + summary + } else { + let mut summary = Summary::new(); + summary.name = args.name; + summary.tag = args.tag.clone(); + summary + }; + + // -------------------------------------------------------------------- + // Compatibility Check + + check_compatibility(&args.name, &args.tag)?; + + // Warn if the directory already exists + if !args.output_dir.exists() { + info!(""Creating output directory: {:?}"", &args.output_dir); + create_dir_all(&args.output_dir)?; + } else { + warn!( + ""Proceed with caution! --output-dir {:?} already exists."", + args.output_dir + ); + } + + // -------------------------------------------------------------------- + // Reference + + let output_path = args.output_dir.join(""reference.fasta""); + info!(""Downloading reference: {output_path:?}""); + + summary.reference = if args.summary.is_some() { + snapshot(&summary.reference, &output_path).await? + } else { + match args.name { + Name::SarsCov2 => { + sarscov2::download::reference(&args.tag, &output_path).await? + } + Name::Toy1 => toy1::download::reference(&args.tag, &output_path)?, + _ => todo!(), + } + }; + + // -------------------------------------------------------------------- + // Populations + + let output_path = args.output_dir.join(""populations.fasta""); + info!(""Downloading populations: {output_path:?}""); + + summary.populations = if args.summary.is_some() { + dataset::download::snapshot(&summary.populations, &output_path).await? + } else { + match args.name { + Name::SarsCov2 => { + sarscov2::download::populations(&args.tag, &output_path).await? + } + Name::Toy1 => toy1::download::populations(&args.tag, &output_path)?, + _ => todo!(), + } + }; + + // -------------------------------------------------------------------- + // Annotations + + let output_path = args.output_dir.join(""annotations.tsv""); + info!(""Creating annotations: {output_path:?}""); + + let annotations = match args.name { + Name::SarsCov2 => sarscov2::annotations::build()?, + Name::Toy1 => toy1::annotations::build()?, + _ => todo!(), + }; + annotations.write(&output_path)?; + + // -------------------------------------------------------------------- + // Graph (Phylogeny) + + let output_path = args.output_dir.join(""phylogeny.json""); + info!(""Building phylogeny: {output_path:?}""); + + let phylogeny = match args.name { + Name::SarsCov2 => { + sarscov2::phylogeny::build(&mut summary, &args.output_dir).await? + } + Name::Toy1 => toy1::phylogeny::build()?, + _ => todo!(), + }; + phylogeny.write(&output_path)?; + // Also write as .dot file for graphviz visualization. + let output_path = args.output_dir.join(""phylogeny.dot""); + info!(""Exporting graphviz phylogeny: {output_path:?}""); + phylogeny.write(&output_path)?; + + // -------------------------------------------------------------------- + // Export Mutations + + let output_path = args.output_dir.join(""mutations.json""); + info!(""Mapping mutations to populations: {output_path:?}""); + let mask = vec![0, 0]; + let (_populations, mutations) = dataset::load::parse_populations( + &summary.populations.local_path, + &summary.reference.local_path, + &mask, + )?; + dataset::write_mutations(&mutations, &output_path)?; + + // -------------------------------------------------------------------- + // Create Edge Cases + // + // Edge cases are simply a vector of the CLI Run Args (cli::run::Args) + // customized to particular recombinants. + + let output_path = args.output_dir.join(""edge_cases.json""); + info!(""Creating edge cases: {output_path:?}""); + + let mut edge_cases = match args.name { + Name::SarsCov2 => dataset::sarscov2::edge_cases::default()?, + Name::Toy1 => dataset::toy1::edge_cases::default()?, + _ => todo!(), + }; + let manual_populations = + edge_cases.iter().filter_map(|e| e.population.clone()).collect_vec(); + + let problematic_recombinants = phylogeny.get_problematic_recombinants()?; + for recombinant in problematic_recombinants { + let parents = phylogeny.get_parents(&recombinant)?; + warn!(""Recombinant {recombinant} is problematic. Parents are not sister taxa: {parents:?}""); + if manual_populations.contains(&recombinant) { + warn!(""Manual edge case exists: {recombinant:?}""); + } else { + warn!(""Creating auto edge case: {recombinant:?}""); + let edge_case = cli::run::Args { + population: Some(recombinant), + parents: Some(parents), + ..Default::default() + }; + edge_cases.push(edge_case); + } + } + + // Reminder, we use the module write method, not the struct method, + // because this is a vector of arguments we need to serialize. + cli::run::Args::write(&edge_cases, &output_path)?; + + // -------------------------------------------------------------------- + // Export Summary + + let output_path = args.output_dir.join(""summary.json""); + info!(""Exporting summary: {output_path:?}""); + summary.write(&output_path)?; + + // -------------------------------------------------------------------- + // Finish + + info!(""Done.""); + Ok(()) +} + +/// Download remote file from a summary snapshot. +pub async fn snapshot( + snapshot: &RemoteFile, + output_path: &Path, +) -> Result { + // Check extension for decompression + let ext = utils::path_to_ext(Path::new(&snapshot.url))?; + let decompress = ext == ""zst""; + + // Update the local path to the desired output + let mut remote_file = snapshot.clone(); + remote_file.local_path = output_path.to_path_buf(); + + // Download the file + utils::download_file(&snapshot.url, output_path, decompress).await?; + + Ok(remote_file) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/toy1/mod.rs",".rs","78","5","pub mod annotations; +pub mod download; +pub mod edge_cases; +pub mod phylogeny; +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/toy1/phylogeny.rs",".rs","1186","40","use crate::phylogeny::Phylogeny; +use color_eyre::eyre::{Report, Result}; + +pub fn build() -> Result { + let mut phylogeny = Phylogeny::new(); + + // Add root node + let name = ""root"".to_string(); + let root_id = phylogeny.graph.add_node(name.clone()); + + // Add A node + let name = ""A"".to_string(); + let a_id = phylogeny.graph.add_node(name.clone()); + phylogeny.graph.add_edge(root_id, a_id, 1); + + // Add B node + let name = ""B"".to_string(); + let b_id = phylogeny.graph.add_node(name.clone()); + phylogeny.graph.add_edge(root_id, b_id, 1); + + // Add C node + let name = ""C"".to_string(); + let c_id = phylogeny.graph.add_node(name.clone()); + phylogeny.graph.add_edge(root_id, c_id, 1); + + // Add recombinant D node + let name = ""D"".to_string(); + let d_id = phylogeny.graph.add_node(name.clone()); + phylogeny.graph.add_edge(a_id, d_id, 1); + phylogeny.graph.add_edge(b_id, d_id, 1); + + // Add recursive recombinant E node + let name = ""E"".to_string(); + let e_id = phylogeny.graph.add_node(name.clone()); + phylogeny.graph.add_edge(d_id, e_id, 1); + phylogeny.graph.add_edge(c_id, e_id, 1); + + Ok(phylogeny) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/toy1/edge_cases.rs",".rs","233","9","use crate::cli::run; +use color_eyre::eyre::{Report, Result}; + +/// Create default Toy1 recombinant edge cases. +pub fn default() -> Result, Report> { + let edge_cases: Vec = Vec::new(); + Ok(edge_cases) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/toy1/annotations.rs",".rs","642","24","use crate::utils::table::Table; +use color_eyre::eyre::{Report, Result}; +use itertools::Itertools; + +/// Create Toy1 genome annotations. +pub fn build() -> Result { + let mut table = Table::new(); + + let headers = vec![""gene"", ""abbreviation"", ""start"", ""end""]; + let rows = vec![ + vec![""Gene1"", ""g1"", ""1"", ""3""], + vec![""Gene2"", ""g2"", ""12"", ""20""], + ]; + + // Convert values to String + table.headers = headers.into_iter().map(String::from).collect_vec(); + table.rows = rows + .into_iter() + .map(|row| row.into_iter().map(String::from).collect_vec()) + .collect_vec(); + + Ok(table) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/toy1/download.rs",".rs","1638","63","use crate::dataset::attributes::Tag; +use crate::utils::remote_file::RemoteFile; +use chrono::Local; +use color_eyre::eyre::{Report, Result, WrapErr}; +use indoc::formatdoc; +use std::fs::File; +use std::io::Write; +use std::path::Path; + +/// Create and write Toy1 reference sequence. +pub fn reference(_tag: &Tag, path: &Path) -> Result { + let sequences = formatdoc!( + "" + >Reference + AAAAAAAAAAAAAAAAAAAA + "" + ); + + let mut file = File::create(path) + .wrap_err_with(|| format!(""Unable to create file: {path:?}""))?; + file.write_all(sequences.as_bytes()) + .wrap_err_with(|| format!(""Unable to write file: {path:?}""))?; + + let remote_file = RemoteFile { + local_path: path.to_owned(), + date_created: Local::now().into(), + ..Default::default() + }; + + Ok(remote_file) +} + +/// Create and write Toy1 populations sequence. +pub fn populations(_tag: &Tag, path: &Path) -> Result { + let sequences = formatdoc!( + "" + >A + CCCCCCAACCCCCCCCCCCC + >B + TTTTTTTTTTTTTTTTTTAA + >C + AAGGGGGGGGGGGGGGGGGG + >D + CCCCCCAACCCTTTTTTTAA + >E + AAGCCCAACCCTTTTTTTAA + "" + ); + + let mut file = File::create(path) + .wrap_err_with(|| format!(""Unable to create file: {path:?}""))?; + file.write_all(sequences.as_bytes()) + .wrap_err_with(|| format!(""Unable to write file: {path:?}""))?; + + let remote_file = RemoteFile { + local_path: path.to_owned(), + date_created: Local::now().into(), + ..Default::default() + }; + + Ok(remote_file) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/sarscov2/mod.rs",".rs","78","5","pub mod annotations; +pub mod download; +pub mod edge_cases; +pub mod phylogeny; +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/sarscov2/phylogeny.rs",".rs","16205","428","use crate::{dataset, phylogeny::Phylogeny, utils::table::Table}; +use bio::io::fasta; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use color_eyre::Help; +use itertools::Itertools; +use log::{debug, info, warn}; +use std::collections::BTreeMap; +use std::path::Path; + +pub async fn build( + summary: &mut dataset::attributes::Summary, + output_dir: &Path, +) -> Result { + // ------------------------------------------------------------------------ + // Download + // ------------------------------------------------------------------------ + + // ------------------------------------------------------------------------ + // Lineage Notes + let output_path = output_dir.join(""lineage_notes.txt""); + info!(""Downloading lineage notes: {output_path:?}""); + + let remote_file = if summary.misc.contains_key(""lineage_notes"") { + dataset::download::snapshot(&summary.misc[""lineage_notes""], &output_path).await? + } else { + dataset::sarscov2::download::lineage_notes(&summary.tag, &output_path).await? + }; + summary.misc.insert(""lineage_notes"".to_string(), remote_file); + + // ------------------------------------------------------------------------ + // Alias key + let output_path = output_dir.join(""alias_key.json""); + info!(""Downloading alias key: {output_path:?}""); + + let remote_file = if summary.misc.contains_key(""alias_key"") { + dataset::download::snapshot(&summary.misc[""alias_key""], &output_path).await? + } else { + dataset::sarscov2::download::alias_key(&summary.tag, &output_path).await? + }; + summary.misc.insert(""alias_key"".to_string(), remote_file); + + // ------------------------------------------------------------------------ + // Alias + // ------------------------------------------------------------------------ + + // read alias key into Map + let alias_key_path = &summary.misc[""alias_key""].local_path; + let alias_key_file_name = alias_key_path.file_name().unwrap().to_str().unwrap(); + let mut alias_key = read_alias_key(alias_key_path)?; + + // MANUAL! + // These are potential conflicts in the prior information, that will + // cause validation to fail + + // Potentially, XAS needs deletions to resolve between BA.4/BA.5 parent? + warn!(""Changing XAS designated parent from BA.5 to BA.4: https://github.com/cov-lineages/pango-designation/issues/882""); + let recombinant = ""XAS"".to_string(); + let parents = vec![""BA.4"".to_string(), ""BA.2"".to_string()]; + alias_key.insert(recombinant, parents); + + warn!(""Relaxing XBB designated parent from BM.1.1.1 to BA.2.75.3""); + let recombinant = ""XBB"".to_string(); + let parents = vec![""BJ.1"".to_string(), ""BA.2.75.3"".to_string()]; + alias_key.insert(recombinant, parents); + + warn!(""Relaxing XBF designated parent from BA.5.2.3 to BA.5.2""); + let recombinant = ""XBF"".to_string(); + let parents = vec![""BA.5.2"".to_string(), ""CJ.1"".to_string()]; + alias_key.insert(recombinant, parents); + + // ------------------------------------------------------------------------ + // Lineage Notes + // ------------------------------------------------------------------------ + + // read lineage notes into Table + let lineage_notes_path = &summary.misc[""lineage_notes""].local_path; + let lineage_notes_file_name = + lineage_notes_path.file_name().unwrap().to_str().unwrap(); + let lineage_table = Table::read(lineage_notes_path)?; + // identify which column is 'Lineage' + let lineage_col_i = lineage_table.header_position(""Lineage"")?; + // get a list of lineages in the notes + let notes_lineages = lineage_table + .rows + .iter() + .filter(|row| { + !row[lineage_col_i].starts_with('*') && row[lineage_col_i].is_empty() + }) + .map(|row| row[lineage_col_i].to_string()) + .collect_vec(); + + // read populations fasta, to check if any lineages are missing in notes + let populations_path = &summary.populations.local_path; + let populations_file_name = populations_path.file_name().unwrap().to_str().unwrap(); + let alignment_reader = fasta::Reader::from_file(populations_path) + .map_err(|e| eyre!(e)) + .wrap_err(""Failed to read file: {populations_path:?}"")?; + + // keep track of population names in alignment, cross-reference against + // lineage notes + alias_key later + let mut alignment_populations = Vec::new(); + for result in alignment_reader.records() { + let record = + result.wrap_err(eyre!(""Failed to parse file: {populations_path:?}""))?; + let lineage = record.id().to_string(); + alignment_populations.push(lineage); + } + + // ------------------------------------------------------------------------ + // Parent Child Relationships + // ------------------------------------------------------------------------ + + let mut graph_order = Vec::new(); + let mut graph_data = BTreeMap::new(); + + for row in lineage_table.rows { + let lineage = row[lineage_col_i].to_string(); + + // Lineages that start with '*' have been withdrawn + if lineage.starts_with('*') || lineage == String::new() { + continue; + } + + let parents = get_lineage_parents(&lineage, &alias_key)?; + graph_order.push(lineage.clone()); + graph_data.insert(lineage, parents); + } + + // ------------------------------------------------------------------------ + // Graph (Phylogeny) + // ------------------------------------------------------------------------ + + let mut phylogeny = Phylogeny::new(); + + // Add root node + let name = ""root"".to_string(); + phylogeny.graph.add_node(name); + + // todo!() Do this twice? in case lineages are accidentally out of order? + + // Add descendants + for name in graph_order { + let id = phylogeny.graph.add_node(name.clone()); + if !graph_data.contains_key(&name) { + return Err( + eyre!(""Parents of {name} are unknown in the phylogeny graph."") + .suggestion( + ""Could the lineage_notes be out of order or misformatted?"", + ) + .suggestion(""Parents are required to appear before children.""), + ); + } + let parents = graph_data.get(&name).unwrap(); + + debug!(""Population: {name}; Parents: {parents:?}""); + + // If multiple parents add this to recombinants list + if parents.len() > 1 { + phylogeny.recombinants.push(name.clone()); + } + for parent in parents { + if phylogeny.get_node(parent).is_err() { + return Err(eyre!(""Parental lineage {parent} is not in the graph."") + .suggestion( + ""Are the alias_key.json and lineage_notes.txt out of sync?"", + ) + .suggestion(""Please check if {parent} is in the alias key."")); + } + let parent_id = phylogeny.get_node(parent)?; + phylogeny.graph.add_edge(parent_id, id, 1); + } + } + + phylogeny.recombinants_all = phylogeny.get_recombinants_all()?; + + // ------------------------------------------------------------------------ + // Consistency Check + // ------------------------------------------------------------------------ + + // All population names in all files + let mut all_populations = alignment_populations.clone(); + all_populations.extend(notes_lineages.clone()); + all_populations.extend(alias_key.keys().cloned().collect_vec()); + all_populations.sort(); + all_populations.dedup(); + + // create table to store consistency info + let inconsistency_table_path = output_dir.join(""inconsistency.tsv""); + let mut inconsistency_table = Table::new(); + + info!(""Writing dataset inconsistency table: {inconsistency_table_path:?}""); + + inconsistency_table.headers = vec![""population"", ""present"", ""absent""] + .into_iter() + .map(String::from) + .collect_vec(); + + let population_col_i = inconsistency_table.header_position(""population"")?; + let present_col_i = inconsistency_table.header_position(""present"")?; + let absent_col_i = inconsistency_table.header_position(""absent"")?; + + // missing population sequences + let mut missing_pop_seq = Vec::new(); + + // check consistency between populations fasta, lineage_notes, alias_key, phylogeny + all_populations.iter().for_each(|pop| { + let mut present_file_names = Vec::new(); + let mut absent_file_names = Vec::new(); + + // Alias Key + if alias_key.contains_key(pop) { + present_file_names.push(&alias_key_file_name); + } else if !pop.contains('.') { + absent_file_names.push(&alias_key_file_name); + } + + // Lineage Notes + if notes_lineages.contains(pop) { + present_file_names.push(&lineage_notes_file_name); + } else { + absent_file_names.push(&lineage_notes_file_name); + } + + // Populations Fasta + if alignment_populations.contains(pop) { + present_file_names.push(&populations_file_name); + } else { + absent_file_names.push(&populations_file_name); + missing_pop_seq.push(pop.clone()); + } + + // Phylogeny + // self.graph.node_references() + + if !absent_file_names.is_empty() { + let mut row = vec![String::new(); inconsistency_table.headers.len()]; + row[population_col_i] = pop.to_string(); + row[present_col_i] = present_file_names.iter().join("",""); + row[absent_col_i] = absent_file_names.iter().join("",""); + inconsistency_table.rows.push(row); + } + }); + + inconsistency_table.write(&inconsistency_table_path)?; + + Ok(phylogeny) +} + +/// Get all immediate parents of a SARS-CoV-2 lineage. +pub fn get_lineage_parents( + lineage: &str, + alias_key: &BTreeMap>, +) -> Result, Report> { + let mut parents: Vec = Vec::new(); + + // If Recombinant with multiple parents, if so, it will be in the alias + // key with the parents listed. + if alias_key.contains_key(lineage) { + let lineage_paths = &alias_key[lineage]; + if lineage_paths.len() > 1 { + // Dedup in case multiple breakpoints/parents + parents = lineage_paths.clone().into_iter().unique().collect(); + return Ok(parents); + } + } + + // Otherwise, single parent + let decompress = decompress_lineage(lineage, alias_key).unwrap(); + + // Ex. BA.5.2 -> [""BA"", ""5"", ""2""] + let decompress_parts = + decompress.split('.').map(|p| p.to_string()).collect::>(); + + // If just 1 part, parent is root (ex. A) + let mut parent = String::from(""root""); + if decompress_parts.len() > 1 { + parent = decompress_parts[0..(decompress_parts.len() - 1)].join("".""); + } + + // Compress the full parent back down with aliases + parent = compress_lineage(&parent, alias_key).unwrap(); + parents.push(parent); + + Ok(parents) +} + +/// Compress a SARS-CoV-2 lineage name into it's aliased form. +pub fn compress_lineage( + lineage: &String, + alias_key: &BTreeMap>, +) -> Result { + // By default, set compression level to self + let mut compress = lineage.to_string(); + + // Reverse the alias-> lineage path lookup + let mut alias_key_rev: BTreeMap = BTreeMap::new(); + + for (alias, lineage_paths) in alias_key { + // Skip over recombinants with multiple parents, don't need their lookup + if lineage_paths.len() > 1 { + continue; + } + let lineage_path = lineage_paths[0].clone(); + alias_key_rev.insert(lineage_path, alias.clone()); + } + + // Ex. BA.5.2 -> [""BA"", ""5"", ""2""] + let compress_parts = compress.split('.').map(|p| p.to_string()).collect::>(); + + if compress_parts.len() > 1 { + for i in (0..compress_parts.len()).rev() { + let compress_subset = compress_parts[0..i].join("".""); + + if alias_key_rev.contains_key(&compress_subset) { + compress = alias_key_rev.get(&compress_subset).unwrap().clone(); + // Get the suffix that was chopped off in subset + let compress_suffix = &compress_parts[i..]; + + // Add the suffix + if !compress_suffix.is_empty() { + compress = format![""{compress}.{}"", compress_suffix.join(""."")]; + } + break; + } + } + } + + Ok(compress) +} + +/// Decompress a SARS-CoV-2 lineage name into it's full unaliased form. +/// +/// # Arguments +/// +/// * `lineage` | A string slice that contains a SARS-CoV-2 lineage name. +/// * `alias_key` | A mapping of SARS-CoV-2 aliases to decompressed lineage paths. +/// ``` +pub fn decompress_lineage( + lineage: &str, + alias_key: &BTreeMap>, +) -> Result { + // By default, set full path to lineage + let mut decompress = lineage.to_string(); + + // Split lineage into levels, Ex. BA.5.2 = [""BA"", ""5"", ""2""] + // Can be a maximum of 4 levels before aliasing + let mut lineage_level = 0; + let mut lineage_parts = vec![String::new(); 4]; + + for (i, level) in lineage.split('.').enumerate() { + lineage_parts[i] = level.to_string(); + lineage_level = i + 1; + } + + // Get the first letter prefix, Ex. BA.5.2 = ""BA"" + let lineage_prefix = lineage_parts[0].clone(); + // If there were multiple parts, get suffix (Ex. ""BA"" and ""5.2"") + let lineage_suffix = lineage_parts[1..lineage_level].join("".""); + + // Decompressing logic + let lineage_paths = alias_key.get(&lineage_prefix).cloned().unwrap_or_default(); + // Not multiple recombinant parents + if lineage_paths.len() == 1 { + decompress = lineage_paths[0].clone(); + // Add back our suffix numbers + if lineage_level > 1 { + decompress = format!(""{decompress}.{lineage_suffix}""); + } + } + + Ok(decompress) +} + +/// Read SARS-CoV-2 alias key from file. +/// +/// Reads the JSON file into a Map where keys are lineage names, and +/// values are a vector of parents. +pub fn read_alias_key(path: &Path) -> Result>, Report> { + // read to json + let alias_key_str = + std::fs::read_to_string(path).expect(""Couldn't read alias_key file.""); + let alias_key_val: serde_json::Value = + serde_json::from_str(&alias_key_str).expect(""Couldn't convert alias_key to json""); + // deserialize to object (raw, mixed types) + let alias_key_raw: serde_json::Map = alias_key_val + .as_object() + .expect(""Couldn't convert alias_key json to json Map"") + .clone(); + + // This should probably be a custom serializer fn for brevity, + // but I don't know how to do that yet :) + let mut alias_key: BTreeMap> = BTreeMap::new(); + + for (alias, lineage) in &alias_key_raw { + let mut lineage_paths: Vec = Vec::new(); + + // Consistify the alias key types + match lineage.as_array() { + // If array, this is a recombinant alias with multiple parents. + Some(parents) => { + for parent in parents { + let parent = + parent.as_str().expect(""Couldn't convert parent to str.""); + // Strip the wildcard asterisks from lineage name + let parent_clean = str::replace(parent, ""*"", """"); + lineage_paths.push(parent_clean); + } + } + // Otherwise, it might be a string + None => { + let mut lineage_path = lineage + .as_str() + .expect(""Couldn't convert lineage to str."") + .to_string(); + // If there is not lineage_path (ex. """" for A, B), set to self + if lineage_path.is_empty() { + lineage_path = alias.clone(); + } + lineage_paths.push(lineage_path); + } + } + + alias_key.insert(alias.clone(), lineage_paths); + } + + Ok(alias_key) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/sarscov2/edge_cases.rs",".rs","6067","175","use crate::cli::run; +use color_eyre::eyre::{Report, Result}; +use log::debug; + +/// Create default SARS-CoV-2 recombinant edge cases. +pub fn default() -> Result, Report> { + let mut edge_cases: Vec = Vec::new(); + + // -------------------------------------------------------------------- + // Manual + + // XR: BA.2 and BA.1 with no unique subs from BA.1 + let recombinant = ""XR"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_subs: 0, + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // XP: BA.1 and BA.2 with a single sub from BA.2 + let recombinant = ""XP"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 1, + min_length: 1, + parents: Some(vec![""BA.1.1"".to_string(), ""BA.2"".to_string()]), + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XAV: BA.5.1.24 and BA.2 with only two consecutive BA.2 subs + + let recombinant = ""XAV"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 2, + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // XAZ: BA.5 and BA.2.5 with a single sub from BA.2.5 + let recombinant = ""XAZ"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 1, + min_length: 1, + min_subs: 0, + parents: Some(vec![""BA.5"".to_string(), ""BA.2.5"".to_string()]), + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // XBK: BA.5.2 and CJ.2 with only 2 consecutive alleles from BA.5.2 + let recombinant = ""XBK"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 2, + population: Some(recombinant), + parents: Some(vec![""BA.5.2"".to_string(), ""CJ.1"".to_string()]), + ..Default::default() + }; + edge_cases.push(edge_case); + // XBQ: BA.5.2 and CJ.2 with only 2 consecutive alleles from BA.5.2 + let recombinant = ""XBQ"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 2, + population: Some(recombinant), + parents: Some(vec![""BA.5.2"".to_string(), ""CJ.1"".to_string()]), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XBZ: EF.1.3 with very small 5' from BA.5.2 + let recombinant = ""XBZ"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_length: 200, + min_consecutive: 2, + parents: Some(vec![""EF.1.3"".to_string(), ""BA.5.2"".to_string()]), + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XCF: FE.1 (XBB.1.18.1) and XBB.1.5.44 with few consecutive + let recombinant = ""XCF"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_subs: 0, + min_consecutive: 2, + parents: Some(vec![""FE.1"".to_string(), ""XBB"".to_string()]), + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XCG: BA.5.2 and XBB.1 with only 2 consecutive bases + + let recombinant = ""XCG"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_subs: 1, + min_consecutive: 2, + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XCL: GK.2.1 and FY.4.2 (only pop with C7417T, 2023-11-20) + + let recombinant = ""XCL"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + population: Some(recombinant), + parents: Some(vec![""GK.2.1.1"".to_string(), ""FY.4.2"".to_string()]), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XCM: XBB.2.3.13 and DV.7.1.2 + + let recombinant = ""XCM"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + population: Some(recombinant), + parents: Some(vec![""DV.7.1.2"".to_string(), ""XBB.2.3.13"".to_string()]), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XCQ: XBB.2.3 and XBB.1.5 with only 2 consecutive + + let recombinant = ""XCQ"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_consecutive: 2, + min_length: 400, + population: Some(recombinant), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // XDB: XBB.1.16.19 with double reversion assumed from XBB + + let recombinant = ""XDB"".to_string(); + debug!(""Creating manual edge case: {recombinant:?}""); + let edge_case = run::Args { + min_subs: 0, + min_consecutive: 2, + population: Some(recombinant), + parents: Some(vec![""XBB.1.16.19"".to_string(), ""XBB"".to_string()]), + ..Default::default() + }; + edge_cases.push(edge_case); + + // -------------------------------------------------------------------- + // Finish + + Ok(edge_cases) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/sarscov2/annotations.rs",".rs","1064","33","use crate::utils::table::Table; +use color_eyre::eyre::{Report, Result}; +use itertools::Itertools; + +/// Create SARS-CoV-2 genome annotations. +pub fn build() -> Result { + let mut table = Table::new(); + + let headers = vec![""gene"", ""abbreviation"", ""start"", ""end""]; + let rows = vec![ + vec![""ORF1a"", ""1a"", ""266"", ""13468""], + vec![""ORF1b"", ""1b"", ""13468"", ""21555""], + vec![""S"", ""S"", ""21563"", ""25384""], + vec![""ORF3a"", ""3a"", ""25393"", ""26220""], + vec![""E"", ""E"", ""26245"", ""26472""], + vec![""M"", ""M"", ""26523"", ""27191""], + vec![""ORF6"", ""6"", ""27202"", ""27387""], + vec![""ORF7a"", ""7a"", ""27394"", ""27759""], + vec![""ORF7b"", ""7b"", ""27756"", ""27887""], + vec![""ORF8"", ""8"", ""27894"", ""28259""], + vec![""ORF9b"", ""9b"", ""28284"", ""28577""], + ]; + + // Convert values to String + table.headers = headers.into_iter().map(String::from).collect_vec(); + table.rows = rows + .into_iter() + .map(|row| row.into_iter().map(String::from).collect_vec()) + .collect_vec(); + + Ok(table) +} +","Rust" +"Microbiology","phac-nml/rebar","src/dataset/sarscov2/download.rs",".rs","2795","67","use crate::dataset::attributes::Tag; +use crate::utils::{download_github, remote_file::RemoteFile}; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use std::path::Path; + +pub async fn reference(tag: &Tag, output_path: &Path) -> Result { + let repo = ""nextstrain/ncov""; + let remote_path = ""data/references_sequences.fasta""; + let sha: Option = None; + let remote_file = download_github(repo, tag, remote_path, output_path, &sha) + .await + .wrap_err_with(|| eyre!(""Failed downloading sars-cov-2 reference fasta.""))?; + Ok(remote_file) +} +pub async fn populations(tag: &Tag, output_path: &Path) -> Result { + let repo = ""corneliusroemer/pango-sequences""; + let remote_path = ""data/pango-consensus-sequences_genome-nuc.fasta.zst""; + let sha: Option = None; + let remote_file = download_github(repo, tag, remote_path, output_path, &sha) + .await + .wrap_err_with(|| eyre!(""Failed downloading sars-cov-2 populations fasta.""))?; + Ok(remote_file) +} + +/// Download the SARS-CoV-2 alias key. +/// +/// The alias key is a JSON mapping lineage names to their parents. +/// Needed to construct the phylogeny and identify known recombinants. +pub async fn alias_key(tag: &Tag, output_path: &Path) -> Result { + let repo = ""cov-lineages/pango-designation""; + let remote_path = ""pango_designation/alias_key.json""; + let sha: Option = None; + let remote_file = download_github(repo, tag, remote_path, output_path, &sha) + .await + .wrap_err_with(|| eyre!(""Failed downloading sars-cov-2 alias key.""))?; + Ok(remote_file) +} + +/// Download the SARS-CoV-2 lineage notes. +/// +/// The lineage notes has two columns: 'Lineage', 'Description'. +/// We only need the 'Lineage' column, to get the full list of all lineages. +pub async fn lineage_notes(tag: &Tag, output_path: &Path) -> Result { + let repo = ""cov-lineages/pango-designation""; + let remote_path = ""lineage_notes.txt""; + let sha: Option = None; + let remote_file = download_github(repo, tag, remote_path, output_path, &sha) + .await + .wrap_err_with(|| eyre!(""Failed downloading sars-cov-2 lineage notes.""))?; + Ok(remote_file) +} + +/// Download the SARS-CoV-2 nameTable mapping clades to lineage names. +pub async fn clade_to_lineage( + tag: &Tag, + output_path: &Path, +) -> Result { + let repo = ""hodcroftlab/covariants""; + let remote_path = ""web/data/nameTable.json""; + let sha: Option = None; + let remote_file = + download_github(repo, tag, remote_path, output_path, &sha).await.wrap_err_with( + || eyre!(""Failed downloading sars-cov-2 clade_to_lineage nameTable.""), + )?; + Ok(remote_file) +} +","Rust" +"Microbiology","phac-nml/rebar","src/simulate/mod.rs",".rs","3798","113","use crate::cli; +use crate::dataset; +use crate::recombination; + +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use itertools::Itertools; +use log::{debug, info}; +use rand::Rng; +use std::fs::{create_dir_all, File}; +use std::io::Write; + +/// Simulate recombination. +pub fn simulate(args: &cli::simulate::Args) -> Result<(), Report> { + // create output directory if it doesn't exist + if !args.output_dir.exists() { + info!(""Creating output directory: {:?}"", args.output_dir); + create_dir_all(&args.output_dir)?; + } + + // Load dataset, disable masking + info!(""Loading dataset: {:?}"", &args.dataset_dir); + let mask = vec![0, 0]; + let dataset = dataset::load::dataset(&args.dataset_dir, &mask)?; + let genome_length = dataset.reference.genome_length; + + // Check to make sure all parents are in dataset + let parents = args.parents.clone(); + for parent in &parents { + if !dataset.populations.contains_key(parent.as_str()) { + return Err(eyre!( + ""Parent {parent} is not the dataset populations fasta."" + )); + } + } + + // ------------------------------------------------------------------------ + // Breakpoints + + let mut breakpoints = if let Some(breakpoints) = &args.breakpoints { + info!(""Using manual breakpoints: {breakpoints:?}""); + breakpoints.clone() + } else { + let mut breakpoints = Vec::new(); + let mut num_breakpoints_remaining = parents.len() - 1; + let mut start = 1; + let mut rng = rand::thread_rng(); + while num_breakpoints_remaining > 0 { + // save some coordinates for future breakpoints + let end = genome_length - num_breakpoints_remaining; + let coord = rng.gen_range(start..end); + breakpoints.push(coord); + start = coord + 1; + num_breakpoints_remaining -= 1; + } + info!(""Using random breakpoints: {breakpoints:?}""); + breakpoints + }; + + let unique_key = format!( + ""simulate_{}_{}"", + &parents.iter().join(""_""), + &breakpoints.iter().map(|start| format!(""{start}-{}"", start + 1)).join(""_""), + ); + info!(""Unique Key: {unique_key:?}""); + + // ------------------------------------------------------------------------ + // Regions + + breakpoints.push(genome_length); + let mut regions = Vec::new(); + let mut start = 1; + + for (origin, end) in parents.into_iter().zip(breakpoints.into_iter()) { + let region = recombination::Region { + start, + end, + origin, + substitutions: Vec::new(), + }; + regions.push(region); + start = end + 1; + } + debug!(""Regions: {regions:?}""); + + // ------------------------------------------------------------------------ + // Sequences + + let sequence: String = regions + .iter() + .map(|region| { + let sequence = dataset.populations.get(®ion.origin).unwrap_or_else(|| { + panic!( + ""Failed to find region origin {} in dataset populations."", + ®ion.origin + ) + }); + // Reminder, -1 to coordinates since they are 1-based + sequence.seq[region.start - 1..=region.end - 1].iter().collect::() + }) + .collect(); + + let output_path = args.output_dir.join(format!(""{unique_key}.fasta"")); + info!(""Exporting fasta: {output_path:?}""); + let mut output_file = File::create(&output_path) + .wrap_err_with(|| format!(""Unable to create file: {output_path:?}""))?; + let lines = format!("">{unique_key}\n{sequence}""); + output_file + .write_all(lines.as_bytes()) + .wrap_err_with(|| format!(""Unable to write file: {output_path:?}""))?; + + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/sequence/mod.rs",".rs","7903","253","pub mod parsimony; + +use bio::io::fasta; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use color_eyre::Help; +use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; +use std::default::Default; +use std::path::Path; +use std::str::FromStr; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +pub enum Mutation { + Substitution, + Deletion, +} + +// ---------------------------------------------------------------------------- +// Deletion +// ---------------------------------------------------------------------------- + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +pub struct Deletion { + pub coord: usize, + pub reference: char, + pub alt: char, +} + +impl std::fmt::Display for Deletion { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, ""{}{}{}"", self.reference, self.coord, self.alt) + } +} + +impl PartialEq for Deletion { + fn eq(&self, other: &Self) -> bool { + self.coord == other.coord + && self.reference == other.reference + && self.alt == other.alt + } +} + +impl Eq for Deletion {} + +impl Ord for Deletion { + fn cmp(&self, other: &Self) -> Ordering { + self.coord.cmp(&other.coord) + } +} + +impl PartialOrd for Deletion { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +// ---------------------------------------------------------------------------- +// Substitution +// ---------------------------------------------------------------------------- + +#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq)] +pub struct Substitution { + pub coord: usize, + pub reference: char, + pub alt: char, +} + +impl std::fmt::Display for Substitution { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, ""{}{}{}"", self.reference, self.coord, self.alt) + } +} + +impl FromStr for Substitution { + type Err = Report; + + fn from_str(text: &str) -> Result { + let reference = text.chars().next().unwrap(); + let alt = text.chars().nth(text.len() - 1).unwrap(); + let coord = text[1..text.len() - 1].parse().unwrap(); + let substitution = Substitution { + reference, + alt, + coord, + }; + + Ok(substitution) + } +} + +impl Eq for Substitution {} + +impl Ord for Substitution { + fn cmp(&self, other: &Self) -> Ordering { + self.coord.cmp(&other.coord) + } +} + +impl PartialOrd for Substitution { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Substitution { + pub fn to_deletion(&self) -> Deletion { + Deletion { + coord: self.coord, + reference: self.reference, + alt: '-', + } + } +} + +// ---------------------------------------------------------------------------- +// Substitution +// ---------------------------------------------------------------------------- + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Sequence { + pub id: String, + pub seq: Vec, + alphabet: Vec, + pub genome_length: usize, + pub substitutions: Vec, + pub deletions: Vec, + pub missing: Vec, +} + +impl Sequence { + pub fn new() -> Self { + Sequence { + id: String::new(), + seq: Vec::new(), + alphabet: vec!['A', 'C', 'G', 'T'], + genome_length: 0, + substitutions: Vec::new(), + deletions: Vec::new(), + missing: Vec::new(), + } + } + + pub fn from_record( + record: bio::io::fasta::Record, + reference: Option<&Sequence>, + mask: &Vec, + ) -> Result { + let mut sample = Sequence::new(); + sample.id = record.id().to_string(); + sample.seq = record.seq().iter().map(|b| *b as char).collect(); + + // check mask coord + for bases in mask { + if *bases > sample.seq.len() { + return Err( + eyre!(""5' and 3' masking ({mask:?}) is incompatible with sequence length {}"", sample.seq.len()) + .suggestion(""Please change your --mask parameter."") + .suggestion(""Maybe you want to disable masking all together with --mask 0,0 ?"") + ); + } + } + + if let Some(reference) = reference { + if sample.seq.len() != reference.seq.len() { + return Err( + eyre!( + ""Reference sequence ({ref_len}) and {record_id} ({record_len}) are different lengths!"", + ref_len=reference.seq.len(), + record_id=sample.id, + record_len=sample.seq.len(), + ) + .suggestion(""Are you sure your --alignment is aligned correctly?"") + ); + } + sample.genome_length = reference.seq.len(); + // Construct iterator to traverse sample and reference bases together + let it = sample.seq.iter().zip(reference.seq.iter()); + for (i, (s, r)) in it.enumerate() { + // Genomic coordinates are 1-based + let coord: usize = i + 1; + let mut s = *s; + let r = *r; + // Mask 5' and 3' ends + if !mask.is_empty() && coord <= mask[0] { + s = 'N'; + } + if mask.len() == 2 && coord > sample.genome_length - mask[1] { + s = 'N'; + } + + match s { + // Missing data (N) + 'N' => sample.missing.push(coord), + // Reference Missing data (N) + _s if r == 'N' => continue, + // Deletion + '-' => { + let deletion = Deletion { + coord, + reference: r, + alt: s, + }; + sample.deletions.push(deletion) + } + // Ambiguous data (IUPAC not in alphabet) + s if s != r && !sample.alphabet.contains(&s) => { + sample.missing.push(coord) + } + // Substitution + s if s != r => { + let substitution = Substitution { + coord, + reference: r, + alt: s, + }; + sample.substitutions.push(substitution) + } + // Reference + _ => continue, + } + } + } else { + sample.genome_length = sample.seq.len(); + } + + Ok(sample) + } +} + +// ---------------------------------------------------------------------------- +// Functions +// ---------------------------------------------------------------------------- + +/// Read first record of fasta path into sequence record. +pub fn read_reference(path: &Path, mask: &Vec) -> Result { + // start reading in the reference as fasta, raise error if file doesn't exist + let reader = fasta::Reader::from_file(path).expect(""Unable to read reference""); + + // parse just the first record from the reference + // 1. raise error if record iterator doesn't work + // 2. raise error if first record is not proper fasta format. + let reference = reader + .records() + .next() + .ok_or_else(|| eyre!(""Unable to read reference records: {path:?}""))? + .wrap_err_with(|| eyre!(""Unable to read first fasta record: {path:?}""))?; + + // convert to sequence + let reference = Sequence::from_record(reference, None, mask)?; + + Ok(reference) +} +","Rust" +"Microbiology","phac-nml/rebar","src/sequence/parsimony.rs",".rs","3462","99","use crate::sequence::{Sequence, Substitution}; +use color_eyre::eyre::{Report, Result}; +use indoc::formatdoc; +use itertools::Itertools; +use serde::{Deserialize, Serialize}; + +// ---------------------------------------------------------------------------- +// Population Parsimony Summary + +/// Summarize support and conflicts between two sequences. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Summary { + pub support: Vec, + pub conflict_ref: Vec, + pub conflict_alt: Vec, + pub score: isize, +} + +impl Summary { + pub fn new() -> Self { + Summary { + support: Vec::new(), + conflict_ref: Vec::new(), + conflict_alt: Vec::new(), + score: 0, + } + } + + /// Summarize support and conflicts between two sequences. + pub fn from_sequence( + sequence: &Sequence, + query: &Sequence, + coordinates: Option<&[usize]>, + ) -> Result { + let mut parsimony_summary = Summary::new(); + + // get all the substitutions found in the sequence + let mut seq_subs = sequence.substitutions.clone(); + //println!(""seq_subs: {}"", seq_subs.iter().join("","")); + // exclude coordinates that are in the sequence missing or deletions + let mut exclude_coordinates = + sequence.deletions.iter().map(|d| d.coord).collect_vec(); + exclude_coordinates.extend(sequence.missing.clone()); + // get all the substitutions found in this query + // exclude missing and deletion coordinates + let mut query_subs = query.substitutions.clone(); + query_subs.retain(|s| !exclude_coordinates.contains(&s.coord)); + //println!(""query_subs: {}"", query_subs.iter().join("","")); + + // optionally filter coordinates + if let Some(coordinates) = coordinates { + query_subs.retain(|sub| coordinates.contains(&sub.coord)); + seq_subs.retain(|sub| coordinates.contains(&sub.coord)); + } + + // support: sub in seq that is also in query + // conflict_alt: sub in seq that is not in candidate query + seq_subs.iter().for_each(|sub| { + if query_subs.contains(sub) { + parsimony_summary.support.push(*sub); + } else { + parsimony_summary.conflict_alt.push(*sub); + } + }); + + // conflict_ref: sub in query that is not in seq + parsimony_summary.conflict_ref = + query_subs.into_iter().filter(|sub| !seq_subs.contains(sub)).collect_vec(); + + // score: support - conflict_alt - conflict_ref + // why did we previously use only conflict_ref and not conflict_alt? + // individual isize conversion otherwise: ""attempt to subtract with overflow"" + parsimony_summary.score = parsimony_summary.support.len() as isize + - parsimony_summary.conflict_ref.len() as isize + - parsimony_summary.conflict_alt.len() as isize; + + Ok(parsimony_summary) + } + + pub fn pretty_print(&self) -> String { + formatdoc!( + ""score:\n {} + support:\n {} + conflict_ref:\n {} + conflict_alt:\n {}"", + self.score, + self.support.iter().join("", ""), + self.conflict_ref.iter().join("", ""), + self.conflict_alt.iter().join("", ""), + ) + } +} + +impl Default for Summary { + fn default() -> Self { + Self::new() + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/plot/constants.rs",".rs","2576","99","use raqote::*; + +// Embed fonts at compile time +pub const FONT_REGULAR: &[u8] = + include_bytes!(""../../assets/fonts/dejavu/DejaVuSans.ttf""); +pub const FONT_BOLD: &[u8] = + include_bytes!(""../../assets/fonts/dejavu/DejaVuSans-Bold.ttf""); + +pub const ALPHABET: [char; 4] = ['A', 'C', 'G', 'T']; + +// D3 Palettes: https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#categorical-colors +pub const PALETTE_DARK: [[u8; 4]; 9] = [ + [31, 119, 180, 255], // dark blue + [255, 127, 14, 255], // dark orange + [44, 160, 44, 255], // dark green + [214, 39, 39, 255], // dark red + [148, 103, 189, 255], // dark purple + [140, 86, 59, 255], // dark brown + [227, 119, 195, 255], // dark pink + //[127, 127, 127, 255], // dark grey + [188, 189, 34, 255], // dark green alt + [23, 189, 207, 255], // dark teal +]; + +pub const PALETTE_LIGHT: [[u8; 4]; 9] = [ + [174, 199, 232, 255], // light blue + [255, 187, 120, 255], // light orange + [152, 223, 138, 255], // light green + [255, 152, 150, 255], // light red + [197, 176, 213, 255], // light purple + [196, 156, 148, 255], // light brown + [247, 182, 210, 255], // light pink + //[199, 199, 199, 255], // light grey + [219, 219, 141, 255], // light green alt + [158, 218, 229, 255], // light teal +]; + +pub const WHITE: Source = Source::Solid(SolidSource { + r: 255, + g: 255, + b: 255, + a: 255, +}); +pub const BLACK: Source = Source::Solid(SolidSource { + r: 0, + g: 0, + b: 0, + a: 255, +}); + +pub const BLACK_ALT: image::Rgba = image::Rgba([0, 0, 0, 255]); + +pub const GREY: Source = Source::Solid(SolidSource { + r: 225, + g: 225, + b: 225, + a: 255, +}); + +pub const LIGHT_GREY: Source = Source::Solid(SolidSource { + r: 240, + g: 240, + b: 240, + a: 255, +}); + +pub const DARK_GREY: Source = Source::Solid(SolidSource { + r: 175, + g: 175, + b: 175, + a: 255, +}); + +pub const TRANSPARENT: Source = Source::Solid(SolidSource { + r: 0, + g: 0, + b: 0, + a: 0, +}); + +pub const TEXT_COLOR: image::Rgba = image::Rgba([0, 0, 0, 255]); +pub const FONT_SIZE: f32 = 25.0; +// want at least 2, a single pixel causes blurry artifacts +pub const LINE_WIDTH: f32 = 2.0; + +// needs to be just large enough to fit single char in FONT_SIZE +pub const X_INC: f32 = 50.0; +// small buffer for legibility +pub const BUFFER: f32 = 5.0; + +pub const BASIC_STROKE_STYLE: StrokeStyle = StrokeStyle { + cap: LineCap::Square, + join: LineJoin::Miter, + width: LINE_WIDTH, + miter_limit: 2., + dash_array: Vec::new(), + dash_offset: 16., +}; +","Rust" +"Microbiology","phac-nml/rebar","src/plot/mod.rs",".rs","43781","1168","pub mod constants; +pub mod polygon; +pub mod text; + +use crate::cli; +use crate::utils::table::Table; +use color_eyre::eyre::{eyre, Report, Result}; +use color_eyre::Help; +use itertools::Itertools; +use log::{debug, info, warn}; +use raqote::*; +use std::fs::create_dir_all; +use std::path::Path; + +/// Plot rebar output +pub fn plot(args: &cli::plot::Args) -> Result<(), Report> { + // ------------------------------------------------------------------------ + // Parse Args + + let run_dir = &args.run_dir; + if !run_dir.exists() { + return Err(eyre!(""--run-dir {run_dir:?} does not exist."")); + } + + // ------------------------------------------------------------------------ + // Check Mandatory Paths + + let linelist = &run_dir.join(""linelist.tsv""); + if !linelist.exists() { + return Err(eyre!( + ""Linelist file {linelist:?} does not exist in --run-dir {run_dir:?}."" + )); + } + let barcodes_dir = &run_dir.join(""barcodes""); + if !linelist.exists() { + return Err(eyre!( + ""Barcodes directory {barcodes_dir:?} does not exist in --run-dir {run_dir:?}."" + )); + } + + if let Some(annotations) = &args.annotations { + if !annotations.exists() { + return Err(eyre!(""Annotations do not exist: {annotations:?}"")); + } + } + + // create plot directory if it doesn't exist + let output_dir = args.output_dir.clone().unwrap_or(run_dir.join(""plots"")); + if !output_dir.exists() { + info!(""Creating plot directory: {output_dir:?}""); + create_dir_all(&output_dir)?; + } + + // ------------------------------------------------------------------------ + // List of Barcodes Files + + let mut barcodes_files: Vec = Vec::new(); + + // Input File Specified + let barcodes_file = &args.barcodes_file; + if let Some(barcodes_file) = barcodes_file { + if !barcodes_file.exists() { + return Err(eyre!(""Barcodes file {barcodes_file:?} does not exist."")); + } + barcodes_files.push(barcodes_file.clone()); + } + // Otherwise, use all files in barcodes_dir + else { + let files = std::fs::read_dir(barcodes_dir)?; + for result in files { + let file_path = result?.path(); + let file_ext = file_path.extension().unwrap_or(std::ffi::OsStr::new("""")); + if file_ext == ""tsv"" { + barcodes_files.push(file_path.clone()); + } else { + warn!(""Skipping barcodes file with unknown extension: {file_path:?}"") + } + } + } + + // ------------------------------------------------------------------------ + // Plot Each Barcodes + + for barcodes_file in barcodes_files { + info!(""Plotting barcodes file: {:?}"", barcodes_file); + let output_prefix = barcodes_file + .file_stem() + .expect(""Failed to get file stem of {barcodes_file:?}"") + .to_str() + .expect(""Failed to convert file of stem {barcodes_file:?} to str.""); + let output_path = output_dir.join(format!(""{}.png"", output_prefix)); + let result = create( + &barcodes_file, + linelist, + args.annotations.as_deref(), + &output_path, + args.all_coords, + ); + match result { + Ok(()) => (), + Err(e) => { + if e.to_string().contains(""not found in the linelist"") { + warn!(""The following error was encountered but ignored: {:?}"", e); + } + } + } + } + + info!(""Done.""); + Ok(()) +} + +#[allow(unused_variables)] +pub fn create( + barcodes_path: &Path, + linelist_path: &Path, + annotations_path: Option<&Path>, + output_path: &Path, + all_coords: bool, +) -> Result<(), Report> { + // ------------------------------------------------------------------------ + // Import Data + // ------------------------------------------------------------------------ + + let mut barcodes = Table::read(barcodes_path)?; + + let unique_key = barcodes_path.file_stem().unwrap().to_str().unwrap(); + + // filter the linelist to the current key + let mut linelist = Table::read(linelist_path)?; + //linelist = linelist.filter(""unique_key"", unique_key)?; + linelist = linelist.filter(""unique_key"", unique_key)?; + if linelist.rows.is_empty() { + return Err( + eyre!(""The barcodes unique key ({unique_key}) was not found in the linelist: {linelist_path:?}"") + .suggestion(format!(""Are you sure the barcodes file ({barcodes_path:?}) corresponds to the linelist?"")) + .suggestion(""Have you used the same --run-dir for multiple rebar runs?"") + ); + } + + // optional import data + let mut annotations = Table::new(); + if let Some(annotations_path) = annotations_path { + annotations = Table::read(annotations_path)? + } + + // check for mandatory columns and header pos + let genome_length_i = linelist.header_position(""genome_length"")?; + let breakpoints_i = linelist.header_position(""breakpoints"")?; + + let coord_i = barcodes.header_position(""coord"")?; + let origin_i = barcodes.header_position(""origin"")?; + let reference_i = barcodes.header_position(""Reference"")?; + + // get genome_length, just use first + let genome_length = linelist + .rows + .iter() + .map(|row| &row[genome_length_i]) + .next() + .unwrap() + .parse::()?; + + // check if we should include/exclude private mutations + if !all_coords { + barcodes.rows.retain(|row| row[origin_i] != ""private""); + } + + // get coords + let coords = barcodes.rows.iter().map(|row| &row[coord_i]).unique().collect_vec(); + + // get parents (origins column), exclude 'private' as name + let parents = barcodes + .rows + .iter() + .filter(|row| row[origin_i] != ""?"" && row[origin_i] != ""private"") + .map(|row| row[origin_i].to_string()) + .unique() + .collect_vec(); + + // If multiple parents weren't confidently identified + if parents.is_empty() { + return Err(eyre!( + ""No parents (origin) were confidently identified in barcodes file: {barcodes_path:?}"" + )); + } + + if parents.len() > constants::PALETTE_DARK.len() { + return Err(eyre!(""There are more parents than colors in the palette!"") + .suggestion(format!( + ""Are you sure you want to plot recombination involving {} parents?"", + parents.len() + )) + .suggestion( + ""If so, please contact the developer to expand the color palette options :)"", + )); + } + + // get sequence ids (columns after mandatory cols and parents) + let sequence_ids = + barcodes.headers.iter().skip(3 + parents.len()).cloned().collect_vec(); + + // search for sequence_ids in the linelist + let strain_i = linelist.header_position(""strain"")?; + + // filter linelist down to just these samples + linelist.rows = linelist + .rows + .into_iter() + .filter(|row| sequence_ids.contains(&row[strain_i])) + .collect_vec(); + + // make a list of all the populations/sequences we will plot + // Reference, Parents, Sequences + let mut populations = vec![""Reference"".to_string()]; + populations.extend(parents.clone()); + populations.extend(sequence_ids.clone()); + + // ------------------------------------------------------------------------ + // Section + // ------------------------------------------------------------------------ + + // the size of the plot is going to be determined by: + // - number of coords in barcodes (width) + // - longest sequence_id name (width on left-hand side) + // - longest coordinate (height) + // - consants::X_INC, which will be width/height white-space for borders + // - number of parents and sequences (height) + // - ...? amount of white-space on top and bottom + + let num_coords = barcodes.rows.len(); + + // longest sequence text id (in pixels) + let mut default_ids = + vec![""Reference"", ""Private""].into_iter().map(String::from).collect_vec(); + let mut sequence_ids_length_check = sequence_ids.clone(); + sequence_ids_length_check.append(&mut default_ids); + + let longest_sequence_id = sequence_ids_length_check + .iter() + .map(|id| { + text::to_image( + id, + constants::FONT_REGULAR, + constants::FONT_SIZE, + &constants::TEXT_COLOR, + ) + .unwrap() + .width() + }) + .max() + .ok_or_else(|| eyre!(""Failed to calculated the maximum sequence ID length""))?; + + // longest coord label (in pixels) + let longest_coord = coords + .iter() + .map(|coord| { + text::to_image( + coord, + constants::FONT_REGULAR, + constants::FONT_SIZE, + &constants::TEXT_COLOR, + ) + .unwrap() + .width() + }) + .max() + .ok_or_else(|| eyre!(""Failed to calculated the maximum coord length""))?; + + // longest legend label (in pixels) + let default_labels = + vec![""Reference"", ""Private Mutation""].into_iter().map(String::from).collect_vec(); + + let longest_legend_label = parents + .iter() + .chain(default_labels.clone().iter()) + .map(|id| { + let label = match default_labels.contains(id) { + true => id.to_string(), + false => format!(""{id} Reference""), + }; + text::to_image( + &label, + constants::FONT_REGULAR, + constants::FONT_SIZE, + &constants::TEXT_COLOR, + ) + .unwrap() + .width() + }) + .max() + .ok_or_else(|| eyre!(""Failed to calculated the maximum legend label length""))?; + + let section_gap = constants::X_INC; + let label_gap = constants::X_INC / 2.; + + // this is the x position each section will start at + let section_x = constants::X_INC // white-space left + + longest_sequence_id as f32 // labels on left-hand-side + + label_gap // gap between labels and sections + + constants::X_INC; // white-space buffer labels-sections + + let canvas_width = section_x // x coord of section start + + (num_coords as f32 * constants::X_INC) // coord boxes + + constants::X_INC; // white-space right + + let mut section_y = constants::X_INC; // white-space top + + // legend is reference (1) + num parents * 2 + private (1) + let legend_height = constants::BUFFER + + constants::X_INC * (1. + (parents.len() as f32 * 2.0)) + + constants::BUFFER * (1. + (parents.len() as f32 * 2.0)) + + constants::X_INC + + constants::BUFFER; + + let legend_width = constants::BUFFER + + constants::X_INC + + constants::BUFFER + + longest_legend_label as f32 + + constants::BUFFER; + + let canvas_height = constants::X_INC // white-space top + + (constants::X_INC * 2.) + section_gap // parent regions and text labels + + (constants::X_INC * 2.) + section_gap // annotations + + constants::X_INC + section_gap // guide section + + constants::X_INC // reference bases + + (constants::X_INC * parents.len() as f32) // parent bases + + section_gap // gap between parents and samples + + (constants::X_INC * sequence_ids.len() as f32) // sequence/sample bases + + longest_coord as f32 + section_gap // x-axis coord ticks + + legend_height // legend + + constants::X_INC; // white-space bottom + + debug!(""Creating canvas: {canvas_width} x {canvas_height}""); + + // add white space between sub boxes by making them smaller than X_INC + let sub_box_w = constants::X_INC * 0.8; + + // convert genomic coordinates to pixels, based on coords + let pixels_per_base = (num_coords as f32 * constants::X_INC) / genome_length as f32; + + // ------------------------------------------------------------------------ + // Canvas + // ------------------------------------------------------------------------ + + let mut canvas = DrawTarget::new(canvas_width as i32, canvas_height as i32); + + // ------------------------------------------------------------------------ + // Background + // ------------------------------------------------------------------------ + + // draw white background + let mut background = PathBuilder::new(); + background.rect(0., 0., canvas_width, canvas_height); + let background = background.finish(); + canvas.fill(&background, &constants::WHITE, &DrawOptions::new()); + + // ------------------------------------------------------------------------ + // Regions + // ------------------------------------------------------------------------ + + debug!(""Drawing parental regions.""); + + // draw section label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Regions"".to_string(); + args.font_style = text::FontStyle::Bold; + args.x = section_x - label_gap; + args.y = section_y + (constants::X_INC * 1.5); + args.horizontal_alignment = text::HorizontalAlignment::Right; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // draw grey box as background (with cross hatching eventually) + let box_x = section_x; + let box_y = section_y + constants::X_INC; + let box_w = num_coords as f32 * constants::X_INC; + let box_h = constants::X_INC; + + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + + let draw = polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::GREY, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + ); + + draw?; + + // iterate over parental regions in linelist + let regions_i = linelist.header_position(""regions"")?; + // they *should be all the same, just grab first + let regions = + &linelist.rows.iter().map(|row| row[regions_i].to_string()).next().unwrap(); + // 0-1000|parent1,1000-2000|parent2; + let regions_split = regions.split(',').collect_vec(); + + for (region_i, region) in regions_split.iter().enumerate() { + // 0-1000|parent1 + let region_parts = region.split('|').collect_vec(); + let parent = region_parts[1]; + let regions_coords = region_parts[0].split('-').collect_vec(); + + let mut region_start = regions_coords[0].parse::()?; + if region_i == 0 { + region_start = 0; + } + let mut region_end = regions_coords[1].parse::()?; + if region_i == regions_split.len() - 1 { + region_end = genome_length; + } + + // draw the region box, leave X_INC gap at top for parent text labels + // convert genomic coordinates to pixel coordinates + let box_x = section_x + (region_start as f32 * pixels_per_base); + let box_w = (region_end - region_start) as f32 * pixels_per_base; + + let box_y = section_y + constants::X_INC; + let box_h = constants::X_INC; + + // region text label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = parent.to_string(); + args.font_size = constants::FONT_SIZE - 5.0; + args.x = box_x + (box_w / 2.0); + args.y = section_y; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + let image = text::draw_raqote(&mut args)?; + + // region text line + let draw_x = vec![box_x + (box_w / 2.), box_x + (box_w / 2.)]; + let draw_y = vec![box_y, args.y + image.height() as f32]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // color + let parent_i = parents.iter().position(|p| *p == parent).unwrap(); + let [r, g, b, a] = constants::PALETTE_DARK[parent_i]; + let color = Source::Solid(SolidSource { r, g, b, a }); + + // draw region box + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &color, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + } + + section_y += constants::X_INC * 2.; + + // ------------------------------------------------------------------------ + // Guide + // ------------------------------------------------------------------------ + + debug!(""Drawing genomic guide.""); + + section_y += section_gap; + + // draw section label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Genome"".to_string(); + args.font_style = text::FontStyle::Bold; + args.x = section_x - label_gap; + args.y = section_y + (constants::X_INC * 1.5); + args.horizontal_alignment = text::HorizontalAlignment::Right; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // draw grey box + let box_x = section_x; + let box_y = section_y + constants::X_INC; + let box_w = num_coords as f32 * constants::X_INC; + let box_h = constants::X_INC; + + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::GREY, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + + // ------------------------------------------------------------------------ + // Annotations (Optional) + + debug!(""Drawing annotations.""); + + // special pallete for annotations, that interleaves dark and light + // skip colors reserverd for parents, x 2 for interleaved palette + // todo!() raise error if no colors left, parents consumed it all + let annot_palette = constants::PALETTE_DARK + .iter() + .zip(constants::PALETTE_LIGHT.iter()) + .skip(parents.len()) + .flat_map(|(dark, light)| vec![*dark, *light]) + .collect_vec(); + + for (i, row) in annotations.rows.iter().enumerate() { + let abbrev_i = annotations.header_position(""abbreviation"")?; + let start_i = annotations.header_position(""start"")?; + let end_i = annotations.header_position(""end"")?; + + let abbreviation = &annotations.rows[i][abbrev_i]; + let start = annotations.rows[i][start_i].parse::()?; + let end = annotations.rows[i][end_i].parse::()?; + + // use colors from the color palette that are not reserved for pops + let mut color_i = i; + if color_i >= annot_palette.len() { + color_i -= annot_palette.len(); + } + let [r, g, b, a] = annot_palette[color_i]; + let color = Source::Solid(SolidSource { r, g, b, a }); + // draw the region box, leave X_INC gap at top for annotation labels + // convert genomic coordinates to pixel coordinates + let box_x = section_x + (start as f32 * pixels_per_base); + let box_y = section_y + constants::X_INC; + let box_w = (end - start) as f32 * pixels_per_base; + let box_h = constants::X_INC; + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &color, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + + // text label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = abbreviation.to_string(); + args.font_style = text::FontStyle::Regular; + args.font_size = constants::FONT_SIZE - 5.0; + args.x = box_x + (box_w / 2.0); + args.y = if let 0 = i % 2 { + section_y + } else { + section_y - (constants::X_INC / 2.) + }; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + let image = text::draw_raqote(&mut args)?; + + // text line + let draw_x = vec![box_x + (box_w / 2.), box_x + (box_w / 2.)]; + let draw_y = vec![box_y, args.y + image.height() as f32]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + } + + // ------------------------------------------------------------------------ + // Sub markers + + debug!(""Drawing substitution markers.""); + + // draw coord black lines + for coord in coords.iter() { + // convert genomic coord to numeric then to pixels + let coord = coord.parse::().unwrap(); + + let line_x = section_x + (coord * pixels_per_base); + let line_y1 = section_y + constants::X_INC; + let line_y2 = section_y + constants::X_INC * 2.; + let draw_x = vec![line_x, line_x]; + let draw_y = vec![line_y1, line_y2]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + } + + section_y += constants::X_INC * 2.; + + // ------------------------------------------------------------------------ + // Guide to Sub Polyons + // ------------------------------------------------------------------------ + + debug!(""Drawing substitution guides.""); + + // draw coord black lines + for (i, coord) in coords.iter().enumerate() { + // convert genomic coord to numeric then to pixels + let coord = coord.parse::().unwrap(); + + // x coordinate for top of triangle, connects with guide + let guide_x = section_x + (coord * pixels_per_base); + let guide_y = section_y; + // x coordinates for bottom of triangle, connects with sub bases + // adjust based on sub_box_w + let sub_x_buff = (constants::X_INC - sub_box_w) / 2.; + let sub_x1 = section_x + (i as f32 * constants::X_INC) + sub_x_buff; + let sub_x2 = section_x + ((i + 1) as f32 * (constants::X_INC)) - sub_x_buff; + let sub_y1 = section_y + (constants::X_INC * 3.) + sub_x_buff; + let sub_y2 = sub_y1; + // Draw triangle from guide to top row of subs + let draw_x = vec![guide_x, sub_x1, sub_x2]; + let draw_y = vec![guide_y, sub_y1, sub_y2]; + + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::LIGHT_GREY, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + } + + // ------------------------------------------------------------------------ + // Axis coordinates (on top of sub triangle polygons) + + debug!(""Drawing guide coordinates.""); + + // how many x_inc are needed for it, add 1 extra x_inc for buffer + let longest_coord_x_inc = (longest_coord as f32 / constants::X_INC).ceil() + 1.0; + // maximum number of coord labels we can fit + let max_num_coords = num_coords as f32 / longest_coord_x_inc; + // calculate interval, round up to next pretty number (ex. 500) + let coord_interval = + (((genome_length as f32 / max_num_coords) / 500.).ceil() * 500.) as usize; + + let mut ax_coords = (0..genome_length).step_by(coord_interval).collect_vec(); + ax_coords.push(genome_length); + + for coord in ax_coords { + // convert genomic units to pixel coords + let coord_x = section_x + (coord as f32 * pixels_per_base); + + // draw x-tick line + let line_y1 = section_y; + let line_y2 = line_y1 + (constants::X_INC / 4.); + let draw_x = vec![coord_x, coord_x]; + let draw_y = vec![line_y1, line_y2]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // draw x-tick label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = coord.to_string(); + args.font_size = constants::FONT_SIZE - 5.0; + args.x = coord_x; + args.y = line_y2; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + text::draw_raqote(&mut args)?; + } + + // ------------------------------------------------------------------------ + // Breakpoints + // ------------------------------------------------------------------------ + + debug!(""Drawing breakpoints.""); + + // draw section label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Breakpoints"".to_string(); + args.font_style = text::FontStyle::Bold; + args.x = section_x - label_gap; + args.y = section_y + (constants::X_INC * 1.5); + args.horizontal_alignment = text::HorizontalAlignment::Right; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + let breakpoints = linelist + .rows + .iter() + .flat_map(|row| row[breakpoints_i].split(',')) + .unique() + .collect_vec(); + + let dash_stroke_style: StrokeStyle = StrokeStyle { + cap: LineCap::Square, + join: LineJoin::Miter, + width: constants::LINE_WIDTH, + miter_limit: 2., + dash_array: vec![8., 20.], + dash_offset: 0., + }; + + for (i, breakpoint) in breakpoints.iter().enumerate() { + // get the region start/end + let breakpoint_parts = breakpoint.split('-').collect_vec(); + // check if breakpoints is single coordinate + let mut prev_region_end = breakpoint_parts[0].parse::()?; + let mut next_region_start = breakpoint_parts[1].parse::()?; + + if prev_region_end == next_region_start { + prev_region_end -= 1.0; + } else { + prev_region_end -= 1.0; + next_region_start += 1.0; + } + //println!(""{prev_region_end} {next_region_start}""); + + // which subs does this fall between + let coord_prev_i = + coords.iter().position(|c| **c == prev_region_end.to_string()).unwrap(); + let coord_next_i = + coords.iter().position(|c| **c == next_region_start.to_string()).unwrap(); + //println!(""\t{coord_prev_i} {coord_next_i}""); + + // middle will depend on breakpoints uncertainy + let line_x; + // top of the line will be the same + let sub_y_buff = (constants::X_INC - sub_box_w) / 2.; + let line_y1 = if breakpoints.len() == 1 { + section_y + (constants::X_INC * 1.5) + } else if let 0 = i % 2 { + section_y + (constants::X_INC * 2.) + } else { + section_y + constants::X_INC + }; + + // the line bottom is all the way at the bottom of ref, parents, sample + let line_y2 = section_y + + (constants::X_INC * 3.) // height of the breakpoints section + + section_gap + + (constants::X_INC * populations.len() as f32) + - sub_y_buff; + + // option 1: draw line if coords right next to each other + if (coord_next_i - coord_prev_i) <= 1 { + // adjust the label line + line_x = section_x + + (coord_prev_i + 1 + (coord_next_i - coord_prev_i) / 2) as f32 + * constants::X_INC; + + let draw_x = vec![line_x, line_x]; + let draw_y = vec![line_y2, line_y1]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &dash_stroke_style, + )?; + } + // option 2: draw box around coords if multiple + else { + // draw dashed grey box + let box_x = section_x + ((coord_prev_i as f32 + 1.) * constants::X_INC); + let box_w = + (coord_next_i as f32 - coord_prev_i as f32 - 1.) * constants::X_INC; + let box_y = section_y + + (constants::X_INC * 3.) // this height of the breakpoints section + + sub_y_buff + - (constants::LINE_WIDTH / 2.); + let box_h = line_y2 - box_y + (constants::LINE_WIDTH / 2.); + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::DARK_GREY, + &constants::BLACK, + &dash_stroke_style, + )?; + + // draw label line, half-way in between box + line_x = box_x + (box_w / 2.); + + let draw_x = vec![line_x, line_x]; + let draw_y = vec![box_y, line_y1]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &dash_stroke_style, + )?; + } + + // breakpoint label, just to get dimensions for box + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = format!(""Breakpoint {}"", i + 1); + args.x = line_x; + args.y = line_y1; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + let image = text::draw_raqote(&mut args)?; + + // draw breakpoint box background, add several pixels for buffer + let box_x = line_x - (image.width() as f32 / 2.) - constants::BUFFER; + let box_y = line_y1 - constants::BUFFER; + let box_w = image.width() as f32 + (constants::BUFFER * 2.0); + let box_h = image.height() as f32 + (constants::BUFFER * 2.0); + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::WHITE, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // actually render the breakpoint label now, reborrowing the canvas + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = format!(""Breakpoint {}"", i + 1); + args.x = line_x; + args.y = line_y1; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + let image = text::draw_raqote(&mut args)?; + } + + section_y += constants::X_INC * 2.; + + // ------------------------------------------------------------------------ + // Sub Box + // ------------------------------------------------------------------------ + + debug!(""Drawing sub base boxes.""); + + section_y += section_gap; + + // iterate through sub coordinates + for (coord_i, coord) in coords.iter().enumerate() { + // absolute x coord + let x = section_x + (constants::X_INC * coord_i as f32); + // adjust box coord based on width/height of sub box + let box_x = x + (constants::X_INC / 2.) - (sub_box_w / 2.); + + // reference genome base + let ref_base = barcodes.rows[coord_i][reference_i].to_string(); + + // origins for samples + let origin = barcodes.rows[coord_i][origin_i].to_string(); + + // iterate through samples + for (pop_i, population) in populations.iter().enumerate() { + // absolute y coord + let mut y = section_y + (constants::X_INC * pop_i as f32); + + // shift samples down, to make gap between parents + // 1 for reference + variable number of parents + if pop_i > parents.len() { + y += section_gap; + } + + // On the first coord, write pop label. + // pop label has same pos as section_label, use that function + if coord_i == 0 { + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = population.replace(""population_"", """").to_string(); + args.x = section_x - label_gap; + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Right; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + } + + // adjust box coord based on width/height of sub box + let box_y = y + (constants::X_INC / 2.) - (sub_box_w / 2.); + + // draw sub box + let draw_x = vec![box_x, box_x, box_x + sub_box_w, box_x + sub_box_w]; + let draw_y = vec![box_y, box_y + sub_box_w, box_y + sub_box_w, box_y]; + + // box color, whether base is reference or not + let pop_header_i = barcodes.header_position(population)?; + let pop_base = barcodes.rows[coord_i][pop_header_i].to_string(); + let pop_color: Source; + // will give black outline if is private + let mut pop_outline = constants::TRANSPARENT; + + // is this the reference genome? + if &**population == ""Reference"" { + pop_color = constants::GREY; + } + // is this a parent? + else if parents.contains(population) { + let [r, g, b, a] = get_base_rgba(&pop_base, &ref_base, pop_i - 1); + pop_color = Source::Solid(SolidSource { r, g, b, a }); + } + // otherwise, it's a sequence + else { + // identify parental origin(s) + let mut origins = vec![]; + for (parent_i, parent) in parents.iter().enumerate() { + let parent_header_i = barcodes.header_position(parent)?; + let parent_base = barcodes.rows[coord_i][parent_header_i].to_string(); + if parent_base == pop_base { + origins.push(parent_i) + } + } + // color by origin if exact + if origins.len() == 1 { + let parent_i = origins[0]; + let [r, g, b, a] = get_base_rgba(&pop_base, &ref_base, parent_i); + pop_color = Source::Solid(SolidSource { r, g, b, a }); + } + // otherwise, just make it white to show ambiguous origins + else { + pop_color = constants::WHITE; + pop_outline = constants::BLACK; + } + } + + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &pop_color, + &pop_outline, + &constants::BASIC_STROKE_STYLE, + )?; + + // draw sub text + let pop_header_i = barcodes.header_position(population)?; + let pop_base = barcodes.rows[coord_i][pop_header_i].to_string(); + + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = pop_base; + args.x = box_x + (sub_box_w / 2.); + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + } + + // draw x axis tick + let line_x = x + (constants::X_INC / 2.); + let line_y1 = section_y + (constants::X_INC * (populations.len() as f32 + 1.)); + let line_y2 = line_y1 + (constants::X_INC / 4.); + let draw_x = vec![line_x, line_x]; + let draw_y = vec![line_y1, line_y2]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // draw x axis tick label, add several pixels for buffer. + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = coord.to_string(); + args.font_size = constants::FONT_SIZE - 5.0; + args.x = line_x; + args.y = line_y2 + constants::BUFFER; + args.rotate = 270; + args.horizontal_alignment = text::HorizontalAlignment::Center; + args.vertical_alignment = text::VerticalAlignment::Top; + text::draw_raqote(&mut args)?; + } + + section_y += (constants::X_INC * (populations.len() as f32)) + section_gap; + section_y += longest_coord as f32; + + // ------------------------------------------------------------------------ + // Legend + // ------------------------------------------------------------------------ + + section_y += section_gap; + + // draw section label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Legend"".to_string(); + args.font_style = text::FontStyle::Bold; + args.x = section_x - label_gap; + args.y = section_y + (legend_height / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Right; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // ------------------------------------------------------------------------ + // Legend Frame + + let box_x = section_x; + let box_y = section_y; + let box_w = legend_width; + let box_h = legend_height; + let draw_x = vec![box_x, box_x, box_x + box_w, box_x + box_w]; + let draw_y = vec![box_y, box_y + box_h, box_y + box_h, box_y]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::TRANSPARENT, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // ------------------------------------------------------------------------ + // Reference + + let x = section_x + constants::BUFFER; + let mut y = section_y + constants::BUFFER; + + // Box + let box_x = x + (constants::X_INC / 2.) - (sub_box_w / 2.); + let box_y = y + (constants::X_INC / 2.) - (sub_box_w / 2.); + let draw_x = vec![box_x, box_x, box_x + sub_box_w, box_x + sub_box_w]; + let draw_y = vec![box_y, box_y + sub_box_w, box_y + sub_box_w, box_y]; + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::GREY, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + + // Text + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Reference"".to_string(); + args.x = box_x + sub_box_w + constants::BUFFER; + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Left; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // ------------------------------------------------------------------------ + // Parents + + for (i, parent) in parents.iter().enumerate() { + // Mutation Box (dark palette) + y += constants::X_INC + constants::BUFFER; + let box_y = y + (constants::X_INC / 2.) - (sub_box_w / 2.); + let draw_x = vec![box_x, box_x, box_x + sub_box_w, box_x + sub_box_w]; + let draw_y = vec![box_y, box_y + sub_box_w, box_y + sub_box_w, box_y]; + let [r, g, b, a] = constants::PALETTE_DARK[i]; + let color = Source::Solid(SolidSource { r, g, b, a }); + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &color, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + + // Mutation Label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = format!(""{} Mutation"", parent).to_string(); + args.x = box_x + sub_box_w + constants::BUFFER; + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Left; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // Reference Box (light palette) + y += constants::X_INC + constants::BUFFER; + let box_y = y + (constants::X_INC / 2.) - (sub_box_w / 2.); + let draw_x = vec![box_x, box_x, box_x + sub_box_w, box_x + sub_box_w]; + let draw_y = vec![box_y, box_y + sub_box_w, box_y + sub_box_w, box_y]; + let [r, g, b, a] = constants::PALETTE_LIGHT[i]; + let color = Source::Solid(SolidSource { r, g, b, a }); + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &color, + &constants::TRANSPARENT, + &constants::BASIC_STROKE_STYLE, + )?; + + // Reference Label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = format!(""{} Reference"", parent).to_string(); + args.x = box_x + sub_box_w + constants::BUFFER; + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Left; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + } + + // ------------------------------------------------------------------------ + // Private + + // Box + y += constants::X_INC + constants::BUFFER; + let box_y = y + (constants::X_INC / 2.) - (sub_box_w / 2.); + let draw_x = vec![box_x, box_x, box_x + sub_box_w, box_x + sub_box_w]; + let draw_y = vec![box_y, box_y + sub_box_w, box_y + sub_box_w, box_y]; + + polygon::draw_raqote( + &mut canvas, + &draw_x, + &draw_y, + &constants::WHITE, + &constants::BLACK, + &constants::BASIC_STROKE_STYLE, + )?; + + // Label + let mut args = text::DrawRaqoteArgs::from_canvas(&mut canvas); + args.text = ""Private Mutation"".to_string(); + args.x = box_x + sub_box_w + constants::BUFFER; + args.y = y + (constants::X_INC / 2.0); + args.horizontal_alignment = text::HorizontalAlignment::Left; + args.vertical_alignment = text::VerticalAlignment::Center; + text::draw_raqote(&mut args)?; + + // ------------------------------------------------------------------------ + // Export + // ------------------------------------------------------------------------ + + canvas.write_png(output_path).unwrap(); + + Ok(()) +} + +/// Get the background color (RGBA) of a nucleotide base +pub fn get_base_rgba(base: &String, ref_base: &String, pal_i: usize) -> [u8; 4] { + // default WHITE + let mut rgba = [255, 255, 255, 255]; + + // convert to char for alphabet comparison + let base_char = base.chars().next().unwrap(); + + // same as reference, light palette + if base == ref_base { + rgba = constants::PALETTE_LIGHT[pal_i]; + } + // mutation, dark palette + else if constants::ALPHABET.contains(&base_char) { + rgba = constants::PALETTE_DARK[pal_i]; + } + + rgba +} +","Rust" +"Microbiology","phac-nml/rebar","src/plot/text.rs",".rs","7381","240","// This module was inspired by @J-Cake's custom implementation of text rendering +// Source: https://gist.github.com/J-Cake/ddccf99d3f7d6fc947fc60204aa41e09#file-text-rs + +use crate::plot::constants; +use color_eyre::eyre::{eyre, Report, Result, WrapErr}; +use image::{imageops, ImageBuffer, Rgba}; +use itertools::Itertools; +use std::path::Path; + +#[derive(Debug)] +pub enum HorizontalAlignment { + Left, + Center, + Right, +} + +#[derive(Debug)] +pub enum VerticalAlignment { + Top, + Center, + Bottom, +} + +pub enum FontStyle { + Regular, + Bold, +} + +/// Load font from file path +pub fn load_font(path: &Path) -> Result { + let font_bytes = std::fs::read(path) + .wrap_err_with(|| format!(""Could not load font from file path: {path:?}""))?; + let font = rusttype::Font::try_from_vec(font_bytes) + .ok_or_else(|| eyre!(""Could not convert file to Font: {path:?}""))?; + + Ok(font) +} + +/// Load font from bytes +pub fn load_font_from_bytes(bytes: &[u8]) -> Result { + let font = rusttype::Font::try_from_vec(bytes.to_vec()) + .ok_or_else(|| eyre!(""Could not convert bytes to font.""))?; + + Ok(font) +} + +/// Convert text string to an image::ImageBuffer +pub fn to_image( + text: &str, + font: &[u8], + font_size: f32, + color: &image::Rgba, +) -> Result, Vec>, Report> { + // get rgba channels of text color + let [r, g, b, a] = [color.0[0], color.0[1], color.0[2], color.0[3]]; + + // load font from file path + let font = load_font_from_bytes(font)?; + + // ------------------------------------------------------------------------ + // Image Dimensions + + // Set font size and get metrics + let scale = rusttype::Scale::uniform(font_size); + let metrics = font.v_metrics(scale); + + // layout the glyphs in the text horizontally + let glyphs: Vec<_> = + font.layout(text, scale, rusttype::point(0., 0. + metrics.ascent)).collect(); + + // get output image height from the font metrics, since height is only dependent on font + let height = (metrics.ascent - metrics.descent).ceil(); + + // Get output image widths from the pixel bounding boxes, since width is dependent + // on font + the text to write (for horizontal layout) + let min_x = glyphs + .iter() + .map(|g| { + if let Some(bounding_box) = g.pixel_bounding_box() { + bounding_box.min.x + } else { + 0 + } + }) + .min() + .unwrap(); + + let max_x = glyphs + .iter() + .map(|g| { + if let Some(bounding_box) = g.pixel_bounding_box() { + bounding_box.max.x + } else { + 0 + } + }) + .max() + .unwrap(); + + let width = if min_x >= 0 { max_x } else { max_x - min_x }; + + //debug!(""width: {width}, height: {height}""); + + // ------------------------------------------------------------------------ + // Rasterize Glyphs + + // construct an image buffer to hold text pixels + let mut image_buffer = + ImageBuffer::, Vec<_>>::new(width as u32, height as u32); + let default_pixel: Rgba = Rgba([0, 0, 0, 0]); + + // iterate through each glyph ('letter') + for glyph in glyphs { + //debug!(""glyph: {glyph:?}""); + + if let Some(bounding_box) = glyph.pixel_bounding_box() { + //debug!(""\tbounding_box: {bounding_box:?}""); + + // rasterize each glyph, by iterating through the pixels + // x, y are relative to bounding box, v is 'coverage' + glyph.draw(|x, y, v| { + //debug!(""\t\tx: {x}, y: {y}, v: {v}""); + let y = y as i32 + bounding_box.min.y; + + // sometimes x bounding box is negative, because kerning is applied + // ex. the letter 'T' in isolation + // in this case, force 0 to be the start point + let x = if bounding_box.min.x >= 0 { + x as i32 + bounding_box.min.x + } else { + x as i32 + }; + + //debug!(""\t\tx: {x}, y: {y}, v: {v}""); + + // construct a pixel + let pixel = Rgba([ + (r as f32 * v) as u8, + (g as f32 * v) as u8, + (b as f32 * v) as u8, + (a as f32 * v) as u8, + ]); + // add pixel to image buffer, if that pixel is still the default + if image_buffer.get_pixel(x as u32, y as u32) == &default_pixel { + image_buffer.put_pixel(x as u32, y as u32, pixel); + } + }); + } + } + + Ok(image_buffer) +} + +/// Convert image::ImageBuffer data text to u32 for raqote +pub fn to_raqote_data( + image: &ImageBuffer, Vec>, +) -> Result, Report> { + // convert from u8 to u32 + let data = image + .pixels() + .map(|rgba| u32::from_be_bytes([rgba.0[3], rgba.0[0], rgba.0[1], rgba.0[2]])) + .collect_vec(); + + Ok(data) +} + +//#[derive(Debug)] +pub struct DrawRaqoteArgs<'canvas> { + pub canvas: &'canvas mut raqote::DrawTarget, + pub text: String, + pub font_style: FontStyle, + pub font_size: f32, + pub color: image::Rgba, + pub x: f32, + pub y: f32, + pub vertical_alignment: VerticalAlignment, + pub horizontal_alignment: HorizontalAlignment, + pub rotate: u32, +} + +impl<'canvas> DrawRaqoteArgs<'canvas> { + pub fn from_canvas(canvas: &'canvas mut raqote::DrawTarget) -> Self { + DrawRaqoteArgs { + canvas, + text: String::new(), + font_style: FontStyle::Regular, + font_size: constants::FONT_SIZE, + color: image::Rgba([0, 0, 0, 255]), + x: 0.0, + y: 0.0, + vertical_alignment: VerticalAlignment::Top, + horizontal_alignment: HorizontalAlignment::Left, + rotate: 0, + } + } +} + +/// Draw text string onto raqote canvas. +pub fn draw_raqote( + args: &mut DrawRaqoteArgs, +) -> Result, Vec>, Report> { + let font = match args.font_style { + FontStyle::Regular => constants::FONT_REGULAR, + FontStyle::Bold => constants::FONT_BOLD, + }; + let image = to_image(&args.text, font, args.font_size, &args.color)?; + + // optional rotate + let image = match args.rotate { + 90 => imageops::rotate90(&image), + 180 => imageops::rotate180(&image), + 270 => imageops::rotate270(&image), + _ => image, + }; + + let data = to_raqote_data(&image)?; + + let x = match args.horizontal_alignment { + HorizontalAlignment::Left => args.x, + HorizontalAlignment::Center => args.x - (image.width() as f32 / 2.), + HorizontalAlignment::Right => args.x - image.width() as f32, + }; + + let y = match args.vertical_alignment { + VerticalAlignment::Top => args.y, + VerticalAlignment::Center => args.y - (image.height() as f32 / 2.), + VerticalAlignment::Bottom => args.y - image.height() as f32, + }; + + let point = raqote::Point::new(x, y); + let draw_image = raqote::Image { + width: image.width() as i32, + height: image.height() as i32, + data: &data, + }; + args.canvas.draw_image_at(point.x, point.y, &draw_image, &raqote::DrawOptions::new()); + + Ok(image) +} +","Rust" +"Microbiology","phac-nml/rebar","src/plot/polygon.rs",".rs","1010","36","use color_eyre::eyre::{Report, Result}; + +pub fn draw_raqote( + canvas: &mut raqote::DrawTarget, + x_coords: &[f32], + y_coords: &[f32], + fill: &raqote::Source, + stroke: &raqote::Source, + stroke_style: &raqote::StrokeStyle, +) -> Result<(), Report> { + // construct a list of path operations (drawing instructions) + let mut ops: Vec = Vec::new(); + let winding = raqote::Winding::EvenOdd; + + for (i, it) in x_coords.iter().zip(y_coords.iter()).enumerate() { + let (x, y) = it; + let point = raqote::Point::new(*x, *y); + let op = match i { + 0 => raqote::PathOp::MoveTo(point), + _ => raqote::PathOp::LineTo(point), + }; + ops.push(op); + } + + ops.push(raqote::PathOp::Close); + + let path = raqote::Path { ops, winding }; + + // fill polygon + canvas.fill(&path, fill, &raqote::DrawOptions::new()); + // outline polygon + canvas.stroke(&path, stroke, stroke_style, &raqote::DrawOptions::new()); + + Ok(()) +} +","Rust" +"Microbiology","phac-nml/rebar","src/phylogeny/mod.rs",".rs","16031","470","use crate::utils; +use color_eyre::eyre::{eyre, ContextCompat, Report, Result, WrapErr}; +use color_eyre::Help; +use itertools::Itertools; +use log::debug; +use petgraph::dot::{Config, Dot}; +use petgraph::graph::{Graph, NodeIndex}; +use petgraph::visit::{Dfs, IntoNodeReferences}; +use petgraph::Direction; +use serde::{Deserialize, Serialize}; +use serde_json; +use std::fs::File; +use std::io::Write; +use std::path::Path; +use std::string::ToString; + +// ---------------------------------------------------------------------------- +// Phylogeny + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Phylogeny { + pub graph: Graph, + // we will parse recombinants on load/read + #[serde(skip_serializing, skip_deserializing)] + pub recombinants: Vec, + #[serde(skip_serializing, skip_deserializing)] + pub recombinants_all: Vec, +} + +impl Default for Phylogeny { + fn default() -> Self { + Self::new() + } +} + +impl Phylogeny { + pub fn new() -> Self { + Phylogeny { + graph: Graph::new(), + recombinants: Vec::new(), + recombinants_all: Vec::new(), + } + } + + pub fn is_empty(&self) -> bool { + self.graph.node_count() == 0 + } + + /// Return true if a node name is a recombinant. + pub fn is_recombinant(&self, name: &str) -> Result { + let node = self.get_node(name)?; + let mut edges = self.graph.neighbors_directed(node, Direction::Incoming).detach(); + + // Recombinants have more than 1 incoming edge + let mut num_edges = 0; + while let Some(_edge) = edges.next_edge(&self.graph) { + num_edges += 1; + } + + if num_edges > 1 { + Ok(true) + } else { + Ok(false) + } + } + + /// Get populations names (all named nodes) + pub fn get_names(&self) -> Result, Report> { + let mut names: Vec = Vec::new(); + + for (_i, n) in self.graph.node_references() { + if !names.contains(n) && !n.is_empty() { + names.push(n.clone()) + } + } + + Ok(names) + } + + /// Get recombinant node names. + pub fn get_recombinants(&self) -> Result, Report> { + let mut recombinants: Vec = Vec::new(); + + for node in self.graph.node_indices() { + let name = self.get_name(&node)?; + let is_recombinant = self.is_recombinant(&name)?; + if is_recombinant { + recombinants.push(name); + } + } + + Ok(recombinants) + } + + /// Get recombinant node names and all descendants. + pub fn get_recombinants_all(&self) -> Result, Report> { + let mut recombinants: Vec = Vec::new(); + + for node in self.graph.node_indices() { + let name = self.get_name(&node)?; + let result = self.get_recombinant_ancestor(&name)?; + if result.is_some() { + recombinants.push(name) + } + } + + Ok(recombinants) + } + + /// Get non-recombinants + pub fn get_non_recombinants_all(&self) -> Result, Report> { + let mut non_recombinants: Vec = Vec::new(); + + for node in self.graph.node_indices() { + let name = self.get_name(&node)?; + let result = self.get_recombinant_ancestor(&name)?; + if result.is_none() { + non_recombinants.push(name) + } + } + + Ok(non_recombinants) + } + + /// Remove a single named node in the graph. + /// + /// Connect parents to children to fill the hole. + pub fn remove(&mut self, name: &str) -> Result<(), Report> { + // Delete the node + debug!(""Removing node: {name}""); + + let node = self.get_node(name)?; + + // get some attributes before we remove it + let parents = self.get_parents(name)?; + let mut children = self.get_children(name)?; + let is_recombinant = self.is_recombinant(name)?; + + // Delete the node + self.graph.remove_node(node).unwrap_or_default(); + + // If it was an interior node, connect parents and child + children.iter().for_each(|c| { + let c_node = self.get_node(c).expect(""Child {c} is not in graph.""); + //debug!(""Connecting child {c} to new parent(s): {parents:?}""); + parents.iter().for_each(|p| { + let p_node = self.get_node(p).expect(""Parent {p} is not in graph.""); + self.graph.add_edge(p_node, c_node, 1); + }) + }); + + // If it was a primary recombinant node, make all children primary recombinants + if is_recombinant { + self.recombinants.append(&mut children); + } + + // Update the recombinants attributes + self.recombinants.retain(|n| n != name); + self.recombinants_all.retain(|n| n != name); + Ok(()) + } + + /// Prune a clade from the graph. + /// + /// Removes named node and all descendants. + pub fn prune(&mut self, name: &str) -> Result<(), Report> { + let descendants = self.get_descendants(name)?; + for d in descendants { + self.remove(&d)?; + } + + Ok(()) + } + + /// Read phylogeny from file. + pub fn read(path: &Path) -> Result { + let phylogeny = std::fs::read_to_string(path) + .wrap_err_with(|| format!(""Failed to read file: {path:?}.""))?; + let mut phylogeny: Phylogeny = serde_json::from_str(&phylogeny) + .wrap_err_with(|| format!(""Failed to parse file: {path:?}.""))?; + + phylogeny.recombinants = phylogeny.get_recombinants()?; + phylogeny.recombinants_all = phylogeny.get_recombinants_all()?; + + Ok(phylogeny) + } + + /// Write phylogeny to file. + pub fn write(&self, output_path: &Path) -> Result<(), Report> { + // Create output file + let mut file = File::create(output_path)?; + + // .unwrap_or_else(|_| { + // return Err(eyre!(""Failed to create file: {:?}."", &output_path)) + // }); + let ext = utils::path_to_ext(Path::new(output_path))?; + + // format conversion + let output = match ext.as_str() { + // ---------------------------------------------------------------- + // DOT file for graphviz + ""dot"" => { + let mut output = + format!(""{}"", Dot::with_config(&self.graph, &[Config::EdgeNoLabel])); + // set graph id (for cytoscape) + output = str::replace(&output, ""digraph"", ""digraph G""); + // set horizontal (Left to Right) format for tree-like visualizer + output = + str::replace(&output, ""digraph {"", ""digraph {\n rankdir=\""LR\"";""); + output + } + // ---------------------------------------------------------------- + // JSON for rebar + ""json"" => serde_json::to_string_pretty(&self) + .unwrap_or_else(|_| panic!(""Failed to parse: {self:?}"")), + _ => { + return Err(eyre!( + ""Phylogeny write for extension .{ext} is not supported."" + ) + .suggestion(""Please try .json or .dot instead."")) + } + }; + + // Write to file + file.write_all(output.as_bytes()) + .unwrap_or_else(|_| panic!(""Failed to write file: {:?}."", &output_path)); + + Ok(()) + } + + // Reminder, this function will also include name (the parent) + pub fn get_descendants(&self, name: &str) -> Result, Report> { + let mut descendants = Vec::new(); + + // Find the node that matches the name + let node = self.get_node(name)?; + // Construct a depth-first-search (Dfs) + let mut dfs = Dfs::new(&self.graph, node); + + // Skip over self? + // dfs.next(&self.graph); + // Iterate over descendants + while let Some(nx) = dfs.next(&self.graph) { + // Get node name + let nx_name = self.get_name(&nx)?; + descendants.push(nx_name); + } + + Ok(descendants) + } + + /// Get parent names of node + pub fn get_parents(&self, name: &str) -> Result, Report> { + let mut parents = Vec::new(); + + let node = self.get_node(name)?; + let mut neighbors = + self.graph.neighbors_directed(node, Direction::Incoming).detach(); + while let Some(parent_node) = neighbors.next_node(&self.graph) { + let parent_name = self.get_name(&parent_node)?; + parents.push(parent_name); + } + + Ok(parents) + } + + /// Get children names of node + pub fn get_children(&self, name: &str) -> Result, Report> { + let mut children = Vec::new(); + + let node = self.get_node(name)?; + let mut neighbors = + self.graph.neighbors_directed(node, Direction::Outgoing).detach(); + while let Some(child_node) = neighbors.next_node(&self.graph) { + let child_name = self.get_name(&child_node)?; + children.push(child_name); + } + + // children order is last added to first added, reverse this + children.reverse(); + + Ok(children) + } + + /// Get problematic recombinants, where the parents are not sister taxa. + /// They might be parent-child instead. + pub fn get_problematic_recombinants(&self) -> Result, Report> { + let mut problematic_recombinants = Vec::new(); + + for recombinant in &self.recombinants { + let parents = self.get_parents(recombinant)?; + for i1 in 0..parents.len() - 1 { + let p1 = &parents[i1]; + for p2 in parents.iter().skip(i1 + 1) { + let mut descendants = self.get_descendants(p2)?; + let ancestors = + self.get_ancestors(p2)?.into_iter().flatten().collect_vec(); + descendants.extend(ancestors); + + if descendants.contains(p1) { + problematic_recombinants.push(recombinant.clone()); + break; + } + } + } + } + + Ok(problematic_recombinants) + } + + /// Get all paths from the origin node to the destination node, always traveling + /// in the specified direction (Incoming towards root, Outgoing towards tips)/ + /// petgraph must have this already implemented, but I can't find it in docs + pub fn get_paths( + &self, + origin: &str, + dest: &str, + direction: petgraph::Direction, + ) -> Result>, Report> { + // container to hold the paths we've found, is a vector of vectors + // because there might be recombinants with multiple paths + let mut paths: Vec> = Vec::new(); + + // check that the origin and dest actually exist in the graph + let origin_node = self.get_node(origin)?; + let _dest_node = self.get_node(dest)?; + + // Check if we've reached the destination + if origin == dest { + paths.push(vec![origin.to_string()]); + } + // Otherwise, continue the search! + else { + let mut neighbors = + self.graph.neighbors_directed(origin_node, direction).detach(); + while let Some(parent_node) = neighbors.next_node(&self.graph) { + // convert the parent graph index to a string name + let parent_name = self.get_name(&parent_node)?; + + // recursively get path of each parent to the destination + let mut parent_paths = self.get_paths(&parent_name, dest, direction)?; + + // prepend the origin to the paths + parent_paths.iter_mut().for_each(|p| p.insert(0, origin.to_string())); + + // update the paths container to return at end of function + for p in parent_paths { + paths.push(p); + } + } + } + + Ok(paths) + } + + /// NOTE: Don't think this will work with 3+ parents yet, to be tested. + pub fn get_ancestors(&self, name: &str) -> Result>, Report> { + let mut paths = self.get_paths(name, ""root"", petgraph::Incoming)?; + + // remove self name (first element) from paths, and then reverse order + // so that it's ['root'.... name] + paths.iter_mut().for_each(|p| { + p.remove(0); + p.reverse(); + }); + + Ok(paths) + } + + /// Identify the most recent common ancestor shared between all node names. + pub fn get_common_ancestor(&self, names: &[String]) -> Result { + // if only one node name was provided, just return it + if names.len() == 1 { + let common_ancestor = names[0].clone(); + return Ok(common_ancestor); + } + + // mass pile of all ancestors of all named nodes + let ancestors: Vec<_> = names + .iter() + .map(|pop| { + let paths = self.get_paths(pop, ""root"", Direction::Incoming)?; + let ancestors = paths.into_iter().flatten().unique().collect_vec(); + debug!(""{pop}: {ancestors:?}""); + Ok(ancestors) + }) + .collect::, Report>>()? + .into_iter() + .flatten() + .collect::>(); + + // get ancestors shared by all sequences + let common_ancestors: Vec<_> = ancestors + .iter() + .unique() + .filter(|anc| { + let count = ancestors.iter().filter(|pop| pop == anc).count(); + count == names.len() + }) + .collect(); + + debug!(""common_ancestors: {common_ancestors:?}""); + + // get the depths (distance to root) of the common ancestors + let depths = common_ancestors + .into_iter() + .map(|pop| { + let paths = self.get_paths(pop, ""root"", Direction::Incoming)?; + let longest_path = paths + .into_iter() + .max_by(|a, b| a.len().cmp(&b.len())) + .unwrap_or_default(); + let depth = longest_path.len(); + debug!(""{pop}: {depth}""); + Ok((pop, depth)) + }) + .collect::, Report>>()?; + + // get the deepest (ie. most recent common ancestor) + let deepest_ancestor = depths + .into_iter() + .max_by(|a, b| a.1.cmp(&b.1)) + .context(""Failed to get common ancestor."")?; + + // tuple (population name, depth) + let common_ancestor = deepest_ancestor.0.to_string(); + + Ok(common_ancestor) + } + + /// Identify the most recent ancestor that is a recombinant. + pub fn get_recombinant_ancestor(&self, name: &str) -> Result, Report> { + let mut recombinant: Option = None; + + let ancestor_paths = self.get_paths(name, ""root"", petgraph::Incoming)?; + + for path in ancestor_paths { + for name in path { + if self.recombinants.contains(&name) { + recombinant = Some(name.to_string()); + break; + } + } + if recombinant.is_some() { + break; + } + } + + Ok(recombinant) + } + + pub fn get_node(&self, name: &str) -> Result { + for (idx, n) in self.graph.node_references() { + if n == name { + return Ok(idx); + } + } + Err(eyre!(""Name {name} is not in the phylogeny."")) + } + + pub fn get_name(&self, node: &NodeIndex) -> Result { + for (idx, n) in self.graph.node_references() { + if &idx == node { + return Ok(n.clone()); + } + } + Err(eyre!(""Node {node:?} is not in the phylogeny."")) + } +} +","Rust" +"Microbiology","phac-nml/rebar","src/export/mod.rs",".rs","4388","128","use crate::dataset::{Dataset, SearchResult}; +use crate::recombination::{validate, Recombination}; +use crate::utils; +use color_eyre::eyre::{Report, Result}; +use itertools::Itertools; + +// ---------------------------------------------------------------------------- +// LineList + +pub fn linelist( + results: &Vec<(SearchResult, Recombination)>, + dataset: &Dataset, +) -> Result { + let mut table = utils::table::Table::new(); + + table.headers = vec![ + ""strain"", + ""validate"", + ""validate_details"", + ""population"", + ""recombinant"", + ""parents"", + ""breakpoints"", + ""edge_case"", + ""unique_key"", + ""regions"", + ""substitutions"", + ""genome_length"", + ""dataset_name"", + ""dataset_tag"", + ""cli_version"", + ] + .into_iter() + .map(|s| s.to_string()) + .collect_vec(); + + // iterate in parallel, checking for same sequence id + for (best_match, recombination) in results { + // initialize the table row + let mut row = vec![String::new(); table.headers.len()]; + + // strain + let strain = recombination.sequence.id.to_string(); + row[table.header_position(""strain"")?] = strain.clone(); + + // population + let population = best_match.consensus_population.to_string(); + row[table.header_position(""population"")?] = population.clone(); + + // recombinant + if let Some(recombinant) = &recombination.recombinant { + row[table.header_position(""recombinant"")?] = recombinant.clone(); + } + + // parents + let parents = recombination.parents.join("","").to_string(); + row[table.header_position(""parents"")?] = parents; + + // breakpoints + let breakpoints = recombination.breakpoints.iter().join("","").to_string(); + row[table.header_position(""breakpoints"")?] = breakpoints; + + // edge_case + let edge_case = recombination.edge_case.to_string(); + row[table.header_position(""edge_case"")?] = edge_case; + + // validate, currently requires phylogeny + if !dataset.phylogeny.is_empty() { + let validate = validate::validate(dataset, best_match, recombination)?; + if let Some(validate) = validate { + row[table.header_position(""validate"")?] = validate.status.to_string(); + row[table.header_position(""validate_details"")?] = + validate.details.iter().join("";""); + } + } + + // unique_key + let unique_key = recombination.unique_key.to_string(); + row[table.header_position(""unique_key"")?] = unique_key; + + // regions + let regions = recombination.regions.values().join("","").to_string(); + row[table.header_position(""regions"")?] = regions; + + // genome_length + let genome_length = recombination.genome_length.to_string(); + row[table.header_position(""genome_length"")?] = genome_length; + + // dataset name + row[table.header_position(""dataset_name"")?] = dataset.name.to_string(); + + // dataset tag + row[table.header_position(""dataset_tag"")?] = dataset.tag.to_string(); + + // cli version + row[table.header_position(""cli_version"")?] = + env!(""CARGO_PKG_VERSION"").to_string(); + + // -------------------------------------------------------------------- + // Substitutions, annotated by parental origin or private + + let subs_by_origin = recombination.get_substitution_origins(best_match)?; + let mut origins = Vec::new(); + // origin order: primary parent, secondary parent, recombinant, private + if recombination.recombinant.is_some() { + origins.extend(recombination.parents.clone()); + } else { + origins.push(best_match.consensus_population.clone()); + } + origins.push(""private"".to_string()); + + // string format + let substitutions = origins + .iter() + .filter_map(|o| { + let subs = subs_by_origin.get(o).cloned().unwrap_or_default(); + let subs_format = format!(""{}|{o}"", subs.iter().join("","")); + (!subs.is_empty()).then_some(subs_format) + }) + .join("";""); + row[table.header_position(""substitutions"")?] = substitutions; + + table.rows.push(row); + } + + Ok(table) +} +","Rust" +"Microbiology","phac-nml/rebar","docs/compile.md",".md","1466","23","## Compile + +For a consistent compilation experience, we recommend using the pre-configured [GitHub Actions](https://github.com/features/actions). The [rebar](https://github.com/phac-nml/rebar) repository will automatically compile on every `git push` using a container in GitHub's cloud architecture. + +1. Create your own fork of [phac-nml/rebar](https://github.com/phac-nml/rebar). +1. Push changes to your fork. +1. Navigate to your GitHub Actions Build page. + + In the following url, replace `` with your GitHub username. + `https://github.com//rebar/actions/workflows/build.yaml` + +1. Click on the most recent build workflow at the top. + + ![Screenshot of the GitHub actions build page, which shows a list of automated analyses.](../assets/images/github_actions_build.png) + +1. Click on the `Summary` tab. If the build succeeded, the compiled binaries and docker images (zipped) will be available for download at the bottom (for 7 days). + + ![Screenshot of a successful automated build, with a summary tab and download links for compiled binaries.](../assets/images/github_actions_build_artifacts.png) + +1. If compilation failed, click on the steps with a ❌ to see the logs for troubleshooting. + + ![Screenshot of failed automated build, showing the failed jobs on the left hand side with red exes next to their name. On the right hand side, is the debugging log for the failed jobs.](../assets/images/github_actions_build_failure.png) +","Markdown" +"Microbiology","phac-nml/rebar","docs/install.md",".md","2765","111","# Install + +## Direct + +### Linux + +```bash +wget -O rebar https://github.com/phac-nml/rebar/releases/latest/download/rebar-x86_64-unknown-linux-musl +./rebar --help +``` + +### macOS + +```bash +wget -O rebar https://github.com/phac-nml/rebar/releases/latest/download/rebar-x86_64-apple-darwin +./rebar --help +``` + +#### Windows + +```powershell +wget ""https://github.com/phac-nml/rebar/releases/latest/download/rebar-x86_64-pc-windows-gnu.exe"" -OutFile rebar.exe +.\rebar.exe --help +``` + +## Conda + +```bash +conda create -c bioconda -n rebar rebar +conda activate rebar +rebar --help +``` + +## Docker + +### GitHub Release + +1. Download and load the Docker image from the releases page. + + ```bash + wget -O rebar-docker.tar https://github.com/phac-nml/rebar/releases/latest/download/rebar-docker.tar + docker load --input rebar-docker.tar + ``` + +1. Run the image. + + ```bash + docker run -v .:/rebar ghcr.io/phac-nml/rebar:latest \ + rebar --help + ``` + + > *TIP*: Use `-v .:/rebar` to connect your local directory (`.`) to the docker image. That way when you run `rebar dataset download`, it will download permanently onto your system, not temporarily inside the image. + +### GitHub Container Registry + +At the moment (2023-12-04), the Github Container Registry is locked to 'private'. Only `phac-nml` members can access. We are working on this! + +1. Authenticate with the GitHub Container Registry. + + ```bash + export GITHUB_USERNAME='' + export GITHUB_TOKEN='' + echo $GITHUB_TOKEN | docker login ghcr.io -u $GITHUB_USERNAME --password-stdin + ``` + +1. Run the image. + + ```bash + docker run -v .:/rebar ghcr.io/phac-nml/rebar:latest \ + rebar --help + ``` + +## Singularity + +### GitHub Release + +1. Download and build a singularity image from the docker image. + + ```bash + wget -O rebar-docker.tar https://github.com/phac-nml/rebar/releases/latest/download/rebar-docker.tar + singularity build rebar_latest.sif docker-archive://rebar-docker.tar + ``` + +1. Run the image + + ```bash + singularity run --home $(pwd) rebar_latest.sif \ + rebar --help + ``` + + > **Tip**: Use `--home $(pwd)` to have `rebar` run in your current working directory. + +### Container Registry + +At the moment (2023-12-04), the Github Container Registry is locked to 'private'. Only `phac-nml` members can access. We are working on this! + +1. Download the image from the GitHub Container Registry. + + ```bash + export SINGULARITY_DOCKER_USERNAME='' + export SINGULARITY_DOCKER_PASSWORD='' + singularity pull docker://ghcr.io/phac-nml/rebar:latest + ``` + +1. Run the image + + ```bash + singularity run --home $(pwd) rebar_latest.sif \ + rebar --help + ``` +","Markdown" +"Microbiology","phac-nml/rebar","docs/run.md",".md","819","13","# Run + +`rebar` begins by comparing a query sequence to the dataset populations in order to find its best match. The best match is simplify defined as the population with the greatest number of shared mutations, and the least number of conflicting bases. Sites with missing data (""N"") and deletions (""-"") are ignored in this calculation. The best match represents the primary parent of the query sequence. + +If a sequence's best match had mutational conflicts, `rebar` will search for secondary parents (recombination) by testing four different recombination hypotheses: + +1. Non-Recombinant +1. Designated Recombinant (using known parents from the dataset) +1. Recursive Recombinant (allowing parents to be recombinants themselves) +1. Non-Recursive Recombinant (not allowing parents to be recombinants) + +(To be continued!) +","Markdown" +"Microbiology","phac-nml/rebar","docs/dataset.md",".md","3307","111","# Dataset + +A minimal example dataset is provided called `toy1`, which can be downloaded with: + +```bash +rebar dataset download --name toy1 --tag custom --output-dir dataset/toy1 +``` + +## Mandatory + +A `rebar` dataset consists of two mandatory parts: + +1. `reference.fasta`: The reference genome. + + ```text + >Reference + AAAAAAAAAAAAAAAAAAAA + ``` + +1. `populations.fasta`: Known populations (ex. clades, lineages) aligned to the reference. + + ```text + >A + CCCCCCAACCCCCCCCCCCC + >B + TTTTTTTTTTTTTTTTTTAA + >C + AAGGGGGGGGGGGGGGGGGG + >D + CCCCCCAACCCTTTTTTTAA + >E + AAGCCCAACCCTTTTTTTAA + ``` + +## Optional + +The following are optional components: + +1. `annotations.tsv`: A table of genome annotations to add to the plot. + + |gene |abbreviation|start|end| + |:----:|:-----------:|:----:|:--:| + |Gene1|g1 |1 |3 | + |Gene2|g2 |12 |20 | + +1. `phylogeny.json`: A phylogenetic graph which provides prior information about the evolutionary history. This is particularly useful if populations in `populations.fasta` are internal nodes or known recombinants. + + For example, an evolutionary history, in which population `D` is a recombinant, and `E` is a recursive recombinant (it has a parent that is also a recombinant). + + ```mermaid + graph LR; + root-->A; + root-->B; + root-->C; + A-->D; + B-->D; + C-->E; + D-->E; + + style D fill:#00758f + style E fill:#00758f + ``` + + Is represented by the following phylogenetic graph: + + ```json + { + ""graph"": { + ""nodes"": [""root"", ""A"", ""B"", ""C"", ""D"", ""E"" ], + ""edge_property"": ""directed"", + ""edges"": [ + [ 0, 1, 1 ], + [ 0, 2, 1 ], + [ 0, 3, 1 ], + [ 1, 4, 1 ], + [ 2, 4, 1 ], + [ 4, 5, 1 ], + [ 3, 5, 1 ] + ] + } + } + ``` + + Where `nodes` are the list of node names in the tree (internal and external), and `edges` are the branches between nodes. For example, the edge `[0, 1, 1]` connects node index 0 (""root"") to node index 1 (""A"") with a branch length of 1. Please note that branch lengths are not currently used in `rebar's` algorithm. + +1. `edge_cases.json`: A list of `rebar` arguments to apply only to a particular population. + + In the dataset, `E` is a recursive recombinant between population `C` and recombinant `D`. However, we could instead force it to be a recombinant between `A`, `B`, and `C` with the following parameters: + + ```json + [ + { + ""population"": ""E"", + ""parents"": [ ""A"", ""B"", ""C""], + ""knockout"": null, + ""mask"": [0, 0], + ""max_iter"": 3, + ""max_parents"": 3, + ""min_parents"": 3, + ""min_consecutive"": 3, + ""min_length"": 3, + ""min_subs"": 1, + ""naive"": false + } + ] + ``` + + | Default | Edge Case | + | ---------------------------------------------------------------------------------------------------------------------------------- | --------- | + | ![Default rebar plot of toy1 population E, showing recombination between populations C and D](../assets/images/toy1_E_default.png) | ![Edge cases rebar plot of toy1 population E, showing recombination between populations A, B, and C](../assets/images/toy1_E_edge-cases.png) | +","Markdown" +"Microbiology","phac-nml/rebar","docs/examples.md",".md","6395","128","# Examples + +Download a SARS-CoV-2 dataset, version controlled to the date 2023-11-30. + +```bash +rebar dataset download \ + --name sars-cov-2 \ + --tag 2023-11-30 \ + --output-dir dataset/sars-cov-2/2023-11-30 +``` + +## Populations + +Use the names of dataset populations (ex. SARS-CoV-2 lineages) as input. + +```bash +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --populations ""AY.4.2*,BA.5.2,XBC.1.6*,XBB.1.5.1,XBL"" \ + --output-dir output/example/population + +rebar plot \ + --run-dir output/example/population \ + --annotations dataset/sars-cov-2/2023-11-30/annotations.tsv +``` + +The populations (`--populations`) can include any sequence name found in the dataset's `populations.fasta`. For `sars-cov-2`, sequence names are the designated lineages. + +The wildcard character (""\*"") will include the population and all its descendants. The pattern (""X*"") will include only recombinants and their descendants. **NOTE**: If using ""\*"", make sure to use quotes (ex. `--lineages ""XBC*,XBB.1.16*""`)! + +## Alignment + +Use an alignment of genomes as input. + +```bash +wget https://raw.githubusercontent.com/phac-nml/rebar/main/data/example2.fasta + +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --alignment example2.fasta \ + --output-dir output/example/alignment + +rebar plot \ + --run-dir output/example/alignment \ + --annotations dataset/sars-cov-2/2023-11-30/annotations.tsv +``` + +Please note that the `--alignment` should be aligned to the same reference as in the dataset `reference.fasta`! We strongly recommend [nextclade](https://clades.nextstrain.org/). + +## Debug + +To understand the inner-workings of the `rebar` algorithm, you can enable the debugging log with `--verbosity debug`. This is an INCREDIBLY verbose log on the dataset searches and hypothesis testing. We recommend only using this for a small number of input `parents`/`populations`. + +```bash +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --populations ""XD"" \ + --output-dir output/example/parents \ + --verbosity debug +``` + +## Parents + +By default, `rebar` will consider all populations in the dataset as possible parents. If you would like to see the evidence for specific parents, you can restrict the parent search with `--parents`. For example, the recombinant `XD` is designated as having parents BA.1 (Omicron) and B.1.617.2 (generic Delta). But you might be interested in forcing it to evaluate a more specific Delta parent (ex. AY.4). + +```bash +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --populations ""XD"" \ + --parents ""AY.4*,BA.1"" \ + --output-dir output/example/parents \ + --verbosity debug + +rebar plot \ + --run-dir output/example/parents \ + --annotations dataset/sars-cov-2/2023-11-30/annotations.tsv +``` + +## Knockout + +Conversely to selecting specific parents, you can perform a 'knockout' experiment to remove populations from the dataset. For example, we might be interested in what the SARS-CoV-2 recombinant `XBB` would have been classified as _before_ it became a designated lineage. + +```bash +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --populations ""XBB"" \ + --knockout ""XBB*"" \ + --output-dir output/example/knockout + +rebar plot \ + --run-dir output/example/knockout \ + --annotations dataset/sars-cov-2/2023-11-30/annotations.tsv +``` + +The linelist (`output/example/knockout/linelist.tsv`) reveals that: + +- `XBB` is descendant of `BJ.1` (`BA.2.10.1.1`), specifically a novel recombinant between `BJ.1` and `BA.2.75`. +- The `substitutions` column reveals: + + - 5 substitutions came from the `BA.2.75` parent: `T22942G`, `T23019C`, `T23031C`, `C25416T`, `A26275G`. + - 1 substitution came from neither parent (private): `A19326G` + +- This can be used to contribute evidence for a new lineage proposal in the [pango-designation](https://github.com/cov-lineages/pango-designation/issues) respository. + +|strain |validate|validate_details|population|recombinant|parents |breakpoints|edge_case|unique_key |regions |substitutions |genome_length|dataset_name|dataset_tag|cli_version| +|:-------------|:-------|:---------------|:---------|:----------|:-----------|:----------|:--------|:-----------------------------|:-----------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------|:-----------|:----------|:----------| +|population_XBB| | |BJ.1 |novel |BJ.1,BA.2.75|22897-22941|false |novel_BJ.1_BA.2.75_22897-22941|405-22896\|BJ.1,22942-29118\|BA.2.75|A405G,T670G,C2790T,C3037T,G4184A,C4321T,C9344T,A9424G,C9534T,C9866T,C10029T,C10198T,G10447A,C10449A,C12880T,C14408T,G15451A,C15714T,C15738T,T15939C,T16342C,C17410T,T17859C,A18163G,C19955T,A20055G,C21618T,T21810C,G21987A,C22000A,C22109G,T22200A,G22577C,G22578A,G22599C,C22664A,C22674T,T22679C,C22686T,A22688G,G22775A,A22786C,G22813T,T22882G,G22895C,T22896C\|BJ.1;T22942G,T23019C,T23031C,C25416T,A26275G\|BA.2.75;A19326G\|private|29903 |sars-cov-2 |2023-11-30 |0.2.0 | + +A visual representation (`output/example/knockout/plots/`) of the genomic composition is: + +![rebar plot of XBB showing parents BJ.1 and BA.2.75 mutations.](../assets/images/XBB_knockout_XBB.png) + +## Validate + +Run `rebar` on all populations in the dataset, and validate against the expected results. + +```bash +rebar run \ + --dataset-dir dataset/sars-cov-2/2023-11-30 \ + --output-dir output/example/validate \ + --populations ""*"" \ + --threads 4 + +rebar plot \ + --run-dir output/example/validate \ + --annotations dataset/sars-cov-2/2023-11-30/annotations.tsv +``` +","Markdown" +"Microbiology","phac-nml/rebar","docs/notes/Notes_Development.md",".md","14","2","# Development +","Markdown" +"Microbiology","phac-nml/rebar","docs/notes/Notes_v0.1.1.md",".md","212","10","# v0.1.1 + +## New + +- Added `x86_64-unknown-linux-musl` to the supported architectures. + +## Issues + +- Issue #6: **Library Linkage Errors**. Resolved runtime errors concerning missing `libssl` or `GLIBC` libraries. +","Markdown" +"Microbiology","phac-nml/rebar","docs/notes/Notes_v0.2.0.md",".md","402","16","# v0.2.0 + +## New + +- Add example dataset `toy1`. + +## Changes + +- Rename dataset tag `latest` to `nightly`. + + - This is to clarify that the absolute latest dataset files are not validated and possibly unstable. + +## Issues + +- Issue #7: **Font Loading**. Resolved cross-platform errors related to font-loading. The two required fonts are(DejaVu Sans, DejaVu Sans Bold) now compiled into the binary itself. +","Markdown" +"Microbiology","phac-nml/rebar","docs/notes/Notes_v0.1.0.md",".md","365","8","# v0.1.0 + +## Issues + +- Issue #1: **Efficiency Improvements**. Code base rewrite from Python to Rust (PR https://github.com/phac-nml/rebar/pull/5). +- Issue #2: **Misclassifications**. Validation of SARS-CoV-2 recombinant detection (2023-11-17). +- Issue #3: **Dataset Discrepancies**: Handle dataset discrepancies between lineages present in sequences vs. phylogeny. +","Markdown" +"Microbiology","phac-nml/rebar","docs/notes/Notes_v0.2.1.md",".md","561","18","# v0.2.1 + +This patch release documents the new conda installation method, resolves a plotting artifact and improves performance of the `phylogeny` function `get_common_ancestor`. + +## New + +- Issue #10, PR #34 | Add documentation for Conda installation. + +## Fixes + +- Issue #27, PR #37 | Fix legend overflow in plot. + +## Changes + +- Issue #23, PR #39 | Change `parsimony::from_sequence` param `coordinates` from Vector to Slice. +- Issue #28, PR #41 | Improve peformance of `phylogeny::get_common_ancestor` +- Issue #29, PR #38 | Reduce large artifact uploads in CI. +","Markdown" +"Microbiology","phac-nml/rebar","tests/integration_tests.rs",".rs","2090","79","use rebar::cli; +use rebar::dataset::attributes::{Name, Tag}; +use rebar::dataset::download; +use rebar::plot::plot; +use rebar::run::run; + +use color_eyre::eyre::{Report, Result}; +use std::path::PathBuf; +use std::str::FromStr; + +#[tokio::test] +async fn toy1() -> Result<(), Report> { + let output_dir = PathBuf::from(""output"").join(""tests"").join(""toy1""); + + // Dataset Download + let mut args = cli::dataset::download::Args { + name: Name::Toy1, + tag: Tag::from_str(""custom"")?, + output_dir: output_dir.join(""dataset""), + summary: None, + }; + download::dataset(&mut args).await?; + + // Run + let mut args = cli::run::Args { + population: Some(""*"".to_string()), + dataset_dir: output_dir.join(""dataset""), + output_dir: output_dir.join(""run""), + mask: vec![0, 0], + min_length: 3, + ..Default::default() + }; + run(&mut args)?; + + // Plot + let args = cli::plot::Args { + annotations: Some(output_dir.join(""dataset"").join(""annotations.tsv"")), + run_dir: output_dir.join(""run""), + ..Default::default() + }; + plot(&args)?; + + Ok(()) +} + +#[tokio::test] +async fn sarscov2_populations() -> Result<(), Report> { + let output_dir = + PathBuf::from(""output"").join(""tests"").join(""sarscov2"").join(""populations""); + + // Dataset Download + let mut args = cli::dataset::download::Args { + name: Name::SarsCov2, + tag: Tag::from_str(""2023-11-17"")?, + output_dir: output_dir.join(""dataset""), + summary: None, + }; + download::dataset(&mut args).await?; + + // Run + let mut args = cli::run::Args { + population: Some(""AY.4.2*,BA.5.2,XBC.1.6*,XBB.1.5.1,XBL"".to_string()), + dataset_dir: output_dir.join(""dataset""), + output_dir: output_dir.join(""run""), + ..Default::default() + }; + run(&mut args)?; + + // Plot + let args = cli::plot::Args { + annotations: Some(output_dir.join(""dataset"").join(""annotations.tsv"")), + run_dir: output_dir.join(""run""), + ..Default::default() + }; + plot(&args)?; + + Ok(()) +} +","Rust" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","notes/notes.md",".md","842","2","Interestingly, some of the exercises in Yang’s books are derived from classic papers and seminal works of the time. Tackling these exercises may help effectively organize the developmental context of related knowledge, thus a chance for current graduate students and early-career researchers to learn the history. Further, for the software operation exercises included in the present brochure, although PAML (Yang, 1993) is used in most exercises, I also include many others, including the last-century MEGA (1993), the “middle-aged” ape (2002) and RAxML (2006), the more recent ones such as IQ-Tree (2015) and RevBayes (2016), and the newest product in the AI era ChatGPT (2023; see 7.12 in Yang 2014). This hopefully provides readers with a better sense of the development of generations of those widely used (phylogenetic) software. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","notes/acknowledgements.md",".md","755","22","**Problems that specifically need help.** +- CME: +- Problem 5.2 (ii) +- MESA: +- Problems 7.8, 8.2, 9.3 + +**Acknowledgements** + +We extend our sincere gratitude to Ziheng Yang for generously providing numerous intriguing problems in his books and for his encouragement throughout our work on the solutions. + +We also wish to thank the following individuals for their contributions: + +- Mario dos Reis: for providing an alternative script for Exercise 5.5 in CME2006. +- Korbinian Strimmer: for contributing to Exercise 6.4 in MESA2014. +- Klaus Schliep: for help in the use of phangorn Problem 9.1 in MESA2014. + +We are also grateful to the following individuals for their comments on an early version of the brochure: + +- Chun Man Chan +- Youhua Chen +- Weiyi Li +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/References.md",".md","1642","20","**References** + +Felsenstein, J. (1973). Maximum likelihood and minimum-steps methods for estimating evolutionary trees from data on discrete characters. Systematic Biology, 22(3), 240–249. https://doi.org/10.1093/sysbio/22.3.240 + +Graham, R., Knuth, D., & Patashnik, O. (1994). Concrete Mathematics. Addison-Wesley Longman Publishing Co., Inc.75 Arlington Street, Suite 300 Boston, MAUnited States. + +Katoh, K., & Standley, D. M. (2013). MAFFT Multiple Sequence Alignment Software Version 7: Improvements in Performance and Usability. Molecular Biology and Evolution, 30(4), 772–780. + +Minh, B. Q., Schmidt, H. A., Chernomor, O., Schrempf, D., Woodhams, M. D., Von Haeseler, A., Lanfear, R., & Teeling, E. (2020). IQ-TREE 2: New Models and Efficient Methods for Phylogenetic Inference in the Genomic Era. Molecular Biology and Evolution, 37(5), 1530–1534. https://doi.org/10.1093/molbev/msaa015 + +Nascimento, F. F., dos Reis, M., & Yang, Z. H. (2017). A biologist’s guide to Bayesian phylogenetic analysis. Nature Ecology & Evolution, 1(10), 1446–1454. https://doi.org/10.1038/s41559-017-0280-x + +Negative binomial distribution. (2023). https://en.wikipedia.org/wiki/Negative_binomial_distribution + +Suyama, M., Torrents, D., & Bork, P. (2006). PAL2NAL: Robust conversion of protein sequence alignments into the corresponding codon alignments. Nucleic Acids Research. https://doi.org/10.1093/nar/gkl315 + +Yang, Z. (2006). Computational Molecular Evolution. Oxford University Press. http://abacus.gene.ucl.ac.uk/CME/ + +Yang, Z. (2014). Molecular Evolution: A Statistical Approach. Oxford University Press. http://abacus.gene.ucl.ac.uk/MESA/ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C2 Models of amino acid and codon/2.3.md",".md","2661","75","**Solution.** + +\(a\) Refer to Eq. (2.10) in (Yang, 2006): + +$$d_{S} = \frac{L_{2}A_{2} + L_{4}d_{4}}{\frac{L_{2}}{3} + L_{4}},\ d_{N} = \frac{L_{2}B_{2} + L_{0}d_{0}}{\frac{2}{3}L_{2} + L_{0}}.$$ + +According to the given information, we have $\alpha = \kappa\beta$, +$A_{0} = \alpha t\omega$, $B_{0} = 2\beta t\omega$, $A_{2} = \alpha t$, +$B_{2} = 2\beta t\omega$, $A_{4} = \alpha t$, +$B_{4} = 2\beta t$,$\ L_{0} = 2$, $L2 = 1 - \gamma$, and +$L_{4} = \gamma$. Hence, + +$${d_{0} = A_{0} + B_{0} = \alpha t\omega + 2\beta t\omega},$$ + +$${d_{4} = A_{4} + B_{4} = \alpha t + 2\beta t.}$$ + +Plugging the above into Eq. (2.10) in (Yang, 2006), we have + +$$ +\begin{align*} +d_{S} &= \frac{(1 - \gamma)\alpha t + \gamma(\alpha t + 2\beta t)}{\frac{1 - \gamma}{3} + \gamma} \\ +&= 3 \times \frac{(1 - \gamma)\kappa\beta t + \gamma(\kappa\beta t + 2\beta t)}{1 + 2\gamma} \\ +&= \frac{3(\kappa + 2\gamma)\beta t}{1 - 2\gamma}, +\end{align*} +$$ + +and + +$$ +\begin{align*} +d_{N} &= \frac{2\beta t\omega(1 - \gamma) + 2(\alpha t\omega + 2\beta t\omega)}{\frac{2}{3}(1 - \gamma) + 2} \\ +&= \frac{3\left( \beta t\omega(1 - \gamma) + (\kappa\beta t\omega + 2\beta t\omega) \right)}{4 - \gamma} \\ +&= \frac{3(\kappa + 3 - \gamma)\beta t\omega}{4 - \gamma}. +\end{align*} +$$ + +\(b\) As to LPB93, following Eq. (2.11) in (Yang, 2006), we have + +$${d_{S} = \frac{L_{2}A_{2} + L_{4}A_{4}}{L_{2} + L_{4}} + B_{4} +}{= \frac{(1 - \gamma)\alpha t + \gamma\alpha t}{(1 - \gamma) + \gamma} + 2\beta t +}{= \alpha t + 2\beta t,}$$ + +$${d_{N} = A_{0} + \frac{L_{0}B_{0} + L_{2}B_{2}}{L_{0} + L_{2}} +}{= \alpha t\omega + \frac{2(2\beta t\omega) + (1 - \gamma) \times 2\beta t\omega}{2 + 1 - \gamma} +}{= \omega(\alpha t + 2\beta t). +}$$ + +As to LWL85m, we follow Eq. (2.12) in (Yang, 2006) to calculate $d_{S}$ +as + +$$ +\begin{align*} +d_{S} &= \frac{L_{2}A_{2} + L_{4}d_{4}}{\rho L_{2} + L_{4}} \\ +&= \frac{(1 - \gamma)\alpha t + \gamma(\alpha t + 2\beta t)}{\frac{\alpha t}{\alpha t + 2\beta t}(1 - \gamma) + \gamma} \\ +&= \frac{(\alpha t + 2\beta t)(\alpha t + 2\gamma\beta t)}{\alpha t(1 - \gamma) + (\alpha t + 2\beta t)\gamma} \\ +&= \alpha t + 2\beta t, +\end{align*} +$$ + +and $d_{N}$ as + +$$ +\begin{align*} +d_{N} &= \frac{L_{2}B_{2} + L_{0}d_{0}}{(1 - \rho)L_{2} + L_{0}} \\ +&= \frac{(1 - \gamma)2\omega\beta t + 2(\omega\alpha t + 2\omega\beta t)}{\left( 1 - \frac{\alpha t}{\alpha t + 2\beta t} \right)(1 - \gamma) + 2} \\ +&= \omega(\alpha t + 2\beta t)\frac{(1 - \gamma)\beta t + (\alpha t + 2\beta t)}{(1 - \gamma)\beta t + (\alpha t + 2\beta t)} \\ +&= \ \omega d_{S}. +\end{align*} +$$ + + +Note that in the above $\rho$ is given as +$\rho = \frac{A_{4}}{A_{4} + B_{4}}$ according to Eq (2.13) in (Yang, +2006). +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C2 Models of amino acid and codon/2.1.md",".md","1301","49","**Solution.** + +Following Exercise 2.1 in (Yang, 2014), I download the sequences of the +gene coding for NADH6 of *Homo sapiens* and *Pongo pygmaeus* from their +mitochondrial genome sequences (Accession: X93334 and D38115 +respectively). Note that to translate the CDS of human one into amino +acids the reverse complement may be needed. Then, alignment the amino +acid sequences using MAFFT (Katoh & Standley, 2013), and construct the +DNA alignment based on the protein alignment with PAL2NAL (Suyama et +al., 2006). + +Then use CODEML to get the results. The following shows my settings of +the file *codeml.ctl*. Note that in the control file *codeml.ctl* you +need to set icode=1 which represents the codon table 1, i.e., the one +used in mammalian mitochondria. Kappa is set to zero which means it is +estimated rather than fixed. + +![](img/2.1-1.png) + +```Bash +$ mafft AA.fas > AA.aln +$ pal2nal.pl AA.aln DNA.fas -output paml -codontable 2 > DNA.paml +$ codeml codeml.ctl +``` + +The estimates for $d_{S}$, $d_{N}$, $d_{1B}$, $d_{2B}$, $d_{3B}$, +$d_{S^\*}$, and $d_{N^\*}$ by using different models are displayed +as follows which are directly obtained from CODEML's output. + +Fequal: + +![](img/2.1-2.png) + +F1X4: + +![](img/2.1-3.png) + +F3X4: + +![](img/2.1-4.png) + +F61: + +![](img/2.1-5.png) + +FMutSel: + +![](img/2.1-6.png) +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C2 Models of amino acid and codon/2.2.md",".md","640","12","**Solution.** + +The following assumes $\kappa = 1$. The three codon positions can each +change to three other nucleotides, so the codon TAT which codes for Tyr, +has nine immediate neighbors, namely TAC (Tyr), TAA (\*), TAG (\*), TTT +(Phe), TCT (Ser), TGT (Cys), CAT (His), AAT (Asn), GAT (Asp). Among +these nine, TAA and TAG are stop codon, TAC codes for the same amino +acid as the original one TAT, while the remaining six code for amino +acids different from TAT. Hence, the number of synonymous sites is equal +to $3 \times \frac{1}{9} = \frac{1}{3}$ and that of nonsynonymous sites +is equal to $3 \times \frac{6}{9} = 2$ for the codon TAT. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.2.md",".md","5774","190","**Solutions.** + +We provide two solutions to (b). The first solves it combinatorically, +while the second uses an approach based on infinite series. Note that +as (b) seems to us a bit unclear and as we interpret it our answer to (b) is slightly different from what is given in the problem statement: +an unbiased estimator of the parameter $\theta$ in negative binomial distribution is $\widetilde{\theta} = \frac{x - 1}{N - 1}$ instead of $\frac{x}{N - 1}$. + + +**Solution 1.** + +a\) Under the model of binomial distribution: + +$$ +\begin{align*} +E(X) &= \sum_{i = 0}^{n}{i \cdot P(X = i)} \\ +&= \sum_{i = 1}^{n}{i\begin{pmatrix} +n \\ +i \\ +\end{pmatrix}\theta^{i}(1 - \theta)^{n - i}} \\ +&= n\theta\sum_{i = 1}^{n}{\begin{pmatrix} +n - 1 \\ +i - 1 \\ +\end{pmatrix}\theta^{i - 1}(1 - \theta)^{(n - 1) - (i - 1)}} \\ +&= n\theta\sum_{j = 0}^{n - 1}{\begin{pmatrix} +n - 1 \\ +j \\ +\end{pmatrix}\theta^{j}(1 - \theta)^{(n - 1) - j}} \\ +&= n\theta(1 - \theta + \theta)^{n - 1} \\ +&= n\theta. +\end{align*} +$$ + +b\) Under the model of negative binomial distribution, given the +context, the number of heads $x = 9$ is fixed and the number of tails, +denoted as $Y$, follows a negative binomial distribution NB(9, +$\theta$). Hence, the number of total tosses can be denoted as +$N = Y + 9$. In the example given in the problem, $N = 12$. + +It should be noted however that an unbiased estimator of $\theta$ is +$\widetilde{\theta} = \frac{x - 1}{N - 1}$. In other words, +$E\left( \widetilde{\theta} \right) = E\left( \frac{x - 1}{n - 1} \right) = \theta$ +(*Negative Binomial Distribution*, 2023). This is different from the +""answer"" given in the problem. The following shows why +$\widetilde{\theta} = \frac{x - 1}{N - 1}$ instead of $\frac{x}{N - 1}$ +is an unbiased estimator. The expectation of +$\widetilde{\theta} = \frac{x - 1}{N - 1}$ may be calculated as follows: + +$$ +\begin{align*} +E(\widetilde{\theta}) &= \sum_{n = x}^{\infty}{\frac{x - 1}{n - 1}\begin{pmatrix} +n - 1 \\ +x - 1 \\ +\end{pmatrix}\theta^{x}(1 - \theta)^{n - x}} \\ +&= \sum_{i = 0}^{\infty}{\frac{x - 1}{x + i - 1}\begin{pmatrix} +x + i - 1 \\ +x - 1 \\ +\end{pmatrix}\theta^{x}(1 - \theta)^{i}}\quad\text{(n = x + i)} \\ +&= \sum_{i = 0}^{\infty}{\frac{x - 1}{x + i - 1}\begin{pmatrix} +x + i - 1 \\ +i \\ +\end{pmatrix}\theta^{x}(1 - \theta)^{i}} +\end{align*} +$$ + +By plugging + +$$ +\begin{pmatrix} +x + i - 1 \\ +i \\ +\end{pmatrix} = \frac{x + i - 1}{i}\begin{pmatrix} +x + i - 2 \\ +i - 1 \\ +\end{pmatrix} +$$ + +into the above, we have + +$$ +\begin{align*} +E\left( \widetilde{\theta} \right) &= \sum_{i = 0}^{\infty}{\frac{x - 1}{x + i - 1}\frac{x + i - 1}{i}\begin{pmatrix} +x + i - 2 \\ +i - 1 \\ +\end{pmatrix}\theta^{x}(1 - \theta)^{i}} \\ +&= \sum_{i = 0}^{\infty}{\frac{x - 1}{i}\frac{(x + i - 2)!}{(i - 1)!(x - 1)!}\theta^{x}(1 - \theta)^{i}} \\ +&= \sum_{i = 0}^{\infty}{\frac{1}{i(i - 1)!}\frac{(x + i - 2)!}{(x - 2)!}\theta^{x}(1 - \theta)^{i}} \\ +&= \sum_{i = 0}^{\infty}{\frac{(x + i - 2)!}{i!(x - 2)!}\theta^{x}(1 - \theta)^{i}} \\ +&= \sum_{i = 0}^{\infty}{\begin{pmatrix} +x + i - 2 \\ +i \\ +\end{pmatrix}\theta^{x}(1 - \theta)^{i}} \\ +&= \theta\sum_{i = 0}^{\infty}{\begin{pmatrix} +x + i - 2 \\ +i \\ +\end{pmatrix}\theta^{x - 1}(1 - \theta)^{i}} \\ +&= \theta\sum_{i = 0}^{\infty}{\begin{pmatrix} +x' + i - 1 \\ +i \\ +\end{pmatrix}\theta^{x'}(1 - \theta)^{i}}\quad\left( x' = x - 1 \right) \\ +&= \theta \times 1 \\ +&= \theta. +\end{align*} +$$ + +Hence, an unbiased estimator of $\theta$ under the negative binomial model +when 3 failures and 9 successes are observed is +$\frac{9 - 1}{12 - 1} = \frac{8}{11}$. + +**Solution 2.** + +\(b\) Define +$(x)_{n} = x \times (x - 1) \times \cdots \times (x - n + 1)$. This is +known as the falling and rising factorial (Graham et al., 1994). Hence, + +

+ +

+ +Consider the summation function + +$$f(t) = \sum_{n = x}^{\infty}{(n - 2)_{x - 2}t^{n - x}}.$$ + +It follows that + +$${f(t) = \sum_{n = x}^{\infty}\frac{d^{x - 2}}{dt^{x - 2}}\left( t^{n - 2} \right) +}{= \sum_{k = x - 2}^{\infty}\frac{d^{x - 2}}{dt^{x - 2}}\left( t^{k} \right).}$$ + +Define + +$$g(y) = \frac{d^{x - 2}}{dt^{x - 2}}\left( t^{y} \right).$$ + +It is easy to see that + +$$g(0) = g(1) = \ldots = g(k - 3) = 0.$$ + +Also, noting that $0 < t < 1 - \theta < 1$, the geometric series +$\sum_{k = 0}^{\infty}t^{k}$ can be calculated as + +$$ +\begin{align*} +\sum_{k = 0}^{\infty}t^{k} &= \lim_{n \rightarrow \infty}{(1 + t^{1} + t^{2} + \ldots t^{n})} \\ +&= \frac{1}{1 - k}. +\end{align*} +$$ + +So $f(t)$ may be re-written as + +$$ +\begin{align*} +f(t) &= \sum_{k = 0}^{\infty}\frac{d^{x - 2}}{dt^{x - 2}}\left( t^{k} \right) \\ +&= \frac{d^{x - 2}}{dt^{x - 2}}\left( \sum_{k = 0}^{\infty}t^{k} \right)\quad \text{(sum - differentiation order swapping)} \\ +&= \frac{d^{x - 2}}{dt^{x - 2}}\left( \frac{1}{1 - t} \right) \\ +&= - 1 \times ( - 1) \times ( - 2) \times \cdots \times (2 - x) \times (t - 1)^{1 - x}. +\end{align*} +$$ + +Noting that + +$$\begin{align*} +( - 1) \times ( - 2) \times \cdots \times (2 - x) &= ( - 1)^{2 - x} \times (x - 2) \times (x - 1) \times \cdots \times 1 \\ +&= ( - 1)^{2 - x}(x - 2)! +\end{align*}$$ + +and that + +$$(t - 1)^{1 - x} = {( - 1)^{1 - x} \times (1 - t)}^{1 - x},$$ + +we have + +$$\begin{align*} +f(t) &= {- 1 \times ( - 1)}^{2 - x}(x - 2)! \times {( - 1)^{1 - x} \times (1 - t)}^{1 - x} \\ +&= (x - 2)!(1 - t)^{1 - x}. +\end{align*}$$ + +So + +$$\begin{align*} +f(1 - \theta) &= \sum_{n = x}^{\infty}{(n - 2)_{x - 2}(1 - \theta)^{n - x}} \\ +&= (x - 2)!\theta^{1 - x}, +\end{align*}$$ + +$$f(\theta) = (x - 2)!{(1 - \theta)}^{1 - x}.$$ + +Plugging this into +$E\left( \widetilde{\theta} \right) = \frac{\theta^{x}}{(x - 2)!}\sum_{n = x}^{\infty}{(n - 2)_{x - 2}(1 - \theta)^{n - x}}$ +(see above), we have + +$${E\left( \widetilde{\theta} \right) = \frac{\theta^{x}}{(x - 2)!}(x - 2)!\theta^{1 - x} +}{= \theta.}$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.3.md",".md","13332","338","**Solutions.** + +As follows three solutions are provided. The first is the most +complicated in calculation but might be the most straightforward to come +up with, the second much simplifies the first by a smart trick, while +the last one is mainly based on some nice properties of normal +distribution. + +**Solution 1.** + +Without loss in generality, assume the original normal distribution to +be approximated by MCMC is the standard normal distribution +$Normal(0,1)$. According to the Metropolis-Hastings algorithm, the +acceptance rate for any $\theta$ is + +$$A\left( \theta^{'};\theta \right) = \min\left( 1,\frac{\pi\left( \theta^{'} \right)g\left( \theta|\theta^{'} \right)}{\pi(\theta)g\left( \theta^{'}|\theta \right)} \right).$$ + +Because the proposal distribution $g$ is the same for all $\theta$, the +above can be re-written as + +$$\alpha = \min\left( 1,\frac{\pi\left( \theta^{'} \right)}{\pi(\theta)} \right).$$ + +For any $x$ randomly sampled from the standard normal distribution, its +acceptance rate is equal to the following + +$$ +\begin{align*} +P &= \iint_{f(y) \geq f(x)}{f(x)q\left( y \middle| x \right)dydx} + \iint_{f(y) < f(x)}{f(x)q\left( y \middle| x \right)\frac{f(y)}{f(x)}dydx} \\ +&= \iint_{f(y) \geq f(x)}{f(x)q\left( y \middle| x \right)dydx} + \iint_{f(y) < f(x)}{f(y)q\left( y \middle| x \right)dydx} \\ +&= \iint_{f(y) > f(x)}{f(x)q\left( y \middle| x \right)dydx} + \iint_{f(y) < f(x)}{f(y)q\left( y \middle| x \right)dydx} + \iint_{f(y) = f(x)}{f(y)q\left( y \middle| x \right)dydx}, +\end{align*} +$$ + +Define the following + +$${I_{1} = \iint_{f(y) > f(x)}^{\ }{f(x)q\left( y \middle| x \right)dydx},}$$ + +$${I_{2} = \iint_{f(y) < f(x)}^{\ }{f(y)q\left( y \middle| x \right)}dydx,}$$ + +$${I_{3} = \iint_{f(y) = f(x)}^{\ }{f(y)q\left( y \middle| x \right)}dydx.}$$ + +Apparently, + +$$I_{3} = 0.$$ + +Hence, + +$$\begin{matrix} +P = I_{1} + I_{2} + I_{3} = I_{1} + I_{2}. (5.1) \\ +\end{matrix}$$ + +As to **$I_{2}$**: Because of symmetry of the +density, without loss of generality, consider only $x$ that are +positive. So $I_{2}$ can be written as + +$$\begin{align*} +I_{2} &= \iint_{f(y) < f(x)}{q\left( y \middle| x \right)f(y)}dydx \\ +&= 2 \times \left( \frac{1}{2\pi\sigma}\int_{0}^{+ \infty}{\int_{x}^{+ \infty}{e^{\frac{- x^{2} - \left( \sigma^{2} + 1 \right)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}} + \frac{1}{2\pi\sigma}\int_{0}^{+ \infty}{\int_{- \infty}^{- x}{e^{\frac{- x^{2} - \left( \sigma^{2} + 1 \right)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}} \right). +\end{align*} +$$ + +Define + +$$I_{21} = \frac{1}{2\pi\sigma}\int_{0}^{+ \infty}{\int_{x}^{+ \infty}{e^{\frac{- x^{2} - \left( \sigma^{2} + 1 \right)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}},$$ + +$$I_{22} = \frac{1}{2\pi\sigma}\int_{0}^{+ \infty}{\int_{- \infty}^{- x}{e^{\frac{- x^{2} - \left( \sigma^{2} + 1 \right)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}}.$$ + +We have + +$$\begin{matrix} +I_{2} = 2\left( I_{21} + I_{22} \right). (5.2) \\ +\end{matrix}$$ + +**To calculate** $I_{21}$, apply the following linear +transformation + +$$\begin{bmatrix} +u \\ +v \\ +\end{bmatrix} = \begin{bmatrix} +1 & - 1 \\ +0 & \sigma \\ +\end{bmatrix}\begin{bmatrix} +x \\ +y \\ +\end{bmatrix},$$ + +$$(x - y)^{2} + (\sigma y)^{2} = u^{2} + v^{2},$$ + +and + +$$u = x - y,\ v = \sigma y$$ + +$$x = u + \frac{v}{\sigma},\ y = \frac{v}{\sigma}.$$ + +Calculate the determinant of the Jacobian as follows + +$$|J| = det\begin{bmatrix} +\frac{dx}{du} & \frac{dx}{dv} \\ +\frac{dy}{du} & \frac{dy}{dv} \\ +\end{bmatrix} = det\begin{bmatrix} +1 & \frac{1}{\sigma} \\ +0 & \frac{1}{\sigma} \\ +\end{bmatrix} = \frac{1}{\sigma}.$$ + +For $I_{21}$, the original integral area is the +region enclosed by $x = 0$ and $y = x$, thus $0 < x < y$. It is easy to +see that $0 < u + \frac{1}{\sigma}v < \frac{v}{\sigma},$ thus +$\ 0 > u > - \frac{v}{\sigma}$. This corresponds to the region enclosed +by $u = 0$ and $u = - \frac{1}{\sigma}v$ (thus $v = - \sigma u$). So +$I_{21}$ may be rewritten as + +$$\begin{align*} +I_{21} &= \frac{1}{2\pi\sigma}\int_{0}^{+\infty}{\int_{x}^{+\infty}{e^{\frac{-x^{2} - \left(\sigma^{2} + 1\right)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}} \\ +&= \frac{1}{2\pi\sigma}\int_{0}^{+\infty}{\int_{-\frac{v}{\sigma}}^{0}{e^{-\frac{u^{2} + v^{2}}{2\sigma^{2}}}|J|dudv}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{\int_{-\frac{v}{\sigma}}^{0}{e^{-\frac{u^{2} + v^{2}}{2\sigma^{2}}}dudv}} \\ +&= \int_{0}^{+\infty}{\frac{1}{\sqrt{2\pi\sigma^{2}}}e^{-\frac{v^{2}}{2\sigma^{2}}}dv\int_{-\frac{v}{\sigma}}^{0}{{\frac{1}{\sqrt{2\pi\sigma^{2}}}e}^{-\frac{u^{2}}{2\sigma^{2}}}du}} \\ +&= \frac{\tan^{-1}\left(\frac{1}{\sigma}\right)}{2\pi} \qquad (5.3) +\end{align*} +$$ + +The last step is because as indicated by the following contour graph of +the probability density of a standard bivariate distribution (left), it +can be seen that +$\int_{0}^{+ \infty}{\frac{1}{\sqrt{(2\pi)\sigma^{2}}}e^{- \frac{v^{2}}{2\sigma^{2}}}dv\int_{- \frac{v}{\sigma}}^{0}{{\frac{1}{\sqrt{(2\pi)\sigma^{2}}}e}^{- \frac{u^{2}}{2\sigma^{2}}}du}}$ +is equal to the proportion of +$\frac{\tan^{- 1}\left( \frac{1}{\sigma} \right)}{2\pi}$ of the +probability covered by a standard bivariate normal distribution the +latter of which equals 1. + +

+ +

+ +$$\begin{align*} +I_{21} &= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{\int_{-\frac{v}{\sigma}}^{0}{e^{-\frac{u^{2} + v^{2}}{2\sigma^{2}}}dudv}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{re^{-\frac{r^{2}}{2\sigma^{2}}}dr\int_{\tan^{-1}\left(-\frac{1}{\sigma}\right)}^{0}{d\theta}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{re^{-\frac{r^{2}}{2\sigma^{2}}}dr\int_{0}^{\tan^{-1}\left(\frac{1}{\sigma}\right)}{d\theta}} \\ +&= \frac{1}{2\pi\sigma^{2}} \times \frac{\Gamma(1)}{2 \times \frac{1}{2} \times \left(\frac{1}{\sigma}\right)^{2}} \cdot \tan^{-1}\left(\frac{1}{\sigma}\right) \\ +&= \frac{\tan^{-1}\left(\frac{1}{\sigma}\right)}{2\pi}. +\end{align*}$$ + +By solving the above, we get + +$$ +\tan\beta = - \frac{\sigma}{\sigma^{2} + 2}. +$$ + +Hence + +$$\begin{align*} +I_{22} &= \frac{1}{2\pi\sigma}\int_{0}^{+\infty}{\int_{-\infty}^{-x}{e^{\frac{-x^{2} - (\sigma^{2} + 1)y^{2} + 2\sigma xy}{2\sigma^{2}}}dydx}} \\ +&= \frac{1}{2\pi\sigma}\int_{0}^{+\infty}{\int_{-\frac{\sigma}{\sigma^{2} + 2}v}^{0}{e^{-\frac{u^{2} + v^{2}}{2\sigma^{2}}}|J|dudv}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{\int_{-\frac{\sigma}{\sigma^{2} + 2}v}^{0}{e^{-\frac{u^{2} + v^{2}}{2\sigma^{2}}}dudv}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+\infty}{e^{-\frac{(x - y)^{2}}{2\sigma^{2}}}\int_{-\frac{\sigma}{\sigma^{2} + 2}v}^{0}{e^{-\frac{y^{2}}{2\sigma^{2}}}dydx}} \\ +&= \frac{\tan^{-1}\left(\frac{\sigma}{\sigma^{2} + 2}\right)}{2\pi}. +\end{align*}$$ + +Note that the last step in the above can be solved by using the same trick applied in deriving Eq. (5.3). Alternatively, it is also possible to use the transformation from Cartesian coordinates to polar coordinates, so that + +$$\begin{align*} +I_{22} &= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+ \infty}{e^{- \frac{r^{2}}{2\sigma^{2}}}rdr\int_{\tan^{- 1}\left( - \frac{\sigma}{\sigma^{2} + 2} \right)}^{0}{d\theta}} \\ +&= \frac{1}{2\pi\sigma^{2}}\int_{0}^{+ \infty}{e^{- \frac{r^{2}}{2\sigma^{2}}}rdr\int_{0}^{\tan^{- 1}\left( \frac{\sigma}{\sigma^{2} + 2} \right)}{d\theta}} \\ +&= {\frac{1}{2\pi\sigma^{2}} \times \frac{\Gamma(1)}{2 \times \frac{1}{2} \times ({\frac{1}{\sigma})}^{2}} \bullet \tan^{- 1}}\left( \frac{\sigma}{\sigma^{2} + 2} \right) \\ +&= \frac{\tan^{- 1}\left( \frac{\sigma}{\sigma^{2} + 2} \right)}{2\pi}. +\end{align*}$$ + + +Further, apply the sum formula for arctangent + +$$\arctan\left( A) + arctan(B \right) = \arctan\left( \frac{A + B}{1 - AB} \right).$$ + +It follows that + +$$\begin{align*} +I_{2} &= I_{21} + I_{22} \\ +&= 2 \times \left( \frac{\tan^{-1}\left(\frac{1}{\sigma}\right)}{2\pi} + \frac{\tan^{-1}\left(\frac{\sigma}{\sigma^{2} + 2}\right)}{2\pi} \right) \\ +&= \frac{1}{\pi}\tan^{-1}\left(\frac{\frac{1}{\sigma} + \frac{\sigma}{\sigma^{2} + 2}}{1 - \frac{1}{\sigma} \cdot \frac{\sigma}{\sigma^{2} + 2}}\right) \\ +&= \frac{1}{\pi}\tan^{-1}\left(\frac{2\sigma^{2} + 2}{\sigma^{3} + \sigma}\right) +\end{align*}$$ + +Similarly, as to $I_{1}$, without loss of generality, considering $x > 0$, $I_{1}$ can be re-written as + +$$\begin{align*} +I_{1} &= \iint_{f(y) \geq f(x)}^{\ }{f(x)q\left( y \middle| x \right)dydx} \\ +&= 2 \times \frac{1}{\sigma}\iint_{f(y) \geq f(x)}^{\ }{{\frac{1}{\sqrt{2\pi}}e}^{- \frac{x^{2}}{2}}\frac{1}{\sqrt{2\pi}\sigma}e^{- \frac{(x - y)^{2}}{2\sigma^{2}}}dydx} \\ +&= \frac{2}{\sigma}\int_{0}^{+ \infty}{\int_{- x}^{x}{{\frac{1}{\sqrt{2\pi}}e}^{- \frac{x^{2}}{2}}\frac{1}{\sqrt{2\pi}\sigma}e^{- \frac{(x - y)^{2}}{2\sigma^{2}}}dydx}} \\ +&= \frac{2}{\sigma}\int_{0}^{+ \infty}{{\frac{1}{\sqrt{2\pi}}e}^{- \frac{x^{2}}{2}}dx\int_{- x}^{x}{\frac{1}{\sqrt{2\pi}\sigma}e^{- \frac{(x - y)^{2}}{2\sigma^{2}}}dy}}. +\end{align*}$$ + +Apply the following linear transformation + +$$\begin{bmatrix} +z \\ +w \\ +\end{bmatrix} = \begin{bmatrix} +\frac{1}{\sigma} & - \frac{1}{\sigma} \\ +1 & 0 \\ +\end{bmatrix}\begin{bmatrix} +x \\ +y \\ +\end{bmatrix},$$ + +so that + +$$x = w + \sigma z,y = w.$$ + +The determinant of the Jacobian is calculated as + +$$|J| = \det\begin{bmatrix} +\frac{dx}{dz} & \frac{dx}{dw} \\ +\frac{dy}{dz} & \frac{dy}{dw} \\ +\end{bmatrix} = \left| \begin{matrix} +\sigma & 1 \\ +0 & 1 \\ +\end{matrix} \right| = \sigma.$$ + +The above can thus be re-written as + +$$\begin{align*} +I_{1} &= \frac{2}{\sigma}\int_{0}^{+\infty}{{\frac{1}{\sqrt{2\pi}}e}^{-\frac{w^{2}}{2}}dw\int_{-x}^{x}{\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{z^{2}}{2\sigma^{2}}}|J|dz}} \\ +&= \sigma \cdot \frac{2}{\sigma} \cdot \int_{0}^{+\infty}{{\frac{1}{\sqrt{2\pi}}e}^{-\frac{w^{2}}{2}}dw\int_{0}^{\frac{2w}{\sigma}}{\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{z^{2}}{2}}dz}} \\ +&= 2\int_{0}^{+\infty}{{\frac{1}{\sqrt{2\pi}}e}^{-\frac{w^{2}}{2}}dw\int_{0}^{\frac{2w}{\sigma}}{\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{z^{2}}{2}}dz}} \\ +&= \frac{1}{\pi}\tan^{-1}\left(\frac{2}{\sigma}\right). (5.5) +\end{align*}$$ + +Finally, by plugging Eqs. (5.3-5.5) into Eq. (5.1), we have +$$P_{jump} = I_{1} + I_{2} = \frac{2}{\pi}\tan^{- 1}\left( \frac{2}{\sigma} \right).$$ + + +**Solution 2.** + +In Solution 1 we see that $I_{1} = I_{2}$ and that calculating $I_{1}$ +is easier than $I_{2}$. As follows, it can be shown that $I_{1} = I_{2}$ +is not a coincidence, and as such, it implies that we can greatly +simplify the calculation by computing only $I_{1}$ ​and then multiplying +it by two to obtain $P$. + +$$\begin{align*} +I_{1} &= \iint_{f(y) > f(x)}^{\ }{f(x)q\left( y \middle| x \right)dydx} \\ +&= \iint_{|y| > |x|}^{\ }{f(x)q\left( y \middle| x \right)dydx} \\ +&= \iint_{|x| > |y|}^{\ }{f(y)q\left( x \middle| y \right)dxdy} \quad \text{(swapping } x \text{ and } y) \\ +&= \iint_{|x| > |y|}^{\ }{f(y)q\left( x \middle| y \right)dydx} \\ +&= I_{2}. +\end{align*}$$ + +The following steps are the same as Solution 1, but there will not be +any need to calculate $I_{2}$ which is more difficult to calculate than +$I_{1}$ any more. + + + +**Solution 3.** + +Define + +$$X\sim Normal(0,1),$$ + +$$Y\sim Normal(X,\theta).$$ + +Further, define + +$$f_{XY}(X = x,Y = y) = \pi(x)q\left( y \middle| x \right).$$ + +According to the above, we have + +$$ +\begin{align*} +P_{\text{jump}} &= E\left( \alpha(X,Y) \right) \\ +&= E\left( \min\left( 1,\frac{f_{XY}(X = y,Y = x)}{f_{XY}(X = x,Y = y)} \right) \right) \\ +&= 2 \times P\left( f_{XY}(X,Y) < f_{XY}(X,Y) \right). +\end{align*} +$$ + +It can also be shown that + +$${f_{XY}(X,Y) = f_{X}(X)f_{Y}\left( Y|X \right) +}{= \frac{1}{\sqrt{2\pi}}e^{- \frac{(X - \theta)^{2}}{2}} \times \frac{1}{\sqrt{2\pi}}e^{- \frac{(Y - X)^{2}}{2\sigma^{2}}}.}$$ + +Likewise, + +$$f_{XY}(Y,X) = \frac{1}{\sqrt{2\pi}}e^{- \frac{(Y - \theta)^{2}}{2}} \times \frac{1}{\sqrt{2\pi}}e^{- \frac{(X - Y)^{2}}{2\sigma^{2}}}.$$ + +Hence, + +$$ +\begin{align*} +P_{jump} &= 2P\left( \frac{1}{\sqrt{2\pi}}e^{- \frac{(X - \theta)^{2}}{2}}\frac{1}{\sqrt{2\pi}}e^{- \frac{(Y - X)^{2}}{2\sigma^{2}}} < \frac{1}{\sqrt{2\pi}}e^{- \frac{(Y - \theta)^{2}}{2}}\frac{1}{\sqrt{2\pi}}e^{- \frac{(X - Y)^{2}}{2\sigma^{2}}} \right) \\ +&= 2P\left( - \frac{(X - \theta)^{2}}{2} - \frac{(Y - X)^{2}}{2\sigma^{2}} < - \frac{(Y - \theta)^{2}}{2} - \frac{(X - Y)^{2}}{2\sigma^{2}} \right) \\ +&= 2P\left( (X - \theta)^{2} > (Y - \theta)^{2} \right) \\ +&= 2P\left( (X - Y)(X + Y - 2\theta) > 0 \right). +\end{align*} +$$ + +According to the context, we have + +$$X - 1\sim Normal(0,1),$$ + +$$Y - X\sim Normal\left( 0,\sigma^{2} \right).$$ + +Also, $X$ and $Y$ are independent variables. Apply the following +transformation + +$$ +\begin{cases} +U = X - \theta \\ +V = \frac{Y - X}{\sigma} \\ +\end{cases} +$$ + +Equivalently, + +$$ +\begin{cases} +X = U + \theta \\ +Y = \sigma V + U + \theta \\ +\end{cases}. +$$ + +So + +$$ +\begin{align*} +P_{jump} &= 2P\left( - \sigma V(\sigma V + 2U) > 0 \right) \\ +&= 2P\left( V(\sigma V + 2U) < 0 \right) \\ +&= 2\left( P(V < 0,\sigma V + 2U > 0) + P(V > 0,\sigma V + 2U < 0) \right) \\ +&= 2\left( P\left( V < 0,U > - \frac{\sigma V}{2} \right) + P\left( V > 0,U < - \frac{\sigma V}{2} \right) \right). +\end{align*} +$$ + +Using corresponding results from Solution 1, it is clear that + +$$P\left( V < 0,U > - \frac{\sigma V}{2} \right) = P\left( V > 0,U < - \frac{\sigma V}{2} \right) = \frac{\tan^{- 1}\left( \frac{2}{\sigma} \right)}{2\pi}.$$ + +Thus + +$$P_{jump}\mathbf{=}2\mathbf{\times}2 \times \frac{\tan^{- 1}\left( \frac{2}{\sigma} \right)}{2\pi}\mathbf{=}\frac{2}{\pi}\tan^{- 1}\left( \frac{2}{\sigma} \right).$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.1.md",".md","1610","37","**Solution.** + +a\) According to the context, $A$ denotes the event that a person is +infected, and $B$ denotes the event that a person tests positive. +According to the Bayes' theorem, it follows that + +$$ +\begin{align*} +P\left( A|\overline{B} \right) &= \frac{P(A)P\left( \overline{B} \middle| A \right)}{P\left( \overline{B} \right)} \\ +&= \frac{P(A)\left( 1 - P\left( B \middle| A \right) \right)}{1 - P(B)} \\ +&= \frac{P(A)\left( 1 - P\left( B \middle| A \right) \right)}{1 - \left( P(A)P\left( B \middle| A \right) + \left( 1 - P(A) \right)P\left( B \middle| \overline{A} \right) \right)}. +\end{align*} +$$ + +Introducing $P\left( B \middle| A \right) = 0.99$, +$P\left( B \middle| \overline{A} \right) = 0.02$, $P(A) = 0.001$ as +given in Section 5.1.2 of (Yang, 2006), we have + +$$\begin{align*} +P\left( A|\overline{B} \right) &= \frac{0.001 \times (1 - 0.99)}{1 - (0.001 \times 0.99 - 0.999 \times 0.02)} \\ +&= 1.021419e - 05. +\end{align*} +$$ + +b\) Denote $C$ as the event that a person tests positive twice. It +follows that + +$$ +\begin{align*} +P\left( A \middle| C \right) &= \frac{P(A)P\left( C \middle| A \right)}{P(C)} \\ +&= \frac{P(A)P\left( B \middle| A \right)P\left( B \middle| A \right)}{P(A)P\left( C|A \right) + P\left( \overline{A} \right)P\left( C|\overline{A} \right)} \\ +&= \frac{P(A)P\left( B \middle| A \right)P\left( B \middle| A \right)}{P(A)P\left( B|A \right)P\left( B|A \right) + P\left( \overline{A} \right)P\left( B|\overline{A} \right)P\left( B|\overline{A} \right)} \\ +&= \frac{0.001 \times {0.99}^{2}}{0.001 \times {0.99}^{2} + 0.999 \times {0.02}^{2}} \\ +&= 0.7103718. +\end{align*} +$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.4.md",".md","3322","113","**Solution.** + +Download the mitochondrial genome sequences for human (D38112) and +orangutan (NC_001646), and extract the 12s rRNA gene. Align them using +your favorite software. However, I am lazy enough to take the +precalculated values provided in Section 5.3.2 of (Yang, 2006). +Accordingly, the number of aligned sites $n$ = 948, the number of +different sites $x$ = 90. Consider a uniform proposal and a flat prior +of $\theta$. + +\(a\) According to Eq. (5.32) of (Yang, 2006), the new state +$\theta^{*}$ is drawn from a uniform distribution +$U\left( \theta - \frac{w}{2},\theta + \frac{w}{2} \right)$. The +likelihood function is given as Eq. (1.42) of (Yang, 2006): + +$$L(\theta;x) = f(x|\theta) = \begin{pmatrix} +n \\ +x \\ +\end{pmatrix}\left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4}{3}d} \right)^{x}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4}{3}d} \right)^{n - x}.$$ + +Because a flat prior of $\theta$ is adopted (see above), the acceptance +ratio can be simplified as + +$$\alpha = \min\left( 1,\frac{L\left( \theta^{*};x \right)}{L(\theta;x)} \right).$$ + +The MCMC sampling may be performed using the following R code +(*5.4a.R*). + +```R +#! /usr/bin/env Rscript + + +######################################## +# assume branch_length ~ Uniform(0,10) +lnprior_unif <- function(d){ + log(dunif(d,0,10)) +} + +lnl_JC69 <- function(d, n, x){ + x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) +} + +do_mcmc <- function(w, nsample, n, x){ + ds <- numeric(nsample) + accepts <- numeric(nsample) + d <- 0.8 + + # log-prior + lnprior <- lnprior_unif(d) + + # log-likelihood + lnl <- lnl_JC69(d, n, x) + + # log-posterior + lnposterior <- lnprior + lnl + + for(i in 2:nsample){ + d_new <- runif(1, d-w/2, d+w/2) + d_new <- ifelse(d_new>=0, d_new, d) + + lnposterior_new <- lnprior_unif(d_new) + lnl_JC69(d_new, n, x) + alpha <- min(1, exp(lnposterior_new-lnposterior)) + if(runif(1) < alpha){ + d <- d_new + lnposterior <- lnposterior_new + accepts[i] <- 1 + } + ds[i] <- d + } + return(list(ds=ds, accepts=accepts)) +} + + +######################################## +x <- 90; n<-948 +w <- 0.3; nsample <- 10000 + +for(w in seq(0.02,0.5,0.04)){ + res <- do_mcmc(w=w, nsample=nsample, n=n, x=x) + ds <- res$ds; accepts <- res$accepts + burnin <- round(nsample/2) + ds_after_burnin <- ds[burnin:nsample] + accepts_after_burnin <- accepts[burnin:nsample] + acceptance_ratio <- length(accepts_after_burnin[accepts_after_burnin==1])/length(accepts_after_burnin) + cat(w, mean(ds_after_burnin), acceptance_ratio, '\n', sep=""\t"") +} +``` + +The result is displayed as follows. +

+ +

+ +\(b\) The proportional shrinking and expanding algorithm is introduced +in Section 5.4.4 in (Yang, 2006). The proposal ratio is + +

+ +

+ +Accordingly, the acceptance ratio is calculated as + +$$\alpha = \min{\left( 1,\frac{L\left( \theta^{*};x \right)}{L(\theta;x)} \times c \right),}$$ + +where $c = e^{\epsilon(r - 0.5)}$ and $r\sim U(0,1)$. + +For simplicity, I do not show the R code here but interested readers can use +the script *5.4b.R* available along with the solutions manual to generate the result highly similar to the +following. +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.6.md",".md","1649","40","**Solution.** + +Refer to Section 1.4.2 of (Yang, 2006) to get the number of transitions +$n_{S} = 84$, and the number of transversions $n_{V} = 6$. The +log-likelihood function is given by Eq. (1.48) in (Yang, 2006) as + +$$\mathcal{l}\left( d,k \middle| n_{S},n_{V} \right) = \left( n - n_{S} - n_{V} \right)\log\left( \frac{p_{0}}{4} \right) + n_{S}\log\left( \frac{p_{1}}{4} \right) + n_{V}\log\left( \frac{p_{2}}{4} \right),$$ + +where + +$$p_{0}(t) = \frac{1}{4} + \frac{1}{4}e^{- \frac{4d}{\kappa + 2}} + \frac{1}{2}e^{- \frac{2d(\kappa + 1)}{\kappa + 2}},$$ + +$$p_{1}(t) = \frac{1}{4} + \frac{1}{4}e^{- \frac{4d}{\kappa + 2}} - \frac{1}{2}e^{- \frac{2d(\kappa + 1)}{\kappa + 2}},$$ + +$$p_{2}(t) = \frac{1}{4} - \frac{1}{4}e^{- \frac{4d}{(\kappa + 2)}},$$ + +according to Eq. (1.10) of (Yang, 2006). + +I fix the width of the sliding-window proposal for $k$ to be 10. +Interestingly, in a paper published 11 years after (Yang, 2006) was +published, the authors performed very detailed MCMC analysis of +estimates of the parameters on the same data set (Nascimento et al., +2017), but note that they used different priors for $d$ and $k$ from +those used in the present example. The MCMC sampling may be performed +using the script *5.6.R*. My result is summarized as follows. + +

+ +

+ +To compare with the MLE, use the following R code which uses the +function *optim* to obtain the MLE. The result is +$\widehat{k} = 0.1045327$, $\widehat{d}\ = 30.8064718$. You can also +refer to the estimates given in Section 1.4.2 of (Yang, 2006). + +```R +> mle <- optim(par=c(0.13,2), lnl_K80, n=948, ns=84, nv=6) +> print(mle$par) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/5.5.md",".md","336","8","**Solution.** + +Run the R script 5.5.R to get the following results. Note that the same window size $w$ is used for both rate and time. Another script associated with this exercise, which is a slightly modefied script originally contributed by Mario dos Reis, is also provided. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/scripts/5.4a.R",".R","1463","60","#! /usr/bin/env Rscript + + +######################################## +# assume branch_length ~ Uniform(0,10) +lnprior_unif <- function(d){ + log(dunif(d,0,10)) +} + +lnl_JC69 <- function(d, n, x){ + x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) +} + +do_mcmc <- function(w, nsample, n, x){ + ds <- numeric(nsample) + accepts <- numeric(nsample) + d <- 0.8 + + # log-prior + lnprior <- lnprior_unif(d) + + # log-likelihood + lnl <- lnl_JC69(d, n, x) + + # log-posterior + lnposterior <- lnprior + lnl + + for(i in 2:nsample){ + d_new <- runif(1, d-w/2, d+w/2) + d_new <- ifelse(d_new>=0, d_new, d) + + lnposterior_new <- lnprior_unif(d_new) + lnl_JC69(d_new, n, x) + alpha <- min(1, exp(lnposterior_new-lnposterior)) + if(runif(1) < alpha){ + d <- d_new + lnposterior <- lnposterior_new + accepts[i] <- 1 + } + ds[i] <- d + } + return(list(ds=ds, accepts=accepts)) +} + + +######################################## +x <- 90; n<-948 +w <- 0.3; nsample <- 10000 + +for(w in seq(0.02,0.5,0.04)){ + res <- do_mcmc(w=w, nsample=nsample, n=n, x=x) + ds <- res$ds; accepts <- res$accepts + burnin <- round(nsample/2) + ds_after_burnin <- ds[burnin:nsample] + accepts_after_burnin <- accepts[burnin:nsample] + acceptance_ratio <- length(accepts_after_burnin[accepts_after_burnin==1])/length(accepts_after_burnin) + cat(w, mean(ds_after_burnin), acceptance_ratio, '\n', sep=""\t"") +} + + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/scripts/5.4b.R",".R","1252","47","#! /usr/bin/env Rscript + + +######################################## +lnl_JC69 <- function(d, n, x){ + x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) +} + +do_mcmc <- function(w, nsample, n, x){ + e <- w # epsilon + ds <- numeric(nsample) + accepts <- numeric(nsample) + d <- 0.8; lnl <- lnl_JC69(d, n, x) + for(i in 2:nsample){ + r <- runif(1,0,1) + c <- exp(e*(r-0.5)) + d_new <- c * d + d_new <- ifelse(d_new>=0, d_new, d) + lnl_new <- lnl_JC69(d_new, n, x) + alpha <- min(1, exp(lnl_new-lnl) * c) + if(runif(1) < alpha){ + d <- d_new + lnl <- lnl_new + accepts[i] <- 1 + } + ds[i] <- d + } + return(list(ds=ds, accepts=accepts)) +} + + +######################################## +x <- 90; n<-948 +w <- 0.3; nsample <- 100000 + +for(w in seq(0.1,2,0.1)){ + res <- do_mcmc(w=w, nsample=nsample, n=n, x=x) + ds <- res$ds; accepts <- res$accepts + burnin <- round(nsample/2) + ds_after_burnin <- ds[burnin:nsample] + accepts_after_burnin <- accepts[burnin:nsample] + acceptance_ratio <- length(accepts_after_burnin[accepts_after_burnin==1])/length(accepts_after_burnin) + cat(w, mean(ds_after_burnin), acceptance_ratio, '\n', sep=""\t"") +} + + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/scripts/5.6.R",".R","2628","86","#! /usr/bin/env Rscript + + +######################################## +lnl_JC69 <- function(d, n, n_diff){ + n_diff*log(3/4-3/4*exp(-4/3*d)) + (n-n_diff)*log(1/4+3/4*exp(-4/3*d)) +} + + +lnl_K80 <- function(param, n, ns, nv){ + # f(d) = Exp(d|1/0.2); f(k) = Exp(k|1/5) + d <- param[1]; k <- param[2] + p0 <- 1/4+1/4*exp(-4*d/(k+2))+1/2*exp(-2*d*(k+1)/(k+2)) + p1 <- 1/4+1/4*exp(-4*d/(k+2))-1/2*exp(-2*d*(k+1)/(k+2)) + p2 <- 1/4-1/4*exp(-4*d/(k+2)) + log_prior <- log(dexp(d,1/0.2)) + log(dexp(k,1/5)) + lnl <- (n-ns-nv)*log(p0/4) + ns*log(p1/4) + nv*log(p2/4) + return(log_prior + lnl) +} + + +do_mcmc <- function(w, nsample, n, ns, nv){ + w.k <- 10 # Mario used w.k=180 but note it's for a diff prior (https://github.com/thednainus/Bayesian_tutorial) + posteriors <- matrix(0, nsample, 2) + accepts <- matrix(0, nsample, 2) + d <- 0.05; k <- 5 + param_new <- c(d, k) + lnl <- lnl_K80(param_new, n, ns, nv) + for(i in 2:nsample){ + d_new <- runif(1, d-w/2, d+w/2) + d_new <- ifelse(d_new>=0, d_new, d) + param_new[1] <- d_new + lnl_new <- lnl_K80(param_new, n, ns, nv) + alpha <- min(1, exp(lnl_new-lnl)) + if(runif(1) < alpha){ + d <- d_new + lnl <- lnl_new + accepts[i,1] <- 1 + } + + k_new <- runif(1, k-w.k/2, k+w.k/2) + k_new <- ifelse(k_new>=0, k_new, k) + param_new[2] <- k_new + lnl_new <- lnl_K80(param_new, n, ns, nv) + alpha <- min(1, exp(lnl_new-lnl)) + #cat(k, k_new, alpha, ""\n"") + if(runif(1) < alpha){ + k <- k_new + lnl <- lnl_new + accepts[i,2] <- 1 + } + + posteriors[i-1,] <- c(d,k) + } + return(list(posteriors=posteriors, accepts=accepts)) +} + + +######################################## +ns <- 84; nv <- 6; n_diff <- ns+nv; n<-948 +w <- NULL; nsample <- 10000; every <- 1 + +calculate_acceptance_ratio <- function(v){ + length(v[v==1])/length(v) +} + +for(w in seq(0.02,0.5,0.04)){ + res <- do_mcmc(w=w, nsample=nsample, n=n, ns=ns, nv=nv) + posteriors <- res$posteriors; accepts <- res$accepts + burnin <- round(nsample/2) + posteriors_after_burnin <- posteriors[seq(burnin,nsample,every), ] + + accepts_after_burnin <- accepts[seq(burnin,nsample,every),] + acceptance_ratio <- apply(accepts_after_burnin, 2, calculate_acceptance_ratio) + + cat(w, apply(posteriors_after_burnin,2,mean), acceptance_ratio, '\n', sep=""\t"") +pdf(""trace.pdf"") +plot(posteriors_after_burnin[,2], ty = ""l"") +lines(posteriors_after_burnin[,2], col=""red"") +#plot(seq(1:length(posteriors_after_burnin[,2])), posteriors_after_burnin[,2]) +dev.off() +} + + + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/scripts/5.5.R",".R","2196","66","#! /usr/bin/env Rscript + + +######################################## +lnl_JC69 <- function(mu, t, n, x){ + d <- 2 * mu * t + lnprior <- log(dexp(mu, 1)) + log(dexp(t,1/0.15)) + #lnl <- x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) + lnl <- x*log(3/4-3/4*exp(-4*d/3)) + (n-x)*log(1/4+3/4*exp(-4*d/3)) + return(lnprior+lnl) +} + +do_mcmc <- function(w, nsample, n, x){ + mus <- ts <- numeric(nsample) + accepts.mu <- accepts.t <- numeric(nsample) + mu <- 0.5; t<-1; lnl <- lnl_JC69(mu, t, n, x) + for(i in 2:nsample){ + mu_new <- runif(1, mu-w/2, mu+w/2) + mu_new <- ifelse(mu_new>=0, mu_new, mu) + lnl_new <- lnl_JC69(mu_new, t, n, x) + alpha <- min(1, exp(lnl_new-lnl)) + if(runif(1) < alpha){ + mu <- mu_new + lnl <- lnl_new + accepts.mu[i] <- 1 + } + mus[i] <- mu + + t_new <- runif(1, t-w/2, t+w/2) + t_new <- ifelse(t_new>=0, t_new, t) + lnl_new <- lnl_JC69(mu, t_new, n, x) + alpha <- min(1, exp(lnl_new-lnl)) + if(runif(1) < alpha){ + t <- t_new + lnl <- lnl_new + accepts.t[i] <- 1 + } + ts[i] <- t + } + return(list(mus=mus, ts=ts, accepts.mu=accepts.mu, accepts.t=accepts.t)) +} + + +######################################## +x <- 90; n<-948 +w <- 0.3; nsample <- 1e6 + +for(w in seq(0.1,1,0.1)){ + if(w == 0.1){ + cat(""step_(w)"", ""rate_(mu)"", ""time_(T)"", ""acc_ratio_of_mu"", ""acc_ratio_of_T"", ""\n"", sep = ""\t"") + } + + res <- do_mcmc(w=w, nsample=nsample, n=n, x=x) + mus <- res$mus; ts<-res$ts ; accepts.mu <- res$accepts.mu; accepts.t <- res$accepts.t + burnin <- round(nsample/2) + mus_after_burnin <- mus[burnin:nsample] + ts_after_burnin <- ts[burnin:nsample] + + accepts_mu_after_burnin <- accepts.mu[burnin:nsample]; accepts_t_after_burnin <- accepts.t[burnin:nsample] + acceptance_ratio <- c( + length(accepts_mu_after_burnin[accepts_mu_after_burnin==1])/length(accepts_mu_after_burnin), + length(accepts_t_after_burnin[accepts_t_after_burnin==1])/length(accepts_t_after_burnin) + ) + cat(w, mean(mus_after_burnin), mean(ts_after_burnin), acceptance_ratio, '\n', sep=""\t"") +} +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C5 Bayesian methods/scripts/5.5-Mario.mcmc.JCrt.R",".R","2988","75","#! /usr/bin/env Rscript + +# created by Mario dos Reis (https://www.qmul.ac.uk/sbbs/staff/mariodosreisbarros.html) +# modified by Sishuo Wang as to the window sizes + +# Solution to EXERCISE 7: +lnL <- function(d, x, n) x*log(3/4 - 3*exp(-4*d/3)/4) + (n - x) *log(1/4 + 3*exp(-4*d/3)/4) +#r.lnprior <- function(r, mu=0.10/22.45) -r/mu # -log(mu) term deleted +r.lnprior <- function(r) log(dexp(r,1)) +#t.lnprior <- function(t, mu=22.45, sd=5.6) -((t-mu)/sd)^2 # constant deleted +t.lnprior <- function(t) log(dexp(t,1/0.15)) +lnL.rt <- function(r, t, x, n) lnL(d=2*r*t, x=x, n=n) +rt.lnpost <- function(r, t, x=90, n=948) r.lnprior(r) + t.lnprior(t) + lnL.rt(r, t, x, n) + + +rt.mcmcf <- function(init.r, init.t, N, w.r, w.t) { + # init.r and init.t are the initial states + # N is the number of 'generations' the algorithm is run for. + # w.r and w.t are the step sizes of the proposal densities. + r <- t <- numeric(N+1) + r[1] <- init.r; t[1] <- init.t + rnow <- init.r; tnow <- init.t + ap.r <- ap.t <- 0 # acceptance proportions + for (i in 1:N) { + # Propose, and accept or reject new r: + rnew <- rnow + runif(1, -w.r/2, w.r/2) + if(rnew < 0) rnew <- -rnew; + lnalpha <- rt.lnpost(rnew, tnow, x=90, n=948) - rt.lnpost(rnow, tnow, x=90, n=948) + # if ru < alpha accept proposal: + if (lnalpha>0 || runif(1, 0, 1) < exp(lnalpha)) { rnow <- rnew; ap.r <- ap.r + 1 } + # else reject it, so that rnow = rnow. + + # Propose, and accept or reject new t: + tnew <- tnow + runif(1, -w.t/2, w.t/2) + if(tnew < 0) tnew <- -tnew; + lnalpha <- rt.lnpost(rnow, tnew, x=90, n=948) - rt.lnpost(rnow, tnow, x=90, n=948) + if (lnalpha > 0 || runif(1, 0, 1) < exp(lnalpha)) { tnow <- tnew; ap.t <- ap.t + 1 } + # else reject it so that tnow = tnow. + r[i+1] <- rnow; t[i+1] <- tnow; # take the sample + } + # print out the acceptance proportions + print(c(ap.r/N, ap.t/N)) + return (list(r=r, t=t)) # return vector of d's visited during MCMC +} + +# Test the chain: +#rt.1 <- rt.mcmcf(0.01, 40, 1e2, 0.001, 10) +#plot(rt.1$r, rt.1$t, ty='b', pch=19, cex=.5, xlab=""rate"", ylab=""time"") + +# Do a longer run and finetune: +#rt.2 <- rt.mcmcf(0.01, 40, 1e4, 0.001, 10) +N <- 1e6 +for(w in seq(0.1,1,0.2)){ + rt.2 <- rt.mcmcf(1, 1, N, w, w) + rt.2 <- lapply(rt.2, function(x){ x[round(length(x)/2):N] } ) + cat(w, sapply(rt.2, mean), ""\n"") +} +# If the acceptance proportion is high, step is too small and needs to be increased +# On the other hand, if acceptance proportion is low, decrease step size +# What step sizes above lead to 30% and 30% acceptance proportions? + +# Look at the trace files: +par(mfrow=c(2,1)) +plot(rt.2$r, ty='l', main=""rate"") +plot(rt.2$t, ty='l', main=""time"") + +require(MASS) # This package has additional statistical functions +zz <- kde2d(rt.2$r, rt.2$t) +par(mfrow=c(1,1)) +image(zz, xlab=""rate"", ylab=""time"") +contour(zz, add=TRUE) + +# Add a first few points to see MCMC progress: +lines(rt.2$r[1:200], rt.2$t[1:200], ty='b', pch=19, cex=.5, col=""blue"") +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C1 Models of nucleotide substitution/1.1.md",".md","2785","60","**Solution.** + +a\) First calculate the right-hand side of the equation. + +For $i = j$, + +$$ +\begin{align*} +p_{ij}\left(t_{1}\right)p_{ji}\left(t_{2}\right) &= \left( \frac{1}{4}+\frac{3}{4}e^{-4\lambda t_{1}} \right)\left( \frac{1}{4} + \frac{3}{4}e^{-4\lambda t_{2}} \right) \\ +&= \frac{1}{16}\left(1+3e^{-4\lambda t_{1}} + 3e^{-4\lambda t_{2}} + 9e^{-4\lambda\left( t_{1} + t_{2} \right)} \right). +\end{align*} +$$ + +For $i \neq j$, + +$$\begin{align*} +p_{ij}\left( t_{1} \right)p_{ji}\left( t_{2} \right) &= \left( \frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{1}} \right)\left( \frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{2}} \right) \\ +&= \frac{1}{16}\left( 1 - e^{-4\lambda t_{1}} - e^{-4\lambda t_{2}} + e^{-4\lambda\left( t_{1} + t_{2} \right)} \right). +\end{align*}$$ + +Hence, + +$$ +p_{ij} \left( t_{1} \right) p_{ji}\left( t_{2} \right) = +\begin{cases} +\frac{1}{16}\left( 1 + 3e^{- 4\lambda t_{1}} + 3e^{- 4\lambda t_{2}} + 9e^{- 4\lambda\left( t_{1} + t_{2} \right)} \right), & i = j \\ +\frac{1}{16}\left( 1 - e^{- 4\lambda t_{1}} - e^{- 4\lambda t_{2}} + e^{- 4\lambda\left( t_{1} + t_{2} \right)} \right), & i \neq j +\end{cases} +$$ + +It follows that + +$$ +\begin{align*} +&p_{TT}\left( t_{1} \right)p_{TT}\left( t_{2} \right) + p_{TC}\left( t_{1} \right)p_{CT}\left( t_{2} \right) + p_{TA}\left( t_{1} \right)p_{AT}\left( t_{2} \right) + p_{TG}\left( t_{1} \right)p_{GT}\left( t_{2} \right) \\ +&= \frac{1}{16}\left( 1 + 3e^{- 4\lambda t_{1}} + 3e^{- 4\lambda t_{2}} + 9e^{- 4\lambda\left( t_{1} + t_{2} \right)} \right) \\ +&\quad + 3 \times \frac{1}{16}\left( 1 - e^{- 4\lambda t_{1}} - e^{- 4\lambda t_{2}} + e^{- 4\lambda\left( t_{1} + t_{2} \right)} \right) \\ +&= \frac{1}{4} + \frac{3}{4}e^{- 4\lambda\left( t_{1} + t_{2} \right)} \\ +&= p_{TT}\left( t_{1} + t_{2} \right). +\end{align*} +$$ + +b) It follows that + +$$ +\begin{align*} +&p_{TT}(t_{1})p_{TC}(t_{2}) + p_{TC}(t_{1})p_{CC}(t_{2}) + p_{TA}(t_{1})p_{AT}(t_{2}) + p_{TG}(t_{1})p_{GT}(t_{2}) \\ +&= \left(\frac{1}{4} + \frac{3}{4}e^{-4\lambda t_{1}}\right)\left(\frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{2}}\right) \\ +&\quad + \left(\frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{1}}\right)\left(\frac{1}{4} + \frac{3}{4}e^{-4\lambda t_{2}}\right) \\ +&\quad + 2 \times \left(\frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{1}}\right)\left(\frac{1}{4} - \frac{1}{4}e^{-4\lambda t_{2}}\right) \\ +&= \frac{1}{16}\left[ \left(1 - e^{-4\lambda t_{2}} + 3e^{-4\lambda t_{1}} - 3e^{-4\lambda(t_{1} + t_{2})}\right) \right. \\ +&\quad + \left(1 - e^{-4\lambda t_{1}} + 3e^{-4\lambda t_{2}} - 3e^{-4\lambda(t_{1} + t_{2})}\right) \\ +&\quad + \left. 2 \times \left(1 - e^{-4\lambda t_{1}} - e^{-4\lambda t_{2}} + e^{-4\lambda(t_{1} + t_{2})}\right) \right] \\ +&= \frac{1}{4} - \frac{1}{4}e^{-4\lambda(t_{1} + t_{2})} \\ +&= p_{TC}(t_{1} + t_{2}). +\end{align*} +$$ + + +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C1 Models of nucleotide substitution/1.3.md",".md","2441","115","**Solution.** + +First, calculate the eigenvalues and eigenvectors of *Q*. + +$$ +\begin{align*} +\left| \begin{matrix} +-u - \lambda & u \\ +v & -v - \lambda \\ +\end{matrix} \right| &= 0 +\end{align*} +$$ + +By solving the following equation + +$$ +\begin{align*} +\lambda^{2} + (u + v)\lambda &= 0 +\end{align*} +$$ + +we get the eigenvalues and their corresponding eigenvectors: + +$$ +\begin{align*} +\lambda_{1} &= 0, \quad \lambda_{2} = -u - v, \\ +v_{1} &= \begin{bmatrix} +1 \\ +1 \\ +\end{bmatrix}, \quad v_{2} = \begin{bmatrix} +-u \\ +v \\ +\end{bmatrix}. +\end{align*} +$$ + +Hence, + +$$ +\begin{align*} +P(t) &= e^{Qt} \\ +&= \begin{bmatrix} +1 & -u \\ +1 & v \\ +\end{bmatrix}e^{\begin{bmatrix} +0 & 0 \\ +0 & -(u + v)t \\ +\end{bmatrix}}\begin{bmatrix} +\frac{v}{u + v} & \frac{u}{u + v} \\ +-\frac{1}{u + v} & \frac{1}{u + v} \\ +\end{bmatrix} \\ +&= \frac{1}{u + v}\begin{bmatrix} +1 & -u \\ +1 & v \\ +\end{bmatrix}\begin{bmatrix} +1 & 0 \\ +0 & e^{-(u + v)t} \\ +\end{bmatrix}\begin{bmatrix} +v & u \\ +-1 & 1 \\ +\end{bmatrix} \\ +&= \frac{1}{u + v}\begin{bmatrix} +v + ue^{-(u + v)t} & u - ue^{-(u + v)t} \\ +v - ve^{-(u + v)t} & u + ve^{-(u + v)t} +\end{bmatrix} +\end{align*} +$$ + +As to the limiting distribution $\pi^{(t)}$, suppose that the system is +in state 1 at time $n = 0$ with probability ${\pi_{1}}^{(0)}$ and in +state 2 at time $n = 0$ with probability ${\pi_{2}}^{(0)}$, such that +$\pi^{(0)} = ({\pi_{1}}^{(0)},{\pi_{2}}^{(0)})$ and +${\pi_{1}}^{(0)} + {\pi_{2}}^{(0)} = 1$. It follows that + +$$ +\begin{align*} +\pi^{(t)} &= \pi^{(0)}P(t) \\ +&= \frac{1}{u + v}\begin{bmatrix} +{\pi_{1}}^{(0)} & {\pi_{2}}^{(0)} +\end{bmatrix} \begin{bmatrix} +v + ue^{-(u + v)t} & u - ue^{-(u + v)t} \\ +v - ve^{-(u + v)t} & u + ve^{-(u + v)t} +\end{bmatrix} \\ +&= \frac{1}{u + v}\begin{bmatrix} +{\pi_{1}}^{(0)}(v + ue^{-(u + v)t}) + {\pi_{2}}^{(0)}(v + ue^{-(u + v)t}) \\ +{\pi_{1}}^{(0)}(u - ue^{-(u + v)t}) + {\pi_{2}}^{(0)}(u + ve^{-(u + v)t}) +\end{bmatrix}^{T}. +\end{align*} +$$ + +By letting $t \rightarrow \infty$, +$\lim_{t \rightarrow \infty}e^{-(u + v)t} = 0$. Hence, the limiting +distribution $\pi$ is given by + +$$ +\begin{align*} +\pi &= \lim_{t \rightarrow \infty} \pi^{(t)} = \begin{bmatrix} +\frac{v}{u + v} & \frac{u}{u + v} +\end{bmatrix}. +\end{align*} +$$ + +According to the text, in case $u=v=1$, we have + +$$ +\begin{align*} +P(t) &= \frac{1}{2} \begin{bmatrix} +1 + e^{-2t} & 1 - e^{-2t} \\ +1 - e^{-2t} & 1 + e^{-2t} +\end{bmatrix}, +\end{align*} +$$ + +which is the binary equivalent of JC69. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C1 Models of nucleotide substitution/1.2.md",".md","3210","143","**Solution.** + +The rate matrix of the JC69 substitution model is defined as + +$$ +Q = \begin{bmatrix} +-3\theta & \theta & \theta & \theta \\ +\theta & -3\theta & \theta & \theta \\ +\theta & \theta & -3\theta & \theta \\ +\theta & \theta & \theta & -3\theta \\ +\end{bmatrix}. +$$ + +Note that we substitute 𝜃 for 𝜆 in the original formula. To obtain the eigenvalues and eigenvectors, let the determinant equal to zero. Denote the eigenvalue as 𝜆. The determinant of 𝑄 is given by + +

+ +

+ +Setting the above to zero, it is easy to see the eigenvalues of *𝑄′* are $\lambda_{1}=0$, $\lambda_{2} = \lambda_{3} = \lambda_{4} = - 4\theta$. The eigenvectors of $\lambda_{2},\lambda_{3},\lambda_{4}$ can be obtained by solving the following. + +$$\begin{bmatrix} +1 & 1 & 1 & 1 \\ +1 & 1 & 1 & 1 \\ +1 & 1 & 1 & 1 \\ +1 & 1 & 1 & 1 \\ +\end{bmatrix}\begin{bmatrix} +a \\ +b \\ +c \\ +d \\ +\end{bmatrix} = \begin{bmatrix} +0 \\ +0 \\ +0 \\ +0 \\ +\end{bmatrix} \rightarrow a + b + c + d = 0$$ + + + +The eigenvectors of +$\lambda_{2} = \lambda_{3} = \lambda_{4} = - 4\theta$ are + +$$ +\begin{bmatrix} +a \\ +b \\ +c \\ +d \\ +\end{bmatrix} = \begin{bmatrix} +a \\ +b \\ +c \\ +-a-b-c \\ +\end{bmatrix} = a\begin{bmatrix} +1 \\ +0 \\ +0 \\ +-1 \\ +\end{bmatrix} + b\begin{bmatrix} +0 \\ +1 \\ +0 \\ +-1 \\ +\end{bmatrix} + c\begin{bmatrix} +0 \\ +0 \\ +1 \\ +-1 \\ +\end{bmatrix}. +$$ + +Taking $a = 1,b = c = 0$ gives $(1,0,0, - 1)$. + +Taking $b = 1,a = c = 0$ gives $(0,1,0, - 1).$ + +Taking $c = 1,a = b = 0$ gives $(0,0,1, - 1)$. + +Similarly, the eigenvector for $\lambda_{1} = 0$ is $(1,1,1,1)$. + +Hence, + +$$Q = U\Lambda U^{- 1},$$ + +where + +$$U = \begin{bmatrix} +1 & 1 & 0 & 0 \\ +1 & 0 & 1 & 0 \\ +1 & 0 & 0 & 1 \\ +1 & - 1 & - 1 & - 1 \\ +\end{bmatrix},U^{-1} = \frac{1}{4}\begin{bmatrix} +1 & 1 & 1 & 1 \\ +3 & -1 & -1 & -1 \\ +-1 & 3 & -1 & -1 \\ + -1 & -1 & -3 & -1 \\ +\end{bmatrix},\Lambda = \begin{bmatrix} +0 & \ & \ & \ \\ +\ & - 4\theta & \ & \ \\ +\ & \ & - 4\theta & \ \\ +\ & \ & \ & - 4\theta \\ +\end{bmatrix}.$$ + +So + +$$ +e^{Qt} = \begin{bmatrix} +1 & 1 & 0 & 0 \\ +1 & 0 & 1 & 0 \\ +1 & 0 & 0 & 1 \\ +1 & -1 & -1 & -1 \\ +\end{bmatrix} +\begin{bmatrix} +1 & \ \ \ \ & \ \ \ \ & \ \ \ \ \\ +\ \ \ \ & e^{-4\theta t} & \ \ \ \ & \ \ \ \ \\ +\ \ \ \ & \ \ \ \ & e^{-4\theta t} & \ \ \ \ \\ +\ \ \ \ & \ \ \ \ & \ \ \ \ & e^{-4\theta t} \\ +\end{bmatrix} +\frac{1}{4} +\begin{bmatrix} +1 & 1 & 1 & 1 \\ +3e^{-4\theta t} & -e^{-4\theta t} & -e^{-4\theta t} & -e^{-4\theta t} \\ +-e^{-4\theta t} & 3e^{-4\theta t} & -e^{-4\theta t} & -e^{-4\theta t} \\ +-e^{-4\theta t} & -e^{-4\theta t} & 3e^{-4\theta t} & -e^{-4\theta t} \\ +\end{bmatrix} += \frac{1}{4}\begin{bmatrix} +1 + 3e^{-4\theta t} & 1 - e^{-4\theta t} & 1 - e^{-4\theta t} & 1 - e^{-4\theta t} \\ +1 - e^{-4\theta t} & 1 + 3e^{-4\theta t} & 1 - e^{-4\theta t} & 1 - e^{-4\theta t} \\ +1 - e^{-4\theta t} & 1 - e^{-4\theta t} & 1 + 3e^{-4\theta t} & 1 - e^{-4\theta t} \\ +1 - e^{-4\theta t} & 1 - e^{-4\theta t} & 1 - e^{-4\theta t} & 1 + 3e^{-4\theta t} \\ +\end{bmatrix}. +$$ + +Substituting $\lambda$ for $\theta$, we obtain + +$$ +p_{ij}(t) = +\begin{cases} +\frac{1}{4} + \frac{3}{4}e^{-4\lambda t}, & i = j \\ +\frac{1}{4} - \frac{1}{4}e^{-4\lambda t}, & i \neq j +\end{cases} +$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C1 Models of nucleotide substitution/1.4.md",".md","2227","40","**Solution.** + +According to Eq. (1.42) in (Yang, 2006), we have + +$$ +\begin{align*} +L(d;x) &= C\left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4d}{3}} \right)^{x}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4d}{3}} \right)^{n - x} \\ +&= C \times 12^{x} \times 4^{n - x} \times \left( \frac{1}{12}\left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4d}{3}} \right) \right)^{x}\left( \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4d}{3}} \right) \right)^{n - x} \\ +&= 3^{x}4^{n}C\left( \frac{1}{16} - \frac{1}{16}e^{- \frac{4d}{3}} \right)^{x}\left( \frac{1}{16} + \frac{3}{16}e^{- \frac{4d}{3}} \right)^{n - x} +\end{align*} +$$ + +The answer to the second question can be easily seen from the above. Alternatively, we can for Eq. (1.42) of (Yang, 2006), set the formula + +$$ +\frac{d\mathcal{l}}{d(d)} = \left[ \log\left( \left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4d}{3}} \right)^{x}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4d}{3}} \right)^{n - x} \right) \right]' = 0. +$$ + +Solving the above equation, we have + +$$ +\begin{align*} +&\left[ \log\left( \left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4d}{3}} \right)^{x}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4d}{3}} \right)^{n - x} \right) \right]' = 0 \\ +&- \frac{4d}{3}e^{- \frac{4d}{3}}\left( x\left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4d}{3}} \right)^{- 1} - (n - x)\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4d}{3}} \right)^{- 1} \right) = 0 \\ +&\frac{x}{4}\left( 1 + 3e^{- \frac{4d}{3}} \right) - \frac{(n - x)}{4}\left( 3 - 3e^{- \frac{4d}{3}} \right) = 0 \\ +&\widehat{d} = - \frac{3}{4}\log\left( 1 - \frac{4x}{3n} \right). +\end{align*} +$$ + +Similarly, for Eq. (1.43) in (Yang, 2006), we have + +$$ +\begin{align*} +&\left[ \log\left( \left( \frac{1}{16} - \frac{1}{16}e^{- \frac{4d}{3}} \right)^{x}\left( \frac{1}{16} + \frac{3}{16}e^{- \frac{4d}{3}} \right)^{n - x} \right) \right]' = 0 \\ +&- \frac{4d}{3}e^{- \frac{4d}{3}}\left( \left( \frac{1}{16} - \frac{1}{16}e^{- \frac{4d}{3}} \right)^{- 1} + (n - x)\left( \frac{1}{16} + \frac{3}{16}e^{- \frac{4d}{3}} \right)^{- 1} \right) = 0 \\ +&\frac{x}{16}\left( 1 + 3e^{- \frac{4d}{3}} \right) - \frac{(n - x)}{16}\left( 3 - 3e^{- \frac{4d}{3}} \right) = 0 \\ +&\widehat{d} = - \frac{3}{4}\log\left( 1 - \frac{4x}{3n} \right). +\end{align*} +$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C1 Models of nucleotide substitution/1.5.md",".md","601","18","**Solution.** + +(a) Set + $\left( \log\left( f\left( x \middle| \theta \right) \right) \right)^{'}$ + to zero and solve the resulting equation: + +$$ +\begin{align*} +x(\log\theta)' + (n - x)(\log{(1 - \theta))}' &= 0 \\ +\frac{x}{\theta} - \frac{(n - x)}{1 - \theta} &= 0 \\ +\widehat{\theta} &= \frac{x}{n}. +\end{align*} +$$ + + + +(b) It is easy to see $\widehat{\theta} = \frac{x}{n}$ based on the result of (a) because the likelihood functions between (a) and (b) differ in only the constant term which contributes nothing to solving $\left( \log\left( f\left( x|\theta \right) \right) \right)^{'} = 0$. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C4 Maximum likelihood methods/4.1.md",".md","14729","540","**Solutions.** + +Three solutions are provided. The first employs induction, +the second one builds upon the first but adopts a linear algebra +perspective, and the final approach solves the problem +combinatorically. + +**Solution 1.** + +At the beginning, it is important to illustrate the different patterns +under model JC69 with the following example when there are three species +($s = 3$). In total, the $4^{3} = 64$ combinations of nucleotides +collapse into the following five patterns denoted as +$aaa,\ abb,\ bab,\ bba,\ abc$. + +111, where all three species have the same nucleotide: + +* TTT, CCC, AAA, GGG + +122, where the second and third species have the same nucleotide but the +first species has a different one. + +* CTT, ATT, GTT, TCC, ACC, GCC, TAA, CAA, GAA, TGG, CGG, AGG + +212, where the first and third species have the same nucleotide but the +* second species has a different one. + +221, where the first and second species have the same nucleotide but the +* third species has a different one. + +123, where all three species have different nucleotides. +* TCG, GCT, GAT, GTA, CTG, ACG, ACT, CGT, GTC, TGC, GAC, CGA, GCA, TGA, +AGC, TAC, ATG, ATC, CTA, TCA, AGT, CAT, TAG, CAG + +Now, denfine $f(s) = \frac{4^{s - 1} + 3 \times 2^{s - 1} + 2}{6}$, the +formula given in the problem. Denote $E_{s}$ as the set of the different +patterns for $s$ species, $A_{s}$ as the set where each element consists +of only a single state, $B_{s}$ as the set where each element consists +of exactly two states, $C_{s}$ as the set where each element consists of +three states, and $D_{s}$ as the set where each element consists of +three states. It is easy to see that $A_{s},B_{s},C_{s},D_{s}$ are +disjoint sets. Equivalently, + +$$E_{s} = A_{s} \cup B_{s} \cup C_{s} \cup D_{s},\ with\ A_{s} \cap B_{s} = A_{s} \cap C_{s} = \ldots = C_{s} \cap D_{s} = \varnothing.$$ + +In the above example, +$A_{3}=$ $`\{111\}`$, $B_{3} =$ $`\{122,212,221\}`$, $C_{3} =$ $`\{123\}`$. + +1\) It is easy to verify that the given formula holds for $s = 1,\ 2$. + +2\) When $s = 3$, there are the following five patterns $aaa$ (all the +same), $baa,\ aba,\ aab$ (one different from the others), and $abc$ (all +different), satisfying +$f(3) = \frac{4^{3 - 1} + 3 \times 2^{3 - 1} + 2}{6} = 5$. + +3\) When $s = 4$, there are 15 patterns (see below), well meeting the +given formula +$f(4) = \frac{4^{4 - 1} + 3 \times 2^{4 - 1} + 2}{6} = 15$. Further +divide the 15 patterns into three disjoint sets according to the number +of states that each element has as follows + +$$E_{4} = A_{4} \cup B_{4} \cup C_{4} \cup D_{4},$$ + +where $A_{4} = \{ 1111\}$, +$B_{4} = \{ 1111,\ 1121,\ 1211,\ 2111,\ 1122,\ 1212,\ 1221\}$, +$C_{4} = \{ 1123,\ 1213,\ 1231,\ 2311,\ 2131,\ 2113\}$, +$D_{4} = \{ 1234\}$. We also have the numbers of elements in the above +sets +$\left| A_{4} \right| = 1,\ \left| B_{4} \right| = 7,\ \left| C_{4} \right| = 7$. + +4\) As to $s = 5$, we have the following result based on the above +pattern for $s = 4$. + +Divide the set $E_{5}$ into four disjoint sets according to the number +of states of its elements as follows + +$$ +\begin{align*} +A_{5} &= \{11111\}, \\ +B_{5} &= \{2\} \times A_{4} \cup \{1,2\} \times B_{4}, \\ +C_{5} &= \{3\} \times B_{4} \cup \{1,2,3\} \times C_{4}, \\ +D_{5} &= \{4\} \times C_{4} \cup \{1,2,3,4\} \times D_{4}. +\end{align*} +$$ + +and apparently we have + +$$ +\begin{align*} +\left| A_{5} \right| &= |A_{4}| = 1, \\ +\left| B_{5} \right| &= 1 + 2 \times |B_{4}| = 15, \\ +\left| C_{5} \right| &= 1 \times |B_{4}| + 3 \times |C_{4}| = 28, \\ +\left| D_{5} \right| &= 1 \times \left| C_{4} \right| + 4 \times \left| D_{4} \right| = 7. +\end{align*} +$$ + +So + +$${|E}_{5}| = 1 + 15 + 28 + 7 = 51 = \frac{4^{5 - 1} + 3 \times 2^{5 - 1} + 2}{6} = f(5).$$ + +5\) As to $s = 6$, likewise, we can have the following result based on +the above patterns for $s = 5$. $ +$Again, divide set $E_{5}$ into three disjoint sets according to the +number of states of the elements as follows + +$$ +\begin{align*} +A_{6} &= \{ 111111 \}, \\ +B_{6} &= ( \{ 2 \} \times A_{5} ) \cup ( \{ 1,2 \} \times B_{5} ), \\ +C_{6} &= ( \{ 3 \} \times B_{5} ) \cup (\{ 1,2,3 \} \times C_{5}), \\ +D_{6} &= ( \{ 4 \} \times C_{5} ) \cup ( \{ 1,2,3,4 \} \times D_{5} ). +\end{align*} +$$ + + +and we have +$\left| A_{6} \right| = 1$, +$\left| B_{6} \right| = 1 + 2 \times |B_{5}| = 31$, +$\left| C_{6} \right| = 1 \times \left| B_{5} \right| + 3 \times \left| C_{5} \right| = 99,\left| D_{6} \right| = 1 \times \left| C_{5} \right| + 4 \times \left| D_{5} \right| = 56$. + +So + +$${|E}_{6}| = 1 + 31 + 99 + 56 = 187 = \frac{4^{6 - 1} + 3 \times 2^{6 - 1} + 2}{6} = f(6).$$ + +You of course can do similar stuff for $s = 7,8,\ldots$, but at this +point, it may be clear enough to see the following + +$$ +\begin{align*} +A_{s} &= \{ 1 \} \times \{ A_{s - 1} \}, \\ +B_{s} &= ( \{ 2 \} \times A_{s - 1} ) \cup ( \{ 1,2 \} \times B_{s - 1} ), \\ +C_{s} &= ( \{ 3 \} \times B_{s - 1} ) \cup ( \{ 1,2,3 \} \times C_{s - 1} ), \\ +D_{s} &= ( \{ 4 \} \times C_{s - 1} ) \cup ( \{ 1,2,3,4 \} \times D_{s - 1} ). +\end{align*} \tag{4.1} +$$ + + +Hence, the total number of patterns for any given $s$ can be calculated as + +$$ +\begin{align*} +f(s) = \left| E_{s} \right| +&= \left| A_{s} \right| + \left| B_{s} \right| + \left| C_{s} \right| + \left| D_{s} \right| \\ +&= \left| A_{s - 1} \right| \times 1 + \left( 1 + \left| B_{s - 1} \right| \times 2 \right) + \left( \left| B_{s - 1} \right| + \left| C_{s - 1} \right| \times 3 \right) + \left( \left| C_{s - 1} \right| + \left| D_{s - 1} \right| \times 4 \right) \\ +&= \left| A_{s - 1} \right| + \left| B_{s - 1} \right| \times 3 + \left( \left| C_{s - 1} \right| + |D_{s - 1}| \right) \times 4 +\end{align*} +$$ + +where $\left| A_{s} \right| \equiv 1$ for any $s$. + +As follows we apply induction. It is obvious from the above +that $f(s)$ holds for $s = 1,2,3,4$. Suppose +$f(s) = \frac{4^{s - 1} + 3 \times 2^{s - 1} + 2}{6}$ holds for all +values up to some $k$. Compare $f(k + 1)$ and $f(k)$, and by eliminating +the items containing $|C_{k - 1}|$ or $|D_{k - 1}|$, we can further show +that + +$$ +\begin{align*} +f(k + 1) &= 4 \times \left( |A_{k - 1}| + \left| B_{k - 1} \right| + \left| C_{k - 1} \right| + \left| D_{k - 1} \right| \right) - \left( \left| B_{k - 1} \right| \times 2 + 3 \right) \\ +&= 4f(k) - \left( 2\left| B_{k - 1} \right| + 3 \right). +\end{align*} +$$ + +Now our focus shifts to $|B_{k}|$.The elements of $|B_{k}|$ consist of +two sources. One is $\{\underset{k\ times}{\overset{aa\ldots a}{︸}}\}$, +which is a singleton set. The other is composed of those with exactly +two states from $B_{k - 1}$. Consider a few different values for $s$: + +$$ +{\left| B_{4} \right| = 7 \times 1 +}{\left| B_{5} \right| = 1 + 7 \times 2 +}{\left| B_{6} \right| = 1 + (1 + 7 \times 2) \times 2 +}{\left| B_{7} \right| = 1 + 2 \times \left( 1 + 2 \times (1 + 7 \times 2) \right).} +$$ + +It is not difficult to see the following + +$$\left| B_{k} \right| = 2^{k - 4} \times 7\ + \ 2^{k - 4} - 1,$$ + +thus + +$$\left| B_{k - 1} \right| = 2^{k - 5} \times 7 + 2^{k - 5} - 1,$$ + +where $s \geq 4$. Introducing the expression of $\left| B_{k - 1} \right|$ to $f(k + 1)$, we have + +$$ +\begin{align*} +f(k + 1) &= \frac{4^{k - 1} + 3 \times 2^{k - 1} + 2}{6} - 2 \times (2^{k - 5} \times 7 + 2^{k - 5} - 1) - 3 \\ +&= \frac{2 \times 4^{k - 1} + (6 \times 2^{k - 1} - 48 \times 2^{k - 5} + 1)}{3} \\ +&= \frac{4^{k} + 6 \times 2^{k} - 3 \times 2^{5} \times 2^{k - 5} + 2}{6}\ (both\ top\ and\ bottom \times 2) \\ +&= \frac{4^{k} + 3 \times 2^{k} + 2}{6} +\end{align*} +$$ + +**Solution 2.** + +Define +$a_{s} = \left| A_{s} \right|,\ b_{s} = \left| B_{s} \right|,\ c_{s} = \left| C_{s} \right|,\ d_{s} = \left| D_{s} \right|,\ e_{s} = |E_{s}|$. + +Starting from Eq. (4.1), we can re-write it in the form of matrix as + +$$\begin{bmatrix} +a_{s + 1} \\ +b_{s + 1} \\ +c_{s + 1} \\ +d_{s + 1} \\ +\end{bmatrix} = \begin{bmatrix} +1 & 0 & 0 & 0 \\ +1 & 2 & 0 & 0 \\ +0 & 1 & 3 & 0 \\ +0 & 0 & 1 & 4 \\ +\end{bmatrix}\begin{bmatrix} +a_{s} \\ +b_{s} \\ +c_{s} \\ +d_{s} \\ +\end{bmatrix}.$$ + +Further define + +$$W = \begin{bmatrix} +1 & 0 & 0 & 0 \\ +1 & 2 & 0 & 0 \\ +0 & 1 & 3 & 0 \\ +0 & 0 & 1 & 4 \\ +\end{bmatrix}.$$ + +Apparently, + +$$\left( a_{1},b_{1},c_{1},d_{1} \right)^{T} = (1,0,0,0)^{T}.$$ + +It follows that + +$$\begin{bmatrix} +a_{s + 1} \\ +b_{s + 1} \\ +c_{s + 1} \\ +d_{s + 1} \\ +\end{bmatrix} = W\begin{bmatrix} +a_{s} \\ +b_{s} \\ +c_{s} \\ +d_{s} \\ +\end{bmatrix} = W^{2}\begin{bmatrix} +a_{s - 1} \\ +b_{s - 1} \\ +c_{s - 1} \\ +d_{s - 1} \\ +\end{bmatrix} = \ldots = W^{s}\begin{bmatrix} +1 \\ +0 \\ +0 \\ +0 \\ +\end{bmatrix}.$$ + +We can do Eigenvalue decomposition for $W$ as follows + +$$W = P\Lambda P^{- 1}$$ + +where + +$$ +\Lambda = \text{diag}(1,2,3,4), +$$ + +$$ +P = \begin{bmatrix} +-6 & 0 & 0 & 0 \\ +6 & 2 & 0 & 0 \\ +-3 & -2 & -1 & 0 \\ +1 & 1 & 1 & 1 \\ +\end{bmatrix}, +$$ + +$$ +P^{-1} = \begin{bmatrix} +-1/6 & 0 & 0 & 0 \\ +1/2 & 1/2 & 0 & 0 \\ +-1/2 & -1 & -1 & 0 \\ +1/6 & 1/2 & 1 & 1 \\ +\end{bmatrix}. +$$ + +Hence, + +$$ +\begin{align*} +\begin{bmatrix} +a_{s + 1} \\ +b_{s + 1} \\ +c_{s + 1} \\ +d_{s + 1} \\ +\end{bmatrix} &= P\Lambda^{s}P^{-1}\begin{bmatrix} +1 \\ +0 \\ +0 \\ +0 \\ +\end{bmatrix} \\ +&= \begin{bmatrix} +-6 & 0 & 0 & 0 \\ +6 & 2 & 0 & 0 \\ +-3 & -2 & -1 & 0 \\ +1 & 1 & 1 & 1 \\ +\end{bmatrix}\begin{bmatrix} +1 & 0 & 0 & 0 \\ +0 & 2^{s} & 0 & 0 \\ +0 & 0 & 3^{s} & 0 \\ +0 & 0 & 0 & 4^{s} \\ +\end{bmatrix}\begin{bmatrix} +-1/6 & 0 & 0 & 0 \\ +1/2 & 1/2 & 0 & 0 \\ +-1/2 & -1 & -1 & 0 \\ +1/6 & 1/2 & 1 & 1 \\ +\end{bmatrix}\begin{bmatrix} +1 \\ +0 \\ +0 \\ +0 \\ +\end{bmatrix} \\ +&= \begin{bmatrix} +-6 & 0 & 0 & 0 \\ +6 & 2 & 0 & 0 \\ +-3 & -2 & -1 & 0 \\ +1 & 1 & 1 & 1 \\ +\end{bmatrix}\begin{bmatrix} +-1/6 & 0 & 0 & 0 \\ +2^{s - 1} & 2^{s} & 0 & 0 \\ +-3^{s}/2 & 0 & 3^{s} & 0 \\ +4^{s}/6 & 2^{s - 1} & -3^{s}/2 & 3^{s} \\ +\end{bmatrix} \\ +&= \begin{bmatrix} +1 \\ +2^{s} - 1 \\ +1/2 - 2^{s} + 3^{s}/2 \\ +2^{s - 1} - 3^{s}/2 + 4^{s}/6 - 1/6 \\ +\end{bmatrix}. +\end{align*} +$$ + +Thus + +$$ +\begin{align*} +f(s + 1) &= 1 + (2^{s} - 1) + (1/2 - 2^{s} + 3^{s}/2) + (2^{s - 1} - 3^{s}/2 + 4^{s}/6 - 1/6) \\ +&= (4^{s} + 3 \times 2^{s} + 2)/6. +\end{align*} +$$ + +So + +$$ +f(s) = (4^{s - 1} + 3 \times 2^{s - 1} + 2)/6. +$$ + + +**Solution 3.** + +This solution uses a combinatorics way. Let $X$ denote the set of all +sequences composed of $n$ types of nucleotides. Let $Y_{i}$ denote the +set of sequences where the $i$-th type of nucleotide does not appear. +Let $Z$ denote the set of sequences where all $m$ types of nucleotides +appear. Let us take an example. For cases where $m = 3$ and $n = 3$, we +have + +$$ +X = \\{ 111,112,113,\ldots,333 \\}, +$$ + +$$ +Y_{1} = \\{ 222,223,232,\ldots,333 \\}, +$$ + +$$ +Y_{2} = \\{ 111,113,131,\ldots,333 \\}, +$$ + +$$ +Y_{3} = \\{ 111,112,121,\ldots,222 \\}, +$$ + +$$ +Z = \\{ 123,132,213,231,312,321 \\}, +$$ + + +where $1,2,3$ denote the different states (note again that in this +example $m = 3$). It is easy to see + +$$|X| = 27,\left| Y_{1} \right| = \left| Y_{2} \right| = \left| Y_{3} \right| = 8,|Z| = 6.$$ + +In general, we have + +$$ +\begin{align*} +|X| &= m^{n}, \\ +|Z| &= |X| - |Y_{1} \cup Y_{2} \cup \ldots \cup Y_{m}|, \\ +|Y_{1} &= |Y_{2}| = \ldots = |Y_{m}| = (m - 1)^{n}, \\ +|Y_{1} \cap Y_{2}| &= |Y_{1} \cap Y_{3}| = \ldots = |Y_{m - 1} \cap Y_{m}| = (m - 2)^{n}, \\ +|Y_{1} \cap Y_{2} \cap Y_{3}| &= |Y_{1} \cap Y_{2} \cap Y_{4}| = \ldots = |Y_{m - 2} \cap Y_{m-1} \cap Y_{m}| = (m - 3)^{n}, \\ +&\vdots \\ +|Y_{1} \cap Y_{2} \cap \ldots \cap Y_{m}| &= (m - m)^{n} = 0. +\end{align*} +$$ + +Apply the inclusion-exclusion principle. It follows that + +$$ +\begin{align*} +\left| Y_{1} \cup Y_{2} \cup \ldots \cup Y_{m} \right| &= \sum_{i = 1}^{m}\left| Y_{i} \right| - \sum_{i = 1}^{m - 1}{\sum_{j = i + 1}^{m}\left| Y_{i} \cap Y_{j} \right|} + \sum_{i = 1}^{m - 2}{\sum_{j = i + 1}^{m - 1}{\sum_{k = j + 1}^{m}\left| Y_{i} \cap Y_{j} \cap Y_{k} \right|}} + \ldots + ( - 1)^{m}\left| Y_{1} \cap Y_{2} \cap \ldots \cap Y_{m} \right| \\ +&= \begin{pmatrix} +m \\ +1 \\ +\end{pmatrix}(m - 1)^{n} + ( - 1)^{1}\begin{pmatrix} +m \\ +2 \\ +\end{pmatrix}(m - 2)^{n} + ( - 1)^{2}\begin{pmatrix} +m \\ +3 \\ +\end{pmatrix}(m - 3)^{n} + \ldots + ( - 1)^{m - 1}\begin{pmatrix} +m \\ +m \\ +\end{pmatrix}(m - m)^{n} \\ +&= \sum_{k = 1}^{m}{( - 1)^{k - 1}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n}. +\end{align*} +$$ + +Therefore, we have + +$$ +\begin{align*} +|Z| &= |X| - \left| Y_{1} \cup Y_{2} \cup \ldots \cup Y_{m} \right| \\ +&= m^{n} - \sum_{k = 1}^{m}{( - 1)^{k - 1}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n} \\ +&= {{- ( - 1)}^{0 - 1}\begin{pmatrix} +m \\ +0 \\ +\end{pmatrix}(m - 0)}^{n} - \sum_{k = 1}^{m}{( - 1)^{k - 1}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n} \\ +&= - 1 \times \left( \sum_{k = 0}^{m}{( - 1)^{k - 1}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n} \right) \\ +&= \sum_{k = 0}^{m}{( - 1)^{k}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n}. +\end{align*} +$$ + +Now, denote in a sequence of length $n$ there are $a_{m,n}$ combinations +that have exactly $m$ states (types of nucleotides). Equivalently, + +$$a_{m,n} = \sum_{k = 0}^{m}{( - 1)^{k}\begin{pmatrix} +m \\ +k \\ +\end{pmatrix}(m - k)}^{n}.$$ + +Denote $b_{m,n}$ as the number of patterns with given $m$ and $n$. Note +that $b_{m,n}$ differs from $a_{m,n}$ in that it refers to the number of +patterns instead of combinations. As an example, the combination ""TTT"" +and ""CCC"" refer to the same pattern which can be denoted by ""111"". +Hence, + +$$b_{m,n} = \frac{a_{m,n}}{m!}.$$ + +According to the context, the number of patterns for four types of +nucleotides thus $m = 1,2,3,4$ may be calculated as + +$$\sum_{m = 1}^{4}b_{m,n} = \sum_{m = 1}^{4}\frac{a_{m,n}}{m!}.$$ + +Hence + +$$ +a_{1,1} = {\begin{pmatrix} +1 \\ +0 \\ +\end{pmatrix}(1 - 0)}^{n} = 1, +$$ + +$$ +{{a_{2,1} = \begin{pmatrix} +2 \\ +0 \\ +\end{pmatrix}(2 - 0)}^{n} - {\begin{pmatrix} +2 \\ +1 \\ +\end{pmatrix}(2 - 1)}^{n} = 2^{n} - 2, +} +$$ + +$$ +{a_{3,1} = {\begin{pmatrix} +3 \\ +0 \\ +\end{pmatrix}(3 - 0)}^{n} - {\begin{pmatrix} +3 \\ +1 \\ +\end{pmatrix}(3 - 1)}^{n} + {\begin{pmatrix} +3 \\ +2 \\ +\end{pmatrix}(3 - 2)}^{n} = 3^{n} - 3 \times 2^{n} + 3, +} +$$ + +$$ +{a_{4,1} = {\begin{pmatrix} +4 \\ +0 \\ +\end{pmatrix}(4 - 0)}^{n} - {\begin{pmatrix} +4 \\ +1 \\ +\end{pmatrix}(4 - 1)}^{n} + {\begin{pmatrix} +4 \\ +2 \\ +\end{pmatrix}(4 - 2)}^{n} - {\begin{pmatrix} +4 \\ +3 \\ +\end{pmatrix}(4 - 3)}^{n} = 4^{n} - 4 \times 3^{n} + 6 \times 2^{n} - 4.} +$$ + +Therefore, the total number of patterns can be calculated as + +$$ +\begin{align*} +\sum_{m = 1}^{4}\frac{a_{m,n}}{m!} &= \frac{1}{1!} + \frac{2^{n} - 2}{2!} + \frac{3^{n} - 3 \times 2^{n} + 3}{3!} + \frac{4^{n} - 4 \times 3^{n} + 6 \times 2^{n} - 4}{4!} \\ +&= 1 + 2^{n - 1} - 1 + \frac{3^{n} - 3 \times 2^{n} + 3}{6} + \frac{4^{n - 1} - 3^{n} + 3 \times 2^{n - 1} - 1}{6} \\ +&= \frac{3 \times 2^{n} + 3^{n} - 3 \times 2^{n} + 3 + 4^{n - 1} - 3^{n} + 3 \times 2^{n - 1} - 1}{6} \\ +&= \frac{4^{n - 1} + 3 \times 2^{n - 1} + 2}{6}. +\end{align*} +$$ + +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C4 Maximum likelihood methods/4.2.md",".md","4969","124","**Solution.** + +Define the likelihoods of observing a site with $i$ substitutions as +$L_{i}$. Let *a*, *b*, and *c* indicate the proportion of the site with +1, 2, and 3 different sites in the alignment respectively. Hence, + +$$ +\begin{matrix} +\mathcal{l =}n\left\lbrack {a \times log}\left( L_{1} \right) + {b \times log}\left( L_{2} \right) + {c \times log}\left( L_{3} \right) \right\rbrack. (4.2) \\ +\end{matrix} +$$ + +Recall Eq. (1.3) in (Yang, 2006) + +$$ +P(t) = \begin{bmatrix} +p_{0}(t) & p_{1}(t) & p_{1}(t) & p_{1}(t) \\ +p_{1}(t) & p_{0}(t) & p_{1}(t) & p_{1}(t) \\ +p_{1}(t) & p_{1}(t) & p_{0}(t) & p_{1}(t) \\ +p_{1}(t) & p_{1}(t) & p_{1}(t) & p_{0}(t) \\ +\end{bmatrix}, +$$ + +with + +$$ +\begin{cases} +p_{0}(t) = \frac{1}{4} + \frac{3}{4}e^{- \frac{4}{3}t} \\ +p_{1}(t) = \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \\ +\end{cases}. +$$ + +Substitute $z$ for $e^{- \frac{4}{3}t}$, it follows that + +$$ +\begin{align*} +L_{0} &= \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4}{3}t} \right)^{3} + \frac{3}{4}\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right)^{3} \\ +&= \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}z \right)^{3} + \frac{3}{4}\left( \frac{1}{4} - \frac{1}{4}z \right)^{3}. +\end{align*} +$$ + +Differentiate the log-likelihood of $L_{0}$ w.r.t. $z$, we have + +$$ +\begin{align*} +\frac{d\log\left( L_{0} \right)}{dz} &= \frac{{\frac{1}{4}\left( \left( \frac{1}{4} + \frac{3}{4}z \right)^{3} \right)}^{'}\left( \frac{3}{4}z \right)^{'} + \frac{3}{4}\left( \left( \frac{1}{4} - \frac{1}{4}z \right)^{3} \right)^{'}\left( - \frac{1}{4}z \right)^{'}}{\frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}z \right)^{3} + \frac{3}{4}\left( \frac{1}{4} - \frac{1}{4}z \right)^{3}} \\ +&= \frac{\frac{9}{32}\left( \ z^{2} + \ z \right)}{\frac{3}{32}z^{3} + \frac{3}{64}z^{2} + \frac{1}{64}} \\ +&= \frac{18\ z\ (1\ + \ z)}{6\ z^{3} + 9\ z^{2} + 1} \quad (4.3) +\end{align*} +$$ + +Likewise, + +$$ +\begin{align*} +L_{1} &= \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4}{3}t} \right)^{2}\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right) \\ +&\quad + \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4}{3}t} \right)\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right)^{2} \\ +&\quad + \frac{1}{2}\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right)^{3} \\ +&= \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}z \right)^{2}\left( \frac{1}{4} - \frac{1}{4}z \right) \\ +&\quad + \frac{1}{4}\left( \frac{1}{4} + \frac{3}{4}z \right)\left( \frac{1}{4} - \frac{1}{4}z \right)^{2} \\ +&\quad + \frac{1}{2}\left( \frac{1}{4} - \frac{1}{4}z \right)^{3} +\end{align*} +$$ + +Hence, + +$$\begin{matrix} +\frac{d\log\left( L_{1} \right)}{dz} = \frac{2\ (1\ - \ 3\ z)z}{- \ 2\ z^{3} + z^{2} + 1}\ (4.4) \\ +\end{matrix}$$ + +For $L2,$ + +$$ +\begin{align*} +L_{2} &= \frac{3}{4}\left( \frac{1}{4} + \frac{1}{4}e^{- \frac{4}{3}t} \right)\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right)^{2} \\ +&\quad + \frac{1}{4}\left( \frac{1}{4} - \frac{1}{4}e^{- \frac{4}{3}t} \right)^{3} \\ +&= \frac{3}{4}\left( \frac{1}{4} + \frac{3}{4}z \right)\left( \frac{1}{4} - \frac{1}{4}z \right)^{2} \\ +&\quad + \frac{1}{4}\left( \frac{1}{4} - \frac{1}{4}z \right)^{3} +\end{align*} +$$ + +and so + +$$\begin{matrix} +\frac{d\log\left( L_{2} \right)}{dz} = \frac{- 6\ z}{- \ 2\ z^{2} + z + 1}\ (4.5) \\ +\end{matrix}$$ + +By plugging Eqs. (4.3-4.5) into Eq. (4.2), we obtain the log-likelihood of +the whole alignment given in the problem as follows (also note that +$c = 1 - a - b$): + +$$ +\begin{align*} +\mathcal{l} &= n\left( a\frac{18z(1 + z)}{6z^3 + 9z^2 + 1} + b\frac{2(1 - 3z)z}{-2z^3 + z^2 + 1} + (1 - a - b)\frac{-6z}{-2z^2 + z + 1} \right) \\ +&= n \times \frac{-2z \begin{pmatrix} +-3 + 12a + 4b - 3z + 30az + 2bz - 33z^2 + 60az^2 + 36bz^2 - \\ +45z^3 + 54az^3 + 42bz^3 - 72z^4 + 36az^4 + 12bz^4 - 36z^5 \\ +\end{pmatrix}}{(-1 + z)(1 + 2z)(1 + z + 2z^2)(1 + 9z^2 + 6z^3)}. +\end{align*} +$$ + +Setting the above to zero, it is easy to note that it is equivalent to +solving the following equation w.r.t. $z$ by setting the numerator to +zero, that is to set + +$$2\ z\ \left( 36\ a\ z^{4} + \ 54\ a\ z^{3} + \ 60\ a\ z^{2} + \ 30\ a\ z\ + \ 12\ a\ + \ 12\ b\ z^{4} + \ 42\ b\ z^{3} + \ 36\ b\ z^{2} + \ 2\ b\ z\ + \ 4\ b\ - \ 36\ z^{5} - \ 72\ z^{4} - \ 45\ z^{3} - \ 33\ z^{2} - \ 3\ z\ - \ 3 \right) = 0$$ + +Combining the similar terms, we obtain the following + +$$- 36z^{5} + (36a - 72 + 12b)z^{4} + {(54a + 42b - 45)z}^{3} + {(60a + 36b - 33)z}^{2} + (30a + 2b - 3)z + (12a + 4b - 3) = 0,$$ + +which, if substituting $f_{0}$ for $a$ and $f_{1}$ for $b$, is exactly +the quintic equation given in the problem. Therefore, +$z = e^{- \frac{4}{3}t}$ is a solution to the quintic equation given in +the problem. + +```R +> library(Ryacas0) +> z <- Sym(“z”) +> Simplify(deriv(log(1/4*(1/4+3/4*z)^3+3/4*(1/4-1/4*z)^3), z)) #L0 +> Simplify(deriv(log(1/4*(1/4+3/4*z)^2*(1/4-1/4*z)+1/4*(1/4+3/4*z)*(1/4-1/4*z)^2+1/2*(1/4-1/4*z)^3), z)) #L1 +> Simplify(deriv(log(3/4*(1/4+3/4*z)*(1/4-1/4*z)^2+1/4*(1/4-1/4*z)^3), z)) #L2 +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C4 Maximum likelihood methods/4.3.md",".md","4433","94","**Solution.** + +

+ +

+ +As to a four-tip tree, there are three possible tree topologies. They +are depicted as *xxyy*, *xyxy*, and *xyyx*, which correspond to +((1,2),3,4), ((1,3),2,4), ((1,4),2,3), respectively. + +

+ +

+ +For tree reconstruction using the most parsimonious (MP) method, only +sites with the patterns where two sites have the same nucleotide while +the other two have another same nucleotide such as TTCC or TATA, are +informative. In other words, a site in the alignment with any other +patterns such as AAAA or ATGG do not provide any information to +distinguish between any of the possible trees because all of them are +equally likely. There have to be at least two nucleotides each occurring +twice at least. See Section 3.4 in (Yang, 2006) for more details. + +Denote the state at node $i$ as $S_{i}$. Hence, + +$$P\left( S_{0} \right) = P\left( S_{1} \right) = ... = P\left( S_{5} \right) = 0.5.$$ + +The probability of observing the pattern $xxyy$ by the MP method can be +calculated as + +$$ +\begin{align*} +P(xxyy) &= P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B) + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A) \\ +&= 0.5\sum_{s_{0} \in \\{ A,B \\}}^{}\left( P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B|S_{0} = s_{0}) + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A|S_{0} = s_{0}) \right) \\ +&= 2 \times 0.5 \times \\left( P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B|S_{0} = A) + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A|S_{0} = A) \\right) \\ +&= P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B|S_{0} = A) + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A|S_{0} = A) \\ +&= P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B,S_{5} = A|S_{0} = A) + P(S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B,S_{5} = B|S_{0} = A) \\ +&\quad + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A,S_{5} = A|S_{0} = A) + P(S_{1} = B,S_{2} = B,S_{3} = A,S_{4} = A,S_{5} = B|S_{0} = A) \\ +&= (1 - q)(1 - p)(1 - q)qp + (1 - q)(1 - p)q(1 - q)(1 - p) + qp(1 - q)(1 - q)(1 - p) + qpqpq \\ +&= 2p^{2}q^{2} - p^{2}q + (q^{3} - 2q^{2} + q). +\end{align*} +$$ + +Likewise, calculate the probability of obtaining the pattern *xyxy* as + +$$ +\begin{align*} +P(xyxy) &= P\left( S_{1} = A,S_{2} = B,S_{3} = A,S_{4} = B \right) + P\left( S_{1} = B,S_{2} = A,S_{3} = B,S_{4} = A \right) \\ +&= 2 \times 0.5 \times \left( P\left( S_{1} = A,S_{2} = B,S_{3} = A,S_{4} = B|S_{0} = A \right) + P\left( S_{1} = B,S_{2} = A,S_{3} = B,S_{4} = A|S_{0} = A \right) \right) \\ +&= (1 - q)p(1 - q)(1 - q)p + (1 - q)pqq(1 - p) + q(1 - p)(1 - q)q(1 - p) + q(1 - p)q(1 - q)p \\ +&= 2\left( p^{2}q^{2} \right) - 3\left( p^{2}q \right) + p^{2} + \left( q^{2} - q^{3} \right). +\end{align*} +$$ + +and the probability of obtaining the pattern *xyyx* as + +$$ +\begin{align*} +P(xyyx) &= P\left( S_{1} = A,S_{2} = B,S_{3} = B,S_{4} = A \right) + P\left( S_{1} = B,S_{2} = A,S_{3} = A,S_{4} = B \right) \\ +&= (1 - q)p(1 - q)q(1 - p) + (1 - q)pq(1 - q)p + q(1 - p)(1 - q)(1 - q)p + q(1 - p)qq(1 - p) \\ +&= 2\left( p^{2}q^{2} \right) - p^{2}q - \left( 4pq^{2} - 2pq \right) + q^{3}. +\end{align*} +$$ + +According to the context of the problem, calculate the difference +between $P(xxyy)$ and $P(xyxy)$ as + +$$ +\begin{align*} +P(xxyy) - P(xyxy) &= \left( 2p^{2}q^{2} - p^{2}q + \left( q^{3} - 2q^{2} + q \right) \right) - \left( 2\left( p^{2}q^{2} \right) - 3\left( p^{2}q \right) + p^{2} + \left( q^{2} - q^{3} \right) \right) \\ +&= (2q - 1)\left( p^{2} - q + q^{2} \right). +\end{align*} +$$ + + +Note that from Exercise 1.3 in (Yang, 2006) the range of $p$ and $q$ are +both $\lbrack 0, + \infty)$. Specifically, it is discerned that the +minimum value of *p* is rendered as 0, whereas the upper limit of p +converges to 1/2 with the progression of time (*t*) towards infinity +$\max(p) = \lim_{t \rightarrow \infty}{\frac{1}{2}\left( 1 - e^{- 2t} \right)} = \frac{1}{2}$ +(the same for $q$). Accordingly, $2q - 1 < 0$. Hence, if and only if +$p^{2} - q + q^{2} > 0$ thus $q(1 - q) < p^{2}$, $P(xxyy) < P(xyxy)$ +holds. + + +```R +> library(Ryacas0) +> p<-Sym(“p”); q<-Sym(“q”) +> f1 <- Simplify( ryacas(expression((1-q)*(1-p)*(1-q)*q*p+(1-q)*(1-p)*q*(1-q)*(1-p)+q*p*(1-q)*(1-q)*(1-p)+q*p*q*p*q)) ) +> f2<- Simplify( ryacas(expression((1-q)*p*(1-q)*(1-q)*p+(1-q)*p*q*q*(1-p)+q*(1-p)*(1-q)*q*(1-p)+q*(1-p)*q*(1-q)*p)) ) +> f3<-Simplify( ryacas(expression((1-q)*p*(1-q)*q*(1-p)+(1-q)*p*q*(1-q)*p+q*(1-p)*(1-q)*(1-q)*p+q*(1-p)*q*q*(1-p))) ) # not used in this exercise +> f1-f2 +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/9.5.md",".md","2748","78","**Solution.** + +Instead of using any software, use the following R code (***9.5.R***) +for branch length estimation. It is based on the famous Felsenstein's +pruning algorithm (Felsenstein, 1973). See also Section 4.2.2 in (Yang, +2006) for a detailed explanation of the algorithm. To use the R script, +please be aware that the following packages *getopt*, *parallel*, +*matrixStats*, *seqinr*, *expm*, *ape, phangorn* may need to be +installed. + +Write the three possible tree topologies (1,2),(3,4), (1,3),(2,4), +(1,4),(2.3) into three files *1.nwk*, *1-2.nwk*, and *1-3.nwk*, +respectively. Now, run *9.5.R* by fixing the tree topology for each of +the three one by one and compare the log-likelihood. The MLEs of the +branch lengths of the tree with the highest likelihood are then compared +with the branch lengths used in simulation (*9.5.R*) where the part that +uses Felsenstein's pruning method is pasted as follows. + +```R +do_phylo_log_lk <- function(param) { + liks_ori <- liks + bl <- param + log_lk <- 0 + j <- 0 + liks <- liks_ori + comp <- numeric(nb.tip + nb.node) + for (anc in (nb.node + nb.tip):(1 + nb.tip)) { + children <- all_children[[anc-nb.tip]] + m <- matrix(0, nl, length(children)) + for(i in 1:length(children)){ + j <- j + 1L + m[,i] <- E(Q * (bl[j])) %*% liks[children[i], ] + } + m_prod <- rowProds(m) + comp[anc] <- sum(m_prod) + if(anc == (1 + nb.tip)){ comp[anc] <- rep(1/nl,nl) %*% m_prod } + liks[anc, ] <- m_prod / comp[anc] + } + log_lk <- rowSums(log(matrix(comp[-TIPS],1))) + return (ifelse(is.na(log_lk), Inf, -log_lk)) # note here -log_lk +} +``` + +Simulate a sequence of $10^{6}$ nucleotide sites using the script +written for Exercise 9.4 and name the simulated alignment as *1.nwk*. +Then, for each of the three possible tree topologies, run the following +in Shell. + +```Bash +for(tree in 1.nwk 1-2.nwk 1-3.nwk){ + echo $tree + Rscript 9.5.R -t 1.nwk -s 1.aln --cpu 10 + echo +} +``` + +The log likelihood of using the three tree topologies are +respectively$\ - 4417007.5$, $- 4433276.3$, and $- 4433276.4$. Hence, +the first topology, thus the correct topology, is indicated as the best +tree. The branch length MLEs of using this tree topology are highly +similar to the parameters used in simulation: + +

+ +

+ +Also confirm this using IQ-Tree (Minh et al., 2020) by the following +command in Shell where the MLEs of branch lengths can be found in the +file *iqtree.treefile* and the log-likelihood is indicated in the file +*iqtree.log* ($- 4417007.476$). Note that the script 9.5.R uses an +algorithm that updates all branch lengths simultaneously in finding +the MLEs, but most modern phylogenetics software instead implement other +faster algorithms. + +```Bash +iqtree -s 1.aln -m JC -redo -pre iqtree +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/9.2.md",".md","1284","33","**Solution.** + +$$f\left( x \middle| \theta \right) = \left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4\theta}{3}} \right)^{x}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4\theta}{3}} \right)^{n - x}$$ + +The MLE of $\theta$ can be easily calculated by setting +$f\left( x \middle| \theta \right)^{'}$ to zero and solving the +equation. + +$$xlog\left( \left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4\theta}{3}} \right) \right)^{'} + (n - x)\log\left( \left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4\theta}{3}} \right) \right)^{'} = 0 +$$ + +The R code for the Monte Carlo integral is given as follows. Note that +in an exponential distribution mean of 0.2 means the density is rate +parameter $\lambda = \frac{1}{0.2} = 5$, and accordingly the probability +density function is $f(x) = 5e^{- 5x}$. My result is +$5.180803{\times 10}^{- 131}$ which is slightly less than +$f\left( x \middle| \widehat{\theta} \right) = 6.30386e{\times 10}^{- 130}$. + +```R +> N<-10^6 +> r<-rexp(N,1/0.2) +> theta_ml <- 0.1015 +> mean(exp(log((3/4-3/4*exp(-4*r/3) )^x * (1/4+3/4*exp(-4*r/3) )^(n-x))-theta_ml) * exp(theta_ml)) +``` + +Alternatively, $\widehat{\theta}$ can be numerically estimated in R with +the following code. + +```R +> f <- function(t){-( x*log(3/4-(3/4)*t) + (n-x)*log((1/4+3*t/4)) )} +> log(optim(0.2, f)$par)*(-3/4) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/9.3.md",".md","2470","73","**Solution.** + +According to Eq. (1.9) and Eq. (1.10) in (Yang, 2006), the transition +probability matrix is given by + +$$P(t) = \begin{bmatrix} +p_{0}(t) & p_{1}(t) & p_{2}(t) & p_{2}(t) \\ +p_{1}(t) & p_{0}(t) & p_{2}(t) & p_{2}(t) \\ +p_{2}(t) & p_{2}(t) & p_{0}(t) & p_{1}(t) \\ +p_{2}(t) & p_{2}(t) & p_{1}(t) & p_{0}(t) \\ +\end{bmatrix},$$ + +where +$p_{0}(t) = \frac{1}{4} + \frac{1}{4}e^{- 4\beta t} + \frac{1}{2}e^{- 2(\alpha + \beta)t},\ $ +$p_{1}(t) = \frac{1}{4} + \frac{1}{4}e^{- 4\beta t} - \frac{1}{2}e^{- 2(\alpha + \beta)t}$ +and +$p_{2}(t) = \frac{1 - p_{0}(t) - p_{1}(t)}{2} = \frac{1}{4} - \frac{1}{4}e^{- 4\beta t}$. +Applying the re-parametrization $d = (\alpha + 2\beta)t$ and +$\kappa = \frac{\alpha}{\beta}$ we have + +$$p_{0}(t) = \frac{1}{4} + \frac{1}{4}e^{- \frac{4d}{\kappa + 2}} + \frac{1}{2}e^{- \frac{2d(\kappa + 1)}{\kappa + 2}},$$ + +$$p_{2}(t) = \frac{1}{4} - \frac{1}{4}e^{- \frac{4d}{(\kappa + 2)}}.$$ + +Here, we apply the third method mentioned in Chapter 9 of (Yang, 2006) +by **multinomial sampling** with the following R code. + +```R +generate_pair_sequence_k80 <- function(d,k,l){ + p0<-1/4+1/4*exp(-4*d/(k+2))+1/2*exp(-2*d*(k+1)/(k+2)) + p1<-1/4+1/4*exp(-4*d/(k+2))-1/2*exp(-2*d*(k+1)/(k+2)) + p2<-1/4-1/4*exp(-4*d/(k+2)) + + P<-matrix(c(p0,p1,p2,p2,p1,p0,p2,p2,p2,p2,p0,p1,p2,p2,p1,p0),ncol=4,byrow=T) + freq<-rep(0.25,4) + A <- freq*P + + dna <- c(""T"",""C"",""A"",""G"") + dna_pair <- expand.grid(dna,dna) + dna_pair_char<-paste(dna_pair[,1], dna_pair[,2], sep="""") + + sample(dna_pair_char, l, prob=A, replace=T); +} +estimate_d_k_from_seq <- function(sequence){ + n_s <- 0; n_v <- 0 + transition <- c(""TC"", ""CT"", ""AG"", ""GA"") + transversion <- c(""TA"", ""TG"", ""CA"", ""CG"", ""AC"", ""AT"", ""GC"", ""GT"") + for(i in names(table(sequence))){ + num <- as.numeric(unname(table(sequence)[i])) + if(i %in% transition){ + n_s <- n_s + num + } else if(i %in% transversion){ + n_v <- n_v + num + } + } + s <- n_s/length(sequence) + v <- n_v/length(sequence) + d_hat = -1/2*log(1-2*s-v) - 1/4*log(1-2*v) + k_hat = 2*log(1-2*s-v)/log(1-2*v) - 1 + return(c(d_hat,k_hat)) +} + +> for(d in seq(0.01,2,0.01)){ + k_hats <- sapply(1:1000, function(i){ + sequence <- generate_pair_sequence_k80(d=d,k=2,l=500) + x <- estimate_d_k_from_seq(sequence) + return(x[2]) + }) + k_hats <- k_hats[!is.na(k_hats) & !is.infinite(k_hats)] + cat(mean(k_hats), var(k_hats), ""\n"") +} +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/9.4.md",".md","2820","87","**Solution.** + +Denote the state (nucleotide) at node $i$ as $S_{i}$ which can take +values $s_{i} \in \\{ T,C,A,G \\}$. $Under the model JC69, the +probability of observing $S_{1} = s_{1},\ldots,S_{4} = s_{4}$ where may +be calculated as + +$$ +\begin{align*} +P(S_{1} = s_{1}, S_{2} = s_{2}, S_{3} = s_{3}, S_{4} = s_{4}) &= \sum_{s_{7}}^{}{P(S_{0} = s_{0})P(S_{1}|S_{0} = s_{0})P(S_{3}|S_{0} = s_{0})P(S_{2},S_{4} | S_{0} = s_{0})}\\ +&= 0.25\sum_{s_{0}}^{}{(P(S_{1}|S_{0} = s_{0})P(S_{3}|S_{0} = s_{0}))\sum_{s_{5}}^{}{P(S_{5}|S_{0})P(S_{2}|S_{5} = s_{5})P(S_{4}|S_{5} = s_{5})}}. +\end{align*} +$$ + +Use the following R code to, for each of the total sequence length of +100, 1000, and 10000 bases, conduct 1000 simulations of sequence +evolution. Then, the most parsimonious (MP) tree(s) inferred from each +simulation are summarized. In case where 2 and 3 MP trees are inferred, +each is counted as $1/2$ and $1/3$ respectively. The following R code +counts the three patterns *xxyy*, *xyxy*, and *xyyx*. See Section 3.4 in +(Yang, 2006) or Problem 4.3 in the book for more details in MP tree +reconstruction. + +```R +sample2 <- function(d, base, nsamples=1){ + p0 <- 1/4 + 3/4*exp(-4*d/3) + p1 <- (1-p0)/3 + bases <- c(base, setdiff(BASES, base)) + sample(bases, nsamples, prob=c(p0,rep(p1,3)), replace=T) +} + +sim_seq <- function(l){ + seq <- matrix(0, nrow=4, ncol=l) + dimnames(seq) = list(paste0('S',1:4), paste0('site',1:l)) + for (i in 1:l){ + for(s0 in sample(BASES, 1, prob=rep(0.25,4), replace=T)){ + list2env( setNames(as.list(sample2(d=0.1, s0, nsamples=2)), paste0('s', c(1,5))), envir = .GlobalEnv ) + s3 <- sample2(d=0.5, s0) + s2 <- sample2(d=0.1, s5) + s4 <- sample2(d=0.5, s5) + seq[1,i] <- s1 + seq[2,i] <- s2 + seq[3,i] <- s3 + seq[4,i] <- s4 + } + } + return(seq) +} + +determine_mp <- function(x){ + if(identical(as.integer(table(x)), as.integer(c(2,2)))){ + if(x[1] == x[3]){ + 'xxyy' + } else if(x[1] == x[2]){ + 'xyxy' + } else if(x[1] == x[4]){ + 'xyyx' + } + } else{ + return(NA) + } +} + +> BASES <- c(""T"", ""C"", ""A"", ""G"") + +> for(l in c(100,1000,10000)){ + c_total <- numeric(3) + names(c_total) <- c('xxyy', 'xyxy', 'xyyx') + for(n in 1:100){ + seq_matrix <- sim_seq(l=l) + pattern <- apply(seq_matrix, 2, determine_mp) + count <- table(pattern[!is.na(pattern)]) + mp_index <- which(count == max(count)) + for(i in names(count[mp_index]) ){ + c_total[i] <- c_total[i] + 1/length(mp_index) + } + } + print(c_total) +} +``` + +The result is as follows. *xxyy* means (1,3),(2,4), *xyxy* means +(1,2),(3,4), and *xyyx* means (1,4),(2.3). +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/9.1.md",".md","282","14","**Solution.** + +It is easy to see the result is given by + +$$1 - \prod_{i = 1}^{30}{\frac{365 - i + 1}{365} =}0.7063162.$$ + +The R code for simulation is as follows. + +```R +> n<-10^6 +> a<-sapply(1:n, function(x){length(unique(sample(1:365,30,T))) == 30}) +> print(length(a[a==T])/n) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/scripts/9.5.R",".R","3576","138","#! /usr/bin/env Rscript + +library(getopt) +library(parallel) +library(matrixStats) +library(seqinr) +library(ape) +library(phangorn) +library(expm) + +E <- expm::expm + +###################################### +get_v_freq <- function(v){ + u <- lapply(v, function(x){paste(x, collapse='!')}) + t <- table(unlist(u)) + t_names_split <- lapply(names(t), function(x){unlist(strsplit(x,""!""), use.name=F)}) + l <- vector(""list"", length(rownames(t))) + for(i in 1:length(rownames(t))){ + l[[i]] <- list(as.integer(t_names_split[[i]]), t[[i]]) + } + l +} + +read_traits <- function(d){ + v <- list() + name <- unlist(d$V1) + for(i in 2:ncol(d)){ + v[[i-1]] <- unlist(d[,i]) + names(v[[i-1]]) <- name + } + return(v) +} + +rename_trait <- function(x){ + if (!is.null(names(x))) { + if (all(names(x) %in% phy$tip.label)) + x <- x[phy$tip.label] + else stop(""the names of 'x' and the tip labels of the tree do not match: the former were ignored in the analysis."") + } + if (!is.factor(x)) { + x <- factor(x) + nl <- nlevels(x) + x <- as.integer(x) + } + x +} + +###################################### +# phylo construction functions +do_phylo_log_lk <- function(param) { + liks_ori <- liks + bl <- param + log_lk <- 0 + j <- 0 + liks <- liks_ori + comp <- numeric(nb.tip + nb.node) + for (anc in (nb.node + nb.tip):(1 + nb.tip)) { + children <- all_children[[anc-nb.tip]] + m <- matrix(0, nl, length(children)) + for(i in 1:length(children)){ + j <- j + 1L + m[,i] <- E(Q * (bl[j])) %*% liks[children[i], ] + } + m_prod <- rowProds(m) + comp[anc] <- sum(m_prod) + if(anc == (1 + nb.tip)){ comp[anc] <- rep(1/nl,nl) %*% m_prod } + liks[anc, ] <- m_prod / comp[anc] + } + log_lk <- rowSums(log(matrix(comp[-TIPS],1))) + return (ifelse(is.na(log_lk), Inf, -log_lk)) # note here -log_lk +} + +format_do_phylo_log_lk <- function(x, param){ + liks <- matrix(0, nb.tip + nb.node, nl) + liks[cbind(TIPS, x[[1]])] <- 1 + environment(do_phylo_log_lk) <- environment() + do_phylo_log_lk(param) * x[[2]] +} + +sum_phylo_log_lk <- function(param){ + s <- sum( unlist (mclapply(v, format_do_phylo_log_lk, c(param=param), mc.cores=cpu) ) ) + s +} + +###################################### +phy <- NULL +s <- NULL +cpu <- 1 + +###################################### +spec <- matrix(c( + 'tree', 't', 2, 'character', + 'traits', 's', 2, 'character', + 'inv', 'i', 0, 'logical', + 'cpu', 'n', 2, 'integer' + ), ncol=4, byrow=T +) +opts <- getopt(spec) +if(!is.null(opts$tree)){phy <- read.tree(opts$tree)} +if(!is.null(opts$traits)){s <- read.fasta(opts$traits)} +if(!is.null(opts$cpu)){cpu <- opts$cpu} +stopifnot(class(phy) != ""Phylo"") + +###################################### +# read and parse the seq +if(var(getLength(s)) != 0){ + stop(paste(""seqfile"", ""seq of diff lengths"")) +} +seq <- getSequence(s) +v <- list() +for(i in 1:getLength(s)[1]){ + v[[i]] <- sapply(s, function(x) x[i]) + names(v[[i]]) <- names(s) +} +nl <- nlevels(factor(unlist(v, use.names=F))) +v <- lapply(v, rename_trait) +cat(""Alignment length:"", length(v), ""\n"") + +###################################### +v <- get_v_freq(v) +nb.tip <- length(phy$tip.label) +nb.node <- phy$Nnode +TIPS <- 1:nb.tip + +# create the rate matrix Q +p <- rep(1, 4) +Q <- matrix(rep(p, 4), nl, nl); diag(Q) <- 0 +Q <- apply(Q, 1, function(x){x/sum(x)}); diag(Q) <- -rowSums(Q) + +all_children <- Children(phy, (1 + nb.tip):(nb.node + nb.tip) ) +df <- length(phy$edge.length) +bl <- rep(0.1, df) + +# employ nlminb to find the parameters (branch length estimates) that minimize the target function sum_phylo_log_lk +opt <- nlminb(bl, function(p) sum_phylo_log_lk(p), lower = 1e-6, upper = Inf, control=list(iter.max=500, eval.max=500, trace=1)) +print(opt$par) +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/scripts/9.4.R",".R","1551","56","sample2 <- function(d, base, nsamples=1){ + p0 <- 1/4 + 3/4*exp(-4*d/3) + p1 <- (1-p0)/3 + bases <- c(base, setdiff(BASES, base)) + sample(bases, nsamples, prob=c(p0,rep(p1,3)), replace=T) +} + +sim_seq <- function(l){ + seq <- matrix(0, nrow=4, ncol=l) + dimnames(seq) = list(paste0('S',1:4), paste0('site',1:l)) + for (i in 1:l){ + for(s0 in sample(BASES, 1, prob=rep(0.25,4), replace=T)){ + list2env( setNames(as.list(sample2(d=0.1, s0, nsamples=2)), paste0('s', c(1,5))), envir = .GlobalEnv ) + s3 <- sample2(d=0.5, s0) + s2 <- sample2(d=0.1, s5) + s4 <- sample2(d=0.5, s5) + seq[1,i] <- s1 + seq[2,i] <- s2 + seq[3,i] <- s3 + seq[4,i] <- s4 + } + } + return(seq) +} + +determine_mp <- function(x){ + if(identical(as.integer(table(x)), as.integer(c(2,2)))){ + if(x[1] == x[3]){ + 'xxyy' + } else if(x[1] == x[2]){ + 'xyxy' + } else if(x[1] == x[4]){ + 'xyyx' + } + } else{ + return(NA) + } +} + +> BASES <- c(""T"", ""C"", ""A"", ""G"") + +> for(l in c(100,1000,10000)){ + c_total <- numeric(3) + names(c_total) <- c('xxyy', 'xyxy', 'xyyx') + for(n in 1:100){ + seq_matrix <- sim_seq(l=l) + pattern <- apply(seq_matrix, 2, determine_mp) + count <- table(pattern[!is.na(pattern)]) + mp_index <- which(count == max(count)) + for(i in names(count[mp_index]) ){ + c_total[i] <- c_total[i] + 1/length(mp_index) + } + } + print(c_total) +} +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","CME2006/C9 Simulating molecular evolution/scripts/9.3.R",".R","1412","44","generate_pair_sequence_k80 <- function(d,k,l){ + p0<-1/4+1/4*exp(-4*d/(k+2))+1/2*exp(-2*d*(k+1)/(k+2)) + p1<-1/4+1/4*exp(-4*d/(k+2))-1/2*exp(-2*d*(k+1)/(k+2)) + p2<-1/4-1/4*exp(-4*d/(k+2)) + + P<-matrix(c(p0,p1,p2,p2,p1,p0,p2,p2,p2,p2,p0,p1,p2,p2,p1,p0),ncol=4,byrow=T) + freq<-rep(0.25,4) + A <- freq*P + + dna <- c(""T"",""C"",""A"",""G"") + dna_pair <- expand.grid(dna,dna) + dna_pair_char<-paste(dna_pair[,1], dna_pair[,2], sep="""") + + sample(dna_pair_char, l, prob=A, replace=T); +} +estimate_d_k_from_seq <- function(sequence){ + n_s <- 0; n_v <- 0 + transition <- c(""TC"", ""CT"", ""AG"", ""GA"") + transversion <- c(""TA"", ""TG"", ""CA"", ""CG"", ""AC"", ""AT"", ""GC"", ""GT"") + for(i in names(table(sequence))){ + num <- as.numeric(unname(table(sequence)[i])) + if(i %in% transition){ + n_s <- n_s + num + } else if(i %in% transversion){ + n_v <- n_v + num + } + } + s <- n_s/length(sequence) + v <- n_v/length(sequence) + d_hat = -1/2*log(1-2*s-v) - 1/4*log(1-2*v) + k_hat = 2*log(1-2*s-v)/log(1-2*v) - 1 + return(c(d_hat,k_hat)) +} + +> for(d in seq(0.01,2,0.01)){ + k_hats <- sapply(1:1000, function(i){ + sequence <- generate_pair_sequence_k80(d=d,k=2,l=500) + x <- estimate_d_k_from_seq(sequence) + return(x[2]) + }) + k_hats <- k_hats[!is.na(k_hats) & !is.infinite(k_hats)] + cat(mean(k_hats), var(k_hats), ""\n"") +} +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/References.md",".md","2367","58","**References** + +Earl DJ, Deem MW. 2005. Parallel tempering: Theory, applications, and +new perspectives. *Phys. Chem. Chem. Phys.* 7:3910--3916. + +Hohna S, Landis MJ, Heath TA, Boussau B, Lartillot N, Moore BR, +Huelsenbeck JP, Ronquist F. 2016. RevBayes: Bayesian phylogenetic +inference using graphical models and an interactive model-specification +language. *Syst. Biol.* 65:726--736. + +Horai S, Hayasaka K, Kondo R, Tsugane K, Takahata N. 1995. Recent +African origin of modern humans revealed by complete sequences of +hominoid mitochondrial DNAs. *Proc. Natl. Acad. Sci. U. S. A.* + +Kumar S, Stecher G, Li M, Knyaz C, Tamura K. 2018. MEGA X: Molecular +evolutionary genetics analysis across computing platforms. *Mol. Biol. +Evol.* 35:1547--1549. + +Lewis PO, Holder MT, Holsinger KE. 2005. Polytomies and bayesian +phylogenetic inference. *Syst. Biol.* 54:241--253. + +Paradis E, Schliep K. 2019. Ape 5.0: An environment for modern +phylogenetics and evolutionary analyses in R. *Bioinformatics* +35:526--528. + +dos Reis M, Yang Z. 2011. Approximate likelihood calculation on a +phylogeny for Bayesian Estimation of Divergence Times. *Mol. Biol. +Evol.* 28:2161--2172. + +Revell LJ. 2012. phytools: An R package for phylogenetic comparative +biology (and other things). *Methods Ecol. Evol.* 3:217--223. + +Schliep KP. 2011. Phangorn: phylogenetic analysis in {R}. +*Bioinformatics* \[Internet\] 27:592--593. Available from: +https://academic.oup.com/bioinformatics/article/27/4/592/198887 + +Yang Z. 2006. Computational Molecular Evolution. Oxford University Press +Available from: http://abacus.gene.ucl.ac.uk/CME/ + +Yang Z. 2014a. Molecular Evolution: A Statistical Approach. Oxford +University Press Available from: http://abacus.gene.ucl.ac.uk/MESA/ + +Yang Z. 2014b. MESA Dataset. Available from: +http://abacus.gene.ucl.ac.uk/MESA/Yang2014.MESA.data.tgz + +Yang Z. 2015. The BPP program for species tree estimation and species +delimitation. *Curr. Zool.* 61:854--865. + +Yang Z. 2022. Errata I of Yang 2014 Molecular Evolution: A Statistical +Approach. Available from: +http://abacus.gene.ucl.ac.uk/MESA/Yang2014.MESA.Corrections.pdf + +Yang Z, Rannala B. 2005. Branch-length prior influences Bayesian +posterior probability of phylogeny. *Syst. Biol.* 54:455--470. + +Yang Z, Dos Reis M. 2011. Statistical properties of the branch-site test +of positive selection. *Mol. Biol. Evol.* 28:1217--1228. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.6.md",".md","863","28","**Solution.** + +The code and the figure are given as follows. Two Gamma priors are used +$Gamma(100,10)$ and $Gamma(50,5)$. I use ""curve()"" instead of MCMC. Note +that $\log_{10}{(f(\theta|D))}$ is displayed as *y*-axis and $\theta$ +denotes the JC69 distance to estimate. + +```R +# 7.6.R +log10_lik_JC69 <- function(d, n, x, a, b){ + log(dgamma(d, a, b)) + x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) / log(10) +} +######################################## +x <- 90; n<-948 +pdf(""7.6.pdf""); par(mfrow=c(1,2)) +posterior <- expression('log10(f('*theta*'|D))'); theta <- expression(italic(theta)) +df <- data.frame(c(100,10), c(50,5)) +for(i in 1:length(df)){ + v <- df[,i] + curve(log10_lik_JC69(d=x,n=n,x=x,a=v[1],b=v[2]), from=0, to=25, ylab=posterior, xlab=theta, main=paste0(""G("",v[1],',',v[2],"")"")) +} +dev.off() +``` + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.3.md",".md","793","23","**Solution.** + +It is straightforward to use the following R code to get +$\alpha_{left} = \frac{\pi(9.9)}{\pi(10)} = 1.000574$, and +$\alpha_{right} = \frac{\pi(10.1)}{\pi(10)} = 0.9994979$. + +```R +lnl_JC69 <- function(d, n, x) x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) +n <- 948; x <- 90; +exp(lnl_JC69(9.9,n=n,x=x) - lnl_JC69(10,n=n,x=x)) +exp(lnl_JC69(10.1,n=n,x=x) - lnl_JC69(10,n=n,x=x)) +``` + +Using a starting value of $\theta_{start} = 10$ and sliding window width +$w = 0.2$ would lead to the correct estimate. However, +$\theta_{start} = 100$ will lead to poor mixing given $w = 0.2$, as +there is little difference between $\pi(99.8)$,$\ \pi(100)$ and +$\pi(100.2)$. Changing $w$ to a bigger value can overcome this problem. + +**Note** + +See also Section 7.3.1 of (Yang 2014a). +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.10.md",".md","11700","429","

+ +

+ +**Solutions.** + +Two solutions are provided, the first solving the problem by Eq. (7.35), +the second using Eq. (7.37) in (Yang 2014a). + +**Solution 1.** + +Eq. (7.35) in (Yang 2014a) is written as + +$$v = h^{T} \bullet B(2Z - I - A) \bullet h.$$ + +Because $h = (1,0,0,\ldots,0)^{T}$, it is apparent that $v$ equals the +element located at the intersection of the first row and the first +column of matrix $B(2Z - I - A)$. + +Define + +$$B(2Z - I - A) = C = \begin{bmatrix} +c_{11} & c_{12} & \cdots & c_{1K} \\ +c_{21} & c_{22} & \cdots & c_{2K} \\ + \vdots & \vdots & \ddots & \vdots \\ +c_{K1} & c_{K2} & \cdots & c_{KK} +\end{bmatrix}.$$ + +In other words, $v = c_{11}$ is what to be calculated. + +Due to symmetry, we have + +$$\pi_{1} = \pi_{2} = \ldots = \pi_{K} = \frac{1}{K}.$$ + +Hence, + +$$A = \begin{bmatrix} +\pi_{1} & \pi_{2} & \cdots & \pi_{K} \\ +\pi_{1} & \pi_{2} & \cdots & \pi_{K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\pi_{1} & \pi_{2} & \cdots & \pi_{K} +\end{bmatrix} = \frac{1}{K}1_{K \times K},$$ + +and + +$$B = \begin{bmatrix} +\pi_{1} & 0 & \cdots & 0 \\ +0 & \pi_{2} & \cdots & 0 \\ + \vdots & \vdots & \ddots & \vdots \\ +0 & 0 & \cdots & \pi_{K} +\end{bmatrix} = \frac{1}{K}I_{K}.$$ + +According to Section 7.3.2.1 in (Yang 2014a), the matrix $Z$ is defined +as + +$$Z = (I - P + A)^{- 1}.$$ + +Define $D = I - P + A$, hence $Z = D^{- 1}$. It follows that + +$$ +\begin{align*} +D &= I_{K} - \begin{bmatrix} +0 & \frac{1}{K - 1} & \cdots & \frac{1}{K - 1} \\ +\frac{1}{K - 1} & 0 & \cdots & \frac{1}{K - 1} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{K - 1} & \frac{1}{K - 1} & \cdots & 0 +\end{bmatrix} + \frac{1}{K}1_{K \times K} \\ +&= \begin{bmatrix} +1 & \frac{1}{1 - K} & \cdots & \frac{1}{1 - K} \\ +\frac{1}{1 - K} & 1 & \cdots & \frac{1}{1 - K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{1 - K} & \frac{1}{1 - K} & \cdots & 1 +\end{bmatrix} + \begin{bmatrix} +\frac{1}{K} & \frac{1}{K} & \cdots & \frac{1}{K} \\ +\frac{1}{K} & \frac{1}{K} & \cdots & \frac{1}{K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{K} & \frac{1}{K} & \cdots & \frac{1}{K} +\end{bmatrix} \\ +&= \frac{1}{K}\begin{bmatrix} +K + 1 & \frac{1}{1 - K} & \cdots & \frac{1}{1 - K} \\ +\frac{1}{1 - K} & K + 1 & \cdots & \frac{1}{1 - K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{1 - K} & \frac{1}{1 - K} & \cdots & K + 1 +\end{bmatrix}. +\end{align*} +$$ + +Further define + +$${a = K + 1, +}{b = \frac{1}{1 - K}, +}{E = \frac{1}{K}\begin{bmatrix} +K + 1 & \frac{1}{1 - K} & \cdots & \frac{1}{1 - K} \\ +\frac{1}{1 - K} & K + 1 & \cdots & \frac{1}{1 - K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{1 - K} & \frac{1}{1 - K} & \cdots & K + 1 +\end{bmatrix} = \begin{bmatrix} +a & b & \cdots & b \\ +b & a & \cdots & b \\ + \vdots & \vdots & \ddots & \vdots \\ +b & b & \cdots & a +\end{bmatrix}.}$$ + +$D$ may be rewritten as follows $D = \frac{1}{K}E.\ $Hence, +$D^{- 1} = K \bullet E^{- 1}$. + +To get the inverse of matrix $D$, we apply the following trick in linear +algebra. Define + +$$E^{- 1} = \begin{bmatrix} +x & y & \cdots & y \\ +y & x & \cdots & y \\ + \vdots & \vdots & \ddots & \vdots \\ +y & y & \cdots & x +\end{bmatrix}.$$ + +Because $EE^{- 1} = I$, we have + +$$\begin{bmatrix} +ax + (K - 1)by & ay + bx + (K - 2)by & \cdots & ay + bx + (K - 2)by \\ +ay + bx + (K - 2)by & ax + (K - 1)by & \cdots & ay + bx + (K - 2)by \\ + \vdots & \vdots & \ddots & \vdots \\ +ay + bx + (K - 2)by & ay + bx + (K - 2)by & \cdots & ax + (K - 1)by +\end{bmatrix} = \begin{bmatrix} +1 & 0 & \cdots & 0 \\ +0 & 1 & \cdots & 0 \\ + \vdots & \vdots & \ddots & \vdots \\ +0 & 0 & \cdots & 1 +\end{bmatrix}.$$ + +Thus, finding $E^{- 1}$ is equivalent to solving the following system of +linear equations with two variables + +$$ +\begin{align*} +ax + (K - 1)by &= 1 \\ +ay + bx + (K - 2)by &= 0 +\end{align*} +$$ + +By solving it, we get + +$$ +x = \frac{{2b - a - Kb}}{{(K-1)b^2 - (a^2 + ab(K-2))}}, +$$ + +$$ +y = \frac{b}{{(K-1)b^2 - (a^2 + ab(K-2))}}. +$$ + +Introducing $a = K + 1,b = \frac{1}{1 - K}$ into $x$ and $y$, the +denominator of $x$ and $y$ can be simplified as + +$${\frac{1}{{(K - 1)b}^{2} - \left( a^{2} + ab(K - 2) \right)} = \frac{(1 - K)^{3}}{K^{3}\left( K^{2} - 2K + \ 1 \right)} +}{= \frac{1 - K}{K^{3}\ }.}$$ + +Therefore, $E$ may be rewritten as + +$$E^{- 1} = \frac{1 - K}{K^{3}\ }\begin{bmatrix} +2b\ - \ a\ - \ Kb & b & \cdots & b \\ +b & 2b\ - \ a\ - \ Kb & \cdots & b \\ + \vdots & \vdots & \ddots & \vdots \\ +b & b & \cdots & 2b\ - \ a\ - \ Kb +\end{bmatrix}.$$ + +It follows that + +$$ +\begin{align*} +Z &= D^{-1} = K \cdot E^{-1} \\ +&= K\frac{1 - K}{K^{3}}\begin{bmatrix} +2b - a - Kb & b & \cdots & b \\ +b & 2b - a - Kb & \cdots & b \\ + \vdots & \vdots & \ddots & \vdots \\ +b & b & \cdots & 2b - a - Kb +\end{bmatrix} \\ +&= \frac{1 - K}{K^{2}}\begin{bmatrix} +\frac{2K^{2} - K^{3} - 2K + 1}{(1 - K)^{2}} & \frac{1}{1 - K} & \cdots & \frac{1}{1 - K} \\ +\frac{1}{1 - K} & \frac{2K^{2} - K^{3} - 2K + 1}{(1 - K)^{2}} & \cdots & \frac{1}{1 - K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{1 - K} & \frac{1}{1 - K} & \cdots & \frac{2K^{2} - K^{3} - 2K + 1}{(1 - K)^{2}} +\end{bmatrix} \\ +&= \frac{1 - K}{K^{2}}\begin{bmatrix} +\frac{K^{2} - K + 1}{1 - K} & \frac{1}{1 - K} & \cdots & \frac{1}{1 - K} \\ +\frac{1}{1 - K} & \frac{K^{2} - K + 1}{1 - K} & \cdots & \frac{1}{1 - K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{1 - K} & \frac{1}{1 - K} & \cdots & \frac{K^{2} - K + 1}{1 - K} +\end{bmatrix} \\ +&= \frac{1}{K^{2}}\begin{bmatrix} +K^{2} - K + 1 & 1 & \cdots & 1 \\ +1 & K^{2} - K + 1 & \cdots & 1 \\ + \vdots & \vdots & \ddots & \vdots \\ +1 & 1 & \cdots & K^{2} - K + 1 +\end{bmatrix}. +\end{align*} +$$ + + +Define $F = 2Z - I - A$. $F$ can be rewritten as + +$$ +\begin{align*} +F &= 2Z - I - A \\ +&= \frac{2}{K^{2}}\begin{bmatrix} +K^{2} - K + 1 & 1 & \cdots & 1 \\ +1 & K^{2} - K + 1 & \cdots & 1 \\ + \vdots & \vdots & \ddots & \vdots \\ +1 & 1 & \cdots & K^{2} - K + 1 +\end{bmatrix} - I - \frac{1}{K}1_{K \times K} \\ +&= \begin{bmatrix} +1 - \frac{2}{K} + \frac{2}{K^{2}} & \frac{2}{K^{2}} & \cdots & \frac{2}{K^{2}} \\ +\frac{2}{K^{2}} & 1 - \frac{2}{K} + \frac{2}{K^{2}} & \cdots & \frac{2}{K^{2}} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{2}{K^{2}} & \frac{2}{K^{2}} & \cdots & 1 - \frac{2}{K} + \frac{2}{K^{2}} +\end{bmatrix} - \frac{1}{K}1_{K \times K} \\ +&= \begin{bmatrix} +1 - \frac{3}{K} + \frac{2}{K^{2}} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ +\frac{2}{K^{2}} & 1 - \frac{3}{K} + \frac{2}{K^{2}} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{2}{K^{2}} - \frac{1}{K} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & 1 - \frac{3}{K} + \frac{2}{K^{2}} +\end{bmatrix}. +\end{align*} +$$ + +Compute the matrix product of matrices $B$ and $F$ as follows + +$$ +\begin{align*} +BF &= \frac{1}{K}I_{K} \times \begin{bmatrix} +1 - \frac{3}{K} + \frac{2}{K^{2}} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ +\frac{2}{K^{2}} & 1 - \frac{3}{K} + \frac{2}{K^{2}} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{2}{K^{2}} - \frac{1}{K} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & 1 - \frac{3}{K} + \frac{2}{K^{2}} +\end{bmatrix} \\ +&= \frac{1}{K}\begin{bmatrix} +1 - \frac{3}{K} + \frac{2}{K^{2}} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ +\frac{2}{K^{2}} & 1 - \frac{3}{K} + \frac{2}{K^{2}} & \cdots & \frac{2}{K^{2}} - \frac{1}{K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{2}{K^{2}} - \frac{1}{K} & \frac{2}{K^{2}} - \frac{1}{K} & \cdots & 1 - \frac{3}{K} + \frac{2}{K^{2}} +\end{bmatrix}. +\end{align*} +$$ + +Extracting the entry located in the very top-left corner of the matrix +yields + +$$v = \frac{1}{K}\left( 1 - \frac{3}{K} + \frac{2}{K^{2}} \right).$$ + +**Solution 2.** + +First, calculate the eigenvalues of the matrix $1_{K \times K}$, which +yields + +$$\lambda_{1} = K,\lambda_{2} = 0,\ldots,\lambda_{n} = 0.$$ + +Conduct orthogonal decomposition for $1_{K \times K}$ as + +$$1_{K \times K} = R\Lambda R^{T},$$ + +where + +$$ +R = \begin{bmatrix} +r_{11} & r_{12} & \cdots & r_{1K} \\ +r_{21} & r_{22} & \cdots & r_{2K} \\ +\vdots & \vdots & \ddots & \vdots \\ +r_{K1} & r_{K2} & \cdots & r_{KK} +\end{bmatrix} +$$ + +is an orthogonal matrix ($R^{T} = R^{- 1}$). + +Apparently, the eigenvector set of the eigenvalue $K$ is +$\{ kI_{K \times 1}|k \neq 0\}$. Hence, for the orthogonal matrix $R$, +its first column is + +$$ +\begin{bmatrix} +\frac{1}{\sqrt{K}} \\ +\frac{1}{\sqrt{K}} \\ +\vdots \\ +\frac{1}{\sqrt{K}} +\end{bmatrix}, +$$ + +thus + +$$ +R = \begin{bmatrix} +\frac{1}{\sqrt{K}} & r_{12} & \cdots & r_{1K} \\ +\frac{1}{\sqrt{K}} & r_{22} & \cdots & r_{2K} \\ + \vdots & \vdots & \ddots & \vdots \\ +\frac{1}{\sqrt{K}} & r_{K2} & \cdots & r_{KK} +\end{bmatrix}. +$$ + +Define + +$$P = \frac{1_{K \times K} - I_{K}}{K - 1} = \frac{1}{K - 1}\left( R\Lambda R^{T} - RI_{K}R^{T} \right) = R\left( \frac{1}{K - 1}\left( \Lambda - I_{K} \right) \right)R^{T}.$$ + +Note + +$${\frac{1}{K - 1}\left( \Lambda - I_{K} \right) = \frac{1}{K - 1}\begin{bmatrix} +K & 0 & \cdots & 0 \\ +0 & 0 & \cdots & 0 \\ + \vdots & \vdots & \ddots & \vdots \\ +0 & 0 & \cdots & 0 +\end{bmatrix} - \frac{1}{K - 1}\begin{bmatrix} +1 & 0 & \cdots & 0 \\ +0 & 1 & \cdots & 0 \\ + \vdots & \vdots & \ddots & \vdots \\ +0 & 0 & \cdots & 1 +\end{bmatrix} +}{= \begin{bmatrix} +1 & 0 & \cdots & 0 \\ +0 & - \frac{1}{K - 1} & \cdots & 0 \\ + \vdots & \vdots & \ddots & \vdots \\ +0 & 0 & \cdots & - \frac{1}{K - 1} +\end{bmatrix}.}$$ + +Thus, according to Eq. (7.37) of (Yang 2014a), we have + +$$\lambda_{1} = 1,\lambda_{2} = \lambda_{3} = \ldots = \lambda_{K} = \frac{1}{K - 1}.$$ + +Hence + +$$B = diag\left( \pi_{1},\pi_{2},\ldots,\pi_{K} \right) = diag\left( \frac{1}{K},\frac{1}{K},\ldots\frac{1}{K} \right) = {\frac{1}{K}I}_{K}.$$ + +Define + +$$h = \begin{bmatrix} +1 \\ +0 \\ + \vdots \\ +0 +\end{bmatrix}.$$ + +It follows that + +$$E = B^{- \frac{1}{2}}R = \left( \frac{1}{K}I_{K} \right)^{- \frac{1}{2}}R = K^{\frac{1}{2}}R.$$ + +So + +$$ +\begin{aligned} +E^{T}Bh &= \left( K^{\frac{1}{2}}R \right)^{T}Bh \\ +&= K^{\frac{1}{2}}R^{T} \times \frac{1}{K}I_{K} \times \begin{bmatrix} +1 \\ +0 \\ +\vdots \\ +0 +\end{bmatrix} \\ +&= K^{- \frac{1}{2}}R^{T}\begin{bmatrix} +1 \\ +0 \\ +\vdots \\ +0 +\end{bmatrix} \\ +&= K^{- \frac{1}{2}}\begin{bmatrix} +\frac{1}{\sqrt{K}} & r_{12} & \cdots & r_{1K} \\ +\frac{1}{\sqrt{K}} & r_{22} & \cdots & r_{2K} \\ +\vdots & \vdots & \ddots & \vdots \\ +\frac{1}{\sqrt{K}} & r_{K2} & \cdots & r_{KK} +\end{bmatrix}^{T}\begin{bmatrix} +1 \\ +0 \\ +\vdots \\ +0 +\end{bmatrix} \\ +&= K^{- \frac{1}{2}}\begin{bmatrix} +\frac{1}{\sqrt{K}} \\ +r_{12} \\ +\vdots \\ +r_{1K} +\end{bmatrix}. +\end{aligned} +$$ + + +Note that + +$$ +E^{T}Bh = K^{-\frac{1}{2}}\begin{bmatrix} +\frac{1}{\sqrt{K}} \\ +r_{12} \\ +\vdots \\ +r_{1K} +\end{bmatrix} +$$ + +is exactly the first column of the orthogonal matrix $R$. +By definition, we have + +$$\left( \frac{1}{\sqrt{K}} \right)^{2} + r_{12}^{2} + \ldots r_{1K}^{2} = 1.$$ + +Hence, + +$$\sum_{i = 2}^{K}r_{1i}^{2} = 1 - \frac{1}{K} = \frac{K - 1}{K}.$$ + +Hence, + +$$ +v = \sum_{k = 2}^{K}{\frac{1 + \lambda_{k}}{1 - \lambda_{k}}\left( E^{T}Bh \right)_{k}^{2}} +$$ + +$$ += \sum_{k = 2}^{K}{\frac{1 - \frac{1}{K - 1}}{1 + \frac{1}{K - 1}} \times {\left( \frac{1}{\sqrt{K}}\begin{bmatrix} +\frac{1}{\sqrt{k}} \\ +r_{12} \\ +\vdots \\ +r_{1K} +\end{bmatrix} \right)_{k}}^{2}} +$$ + +we have + +$$ +\begin{align*} +v &= \sum_{k = 2}^{K}{\frac{K - 2}{K} \times \frac{1}{K} \times r_{1k}^{2}} \\ +&= \frac{K - 2}{K^{2}}\sum_{k = 2}^{K}r_{1k}^{2} \\ +&= \frac{K - 2}{K^{2}} \times \frac{K - 1}{K} \\ +&= \frac{1}{K}\left( 1 - \frac{3}{K} + \frac{2}{K^{2}} \right). +\end{align*} +$$ + +As to the efficiency, + +$$E = \frac{\pi_{1}\left( 1 - \pi_{1} \right)}{v} = \frac{\frac{1}{K}\left( 1 - \frac{1}{K} \right)}{\frac{1}{K}\left( 1 - \frac{3}{K} + \frac{2}{K^{2}} \right)} = \frac{K}{K - 2}.$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.4.md",".md","2636","93","Solution. + +Refer to Eq. (7.30) in (Yang 2014a): + +$$\pi(x,y) \propto e^{- \left( x^{2} + x^{2}y^{2} + y^{2} \right)},\ - \infty < x,y < \infty.$$ + +The acceptance ratios of using a 2-D and 1-D sliding windows should be +close to 0% and 25% respectively, if the step size is set to 10 for +both. Also, the posterior means of using the 2-D sliding window would be +far away from the MLEs x=0, y=0. + +The code with a 2-D sliding window (7.4-1.R): +```R +proposal_function <- function(x, y, step=10) { + return(c(runif(1, x - step/2, x + step/2), runif(1, y - step/2, y + step/2))) +} + +# Initialize the chain +chain <- matrix(0, nrow=10000, ncol=2) +chain[1,] <- c(10000, 0) + +# Define the log-likelihood function +log_likelihood <- function(x, y) { + return(-(x^2 + y^2 + x^2 * y^2)) +} + +# Metropolis-Hastings algorithm +for (i in 2:nrow(chain)) { + proposal <- proposal_function(chain[i-1, 1], chain[i-1, 2]) + + log_likelihood_ratio <- log_likelihood(proposal[1], proposal[2]) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + + if (runif(1) < min(1, exp(log_likelihood_ratio))) { + chain[i,] <- proposal + } else { + chain[i,] <- chain[i-1,] + } +} + +accepted <- chain[-1, ] != chain[-nrow(chain), ] +accepted_fraction <- mean(accepted) + +print(accepted_fraction) +apply(chain[-c(1:8000),], 2, mean) +``` + +The code with a 1-D sliding window ((7.4-2.R)): +```R +# Define the proposal function for x and y +proposal_function_x <- function(x, step=10) { + return(runif(1, x - step/2, x + step/2)) +} + +proposal_function_y <- function(y, step=10) { + return(runif(1, y - step/2, y + step/2)) +} + +# Initialize the chain +chain <- matrix(0, nrow=10000, ncol=2) +chain[1,] <- c(10000, 0) + +# Metropolis-Hastings algorithm +for (i in 2:nrow(chain)) { + # Propose moves for x and y separately + proposal_x <- proposal_function_x(chain[i-1, 1]) + proposal_y <- proposal_function_y(chain[i-1, 2]) + + # Calculate log likelihood ratios for x and y separately + log_likelihood_ratio_x <- log_likelihood(proposal_x, chain[i-1, 2]) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + log_likelihood_ratio_y <- log_likelihood(chain[i-1, 1], proposal_y) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + + # Accept or reject proposals for x and y separately + if (runif(1) < min(1, exp(log_likelihood_ratio_x))) { + chain[i, 1] <- proposal_x + } else { + chain[i, 1] <- chain[i-1, 1] + } + + if (runif(1) < min(1, exp(log_likelihood_ratio_y))) { + chain[i, 2] <- proposal_y + } else { + chain[i, 2] <- chain[i-1, 2] + } +} + +accepted <- chain[-1, ] != chain[-nrow(chain), ] +accepted_fraction <- mean(accepted) + +print(accepted_fraction) +apply(chain[-c(1:8000),], 2, mean) +``` + +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.2.md",".md","72","6","

+ +

+ +**See Problem 5.6 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.11.md",".md","77","6","

+ +

+ +**See Problem 5.3 of** (Yang 2006)**.** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.7.md",".md","2699","74","**Solution.** + +According to Eq. (7.9) in (Yang 2014a), the transition probability is +defined as + +$$p(x,y) = \left\{ \begin{array}{r} +q\left( y \middle| x \right) \alpha(x,y),y \neq x, \\ +1 - \sum_{y \neq x}^{}{q\left( y \middle| x \right)\alpha(x,y),y = x,} +\end{array} \right.\ $$ + +where +$\alpha(x,y) = \min\left( 1,\frac{\pi(y)}{\pi(x)} \times \frac{q\left( x \middle| y \right)}{q\left( y \middle| x \right)} \right).$ + + +a\) + +Consider the symmetrical move, where by definition +$\( q(\bullet | \bullet) = \frac{1}{2} \).$ +As given in the problem, $\pi_{1} \geq \pi_{2} \geq \pi_{3}$. Hence, the transition +matrix $P$ is given as + +$$ +{\alpha(1,2) = \frac{\pi_{2}}{\pi_{1}}, +}{\alpha(1,3) = \frac{\pi_{3}}{\pi_{1}}, +}{\alpha(2,1) = 1, +}{\alpha(2,3) = \frac{\pi_{3}}{\pi_{2}}, +}{\alpha(3,1) = \alpha(3,2) = 1.} +$$ + +Accordingly, + +$$ +P = \begin{bmatrix} +1 - \frac{\pi_{2}}{2\pi_{1}} - \frac{\pi_{3}}{2\pi_{1}} & \frac{\pi_{2}}{2\pi_{1}} & \frac{\pi_{3}}{2\pi_{1}} \\ +\frac{1}{2} & 1 - \frac{1}{2} - \frac{\pi_{3}}{2\pi_{2}} & \frac{\pi_{3}}{2\pi_{2}} \\ +\frac{1}{2} & \frac{1}{2} & 0 +\end{bmatrix} = +\begin{bmatrix} +\frac{3}{2} - \frac{1}{2\pi_{1}} & \frac{\pi_{2}}{2\pi_{1}} & \frac{\pi_{3}}{2\pi_{1}} \\ +\frac{1}{2} & \frac{1}{2} - \frac{\pi_{3}}{2\pi_{2}} & \frac{\pi_{3}}{2\pi_{2}} \\ +\frac{1}{2} & \frac{1}{2} & 0 +\end{bmatrix}. +$$ + + +b\) + +Consider the asymmetrical move where +$q\left( 3 \middle| 1 \right) = q\left( 1 \middle| 2 \right) = q\left( 2 \middle| 3 \right) = \frac{2}{3}$ +and +$q\left( 2 \middle| 1 \right) = q\left( 3 \middle| 2 \right) = q\left( 1 \middle| 3 \right) = \frac{1}{3}$. + + +$$ +\begin{align*} +\alpha(1,2) &= \min\left(1, \frac{2\pi_{2}}{\pi_{1}}\right), \\ +\alpha(1,3) &= \min\left(1, \frac{\pi_{3}}{2\pi_{1}}\right) = \frac{\pi_{3}}{2\pi_{1}}, \\ +\alpha(2,1) &= \min\left(1, \frac{\pi_{1}}{2\pi_{2}}\right), \\ +\alpha(2,3) &= \min\left(1, \frac{2\pi_{3}}{\pi_{2}}\right), \\ +\alpha(3,1) &= \min\left(1, \frac{2\pi_{1}}{\pi_{3}}\right) = 1, \\ +\alpha(3,2) &= \min\left(1, \frac{\pi_{2}}{2\pi_{3}}\right). +\end{align*} +$$ + +Consequently, we can derive the transition matrix $P$ as + +$$ +P = \begin{bmatrix} +1 - \frac{1}{3}\min\left(1, \frac{2\pi_{2}}{\pi_{1}}\right) - \frac{\pi_{3}}{3\pi_{1}} & \frac{1}{3}\min\left(1, \frac{2\pi_{2}}{\pi_{1}}\right) & \frac{\pi_{3}}{3\pi_{1}} \\ +\frac{2}{3}\min\left(1, \frac{\pi_{1}}{2\pi_{2}}\right) & 1 - \frac{2}{3}\min\left(1, \frac{\pi_{1}}{2\pi_{2}}\right) - \frac{1}{3}\min\left(1, \frac{2\pi_{3}}{\pi_{2}}\right) & \frac{1}{3}\min\left(1, \frac{2\pi_{3}}{\pi_{2}}\right) \\ +\frac{1}{3} & \frac{2}{3}\min\left(1, \frac{\pi_{2}}{2\pi_{3}}\right) & \frac{2}{3} - \frac{2}{3}\min\left(1, \frac{\pi_{2}}{2\pi_{3}}\right) +\end{bmatrix}. +$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.5.md",".md","73","6","

+ +

+ + **See Problem 5.5 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.1.md",".md","72","6","

+ +

+ +**See Problem 5.4 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/7.12.md",".md","2116","56","

+ +

+ +**Solution.** + +This problem involves the so-called parallel tempering MCMC method. I +tentatively set the temperature of the hold chain to be 30, which +achieves an acceptance ratio of chain swap of roughly 25%. The result +using the script *7.12.R* is shown as follows, the swap acceptance rate +being 25.2%. As advised by a prior study (Earl and Deem 2005), people +should try to achieving an acceptance ratio of chain swap at around 20% +by adjusting the temperature(s). The results of using a single cold +chain, a single hot chain at $T = 30$, and the MCMCMC algorithm which +couples the two chains, are displayed as follows. + +

+ +

+ +```R +# 7.12.R +num_iterations <- 100000; num_chains <- 2 +chains <- matrix(0, nrow = num_iterations, ncol = num_chains) +chains[1, ] <- numeric(num_chains) +temperatures <- c(1, 30) + +target_distribution <- function(x) { + weights <- c(0.2, 0.5, 0.3); means <- c(-2, 0, 1.5); sigma <- 0.1 + lnl <- log(sum(weights * sapply(means, function(mu) dnorm(x, mean = mu, sd = sigma)))) +} +metropolis_hastings_step <- function(current, proposal, temperature, log_target) { + log_acceptance_ratio <- (log_target(proposal) - log_target(current)) / temperature + if (log(runif(1)) < log_acceptance_ratio) {return(proposal)} else{return(current)} +} + +accepted_swap <- 0 +for (i in 2:num_iterations) { + for (chain in 1:num_chains) { + current_value <- chains[i-1, chain] + proposal_value <- runif(1, current_value-0.5, current_value+0.5) + temperature <- temperatures[chain] + chains[i, chain] <- metropolis_hastings_step(current_value, proposal_value, temperature, target_distribution) + } + if (i %% 100 == 1) { + chain1 <- 1; chain2 <- 2; current_values <- chains[i, c(chain1, chain2)] + if (log(runif(1)) < log_acceptance_ratio_swap) { + chains[i, c(chain1, chain2)] <- chains[i, c(chain2, chain1)] + accepted_swap <- accepted_swap + 1 + } + } +} +plot(density(chains[-(1:num_iterations/2), 1]), main = ""MCMCMC"", xlab = """", col = ""purple"", xlim=c(-5,5)) +cat(paste(""accepted swap:"", accepted_swap), ""\n"") +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/scripts/7.4-1.R",".R","949","35","proposal_function <- function(x, y, step=10) { + return(c(runif(1, x - step/2, x + step/2), runif(1, y - step/2, y + step/2))) +} + +# Initialize the chain +chain <- matrix(0, nrow=10000, ncol=2) +chain[1,] <- c(10000, 0) + + +###################################################### +###################################################### +# Define the log-likelihood function +log_likelihood <- function(x, y) { + return(-(x^2 + y^2 + x^2 * y^2)) +} + +# Metropolis-Hastings algorithm +for (i in 2:nrow(chain)) { + proposal <- proposal_function(chain[i-1, 1], chain[i-1, 2]) + + log_likelihood_ratio <- log_likelihood(proposal[1], proposal[2]) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + + if (runif(1) < min(1, exp(log_likelihood_ratio))) { + chain[i,] <- proposal + } else { + chain[i,] <- chain[i-1,] + } +} + +accepted <- chain[-1, ] != chain[-nrow(chain), ] +accepted_fraction <- mean(accepted) + +print(accepted_fraction) +apply(chain[-c(1:8000),], 2, mean) +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/scripts/7.4-2.R",".R","1284","43","# Define the proposal function for x and y +proposal_function_x <- function(x, step=10) { + return(runif(1, x - step/2, x + step/2)) +} + +proposal_function_y <- function(y, step=10) { + return(runif(1, y - step/2, y + step/2)) +} + +# Initialize the chain +chain <- matrix(0, nrow=10000, ncol=2) +chain[1,] <- c(10000, 0) + +# Metropolis-Hastings algorithm +for (i in 2:nrow(chain)) { + # Propose moves for x and y separately + proposal_x <- proposal_function_x(chain[i-1, 1]) + proposal_y <- proposal_function_y(chain[i-1, 2]) + + # Calculate log likelihood ratios for x and y separately + log_likelihood_ratio_x <- log_likelihood(proposal_x, chain[i-1, 2]) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + log_likelihood_ratio_y <- log_likelihood(chain[i-1, 1], proposal_y) - log_likelihood(chain[i-1, 1], chain[i-1, 2]) + + # Accept or reject proposals for x and y separately + if (runif(1) < min(1, exp(log_likelihood_ratio_x))) { + chain[i, 1] <- proposal_x + } else { + chain[i, 1] <- chain[i-1, 1] + } + + if (runif(1) < min(1, exp(log_likelihood_ratio_y))) { + chain[i, 2] <- proposal_y + } else { + chain[i, 2] <- chain[i-1, 2] + } +} + +accepted <- chain[-1, ] != chain[-nrow(chain), ] +accepted_fraction <- mean(accepted) + +print(accepted_fraction) +apply(chain[-c(1:8000),], 2, mean) +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/scripts/7.6.R",".R","540","14","log10_lik_JC69 <- function(d, n, x, a, b){ + log(dgamma(d, a, b)) + x*log(3/4-3/4*exp(-4/3*d)) + (n-x)*log(1/4+3/4*exp(-4/3*d)) / log(10) +} +######################################## +x <- 90; n<-948 +pdf(""7.6.pdf""); par(mfrow=c(1,2)) +posterior <- expression('log10(f('*theta*'|D))'); theta <- expression(italic(theta)) +df <- data.frame(c(100,10), c(50,5)) +for(i in 1:length(df)){ + v <- df[,i] + curve(log10_lik_JC69(d=x,n=n,x=x,a=v[1],b=v[2]), from=0, to=25, ylab=posterior, xlab=theta, main=paste0(""G("",v[1],',',v[2],"")"")) +} +dev.off() +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C7 Bayesian computation (MCMC)/scripts/7.12.R",".R","2288","72","#! /usr/bin/env Rscript + +# Number of iterations and chains +num_iterations <- 100000 +num_chains <- 2 + +# Initialize chains +chains <- matrix(0, nrow = num_iterations, ncol = num_chains) + +# Set initial values for each chain +chains[1, ] <- numeric(num_chains) + +# Define temperatures for each chain +temperatures <- c(1, 10) # Cold chain and hot chain + +# Define the target distribution (mixture of normals) +target_distribution <- function(x) { + weights <- c(0.2, 0.5, 0.3) + means <- c(-2, 0, 1.5) + sigma <- 0.1 + density <- sum(weights * sapply(means, function(mu) dnorm(x, mean = mu, sd = sigma))) + return(log(density)) # Calculate the log density +} + +# Function to perform a Metropolis-Hastings step +metropolis_hastings_step <- function(current, proposal, temperature, log_target) { + log_acceptance_ratio <- (log_target(proposal) - log_target(current)) / temperature + if (log(runif(1)) < log_acceptance_ratio) { + return(proposal) + } else { + return(current) + } +} + +accepted_swap <- 0 +# Perform Parallel Tempering MCMC +for (i in 2:num_iterations) { + for (chain in 1:num_chains) { + current_value <- chains[i-1, chain] + proposal_value <- runif(1, current_value-0.5, current_value+0.5) + + # Adjust the proposal based on the chain's temperature + temperature <- temperatures[chain] + + chains[i, chain] <- metropolis_hastings_step( + current_value, proposal_value, temperature, target_distribution + ) + } + + # Perform chain swapping with a certain probability + if (i %% 100 == 1) { + swap_chain <- c(1,2) + chain1 <- swap_chain[1] + chain2 <- swap_chain[2] + current_values <- chains[i, c(chain1, chain2)] + + # Compute the Metropolis-Hastings acceptance ratio for swapping + log_acceptance_ratio_swap <- (1/temperatures[chain2] - 1/temperatures[chain1]) * (target_distribution(current_values[chain1]) - target_distribution(current_values[chain2])) + + if (log(runif(1)) < log_acceptance_ratio_swap) { + # Swap the values between chain1 and chain2 + chains[i, c(chain1, chain2)] <- chains[i, c(chain2, chain1)] + accepted_swap <- accepted_swap + 1 + } + } +} + +# Plot +plot(density(chains[-(1:num_iterations/2), 1]), main = ""MCMCMC"", xlab = """", col = ""purple"", xlim=c(-5,5)) +cat(paste(""accepted swap:"", accepted_swap), ""\n"") + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.1.md",".md","3219","38","![1](img/8.1-P.png) + +**Solution.** + +Note that the proposal draws $x'$ from $[x - \frac{\epsilon}{2}, x + \frac{\epsilon}{2}]$, but restricts $x'$ to $(0,s)$ by reflecting any proposal that falls outside. Noting that the proposal is symmetric, we can see that $q(x \rightarrow x') = q(x' \rightarrow x) = \frac{1}{\epsilon}$. Thus, the Hastings ratio is $r = \frac{q(x \rightarrow x')}{q(x' \rightarrow x)} = 1$. + +As an example, consider $x = 0.9$, $s = 1$, $\epsilon = 0.4$, $x' = 0.95$. Then, $x'$ is achieved by either a draw within $[0.9 - \frac{0.4}{2}, 1]$ whose probability density equals $\frac{0.3}{0.4} \times \frac{1}{0.3} = \frac{1}{0.4}$, or a draw within the reflection region, where the PDF = $\frac{0.1}{0.4} \times \frac{1}{0.1} = \frac{1}{0.4}$. Hence, $q(0.9 \rightarrow 0.95) = \frac{1}{0.4} + \frac{1}{0.4} = 5$. Likewise, we see $q(0.95 \rightarrow 0.9) = \frac{0.25}{0.4} \times \frac{1}{0.25} + \frac{0.15}{0.4} \times \frac{1}{0.15} = \frac{1}{0.4} + \frac{1}{0.4} = 5$. + +In case where the proposal distribution is a normal distribution, we have + +$$q(x \rightarrow x') = \sum_{k = - \infty}^{\infty} \left[ \mathcal{N}(x' + 2ks \mid x, \sigma^2) + \mathcal{N}(-x' + 2ks \mid x, \sigma^2) \right] = q(x' \rightarrow x).$$ + +To verify this, we again use the above example. We restrict the number of reflections to be two, such that for $x = 0.9$ and $x' = 0.95$, we have the following: + +| Case | y | Reflections | PDF | +| :---------------- | :---------- | :------------ | :-------------------------------------- | +| No reflection | 0.95 | N/A | $\mathcal{N}(0.95 \mid 0.9, \sigma^2)$ | +| One reflection | $-0.95$ | Reflect at 0 | $\mathcal{N}(-0.95 \mid 0.9, \sigma^2)$ | +| One reflection | $2s - 0.95$ | Reflect at s | $\mathcal{N}(1.05 \mid 0.9, \sigma^2)$ | +| Two reflections | $0.95 - 2s$ | Reflect at 0, s | $\mathcal{N}(-1.05 \mid 0.9, \sigma^2)$ | +| Two reflections | $2s + 0.95$ | Reflect at s, 0 | $\mathcal{N}(2.95 \mid 0.9, \sigma^2)$ | + +and for $x = 0.95$ while $x' = 0.9$, we have the table below. + +| Case | y | Reflections | PDF | +| :---------------- | :--------- | :------------ | :-------------------------------------- | +| No reflection | 0.9 | N/A | $\mathcal{N}(0.9 \mid 0.95, \sigma^2)$ | +| One reflection | $-0.9$ | Reflect at 0 | $\mathcal{N}(-0.9 \mid 0.95, \sigma^2)$ | +| One reflection | $2s - 0.9$ | Reflect at s | $\mathcal{N}(1.1 \mid 0.95, \sigma^2)$ | +| Two reflections | $0.9 - 2s$ | Reflect at 0, s | $\mathcal{N}(-1.1 \mid 0.95, \sigma^2)$ | +| Two reflections | $2s + 0.9$ | Reflect at s, 0 | $\mathcal{N}(2.9 \mid 0.95, \sigma^2)$ | + +Denote the number of reflections as $n$. Thus, + +$$q_{n \leq 2}(x \rightarrow x') = \sum_{y \in \{\pm 0.95, \pm 1.05, 2.95\}} \mathcal{N}(y \mid 0.9, \sigma^2) = \sum_{y \in \{\pm 0.90, \pm 1.10, 2.90\}} \mathcal{N}(y \mid 0.95, \sigma^2) = q_{n \leq 2}(x' \rightarrow x).$$ + +For the Bactrian distribution, it is a 1:1 mixture of two normal distributions, and the same logic should apply. We leave this for the readers. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.3.md",".md","3093","79","**Solution.** + +According to the statement of the problem, the prior for each hypothesis +$P\left( H_{1} \right) = P\left( H_{2} \right) = 0.5$. It follows that + +$$ +\\begin{align*} +P(H_{1}|X = x) &= \frac{P\left( H_{1} \right)P\left( X = x \middle| H_{1} \right)}{P\left( H_{1} \right)P\left( X = x \middle| H_{1} \right) + P\left( H_{2} \right)P\left( X = x \middle| H_{2} \right)} \\ +&= \frac{0.5 \times {0.4}^{x} \times (1 - 0.4)^{n - x} \times \binom{n}{x}}{0.5 \times {0.4}^{x} \times (1 - 0.4)^{n - x} \times \binom{n}{x} + 0.5 \times {0.6}^{x} \times (1 - 0.6)^{n - x} \times \binom{n}{x}} \\ +&= \frac{{0.4}^{x} \times (0.6)^{n - x}}{{0.4}^{x} \times (0.6)^{n - x} + {0.6}^{x} \times (0.4)^{n - x}} \\ +&= \frac{1}{1 + \frac{{0.6}^{x} \times (0.4)^{n - x}}{{0.4}^{x} \times (0.6)^{n - x}}} \\ +&= \frac{1}{1 + \left( \frac{3}{2} \right)^{x}\left( \frac{2}{3} \right)^{n - x}} \\ +&= \frac{1}{1 + \left( \frac{3}{2} \times \frac{2}{3} \right)^{x}\left( \frac{2}{3} \right)^{n - 2x}} \\ +&= \frac{1}{1 + \left( \frac{2}{3} \right)^{n - 2x}}. +\end{align*} +$$ + +Define a random variable $Y = P\left( H_{1} \middle| X \right) = \left( 1 + \left( \frac{2}{3} \right)^{n - 2X} \right)^{- 1}$. When $x > \frac{n}{2} + 5$, it can be calculated that + + +$$\frac{1}{1 + \left( \frac{2}{3} \right)^{n - 2x}} < \frac{1}{1 + \left( \frac{2}{3} \right)^{- 10}} = 0.01.$$ + +Similarly, when $x < \frac{n}{2} + 5,$ we have + +$$\frac{1}{1 + \left( \frac{2}{3} \right)^{n - 2x}} > \frac{1}{1 + \left( \frac{2}{3} \right)^{10}} = 0.99.$$ + +In other words, in case where the number of heads differs from the mean +by five, $P_{1}$ will be fairly close to either zero or one. According +to CLT, we have + +$X\sim Normal\left( \frac{1}{2}n,\frac{1}{4}n \right),$ as +$n \rightarrow \infty.$ + +Further, denote the standard normal CDF by $\Phi$. So + +$$ +{P\left( \frac{n}{2} - 5 < X < \frac{n}{2} + 5 \right) = P\left( 5 < X - \frac{n}{2} < 5 \right) +}{= P\left( - \frac{5}{\sqrt{\frac{1}{4}n}} < \frac{X - \frac{n}{2}}{\sqrt{\frac{1}{4}n}} < \frac{5}{\sqrt{\frac{1}{4}n}} \right) +}{= 2\Phi\left( \frac{10}{\sqrt{n}} \right) - 1. +} +$$ + +Hence + +$$\lim_{n \rightarrow \infty}{2\Phi\left( \frac{10}{\sqrt{n}} \right) - 1 = 2 \times 0.5 - 1 = 0.}$$ + +Thus, as $n$ approaches infinity, the probability that $X$ is between +$\frac{n}{2} - 5$ and $\frac{n}{2} + 5$ tends to zero, and in such cases +$P_{1}$ will be 0 or 1 each roughly half of the times. Hence, +$P\left( H_{1} \middle| X \right)$ behaves like a Bernoulli distributed +variable with the parameter $p = 0.5$. + +The R code for simulation can be found in *8.3.R*. + +```R +get_lnl <- function(p, n, x){ + lnl <- x*log(p) + (n-x)*log(1-p) +} +########################################### +p <- 0.5 +n <- 10000 +n_sim <- 1000 + +marginal_lks <- numeric(n_sim) +for(i in 1:n_sim){ + x <- rbinom(1, n, p) + ps <- c(0.4, 0.6) + lnls <- sapply(ps, get_lnl, n=n, x=x) + #print(c(lnls[2]-lnls[1], 1/(1 + exp(lnls[2] - lnls[1])))) + lk <- 1/(1 + exp(lnls[2] - lnls[1])) + marginal_lks[i] <- lk +} +pdf(""8.3-1.pdf"") +hist(marginal_lks, breaks=30) +dev.off() +``` + +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.5.md",".md","5469","125","**Solutions.** + +As follows two solutions are provided, the first showing that the +expectation of the two probabilities are equal, and the second adopting +a way similar to Problem 8.4's solution. Note that the two ways of +solving the problem is somehow different in how to define ""equally wrong +models"", and our feeling is that the way it is defined in Solution 2 may +be closer to what Ziheng hopes to seek. + +**Solution 1.** + +Denote the variable $X$ as the mean of $X_{1},X_{2},\ldots X_{n}$. +According to the problem statement, + +$${P\left( H_{1}|X = x \right) = \frac{0.5 \times \mu_{1}^{- 1}\ e^{- \mu_{1}^{- 1}x}}{0.5 \times \mu_{1}^{- 1}e^{- \mu_{1}^{- 1}x} + 0.5 \times \mu_{2}^{- 1}e^{- \mu_{2}^{- 1}x}} +}{= \frac{1}{1 + \frac{\mu_{1}}{\mu_{2}}e^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)x}}.}$$ + +Denote $k$ as any positive number. It follows that + +$$ +\begin{align*} +& \left\{ \begin{array}{r} +P\left( H_{1} \middle| \mu_{0} + k \right) + P\left( H_{2} \middle| \mu_{0} + k \right) = 1 \\ +P\left( H_{1} \middle| \mu_{0} - k \right) + P\left( H_{2} \middle| \mu_{0} - k \right) = 1 +\end{array} \right. .\#(8.1) +\end{align*} +$$ + +Consider the more general case where +$\mu_{0} = \log\left( \frac{\frac{\mu_{2}}{\mu_{1}}}{\mu_{1}^{- 1} - \mu_{2}^{- 1}} \right)$. +Therefore, we have + +

+ +

+ +Actually, at the third-to-last step, if you are familiar with logistic +regression or some basics of neural network, you should be able to +recognize that it is in the form of sigmoid function +$\sigma\left( f(x) \right)$ where +$f(x) = - \left( \mu_{1}^{- 1} - \mu_{2}^{- 1} \right)k$. Then it is +easy to find the result according to a well-known property of sigmoid +function which states that +$\sigma\left( f(x) \right) + \sigma\left( - f(x) \right) = 1.$ + +By simultaneously solving Eq. 8.1 and +$P\left( H_{1} \middle| \mu_{0} + k \right) + P\left( H_{1} \middle| \mu_{0} - k \right) = 1$ +as calculated above, we have + +$$\left\{ \begin{array}{r} +P\left( H_{1}|X = \mu_{0} + k \right) = P\left( H_{2}|X = \mu_{0} - k \right) \\ +P\left( H_{1}|X = \mu_{0} - k \right) = P\left( H_{2}|X = \mu_{0} + k \right) +\end{array}, \right.\ $$ + +or equivalently + +$$\left\{ \begin{array}{r} +P\left( H_{1}|X = x \right) = P\left( H_{2}|2\mu_{0} - x \right) \\ +P\left( H_{2}|X = x \right) = P\left( H_{1}|2\mu_{0} - x \right) +\end{array} \right.\ .$$ + +According to CLT, + +$X\sim Normal\left( \mu_{0},\frac{\mu_{0}^{2}}{n} \right),$ as +$n \rightarrow \infty.$ + +Define a new variable +$Y = \frac{X - \mu_{0}}{\sqrt{\frac{\mu_{0}^{2}}{n}}}.$ Thus, $Y$ +follows standard normal distribution as $n \rightarrow \infty.$ Hence, +the expectation of $P\left( H_{1}|X \right)$ can be calculated as + +$$ +\begin{align*} +E\left( P\left( H_{1}|X \right) \right) &\approx \int_{- \infty}^{\infty}{\left| \frac{dy}{dx} \right| \times \phi\left( \frac{x - \mu_{0}}{\sqrt{\frac{\mu_{0}^{2}}{n}}} \right) \times P\left( H_{1} \middle| X = x \right)}dx \\ +&= \int_{- \infty}^{\infty}{\frac{1}{\sqrt{\frac{\mu_{0}^{2}}{n}}} \times \phi\left( \frac{\mu_{0} - x}{\sqrt{\frac{\mu_{0}^{2}}{n}}} \right) \times P\left( H_{2} \middle| X = 2\mu_{0} - x \right)}dx \\ +&= \int_{- \infty}^{\infty}{\frac{1}{\sqrt{\frac{\mu_{0}^{2}}{n}}} \times \phi\left( \frac{(2\mu_{0} - x) - \mu_{0}}{\sqrt{\frac{\mu_{0}^{2}}{n}}} \right) \times P\left( H_{2} \middle| X = 2\mu_{0} - x \right)dx} \\ +&\approx E\left( P\left( H_{1}|X \right) \right). +\end{align*} +$$ + +**Solution 2.** + +According to the problem statement, we have + +$$ +\begin{align*} +&P\left( H_{1} \middle| X_{1} = x_{1},\ldots,X_{n} = x_{n} \right) \\ +&= \frac{\left( \frac{1}{\mu_{1}} \right)^{n}e^{- \frac{1}{\mu_{1}}\left( x_{1} + \ldots + x_{n} \right)}}{e^{- \frac{1}{\mu_{1}}\left( x_{1} + \ldots + x_{n} \right)} + e^{- \frac{1}{\mu_{2}}\left( x_{1} + \ldots + x_{n} \right)}} \\ +&= \frac{1}{1 + {\left( \frac{\mu_{1}}{\mu_{2}} \right)^{n}e}^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)\left( x_{1} + \ldots + x_{n} \right)}} \\ +&= \frac{1}{1 + e^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)\left( x_{1} + \ldots + x_{n} \right) + n\log\left( \frac{\mu_{1}}{\mu_{2}} \right)}}. +\end{align*} +$$ + +As given in the problem statement, + +$$\mu_{0} = \frac{\log\left( \frac{\mu_{2}}{\mu_{1}} \right)}{\frac{1}{\mu_{1}} - \frac{1}{\mu_{2}}}.$$ + +So + +$$n\log\left( \frac{\mu_{1}}{\mu_{2}} \right) = - \mu_{0}\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right).$$ + +Substituting $n\log\left( \frac{\mu_{2}}{\mu_{1}} \right)$ for +$\mu_{0}\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)$ into the +above, we have\ +$$P\left( H_{1} \middle| X_{1} = x_{1},\ldots,X_{n} = x_{n} \right) = \frac{1}{1 + e^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)\left( x_{1} + \ldots + x_{n} - n\mu_{0} \right)}}.$$ + +Define $Y_{n} = X_{1} + \ldots + X_{n}$. According to CLT, apparently + +$$Y_{n}\dot{\sim}Normal\left( n\mu_{0},n\mu_{0}^{2} \right).$$ + +Define $Z_{n} = P\left( H_{1} \middle| X_{1},\ldots,X_{n} \right),$ we +have + +$$ +{Z_{n} = \frac{1}{1 + e^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)\left( X_{1} + \ldots + X_{n} - n\mu_{0} \right)}} +}{= \frac{1}{1 + e^{\left( \frac{1}{\mu_{1}} - \frac{1}{\mu_{2}} \right)\left( Y_{n} - n\mu_{0} \right)}}. +} +$$ + +Because +$Y_{n} - n\mu_{0}\dot{\sim}Normal\left( 0,n\mu_{0}^{2} \right),$ using a +similar logic in Problem 8.3 above, it is not difficult to see that it +holds that the two models given in the problem statement are equally +wrong. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.4.md",".md","6286","163","**Solution.** + +This very interesting problem was first formulated in (Lewis et al. +2005), but in this paper the result is shown implicitly. It is in (Yang +and Rannala 2005) that an analytical result is given. However, its proof +is very short and seems somehow incomplete. To help readers better +understand it, I follow (Yang and Rannala 2005) to give a complete +proof. Note that there might be a little confusion in the notation used +at the corresponding part of the original paper (Yang and Rannala 2005) +where $y$ indicates a variable in some cases but the value it takes in +other cases. This is clarified in the following solution. + +According to CLT, + +$$X\sim Normal\left( \frac{1}{2}n,\frac{1}{4}n \right).$$ + +According to the problem statement, the posterior of $\theta$ is given +by + +$$\theta|x\sim beta(x + 1,n - x + 1).$$ + +According to CLT, when $n \rightarrow \ \infty$, the above posterior +converges to +$Normal\left( \frac{x}{n},\frac{\frac{x}{n}\left( 1 - \frac{x}{n} \right)}{n} \right)$. + +Define a new variable $Y = \frac{X}{n}.$ We have when +$n \rightarrow \infty$,\ +$$\theta|X\sim Normal\left( Y,\frac{Y(1 - Y)}{n} \right).$$ + +It follows that + +$${P_{1} = P\left( \theta < \frac{1}{2} \middle| X \right) +}{= \Phi\left( \frac{\frac{1}{2} - Y}{\sqrt{\frac{Y(1 - Y)}{n}}} \right).}$$ + +Denote the CDF and PDF of standard normal distribution by $\Phi,\ \phi$ +respectively. Hence, + +$$\begin{array}{r} +\frac{dP_{1}}{dy} = \left( \Phi\left( \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}} \right) \right)^{'} = \phi\left( \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}} \right)\left( \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}} \right)^{'}. +\end{array}$$ + +Define + +$$\begin{array}{r} +a = \Phi^{- 1}\left( P_{1} \right) = \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}}.(8.2) +\end{array}$$ + +Substituting Eq. (8.2) into Eq. (8.1), we have + +$$\begin{array}{r} +\frac{dP_{1}}{dy} = \phi(a)\left( \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}} \right)^{'}.(8.3) +\end{array}$$ + +Calculate the derivative of $\Phi^{- 1}\left( P_{1} \right)$ w.r.t. $y$ +as follows + +$$ +\begin{align*} +\left( \frac{\frac{1}{2} - y}{\sqrt{\frac{y(1 - y)}{n}}} \right)^{'} &= \frac{\left( \frac{1}{2} - y \right)^{'}\sqrt{\frac{y(1 - y)}{n}} - \left( \frac{1}{2} - y \right)\left( \sqrt{\frac{y(1 - y)}{n}} \right)^{'}}{\left( \sqrt{\frac{y(1 - y)}{n}} \right)^{2}} \\ +&= n \times \frac{- \sqrt{\frac{y(1 - y)}{n}} - \left( \frac{1}{2} - y \right) \times \frac{1}{2} \times \frac{\left( y(1 - y) \right)^{'}}{n\sqrt{\frac{y(1 - y)}{n}}}\ }{y(1 - y)} \\ +&= \frac{- \sqrt{y(1 - y)} - \frac{1}{2}\left( \frac{1}{2} - y \right)(1 - 2y)\left( y(1 - y) \right)^{- \frac{1}{2}}\ }{y(1 - y)} \\ +&= \frac{- 4y(1 - y) - (1 - 2y)^{2}\ }{4n^{- \frac{1}{2}}\left( (1 - y)y \right)^{\frac{3}{2}}} \\ +&= \frac{- 1}{4\ n\ \left( \frac{(1 - y)y}{n} \right)^{\frac{3}{2}}}.(8.4) +\end{align*} +$$ + +According to Eq. (8.2), we have + +$$ +\begin{array}{r} +a^{2}y(1 - y) = n\left( \frac{1}{2} - y \right)^{2}.(8.5) +\end{array} +$$ + +So + +$$\left( n + a^{2} \right)y^{2} - \left( n + a^{2} \right)y + \frac{n}{4} = 0.$$ + +Thus + +$$\begin{array}{r} +\frac{y(1 - y)}{n} = \frac{1}{4\left( n + a^{2} \right)}.(8.6) +\end{array}$$ + +Plugging Eqs. (8.4) and (8.6) into Eq. (8.2), we have + +$$ +\begin{align*} +\frac{dP_{1}}{dy} &= \phi(a) \times \frac{-1}{4\ n\ \left( \frac{(1 - y)y}{n} \right)^{\frac{3}{2}}} \\ +&= \phi(a) \times \frac{-1}{4n\ \left( \frac{1}{4\left( n + a^{2} \right)} \right)^{\frac{3}{2}}} \\ +&= \phi(a) \times \left( - 2n^{-1} \right) \times \left( n + a^{2} \right)^{\frac{3}{2}} \\ +&= \phi(a) \times \left( - 2\sqrt{n} \right) \times \left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}. +\end{align*} +$$ + +Hence + +$$\left| \frac{dP_{1}}{dy} \right| = \phi(a) \times \left( 2\sqrt{n} \right) \times \left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}.$$ + +Further, it can be shown that + +$$\begin{array}{r} +f_{Y}(y) = \frac{1}{\sqrt{2\pi \times \frac{1}{4n}}}e^{{- 2n\left( y - \frac{1}{2} \right)}^{2}} = \sqrt{\frac{2n}{\pi}}e^{{- 2n\left( y - \frac{1}{2} \right)}^{2}}.(8.7) +\end{array}$$ + +Plugging Eq. (8.6) into Eq. (8.5), we have + +$$\begin{array}{r} +\left( \frac{1}{2} - y \right)^{2} = \frac{a^{2}}{4\left( n + a^{2} \right)}.(8.8) +\end{array}$$ + +Plugging Eq. (8.8) into Eq. (8.7) and eliminating $y$, we have + +$$f\left( y(P_{1}) \right) = \sqrt{\frac{2n}{\pi}}e^{- 2n\frac{a^{2}}{4\left( n + a^{2} \right)}}.$$ + +Hence, + +$$ +\begin{align*} +f(P_{1}) &= f_{Y}(y(P_{1})) \times \left| \frac{dy}{dP_{1}} \right| \\ +&= \frac{\sqrt{\frac{2n}{\pi}}e^{-2n\frac{a^{2}}{4(n + a^{2})}}}{\phi(a) \times (2\sqrt{n}) \times \left(1 + \frac{a^{2}}{n}\right)^{\frac{3}{2}}} \\ +&= \frac{e^{-\frac{na^{2}}{2(n + a^{2})}}}{\phi(a) \times \sqrt{2\pi} \times \left(1 + \frac{a^{2}}{n}\right)^{\frac{3}{2}}} = \frac{e^{-\frac{n(\Phi^{-1}(P_{1}))^{2}}{2(n + (\Phi^{-1}(P_{1}))^{2})}}}{\phi(\Phi^{-1}(P_{1})) \times \sqrt{2\pi} \times \left(1 + \frac{(\Phi^{-1}(P_{1}))^{2}}{n}\right)^{\frac{3}{2}}}. +\end{align*} +$$ + +It thus follows that + +$${\lim_{n \rightarrow \infty}{f\left( P_{1} \right)} = \lim_{n \rightarrow \infty}\frac{e^{- \frac{na^{2}}{2\left( n + a^{2} \right)}}}{\phi(a) \times \sqrt{2\pi} \times \left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}} +}{= \lim_{n \rightarrow \infty}\frac{e^{- \frac{na^{2}}{2\left( n + a^{2} \right)}}}{\frac{1}{\sqrt{2\pi}}e^{- \frac{a^{2}}{2}} \times \sqrt{2\pi} \times \left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}} +}{= \lim_{n \rightarrow \infty}\frac{e^{- \frac{na^{2}}{2\left( n + a^{2} \right)} + \frac{a^{2}}{2}}}{\left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}} +}{= \lim_{n \rightarrow \infty}\frac{e^{\frac{a^{4}}{2\left( n + a^{2} \right)}}}{\left( 1 + \frac{a^{2}}{n} \right)^{\frac{3}{2}}} +}{= 1. +}$$ + +The R code for simulation can be found in *8.4.R*. + +```R +get_lnl <- function(p, n, x){ + lnl <- x*log(p) + (n-x)*log(1-p) +} +integrand <- function(k) exp(get_lnl(k,n=n,x=x)) +########################################### +p <- 0.5 +n <- 1000 +n_sim <- 1000 + +marginal_lks <- numeric(n_sim) + +for(i in 1:n_sim){ + x <- rbinom(1, n, p) + i1 <- integrate(integrand, 0,1/2) + i2 <- integrate(integrand, 1/2,1) + marginal_lk <- i1$value/(i1$value+i2$value) + marginal_lks[i] <- marginal_lk +} + +pdf(""8.4-1.pdf"") +hist(marginal_lks, breaks=30) +dev.off() +``` + +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.6.md",".md","2504","86","**Solution.** + +I choose to use RevBayes (Hohna et al. 2016), the so-called new +generation of MrBayes (MrBayes is no longer updated). The following +takes JC69 as an example (see ""JC69.revbayes""). More information can be +found at RevBayes' tutorial website at +. As to the alignment, +""sample.fasta"" given in the folder ""data/"" of the current chapter is the +same as the one used in Problem 4.6 (""rbcL.nogaps_amb.fas""). + +```RevBayes +#RevBayes +# load alignment +data <- readDiscreteCharacterData(""sample.fasta"") +# taxon info +num_taxa <- data.ntaxa() +num_branches <- 2 * num_taxa - 3 +taxa <- data.taxa() +# moves +moves = VectorMoves() +monitors = VectorMonitors() +# transition rate matrix +Q <- fnJC(4) +# topology prior +topology ~ dnUniformTopology(taxa) +# NNI+SPR +moves.append( mvNNI(topology, weight=num_taxa) ) +moves.append( mvSPR(topology, weight=num_taxa/10.0) ) +for (i in 1:num_branches) { + br_lens[i] ~ dnExponential(10.0) + moves.append( mvScale(br_lens[i]) ) +} +TL := sum(br_lens) +# phylogeny +psi := treeAssembly(topology, br_lens) + +# set up everything +seq ~ dnPhyloCTMC(tree=psi, Q=Q, type=""DNA"") +seq.clamp(data) +mymodel = model(Q) +monitors.append( mnModel(filename=""output/JC69/sample_JC.log"", printgen=10) ) +monitors.append( mnFile(filename=""output/JC69/sample_JC.trees"", printgen=10, psi) ) +monitors.append( mnScreen(printgen=100, TL) ) +mymcmc = mcmc(mymodel, monitors, moves) + +# run mcmc +mymcmc.burnin(1000,100) +mymcmc.run(generations=2000) +q() +``` + +We can further summarize the result by the following command where the +MAP tree is generated. + +```RevBayes +#RevBayes +# summarize +treetrace = readTreeTrace(""output/JC69/sample_JC.trees "", treetype=""non-clock"") +map_tree = mapTree(treetrace,""output/JC69/sample_JC_MAP.tree"") +``` + +Now, open the file ""output/JC69/sample_JC.log"" in Tracer. You should see +something like the following. + +

+ +The MAP tree is displayed as follows. + +

+ +Another script, ""GTR+G5.revbayes"" is used for tree construction under +the model GTR+G5. Specifically, to enable the gamma rate variation in +RevBayes, it is needed to specify the following. + +```revBayes +#RevBayes +alpha ~ dnUniform( 0.0, 10 ) +sr := fnDiscretizeGamma( alpha, alpha, 5 ) # discrete gamma w 5 categories +moves.append( mvScale(alpha, weight=2.0) ) +``` + +**Bonus question.** + +Compare the estimated parameters by RevBayes with those by IQ-Tree or +raxml-ng in Problem 4.6 under the same model. What do you see? +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/8.2.md",".md","268","10","

+ +

+ +**Solution.** + +Unfortunately, I see the version 3.1 of MrBayes at nowhere. If you +happen to know any old-fashioned Bayesian phylogenetics person who has not +updated their software for a decade, please let them know this exercise. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/scripts/8.3.R",".R","476","21","get_lnl <- function(p, n, x){ + lnl <- x*log(p) + (n-x)*log(1-p) +} +########################################### +p <- 0.5 +n <- 10000 +n_sim <- 1000 + +marginal_lks <- numeric(n_sim) +for(i in 1:n_sim){ + x <- rbinom(1, n, p) + ps <- c(0.4, 0.6) + lnls <- sapply(ps, get_lnl, n=n, x=x) + #print(c(lnls[2]-lnls[1], 1/(1 + exp(lnls[2] - lnls[1])))) + lk <- 1/(1 + exp(lnls[2] - lnls[1])) + marginal_lks[i] <- lk +} +pdf(""8.3-1.pdf"") +hist(marginal_lks, breaks=30) +dev.off() +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C8 Bayesian phylogenetics/scripts/8.4.R",".R","491","23","get_lnl <- function(p, n, x){ + lnl <- x*log(p) + (n-x)*log(1-p) +} +integrand <- function(k) exp(get_lnl(k,n=n,x=x)) +########################################### +p <- 0.5 +n <- 1000 +n_sim <- 1000 + +marginal_lks <- numeric(n_sim) + +for(i in 1:n_sim){ + x <- rbinom(1, n, p) + i1 <- integrate(integrand, 0,1/2) + i2 <- integrate(integrand, 1/2,1) + marginal_lk <- i1$value/(i1$value+i2$value) + marginal_lks[i] <- marginal_lk +} + +pdf(""8.4-1.pdf"") +hist(marginal_lks, breaks=30) +dev.off() +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C11 Neutral and adaptive protein evolution/11.3.md",".md","337","20","

+ +

+ +**Solution.** + +Run codeml. Identify that Branch 2 is the branch that connects Node 22 +(the clade of colobine monkeys) and its parent (Node 21) in the file +*rst*. + +

+ +

+ +The nucleotide/codon changes on Branch 2 are shown as follows. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C11 Neutral and adaptive protein evolution/11.2.md",".md","623","24","

+ +

+ +**Solution.** + +According to the problem statement, label the following branch as ""#1"" +in the tree, which is the so-called foreground lineage in the analysis. + +

+ +

+ +Then, run codeml under the branch model (model=2, NSsites=0) and +branch-site (model=2, NSsites=2) model. The positively selected sites +identified by the NEB and BEB methods are given as follows \[but note +that BEB is more reliable and is suggested to use; see (Yang 2014a)\]. +More detailed results are given in *data/11.2/B-mlc* and +*data/11.2/BS-mlc*. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C11 Neutral and adaptive protein evolution/11.4.md",".md","2285","62","

+ +

+ +**Solution.** + +Note that + +$${P(Class = 0) = p_{0} = 0.5,}$$ + +$${P(Class = 1) = p_{1} = 0.3,}$$ + +$${P(Class = 2a) = \frac{\left( 1\ - \ p_{0}\ - \ p_{1} \right)p_{0}}{p_{0}\ + \ p_{1}} = 0.125,}$$ + +$${P(Class = 2b) = \frac{\left( 1\ - \ p_{0}\ - \ p_{1} \right)p_{1}}{p_{0}\ + \ p_{1}} = 0.075.}$$ + +To simulate codon sequences under the branch-site model, we need to use +the program evolverNSbranchsites from PAML, which however is not +compiled in the default mode of installation. One has to type the +following in Bash to compile evolver to do codon sequence simulation +under the branch-site model (as well as the branch and site models if +necessary). The control files used to simulate sequences under the null +hypothesis are provided in the folder ""C11/data/11.4/"". + +``` +cd ./paml/src/ +cc -O2 -DCodonNSbranches -o evolverNSbranches evolver.c tools.c -lm +cc -O2 -DCodonNSsites -o evolverNSsites evolver.c tools.c -lms | +cl -O2 -DCodonNSbranchsites -o evolverNSbranchsites evolver.c tools.c +-lm +``` + +After simulation of sequence evolution, to set the control file +codeml.ctl for the unconstrained analysis, one needs to make sure +$model = 2,Nsites = 2,fix\_ omega = 0.$ To set it for the constrained +analysis (under the null hypothesis), one needs to change the above +settings to $model = 2,Nsites = 2,fix\_ omega = 1,omega = 1.$ The +control files as well as the results are provided in the folder +""C11/data/11.4/"". + +The result is summarized as follows. Note that datasets where +$2\Delta L < 0$ are discarded. + +

+ +

+ +As follows the histograms of the $2\Delta\mathcal{l}$, the likelihood +ratio test statistic, for the branch-site test are plotted against the +curve of $\chi_{1}^{2}$ density. Note that datasets with $2\Delta L = 0$ +are not included in the plot and that sequence length indicates the +number of **codons** instead of that of nucleotides. + +The result is generally supportive of the conclusions of (Yang and Dos +Reis 2011), but note the differences in the proportions of datasets +where $2\Delta L = 0$ and where $2\Delta L = 0$ which suggests the +impact of tree topologies and branches to test. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C11 Neutral and adaptive protein evolution/11.1.md",".md","268","10","

+ +

+ +**Solution.** + +Download the files *bigmhc.\** from (Yang 2014b). Using PAML v4.10.3, my +result is pretty similar to Fig. 11.4 in (Yang 2014a), the only small +difference being positively selected sites. See the folder *data/11.4/*. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/5.1-5.4.md",".md","243","13","$${\color{red} +To\ make\ the\ result\ more\ \“interesting\”,\ I\ change\ in\ all\ exercises\ of\ Chapter\ 5\ the\ number\ of\ sites\ from\ 1000\ to\ 100. +} +$$ + +

+ +

+ +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/scripts/5.2.sh",".sh","920","41","#! /bin/bash + + +############################################### +nsim=100 +trees=(1.tre 2.tre 3.tre) +model=K80 +iqtree=iqtree +mpboot=mpboot +CAL=~/project/Yang/scripts/cal_partition_dist.R + + +############################################### +for tree in ${trees[@]}; do + count_ml=0; count_ml2=0; count_mp=0 + echo $tree + for i in `seq $nsim`; do + tree_str=`cat $tree` + sed -i ""7s/.*/$tree_str/"" model.dat + evolver 5 model.dat >/dev/null + + mpboot -st DNA -s mc.txt -pre mp >/dev/null + if [ `Rscript $CAL mp.treefile $tree` == ""T"" ]; then + count_mp=$(($count_mp+1)) + fi + + iqtree -st DNA -s mc.txt -m $model -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml=$(($count_ml+1)) + fi + + iqtree -st DNA -s mc.txt -m JC69 -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml2=$(($count_ml2+1)) + fi + done + echo -e ""$count_mp\t$count_ml\t$count_ml2"" +done + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/scripts/5.3.sh",".sh","988","43","#! /bin/bash + + +############################################### +nsim=100 +trees=(1.tre 2.tre 3.tre) +model=JC69+G5 +iqtree=iqtree +mpboot=mpboot +CAL=cal_partition_dist.R + + +############################################### +for tree in ${trees[@]}; do + count_ml=0; count_ml2=0; count_mp=0 + echo $tree + for i in `seq $nsim`; do + #iqtree --alisim test -m $model -st DNA -t $tree --length 1000 -af fasta >/dev/null + tree_str=`cat $tree` + sed -i ""7s/.*/$tree_str/"" model.dat + evolver 5 model.dat >/dev/null + + mpboot -st DNA -s mc.txt -pre mp >/dev/null + if [ `Rscript $CAL mp.treefile $tree` == ""T"" ]; then + count_mp=$(($count_mp+1)) + fi + + iqtree -st DNA -s mc.txt -m $model -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml=$(($count_ml+1)) + fi + + iqtree -st DNA -s mc.txt -m JC69 -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml2=$(($count_ml2+1)) + fi + + done + echo -e ""$count_mp\t$count_ml\t$count_ml2"" +done + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/scripts/5.4.sh",".sh","818","37","#! /bin/bash + + +############################################### +nsim=100 +trees=(2.tre 3.tre) +model=JC69 +iqtree=iqtree +mpboot=mpboot +CAL=cal_partition_dist.R + + +############################################### +for tree in ${trees[@]}; do + count_ml=0; count_ml2=0; count_mp=0 + echo $tree + for i in `seq $nsim`; do + #iqtree --alisim test -m $model -st DNA -t $tree --length 1000 -af fasta >/dev/null + tree_str=`cat $tree` + sed -i ""7s/.*/$tree_str/"" model.dat + evolver 5 model.dat >/dev/null + + mpboot -st DNA -s mc.txt -pre mp >/dev/null + if [ `Rscript $CAL mp.treefile $tree` == ""T"" ]; then + count_mp=$(($count_mp+1)) + fi + + iqtree -st DNA -s mc.txt -m $model -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml=$(($count_ml+1)) + fi + done + echo -e ""$count_mp\t$count_ml"" +done + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/scripts/5.1.sh",".sh","754","37","#! /bin/bash + + +############################################### +nsim=100 +#trees=(4.tre) +trees=(1.tre 2.tre 3.tre) +model=JC69 +iqtree=iqtree +mpboot=mpboot +CAL=cal_partition_dist.R + + +############################################### +for tree in ${trees[@]}; do + count_ml=0; count_ml2=0; count_mp=0 + echo $tree + for i in `seq $nsim`; do + tree_str=`cat $tree` + sed -i ""7s/.*/$tree_str/"" model.dat + evolver 5 model.dat >/dev/null + + mpboot -st DNA -s mc.txt -pre mp >/dev/null + if [ `Rscript $CAL mp.treefile $tree` == ""T"" ]; then + count_mp=$(($count_mp+1)) + fi + + iqtree -st DNA -s mc.txt -m $model -pre ml -quiet -redo + if [ `Rscript $CAL ml.treefile $tree` == ""T"" ]; then + count_ml=$(($count_ml+1)) + fi + done + echo -e ""$count_mp\t$count_ml"" +done + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C5 Comparison of phylogenetic methods and tests on trees/scripts/cal_partition_dist.R",".R","317","15","#! /usr/bin/env Rscript + +########################################## +suppressWarnings({ + library(ape) +}) + +########################################## +args <- commandArgs(trailingOnly=TRUE) +tree1 <- read.tree(args[1]) +tree2 <- read.tree(args[2]) +dist <- dist.topo(tree1,tree2) +cat(ifelse(dist[1]==0, ""T"", ""F""),""\n"") + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/9.6.md",".md","618","17","

+ +

+ +**Solution.** + +I use BP&P v3.4a (Yang 2015) for this analysis. Note that for species delimitation, +users should set speciesdelimitation=1 and speciestree=0 in the control file, thus +the mode “A10”. The results of using one to four loci are displayed as follows where +the posterior probabilities of the two models are given. Note that Model 0 denotes the +hypothesis that all belong to the same species while Model 1 denotes the hypothesis that +the species delimitation should be as indicated in the “Imap” file with species D and E. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/9.2.md",".md","736","25","

+ +

+ +**Solution.** + +Denote the probability that the gene tree has the topology +$\left( \left( a_{1},a_{2} \right),b \right)$ as $P_{same}$ and the +probability of other gene tree topologies as $P_{diff}$. According to +the problem statement, we have + +$$P_{diff} = P_{no\_ coal} \times P_{joining},$$ + +where $P_{no\_ coal}$ is the probability that sequences $a_{1}$ and +$a_{2}$ do not coalesce in population $A$, and $P_{joining}$ indicates +the probability that random joining of all gene sequences in population +$AB$. It is not difficult to see the following + +$${P_{no\_ coal} = e^{- \frac{\tau}{2N}}, +}{P_{joining} = \frac{2}{3}.}$$ + +So + +$$P_{same} = 1 - P_{diff} = 1 - \frac{2}{3}e^{- \frac{\tau}{2N}}.$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/9.4.md",".md","3967","86","

+ +

+ +**Solution.** + +a\) + +According to the problem statement, the likelihood given the species +tree $S_{0}$ is given as + +$$ +\begin{align*} +f\left( G,t \middle| S_{0},\Theta \right) &= \frac{2}{\theta_{0}}\frac{2}{\theta_{1}}e^{- \frac{2}{\theta_{1}}\left( t_{1} - \tau_{1} \right) - \frac{2}{\theta_{0}}\left( t_{0} - \tau_{0} \right)} \\ +&= \frac{2}{\theta_{0}}e^{- \frac{2}{\theta_{0}}\left( t_{0} - \tau_{0} \right)} \times \frac{2}{\theta_{1}}e^{- \frac{2}{\theta_{1}}\left( t_{1} - \tau_{1} \right)}. +\end{align*} +$$ + +According to the problem statement, let $\tau_{1} \rightarrow t_{1}$ and $\theta_{1} = k\left( t_{1} - \tau_{1} \right) \rightarrow 0.$ Thus, when $\tau_{1} \rightarrow t_{1}$, we have + +$$f\left( G,t \middle| S_{0},\Theta \right) = \frac{2}{\theta_{0}}e^{- \frac{2}{\theta_{0}}\left( t_{0} - \tau_{0} \right)} \times \frac{2}{\theta_{1}}e^{- \frac{2}{k}}$$ + +which approaches infinite. + +b\) + +For the three wrong species trees $S_{1},S_{2},S_{3}$, the likelihood is +given as + +$$ +\begin{align*} +f\left( G,t \middle| S_{1},\Theta \right) &= f\left( G,t \middle| S_{2},\Theta \right) = f\left( G,t \middle| S_{3},\Theta \right) \\ +&= e^{- \frac{2}{\theta_{1}}\left( \tau_{0} - \tau_{1} \right)} \times \frac{2}{\theta_{0}}e^{- \frac{2}{\theta_{0}} \times 3\left( t_{1} - \tau_{0} \right)} \times \frac{2}{\theta_{0}}e^{- \frac{2}{\theta_{0}}\left( t_{0} - t_{1} \right)} \\ +&= e^{- \frac{2}{\theta_{1}}\left( \tau_{0} - \tau_{1} \right)} \times \left( \frac{2}{\theta_{0}} \right)^{2}e^{- \frac{2}{\theta_{0}}\left( 3t_{1} - 3\tau_{0} + t_{0} - t_{1} \right)}. +\end{align*} +$$ + +Because $t_{1} \geq \tau_{0}$, it is easy to see that the expression +$3t_{1} - 3\tau_{0} + t_{0} - t_{1}$ is bounded below $t_{0} - t_{1}.$ + +It is not difficult to realize that the maximum of +$f\left( G,t \middle| S_{1},\Theta \right)$ is achieved when its first +term $f\left( G,t \middle| S_{1},\Theta \right)$ and second term +$\left( \frac{2}{\theta_{0}} \right)^{2}e^{- \frac{2}{\theta_{0}}\left( 3t_{1} - 3\tau_{0} + t_{0} - t_{1} \right)}$ +both independently reach its maximum. The following show that this +maximum can be achieved. + +Because $\theta_{1} > 0$, the first term of +$f\left( G,t \middle| S_{1},\Theta \right)$, which is +$e^{- \frac{2}{\theta_{1}}\left( \tau_{0} - \tau_{1} \right)}$, reaches +the maximum whenever $\tau_{0} = \tau_{1}.$ As to the second term +$\left( \frac{2}{\theta_{0}} \right)^{2}e^{- \frac{2}{\theta_{0}}\left( 3t_{1} - 3\tau_{0} + t_{0} - t_{1} \right)}$ +which does not involve the unknown $\tau_{1}$, its log-likelihood can be +calculated as + +$${\mathcal{l} = \log\left( \left( \frac{2}{\theta_{0}} \right)^{2}e^{- \frac{2}{\theta_{0}}\left( 3t_{1} - 3\tau_{0} + t_{0} - t_{1} \right)} \right) +}{= 2\log\left( \frac{2}{\theta_{0}} \right) - \frac{2}{\theta_{0}}\left( 3t_{1} - 3\tau_{0} + t_{0} - t_{1} \right)\text{.}}$$ + +Noting that $\tau_{0}$ has to meet the requirement +$\tau_{0} \leq t_{1}$, it is not difficult to realize that the maximum +of $\mathcal{l}$ is reached when $\tau_{0} = t_{1}$, as also evident in +Problem 9.3 and Section 9.4.3.2 of (Yang 2014a). + +Accordingly, by setting it to zero and calculating the derivative w.r.t +to $\theta_{0}$, we obtain + +$$ +\begin{align*} +\widehat{\theta}_0 &= 3t_1 - 3\widehat{\tau}_0 + t_0 - t_1 \\ +&= t_0 - t_1. +\end{align*} +$$ + +Hence, the maximum of the likelihood function is given as + +$$ +\begin{align*} +f\left( G,t \middle| S_{1},\tau_{0} = \tau_{1} = t_{1},\theta_{0} = t_{0} - t_{1} \right) &= e^{- \frac{2}{\theta_{1}}\left( \tau_{0} - \tau_{1} \right)} \times \left( \frac{2}{\theta_{0}} \right)^{2}e^{- \frac{2}{\theta_{0}}\left( t_{0} - t_{1} \right)} \\ +&= 1 \times \left( \frac{2}{t_{0} - t_{1}} \right)^{2}e^{- \frac{2}{t_{0} - t_{1}}\left( t_{0} - t_{1} \right)} \\ +&= \left( \frac{2}{t_{0} - t_{1}} \right)^{2}e^{- 2}. +\end{align*} +$$ + +Thus, the singularity problem does not exist for the three wrong +three-species trees $S_{1},S_{2},S_{3}$. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/9.1.md",".md","431","16","

+ +

+ +**Solution.** + +If you were as lazy as me, you could simply use the following R code for the purpose. Note that the R packages ape (Paradis and Schliep 2019) and Phangorn (Schliep 2011) need to be installed. + +```R +#! /usr/bin/env Rscript +library(ape) +library(phangorn) +coalescent_tree <- rcoal(10) +simSeq(coalescent_tree, type=""DNA"", l=1000) # the default it JC69, confirmed by Klaus Schliep +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/scripts/9.5.R",".R","1101","34","# 9.5.R +#! /usr/bin/env Rscript +library(expm) +g <- function(m,theta){ + matrix(c(-2*m-2/theta,m,0,0,0, 2*m,-2*m,2*m,0,0, 0,m,-2*m-2/theta,0,0, 2/theta,0,0,-m,m, 0,0,2/theta,m,-m), ncol=5) +} +h0 <- function(t){ + theta<-0.005; m<-4*M/theta + sum(sapply(c(1,3), function(x){ init * 2/theta * expm(g(m=m,theta=theta)*t)[1:3,x]})) +} +h1 <- function(t) { + theta <- 0.005; theta_a <- 0.003; m <- 4*M/theta; m_a <- 4*M/theta_a + dexp(t-tau, 2/theta_a) * sum(sapply(c(1,2,3), function(x){ init * expm(g(m=m,theta=theta)*tau)[1:3,x]})) +} +h <- function(t, tau=0.005) if(t f0, (0,1,0) -> f1 +for(i in 1:ncol(inits)){ + init <- inits[,i] + p <- Vectorize(h) + M <- 0.01 + curve(p, from=0, to=2*tau, col=""blue"") + integrate(p, lower=0, upper=1) + M <- 100000 + curve(p, from=0, to=2*tau, add=T, col=""red"") + legend(x = ""topright"", legend=c(""M=0.01"", ""M=10""), + fill = c(""blue"",""red"") + ) +} +dev.off() +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/scripts/9.1.R",".R","182","6","#! /usr/bin/env Rscript +library(ape) +library(phangorn) +coalescent_tree <- rcoal(10) +simSeq(coalescent_tree, type=""DNA"", l=1000) # need to further check if the default model is JC69. +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C9 Coalescent theory and species trees/scripts/9.5-1.R",".R","849","25","library(expm) + +# important to note the following +t=1.1; tau=1; theta=1; m=10000 # (m as if infinite) + +calc_Q <- function(m, t){ + matrix(c(-2*(m+1/theta), 2*m, 0, 2/t, 0, + m, -2*m, m, 0, 0, + 0, 2*m, -2*(m+1/theta), 0, 2/theta, + 0, 0, 0, -m, m, + 0, 0, 0, m, -m + ), + byrow=T, ncol=5 + ) +} + +# assume m=10000 (big enough as if infinite), and theta=1 (i use symbol t in the code for simplicity) +Q <- calc_Q(m=10^4, t=1) +P = expm(Q) +rownames(P) = colnames(P) = c(""S11"", ""S12"", ""S22"", ""S1"", ""S2"") +print(P) + +print(c(""for f0"", ""Eq. 9.50 in Yang 2014"", ""analytical calculation based on our solutions"")) +print(c(""f0 (t<=tau):"", 2/theta * (P[1,1]+P[1,3]), 1/theta*exp(-1/theta))) +print( c(""f0 (t>tau):"", sum(P[1,1:3]) * 2/theta * exp(-2/theta*(t-tau)), exp(-1/theta*tau)*2/theta*exp(-2*(t-tau)/theta)) )","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/2.3.md",".md","110","8","

+ +

+ + **Solution.** + +It is easy to verify using the result of Problem 2.1. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/2.5.md",".md","1404","50","

+ +**Solution.** + +I take the liberty to use AliSim instead of EVOLVER to generate the +sequence. + +```Bash +n=1000 +n_codons=(50 100 200 300 500 1000) + +for n_codon in ${n_codons[@]}; do + echo -e ""# of codons:\t$n_codon"" + [ -f deltaLL$n_codon.list ] && rm deltaLL$n_codon.list + for i in `seq $n`; do + mod=`echo ""$i%100""|bc` + [ $mod == 1 ] && echo $i >&2 + length=`expr 3 \* $n_codon` + iqtree --alisim alignment_codon -m 'MG2K{1,2}+FQ' --length $length -t tree.nwk -af phy -quiet + # omega to be estimated + sed -i 's/fix_omega.*/fix_omega = 0/' codeml.ctl + codeml >/dev/null + lnl1=`grep -P 'lnL' mlc | awk '{print $(NF-1)}'` + # omega fixed as 1.0 + sed -i 's/fix_omega.*/fix_omega = 1/' codeml.ctl + codeml >/dev/null + lnl0=`grep -P 'lnL' mlc | awk '{print $(NF-1)}'` + echo ""scale=2; 2 * ($lnl1 - $lnl0)"" | bc + done > deltaLL$n_codon.list + echo +done +``` + +The following result shows that with 100 codons the chi-square +approximation is good enough but even with 50 codons it is not fine. +This can be visualized by using the following R code. + +```R +par(mfrow=c(2,3)) +for(i in c(50,100,200,300,500,1000)) { + a<-unlist(read.table(paste0(""deltaLL"",i,"".list""))) + hist(a, freq=F, breaks=80,ylim=c(0,2), xlim=c(0,10), main=paste0(""# of codons: "", i), xlab="""") + curve(dchisq(x,df=1),add=T, col=""RED"") } +} +``` + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/2.1-2.2.md",".md","99","7","

+ + +

+ +See Problems 2.1-2.2 of (Yang 2006). +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/2.4.md",".md","677","29","

+ +**Solution.** + +To save time, I use only 100 replicates by setting ndata = 100 in +*codeml.ctl*. Then, use the following R code to obtain the mean and +variance of $\widehat{\omega}$ for data sets simulated with each tree +length. My output is shown as follows. + +```R +d <- read.table(""omega.tab"", header=T); +lapply(d, function(x){cat(mean(x), var(x), ""\n"", sep=""\t"")}) +``` + +

+ +

+ +```Bash +for i in 0.1 0.3 0.5 1 1.5 2 3; do + echo $i + sed ""/tree length/s/^[^ ]\+/$i/"" -i MCcodon.dat + evolver 6 MCcodon.dat >/dev/null + codeml >/dev/null + grep omega mlc | awk '{print $NF}' > omega-$i.list + echo +done +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/scripts/2.5.sh",".sh","895","31","#! /bin/bash + + +################################################ +n=1000 +n_codons=(100 200 300 500 1000) +#n_codons=(50 100 200 300 500 1000) + + +################################################ +for n_codon in ${n_codons[@]}; do + echo -e ""# of codons:\t$n_codon"" + [ -f deltaLL$n_codon.list ] && rm deltaLL$n_codon.list + for i in `seq $n`; do + mod=`echo ""$i%100""|bc` + [ $mod == 1 ] && echo $i >&2 + length=`expr 3 \* $n_codon` + iqtree --alisim alignment_codon -m 'MG2K{1,2}+FQ' --length $length -t tree.nwk -af phy -quiet + # omega to be estimated + sed -i 's/fix_omega.*/fix_omega = 0/' codeml.ctl + codeml >/dev/null + lnl1=`grep -P 'lnL' mlc | awk '{print $(NF-1)}'` + # omega fixed as 1.0 + sed -i 's/fix_omega.*/fix_omega = 1/' codeml.ctl + codeml >/dev/null + lnl0=`grep -P 'lnL' mlc | awk '{print $(NF-1)}'` + echo ""scale=2; 2 * ($lnl1 - $lnl0)"" | bc + done > deltaLL$n_codon.list + echo +done +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C2 Models of amino acid and codon/scripts/2.4.sh",".sh","209","9","for i in 0.1 0.3 0.5 1 1.5 2 3; do + echo $i + sed ""/tree length/s/^[^ ]\+/$i/"" -i MCcodon.dat + evolver 6 MCcodon.dat >/dev/null + codeml >/dev/null + grep omega mlc | awk '{print $NF}' > omega-$i.list + echo +done +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/10.4.md",".md","165","13","

+ +

+ +**Solution.** + +It looks that IR model yields slightly larger time estimates in some +nodes. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/10.5.md",".md","764","28","

+ +

+ +**Solution.** + +Use the following Bash code to summary the results and to generate the +graphs where the x-axis indicates the posterior times obtained by DNA +and the y-axis indicates those obtained with protein sequences. + +```Bash +for i in 2 3; do + cd clock${i}_AA/ori/ + scripts/get_bl_CI_interval.sh FigTree.tre --minmax --format mcmctree --header > time-ci.tbl + cd ../../ + cd clock${i}_DNA/ori/ + scripts/get_bl_CI_interval.sh FigTree.tre --minmax --format mcmctree --header > time-ci.tbl + cd ../../ + Rscript scripts/compare_age.R -i clock${i}_DNA/ori/time-ci.tbl -j clock${i}_AA/ori/time-ci.tbl -c blue -o clock${i}_DNAvsAA.pdf -m 0,2 +done +``` + +

+ +

+ +Left: IR (clock2); Right: AR (clock3) +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/10.3.md",".md","887","26","

+ +

+ +**Solution.** + +We run the analysis for only the independent rate (IR; clock2) and +correlated rate (AR; clock3) model. For global rate, obviously nothing +would change. I change the gamma priors for rate as ""rgene_gamma = 1 10"" +and set the gamma priors for sigma2 as ""sigma2_gamma = 10 1"" in the file +*mcmctree.ctl*. After MCMCTree run is finished, I use the following +script to summarize the result. + +```Bash +Bash scripts/get_bl_CI_interval.sh FigTree.tre --minmax --format mcmctree --header > time-ci.tbl +Rscript scripts/compare_age.R -i ori/time-ci.tbl -j change_rgene_sigma/time-ci.tbl -m 0,2 -c blue -o ci-compare.pdf +``` + +The results are displayed in the following graph for IR (left) and AR +(right), where the mean and 95% HPD interval are indicated between using +the original priors and the changed priors. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/10.2.md",".md","1039","30","

+ +

+ +**Solution.** + +See the data set Steiper2004 from C10 in (Yang 2014b). We take the +global clock as an example. Open *mcmctree.clock2.ctl*, the control file +for MCMCTree. + +1. HKY+G5: use HKY with five rate categories of discrete gamma + distribution. In Line 5, change to the alignment file separated as + five loci *Steiper2004ABCDE.txt*. In Line 8, set *ndata* = 5. Run + MCMCTree. + +2. JC69. On top of *mcmctree.clock2.ctl*, edit Line 13 to change model + = 0 and Line 14 to set alpha = 0. Run MCMCTree. + +The results, as compared to those shown in Table 10.1 in (Yang 2014a), +are summarized as follows (STR: strict rate or global rate; IR: +independent rate; AR: autocorrelated rate). The posteriors estimated +by treating the five genes as independent loci should yield narrower +CI intervals under independent or correlated rate models (but not the +global clock because for global clock applying independent loci does +not change any parameter). + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/10.1.md",".md","1094","40","

+ +

+ +**Solution** + +Download the mitochondrial genome sequences of *Homo sapiens*, *Pan +troglodytes*, *Gorrila gorilla*, *Pongo pygmaeus*, and *Pan paniscus* +from NCBI Genbank according to the accessions indicated in the study +(Horai et al. 1995), and have the 12s rRNA sequences extracted. Perform +a sequence alignment using your favourite software, and name the file as +*Horai1995.aln*. + +Write to the file *Horai1995.nwk* the following Newick-formatted tree: + +``` +(Pongo_pygmaeus,(Homo_sapiens,((Pan_troglodytes,Pan_paniscus),Gorrila_gorrila))); +``` + +I choose to use MEGA (Kumar et al. 2018) to perform the molecular test. + +

+ +

+ +For the model GTR, remember to choose the ""CUSTOM"" model and then input +""012345"". The results are displayed as follows. + +

+ +

+ +Note that there are $(2 \times 5 - 3) - 4 = 3$ constrained parameters +when a global clock is assumed hence a degree of freedom of 3. Use +""pchisq(2\*delta_lnL,3,lower.tail=F)"" in R to obtain the *P*-value. + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/scripts/compare_age.R",".R","2779","122","#! /usr/bin/env Rscript + + +###################################################################### +library('getopt') + + +###################################################################### +circle_cex <- 0.5 +pch <- 16 +point_col <- 'black' + + +###################################################################### +spec = matrix( + c( + 'infile1', 'i', 1, 'character', + 'infile2', 'j', 1, 'character', + 'outfile', 'o', 1, 'character', + 'minmax', 'm', 1, 'character', + 'color', 'c', 1, 'character', + 'list', 'l', 1, 'character', + 'noCI', 'n', 0, 'logical' + ), + byrow=T, ncol=4 +) + +opts = getopt(spec) +infile1 = opts$infile1 +infile2 = opts$infile2 +outfile = opts$outfile +minmax = opts$minmax +color = opts$color +noCI = opts$noCI + +lineages <- list() +lineage_list_s = opts$list + +if (is.null(infile1) | is.null(infile2) | is.null(outfile)){ + print(""infile or outfile not given! Exiting ......""); q() +} +if (is.null(minmax)){ + print(""minmax not given! Exiting ......""); q() +} +if (is.null(noCI)){ + noCI <- F +} +if (!is.null(lineage_list_s)){ + for(lineage_list in unlist(strsplit(lineage_list_s, ','))){ + lineages[[length(lineages)+1]] <- read.table(lineage_list, stringsAsFactors=F)$V1 + } +} +if(!is.null(color)){ + colors <- unlist(strsplit(color, "","")) +} + +min = as.numeric(unlist(strsplit(minmax, "",""))[1]) +max = as.numeric(unlist(strsplit(minmax, "",""))[2]) + + +###################################################################### +#Make up data +d1 <- read.table(infile1, header=T) +d2 <- read.table(infile2, header=T) + +d <- merge(d1, d2, by='node') +age1<-d$age.x +age2<-d$age.y +age1_min<-d$min.x +age2_min<-d$min.y +age1_max<-d$max.x +age2_max<-d$max.y + + +if (is.null(col)){ + col1<-as.character(d1$V5) + col2<-as.character(d2$V5) +} else{ + col1<-colors[1] + col2<-colors[1] +} + +if (noCI){ + circle_cex <- 1 + pch <- 16 + #point_col <- rgb(255, 0, 0, max = 255, alpha = 175, names = ""blue50"") + point_col <- rep(adjustcolor(colors[1], alpha.f = 0.75), length(d$node)) +} + + +if( length(lineages) != 0 ){ + for( i in 1:length(lineages) ){ + point_col[ which(d$node %in% lineages[[i]] ) ] <- adjustcolor(colors[i+1], alpha.f = 0.75) + } +} + + +###################################################################### +#The plot +pdf(outfile) + +#plot(age1, age2, pch=pch, cex=0.8, col=""black"", cex.axis=1.1, cex.lab=1.2) +#print(age1) +plot(age1, age2, pch=pch, cex=circle_cex, col=point_col, ylim=c(min,max), xlim=c(min,max), cex.axis=1.1, cex.lab=1.2, + ylab='', xlab='' +) + +if(! noCI){ + segments(age1_max, age2, age1_min, age2, lwd=0.5, col=col1) + segments(age1, age2_max, age1, age2_min, lwd=0.5, col=col2) + #legend(""topright"", legend=paste(""Study"",1:10),col=rainbow(length(pop.size)), pt.cex=1.5, pch=16) +} + +abline(0,1,col=""darkgrey"", lty=2, lwd=2) + +#axis(1,seq(0, 3000, 1000)) +#axis(2,seq(0, 3000, 1000)) + +dev.off() + + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C10 Molecular clock and estimation of species divergence times/scripts/get_bl_CI_interval.sh",".sh","1529","88","#! /bin/bash + + +############################################### +d=`dirname $0` +PROG=$d/get_bl_CI_interval.rb + +minmax_arg="""" +multiply_arg="""" +is_ci=false +format='' +is_header=false +exclude_list='' + + +############################################### +figtree_file=$1 + + +############################################### +while [ $# -gt 0 ]; do + case $1 in + -i) + figtree_file=$2 + shift + ;; + --minmax) + minmax_arg=""--minmax"" + ;; + --multiply) + multiply_arg=""--multiply $2"" + shift + ;; + --ci|--CI) + is_ci=true + ;; + --format|-f) + format=$2 + ;; + --header) + is_header=true + ;; + --exclude_list) + exclude_list=$2 + shift + ;; + esac + shift +done + + +############################################### +if [ -z $format ]; then + echo ""--format (mcmctree or revbayes) has to be specified! Exiting ......"" >&2 + echo """" + exit 1 +fi + + +############################################### +if [ $is_header == true ]; then + if [ $minmax_arg == ""--minmax"" ]; then + echo -e ""node\tage\tmin\tmax"" + else + echo -e ""node\tage\tinterval"" + fi +fi + +if [ ""$is_ci"" == true ]; then + minmax_arg='' +fi + +case $format in + mcmctree) + SED=$d/figtree_mcmctree_reformat.sed + ;; + revbayes) + SED=$d/figtree_revbayes_reformat.sed + #sed -f $d/figtree_revbayes_reformat.sed $figtree_file | ruby $PROG -i - $minmax_arg $multiply_arg + ;; +esac + +if [ -f ""$exclude_list"" ]; then + sed -f $SED $figtree_file | nw_prune -f - $exclude_list | ruby $PROG -i - $minmax_arg $multiply_arg +else + sed -f $SED $figtree_file | ruby $PROG -i - $minmax_arg $multiply_arg +fi +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C6 Bayesian theory/6.3.md",".md","1566","45","

+ +

+ +**Solution.** + +a\) + +$$\begin{align*} +2\Delta lnL &= - 2\mathcal{l}(0) + 2\mathcal{l}\left( \widehat{\mu} \right) \\ +&= - 2\log\left( \frac{\prod_{i = 1}^{n}\frac{1}{\sqrt{2\pi}}\ e^{- \frac{x_{i}^{2}}{2}}}{\prod_{i = 1}^{n}\frac{1}{\sqrt{2\pi}}\ e^{\frac{- \left( x_{i} - \overline{x} \right)^{2}}{2}}} \right) \\ +&= \sum_{i = 1}^{n}x_{i}^{2} - \sum_{i = 1}^{n}\left( x_{i} - \overline{x} \right)^{2} \\ +&= n{\overline{x}}^{2} +\end{align*} +$$ + +Given the context, $n = 100$ and $\overline{x} = 0.3$, hence +$2\Delta lnL = 9$. This is enough to reject the null hypothesis because +$\chi_{0.05,1} = 3.84 < 9$ (the *P*-value is 0.0027). + +b\) + +Referring back to Eq. (6.32) of (Yang 2014a), $P_{0}$ is defined as +follows + +$$ +P_{0} = \frac{1}{1 + \frac{1}{\sqrt{1 + n\sigma_{0}^{2}}}\exp\left(\frac{n^{2}\sigma_{0}^{2}\overline{x} + 2n\mu_{0}\overline{x} - n\mu_{0}^{2}}{2\left( 1 + n\sigma_{0}^{2} \right)}\right)}. +$$ + +Hence, using the following R code, it can be easily calculated that i) +$P_{0} = 0.067$, ii) $P_{0} = 0.25$, iii) $P_{0} = 0.95$. + +```R +calculate_p0 <- function(n,x,mu,var0){ denominator=1+1/sqrt(1+n*var0)*exp( (n^2*var0*x^2 + 2*n*mu*x - n*mu^2)/(2+2*n*var0) ); 1/denominator} +alculate_p0(n=100,x=0.3,mu=0.3,var0=0.3) +calculate_p0(n=100,x=0.3,mu=0.3,var0=9) +calculate_p0(n=100,x=0.3,mu=-2.95,var0=1) +``` + +**Note.** + +If you use Eq. (6.33) of (Yang 2014a) to calculate i) and ii) where +$\mu_{0} = 0$, you may want to be aware of a typo in the original +equation, as also pointed out in Errata I of the book (Yang 2022). +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C6 Bayesian theory/6.2.md",".md","1626","49","

+ +

+ +**Solution.** + +a\) + +It is easy to see the following +

+$\frac{dp}{d\theta} = - \frac{3}{4}\left( - \frac{4}{3} \right)e^{\frac{- 4}{3}\theta} = e^{- \frac{4}{3}\theta}$. +

+ +Hence, + +$$f_{\Theta}(\theta) = \left( \frac{3}{4} \right)^{- 1}e^{- \frac{4}{3}\theta} = \frac{4}{3}e^{- \frac{4}{3}\theta}.$$ + +Thus, this corresponds to an exponential distribution with the parameter +$\theta = \frac{4}{3}$. + +b\) + +Refer back to Eq. (6.58) of (Yang 2014a), which is expressed as + +$$f(p) \propto p^{- \frac{1}{2}}(1 - p)^{- \frac{1}{2}},\ 0 \leq p < \frac{3}{4}.$$ + +Note that there might be some confusion by using $P$ to denote the +variable the probability of difference but as that is what is stated in +the problem, we follow it in the solution. Derive the PDF of $P$ as + +$$f(p) = \frac{p^{- \frac{1}{2}}(1 - p)^{- \frac{1}{2}}}{\int_{0}^{\frac{3}{4}}{p^{- \frac{1}{2}}(1 - p)^{- \frac{1}{2}}dp}}.$$ + +The denominator can be calculated as follows + +$$ +\int_{0}^{\frac{3}{4}}{p^{- \frac{1}{2}}(1 - p)^{- \frac{1}{2}}dp} = \int_{0}^{\frac{3}{4}}{\frac{1}{\sqrt{(1 - p)p}}dp} \\ += 2\int_{0}^{\frac{\sqrt{3}}{2}}{\frac{1}{\sqrt{1 - u^{2}}}du} \quad \left( u = \sqrt{p} \right) \\ += 2\arcsin\left( \frac{\sqrt{3}}{2} \right). +$$ + + +Therefore, we have + +$$f_{\Theta}(\theta) = \frac{\left( \frac{3}{4} - \frac{3}{4}e^{- \frac{4\theta}{3}} \right)^{- \frac{1}{2}}\left( \frac{1}{4} + \frac{3}{4}e^{- \frac{4\theta}{3}} \right)^{- \frac{1}{2}}e^{- \frac{4}{3}\theta}}{2\arcsin\left( \frac{\sqrt{3}}{2} \right)}.$$ + +**Note** + +This problem likely comes from the study (dos Reis and Yang, 2011). +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C6 Bayesian theory/6.1.md",".md","72","6","

+ +

+ +**See Problem 5.1 in (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C6 Bayesian theory/6.4.md",".md","1296","14","

+ +

+ +**Solution 1.** + +Briefly, for a Bayesian analysis, you have to specify a prior, no matter if you like it or not. + +**Solution 2 (by [Korbinian Strimmer](https://strimmerlab.github.io/korbinian.html)).** + +In my understanding, the answer to the open question is as follows. + +The key thing to understand is there is always prior information involved in any estimation procedure, either you specify it explicitly or it is implicit in the procedure. The second insight is that there are no neutral or uniformative priors. Hence it is best to acknowledge that a prior is used, and then choose the one that has known properties and is minimally informative, rather than using the implicit prior that may have unknown properties that will potentially strongly bias your estimation. For example, maximum likelihood is equivalent to assuming a flat prior and finding the maximum a-posteriori estimate. However, this implicit prior is typically improper and is not protecting the model from overfitting, hence leading to poor estimates when sample size is small. The only case when you can ignore the prior is when the sample size is very large compared to the number of parameters in the model, because then the prior will have neglible influence on the estimate. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C1 Models of nucleotide substitution/1.6.md",".md","3284","98","

+ +

+ +**Solution.** + +According to the context of the problem, the rate, $3\lambda$, is given +in the problem as $2 \times 10^{- 8}$ substitutions/site/year. + +a\) The starting frequency $\pi^{(0)}$ is given by +$\pi^{(0)} = (1,0,0,0)$. Under the JC69 model, according to Eq. (1.4) in +(Yang 2014a), the transition probability matrix is defined as + +$$ +P(t) = \begin{bmatrix} +p_{0}(t) & p_{1}(t) & p_{1}(t) & p_{1}(t) \\ +p_{1}(t) & p_{0}(t) & p_{1}(t) & p_{1}(t) \\ +p_{1}(t) & p_{1}(t) & p_{0}(t) & p_{1}(t) \\ +p_{1}(t) & p_{1}(t) & p_{1}(t) & p_{0}(t) +\end{bmatrix},\ $with $\left\{ \begin{array}{r} +p_{0}(t) = \frac{1}{4} + \frac{3}{4}e^{- 4\lambda t} \\ +p_{1(t)} = \frac{1}{4} - \frac{1}{4}e^{- 4\lambda t} +\end{array} \right.\ . +$$ + +Thus, for evolution over $10^{6}$ and $10^{8}$ years, it follows that + +$$ +\begin{align*} +\pi^{\left( 10^{6} \right)} &= \pi^{(0)}P\left( t = 10^{6} \right) \\ +&= \begin{bmatrix} +\frac{1}{4} + \frac{3}{4}e^{- \frac{0.02 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{0.02 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{0.02 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{0.02 \times 4}{3}} +\end{bmatrix} \\ +&= \begin{bmatrix} +0.98 & 0.007 & 0.007 & 0.007 +\end{bmatrix}, +\end{align*} +$$ + +and + +$$ +\begin{align*} +\pi^{\left( 10^{8} \right)} &= \pi^{(0)}P\left( t = 10^{8} \right) \\ +&= \begin{bmatrix} +\frac{1}{4} + \frac{3}{4}e^{- \frac{2 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{2 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{2 \times 4}{3}} & \frac{1}{4} - \frac{1}{4}e^{- \frac{2 \times 4}{3}} +\end{bmatrix} \\ +&= \begin{bmatrix} +0.30 & 0.23 & 0.23 & 0.23 +\end{bmatrix}. +\end{align*} +$$ + +b\) The starting frequency $\pi^{(0)}$ is given by +$\pi^{(0)} = (0,1,0,0)$. Hence, + +$${\pi^{\left( 10^{6} \right)} = \begin{bmatrix} +0.007 & 0.98 & 0.007 & 0.007 +\end{bmatrix}, +}{\pi^{\left( 10^{8} \right)} = \begin{bmatrix} +0.23 & 0.30 & 0.23 & 0.23 +\end{bmatrix}.}$$ + +c\) The starting frequency $\pi^{(0)}$ is given by +$\pi^{(0)} = (0.1,0.2,0.3,0.4)$. Hence, + +$$ +{\pi^{\left( 10^{6} \right)} = \pi^{(0)}P\left( t = 10^{6} \right) +}{= \begin{bmatrix} +0.1 & 0.2 & 0.3 & 0.4 +\end{bmatrix} \times +\frac{1}{4} \begin{bmatrix} +1 + 3e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} \\ +1 - e^{-\frac{0.02 \times 4}{3}} & 1 + 3e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} \\ +1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 + 3e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} \\ +1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 - e^{-\frac{0.02 \times 4}{3}} & 1 + 3e^{-\frac{0.02 \times 4}{3}} +\end{bmatrix} +}{= \begin{bmatrix} +0.104 & 0.201 & \ 0.300\ & 0.396 +\end{bmatrix}.\ } +$$ + +Likewise, + +$$ +\pi^{(10^8)} = \begin{bmatrix} +0.240 & 0.247 & 0.253 & 0.260 +\end{bmatrix}. +$$ + + +```R +f <- function(pi_0, t){ p0<-1/4+3/4*exp(-4*lambda*t); p1<-1/4-1/4*exp(-4*lambda*t); P_t <- matrix(c(p0,p1,p1,p1, p1,p0,p1,p1, p1,p1,p0,p1, p1,p1,p1,p0), ncol=4, byrow=T); pi_0 %*% P_t } +pi_0s <- matrix(c(1,0,0,0, 0,1,0,0, 0.1,0.2,0.3,0.4), byrow=T, ncol=4) +t(apply(pi_0s, 1, f, t=10^6)) +t(apply(pi_0s, 1, f, t=10^8)) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C1 Models of nucleotide substitution/1.5.md",".md","961","36","

+ +

+ +**Solution.** + +The transition rate matrix for the model K80 is given as + +$$ +Q = \begin{bmatrix} + -(\alpha + 2\beta) & \alpha & \beta & \beta \\ +\alpha & - (\alpha + 2\beta) & \beta & \beta \\ +\beta & \beta & - (2\beta + \alpha) & \alpha \\ +\beta & \beta & \alpha & - (2\beta + \alpha) \\ +\end{bmatrix}. +$$ + +According to Eq. (1.61) of (Yang 2014a), the equilibrium is achieved +when the following holds + +$$\pi Q = \mathbf{0}\mathbf{.}$$ + +Thus, we have + +$$ +\begin{cases} +-(\alpha + 2\beta)\pi_{T} + \alpha\pi_{C} + \beta\pi_{A} + \beta\pi_{G} = 0 \\ +\alpha\pi_{T} - (\alpha + 2\beta)\pi_{C} + \beta\pi_{A} + \beta\pi_{G} = 0 \\ +\beta\pi_{T} + \beta\pi_{C} - (\alpha + 2\beta)\pi_{A} + \alpha\pi_{G} = 0 \\ +\beta\pi_{T} + \beta\pi_{C} + \alpha\pi_{A} - (\alpha + 2\beta)\pi_{G} = 0 +\end{cases} +$$ + +Because $\sum_{j}^{}\pi_{j} = 1$, it is not difficult to see that due to +symmetry, $\pi_{T} = \pi_{C} = \pi_{A} = \pi_{G} = 0.25$. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C1 Models of nucleotide substitution/1.1-1.4.md",".md","81","6","

+ +

+ +**See Problems 1.1-1.4 in (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C1 Models of nucleotide substitution/1.7.md",".md","700","20","

+ +

+ +**Solution.** + +If you were as lazy as I, you can find the data necessary to do the +likelihood ratio test in Table 1.4 of (Yang 2014a) where the +log-likelihoods under K80 and GTR are $-1637.90$ and $-1610.36$ +respectively. Thus, the difference of log-likelihood is equal to +$1637.90 - 1610.36 = 27.54$. The number of different parameters of these +two nested models are $8 - 1 = 7$. The following R code gives the +*P*-value of the LRT test, which is 1.43747e-09, therefore the simpler +model K80 is rejected at a significance level of 0.05. Note that it is +$27.54 \times 2 = 55.08$ that should be the statistic to use. + +```R +pchisq(27.54\*2, 7, lower.tail=FALSE) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.4.md",".md","1853","55","

+ +

+ +**Solution.** + +Recall Eq. (4.26) in (Yang 2014a), where the transition matrix is given as + +$$P(0.2) = \begin{bmatrix} +0.811138 & 0.080114 & 0.082824 & 0.025924 \\ +0.055240 & 0.836012 & 0.082824 & 0.025924 \\ +0.055240 & 0.080114 & 0.838722 & 0.025924 \\ +0.055240 & 0.080114 & 0.082824 & 0.781821 +\end{bmatrix}.$$ + +Denote the ancestral node as node 0, such that its ancestral state is +expressed as $X_{0}$ which can take any of the four nucleotides, denoted +as $x_{0}$. The likelihoods that the ancestral nucleotide at the root is +T, C, A, G, respectively, are calculated as follows + +$$L_{0}(T) = 0.082824 \times 0.082824 \times 0.025924,$$ + +$$L_{0}(C) = 0.082824 \times 0.082824 \times 0.025924,$$ + +$$L_{0}(A) = 0.838722 \times 0.838722 \times 0.025924,$$ + +$$L_{0}(G) = 0.082824 \times 0.082824 \times 0.781821.$$ + +According to the problem statement, the equilibrium frequencies of each +nucleotide are given as +$\pi_{T} = 0.2263,\ \pi_{C} = 0.3282,\ \pi_{A} = 0.3393,\ \pi_{G} = 0.1062.$ +The posterior probability that the ancestral node (node 0) takes +character $x_{0}$ can be expressed as follows, according to Eq. (4.23) +of (Yang 2014a) + +$$f\left( x_{0} \middle| x_{h};\theta \right) = \frac{\pi_{x_{0}}L_{0}\left( x_{0} \right)}{\sum_{x_{0} \in \left\{ T,C,A,G \right\}}^{}{\pi_{x_{0}}L_{0}\left( x_{0} \right)}}.$$ + +Hence, using the following R script, the posterior probabilities of the +ancestral nucleotide at the root for T, C, A, G are respectively +0.005870062, 0.008513276, 0.902538297, 0.083078366. + + +```R +> lik <- numeric(4) +# in the order T, C, A, G +> lik[1] <- 0.082824*0.082824*0.025924 +> lik[2] <- 0.082824*0.082824*0.025924 +> lik[3] <- 0.838722*0.838722*0.025924 +> lik[4] <- 0.082824*0.082824*0.781821 +> pi <- c(0.2263, 0.3282, 0.3393, 0.1062) +> result = pi * lik / sum(pi * lik) +> print(result) +``` + +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.6.md",".md","1167","44","

+ +

+ +**Solution.** + +You are welcome to follow what is told in the problem but I am lazy +enough to just take the nucleotide alignment from Problem 4.5, i.e., the +file ""rbcL.nogaps_amb.fas"". Here, I choose to use IQ-Tree and raxml-ng +for tree construction. The command is as follows (**4.6.sh**). Note that JC69 is +specified as ""JC"", and HKY85 is specified as ""HKY"" in raxml-ng. + +```Bash +#! /bin/bash +# IQ-Tree +mkdir iqtree +cd iqtree +for m in JC69 K80 HKY85 GTR JC69+G5 K80+G5 HKY85+G5 GTR+G5; do + echo $m + iqtree -redo -m $m -pre $m -s ../sample.fasta -quiet +done +cd .. +# raxml-ng +mkdir raxml-ng +cd raxml-ng +for m in JC K80 HKY GTR JC+G5 K80+G5 HKY+G5 GTR+G5; do + echo $m + raxml-ng --redo --msa ../sample.fasta --model $m --prefix $m +done +cd .. +``` + +Then, use the following Bash command to summarize the result shown at +the end. + +```Bash +for m in JC69 K80 HKY85 GTR JC69+G5 K80+G5 HKY85+G5 GTR+G5; do grep ""BEST SCORE FOUND"" iqtree/$m.log | awk '{print $NF}'; done +for m in JC K80 HKY GTR JC+G5 K80+G5 HKY+G5 GTR+G5; do grep ""Final LogLikelihood"" raxml-ng/$m.raxml.log | awk '{print $NF}'; done +``` + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.1.md",".md","5224","84","

+ +

+ +

+ +

+ +**Solution.** + +In Eq. (1.79) of (Yang 2014a), the transition probability matrix is +given as + +$$P(t) = \ \begin{bmatrix} +p_{0} & p_{1} \\ +p_{1} & p_{0} +\end{bmatrix},$$ + +where $p_{0} = 0.5 + 0.5e^{- 2t}$ and +$p_{1} = 0.5 - 0.5e^{- 2t}$. + +Denote the state at node $i$ (either tip or ancestral node) as $S_{i}$. +According to the problem statement, $S_{i}$ are restricted to only two +values, which we assign as A or B. The following can be easily +calculated based on Section 4.2 of (Yang 2014a). Further, define +$a = e^{- 2t_{10}}$ and $b = e^{- 2t_{11}}$, thus +$e^{- 2\left( t_{10} + t_{11} \right)} = ab$. + +Hence, + +$$ +\begin{align*} +P(xxx) &= P\left( S_{1} = A,S_{2} = A,S_{3} = A \right) + P\left( S_{1} = B,S_{2} = B,S_{3} = B \right) \\ +&= 2 \times P\left( S_{1} = A,S_{2} = A,S_{3} = A \right) \\ +&= 2 \times 0.5 \times \left( P\left( S_{1} = A,S_{2} = A,S_{3} = A \middle| S_{0} = A \right) + P\left( S_{1} = A,S_{2} = A,S_{3} = A \middle| S_{0} = B \right) \right) \\ +&= P\left( S_{1} = A,S_{2} = A,S_{3} = A,S_{4} = A \middle| S_{0} = A \right) \\ +&\quad + P\left( S_{1} = A,S_{2} = A,S_{3} = A,S_{4} = B \middle| S_{0} = A \right) \\ +&\quad + P\left( S_{1} = A,S_{2} = A,S_{3} = A,S_{4} = A \middle| S_{0} = B \right) \\ +&\quad + P\left( S_{1} = A,S_{2} = A,S_{3} = A,S_{4} = B \middle| S_{0} = B \right) \\ +&= \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right)^{2} \\ +&= \frac{1}{16}\left( (1\ + \ ab)(1\ + \ a)(1\ + \ b)(1\ + \ b) + \ (1\ + \ ab)(1\ + \ a)(1\ - \ b)(1\ - \ b) + \ (1\ - \ ab)(1\ - \ a)(1\ + \ b)(1\ + \ b) + \ (1\ - \ ab)(1\ + \ a)(1\ - \ b)(1\ - \ b) \right) \\ +&= \frac{1}{16}\left( 4 + 2a - 4ab + 2a^{2}b + 4b^{2} + 2ab^{2} + a^{2}b^{2} + 2a^{2}b^{3} \right), \\ +\end{align*} +$$ + +
+ +$$ +\begin{align*} +P(xxy) &= P\left( S_{1} = A,S_{2} = A,S_{3} = B \right) + P\left( S_{1} = B,S_{2} = B,S_{3} = A \right) \\ +&= 2 \times P\left( S_{1} = A,S_{2} = A,S_{3} = B \right) \\ +&= P\left( S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = A \middle| S_{0} = A \right) + P\left( S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B \middle| S_{0} = A \right) \\ +&\quad + P\left( S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = A \middle| S_{0} = B \right) + P\left( S_{1} = A,S_{2} = A,S_{3} = B,S_{4} = B \middle| S_{0} = B \right) \\ +&= \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)^{2} \\ +&\quad + \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right)^{2} \\ +&= \frac{1}{16}\left[ (1 - ab)(1 + a)(1 + b)(1 + b) + (1 - ab)(1 - a)(1 - b)(1 - b) + (1 + ab)(1 - a)(1 + b)(1 + b) + (1 + ab)(1 + a)(1 - b)(1 - b) \right] \\ +&= - 0.5a^{2}b^{2} + \frac{1}{4}\left( b^{2} + 1 \right), \\ +\end{align*} +$$ + +
+ +$$ +\begin{align*} +P(yxx) &= P\left( S_{1} = A,S_{2} = B,S_{3} = B \right) + P\left( S_{1} = B,S_{2} = A,S_{3} = A \right) \\ +&= 2 \times P\left( S_{1} = A,S_{2} = B,S_{3} = B \right) \\ +&= P\left( S_{1} = A,S_{2} = B,S_{3} = B,S_{4} = A \middle| S_{0} = A \right) + P\left( S_{1} = A,S_{2} = B,S_{3} = B,S_{4} = B \middle| S_{0} = A \right) \\ +&\quad+ P\left( S_{1} = A,S_{2} = B,S_{3} = B,S_{4} = A \middle| S_{0} = B \right) + P\left( S_{1} = A,S_{2} = B,S_{3} = B,S_{4} = B \middle| S_{0} = B \right) \\ +&= \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right) \\ +&\quad+ \left( 0.5 - 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right) \\ +&\quad+ \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 - 0.5e^{- 2t_{10}} \right)\left( 0.5 + 0.5e^{- 2t_{11}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right) \\ +&\quad+ \left( 0.5 + 0.5e^{- 2\left( t_{10} + t_{11} \right)} \right)\left( 0.5 + 0.5e^{- 2t_{10}} \right)\left( 0.5 - 0.5e^{- 2t_{11}} \right)^{2} \\ +&= \frac{1}{16}\left( (1 - ab)(1 + a)(1 + b)(1 - b) + (1 - ab)(1 - a)(1 + b)(1 - b) + (1 + ab)(1 - a)(1 + b)(1 - b) + (1 + ab)(1 + a)(1 - b)(1 - b) \right) \\ +&= \frac{1}{8}\left( a^{2}b^{3} - a^{2}b^{2} + \left( ab^{3} - ab \right) + \left( 2 - \left( b + b^{2} \right) \right) \right). +\end{align*} +$$ + + +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.5.md",".md","2590","101","

+ +

+ +**Solution.** + +Data preparation. + +Download the alignment and the tree from Yang's website (Yang 2014b) +(see C2). Convert the alignment into FASTA format. Then, remove all +sites that have any ambiguous sites or gaps. See pp. 146 of (Yang +2014a): + +\| *We do not have a model for alignment gaps, so we remove sites with +gaps, with 1,312 sites left*. + +This should generate an alignment of 1312 bp, available in the file +""rbcL.nogaps_amb.fas"". + +Check the R script + +I write the following R script to calculate log-likelihood under the +multinomial distribution model where $𝓁_{\max}$ is calculated +as + +$$ +𝓁_{\max} = \sum_{i=1}^{4^{s}}{n_{i}\log\left(\frac{n_{i}}{n}\right)}, +$$ + + +as given by Eq. (4.39) of (Yang 2014a). Of course, an alternative way is +to use the value calculated by BASEML. + +**4.5R** +```R +library(seqinr) +args = commandArgs(trailingOnly=TRUE) +seq_file <- args[1] +s <- read.fasta(seq_file) +v <- list() +for(i in 1:getLength(s)[1]){ + v[[i]] <- sapply(s, function(x) x[i]) + names(v[[i]]) <- names(s) +} + +m <- t(sapply(v, unlist, list(use.names=F))) +dimnames(m) <- NULL +h <- apply(m, 1, function(x){paste(x,collapse="""")}) +t <- table(h) +n <- sum(t) +lnl <- 0 +for(n_i in table(h)){ + lnl <- lnl + n_i * log(n_i/n) +} +cat(lnl,""\n"") +``` + +Examine that the R script (*4.5.R*) yields +$\mathcal{l}_{\max} = –4025.03$, exactly the same as that shown in +Section 4.7.2 of (Yang 2014a) under the multinomial model. Also verify +that the log-likelihood under the model HKY+G5 is generated by using +IQ-Tree is $- 5703.967$. + +```Bash +iqtree -s rbcL.nogaps_amb.fas -m HKY+G5 -te vegetables.nwk -redo +Rscript 4.5.R +``` + +Run analysis + +Now, run the analysis. The following is my setting of the control file of EVOLVER. +Note that I indicate ""2"" in the first row which indicates that the +sequence output is *mc.nex* in Nexus format. All scripts are available in the folder ""scripts/"". + +

+ +

+ +**4.5.sh** + +```Bash +model=JC69 +evolver 5 JC69.dat >/dev/null +python nexus2fasta.py mc.nex sample.fasta >/dev/null +iqtree -s sample.fasta -m $model -te vegetables.nwk -redo -quiet +lnl=`grep ""Optimal log-likelihood"" sample.fasta.log | awk '{print $NF}'` +lnl_max=`Rscript 4.5.R sample.fasta 2>/dev/null` +echo ""scale=2; $lnl_max - $lnl"" | bc +``` + +Run the following to generate the graph below. + +```Bash +for i in `seq 1000`; do bash 4.5.sh ; done > deltaLL.list +R -e 'v=unlist(read.table(""deltaLL.list"")); hist(v, freq=F, xlab=""deltaLL"")' +``` + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.2.md",".md","72","6","

+ +

+ +**See Problem 4.2 in (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/4.3.md",".md","72","6","

+ +

+ +**See Problem 4.3 in (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/scripts/4.5.sh",".sh","518","22","#! /bin/bash + + +model=JC69 + +#iqtree -redo -s rbcL.nogaps_amb.fas -te vegetables.nwk -m $model -quiet + +#iqtree --alisim sim -m $model -te rbcL.nogaps_amb.fas.treefile -st DNA -af fasta -quiet --length 1312 + +evolver 5 JC69.dat >/dev/null + +python nexus2fasta.py mc.nex sample.fasta >/dev/null + +iqtree -s sample.fasta -m $model -te vegetables.nwk -redo -quiet + +lnl=`grep ""Optimal log-likelihood"" sample.fasta.log | awk '{print $NF}'` + +lnl_max=`Rscript 4.5.R sample.fasta 2>/dev/null` + +echo ""scale=2; $lnl_max - $lnl"" | bc + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/scripts/4.5.R",".R","571","33","#! /usr/bin/env Rscript + + +################################################ +library(seqinr) + + +################################################ +args = commandArgs(trailingOnly=TRUE) +seq_file <- args[1] +s <- read.fasta(seq_file) + +v <- list() +for(i in 1:getLength(s)[1]){ + v[[i]] <- sapply(s, function(x) x[i]) + names(v[[i]]) <- names(s) +} + +m <- t(sapply(v, unlist, list(use.names=F))) +dimnames(m) <- NULL + +h <- apply(m, 1, function(x){paste(x,collapse="""")}) +t <- table(h) +n <- sum(t) + +lnl <- 0 +for(n_i in table(h)){ + lnl <- lnl + n_i * log(n_i/n) +} + +cat(lnl,""\n"") + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/scripts/nexus2fasta.py",".py","278","12","#! /usr/bin/env python + +########################################## +from Bio import SeqIO +import sys + +########################################## +records = SeqIO.parse(sys.argv[1], ""nexus"") +count = SeqIO.write(records, sys.argv[2], ""fasta"") +print(""Converted %i records"" % count) + +","Python" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/scripts/4.4.R",".R","295","9","> lik <- numeric(4) +# in the order T, C, A, G +> lik[1] <- 0.082824*0.082824*0.025924 +> lik[2] <- 0.082824*0.082824*0.025924 +> lik[3] <- 0.838722*0.838722*0.025924 +> lik[4] <- 0.082824*0.082824*0.781821 +> pi <- c(0.2263, 0.3282, 0.3393, 0.1062) +> result = pi * lik / sum(pi * lik) +> print(result)","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C4 Maximum likelihood methods/scripts/4.6.sh",".sh","374","20","#! /bin/bash + +# IQ-Tree +mkdir iqtree +cd iqtree +for m in JC69 K80 HKY85 GTR JC69+G5 K80+G5 HKY85+G5 GTR+G5; do + echo $m + iqtree -redo -m $m -pre $m -s ../rbcL.nogaps_amb.fas -quiet +done +cd .. + +# raxml-ng +mkdir raxml-ng +cd raxml-ng +for m in JC K80 HKY GTR JC+G5 K80+G5 HKY+G5 GTR+G5; do + echo $m + raxml-ng --redo --msa ../rbcL.nogaps_amb.fas --model $m --prefix $m +done +cd .. +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.3.md",".md","73","6","

+ +

+ +**See Problem 9.2 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.1.md",".md","264","19","

+ +

+ +**Solution.** + +Use the following R code. The first 10 pseudo-random numbers generated in this way are + +

+ +

+ +```R +x<-numeric(10) +x[1] <- 11 +for(i in 2:10){x[i] <- 37*x[i-1] %% 1000} +print(x) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.2.md",".md","397","12","**Solution.** + +For exponential distribution, + +$$P(X > x) = 1 - \int_{0}^{\infty}{e^{- \lambda x}dx} = e^{- \lambda x}.$$ + +Apply the Bayes' theorem. It follows that + +$${P\left( X > a + x \middle| X > a \right) = \frac{P(X > a + x)P\left( X > a \middle| X > a + x \right)}{P(X > a)} +}{= \frac{P(X > a + x)}{P(X > a)} +}{= \frac{e^{- \lambda(a + x)}}{e^{- \lambda a}} = e^{- \lambda x} = P(X > x).}$$ +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.6.md",".md","71","6","

+ +

+ +**See Problem 9.4 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.5.md",".md","583","18","**Solution.** + +I use EVOLER to simulate 1000 replicates of sequences under JC69 with +sequence distances from 0.1 to 1.0 (every 0.2) and sequence lengths +$l$ = 50, 100, 200, and 500. Then run BASEML with both +JC69 and K80. Summarize the results using the R script *12.5.R*. You can +use the following Bash command to get the following histogram. It looks +that with a larger $d$ and longer sequence, the distribution of +$2\Delta$ better approximates $\chi_{1}$. The codes are available at +*12.5.sh* and *12.5.R*. + +

+ +

+

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.7.md",".md","73","6","

+ +

+ +**See Problem 9.5 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/12.4.md",".md","69","4","

+ +**See problem 9.3 of (Yang 2006).** +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/scripts/12.5.sh",".sh","508","20","#! /bin/bash + + +for d in `seq 0.1 0.1 1`; do + for n in 50 100 200 500; do + echo -e ""$d\t$n"" + sed -i ""5s/.*/$d/"" model.dat + sed -i ""4s/.*/2 $n 1000/"" model.dat + evolver 5 model.dat >/dev/null + + sed -i 's/model = .*/model = 0/' baseml.ctl + baseml baseml.ctl >/dev/null; grep -i lnL mlb | grep ""best tree"" | awk '{print $NF}' > jc69.$d-$n.lnl + sed -i 's/model = .*/model = 1/' baseml.ctl + baseml baseml.ctl >/dev/null; grep -i lnL mlb | grep ""best tree"" | awk '{print $NF}' > k80.$d-$n.lnl + done +done + + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/scripts/12.5.R",".R","676","23","#! /usr/bin/env Rscript + + +################################################# +pdf() + +par(mfrow=c(3,4)) +for(d in seq(0.1, by=0.2, length.out=5)){ + d <- ifelse(d==1, format(d, nsmall=1), d) + for(n in c(50,100,200,500)) { + infile1 <- paste('jc69.', d, '-', n, '.lnl', sep='') + infile2 <- paste('k80.', d, '-', n, '.lnl', sep='') + a1 <- unlist(read.table(infile1)) + a2 <- unlist(read.table(infile2)) + print(infile2) + hist(2*(a2-a1), breaks=50, freq=F, ylim=c(0,2), xlim=c(0,8), main=paste(paste0(""distance:"",d),paste0(""length:"",n),sep='\n'), xlab="""", ylab="""", lwd=1) + curve(dchisq(x,df=1),add=T, col=""RED"") + } +} + +dev.off() + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/data/12.5-data/12.5.sh",".sh","508","20","#! /bin/bash + + +for d in `seq 0.1 0.1 1`; do + for n in 50 100 200 500; do + echo -e ""$d\t$n"" + sed -i ""5s/.*/$d/"" model.dat + sed -i ""4s/.*/2 $n 1000/"" model.dat + evolver 5 model.dat >/dev/null + + sed -i 's/model = .*/model = 0/' baseml.ctl + baseml baseml.ctl >/dev/null; grep -i lnL mlb | grep ""best tree"" | awk '{print $NF}' > jc69.$d-$n.lnl + sed -i 's/model = .*/model = 1/' baseml.ctl + baseml baseml.ctl >/dev/null; grep -i lnL mlb | grep ""best tree"" | awk '{print $NF}' > k80.$d-$n.lnl + done +done + + + +","Shell" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C12 Simulating molecular evolution/data/12.5-data/12.5.R",".R","676","23","#! /usr/bin/env Rscript + + +################################################# +pdf() + +par(mfrow=c(3,4)) +for(d in seq(0.1, by=0.2, length.out=5)){ + d <- ifelse(d==1, format(d, nsmall=1), d) + for(n in c(50,100,200,500)) { + infile1 <- paste('jc69.', d, '-', n, '.lnl', sep='') + infile2 <- paste('k80.', d, '-', n, '.lnl', sep='') + a1 <- unlist(read.table(infile1)) + a2 <- unlist(read.table(infile2)) + print(infile2) + hist(2*(a2-a1), breaks=50, freq=F, ylim=c(0,2), xlim=c(0,8), main=paste(paste0(""distance:"",d),paste0(""length:"",n),sep='\n'), xlab="""", ylab="""", lwd=1) + curve(dchisq(x,df=1),add=T, col=""RED"") + } +} + +dev.off() + +","R" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C3 Phylogeny reconstruction/3.5.md",".md","103","10","

+ +

+ +**Solution.** + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C3 Phylogeny reconstruction/3.1.md",".md","688","28","

+ +

+ +**Solution.** + +Use the following R code to find the pair of taxa most distant to each +other. The package *phytools* (Revell 2012) may need to be installed. + +```R +library(phytools) +tree <- read.tree( text=""(((human: 0.040, chimpanzee: 0.052): 0.016, gorilla: 0.059): 0.047, orangutan: 0.090, gibbon: 0.125);"" ) +which(dist.nodes(tree) == max(dist.nodes(tree)), arr.ind = TRUE) +tree$tip.label +``` + +This gives taxon 2 and taxon 5, which are chimpanzee and gibbon +respectively. Then use the R code to root the tree and visualize it. + +```R +rooted_tree <- midpoint.root(tree) +plot(rooted_tree) +``` + +

+ +

+","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C3 Phylogeny reconstruction/3.2.md",".md","196","13","

+ +

+ +

+ +

+ +**Solution.** + +Two possible ways are ((A,B,C),D,E,(F,G,H)), or (((A,B,C),D),E,(H,F,G)), +among many others. +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C3 Phylogeny reconstruction/3.4.md",".md","697","24","

+ +

+ +

+ +

+ +**Solution.** +In Section 3.1.1.6 of (Yang 2014a), it is clearly indicated that the +partition distance between two trees is the number of bipartitions that +are in one but not the other. Because none of the 3 bipartitions in the +left tree is included in the right tree, and the same holds for the +right tree, the partition distance equals $3 + 3 = 6$. + +You can verify this by the following R code. Note that the package ape +needs to be installed. +```R +library(ape) +tree1 <- read.tree(text = ""(((c,horse),r), human,(l,b));"") +tree2 <- read.tree(text = ""(((r,horse),human), b,(l,c));"") +dist.topo(tree1,tree2) +``` +","Markdown" +"Microbiology","sishuowang/Solutions_Manual_CME2006_MESA2014","MESA2014/C3 Phylogeny reconstruction/3.3.md",".md","934","24","

+ +

+ +**Solution.** + +a\) Correct. It is important to note that when we say that some taxa are +more closely related it means that they a more recent common ancestor +than other taxa \[see Section 3.1.1.8 of (Yang 2014a)\]. Because species +d and e share the most recent common ancestor, they are more closely +related to each other than to any others in the tree. + +b\) Correct. The sequence similarity may be measured by genetic +distance. In view of the tree, this is calculated as the length of +branches connecting any two tips. According to the Newick-formatted tree +given in the problem, the distance between sequence b and sequence d is +0.01+0.005+0.01+0.015=0.04 which indeed is the smallest. + +c\) Incorrect. Because taxa b and e form a monophyly, b is more closely +related to e than to any others in the tree. + +d\) Incorrect. Taxa d and f share a more recent common ancestor than +with taxon c. +","Markdown" +"Microbiology","phac-nml/galaxy_tools","packages/package_spades_3_8_0/env.sh",".sh","594","18","#!/bin/bash +if [[ ! -d $INSTALL_DIR ]] +then + echo ""ERROR: Environment variable INSTALL_DIR not a directory!"" +fi +export INSTALL_DIR=${INSTALL_DIR:-$PWD} +export INSTALL_DIR=`(cd ""$INSTALL_DIR""; pwd)` +#============================================================ +echo ""Setting environment variables for spades version 3.8.0"" +#============================================================ +specifc_action_done=0 +#------------------------------------------------------------ +if [[ $specifc_action_done == 0 ]] +then + echo ""Non-platform-specific actions"" + export PATH=$INSTALL_DIR/bin:$PATH +fi +","Shell" +"Microbiology","phac-nml/galaxy_tools","tools/biohansel_bionumeric_converter/bionumeric_converter.py",".py","1283","53","#!/usr/bin/env python + +# Import dependancies needed +import argparse + +import pandas as pd + +# Define the main function: + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '-f', + '--filename', + required=True, + help='Specify your biohansel tsv or other tabular separated input') + parser.add_argument( + '-o', + '--output', + default='output.csv', + help='Specify output name') + args = parser.parse_args() + tsv_file = args.filename + out_name = args.output + + df_input = pd.read_csv(tsv_file, sep='\t') + + df_no_comma = df_input.replace(',', '/', regex=True) + df = qc_shortener(df_no_comma) + df.to_csv(out_name, index=False) + +# Shorten QC results: + + +def splittingstrings(string, length): + return (string[0+i:length+i] for i in range(0, len(string), length)) + + +def qc_shortener(df): + for i, row in df.iterrows(): + message = str(row['qc_message']) + if len(message) > 150: + message_list = list(splittingstrings(message, 150)) + df.at[i, 'qc_message'] = message_list[0] + for val in range(1, len(message_list)): + df.at[i, 'qc_message_{}'.format(val)] = message_list[val] + return df + + +if __name__ == '__main__': + main() +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/assemblystats/assembly_stats_txt.py",".py","3752","146","#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Version 1.01 - bugs kindly corrected by Jan van Haarst +# Modified by Matthew Gopez October 13th, 2017 +# Rewritten by Matthew Gopez May 25th, 2020 + +import argparse +import os +import shutil +import subprocess +from pathlib import Path + + +PERL_OUT_FILES = ['stats.txt', 'sorted_contigs.fa', 'histogram_bins.dat.png', + 'summed_contig_lengths.dat.png', 'histogram_bins.dat', + 'summed_contig_lengths.dat'] + + +def init_parser(): + """"""Create argument parser and return parser obj."""""" + parser = argparse.ArgumentParser(description=""usage: %prog [options]"") + + parser.add_argument( + ""-d"", + ""--working-dir"", + dest=""working_dir"", + required=True) + + parser.add_argument( + ""-t"", + ""--type"", + dest=""file_type"", + required=True) + + parser.add_argument( + ""-b"", + ""--bucket"", + dest=""bucket"", + action='store_true') + + parser.add_argument( + ""-i"", + ""--input"", + dest=""input"", + required=True) + + parser.add_argument( + ""-s"", + ""--stats"", + dest=""stats"", + required=True) + + parser.add_argument( + ""-sc"", + ""--sorted-contigs"", + dest=""sorted_contigs"", + required=True) + + parser.add_argument( + ""-hpng"", + ""--histogram-png"", + dest=""histogram_png"", + required=True) + + parser.add_argument( + ""-spng"", + ""--summed-contigs-png"", + dest=""summed_contigs_png"", + required=True) + + parser.add_argument( + ""-hd"", + ""--histogram-data"", + dest=""histogram_data"", + required=True) + + parser.add_argument( + ""-scd"", + ""--summed-config-data"", + dest=""summed_contig_data"", + required=True) + + return parser + + +def exec_fasta_summary(input_data, file_type, bucket, working_dir): + """"""Execute fasta_summary.pl script with user arguments."""""" + script_dir = Path(__file__).parent.absolute() + + if bucket: + bucket_arg = '-b' + else: + bucket_arg = '' + + cli_command = \ + '{}/fasta_summary.pl -i {} -t {} {} -o {} > /dev/null'.format( + script_dir, input_data, file_type, bucket_arg, working_dir) + + try: + subprocess.check_output( + cli_command, + stderr=subprocess.STDOUT, + shell=True, + universal_newlines=True) + except subprocess.CalledProcessError as exc: + raise RuntimeError('Error running assembly_stats.py!\n' + 'Return Code: {}\nOutput: {}'.format( + exc.returncode, exc.output)) + + +def main(): + """"""This is where the magic happens. (not really) + + 1. Gets command line arguments. + 2. Grabs the user's desired parameters for running the perl script. + 3. Ensures the directories are in place. + 4. Executes fasta_summary.pl + 5. Move the out files from the perl script to the desired + location the user specified. + + """""" + parser = init_parser() + args = parser.parse_args() + + working_dir = args.working_dir + + out_file_names = [args.stats, args.sorted_contigs, args.histogram_png, + args.summed_contigs_png, args.histogram_data, + args.summed_contig_data] + + # Ensure working directory is created. + Path(working_dir).mkdir(parents=True, exist_ok=True) + + # Execute Perl Script + exec_fasta_summary(args.input, args.file_type, args.bucket, working_dir) + + # Rename out files to desired file names + for perl_out_file, dest_file in zip(PERL_OUT_FILES, out_file_names): + shutil.move(os.path.join(working_dir, perl_out_file), + dest_file) + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/combineJSON/combineJSON.py",".py","1474","52","#!/usr/bin/env python +import argparse +import json +import sys + + +def init_parser(): + parser = argparse.ArgumentParser( + prog=""combineJSON"", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=""Combine JSON data arrays into a single array"") + parser.add_argument('-i', + nargs='*', + help=""Input JSON files to be combined"") + parser.add_argument('-o', + help='Output file name') + return parser + + +parser = init_parser() +args = parser.parse_args() +input_files = args.i +json_file = [] + +if input_files is None or len(input_files) < 1: + print('Not enough input files. ' + 'Please use -i filename.txt filename1.txt ' + 'to combine JSON data files') + sys.exit(0) + + +for file_path in input_files: + try: + # Attempt to open each input file, parse as JSON + with open(file_path, 'r') as curr_file: + file_data = curr_file.read() + parsed_json_file = json.loads(file_data) + # Append each valid JSON data array + for entry in parsed_json_file: + json_file.append(entry) + except Exception as e: + print(""Help! I can't parse this file {}. "" + ""Are you sure this is a valid JSON file?"" + .format(file_path)) + raise(e) + +if args.o: + with open(args.o, 'w') as out_json: + json.dump(json_file, out_json) +else: + print(json.dumps(json_file)) +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/mummer4/promer_substitutions.py",".py","3823","139","#!/usr/bin/env python + +import os +import subprocess +import sys + +from Bio import SeqIO +from Bio.SeqIO import FastaIO + +"""""" +# ============================================================================= +Copyright Government of Canada 2018 +Written by: Eric Marinier, Public Health Agency of Canada, + National Microbiology Laboratory +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at: +http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +# ============================================================================= +"""""" + +__version__ = '0.2.0' + +FASTA_DIRECTORY = ""fasta"" + +REF_START = 2 +REF_END = 3 + +HEADER_ROW = ""[P1]\t[SUB]\t[SUB]\t[P2]\t[BUFF]\t[DIST]\ + \t[R]\t[Q]\t[FRM]\t[FRM]\t[TAG]\t[TAG]\n"" + + +def reorient_file(fasta_location, start, end): + + record = list(SeqIO.parse(fasta_location, ""fasta""))[0] + + # reversed + if start > end: + record.seq = record.seq[(end - 1):start].reverse_complement() + + # same orientation + else: + record.seq = record.seq[(start - 1):end] + + SeqIO.write(record, fasta_location, ""fasta"") + + +def promer(reference_location, query_location): + + # promer + subprocess.check_output( + ['promer', reference_location, query_location], + universal_newlines=True) + + # filter + output = subprocess.check_output( + ['delta-filter', '-grq', 'out.delta'], universal_newlines=True) + + filter_file = open(""out.filter"", ""w"") + filter_file.write(output) + filter_file.close() + + +# File locations from arguments: +reference_location = sys.argv[1] +query_location = sys.argv[2] + +# Make directories: +if not os.path.exists(FASTA_DIRECTORY): + os.mkdir(FASTA_DIRECTORY) + +# Read query FASTA: +query = list(SeqIO.parse(query_location, ""fasta"")) +fasta_locations = [] + +# Prepare final output: +snps_file = open(""snps.tab"", ""w"") +snps_file.write(HEADER_ROW) + +# Split the query FASTA file into multiple files, each with one record: +# (This is done to work around a bug in promer.) +for record in query: + + output_name = str(record.id) + "".fasta"" + output_location = os.path.join(FASTA_DIRECTORY, output_name) + + fasta_locations.append(output_location) + SeqIO.write(record, output_location, ""fasta"") + +# Run promer on each (new) FASTA file: +for fasta_location in fasta_locations: + + promer(reference_location, fasta_location) + + # show-coords + output = subprocess.check_output( + ['show-coords', '-THrcl', 'out.filter'], universal_newlines=True) + + if not output: + continue + + ref_start = int(output.split()[REF_START]) + ref_end = int(output.split()[REF_END]) + + reorient_file(fasta_location, ref_start, ref_end) + promer(reference_location, fasta_location) + + # show-coords + output = subprocess.check_output( + ['show-coords', '-THrcl', 'out.filter'], universal_newlines=True) + + # show snps + output = str(subprocess.check_output( + ['show-snps', '-T', '-q', 'out.filter'], universal_newlines=True)) + output = output.split(""\n"")[4:] + output = ""\n"".join(output) + + snps_file.write(output) + +snps_file.close() + +# Write all FASTA files into one output: +output_location = ""contigs.fasta"" +records = [] + +for fasta_location in fasta_locations: + + record = list(SeqIO.parse(fasta_location, ""fasta""))[0] + records.append(record) + +contigs_file = open(output_location, 'w') +fasta_writer = FastaIO.FastaWriter(contigs_file, wrap=None) +fasta_writer.write_file(records) +contigs_file.close() +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/promer/promer_substitutions.py",".py","3469","127","#!/usr/bin/env python + +import os +import subprocess +import sys + +from Bio import SeqIO +from Bio.SeqIO import FastaIO + +"""""" +# ============================================================================= +Copyright Government of Canada 2018 +Written by: Eric Marinier, Public Health Agency of Canada, + National Microbiology Laboratory +Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at: +http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. +# ============================================================================= +"""""" + +__version__ = '0.2.0' + +FASTA_DIRECTORY = ""fasta"" + +REF_START = 2 +REF_END = 3 + +HEADER_ROW = ""[P1]\t[SUB]\t[SUB]\t[P2]\t[BUFF]\t[DIST]\ + \t[R]\t[Q]\t[FRM]\t[FRM]\t[TAG]\t[TAG]\n"" + + +def reorient_file(fasta_location, start, end): + + record = list(SeqIO.parse(fasta_location, ""fasta""))[0] + + # reversed + if start > end: + record.seq = record.seq[(end - 1):start].reverse_complement() + + # same orientation + else: + record.seq = record.seq[(start - 1):end] + + SeqIO.write(record, fasta_location, ""fasta"") + + +def promer(reference_location, query_location): + + # promer + subprocess.check_output( + ['promer', reference_location, query_location], + universal_newlines=True) + + +# File locations from arguments: +reference_location = sys.argv[1] +query_location = sys.argv[2] + +# Make directories: +if not os.path.exists(FASTA_DIRECTORY): + os.mkdir(FASTA_DIRECTORY) + +# Read query FASTA: +query = list(SeqIO.parse(query_location, ""fasta"")) +fasta_locations = [] + +# Prepare final output: +snps_file = open(""snps.tab"", ""w"") +snps_file.write(HEADER_ROW) + +# Split the query FASTA file into multiple files, each with one record: +# (This is done to work around a bug in promer.) +for record in query: + + output_name = str(record.id) + "".fasta"" + output_location = os.path.join(FASTA_DIRECTORY, output_name) + + fasta_locations.append(output_location) + SeqIO.write(record, output_location, ""fasta"") + +# Run promer on each (new) FASTA file: +for fasta_location in fasta_locations: + + promer(reference_location, fasta_location) + + # show-coords + output = subprocess.check_output( + ['show-coords', '-THrcl', 'out.delta'], universal_newlines=True) + + if not output: + continue + + ref_start = int(output.split()[REF_START]) + ref_end = int(output.split()[REF_END]) + + reorient_file(fasta_location, ref_start, ref_end) + promer(reference_location, fasta_location) + + # show snps + output = str(subprocess.check_output( + ['show-snps', '-T', '-q', 'out.delta'], universal_newlines=True)) + output = output.split(""\n"")[4:] + output = ""\n"".join(output) + + snps_file.write(output) + +snps_file.close() + +# Write all FASTA files into one output: +output_location = ""contigs.fasta"" +records = [] + +for fasta_location in fasta_locations: + + record = list(SeqIO.parse(fasta_location, ""fasta""))[0] + records.append(record) + +contigs_file = open(output_location, 'w') +fasta_writer = FastaIO.FastaWriter(contigs_file, wrap=None) +fasta_writer.write_file(records) +contigs_file.close() +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/abacas/abacas.sh",".sh","1697","78","#!/bin/bash + +#wrapper for abacas +##our arguments will come in as an array + +args=(""$@"") + +#to keep things readable assign vars +input_ref=""${args[0]}"" +input_query=""${args[1]}"" +ordered_contigs=""${args[2]}"" +use_bin=""${args[3]}"" +non=""${args[4]}"" +append_bin=""${args[5]}"" +out_bin=""${args[6]}"" +out_crunch=""${args[7]}"" +out_gaps=""${args[8]}"" +out_fasta=""${args[9]}"" +out_tab=""${args[10]}"" +out_unused=""${args[11]}"" +out_multi=""${args[12]}"" +out_binmulti=""${args[13]}"" +out_nonpseudo=""${args[14]}"" + +##ok lets do up the optional tags.....I have four thus far +##generate ordered multifasta file + +if [ ""$ordered_contigs"" == ""yes"" ]; then + options=""-m"" +fi + +if [ ""$use_bin"" == ""yes"" ]; then + options=""$options -b"" +fi + +if [ ""$non"" == ""yes"" ]; then + options=""$options -N"" +fi + +if [ ""$append_bin"" == ""yes"" ]; then + options=""$options -a"" +fi + +options=""$options -o ab_out"" + +script_path=""$( cd ""$( dirname ""${BASH_SOURCE[0]}"" )"" && pwd)"" + +#run abacas +eval ""perl $script_path/abacas.1.1.pl $options -r $input_ref -q $input_query -p nucmer"" +echo ""perl $script_path/abacas.1.1.pl $options -r $input_ref -q $input_query -p nucmer"" +#ok now we have to remove the nucmer files to cleanup a bit... +rm nucmer.delta +rm nucmer.filtered.delta +rm nucmer.tiling + +#name the datafiles properly +mv ab_out.bin ""$out_bin"" +if [ ""$ordered_contigs"" == ""yes"" ]; then + mv ab_out.contigs.fas ""$out_multi"" +fi + +if [ ""$use_bin"" == ""yes"" ]; then + mv ab_out.contigsInbin.fas ""$out_binmulti"" +fi + +mv ab_out.crunch ""$out_crunch"" +mv ab_out.fasta ""$out_fasta"" +mv ab_out.gaps ""$out_gaps"" + +if [ ""$non"" == ""yes"" ]; then + mv ab_out.NoNs.fasta ""$out_nonpseudo"" +fi + +mv ab_out.tab ""$out_tab"" +mv unused_contigs.out ""$out_unused"" + +#end script for now +","Shell" +"Microbiology","phac-nml/galaxy_tools","tools/stringmlst/split_by_allele.py",".py","1922","76","#!/usr/bin/env python +import getopt +import os +import sys + +from Bio import SeqIO + +ERROR_MSG = ""Error could not parse out allele name and number from '%s'"" + + +def split_allele_file(alleles, profiles): + + writers = {} + + handle = open(alleles, ""rU"") + for record in SeqIO.parse(handle, ""fasta""): + + seqid = record.id + + # split out the alelle name from the version number + # attempting to split based on '-' first, if that fails, then '_' + result = seqid.split('_') + + if len(result) != 2: + result = seqid.split('-') + if len(result) == 2: + newid = '_'.join(result) + record.id = newid + else: + print(ERROR_MSG % seqid) + exit(0) + + name, num = result + + # if writer exist, then write to that current fasta file + if name in writers: + SeqIO.write(record, writers[name], ""fasta"") + else: + # new allele found, create new writer and add the first record + file_name = name + '.fasta' + output_fh = open(file_name, ""w"") + SeqIO.write(record, output_fh, ""fasta"") + writers[name] = output_fh + + handle.close() + + # create config file based on the alleles found + with open('config.txt', 'w') as cfile: + cfile.write(""[loci]\n"") + for name, writer in writers.items(): + path = os.path.realpath(writer.name) + cfile.write(""%s\t%s\n"" % (name, path)) + cfile.write(""[profile]\n"") + cfile.write(""profile\t%s\n"" % profiles) + + return + + +alleles = None +profiles = None + +""""""Input arguments"""""" +options, remainder = getopt.getopt(sys.argv[1:], '', [ + 'alleles=', + 'profiles=' +]) + +for opt, arg in options: + if opt in ('--alleles'): + alleles = arg + elif opt in ('--profiles'): + profiles = arg + +if alleles and profiles: + split_allele_file(alleles, profiles) +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/patrist/patrist.py",".py","5165","152","import argparse +import os +import sys + +from Bio import Phylo + + +def walk_up(tips, curnode, pathlen, cutoff): + """""" + Recursive function for traversing up a tree. + """""" + pathlen += curnode.branch_length + if pathlen < cutoff: + if curnode.is_terminal(): + tips.append((curnode.name, pathlen)) + else: + for c in curnode.clades: + tips = walk_up(tips, c, pathlen, cutoff) + return tips + + +def walk_trunk(curnode, cutoff, parents): + """""" + Find all tips in the tree that are within a threshold distance + of a reference tip. + """""" + # first go down to parent and up other branch + tips = [] + pathlen = curnode.branch_length # 0.0184788 + p = parents[curnode] + + for c in p.clades: + if c == curnode: + continue + if c.is_terminal(): + if pathlen + c.branch_length < cutoff: + tips.append((c.name, pathlen+c.branch_length)) + else: + tips.extend(walk_up([], c, pathlen, cutoff)) + + # next walk down trunk until path length exceeds cutoff or hit root + while p in parents: + curnode = p + pathlen += p.branch_length # + 0.0104047 + p = parents[curnode] + if pathlen >= cutoff: + break + for c in p.clades: + if c == curnode: + continue + if c.is_terminal(): + if pathlen + c.branch_length < cutoff: # + 0.0503079 + tips.append((c.name, pathlen+c.branch_length)) + else: + tips.extend(walk_up([], c, pathlen, cutoff)) + return tips + + +def find_short_edges(tree, cutoff, keep_ties=True, + minimize=False, returnlist=False): + """""" + Find the shortest edge from the earliest sequence of a patient to a + any sequence from any other patient. + minimize = keep only edge from earliest seq to the closest other seq + keep_ties = [to be used in conjunction with minimize] + report all edges with the same minimum distance + """""" + + # generate dictionary of child->parent associations + parents = {} + for clade in tree.find_clades(order='level'): + for child in clade: + parents.update({child: clade}) + + tips = tree.get_terminals() + res = {} + for tip1 in tips: + # find the shortest distance in sequences that ""cluster"" with this one + min_dist = 99999. + tip2 = [] + for tipname, dist in walk_trunk(tip1, cutoff, parents): + if minimize and dist < min_dist: + min_dist = dist + tip2 = [[tipname, dist]] + else: + tip2.append([tipname, dist]) + + t1 = tip1.name + for t2, dist in tip2: + # sort tip names in lexico order + key = (t1, t2) if t1 < t2 else (t2, t1) + if key in res: + continue + res.update({key: dist}) + if minimize and keep_ties: + # output only one edge + break + + if returnlist: + reslist = [] + for key, dist in res.iteritems(): + reslist.append((key[0], key[1], dist)) + return reslist + + return res + + +def main(): + parser = argparse.ArgumentParser( + description='Generate clusters of tips from a tree that have' + ' a path length within a maximum distance of each other.' + ) + parser.add_argument('tree', help=' file ' + 'containing Newick tree string.') + parser.add_argument('cutoff', type=float, help='Maximum ' + 'patristic distance.') + parser.add_argument('outfile', default=None, help=' file to ' + 'write results ' + 'in CSV format.') + parser.add_argument('--minimize', help='Report no more than ' + 'one nearest neighbour per tip.', + action='store_true') + parser.add_argument('--keep_ties', help='If more than one ' + 'tip has the same patristic distance, ' + 'report all as nearest neighbours.', + action='store_true') + parser.add_argument('--overwrite', help='Overwrite existing ' + 'output file.', + action='store_true') + args = parser.parse_args() + + assert args.cutoff > 0, 'Cutoff %f must be greater than 0.' % (args.cutoff) + + if os.path.exists(args.outfile) and not args.overwrite: + print ('Output file', args.outfile, 'already exists, use --overwrite.') + sys.exit() + + outfile = open(args.outfile, 'w') + outfile.write('tree,tip1,tip2,dist,is.tie\n') + + trees = Phylo.parse(args.tree, 'newick') + for treenum, tree in enumerate(trees): + results = find_short_edges(tree, args.cutoff) + for key, dist in results.items(): + outfile.write('%d,%s,%s,%f\n' % (treenum, key[0], key[1], dist)) + + outfile.close() + + +if __name__ == ""__main__"": + main() +","Python" +"Microbiology","phac-nml/galaxy_tools","tools/spolpred/spolpred.sh",".sh","85","11","#/bin/bash + +name=$1 +shift + +spolpred $@ + +sed -i ""s/^[^\t]*/$name/"" output.txt + +exit 0 +","Shell" +"Microbiology","phac-nml/galaxy_tools","tools/plasmid_profiler/plasmidprofile.R",".R","2460","60","#' RScript capable +#' Rscript plasmidprofile.R -b blast_runG.tsv -s srst2_runG.tsv -u 0.75 -l 10000 -t ""This is a test"" -a + + +suppressPackageStartupMessages(library(""optparse"")) +suppressPackageStartupMessages(library(""Plasmidprofiler"")) +options(bitmapType='cairo') + +cl_arguments <- function(){ + # CL arguments #### + option_list = list( + make_option(c(""-b"", ""--blastfile""), type=""character"", default=NULL, + help=""BLAST TSV file name"", metavar=""character""), + make_option(c(""-s"", ""--srst2file""), type=""character"", default=NULL, + help=""SRST2 TSV file name"", metavar=""character""), + make_option(c(""-u"", ""--sureness""), type=""numeric"", default=NA, + help=""Sureness cut off [default = %default]"", metavar=""numeric""), + make_option(c(""-c"", ""--coverage""), type=""numeric"", default=NA, + help=""Percent coverage cut off"", metavar=""numeric""), + make_option(c(""-l"", ""--length""), type=""numeric"", default=NA, + help=""Plasmid length cut off"", metavar=""numeric""), + make_option(c(""-a"", ""--anonymize""), action=""store_true"", default=NA, + help=""Anonymize plasmid and sample names""), + make_option(c(""-o"", ""--outfile""), type=""character"", default=""P2Run_"", + help=""Output filename prefix [default= %default]"", metavar=""character""), + make_option(c(""-t"", ""--title""), type=""character"", default=""Plasmid Profiles"", + help=""Title of image [default = %default]"", metavar=""character""), + make_option(c(""-C"", ""--combineincs""), action=""store_true"", default=NA, + help=""Combine very closely related incompatibility groups. eg. "") + # make_option(c(""-T"", ""--Test""), action=""store_true"", default=NA, + # help=""Test filecache"") + + ); + + opt_parser <- OptionParser(option_list=option_list); + opt <- parse_args(opt_parser); + + if (is.null(opt$blastfile) | is.null(opt$srst2file)){ + print_help(opt_parser) + stop(""SRST2 and BLAST files must be supplied."", call.=FALSE) + } + opt +} + + +opt <- cl_arguments() + +filecache <<- new.env(parent = .GlobalEnv) +assign(""name"", opt$outfile, envir = filecache) +assign(""mods"", ""Subsampling applied: "", envir = filecache) + +main(blast.file = opt$blastfile, + srst2.file = opt$srst2file, + coverage.filter = opt$coverage, + sureness.filter = opt$sureness, + length.filter = opt$length, + anonymize = opt$anonymize, + combine.inc = opt$combineincs, + main.title = opt$title) +","R" +"Microbiology","phac-nml/galaxy_tools","tools/combine_tabular_collection/combine.sh",".sh","219","25","#!/bin/bash + +output=$1 +shift + +i=1 + +for var in ""$@"" +do + if [[ -s $var ]] ; then + ( head -q -n 1 $var ) > $output + break + fi + i=$[i+1] +done + +if [ $i -le ""$#"" ] + then + ( tail -q -n +2 $@ )>> $output +else + exit 5 +fi + + +","Shell" +"Microbiology","phac-nml/galaxy_tools","tools/mykrobe_parser/mykrobe_parser.R",".R","18925","600","# Copyright Government of Canada 2018 +# +# Written by: National Microbiology Laboratory, Public Health Agency of Canada +# +# Licensed under the Apache License, Version 2.0 (the ""License""); you may not use +# this work except in compliance with the License. You may obtain a copy of the +# License at: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed +# under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR +# CONDITIONS OF ANY KIND, either express or implied. See the License for the +# specific language governing permissions and limitations under the License. + + +# Parsing JSONs from Mykrobe Predict into CSV reports +# Take the JSON output from Mykrobe, rearrange, output for LIMS +# Adrian Zetner +# August 2018 +# Updated August 2023 + +# Libraries #### + +sink(stdout(), type = ""message"") + +suppressPackageStartupMessages({ + library(jsonlite) + library(here) + library(dplyr) + library(purrr) + library(tidyr) + library(stringr) + library(optparse) +}) + +# Define custom functions, variables, and paths. Collect and use CL arguments #### + +# Here's a function to recreate that output table from the input JSON files for 2019 + +getResults2019 <- function(listelement) { + # Define list levels for various elements of the json + phylo_group <- + names(listelement[[1]][[""phylogenetics""]][[""phylo_group""]]) + if (""Non_tuberculosis_mycobacterium_complex"" %in% phylo_group) { + warning( + paste( + ""Non-tuberculosis mycobacteria detected in file "", + names(listelement), + "". Skipping."", + sep = """" + ) + ) + return() + } + + species <- + names(listelement[[1]][[""phylogenetics""]][[""species""]]) + lineage <- + if (length(listelement[[1]][[""phylogenetics""]][[""lineage""]]) == 1) { + names(listelement[[1]][[""phylogenetics""]][[""lineage""]]) + } else { + listelement[[1]][[""phylogenetics""]][[""lineage""]][[""lineage""]] + } + + # Start building a list of all your various elements + temp <- + list( + mykrobe_version = listelement[[1]][[""version""]][[""mykrobe-predictor""]], + file = names(listelement), + # One element + plate_name = ""test"", + # This probably needs changing + sample = ""sequence_calls"", + # Likewise change this + phylo_group = phylo_group, + # As above + species = species, + # As above + lineage = lineage, + # As above + # The following expressions drill down into the list elements and pull out what is needed. + # It's inelegant and vulnerable to changes in the input formats but if they're consistent it'll work + phylo_group_per_covg = listelement[[1]][[""phylogenetics""]][[""phylo_group""]][[phylo_group]][[""percent_coverage""]], + species_per_covg = listelement[[1]][[""phylogenetics""]][[""species""]][[species]][[""percent_coverage""]], + lineage_per_covg = listelement[[1]][[""phylogenetics""]][[""lineage""]][[lineage]][[""percent_coverage""]], + phylo_group_depth = listelement[[1]][[""phylogenetics""]][[""phylo_group""]][[phylo_group]][[""median_depth""]], + species_depth = listelement[[1]][[""phylogenetics""]][[""species""]][[species]][[""median_depth""]], + lineage_depth = listelement[[1]][[""phylogenetics""]][[""lineage""]][[lineage]][[""median_depth""]], + Mykrobe_Resistance_probe_set = basename(listelement[[1]][[""probe_sets""]][2]) # Is it always the second? + ) + + # Super cool nested and vectorized (for SPEED!) functions to grab the predictions for drug sensitivity and gene variants + # Both produce character vectors of the same length as the number of drugs tested in the same order + # All of these also check if there are missing values in drug/susceptibility/variant elements and adds the column anyhow + + if (length(map_chr(listelement[[1]][[""susceptibility""]], ""predict"")) != 0) { + temp$susceptibility <- + map_chr(listelement[[1]][[""susceptibility""]], ""predict"") + } else { + temp$susceptibility <- NA + } + + if (length(names(listelement[[1]][[""susceptibility""]])) != 0) { + temp$drug <- names(listelement[[1]][[""susceptibility""]]) + } else { + temp$drug <- NA + } + + mapped.variants <- + map( + listelement[[1]][[""susceptibility""]], # Dig into the lists, pull out variants and collapse into chr vector + ~ imap( + .x[[""called_by""]], # imap is shorthand for map2(x, names(x), ...), calling .y gets you the name / index of the current element + ~ paste(.y, + .x[[""info""]][[""coverage""]][[""alternate""]][[""median_depth""]], + .x[[""info""]][[""coverage""]][[""reference""]][[""median_depth""]], + .x[[""info""]][[""conf""]], + sep = "":"" + ) + ) + ) %>% + map_chr(~ paste(.x, collapse = ""__"")) + + if (length(mapped.variants) != 0) { + temp$`variants (gene:alt_depth:wt_depth:conf)` <- mapped.variants + } else { + temp$`variants (gene:alt_depth:wt_depth:conf)` <- NA + } + + temp$`genes (prot_mut-ref_mut:percent_covg:depth)` <- NA + + # Take that list and mash all the elements together as columns in a tibble, recycling as needed to fill in space + # eg. phylo_group is repeated/recycled as many times as there are drugs tested + as_tibble(temp) +} + +# Here's a function to recreate that output table from the input JSON files for panel 2020 + +getResults2020 <- function(listelement) { + # Define list levels for various elements of the json + phylo_group <- + names(listelement[[1]][[""phylogenetics""]][[""phylo_group""]]) + if (""Non_tuberculosis_mycobacterium_complex"" %in% phylo_group) { + warning( + paste( + ""Non-tuberculosis mycobacteria detected in file "", + names(listelement), + "". Skipping."", + sep = """" + ) + ) + return() + } + + species <- + names(listelement[[1]][[""phylogenetics""]][[""species""]]) + + # Start building a list of all your various elements + temp <- + list( + mykrobe_version = listelement[[1]][[""version""]][[""mykrobe-predictor""]], + file = names(listelement), + # One element + plate_name = ""test"", + # This probably needs changing + sample = ""sequence_calls"", + # Likewise change this + phylo_group = phylo_group, + # As above + species = species, + # As above + # The following expressions drill down into the list elements and pull out what is needed. + # It's inelegant and vulnerable to changes in the input formats but if they're consistent it'll work + phylo_group_per_covg = listelement[[1]][[""phylogenetics""]][[""phylo_group""]][[phylo_group]][[""percent_coverage""]], + species_per_covg = listelement[[1]][[""phylogenetics""]][[""species""]][[species]][[""percent_coverage""]], + phylo_group_depth = listelement[[1]][[""phylogenetics""]][[""phylo_group""]][[phylo_group]][[""median_depth""]], + species_depth = listelement[[1]][[""phylogenetics""]][[""species""]][[species]][[""median_depth""]], + Mykrobe_Resistance_probe_set = basename(listelement[[1]][[""probe_sets""]][2]) # Is it always the second? + ) + + # Super cool nested and vectorized (for SPEED!) functions to grab the predictions for drug sensitivity and gene variants + # Both produce character vectors of the same length as the number of drugs tested in the same order + # All of these also check if there are missing values in drug/susceptibility/variant elements and adds the column anyhow + + if (length(map_chr(listelement[[1]][[""susceptibility""]], ""predict"")) != 0) { + temp$susceptibility <- + map_chr(listelement[[1]][[""susceptibility""]], ""predict"") + } else { + temp$susceptibility <- NA + } + + if (length(names(listelement[[1]][[""susceptibility""]])) != 0) { + temp$drug <- names(listelement[[1]][[""susceptibility""]]) + } else { + temp$drug <- NA + } + + mapped.variants <- + map( + listelement[[1]][[""susceptibility""]], # Dig into the lists, pull out variants and collapse into chr vector + ~ imap( + .x[[""called_by""]], # imap is shorthand for map2(x, names(x), ...), calling .y gets you the name / index of the current element + ~ paste(.y, + .x[[""info""]][[""coverage""]][[""alternate""]][[""median_depth""]], + .x[[""info""]][[""coverage""]][[""reference""]][[""median_depth""]], + .x[[""info""]][[""conf""]], + sep = "":"" + ) + ) + ) %>% + map_chr(~ paste(.x, collapse = ""__"")) + + if (length(mapped.variants) != 0) { + temp$`variants (gene:alt_depth:wt_depth:conf)` <- mapped.variants + } else { + temp$`variants (gene:alt_depth:wt_depth:conf)` <- NA + } + + temp$`genes (prot_mut-ref_mut:percent_covg:depth)` <- NA + + # Take that list and mash all the elements together as columns in a tibble, recycling as needed to fill in space + # eg. phylo_group is repeated/recycled as many times as there are drugs tested + as_tibble(temp) +} + +# Get command line arguments with optparse +option_list <- list( + make_option( + c(""-f"", ""--file""), + type = ""character"", + default = NULL, + help = 'dataset file name or quoted comma separated names: eg. ""file1,file2,file3""', + metavar = ""character"" + ), + make_option( + c(""-d"", ""--dir""), + type = ""character"", + default = NULL, + help = ""directory location of json files"", + metavar = ""character"" + ), + make_option( + c(""-v"", ""--version""), + type = ""character"", + default = """", + help = ""Mykrobe Workflow Version"", + metavar = ""character"" + ), + make_option( + c(""-p"", ""--panel""), + type = ""character"", + default = ""2019"", + help = ""Mykrobe Panel Version: 2019 or 2020. [default= %default]"", + metavar = ""character"" + ), + make_option( + c(""-D"", ""--depth""), + type = ""integer"", + default = 5, + help = ""Minimum depth of coverage [default= %default]"", + metavar = ""integer"" + ), + make_option( + c(""-c"", ""--conf""), + type = ""integer"", + default = 10, + help = ""Minimum genotype confidence for variant genotyping [default= %default]"", + metavar = ""integer"" + ), + make_option( + c(""-n"", ""--name""), + type = ""character"", + default = """", + help = ""Name of the run"", + metavar = ""character"" + ), + make_option( + c(""-r"", ""--reportfile""), + type = ""character"", + default = ""report"", + help = ""File name for susceptibility report data"", + metavar = ""character"" + ), + make_option( + c(""-s"", ""--speciationfile""), + type = ""character"", + default = ""jsondata"", + help = ""File name for speciation data"", + metavar = ""character"" + ) +) + +opt_parser <- OptionParser(option_list = option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$file) && is.null(opt$dir)) { + print_help(opt_parser) + stop(""At least one argument must be supplied to input file or directory"", + call. = FALSE + ) +} + +if (opt$panel != ""2019"" && opt$panel != ""2020"") { + print_help(opt_parser) + stop(""Panel must be one of 2019 or 2020"", call. = FALSE) +} + +# Parameters to take from Galaxy/CL as args or however works best +params <- c( + """", # Lims_Comment + """", # Lims_INTComment + opt$version, # Mykrobe_Workflow_Version + opt$panel, # Mykrobe Panel Version + opt$depth, # Mykrobe_min_depth_default_5 + opt$conf, # Mykrobe_min_conf_default_10 + """", # LIMS_file - empty as it's an upload field in LIMS + opt$name +) # Mutation_set_version + +names(params) <- c( + ""Lims_Comment"", + ""Lims_INTComment"", + ""Mykrobe_Workflow_Version"", + ""Mykrobe_Panel_Version"", + ""Mykrobe_min_depth_default_5"", + ""Mykrobe_min_conf_default_10"", + ""LIMS_file"", + ""Mutation_set_version"" +) + + +# A default report in the order our LIMS requires + +# Make a default dataframe to combine the rest into and enforce column order / fill missing ones with NAs +columns <- c( + ""file"", + ""Mykrobe_fabG1"", + ""Mykrobe_katG"", + ""Mykrobe_ahpC"", + ""Mykrobe_inhA"", + ""Mykrobe_ndh"", + ""Isoniazid_R_mutations"", + ""Isoniazid_Prediction"", + ""Mykrobe_rpoB"", + ""Rifampicin_R_mutations"", + ""Rifampicin_Prediction"", + ""Mykrobe_embB"", + ""Mykrobe_embA"", + ""Ethambutol_R_mutations"", + ""Ethambutol_Prediction"", + ""Mykrobe_pncA"", + ""Mykrobe_rpsA"", + ""Pyrazinamide_R_mutations"", + ""Pyrazinamide_Prediction"", + ""Mykrobe_Ofloxacin_gyrA"", + ""Ofloxacin_R_mutations"", + ""Ofloxacin_Prediction"", + ""Mykrobe_Moxifloxacin_gyrA"", + ""Moxifloxacin_R_mutations"", + ""Moxifloxacin_Prediction"", + ""Mykrobe_Ciprofloxacin_gyrA"", + ""Ciprofloxacin_R_mutations"", + ""Ciprofloxacin_Prediction"", + ""Mykrobe_rpsL"", + ""Mykrobe_Streptomycin_rrs"", + ""Mykrobe_Streptomycin_gid"", + ""Streptomycin_R_mutations"", + ""Streptomycin_Prediction"", + ""Mykrobe_Amikacin_rrs"", + ""Amikacin_R_mutations"", + ""Amikacin_Prediction"", + ""Mykrobe_Capreomycin_rrs"", + ""Mykrobe_Capreomycin_tlyA"", + ""Capreomycin_R_mutations"", + ""Capreomycin_Prediction"", + ""Mykrobe_Kanamycin_rrs"", + ""Mykrobe_Kanamycin_eis"", + ""Kanamycin_R_mutations"", + ""Kanamycin_Prediction"", + ""Lims_Comment"", + ""Lims_INTComment"", + ""Mykrobe_Workflow_Version"", + ""mykrobe_version"", + ""Mykrobe_Resistance_probe_set"", + ""Mykrobe_min_depth_default_5"", + ""Mykrobe_min_conf_default_10"", + ""LIMS_file"", + ""Mutation_set_version"" +) + +report <- + setNames(data.frame(matrix( + """", + ncol = length(columns), nrow = 1 + ), stringsAsFactors = FALSE), columns) + +report_cols <- c( + ""file"", + ""phylo_group"", + ""species"", + ""lineage"", + ""phylo_group_per_covg"", + ""species_per_covg"", + ""lineage_per_covg"", + ""phylo_group_depth"", + ""species_depth"", + ""lineage_depth"" +) + +# List of drugs that are tested +all_drugs <- c( + ""Isoniazid"", + ""Rifampicin"", + ""Ethambutol"", + ""Pyrazinamide"", + ""Moxifloxacin"", + ""Ofloxacin"", + ""Streptomycin"", + ""Amikacin"", + ""Capreomycin"", + ""Kanamycin"" +) + +# Do Stuff #### + +# Import all the JSON files into a list of lists format #### + +if (is.null(opt$file)) { + # opt$dir is used to get the list of files, a vector of non-duplicated files is then passed to map + files <- list.files( + path = opt$dir, + pattern = ""*.json"", + full.names = TRUE + ) +} else { + files <- unlist(strsplit(opt$file, "","")) +} + +files <- files[!duplicated(basename(files))] + +list.of.json.files <- map( + files, + ~ fromJSON(.x, simplifyDataFrame = FALSE) +) + + +# Apply the correct getResults function to each element in your list then bash it together into a final report + +if (opt$panel == ""2019"") { + temp <- map(list.of.json.files, getResults2019) %>% + bind_rows() +} else if (opt$panel == ""2020"") { + temp <- map(list.of.json.files, getResults2020) %>% + bind_rows() + columns <- + setdiff( + columns, + c( + ""Mykrobe_Ciprofloxacin_gyrA"", + ""Ciprofloxacin_R_mutations"", + ""Ciprofloxacin_Prediction"" + ) + ) + report_cols <- setdiff( + report_cols, + c( + ""lineage"", + ""lineage_per_covg"", + ""lineage_depth"" + ) + ) +} else { + stop(""Panel must be one of 2019 or 2020"", call. = FALSE) +} + + +# Predictions of resistance or susceptibility + +predictions.table <- + temp %>% + select(file, drug, susceptibility) %>% + mutate(drug = paste(drug, ""_Prediction"", sep = """")) %>% + spread(drug, susceptibility, fill = ""failed"") %>% + select(-starts_with(""NA"")) + +if (length(predictions.table) == 1) { + print(predictions.table) + stop(""No susceptibility results in files specified. Did the testing fail?"", + call. = FALSE + ) +} + +# Variants, if present +num.variants <- + predictions.table %>% + select(ends_with(""_Prediction"")) %>% + unlist(use.names = FALSE) %>% + str_count(""[R,r]"") %>% + sum() + +if (num.variants > 0) { + # Multiple resistance mutations and confidence per drug in the X_R_mutations column + # Actual protein changes in Mykrobe_X columns + + variants.temp <- + temp %>% + select(file, drug, variants = `variants (gene:alt_depth:wt_depth:conf)`) %>% + mutate(variants = replace(variants, variants == """", NA)) %>% # Make missing data consistent... + filter(!is.na(variants)) %>% # ...Then get rid of it + mutate(tempcols = paste(drug, ""R_mutations"", sep = ""_"")) %>% + mutate(R_mutations = variants) %>% + mutate(variants = strsplit(variants, ""__"")) %>% # Split the mutations across rows (list first then split across rows) + unnest(variants) %>% + separate(variants, c(""gene"", ""mutation""), ""_"") %>% + mutate(columnname = ifelse( + gene %in% c(""gyrA"", ""rrs"", ""eis"", ""gid""), + # Check for columns that include the drug name or not and paste accordingly + paste(""Mykrobe"", drug, gene, sep = ""_""), + paste(""Mykrobe"", gene, sep = ""_"") + )) %>% + # Extract out the mutation information with a regex that covers all potential genes + # This regex looks for whatever is ahead of the first colon and after the last hyphen + mutate(mutation = str_match(mutation, ""(.*)-.*:"")[, 2]) %>% + select(file, tempcols, R_mutations, columnname, mutation) + + # Split each kind of variants into its own temp table then merge + variants.1 <- + variants.temp %>% + select(file, tempcols, R_mutations) %>% + distinct() %>% + spread(tempcols, R_mutations) + + variants.2 <- + variants.temp %>% + select(file, columnname, mutation) %>% + group_by(file, columnname) %>% + summarise(mutation = paste(mutation, collapse = "";"")) %>% + spread(columnname, mutation) + + variants.table <- + full_join(variants.1, variants.2, by = ""file"") +} else { + variants.table <- + data.frame(file = predictions.table$file, stringsAsFactors = FALSE) +} + + +# Make a report #### + +report <- + temp %>% + select(file, mykrobe_version, Mykrobe_Resistance_probe_set) %>% # Get important info from initial table + distinct() %>% # Drop duped rows and combine all the tables together + full_join(variants.table) %>% + full_join(predictions.table) %>% + bind_rows(report) %>% # Use bind_rows to add columns (eg. unteseted drugs) to the final output + filter(file != """") + +# Only add the 'no mutation' replacement to the columns that actually have a result +report <- + report %>% + filter_at(vars(ends_with(""_Prediction"")), any_vars(. != ""failed"")) %>% + mutate_at(vars(starts_with(""Mykrobe_"")), funs(replace(., is.na(.), ""No Mutation""))) %>% + full_join(anti_join(report, ., by = ""file"")) %>% + select(columns) + + +# Add in the parameters fed from Galaxy using named character vector +report <- + report %>% + mutate( + Lims_Comment = params[""Lims_Comment""], + Lims_INTComment = params[""Lims_INTComment""], + Mykrobe_Workflow_Version = params[""Mykrobe_Workflow_Version""], + Mykrobe_min_depth_default_5 = params[""Mykrobe_min_depth_default_5""], + Mykrobe_min_conf_default_10 = params[""Mykrobe_min_conf_default_10""], + LIMS_file = params[""LIMS_file""], + Mutation_set_version = params[""Mutation_set_version""] + ) + +# Write some output +# Report as is +write.csv(report, ""output-report.csv"", row.names = FALSE) +print(""Writing Susceptibility report to CSV as output-report.csv"") + +# Select specific columns from temp and output them +# Addition of any_of accounts for both 2019 and 2020 panels + +temp %>% + select_at( # This is a dplyr 0.8.3 function, superceded in newer versions but this tool is built around a number of specific deps + report_cols + ) %>% + distinct() %>% + write.csv(file = ""output-jsondata.csv"", row.names = FALSE) +print(""Writing JSON data to CSV as output-jsondata.csv"") +sink(NULL, type = ""message"") # close the sink + +quit() +","R"