├── tests ├── __init__.py ├── empty.fasta ├── 8Jun17.fasta.nhr ├── 8Jun17.fasta.nin ├── 8Jun17.fasta.nsq ├── isPcrPrim.tsv ├── isPcrPrim-Frost.tsv ├── blast.fa.tsv ├── amplicon.fasta ├── test_result_row.py ├── test_clusterer.py ├── test_run_emmtyper.py ├── test_blast.py ├── test_make_db.py ├── emm_clusters.csv ├── test_isPcr.py └── data.py ├── emmtyper ├── bin │ ├── __init__.py │ └── run_emmtyper.py ├── objects │ ├── __init__.py │ ├── emm.py │ ├── command.py │ ├── ispcr.py │ ├── result_row.py │ ├── blast.py │ └── clusterer.py ├── utilities │ ├── __init__.py │ ├── find.py │ ├── run_ispcr.py │ ├── run_blast.py │ └── make_db.py ├── db │ ├── emm.fna.nhr │ ├── emm.fna.nin │ ├── emm.fna.nsq │ └── db_metadata.json ├── data │ ├── isPcrPrim-Frost.tsv │ ├── isPcrPrim.tsv │ └── emm_clusters.csv └── __init__.py ├── .binder ├── runtime.txt └── requirements.txt ├── setup.cfg ├── .gitignore ├── pyproject.toml ├── dist ├── emmtyper-0.2.0-py3-none-any.whl └── emmtyper-0.2.1-py3-none-any.whl ├── .flake8 ├── .bumpversion.cfg ├── Pipfile ├── environment.yml ├── .pre-commit-config.yaml ├── .github └── workflows │ └── unit-tests.yml ├── tasks.py ├── setup.py ├── paper.md ├── README.md ├── Pipfile.lock └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /emmtyper/bin/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /emmtyper/objects/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /emmtyper/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.binder/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.7 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md -------------------------------------------------------------------------------- /tests/empty.fasta: -------------------------------------------------------------------------------- 1 | >contignull 2 | AGTCAGGATCAGAGACACCCCAATTGGACAGATACATCATCATG 3 | -------------------------------------------------------------------------------- /emmtyper/db/emm.fna.nhr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/emmtyper/db/emm.fna.nhr -------------------------------------------------------------------------------- /emmtyper/db/emm.fna.nin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/emmtyper/db/emm.fna.nin -------------------------------------------------------------------------------- /emmtyper/db/emm.fna.nsq: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/emmtyper/db/emm.fna.nsq -------------------------------------------------------------------------------- /tests/8Jun17.fasta.nhr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/tests/8Jun17.fasta.nhr -------------------------------------------------------------------------------- /tests/8Jun17.fasta.nin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/tests/8Jun17.fasta.nin -------------------------------------------------------------------------------- /tests/8Jun17.fasta.nsq: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/tests/8Jun17.fasta.nsq -------------------------------------------------------------------------------- /tests/isPcrPrim.tsv: -------------------------------------------------------------------------------- 1 | emm TATTCGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT 2 | emm2 TATTGGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT 3 | -------------------------------------------------------------------------------- /.binder/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.16.* 2 | matplotlib==3.1.* 3 | seaborn==0.9.* 4 | pandas==0.25.* 5 | plotly==4.1.* 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | emmtyper.egg-info/ 2 | __pycache__/ 3 | build/ 4 | .pytest_cache/ 5 | .coverage 6 | .vscode 7 | .idea 8 | /dist -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel"] 3 | build-backend = "setuptools.build_meta:__legacy__" -------------------------------------------------------------------------------- /tests/isPcrPrim-Frost.tsv: -------------------------------------------------------------------------------- 1 | emm TATTCGCTTAGAAAATTAA TTCTTCAAGCTCTTTGTT 2 | emm2 TATTGGCTTAGAAAATTAA TTCTTCAAGCTCTTTGTT 3 | -------------------------------------------------------------------------------- /dist/emmtyper-0.2.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/dist/emmtyper-0.2.0-py3-none-any.whl -------------------------------------------------------------------------------- /dist/emmtyper-0.2.1-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MDU-PHL/emmtyper/HEAD/dist/emmtyper-0.2.1-py3-none-any.whl -------------------------------------------------------------------------------- /emmtyper/data/isPcrPrim-Frost.tsv: -------------------------------------------------------------------------------- 1 | emm TATTCGCTTAGAAAATTAA TTCTTCAAGCTCTTTGTT 2 | emm2 TATTGGCTTAGAAAATTAA TTCTTCAAGCTCTTTGTT 3 | -------------------------------------------------------------------------------- /emmtyper/data/isPcrPrim.tsv: -------------------------------------------------------------------------------- 1 | emm TATTCGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT 2 | emm2 TATTGGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT 3 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E203, E266, E501, W503 3 | max-line-length = 80 4 | max-complexity = 18 5 | select = B,C,E,F,W,T4,B9 6 | -------------------------------------------------------------------------------- /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.1.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:emmtyper/__init__.py] 7 | -------------------------------------------------------------------------------- /emmtyper/db/db_metadata.json: -------------------------------------------------------------------------------- 1 | [{"updated_on": "2019-08-15", "host": "ftp.cdc.gov", "filename": "/pub/infectious_diseases/biotech/tsemm/trimmed.tfa", "uploaded_to_server_on": "2019-08-13"}] -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | "e1839a8" = {editable = true, path = "."} 8 | python-dateutil = "*" 9 | click = "*" 10 | 11 | [dev-packages] 12 | pytest = "*" 13 | bumpversion = "*" 14 | pytest-cov = "*" 15 | coveralls = "*" 16 | pre-commit = "*" 17 | twine = "*" 18 | invoke = "*" 19 | 20 | [requires] 21 | -------------------------------------------------------------------------------- /tests/blast.fa.tsv: -------------------------------------------------------------------------------- 1 | .blast.5 EMM65.0 100.000 180 0 0 82168 82347 1 180 1.89e-90 333 180 2 | .blast.5 EMM65.1 99.444 180 1 0 82168 82347 1 180 8.78e-89 327 180 3 | .blast.5 EMM65.4 98.889 180 2 0 82168 82347 1 180 4.08e-87 322 180 4 | .blast.5 EMM65.2 98.889 180 2 0 82168 82347 1 180 4.08e-87 322 180 5 | .blast.5 EMM65.3 98.333 180 3 0 82168 82347 1 180 1.90e-85 316 180 6 | .blast.5 EMM156.0 95.000 180 2 0 80776 80955 1 180 1.93e-75 283 180 -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: emmtyper 2 | channels: 3 | - conda-forge 4 | - bioconda 5 | - defaults 6 | dependencies: 7 | - blast>=2.10.1 8 | - ispcr>=33 9 | - pip>=21.0.1 10 | - python>=3.8 11 | - seqkit>=2.2.0 12 | - pip: 13 | - click>=7.1.2 14 | - numpy>=1.23.0 15 | - python-dateutil>=2.8.1 16 | - scipy>=1.6.0 17 | - -e . # editable install of emmtyper 18 | prefix: /usr/local/anaconda3/envs/emmtyper 19 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.1.0 4 | hooks: 5 | - id: trailing-whitespace 6 | - id: end-of-file-fixer 7 | - id: check-docstring-first 8 | - id: debug-statements 9 | - repo: https://github.com/ambv/black 10 | rev: stable 11 | hooks: 12 | - id: black 13 | language_version: python3.7 14 | - repo: https://gitlab.com/pycqa/flake8 15 | rev: 3.7.7 16 | hooks: 17 | - id: flake8 18 | -------------------------------------------------------------------------------- /emmtyper/utilities/find.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a wrapper function to find files in the package folder 3 | ''' 4 | import os 5 | 6 | 7 | def find(filename, path): 8 | ''' 9 | Given a filename and a path, walk all files and subfolders of path trying 10 | to find an exact match to filename. 11 | ''' 12 | for root, dirs, files in os.walk(os.path.dirname(path), topdown=True): 13 | for name in files: 14 | if name == filename: 15 | return os.path.join(root, name) 16 | -------------------------------------------------------------------------------- /emmtyper/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | emmtyper: an in silico EMM typer for Streptococcus pyogenes 3 | """ 4 | __name__ = "emmtyper" 5 | __version__ = "0.2.2" 6 | __author__ = "Andre Tan" 7 | __email__ = "andre.sutanto.91@gmail.com" 8 | __url__ = "https://github.com/MDUPHL/emmtyper" 9 | __license__ = "GPL-3.0" 10 | __description__ = "Streptococcus pyogenes in silico EMM typer" 11 | __maintainer__ = "Bioinformatics @ MDUPHL" 12 | __maintainer_email__ = "anders.goncalves@unimelb.edu.au" 13 | 14 | __epilog__ = """\ 15 | Developed by {} ({}) 16 | Maintained by {} ({}) 17 | Distributed under {} license 18 | © 2019 {}""".format( 19 | __author__, __email__, __maintainer__, __maintainer_email__, __license__, __author__ 20 | ) 21 | -------------------------------------------------------------------------------- /emmtyper/utilities/run_ispcr.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define the workflow to run PCR using isPcr 3 | """ 4 | from os import environ 5 | import logging 6 | 7 | from emmtyper.objects.ispcr import IsPCR 8 | 9 | 10 | logging.basicConfig(level=environ.get("LOGLEVEL", "INFO")) 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def get_amplicons(query, primer_db, min_perfect, min_good, max_size, tile_size, step_size, tool_path): 15 | """ 16 | Run isPcr and return temporary file with amplicons 17 | """ 18 | pcr_amplicons = query.split("/")[-1].split(".")[0] + "_pcr.tmp" 19 | 20 | pcr = IsPCR( 21 | assembly_filename=query, 22 | primer_filename=primer_db, 23 | min_perfect=min_perfect, 24 | min_good=min_good, 25 | tile_size=tile_size, 26 | step_size=step_size, 27 | max_product_length=max_size, 28 | output_stream="stdout", 29 | tool_path=tool_path, 30 | ) 31 | 32 | # Run isPcr, take output and use it as input for Blast. 33 | with open(pcr_amplicons, "w") as temp: 34 | temp.write(pcr.run_isPCR()) 35 | 36 | return pcr_amplicons 37 | -------------------------------------------------------------------------------- /emmtyper/utilities/run_blast.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define the workflow to run BLAST 3 | """ 4 | from os import environ 5 | import logging 6 | 7 | from emmtyper.objects.blast import BLAST 8 | 9 | 10 | logging.basicConfig(level=environ.get("LOGLEVEL", "INFO")) 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def get_matches( 15 | query, 16 | blast_db, 17 | dust, 18 | percent_identity, 19 | culling_limit, 20 | mismatch, 21 | align_diff, 22 | gap, 23 | tool_path, 24 | ): 25 | """ 26 | Run BLAST and return a temporary file with matches 27 | """ 28 | blast_matches = query.split("/")[-1].split(".")[0] + ".tmp" 29 | 30 | blast = BLAST( 31 | db=blast_db, 32 | query=query, 33 | dust=dust, 34 | perc_identity=percent_identity, 35 | culling_limit=culling_limit, 36 | output_stream=blast_matches, 37 | header=False, 38 | mismatch=mismatch, 39 | align_diff=align_diff, 40 | gap=gap, 41 | tool_path=tool_path, 42 | ) 43 | 44 | blast.run_blastn_pipeline() 45 | 46 | return blast_matches 47 | -------------------------------------------------------------------------------- /.github/workflows/unit-tests.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build-linux: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: Set up Python 3.10 11 | uses: actions/setup-python@v4 12 | with: 13 | python-version: 14 | '3.10' 15 | - name: Add conda to system path 16 | run: | 17 | # $CONDA is an environment variable pointing to the root of the miniconda directory 18 | echo $CONDA/bin >> $GITHUB_PATH 19 | - name: Install dependencies 20 | run: | 21 | conda env update --file environment.yml --name base 22 | - name: Lint with flake8 23 | run: | 24 | conda install flake8 25 | # stop the build if there are Python syntax errors or undefined names 26 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 27 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 28 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 29 | - name: Test with pytest 30 | run: | 31 | conda install pytest 32 | pytest 33 | -------------------------------------------------------------------------------- /tests/amplicon.fasta: -------------------------------------------------------------------------------- 1 | >contig1:113750+114924 emm 1175bp TATTCGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT\nTATTCGCTTAGAAAATTAAaaacaggaacggcttcagtagcggtagcttt\ngactgttttaggggcaggttttgcgaatcaaacagaggttaaggctaacg\ngtgatggtaatcctagggaagttatagaagatcttgcagcaaacaatccc\ngcaatacaaaatatacgtttacgtcacgaaaacaaggacttaaaagcgag\nattagagaatgcaatggaagttgcaggaagagattttaagagagctgaag\naacttgaaaaagcaaaacaagccttagaagaccagcgtaaagatttagaa\nactaaattaaaagaactacaacaagactatgacttagcaaaggaatcaac\naagttgggatagacaaagacttgaaaaagagttagaagagaaaaaggaag\nctcttgaattagcgatagaccaggcaagtcgggactaccatagagctacc\ngctttagaaaaagagttagaagagaaaaagaaagctcttgaattagcgat\nagaccaagcgagtcaggactataatagagctaacgtcttagaaaaagagt\ntagaaacgattactagagaacaagagattaatcgtaatcttttaggcaat\ngcaaaacttgaacttgatcaactttcatctgaaaaagagcagctaacgat\ncgaaaaagcaaaacttgaggaagaaaaacaaatctcagacgcaagtcgtc\naaagccttcgtcgtgacttggacgcatcacgtgaagctaagaaacaggtt\ngaaaaagatttagcaaacttgactgctgaacttgataaggttaaagaaga\ncaaacaaatctcagacgcaagccgtcaaggccttcgccgtgacttggacg\ncatcacgtgaagctaagaaacaggttgaaaaagatttagcaaacttgact\ngctgaacttgataaggttaaagaagaaaaacaaatctcagacgcaagccg\ntcaaggccttcgccgtgacttggacgcatcacgtgaagctaagaaacaag\nttgaaaaagctttagaagaagcaaacagcaaattagctgctcttgaaaaa\ncttaacaaagagcttgaagaaagcaagaaattaacagaaaaagaaaaagc\ntgaactacaagcaaaacttgaagcagaagcaaaagcactcaaagaacaat\ntagcgAAACAAGCTGAAGAACTcGC 2 | -------------------------------------------------------------------------------- /tasks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Automate deployment to PyPi 3 | """ 4 | 5 | import invoke 6 | 7 | 8 | @invoke.task 9 | def deploy_patch(ctx): 10 | """ 11 | Automate deployment 12 | rm -rf build/* dist/* 13 | bumpversion patch --verbose 14 | python3 setup.py sdist bdist_wheel 15 | twine upload dist/* 16 | git push --tags 17 | """ 18 | ctx.run("rm -rf build/* dist/*") 19 | ctx.run("bumpversion patch --verbose") 20 | ctx.run("python3 setup.py sdist bdist_wheel") 21 | ctx.run("twine check dist/*") 22 | ctx.run("twine upload dist/*") 23 | ctx.run("git push --tags") 24 | 25 | 26 | @invoke.task 27 | def check_for_unstaged_changes(ctx): 28 | """ 29 | If unstaged changes raise an error 30 | """ 31 | try: 32 | ctx.run("git diff-index --quiet HEAD") 33 | except invoke.exceptions.UnexpectedExit as error: 34 | print(("ERROR: There are unstaged changes.")) 35 | raise error 36 | except Exception as error: 37 | raise error 38 | 39 | 40 | @invoke.task(pre=[check_for_unstaged_changes]) 41 | def first_deploy(ctx): 42 | """ 43 | First deployment 44 | """ 45 | ctx.run("python3 setup.py sdist bdist_wheel") 46 | ctx.run("twine check dist/*") 47 | ctx.run("twine upload dist/*") 48 | ctx.run("git tag 'v0.1.0'") 49 | ctx.run("git push --tags") 50 | -------------------------------------------------------------------------------- /tests/test_result_row.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from emmtyper.objects.result_row import ResultRow, WrongLengthException 3 | from tests.data import * 4 | 5 | row = ResultRow(string) 6 | row_not100 = ResultRow(string_not100) 7 | row_imp = ResultRow(string_imp) 8 | 9 | 10 | class TestResultMethods(unittest.TestCase): 11 | def test_null(self): 12 | self.assertEqual(test_null, "this is a null test") 13 | 14 | def test_is_row(self): 15 | self.assertIs(type(row), ResultRow) 16 | 17 | def test_raises_wrong_length(self): 18 | self.assertRaises(WrongLengthException, ResultRow, string_long) 19 | 20 | def test_build_header(self): 21 | self.assertEqual(row.build_header(), header) 22 | 23 | def test_mismatch(self): 24 | self.assertTrue(row.mismatch_k(4)) 25 | 26 | def test_align_diff(self): 27 | self.assertTrue(row.alignment_to_subject_length_k(5)) 28 | 29 | def test_gap(self): 30 | self.assertTrue(row.gap_k(2)) 31 | 32 | def test_filter_me(self): 33 | self.assertTrue(row.filter(mismatch=4, align_diff=5, gap=2)) 34 | 35 | def test_string_representation(self): 36 | self.assertEqual(str(row), string_str) 37 | self.assertEqual(str(row_not100), string_not100_str) 38 | self.assertEqual(str(row_imp), string_imp_str) 39 | 40 | 41 | if __name__ == "__main__": 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /emmtyper/objects/emm.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define the EMM class 3 | ''' 4 | import pathlib 5 | from emmtyper.utilities.find import find 6 | 7 | EMM_CLUSTERS = pathlib.Path(__file__).parent.parent / "data" / "emm_clusters.csv" 8 | 9 | cluster_translations = dict() 10 | 11 | with open(EMM_CLUSTERS) as handle: 12 | for line in handle.readlines(): 13 | emm, cluster = line.split(",") 14 | cluster_translations[emm] = cluster.strip() 15 | 16 | # Add nonexistent EMM0 as null result 17 | cluster_translations["0"] = "-" 18 | 19 | 20 | class EMM: 21 | ''' 22 | Identify to which cluster the emm type belongs 23 | ''' 24 | def __init__(self, string): 25 | self.number = "".join([char for char in string if char.isdigit()]) 26 | self.code = "".join([char for char in string if not char.isdigit()]) 27 | self.emm_cluster = self.translate_to_cluster() 28 | 29 | def translate_to_cluster(self): 30 | if self.code == "EMM": 31 | # The try/except block will catch emm-types 32 | # that are not assigned to a cluster 33 | try: 34 | return cluster_translations[self.number] 35 | except KeyError: 36 | return cluster_translations["0"] 37 | 38 | return cluster_translations["0"] 39 | 40 | def __str__(self): 41 | return "{} is in Cluster {}".format(self.blastHit, self.emm_cluster) 42 | -------------------------------------------------------------------------------- /tests/test_clusterer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test the Clustered object 3 | """ 4 | import unittest 5 | 6 | from emmtyper.objects.clusterer import Clusterer 7 | from tests.data import ( 8 | test_blast_product, 9 | test_null, 10 | clusterer_repr_short, 11 | clusterer_repr_verbose, 12 | clusterer_result_short, 13 | clusterer_result_verbose, 14 | ) 15 | 16 | # Single BLAST output file 17 | 18 | clusterer = Clusterer( 19 | blastOutputFile=test_blast_product, 20 | output_stream="stdout", 21 | output_type="short", 22 | header=False, 23 | distance=800, 24 | ) 25 | 26 | clusterer_verbose = Clusterer( 27 | blastOutputFile=test_blast_product, 28 | output_stream="stdout", 29 | output_type="verbose", 30 | header=True, 31 | distance=800, 32 | ) 33 | 34 | 35 | class testClusterer(unittest.TestCase): 36 | def test_null(self): 37 | self.assertEqual(test_null, "this is a null test") 38 | 39 | def test_is_clusterer(self): 40 | self.assertIs(type(clusterer), Clusterer) 41 | self.assertIs(type(clusterer_verbose), Clusterer) 42 | 43 | def test_repr_short(self): 44 | self.assertEqual(repr(clusterer), clusterer_repr_short) 45 | self.assertEqual(repr(clusterer_verbose), clusterer_repr_verbose) 46 | 47 | def test_run_short(self): 48 | self.assertEqual(clusterer(), clusterer_result_short) 49 | 50 | def test_run_verbose(self): 51 | self.assertEqual(clusterer_verbose(), clusterer_result_verbose) 52 | 53 | 54 | if __name__ == "__main__": 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /tests/test_run_emmtyper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test the command line intereface 3 | """ 4 | 5 | from click.testing import CliRunner 6 | from emmtyper.bin.run_emmtyper import main 7 | from emmtyper import __version__ as version 8 | 9 | from tests.data import test_sequence_path, primer_path_cdc 10 | 11 | 12 | runner = CliRunner() 13 | 14 | 15 | def test_run_emmtyper_version(): 16 | """ 17 | Test emmtyper --version flag 18 | """ 19 | result = runner.invoke(main, ["--version"]) 20 | assert result.exit_code == 0 21 | assert result.output == f"emmtyper v{version}\n" 22 | 23 | """ 24 | def test_run_emmtyper_basic_blast(): 25 | #Test basic blast workflow 26 | 27 | result = runner.invoke(main, [test_sequence_path]) 28 | assert result.exit_code == 0 29 | assert result.output == "contig.tmp\t1\t_emm_1.0\t\tA-C3\n" 30 | 31 | 32 | def test_run_emmtyper_cdc_ispcr(): 33 | 34 | #Test basic ispcr workflow 35 | 36 | result = runner.invoke(main, ["-w", "pcr", "--pcr-primers", "cdc", test_sequence_path]) 37 | assert result.exit_code == 0 38 | assert result.output == "contig_pcr.tmp\t1\t_emm_1.0\t\tA-C3\n" 39 | 40 | def test_run_emmtyper_frost_ispcr(): 41 | 42 | #Test basic ispcr workflow 43 | 44 | result = runner.invoke(main, ["-w", "pcr", "--pcr-primers", "frost", test_sequence_path]) 45 | assert result.exit_code == 0 46 | assert result.output == "contig_pcr.tmp\t1\t_emm_1.0\t\tA-C3\n" 47 | 48 | def test_run_emmtyper_user_ispcr(): 49 | 50 | #Test basic ispcr workflow 51 | 52 | result = runner.invoke(main, ["-w", "pcr", "--primer-db", primer_path_cdc, test_sequence_path]) 53 | assert result.exit_code == 0 54 | assert result.output == "contig_pcr.tmp\t1\t_emm_1.0\t\tA-C3\n" 55 | """ 56 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from sys import exit, version_info 2 | from setuptools import setup, find_packages 3 | from os import environ 4 | import logging 5 | import emmtyper 6 | 7 | logging.basicConfig(level=environ.get("LOGLEVEL", "INFO")) 8 | 9 | if version_info <= (3, 0): 10 | logging.fatal("Sorry, requires Python 3.x, not Python 2.x\n") 11 | exit(1) 12 | 13 | 14 | with open("README.md", "r") as f: 15 | long_description = f.read() 16 | 17 | setup( 18 | name=emmtyper.__name__, 19 | version=emmtyper.__version__, 20 | description=emmtyper.__description__, 21 | long_description=long_description, 22 | long_description_content_type="text/markdown", 23 | url=emmtyper.__url__, 24 | author=emmtyper.__author__, 25 | author_email=emmtyper.__email__, 26 | maintainer=emmtyper.__maintainer__, 27 | maintainer_email=emmtyper.__maintainer_email__, 28 | license=emmtyper.__license__, 29 | python_requires=">=3.6, <4", 30 | packages=find_packages(exclude=["contrib", "docs", "tests"]), 31 | zip_safe=False, 32 | install_requires=["scipy>=1.1.0", "numpy>=1.15.0", "python-dateutil", "click"], 33 | test_suite="nose.collector", 34 | tests_require=["nose"], 35 | entry_points={ 36 | "console_scripts": [ 37 | "emmtyper=emmtyper.bin.run_emmtyper:main", 38 | "emmtyper-db=emmtyper.utilities.make_db:emmtyper_db", 39 | ] 40 | }, 41 | classifiers=[ 42 | "Development Status :: 4 - Beta", 43 | "Programming Language :: Python :: Implementation :: CPython", 44 | "Intended Audience :: Science/Research", 45 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 46 | "Natural Language :: English", 47 | "Programming Language :: Python :: 3 :: Only", 48 | "Programming Language :: Python :: 3.6", 49 | "Programming Language :: Python :: 3.7", 50 | "Topic :: Scientific/Engineering :: Bio-Informatics", 51 | ], 52 | package_data={"emmtyper": ["data/*", "db/*"]}, 53 | ) 54 | -------------------------------------------------------------------------------- /emmtyper/objects/command.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define the Command class to provide a wrapper around subprocess and run shell commands 3 | ''' 4 | from os import path, environ 5 | import shutil 6 | import subprocess 7 | import logging 8 | 9 | from sys import exit 10 | from abc import ABCMeta, abstractmethod, abstractproperty 11 | 12 | logging.basicConfig(level=environ.get("LOGLEVEL", "DEBUG")) 13 | logger = logging.getLogger() 14 | 15 | 16 | class FileNotInPathException(Exception): 17 | ''' 18 | Custom exception for missing file 19 | ''' 20 | pass 21 | 22 | 23 | class Command(object, metaclass=ABCMeta): 24 | ''' 25 | A wrapper class to run shell commands using subprocess 26 | ''' 27 | @abstractmethod 28 | def __init__(self, tool_name, tool_path=None): 29 | 30 | self.tool_name = tool_name 31 | if tool_path is None: 32 | self.tool_path = self.get_tool_path() 33 | else: 34 | self.tool_path = tool_path 35 | self.version = None 36 | self.command_string = None 37 | self.output_stream = None 38 | 39 | def get_tool_path(self): 40 | """Check whether tool exists. If True, return path to the tool.""" 41 | tool_path = shutil.which(self.tool_name) 42 | 43 | if tool_path == None: 44 | raise FileNotInPathException( 45 | "{} does not exist in $PATH!".format(self.tool_name) 46 | ) 47 | exit(1) 48 | 49 | return tool_path 50 | 51 | @staticmethod 52 | def assert_filepath_and_return(file_path): 53 | 54 | if not path.isfile(file_path): 55 | raise FileNotInPathException("{} is not a file!".format(file_path)) 56 | exit(1) 57 | 58 | return file_path 59 | 60 | def run(self): 61 | process = subprocess.Popen( 62 | args=self.command_string, 63 | shell=True, 64 | stdout=subprocess.PIPE, 65 | stderr=subprocess.PIPE, 66 | ) 67 | 68 | stdout, stderr = process.communicate() 69 | 70 | if stderr.decode("ascii"): 71 | logger.warning("{}: {}".format(self.tool_name, stderr.decode("ascii")[:-1])) 72 | 73 | return stdout.decode("ascii") 74 | -------------------------------------------------------------------------------- /tests/test_blast.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from emmtyper.objects.blast import BLAST 4 | from tests.data import test_sequence_path, db, \ 5 | test_empty_path, blast_command, \ 6 | blast_command_h, blast_result, \ 7 | test_null, header 8 | 9 | # Normal no nonsense BLAST. 10 | blast = BLAST( 11 | db, 12 | test_sequence_path, 13 | dust="no", 14 | perc_identity=95, 15 | culling_limit=1, 16 | output_stream=None, 17 | header=False, 18 | mismatch=4, 19 | align_diff=5, 20 | gap=2, 21 | tool_path=None, 22 | ) 23 | 24 | # BLAST result with header. 25 | blast_h = BLAST( 26 | db, 27 | test_sequence_path, 28 | dust="no", 29 | perc_identity=100, 30 | culling_limit=1, 31 | output_stream=None, 32 | header=True, 33 | mismatch=4, 34 | align_diff=5, 35 | gap=2, 36 | tool_path=None, 37 | ) 38 | 39 | # BLAST result will be empty. 40 | blast_e = BLAST( 41 | db, 42 | test_empty_path, 43 | dust="no", 44 | perc_identity=100, 45 | culling_limit=1, 46 | output_stream=None, 47 | header=True, 48 | mismatch=0, 49 | align_diff=0, 50 | gap=0, 51 | tool_path=None, 52 | ) 53 | 54 | 55 | class testBLASTapp(unittest.TestCase): 56 | def test_sanity(self): 57 | self.assertEqual(test_null, "this is a null test") 58 | 59 | def test_is_BLAST(self): 60 | self.assertIs(type(blast), BLAST) 61 | self.assertIs(type(blast_h), BLAST) 62 | 63 | def test_b_repr(self): 64 | self.assertTrue(blast_command in repr(blast)) 65 | 66 | def test_b_command(self): 67 | self.assertTrue(blast_command in blast.build_blastn_command()) 68 | 69 | def test_b_out(self): 70 | self.assertEqual(blast.run_blastn_pipeline(), blast_result) 71 | 72 | def test_h_command(self): 73 | self.assertTrue(blast_command_h in blast_h.build_blastn_command()) 74 | 75 | def test_h_out(self): 76 | self.assertEqual(blast_h.run_blastn_pipeline(), header + blast_result) 77 | 78 | def test_e_out(self): 79 | self.assertEqual(blast_e.run_blastn_pipeline(), "") 80 | 81 | 82 | if __name__ == "__main__": 83 | unittest.main() 84 | -------------------------------------------------------------------------------- /tests/test_make_db.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import pathlib 4 | from emmtyper.utilities import make_db 5 | 6 | 7 | db_hist = json.loads('[{"updated_on": "2019-08-15", "host": "ftp.cdc.gov", "filename": "/pub/infectious_diseases/biotech/tsemm/trimmed.tfa", "uploaded_to_server_on": "2019-08-13"}, \ 8 | {"updated_on": "2020-10-01", "host": "ftp.cdc.gov", "filename": "/pub/infectious_diseases/biotech/tsemm/trimmed.tfa", "uploaded_to_server_on": "2020-09-29"}]') 9 | 10 | 11 | def test_load_db_history(tmp_path): 12 | db_hist_path = tmp_path / "db_hist.json" 13 | with open(db_hist_path, "w") as db_hist_file: 14 | json.dump(db_hist, db_hist_file) 15 | db_instance = make_db.DBMetadata(db_hist_path, "email@example.com") 16 | 17 | assert db_instance.metad["updated_on"] == datetime.datetime(2020, 10, 1, 0, 0) 18 | assert db_instance.metad["host"] == "ftp.cdc.gov" 19 | assert db_instance.metad["filename"] == "/pub/infectious_diseases/biotech/tsemm/trimmed.tfa" 20 | assert db_instance.metad["uploaded_to_server_on"] == datetime.datetime(2020, 9, 29, 0, 0) 21 | 22 | def test_update_history(tmp_path): 23 | db_hist_path = tmp_path / "db_hist.json" 24 | with open(db_hist_path, "w") as db_hist_file: 25 | json.dump(db_hist, db_hist_file) 26 | db_instance = make_db.DBMetadata(db_hist_path, "email@example.com") 27 | db_instance.update_info("updated_on", datetime.datetime(2021, 3, 3, 0, 0)) 28 | db_instance.update_info("uploaded_to_server_on", datetime.datetime(2021, 3, 1, 0, 0)) 29 | db_instance.update_metadata_file() 30 | with open(db_hist_path) as db_hist_file: 31 | db_hist_new = json.load(db_hist_file, object_hook=make_db.decode_history) 32 | assert len(db_hist_new) == 3 33 | assert db_hist_new[-1]["updated_on"] == datetime.datetime(2021, 3, 3, 0, 0) 34 | assert db_hist_new[-1]["uploaded_to_server_on"] == datetime.datetime(2021, 3, 1, 0, 0) 35 | 36 | def test_make_db(tmp_path): 37 | fasta = tmp_path / "trimmed.tfa" 38 | local_fasta = pathlib.Path(__file__).parent / "8Jun17.fasta" 39 | fasta.write_bytes(local_fasta.read_bytes()) 40 | db_instance = make_db.DBMetadata(tmp_path / "db_hist.json", "email@example.com") 41 | db_instance.make_db(fasta) 42 | db_instance.update_metadata_file() 43 | p = [p.name for p in pathlib.Path(tmp_path).glob("*.tfa*")] 44 | assert 'trimmed.tfa.clean' in p 45 | assert 'trimmed.tfa.ndb' in p 46 | assert 'trimmed.tfa.nhr' in p 47 | assert 'trimmed.tfa' in p 48 | assert 'trimmed.tfa.nto' in p 49 | assert 'trimmed.tfa.ntf' in p 50 | assert 'trimmed.tfa.not' in p 51 | assert 'trimmed.tfa.nsq' in p 52 | assert 'trimmed.tfa.nin' in p 53 | with open(tmp_path / "db_hist.json") as db_hist_file: 54 | db_hist_new = json.load(db_hist_file, object_hook=make_db.decode_history) 55 | assert len(db_hist_new) == 1 56 | assert db_hist_new[-1]['total_seqs'] == 1819 57 | assert db_hist_new[-1]['total_duplicate_seqs'] == 7 58 | -------------------------------------------------------------------------------- /tests/emm_clusters.csv: -------------------------------------------------------------------------------- 1 | 1,A-C3 2 | 2,E4 3 | 3,A-C5 4 | 4,E1 5 | 5,Single protein cluster clade Y 6 | 6,Single protein cluster clade Y 7 | 8,E4 8 | 9,E3 9 | 11,E6 10 | 12,A-C4 11 | 13,E2 12 | 14,Single protein cluster clade Y 13 | 15,E3 14 | 17,Single protein cluster clade Y 15 | 18,Single protein cluster clade Y 16 | 19,Single protein cluster clade Y 17 | 22,E4 18 | 23,Single protein cluster clade Y 19 | 24,Single protein cluster clade Y 20 | 25,E3 21 | 26,Single protein cluster clade Y 22 | 27,E2 23 | 28,E4 24 | 29,Single protein cluster clade Y 25 | 30,A-C2 26 | 31,A-C5 27 | 32,D2 28 | 33,D4 29 | 34,E5 30 | 36,D1 31 | 37,Single protein cluster clade Y 32 | 38,Single protein cluster clade Y 33 | 39,A-C4 34 | 41,D4 35 | 42,E6 36 | 43,D4 37 | 44,E3 38 | 46,A-C1 39 | 47,Single protein cluster clade Y 40 | 48,E6 41 | 49,E3 42 | 50,E2 43 | 51,E5 44 | 52,D4 45 | 53,D4 46 | 54,D1 47 | 55,Single protein cluster clade Y 48 | 56,D4 49 | 56.2,D4 50 | 57,Single protein cluster clade Y 51 | 58,E3 52 | 59,E6 53 | 60,E1 54 | 63,E6 55 | 64,D4 56 | 65,E6 57 | 66,E2 58 | 67,E6 59 | 68,E2 60 | 70,D4 61 | 71,D2 62 | 72,D4 63 | 73,E4 64 | 74,Single protein cluster clade Y 65 | 75,E6 66 | 76,E2 67 | 77,E4 68 | 78,E1 69 | 79,E3 70 | 80,D4 71 | 81,E6 72 | 82,E3 73 | 83,D4 74 | 84,E4 75 | 85,E6 76 | 86,D4 77 | 87,E3 78 | 88,E4 79 | 89,E4 80 | 90,E2 81 | 91,D4 82 | 92,E2 83 | 93,D4 84 | 94,E6 85 | 95,Single protein cluster clade Y 86 | 96,E2 87 | 97,D5 88 | 98,D4 89 | 99,E6 90 | 100,D2 91 | 101,D4 92 | 102,E4 93 | 103,E3 94 | 104,E2 95 | 105,Single protein cluster clade Y 96 | 106,E2 97 | 107,E3 98 | 108,D4 99 | 109,E4 100 | 110,E2 101 | 111,Single protein cluster clade Y 102 | 112,E4 103 | 113,E3 104 | 114,E4 105 | 115,D2 106 | 116,D4 107 | 117,E2 108 | 118,E3 109 | 119,D4 110 | 120,D4 111 | 121,D4 112 | 122,Single protein cluster clade Y 113 | 123,D3 114 | 124,E4 115 | 133,A-C5 116 | 134,E5 117 | 137,E5 118 | 139,E6 119 | 140,Single protein cluster clade Y 120 | 142,A-C1 121 | 144,E3 122 | 157,D5 123 | 158,E6 124 | 163,A-C3 125 | 164,Single protein cluster clade X 126 | 165,E1 127 | 166,E2 128 | 168,E2 129 | 169,E4 130 | 170,E5 131 | 172,E6 132 | 174,E5 133 | 175,E4 134 | 176,E1 135 | 177,E6 136 | 178,D4 137 | 179,Single protein cluster clade Y 138 | 180,E3 139 | 182,E6 140 | 183,E3 141 | 184,D5 142 | 185,Single protein cluster clade X 143 | 186,D4 144 | 191,E6 145 | 192,D4 146 | 193,A-C4 147 | 194,D4 148 | 197,A-C2 149 | 205,E5 150 | 207,D1 151 | 208,D4 152 | 209,E3 153 | 211,Single protein cluster clade X 154 | 213,D2 155 | 215,Single protein cluster clade Y 156 | 217,D3 157 | 218,Single protein cluster clade Y 158 | 219,E3 159 | 221,Single protein cluster clade Y 160 | 222,Single protein cluster clade Y 161 | 223,D4 162 | 224,D4 163 | 225,D4 164 | 227,A-C3 165 | 228,A-C4 166 | 229,A-C4 167 | 230,D4 168 | 231,E3 169 | 232,E4 170 | 233,Single protein cluster clade Y 171 | 234,Single protein cluster clade Y 172 | 236,Single protein cluster clade X 173 | 238,A-C3 174 | 239,A-C3 175 | 242,D4 176 | -------------------------------------------------------------------------------- /emmtyper/data/emm_clusters.csv: -------------------------------------------------------------------------------- 1 | 1,A-C3 2 | 2,E4 3 | 3,A-C5 4 | 4,E1 5 | 5,Single protein cluster clade Y 6 | 6,Single protein cluster clade Y 7 | 8,E4 8 | 9,E3 9 | 11,E6 10 | 12,A-C4 11 | 13,E2 12 | 14,Single protein cluster clade Y 13 | 15,E3 14 | 17,Single protein cluster clade Y 15 | 18,Single protein cluster clade Y 16 | 19,Single protein cluster clade Y 17 | 22,E4 18 | 23,Single protein cluster clade Y 19 | 24,Single protein cluster clade Y 20 | 25,E3 21 | 26,Single protein cluster clade Y 22 | 27,E2 23 | 28,E4 24 | 29,Single protein cluster clade Y 25 | 30,A-C2 26 | 31,A-C5 27 | 32,D2 28 | 33,D4 29 | 34,E5 30 | 36,D1 31 | 37,Single protein cluster clade Y 32 | 38,Single protein cluster clade Y 33 | 39,A-C4 34 | 41,D4 35 | 42,E6 36 | 43,D4 37 | 44,E3 38 | 46,A-C1 39 | 47,Single protein cluster clade Y 40 | 48,E6 41 | 49,E3 42 | 50,E2 43 | 51,E5 44 | 52,D4 45 | 53,D4 46 | 54,D1 47 | 55,Single protein cluster clade Y 48 | 56,D4 49 | 56.2,D4 50 | 57,Single protein cluster clade Y 51 | 58,E3 52 | 59,E6 53 | 60,E1 54 | 63,E6 55 | 64,D4 56 | 65,E6 57 | 66,E2 58 | 67,E6 59 | 68,E2 60 | 70,D4 61 | 71,D2 62 | 72,D4 63 | 73,E4 64 | 74,Single protein cluster clade Y 65 | 75,E6 66 | 76,E2 67 | 77,E4 68 | 78,E1 69 | 79,E3 70 | 80,D4 71 | 81,E6 72 | 82,E3 73 | 83,D4 74 | 84,E4 75 | 85,E6 76 | 86,D4 77 | 87,E3 78 | 88,E4 79 | 89,E4 80 | 90,E2 81 | 91,D4 82 | 92,E2 83 | 93,D4 84 | 94,E6 85 | 95,Single protein cluster clade Y 86 | 96,E2 87 | 97,D5 88 | 98,D4 89 | 99,E6 90 | 100,D2 91 | 101,D4 92 | 102,E4 93 | 103,E3 94 | 104,E2 95 | 105,Single protein cluster clade Y 96 | 106,E2 97 | 107,E3 98 | 108,D4 99 | 109,E4 100 | 110,E2 101 | 111,Single protein cluster clade Y 102 | 112,E4 103 | 113,E3 104 | 114,E4 105 | 115,D2 106 | 116,D4 107 | 117,E2 108 | 118,E3 109 | 119,D4 110 | 120,D4 111 | 121,D4 112 | 122,Single protein cluster clade Y 113 | 123,D3 114 | 124,E4 115 | 133,A-C5 116 | 134,E5 117 | 137,E5 118 | 139,E6 119 | 140,Single protein cluster clade Y 120 | 142,A-C1 121 | 144,E3 122 | 157,D5 123 | 158,E6 124 | 163,A-C3 125 | 164,Single protein cluster clade X 126 | 165,E1 127 | 166,E2 128 | 168,E2 129 | 169,E4 130 | 170,E5 131 | 172,E6 132 | 174,E5 133 | 175,E4 134 | 176,E1 135 | 177,E6 136 | 178,D4 137 | 179,Single protein cluster clade Y 138 | 180,E3 139 | 182,E6 140 | 183,E3 141 | 184,D5 142 | 185,Single protein cluster clade X 143 | 186,D4 144 | 191,E6 145 | 192,D4 146 | 193,A-C4 147 | 194,D4 148 | 197,A-C2 149 | 205,E5 150 | 207,D1 151 | 208,D4 152 | 209,E3 153 | 211,Single protein cluster clade X 154 | 213,D2 155 | 215,Single protein cluster clade Y 156 | 217,D3 157 | 218,Single protein cluster clade Y 158 | 219,E3 159 | 221,Single protein cluster clade Y 160 | 222,Single protein cluster clade Y 161 | 223,D4 162 | 224,D4 163 | 225,D4 164 | 227,A-C3 165 | 228,A-C4 166 | 229,A-C4 167 | 230,D4 168 | 231,E3 169 | 232,E4 170 | 233,Single protein cluster clade Y 171 | 234,Single protein cluster clade Y 172 | 236,Single protein cluster clade X 173 | 238,A-C3 174 | 239,A-C3 175 | 242,D4 176 | -------------------------------------------------------------------------------- /emmtyper/objects/ispcr.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define the isPCR class 3 | ''' 4 | from os import environ 5 | import logging 6 | import shlex 7 | 8 | from emmtyper.objects.command import Command 9 | 10 | logging.basicConfig(level=environ.get("LOGLEVEL", "INFO")) 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class IsPCR(Command): 15 | ''' 16 | Run isPCR. Inherits from Command 17 | ''' 18 | def __init__( 19 | self, 20 | assembly_filename, 21 | primer_filename, 22 | min_perfect, 23 | min_good, 24 | tile_size, 25 | step_size, 26 | max_product_length, 27 | output_stream, 28 | tool_path=None, 29 | ): 30 | 31 | Command.__init__(self, "isPcr", tool_path=tool_path) 32 | 33 | self.assembly_filename = shlex.quote( 34 | Command.assert_filepath_and_return(assembly_filename) 35 | ) 36 | self.primer_filename = shlex.quote( 37 | Command.assert_filepath_and_return(primer_filename) 38 | ) 39 | 40 | self.min_perfect = min_perfect 41 | self.min_good = min_good 42 | 43 | self.tile_size = tile_size 44 | self.step_size = step_size 45 | 46 | self.max_product_length = max_product_length 47 | self.output_stream = output_stream 48 | 49 | self.command_string = self.build_isPCR_command() 50 | 51 | def __repr__(self): 52 | return self.command_string 53 | 54 | def build_isPCR_command(self): 55 | 56 | string = ( 57 | "{tool_path} {db} {query} {output} " 58 | "-minPerfect={min_perfect} -minGood={min_good}" 59 | #" -tileSize={tile_size} -stepSize={step_size}" 60 | " -tileSize={tile_size}" 61 | " -stepSize={step_size}" 62 | " -maxSize={max_size}" 63 | ) 64 | 65 | command = string.format( 66 | min_perfect=self.min_perfect, 67 | min_good=self.min_good, 68 | tile_size=self.tile_size, 69 | step_size = self.step_size, 70 | max_size=self.max_product_length, 71 | db=self.assembly_filename, 72 | query=self.primer_filename, 73 | output=self.output_stream, 74 | tool_path=self.tool_path, 75 | ) 76 | logger.info(command) 77 | 78 | return command 79 | 80 | def run_isPCR(self): 81 | # logger.info("Running on {}".format(self.assembly_filename)) 82 | 83 | output = Command.run(self) 84 | 85 | if not output: 86 | logger.info("There is no output for {}".format(self.assembly_filename)) 87 | 88 | #remove the primer in contigs headers 89 | new_out = [] 90 | for line in output.split("\n"): 91 | if len(line) > 0: 92 | if line[0] == ">": 93 | new_line = " ".join(line.split()[:-2]) 94 | new_out.append(new_line) 95 | else: 96 | new_out.append(line) 97 | else: 98 | new_out.append(line) 99 | return "\n".join(new_out) 100 | #return output[:-1] 101 | -------------------------------------------------------------------------------- /tests/test_isPcr.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from emmtyper.objects.ispcr import IsPCR 4 | 5 | from tests.data import primer_path_cdc, \ 6 | primer_path_frost, \ 7 | test_sequence_path, \ 8 | test_empty_path, \ 9 | test_null, \ 10 | isPcr_command_cdc, \ 11 | isPcr_command_e_cdc, \ 12 | isPcr_command_frost, \ 13 | isPcr_command_e_frost, \ 14 | isPcr_result_cdc, \ 15 | isPcr_result_frost, \ 16 | isPcr_result_e \ 17 | 18 | ispcr_cdc = IsPCR( 19 | test_sequence_path, 20 | primer_path_cdc, 21 | min_perfect=15, 22 | min_good=15, 23 | #tile_size=6, 24 | #step_size=5, 25 | max_product_length=4000, 26 | tile_size=6, 27 | step_size=5, 28 | output_stream="stdout", 29 | ) 30 | 31 | ispcr_frost = IsPCR( 32 | test_sequence_path, 33 | primer_path_frost, 34 | min_perfect=15, 35 | min_good=15, 36 | #tile_size=6, 37 | #step_size=5, 38 | max_product_length=4000, 39 | tile_size=6, 40 | step_size=5, 41 | output_stream="stdout", 42 | ) 43 | 44 | 45 | ispcr_e_cdc = IsPCR( 46 | test_empty_path, 47 | primer_path_cdc, 48 | min_perfect=20, 49 | min_good=30, 50 | #tile_size=6, 51 | #step_size=5, 52 | max_product_length=4000, 53 | tile_size=6, 54 | step_size=5, 55 | output_stream="stdout", 56 | ) 57 | 58 | 59 | ispcr_e_frost = IsPCR( 60 | test_empty_path, 61 | primer_path_frost, 62 | min_perfect=20, 63 | min_good=30, 64 | #tile_size=6, 65 | #step_size=5, 66 | max_product_length=4000, 67 | tile_size=6, 68 | step_size=5, 69 | output_stream="stdout", 70 | ) 71 | 72 | 73 | class testIsPCRapp(unittest.TestCase): 74 | def test_null(self): 75 | self.assertEqual(test_null, "this is a null test") 76 | 77 | def test_is_IsPCR(self): 78 | self.assertIs(type(ispcr_cdc), IsPCR) 79 | self.assertIs(type(ispcr_e_cdc), IsPCR) 80 | self.assertIs(type(ispcr_frost), IsPCR) 81 | self.assertIs(type(ispcr_e_frost), IsPCR) 82 | 83 | '''def test_isPcr_command(self): 84 | self.assertTrue(isPcr_command_cdc in ispcr_cdc.build_isPCR_command()) 85 | self.assertTrue(isPcr_command_frost in ispcr_frost.build_isPCR_command()) 86 | 87 | def test_isPcr_result(self): 88 | self.assertEqual(ispcr_cdc.run_isPCR(), isPcr_result_cdc) 89 | self.assertEqual(ispcr_frost.run_isPCR(), isPcr_result_frost) 90 | 91 | def test_empty_command(self): 92 | self.assertTrue(isPcr_command_e_cdc in ispcr_e_cdc.build_isPCR_command()) 93 | self.assertTrue(isPcr_command_e_frost in ispcr_e_frost.build_isPCR_command())''' 94 | 95 | def test_empty_result(self): 96 | self.assertEqual(ispcr_e_cdc.run_isPCR(), isPcr_result_e) 97 | self.assertEqual(ispcr_e_frost.run_isPCR(), isPcr_result_e) 98 | 99 | # How to test the connection between isPcr and BLAST? 100 | 101 | 102 | if __name__ == "__main__": 103 | unittest.main() 104 | -------------------------------------------------------------------------------- /emmtyper/objects/result_row.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define the ResultRow class to store resultss 3 | ''' 4 | import numpy as np 5 | 6 | # define some known emm-like genes 7 | PHE_emmLike = [ 8 | "EMM51", 9 | "EMM134", 10 | "EMM138", 11 | "EMM149", 12 | "EMM156", 13 | "EMM159", 14 | "EMM164", 15 | "EMM167", 16 | "EMM170", 17 | "EMM174", 18 | "EMM202", 19 | "EMM205", 20 | "EMM236", 21 | "EMM240", 22 | ] 23 | 24 | Suspects = [] # "EMM134", "EMM167", 25 | # "EMM137", "EMM141", "EMM166", "EMM203"] 26 | 27 | EmmImposters = PHE_emmLike + Suspects 28 | 29 | 30 | class WrongLengthException(Exception): 31 | ''' 32 | Exception to handle wrong length matches 33 | ''' 34 | pass 35 | 36 | 37 | class ResultRow: 38 | ''' 39 | Store and print Blast results 40 | ''' 41 | variableList = [ 42 | "Query", 43 | "BlastHit", 44 | "Identity", 45 | "AlignmentLength", 46 | "Mismatch", 47 | "GapOpen", 48 | "QueryStart", 49 | "QueryEnd", 50 | "HitStart", 51 | "HitEnd", 52 | "E-Value", 53 | "BitScore", 54 | "SubjectLength", 55 | ] 56 | 57 | flagDict = { 58 | (False, True): "~", 59 | (True, False): "*", 60 | (True, True): "", 61 | (False, False): "~*", 62 | } 63 | 64 | def __init__(self, string): 65 | self.fullRow = string 66 | 67 | rowSplit = string.split("\t") 68 | 69 | if len(self.variableList) != len(rowSplit): 70 | raise WrongLengthException("Wrong row length!") 71 | 72 | rowSplit[3:10] = map(int, rowSplit[3:10]) 73 | rowSplit[12:14] = map(int, rowSplit[12:14]) 74 | 75 | ( 76 | query, 77 | blastHit, 78 | identity, 79 | alignmentLength, 80 | mismatch, 81 | gapOpen, 82 | queryStart, 83 | queryEnd, 84 | hitStart, 85 | hitEnd, 86 | eValue, 87 | bitScore, 88 | subjectLength, 89 | ) = rowSplit 90 | 91 | self.query = query 92 | 93 | self.blastHit = blastHit 94 | self.type = blastHit.split(".")[0] 95 | self.subtype = blastHit.split(".")[1] 96 | 97 | self.identity = float(identity) 98 | self.alignmentLength = alignmentLength 99 | self.mismatch = mismatch 100 | self.gapOpen = gapOpen 101 | self.queryStart = queryStart 102 | self.queryEnd = queryEnd 103 | self.hitStart = hitStart 104 | self.hitEnd = hitEnd 105 | self.eValue = eValue 106 | self.bitScore = bitScore 107 | self.subjectLength = subjectLength 108 | 109 | # Score is percent identity, penalized by gap opening and difference in alignment length and actual subject length 110 | self.positions = np.array([self.query, self.queryStart, self.queryEnd]) 111 | self.score = self.identity - ( 112 | self.gapOpen + abs(self.alignmentLength - self.subjectLength) 113 | ) 114 | 115 | def __repr__(self): 116 | return self.fullRow 117 | 118 | def __str__(self): 119 | if self.blastHit == "EMM0.0": 120 | return "-" 121 | else: 122 | return "{}{}".format( 123 | self.blastHit, 124 | ResultRow.flagDict[(self.score == 100, self.type not in EmmImposters)], 125 | ) 126 | 127 | @staticmethod 128 | def build_header(): 129 | header = "\t".join([variable for variable in ResultRow.variableList]) 130 | 131 | return header + "\n" 132 | 133 | def filter(self, mismatch, align_diff, gap): 134 | return ( 135 | self.mismatch_k(mismatch) 136 | and self.alignment_to_subject_length_k(align_diff) 137 | and self.gap_k(gap) 138 | ) 139 | 140 | ### Filter functions. 141 | 142 | def alignment_to_subject_length_k(self, k=0): 143 | # Check whether alignment length is within minimum k threshold to subject length. 144 | 145 | return abs(self.subjectLength - self.alignmentLength) <= k 146 | 147 | def mismatch_k(self, k=0): 148 | # Accounts possibility of k mismatch(es) as okay for classification. 149 | 150 | return self.mismatch <= k 151 | 152 | def gap_k(self, k=0): 153 | # Check whether there are k (or less) gaps in Row instance. 154 | 155 | return self.gapOpen <= k 156 | 157 | ### Prototype filter functions. Currently not used. 158 | 159 | def hit_start_end_k(self, k=0): 160 | # Reduces need for alignment length to be same as subject length by k value. 161 | # Requires other functions to work well, such as mismatch functions. 162 | 163 | start = 1 + k 164 | end = self.subjectLength - k 165 | 166 | start_bool = self.hitStart <= start or self.hitStart >= end 167 | end_bool = self.hitEnd <= start or self.hitEnd >= end 168 | 169 | return start_bool and end_bool 170 | 171 | def bit_score_346(self, bit=346): 172 | # Check whether bit score is full. 173 | 174 | return self.bitScore == bit 175 | -------------------------------------------------------------------------------- /paper.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'emmtyper: A tool for in silico EMM typing of Streptococcus pyogenes' 3 | tags: 4 | - Python 5 | - Bioinformatics 6 | - Microbial Genomics 7 | - Public Health Microbiology 8 | - Molecular Epidemiology 9 | authors: 10 | - name: Andre Tan 11 | affiliation: "1, 2" 12 | - name: Torsten Seemann 13 | orcid: 0000-0001-6046-610X 14 | affiliation: "2, 3" 15 | - name: Jake A. Lacey 16 | orcid: 0000-0002-6492-6983 17 | affiliation: 3 18 | - name: Liam Mcintyre 19 | affiliation: 3 20 | - name: Mark R. Davies 21 | affiliation: 3 22 | - name: Hannah Frost 23 | orcid: 0000-0002-1543-2805 24 | affiliation: 4 25 | - name: Pierre R. Smeesters 26 | affiliation: 4 27 | - name: Deborah A. Williamson 28 | affiliation: "2, 3" 29 | - name: Anders Gonçalves da Silva 30 | orcid: 0000-0002-2257-8781 31 | affiliation: 2 32 | affiliations: 33 | - name: FinAccel Pte Ltd 34 | index: 1 35 | - name: Microbiological Diagnostic Unit Public Health Laboratory, Department of Microbiology and Immunology, Peter Doherty Institute for Immunity and Infection, The University of Melbourne 36 | index: 2 37 | - name: Department of Microbiology and Immunology, Peter Doherty Institute for Immunity and Infection, The University of Melbourne 38 | index: 3 39 | - name: Molecular Bacteriology Laboratory, Université Libre de Bruxelles 40 | index: 4 41 | date: 30 October 2019 42 | bibliography: paper.bib 43 | --- 44 | 45 | # Summary 46 | 47 | Bacterial pathogen subtyping is a corner-stone of public health microbiology and epidemiology. By classifying bacterial strains at levels below species and sub-species, bacterial subtyping allows public health officials and epidemiologists to identify and track outbreaks, identify particularly virulent strains, and make decisions about vaccination programmes. As public health microbiology transitions to a workflow primarily based on genomic data, there is an increasing need for Bioinformatic tools to perform *in silico* bacterial subtyping. Such tools are essential to enable the carryover of vast troves of historical data and allow for a smooth transition to genomics-based public health. 48 | 49 | `emmtyper` is an *in silico* bacterial subtyping tool written in Python for *emm*-typing and *emm*-cluster typing of *Streptococcus pyogenes*, also known as Group A Streptococcus (GAS). *S. pyogenes* is the causative agent of strep throat, necrotizing fasciitis, and Scarlet fever. *emm*-typing targets variation at the *emm* gene that produces the surface antigen known as M protein. The M protein was initially used as a target for GAS subtyping because it is essential for evading the human immune system, and thus essential to the bacteria's virulence. *emm*-cluster typing groups *emm*-types into functionally equivalent clusters, facilitating vaccine development. 50 | 51 | Essential to the working of `emmtyper` is a FASTA database of sequences annotated with the M-type. The database consists of a set of sequences typically of 180bp in length that covers a portion of the *emm* gene, and is curated by the CDC *Streptococcus* laboratory ([CDC](https://www2.cdc.gov/vaccines/biotech/strepblast.asp)). The database is updated on a regular basis, adding newly characterized sequences. To ensure the local database used by `emmtyper` is up to date, we provide facilities for the user to check if their database is out-of-date, and if so, to download and update the local database. We check the database integrity by checking for and removing any duplicate sequences using the tool `seqkit` [CITATION]. `emmtyper` keeps a JSON formatted log of database updates, providing the user with a history of changes over time and is what permits the tool to check if the local database is out-of-date. 52 | 53 | To give users flexibility about how they wish to use `emmtyper`, we provide two distinct modes of operation: `blast` and *in silico* PCR. The `blast` mode is the default mode of operation, and it blasts the contigs of the assembly supplied by the user against the database of *emm*-type annotated sequences. The `in silico` mode uses the *in silico* PCR tool `isPcr` [CITATION] to identify one or more PCR fragments in the contigs of the assembly suppplied by the user, and then subsequently, the fragments are blasted against the database of *emm*-type annotated sequences. At the moment, two sets of PCR primers are shipped with `emmtyper`, the canonical PCR primers recommended by the CDC M-typing protocol [CITATION], and a set of redesigned primers published more recently by Frost *et al.* [CITATION]. The CDC canonical primers are used by default, but the user is able to select the Frost *et al.* `in silico` PCR primers by setting the `--pcr-primer` option to `frost`. The user is also able to supply their own primers by setting the `--primer-db` to the path to the appropriately formatted file. 54 | 55 | `emmtyper` is now routinely used for *emm*-typing and *emm*-cluster typing of *Streptococcus pyogenes* at the Microbiological Diagnostic Unit Public Health Lab, has been used in a number of papers, and has been added to bacterial pathogen Bioinformatic pipelines (e.g., Bactopia). Importantly, the tool has been fully validated and is ready for use in the field. `emmtyper` is available on PyPI, and on Bioconda, to make it easy for the user to install the tool. 56 | 57 | Transition to genomics in public health. 58 | 59 | Bacterial subtyping in public health. 60 | 61 | EMM typing in GAS. 62 | 63 | GAS epidemiology. 64 | 65 | Prior use of emmtyper (Lacey). 66 | 67 | Statement of need: what it provides: support for transition to genomics. Validated tool. 68 | -------------------------------------------------------------------------------- /tests/data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test data 3 | """ 4 | import os 5 | import shlex 6 | from emmtyper.utilities.find import find 7 | 8 | PROJECT_FOLDER=os.path.dirname(os.path.dirname(__file__)) 9 | 10 | test_null = "this is a null test" 11 | 12 | primer_path_cdc = find("isPcrPrim.tsv", PROJECT_FOLDER) 13 | primer_path_frost = find("isPcrPrim-Frost.tsv", PROJECT_FOLDER) 14 | db = find("emm.fna", PROJECT_FOLDER) 15 | 16 | test_sequence_path = find("contig.fasta", __file__) 17 | test_empty_path = find("empty.fasta", __file__) 18 | test_pcr_product_path = find("amplicon.fasta", __file__) 19 | 20 | test_blast_product = find("blast.fa.tsv", __file__) 21 | 22 | # For ResultRow 23 | string = "SP3LAU\t_emm_89.0\t100\t180\t0\t0\t737626\t737805\t1\t180\t1.93e-89\t333\t180" 24 | string_str = "_emm_89.0" 25 | string_not100 = ( 26 | "SP3LAU\t_emm_89.0\t99\t180\t1\t1\t737626\t737805\t1\t180\t1.93e-89\t333\t180" 27 | ) 28 | string_not100_str = "_emm_89.0~" 29 | string_imp = ( 30 | "SP3LAU\t_emm_202.0\t100\t180\t0\t0\t737626\t737805\t1\t180\t1.93e-89\t333\t180" 31 | ) 32 | string_imp_str = "_emm_202.0" 33 | string_long = ( 34 | "SP3LAU\t65\t_emm_89.0\t100\t180\t0\t0\t737626\t737805\t1\t180\t1.93e-89\t333\t180" 35 | ) 36 | 37 | # For BLAST and isPcr 38 | blast_command = 'blastn -db {} -query {} -dust no -perc_identity 95 -culling_limit 1 -outfmt "6 std slen"'.format( 39 | '"\\"' + db + '"\\"', shlex.quote(test_sequence_path) 40 | ) 41 | blast_command_h = 'blastn -db {} -query {} -dust no -perc_identity 100 -culling_limit 1 -outfmt "6 std slen"'.format( 42 | '"\\"' + db + '"\\"', shlex.quote(test_sequence_path) 43 | ) 44 | isPcr_command_cdc = "isPcr {} {} stdout -minPerfect=15 -minGood=15 -maxSize=4000".format( 45 | shlex.quote(test_sequence_path), shlex.quote(primer_path_cdc) 46 | ) 47 | isPcr_command_e_cdc = "isPcr {} {} stdout -minPerfect=20 -minGood=30 -maxSize=4000".format( 48 | shlex.quote(test_empty_path), shlex.quote(primer_path_cdc) 49 | ) 50 | 51 | isPcr_command_frost = "isPcr {} {} stdout -minPerfect=15 -minGood=15 -maxSize=4000".format( 52 | shlex.quote(test_sequence_path), shlex.quote(primer_path_frost) 53 | ) 54 | isPcr_command_e_frost = "isPcr {} {} stdout -minPerfect=20 -minGood=30 -maxSize=4000".format( 55 | shlex.quote(test_empty_path), shlex.quote(primer_path_frost) 56 | ) 57 | 58 | 59 | header = "Query\tBlastHit\tIdentity\tAlignmentLength\tMismatch\tGapOpen\tQueryStart\tQueryEnd\tHitStart\tHitEnd\tE-Value\tBitScore\tSubjectLength\n" 60 | 61 | blast_result = ( 62 | "contig1\tEMM1.0\t100.000\t180\t0\t0\t113816\t113995\t1\t180\t1.50e-90\t333\t180" 63 | ) 64 | isPcr_result_cdc = ">contig1:113750+114924 emm 1175bp TATTCGCTTAGAAAATTAA GCAAGTTCTTCAGCTTGTTT\nTATTCGCTTAGAAAATTAAaaacaggaacggcttcagtagcggtagcttt\ngactgttttaggggcaggttttgcgaatcaaacagaggttaaggctaacg\ngtgatggtaatcctagggaagttatagaagatcttgcagcaaacaatccc\ngcaatacaaaatatacgtttacgtcacgaaaacaaggacttaaaagcgag\nattagagaatgcaatggaagttgcaggaagagattttaagagagctgaag\naacttgaaaaagcaaaacaagccttagaagaccagcgtaaagatttagaa\nactaaattaaaagaactacaacaagactatgacttagcaaaggaatcaac\naagttgggatagacaaagacttgaaaaagagttagaagagaaaaaggaag\nctcttgaattagcgatagaccaggcaagtcgggactaccatagagctacc\ngctttagaaaaagagttagaagagaaaaagaaagctcttgaattagcgat\nagaccaagcgagtcaggactataatagagctaacgtcttagaaaaagagt\ntagaaacgattactagagaacaagagattaatcgtaatcttttaggcaat\ngcaaaacttgaacttgatcaactttcatctgaaaaagagcagctaacgat\ncgaaaaagcaaaacttgaggaagaaaaacaaatctcagacgcaagtcgtc\naaagccttcgtcgtgacttggacgcatcacgtgaagctaagaaacaggtt\ngaaaaagatttagcaaacttgactgctgaacttgataaggttaaagaaga\ncaaacaaatctcagacgcaagccgtcaaggccttcgccgtgacttggacg\ncatcacgtgaagctaagaaacaggttgaaaaagatttagcaaacttgact\ngctgaacttgataaggttaaagaagaaaaacaaatctcagacgcaagccg\ntcaaggccttcgccgtgacttggacgcatcacgtgaagctaagaaacaag\nttgaaaaagctttagaagaagcaaacagcaaattagctgctcttgaaaaa\ncttaacaaagagcttgaagaaagcaagaaattaacagaaaaagaaaaagc\ntgaactacaagcaaaacttgaagcagaagcaaaagcactcaaagaacaat\ntagcgAAACAAGCTGAAGAACTcGC" 65 | isPcr_result_frost = ">contig1:113750+114820 emm 1071bp TATTCGCTTAGAAAATTAA TTCTTCAAGCTCTTTGTT\nTATTCGCTTAGAAAATTAAaaacaggaacggcttcagtagcggtagcttt\ngactgttttaggggcaggttttgcgaatcaaacagaggttaaggctaacg\ngtgatggtaatcctagggaagttatagaagatcttgcagcaaacaatccc\ngcaatacaaaatatacgtttacgtcacgaaaacaaggacttaaaagcgag\nattagagaatgcaatggaagttgcaggaagagattttaagagagctgaag\naacttgaaaaagcaaaacaagccttagaagaccagcgtaaagatttagaa\nactaaattaaaagaactacaacaagactatgacttagcaaaggaatcaac\naagttgggatagacaaagacttgaaaaagagttagaagagaaaaaggaag\nctcttgaattagcgatagaccaggcaagtcgggactaccatagagctacc\ngctttagaaaaagagttagaagagaaaaagaaagctcttgaattagcgat\nagaccaagcgagtcaggactataatagagctaacgtcttagaaaaagagt\ntagaaacgattactagagaacaagagattaatcgtaatcttttaggcaat\ngcaaaacttgaacttgatcaactttcatctgaaaaagagcagctaacgat\ncgaaaaagcaaaacttgaggaagaaaaacaaatctcagacgcaagtcgtc\naaagccttcgtcgtgacttggacgcatcacgtgaagctaagaaacaggtt\ngaaaaagatttagcaaacttgactgctgaacttgataaggttaaagaaga\ncaaacaaatctcagacgcaagccgtcaaggccttcgccgtgacttggacg\ncatcacgtgaagctaagaaacaggttgaaaaagatttagcaaacttgact\ngctgaacttgataaggttaaagaagaaaaacaaatctcagacgcaagccg\ntcaaggccttcgccgtgacttggacgcatcacgtgaagctaagaaacaag\nttgaaaaagctttagaagaagcaaacagcaaattagctgctcttgaaaaa\ncttAACAAAGAGCTTGAAGAA" 66 | isPcr_result_e = "" 67 | 68 | 69 | # For Clusterer 70 | header_short = "Isolate\tNumberOfClusters\tAnswers\tSuspectImposters\tAnswersClusters\n" 71 | header_verbose = "Isolate\tNumberOfHits\tNumberOfClusters\tAnswers\tAnswerPositions\tSuspectImposters\tSuspectPositions\tAnswersClusters\n" 72 | 73 | clusterer_repr_short = "Clusterer for {} with clustering distance 800bp\nshort output to stdout".format( 74 | test_blast_product 75 | ) 76 | clusterer_result_short = "{}\t2\t_emm_65.0\t_emm_156.0~*\tE6".format(test_blast_product) 77 | clusterer_repr_verbose = "Clusterer for {} with clustering distance 800bp\nverbose output to stdout".format( 78 | test_blast_product 79 | ) 80 | clusterer_result_verbose = "{}{}\t6\t2\t_emm_65.0\t.blast.5:82168\t_emm_156.0~*\t.blast.5:80776\tE6".format( 81 | header_verbose, test_blast_product 82 | ) 83 | -------------------------------------------------------------------------------- /emmtyper/objects/blast.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Define a wrapper class for BLAST 3 | ''' 4 | from os import path, environ 5 | import logging 6 | import subprocess 7 | import shlex 8 | 9 | from emmtyper.objects.command import Command, FileNotInPathException 10 | from emmtyper.objects.result_row import ResultRow 11 | 12 | logging.basicConfig(level=environ.get("LOGLEVEL", "INFO")) 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | class BLAST(Command): 17 | """ 18 | Wrapper class for command-line blastn. 19 | 20 | Command-line blastn only allows filtering using e-value, percent identity, and culling limit. 21 | Additional filter option is given in this wrapper, namely: 22 | 1. Mismatch 23 | Regular blastn can do this with perc_identity, but needs to be in percentage of alignment length. 24 | Specify an integer N, number of mismatches allowed as result. Default = 4. 25 | 2. GapOpen 26 | Regular blastn cannot do this directly, but you can calculate the resulting e-value from gap open penalty. 27 | Specify an integer N, number of gap open allowed. Default = 2. 28 | 3. AlignDiff 29 | This cannot be done only with regular blastn. 30 | Specify an integer N, which is the maximum allowed difference between subject and alignment length. Default = 5. 31 | 32 | Requires user to install blastn on own, and needs ResultRow class. 33 | 34 | This class is developed to be used within emmtyper, thus the output format. 35 | You need to change the output format AFTER filtering if you want anything other than "6 std slen". 36 | """ 37 | 38 | def __init__( 39 | self, 40 | db, 41 | query, 42 | dust, 43 | perc_identity, 44 | culling_limit, 45 | output_stream, 46 | header, 47 | mismatch, 48 | align_diff, 49 | gap, 50 | tool_path=None, 51 | ): 52 | 53 | Command.__init__(self, "blastn", tool_path=tool_path) 54 | 55 | self.version = self.get_version() 56 | 57 | self.db = '"\\"' + self.assert_db_and_return(db) + '"\\"' 58 | self.query = shlex.quote(Command.assert_filepath_and_return(query)) 59 | 60 | self.dust = dust 61 | self.perc_identity = perc_identity 62 | self.culling_limit = culling_limit 63 | 64 | self.outformat = "6 std slen" 65 | self.output_stream = output_stream 66 | 67 | self.want_header = header 68 | 69 | # Threshold for ResultRow filtering 70 | 71 | self.mismatch = mismatch 72 | self.align_diff = align_diff 73 | self.gap = gap 74 | 75 | self.command_string = self.build_blastn_command() 76 | 77 | def __repr__(self): 78 | return self.command_string 79 | 80 | def __str__(self): 81 | string = ( 82 | "{0}\n" 83 | "Query = {1}\n" 84 | "DB = {2}\n" 85 | "Dust filter = {3}\n" 86 | "% Identity = {4}\n" 87 | "Culling limit = {5}\n" 88 | "Outformat = {6}\n" 89 | "Output to = {7}\n" 90 | "Mismatch filter = {8}\n" 91 | "Align difference filter = {9}\n" 92 | "Gap filter = {10}" 93 | ) 94 | 95 | string = string.format( 96 | self.version, 97 | self.query, 98 | self.db, 99 | self.dust, 100 | self.perc_identity, 101 | self.culling_limit, 102 | self.outformat, 103 | self.output_stream, 104 | self.mismatch, 105 | self.align_diff, 106 | self.gap, 107 | ) 108 | 109 | return string 110 | 111 | def get_version(self): 112 | process = subprocess.Popen( 113 | args="{} -version".format(self.tool_name), 114 | shell=True, 115 | stdout=subprocess.PIPE, 116 | stderr=subprocess.PIPE, 117 | ) 118 | 119 | stdout, stderr = process.communicate() 120 | 121 | return stdout.decode("ascii") 122 | 123 | def assert_db_and_return(self, file_path): 124 | if not ( 125 | path.isfile(file_path + ".nin") 126 | and path.isfile(file_path + ".nhr") 127 | and path.isfile(file_path + ".nsq") 128 | ): 129 | raise FileNotInPathException( 130 | "{} is not a BLAST database!".format(file_path) 131 | ) 132 | exit(1) 133 | 134 | return file_path 135 | 136 | def build_blastn_command(self): 137 | string = ( 138 | "{tool_path} -db {db} -query {query} -dust {dust} -perc_identity {perc_id}" 139 | " -culling_limit {cull_limit} -outfmt \"{outfmt}\"" 140 | ) 141 | 142 | command = string.format( 143 | tool_path=self.tool_path, 144 | db=self.db, 145 | query=self.query, 146 | dust=self.dust, 147 | perc_id=self.perc_identity, 148 | cull_limit=self.culling_limit, 149 | outfmt=self.outformat, 150 | ) 151 | 152 | logger.info(f"Running command {command}") 153 | 154 | return command 155 | 156 | def filter_blastn_results(self, outputs): 157 | 158 | ok_results = [ 159 | ResultRow(output) 160 | for output in outputs 161 | if ResultRow(output).filter(self.mismatch, self.align_diff, self.gap) 162 | ] 163 | 164 | return ok_results 165 | 166 | def result_to_output(self, filtered_outputs): 167 | string = "" 168 | 169 | for output in filtered_outputs: 170 | string = "\n".join([repr(output) for output in filtered_outputs]) 171 | 172 | # Log if BLAST produces no result 173 | if not string: 174 | logger.info("There is no output for {}".format(self.query)) 175 | 176 | # Produces header if wanted, attach to string 177 | if self.want_header and string: 178 | string = ResultRow.build_header() + string 179 | 180 | # Where to output product 181 | if self.output_stream in [None, "None", "stdout"]: 182 | print(string) 183 | else: 184 | with open(self.output_stream, "w") as handle: 185 | handle.write(string) 186 | 187 | return string 188 | 189 | def run_blastn_pipeline(self): 190 | # logger.info("Running on {}".format(self.query)) 191 | 192 | outputs = Command.run(self).split("\n")[:-1] 193 | 194 | filtered_outputs = self.filter_blastn_results(outputs) 195 | 196 | return self.result_to_output(filtered_outputs) 197 | -------------------------------------------------------------------------------- /emmtyper/bin/run_emmtyper.py: -------------------------------------------------------------------------------- 1 | """ 2 | For running emmtyper 3 | """ 4 | 5 | import logging 6 | import pathlib 7 | import os 8 | import sys 9 | 10 | import click 11 | 12 | from emmtyper.__init__ import __version__ as version 13 | from emmtyper.utilities import run_ispcr, run_blast 14 | from emmtyper.objects.clusterer import Clusterer 15 | 16 | DEFAULT_DB = pathlib.Path(__file__).parent.parent / "db" / "emm.fna" 17 | CDC_PRIMERS = pathlib.Path(__file__).parent.parent / "data" / "isPcrPrim.tsv" 18 | FROST_PRIMERS = pathlib.Path(__file__).parent.parent / "data" / "isPcrPrim-Frost.tsv" 19 | 20 | logger = logging.getLogger(__name__) 21 | 22 | 23 | @click.command() 24 | @click.version_option( 25 | version=version, prog_name="emmtyper", message=("%(prog)s v%(version)s") 26 | ) 27 | @click.argument("fasta", nargs=-1) 28 | @click.option( 29 | "-w", 30 | "--workflow", 31 | default="blast", 32 | help="Choose workflow", 33 | type=click.Choice(["blast", "pcr"]), 34 | show_default=True, 35 | ) 36 | @click.option( 37 | "-db", 38 | "--blast_db", 39 | default=os.environ.get("EMM_DB", DEFAULT_DB), 40 | help="Path to EMM BLAST DB", 41 | show_default=True, 42 | ) 43 | @click.option( 44 | "-k", 45 | "--keep", 46 | is_flag=True, 47 | help="Keep BLAST and isPcr output files.", 48 | show_default=True, 49 | ) 50 | @click.option( 51 | "-d", 52 | "--cluster-distance", 53 | default=500, 54 | help="Distance between cluster of matches to consider as different clusters.", 55 | show_default=True, 56 | ) 57 | @click.option( 58 | "-o", 59 | "--output", 60 | default="stdout", 61 | help="Output stream. Path to file for output to a file.", 62 | show_default=True, 63 | ) 64 | @click.option( 65 | "-f", 66 | "--output-format", 67 | default="short", 68 | help="Output format.", 69 | type=click.Choice(["short", "verbose", "visual"]), 70 | ) 71 | @click.option( 72 | "--dust", 73 | default="no", 74 | help="[BLAST] Filter query sequence with DUST.", 75 | type=click.Choice(["yes", "no", "level window linker"]), 76 | show_default=True, 77 | ) 78 | @click.option( 79 | "--percent-identity", 80 | default=95, 81 | help="[BLAST] Minimal percent identity of sequence.", 82 | show_default=True, 83 | ) 84 | @click.option( 85 | "--culling-limit", 86 | default=5, 87 | help="[BLAST] Total hits to return in a position.", 88 | show_default=True, 89 | ) 90 | @click.option( 91 | "--mismatch", 92 | default=4, 93 | help="[BLAST] Threshold for number of mismatch to allow in BLAST hit.", 94 | show_default=True, 95 | ) 96 | @click.option( 97 | "--align-diff", 98 | default=5, 99 | help="[BLAST] Threshold for difference between alignment length and subject length in BLAST hit.", 100 | show_default=True, 101 | ) 102 | @click.option( 103 | "--gap", 104 | default=2, 105 | help="[BLAST] Threshold gap to allow in BLAST hit.", 106 | show_default=True, 107 | ) 108 | @click.option( 109 | "--blast-path", 110 | help="[BLAST] Specify full path to blastn executable.", 111 | show_default=True, 112 | ) 113 | @click.option( 114 | "--pcr-primers", 115 | default='cdc', 116 | type=click.Choice(['cdc', 'frost'], case_sensitive=False), 117 | help="[isPcr] Primer set to use (either canonical CDC or Frost et al. 2020).", 118 | show_default=True, 119 | ) 120 | @click.option( 121 | "--primer-db", 122 | default=os.environ.get("EMM_PCR", None), 123 | help="[isPcr] PCR primer. Text file with 3 columns: Name, Forward Primer, Reverse Primer. This options overrides --pcr-primers.", 124 | show_default=True, 125 | ) 126 | @click.option( 127 | "--min-perfect", 128 | default=5, 129 | help="[isPcr] Minimum size of perfect match at 3' primer end.", 130 | show_default=True, 131 | ) 132 | @click.option( 133 | "--min-good", 134 | default=15, 135 | help="[isPcr] Minimum size where there must be 2 matches for each mismatch.", 136 | show_default=True, 137 | ) 138 | @click.option( 139 | "--max-size", 140 | default=2000, 141 | help="[isPcr] Maximum size of PCR product.", 142 | show_default=True, 143 | ) 144 | @click.option( 145 | "--tile-size", 146 | default=6, 147 | help="[isPcr] The size of match that triggers an alignment.[6-18]", 148 | show_default=True, 149 | ) 150 | @click.option( 151 | "--step-size", 152 | default=5, 153 | help="[isPcr] Spacing between tiles.", 154 | show_default=True, 155 | ) 156 | @click.option( 157 | "--ispcr-path", 158 | help="[isPcr] Specify full path to isPcr executable.", 159 | show_default=True, 160 | ) 161 | def main( 162 | fasta, 163 | workflow, 164 | blast_db, 165 | keep, 166 | cluster_distance, 167 | output, 168 | output_format, 169 | dust, 170 | percent_identity, 171 | culling_limit, 172 | mismatch, 173 | align_diff, 174 | gap, 175 | blast_path, 176 | primer_db, 177 | min_perfect, 178 | min_good, 179 | max_size, 180 | tile_size, 181 | step_size, 182 | pcr_primers, 183 | ispcr_path, 184 | ): 185 | """ 186 | Welcome to emmtyper. 187 | 188 | Usage: 189 | 190 | emmtyper *.fasta 191 | """ 192 | logger.info("Start running emmtyper on {} queries.".format(len(fasta))) 193 | for i, query in enumerate(fasta): 194 | if workflow == "pcr": 195 | if int(tile_size) > 18 or int(tile_size) < 6: 196 | logger.error("isPCR DNA tileSize must be between 6 and 18") 197 | sys.exit() 198 | query = run_ispcr.get_amplicons( 199 | query, 200 | str(primer_db), 201 | min_perfect, 202 | min_good, 203 | max_size, 204 | tile_size, 205 | step_size, 206 | ispcr_path 207 | ) 208 | if not primer_db and pcr_primers.lower() == 'cdc': 209 | primer_db = CDC_PRIMERS 210 | query = run_ispcr.get_amplicons( 211 | query, str(primer_db), min_perfect, min_good, max_size, ispcr_path 212 | ) 213 | elif not primer_db and pcr_primers.lower() == 'frost': 214 | primer_db = FROST_PRIMERS 215 | query = run_ispcr.get_amplicons( 216 | query, str(primer_db), min_perfect, min_good, max_size, ispcr_path 217 | ) 218 | elif primer_db: 219 | query = run_ispcr.get_amplicons( 220 | query, str(primer_db), min_perfect, min_good, max_size, ispcr_path 221 | ) 222 | else: 223 | logger.error("No primer database specified.") 224 | raise SystemExit(1) 225 | 226 | blast_matches = run_blast.get_matches( 227 | query, 228 | str(blast_db), 229 | dust, 230 | percent_identity, 231 | culling_limit, 232 | mismatch, 233 | align_diff, 234 | gap, 235 | blast_path, 236 | ) 237 | 238 | clusterer = Clusterer( 239 | blastOutputFile=blast_matches, 240 | distance=cluster_distance, 241 | output_stream=output, 242 | output_type=output_format, 243 | ) 244 | clusterer() 245 | 246 | if not keep: 247 | os.remove(blast_matches) 248 | 249 | logger.info("Finished emmtyper.") 250 | 251 | 252 | if __name__ == "__main__": 253 | main() 254 | -------------------------------------------------------------------------------- /emmtyper/utilities/make_db.py: -------------------------------------------------------------------------------- 1 | """ 2 | Update and make a BLAST DB from a new DB FASTA file 3 | """ 4 | 5 | import subprocess 6 | import ftplib 7 | import logging 8 | import datetime 9 | from dateutil import parser 10 | import json 11 | import pathlib 12 | import os 13 | import tempfile 14 | import shutil 15 | from typing import List, Dict 16 | 17 | import click 18 | 19 | 20 | logging.basicConfig(level=logging.DEBUG) 21 | LOGGER = logging 22 | 23 | def decode_history(dct: dict) -> dict: 24 | """ 25 | Decode the history dictionary from JSON to a Python dictionary. 26 | """ 27 | dct['updated_on'] = datetime.datetime.strptime(dct["updated_on"], "%Y-%m-%d") if dct["updated_on"] else "" 28 | dct['uploaded_to_server_on'] = datetime.datetime.strptime(dct["uploaded_to_server_on"], "%Y-%m-%d") if dct["uploaded_to_server_on"] else "" 29 | return dct 30 | 31 | def encode_history(obj): 32 | if isinstance(obj, datetime.datetime): 33 | return obj.strftime("%Y-%m-%d") 34 | return obj 35 | 36 | class DBMetadata: 37 | """ 38 | Store and update the DB Metadata 39 | """ 40 | 41 | def __init__(self, metadata_db, passwd, user="anonymous"): 42 | self.path = pathlib.Path(metadata_db) 43 | self.db_folder = self.path.parent 44 | self.history = [] 45 | self.update_dupes = [] 46 | self.update_total_seqs = 0 47 | self.user = user 48 | self.passwd = passwd 49 | if self.path.exists(): 50 | with open(self.path) as history: 51 | self.history = json.load(history, object_hook=decode_history) 52 | self.history = sorted(self.history, key=lambda k: k["updated_on"]) 53 | self.metad = self.history[-1] 54 | else: 55 | self.metad = { 56 | "updated_on": f"{datetime.datetime.today():%Y-%m-%d}", 57 | "host": "ftp.cdc.gov", 58 | "filename": "/pub/infectious_diseases/biotech/tsemm/trimmed.tfa", 59 | "uploaded_to_server_on": "", 60 | } 61 | 62 | def needs_updating(self): 63 | con = ftplib.FTP(host=self.metad['host'], user=self.user, passwd=self.passwd) 64 | modified_date = parser.parse(con.sendcmd("MDTM " + self.metad['db_name'])[4:]) 65 | LOGGER.debug( 66 | f"Is {modified_date:%Y-%m-%d} later than {self.uploaded_to_server_on:%Y-%m-%d}?: {modified_date.date() > self.uploaded_to_server_on.date()}" 67 | ) 68 | return modified_date.date() > self.uploaded_to_server_on.date() 69 | 70 | def update_info(self, key, value): 71 | try: 72 | self.metad[key] = value 73 | except KeyError as error: 74 | print(error) 75 | pass 76 | 77 | def update_metadata_file(self): 78 | self.history.append(self.metad) 79 | with open(self.path, "w") as metajson: 80 | json.dump(self.history, metajson, default=encode_history, indent=4) 81 | 82 | def make_db(self, fasta_file): 83 | ''' 84 | Main function to generate a BLAST DB 85 | ''' 86 | title = f'"EMM DB created on {datetime.date.today():%Y-%m-%d}"' 87 | with tempfile.TemporaryDirectory() as tmpdir: 88 | os.chdir(tmpdir) 89 | LOGGER.info("Making BLAST DB...") 90 | LOGGER.debug(f"Working in temp folder {tmpdir}...") 91 | LOGGER.debug(f"Original FASTA file: {str(fasta_file.absolute())}") 92 | fasta_name = fasta_file.name 93 | shutil.copy(str(fasta_file.absolute()), fasta_name) 94 | clean_db = f'seqkit rmdup -s -D dupes.txt {fasta_name} > {fasta_name}.clean' 95 | LOGGER.debug(f"Checking for duplicates in the FASTA file: {clean_db}") 96 | subprocess.run(clean_db, shell=True, check=True) 97 | with open("dupes.txt", "r") as dupes: 98 | dupes = dupes.readlines() 99 | if len(dupes) > 0: 100 | # create a backup copy of the original FASTA 101 | shutil.copy(fasta_name, fasta_name + ".orig") 102 | LOGGER.warning(f"Found {len(dupes)} duplicate sequences in {fasta_name}") 103 | LOGGER.warning("Cleaning up duplicates...") 104 | dupes = [d.strip().split("\t")[1].replace(", ", ":") for d in dupes] 105 | dupes = [f"{d.split(':')[0]}\t{d}" for d in dupes] 106 | self.update_dupes = dupes 107 | with open("replacements.txt", "w") as replacements: 108 | replacements.write("\n".join(dupes)) 109 | relabel_db = f"seqkit replace -r '{{kv}}${{2}}' -k replacements.txt -p '(\w+\.\d+)( .*)$' -K {fasta_name}.clean > {fasta_name}" 110 | subprocess.run(relabel_db, shell=True, check=True) 111 | self.update_total_seqs = int(subprocess.run(f"grep '>' {fasta_name} | wc -l", shell=True, capture_output=True, encoding='utf-8').stdout.strip()) 112 | cmd = f'makeblastdb -in "{fasta_name}" -dbtype nucl -title {title}' 113 | LOGGER.info(f"Running command: {cmd}") 114 | try: 115 | subprocess.run(cmd, shell=True, check=True) 116 | dest = str(fasta_file.parent) 117 | for fn in os.listdir(): 118 | if fasta_name in fn: 119 | LOGGER.debug(f"Copying {fn} to {dest}") 120 | shutil.copy(fn, dest) 121 | except subprocess.CalledProcessError as error: 122 | LOGGER.exception(error) 123 | raise 124 | self.update_info("total_seqs", self.update_total_seqs) 125 | self.update_info("total_duplicate_seqs", len(self.update_dupes)) 126 | self.update_info("duplicated_seqs", self.update_dupes) 127 | 128 | 129 | def download_cdc_db( 130 | db_folder, passwd, user="anonymous", db_metadata="db_metadata.json" 131 | ): 132 | ''' 133 | Download the CDC DB. 134 | ''' 135 | db_path = pathlib.Path(db_folder) 136 | db_path.mkdir(parents=True, exist_ok=True) 137 | db_metadata = db_path / db_metadata 138 | db_fasta = db_path / "emm.fna" 139 | db = DBMetadata(db_metadata) 140 | filename = db.metad["filename"] 141 | host = db.metad["host"] 142 | con = ftplib.FTP(host=host, user=user, passwd=passwd) 143 | updated_on = f"{datetime.datetime.today():%Y-%m-%d}" 144 | modified_time = parser.parse(con.sendcmd("MDTM " + filename)[4:]) 145 | if db.needs_updating(modified_time): 146 | with open(db_fasta, "wb") as emm_fa: 147 | con.retrbinary(f"RETR {filename}", emm_fa.write) 148 | try: 149 | if db_fasta.exists(): 150 | db.make_db(db_fasta, updated_on) 151 | db.update_info("updated_on", updated_on) 152 | db.update_info("uploaded_to_server_on", f"{modified_time:%Y-%m-%d}") 153 | db.update_metadata_file() 154 | else: 155 | raise FileNotFoundError 156 | except FileNotFoundError as error: 157 | LOGGER.exception(error) 158 | else: 159 | LOGGER.info("EMM DB is up-to-date.") 160 | 161 | 162 | def get_db_folder(): 163 | """ 164 | Check if EMM_DB is in the os.environ, else return the location of the DB in the package. 165 | 166 | If not writable, make another suggestion in the users /home folder 167 | """ 168 | db_folder = os.environ.get( 169 | "EMM_DB", pathlib.Path(__file__).absolute().parent.parent / "db" 170 | ) 171 | try: 172 | test_file = db_folder / "test.txt" 173 | with open(test_file, "w") as testf: 174 | testf.write("testing") 175 | test_file.unlink() 176 | except PermissionError: 177 | try: 178 | db_folder = pathlib.Path.home() / "emm_db" 179 | db_folder.mkdir() 180 | except FileExistsError as error: 181 | pass 182 | except Exception as error: 183 | LOGGER.exception(error) 184 | return db_folder 185 | 186 | 187 | @click.command() 188 | @click.argument("email") 189 | @click.option( 190 | "--db_folder", 191 | "-d", 192 | help="Where to update the DB", 193 | default=get_db_folder(), 194 | show_default=True, 195 | ) 196 | def emmtyper_db(email, db_folder): 197 | """\ 198 | EMAIL is needed to connect to CDC FTP server. 199 | 200 | By default, db_folder will be taken from EMM_DB environmental folder. 201 | If can't find the folder, will default to where emmtyper 202 | is installed. If it cannot write to the installation folder, 203 | it will make a suggestion in your /home folder. 204 | 205 | """ 206 | download_cdc_db(db_folder, email) 207 | 208 | 209 | if __name__ == "__main__": 210 | emmtyper_db() 211 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # emmtyper - Emm Automatic Isolate Labeller 2 | 3 | [![CI](https://github.com/MDU-PHL/emmtyper/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/MDU-PHL/emmtyper/actions/workflows/unit-tests.yml) 4 | [![Coverage Status](https://coveralls.io/repos/github/MDU-PHL/emmtyper/badge.svg?branch=master)](https://coveralls.io/github/MDU-PHL/emmtyper?branch=master) ![PyPI - Implementation](https://img.shields.io/pypi/implementation/emmtyper) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/emmtyper) ![PyPI](https://img.shields.io/pypi/v/emmtyper) ![PyPI - License](https://img.shields.io/pypi/l/emmtyper) ![PyPI - Wheel](https://img.shields.io/pypi/wheel/emmtyper) ![Conda](https://img.shields.io/conda/pn/bioconda/emmtyper?label=bioconda) ![PyPI - Downloads](https://img.shields.io/pypi/dm/emmtyper) ![PyPI - Status](https://img.shields.io/pypi/status/emmtyper) ![GitHub issues](https://img.shields.io/github/issues-raw/MDU-PHL/emmtyper) 5 | 6 | ## Table of Content 7 | 8 | - [emmtyper - Emm Automatic Isolate Labeller](#emmtyper---emm-automatic-isolate-labeller) 9 | - [Table of Content](#table-of-content) 10 | - [Background](#background) 11 | - [Inner workings](#inner-workings) 12 | - [Requirements](#requirements) 13 | - [Installation](#installation) 14 | - [Brew](#brew) 15 | - [Conda](#conda) 16 | - [Usage](#usage) 17 | - [Example Commands](#example-commands) 18 | - [Result Format](#result-format) 19 | - [Short format](#short-format) 20 | - [Verbose format](#verbose-format) 21 | - [Visual format](#visual-format) 22 | - [Tags](#tags) 23 | - [Example outputs](#example-outputs) 24 | - [BLAST or PCR?](#blast-or-pcr) 25 | - [Validation data](#validation-data) 26 | - [Authors](#authors) 27 | - [Maintainer](#maintainer) 28 | - [Issues](#issues) 29 | - [References](#references) 30 | 31 | ## Background 32 | 33 | `emmtyper` is a command line tool for emm-typing of _Streptococcus pyogenes_ using a _de novo_ or complete assembly. 34 | 35 | By default, we use the U.S. Centers for Disease Control and Prevention trimmed emm subtype database, 36 | which can be found [here](https://www2a.cdc.gov/ncidod/biotech/strepblast.asp). 37 | The database is curated by Dr. Velusamy Srinivasan. We take this opportunity to thank Dr. Srinivasan for his work. 38 | 39 | The tool has two basic modes: 40 | 41 | * `blast`: In this mode the contigs are blasted against the trimmed FASTA database curated by the CDC. 42 | * `pcr`: In this mode, first an _in silico_ PCR is done on the contigs using the `isPCR` tool (Kuhn et al. 2013). The resulting fragments are then blasted against the trimmed FASTA database curated by the CDC. Two sets of primers are provided for the user to choose from: 1. The canonical CDC primers used for **conventional** PCR (Whatmore and Kehoe 1994); 2. the primers described by Frost et al. 2020. This last set uses the forward primers of Whatmore and Kehoe (1994), but provide a re-designed reverse primer. There is also the option of the user providing their own primer set in the format required by the `isPCR` tool. 43 | 44 | ### Inner workings 45 | 46 | The difficulty in performing M-typing is that there is a single gene of interest (`emm`), but two other homologue genes (`enn` and `mrp`), often referred to as `emm-like`. The homologue genes may or may not occur in the isolate of interest. When performing `emm-typing` from an assembly, we can distinguish betweeen one or more clusters of matches on the contigs. The best match for each of the clusters identified is then parsed from the BLAST results. Where possible, we try to distinguish between matches to the `emm` gene, and matches to one of the `emm-like` genes. 47 | 48 | Possible arrangments: 49 | 50 |        _emm_ 51 | 52 | ---->>>>>>>---- 53 | 54 |         _mrp_                 _emm_                 _enn_ 55 | 56 | ---->>>>>>----->>>>>>------>>>>>>----- 57 | 58 |            _emm_                 _enn_ 59 | 60 | ----->>>>>>------>>>>>>----- 61 | 62 | ## Requirements 63 | 64 | - `blastn` ≥ 2.6 (tested on 2.9) 65 | - `isPcr` 66 | - `python` ≥ 3.6 67 | 68 | ## Installation 69 | 70 | ### Brew 71 | 72 | ```bash 73 | brew install python blast ispcr 74 | pip3 install emmtyper 75 | emmtyper --help 76 | ``` 77 | 78 | ### Conda 79 | 80 | ```bash 81 | conda install -c conda-forge -c bioconda -c defaults emmtyper 82 | ``` 83 | 84 | ## Usage 85 | 86 | `emmtyper` has two workflows: directly BLASTing the contigs against the DB, or using `isPcr` to generate an _in silico_ PCR product that is then BLASTed against the DB. The BLAST results go through `emmtyper`'s business logic to distinguish between `emm` and `emm-like` alleles and derive the isoolate M-type. 87 | 88 | The basic usage of emmtyper is in the form of: 89 | 90 | ```bash 91 | emmtyper [options] contig1 contig2 ... contigN 92 | ``` 93 | 94 | All the available options can be printed to the console with `emmtyper --help`. Options passed on to `blast` are tagged with `[BLAST]`, and those for `isPcr` are tagged with `[isPcr]`. 95 | 96 | ```bash 97 | Usage: emmtyper [OPTIONS] [FASTA]... 98 | 99 | Welcome to emmtyper. 100 | 101 | Usage: 102 | 103 | emmtyper *.fasta 104 | 105 | Options: 106 | --version Show the version and exit. 107 | -w, --workflow [blast|pcr] Choose workflow [default: blast] 108 | -db, --blast_db TEXT Path to EMM BLAST DB [default: 109 | /path/to/emmtyper/db/emm.fna] 110 | -k, --keep Keep BLAST and isPcr output files. 111 | [default: False] 112 | -d, --cluster-distance INTEGER Distance between cluster of matches to 113 | consider as different clusters. [default: 114 | 500] 115 | -o, --output TEXT Output stream. Path to file for output to a 116 | file. [default: stdout] 117 | -f, --output-format [short|verbose|visual] 118 | Output format. 119 | --dust [yes|no|level window linker] 120 | [BLAST] Filter query sequence with DUST. 121 | [default: no] 122 | --percent-identity INTEGER [BLAST] Minimal percent identity of 123 | sequence. [default: 95] 124 | --culling-limit INTEGER [BLAST] Total hits to return in a position. 125 | [default: 5] 126 | --mismatch INTEGER [BLAST] Threshold for number of mismatch to 127 | allow in BLAST hit. [default: 4] 128 | --align-diff INTEGER [BLAST] Threshold for difference between 129 | alignment length and subject length in BLAST 130 | hit. [default: 5] 131 | --gap INTEGER [BLAST] Threshold gap to allow in BLAST hit. 132 | [default: 2] 133 | --blast-path TEXT [BLAST] Specify full path to blastn 134 | executable. 135 | --pcr-primers [cdc|frost] [isPcr] Primer set to use (either canonical 136 | CDC or Frost et al. 2020). [default: cdc] 137 | --primer-db TEXT [isPcr] PCR primer. Text file with 3 138 | columns: Name, Forward Primer, Reverse 139 | Primer. This options overrides --pcr- 140 | primers. 141 | --min-perfect INTEGER [isPcr] Minimum size of perfect match at 3\' 142 | primer end. [default: 15] 143 | --min-good INTEGER [isPcr] Minimum size where there must be 2 144 | matches for each mismatch. [default: 15] 145 | --max-size INTEGER [isPcr] Maximum size of PCR product. 146 | [default: 2000] 147 | --ispcr-path TEXT [isPcr] Specify full path to isPcr 148 | executable. 149 | --help Show this message and exit. 150 | ``` 151 | 152 | Most of these options are self explanatory. The two expections are: 153 | 154 | 1. `--workflow`: choose between a `blast` only workflow, or a _in silico_ PCR followed by `blast` workflow. See below for more information. 155 | 2. `--clust_distance` defines the minimum distance between clusters of matched sequences on the contigs to generate separate `emm-type` calls for each clusters. Clusters of matches that are within the minimum `clust-distance` are treated as a single location match. 156 | 3. `--output_type` demonstrated below. 157 | 158 | ### Example Commands 159 | 160 | ```bash 161 | # basic call using the blast workflow for a single contig file 162 | emmtyper isolate1.fa 163 | # basic call using the pcr workflow for all the .fa files in a folder 164 | emmtyper -w pcr *.fa 165 | # basic call changing some of the options for blast 166 | emmtyper --keep --culling_limit 10 --align_diff 10 *.fa 167 | # call using the pcr workflow changing some of the isPcr options and 168 | # using the visual output format - this will run the with the CDC canonical 169 | # primers 170 | emmtyper -w pcr --output-format visual --max-size 2000 --mismatch 5 *.fa 171 | 172 | # same as above, but now with the Frost et al. 2020 primers. 173 | emmtyper -w pcr --output-format visual --max-size 2000 --mismatch 5 --pcr-primers frost *.fa 174 | ``` 175 | 176 | ## Result Format 177 | 178 | ### Short format 179 | 180 | emmtyper has three different result formats: `short`, `verbose`, and `visual`. 181 | 182 | emmtyper by default produces the `short` version. This consists of five values in tab-separated format printed to stdout. 183 | 184 | The values are: 185 | 186 | - Isolate name 187 | - Number of clusters: should be between 1 and 3, larger values could indicate contamination 188 | - Predicted `emm-type` 189 | - Possible `emm-like` alleles (semi-colon separated list) 190 | - EMM cluster: Functional grouping of EMM types into 48 clusters 191 | 192 | ### Verbose format 193 | 194 | The verbose result returns: 195 | 196 | - Isolate name 197 | - Number of BLAST hits 198 | - Number of clusters: should be between 1 and 3, larger values could indicate contamination 199 | - Predicted `emm-type` 200 | - Position(s) `emm-like` alleles in the assembly 201 | - Possible `emm-like` alleles (semi-colon separated list) 202 | - `emm-like` position(s) in assembly 203 | - EMM cluster: Functional grouping of EMM types into 48 clusters 204 | 205 | The positions in the assembly are presented in the following format `:`. 206 | 207 | ### Visual format 208 | 209 | The visual result returns an ASCII map of the `emm` and, if found any `emm-alleles`, in the genome. Alleles on a single contig are separated by "-", with each "-" representing 500bp. Alleles found on different contigs are separated with tab. 210 | 211 | ### Tags 212 | 213 | The alleles can be tagged with a suffix character to indicate different possibilities: 214 | 215 | | Tag | Description | Additional Information | 216 | | --- | ------------------ | --------------------------------------------------------- | 217 | | \* | Suspect `emm-like` | Allele flagged in the CDC database as possibly `emm-like` | 218 | | ~ | Imperfect score | Match score below 100% | 219 | 220 | ### Example outputs 221 | 222 | Example for all result format: 223 | 224 | Short format: 225 | 226 | ``` 227 | Isolate1 1 EMM65.0 E6 228 | Isolate2 3 EMM4.0 EMM236.3*;EMM156.0* E1 229 | Isolate3 2 EMM52.1 EMM134.2* D4 230 | ``` 231 | 232 | Verbose format: 233 | 234 | ``` 235 | Isolate1 6 1 EMM65.0 5:82168 E6 236 | Isolate2 8 3 EMM4.0 2:104111 EMM236.3*;EMM156.0* 2:102762;2:105504 E1 237 | Isolate3 5 2 EMM52.1 14:10502 EMM134.2* 5:913 D4 238 | ``` 239 | 240 | Visual format: 241 | 242 | ``` 243 | Isolate1 EMM65.0 244 | Isolate2 EMM156.0*--EMM4.0--EMM236.3* 245 | Isolate3 EMM52.1 EMM134.2* 246 | ``` 247 | 248 | ## BLAST or PCR? 249 | 250 | If you are not sure which pipeline to choose from, we recommend using `blast` first. The `blast` workflow is fast and works well with assemblies. You can then use the `pcr` mode if you wish to perform some troubleshooting. 251 | 252 | For example, the `pcr` workflow might be useful when troubleshooting isolates for which emmtyper has reported more than 3 clusteres and/or too many alleles. 253 | 254 | An important thing to note is that not all `emm-like` alleles can be identified by using by PCR typing. The `pcr` workflow can be used to test which hits would be returned if carrying out conventional M-typing using PCR. However, the workflow is not foolproof, as _in silico_ PCR will fail when one or both primers do not align in the same contig (i.e., the allele is broken across two or more contigs) or there are mutations in the primer sites. In the former case, this might be an indication of poor sequence coverage or contamination. 255 | 256 | ## Validation data 257 | 258 | We compared `emmtyper` against `Sanger` sequencing data and PHE's tool [`emm-typing-tool`](https://github.com/phe-bioinformatics/emm-typing-tool). 259 | 260 | You can check out the validation comparison go to out binder: 261 | 262 | [![badge](https://img.shields.io/badge/launch-binder-579ACA.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFkAAABZCAMAAABi1XidAAAB8lBMVEX///9XmsrmZYH1olJXmsr1olJXmsrmZYH1olJXmsr1olJXmsrmZYH1olL1olJXmsr1olJXmsrmZYH1olL1olJXmsrmZYH1olJXmsr1olL1olJXmsrmZYH1olL1olJXmsrmZYH1olL1olL0nFf1olJXmsrmZYH1olJXmsq8dZb1olJXmsrmZYH1olJXmspXmspXmsr1olL1olJXmsrmZYH1olJXmsr1olL1olJXmsrmZYH1olL1olLeaIVXmsrmZYH1olL1olL1olJXmsrmZYH1olLna31Xmsr1olJXmsr1olJXmsrmZYH1olLqoVr1olJXmsr1olJXmsrmZYH1olL1olKkfaPobXvviGabgadXmsqThKuofKHmZ4Dobnr1olJXmsr1olJXmspXmsr1olJXmsrfZ4TuhWn1olL1olJXmsqBi7X1olJXmspZmslbmMhbmsdemsVfl8ZgmsNim8Jpk8F0m7R4m7F5nLB6jbh7jbiDirOEibOGnKaMhq+PnaCVg6qWg6qegKaff6WhnpKofKGtnomxeZy3noG6dZi+n3vCcpPDcpPGn3bLb4/Mb47UbIrVa4rYoGjdaIbeaIXhoWHmZYHobXvpcHjqdHXreHLroVrsfG/uhGnuh2bwj2Hxk17yl1vzmljzm1j0nlX1olL3AJXWAAAAbXRSTlMAEBAQHx8gICAuLjAwMDw9PUBAQEpQUFBXV1hgYGBkcHBwcXl8gICAgoiIkJCQlJicnJ2goKCmqK+wsLC4usDAwMjP0NDQ1NbW3Nzg4ODi5+3v8PDw8/T09PX29vb39/f5+fr7+/z8/Pz9/v7+zczCxgAABC5JREFUeAHN1ul3k0UUBvCb1CTVpmpaitAGSLSpSuKCLWpbTKNJFGlcSMAFF63iUmRccNG6gLbuxkXU66JAUef/9LSpmXnyLr3T5AO/rzl5zj137p136BISy44fKJXuGN/d19PUfYeO67Znqtf2KH33Id1psXoFdW30sPZ1sMvs2D060AHqws4FHeJojLZqnw53cmfvg+XR8mC0OEjuxrXEkX5ydeVJLVIlV0e10PXk5k7dYeHu7Cj1j+49uKg7uLU61tGLw1lq27ugQYlclHC4bgv7VQ+TAyj5Zc/UjsPvs1sd5cWryWObtvWT2EPa4rtnWW3JkpjggEpbOsPr7F7EyNewtpBIslA7p43HCsnwooXTEc3UmPmCNn5lrqTJxy6nRmcavGZVt/3Da2pD5NHvsOHJCrdc1G2r3DITpU7yic7w/7Rxnjc0kt5GC4djiv2Sz3Fb2iEZg41/ddsFDoyuYrIkmFehz0HR2thPgQqMyQYb2OtB0WxsZ3BeG3+wpRb1vzl2UYBog8FfGhttFKjtAclnZYrRo9ryG9uG/FZQU4AEg8ZE9LjGMzTmqKXPLnlWVnIlQQTvxJf8ip7VgjZjyVPrjw1te5otM7RmP7xm+sK2Gv9I8Gi++BRbEkR9EBw8zRUcKxwp73xkaLiqQb+kGduJTNHG72zcW9LoJgqQxpP3/Tj//c3yB0tqzaml05/+orHLksVO+95kX7/7qgJvnjlrfr2Ggsyx0eoy9uPzN5SPd86aXggOsEKW2Prz7du3VID3/tzs/sSRs2w7ovVHKtjrX2pd7ZMlTxAYfBAL9jiDwfLkq55Tm7ifhMlTGPyCAs7RFRhn47JnlcB9RM5T97ASuZXIcVNuUDIndpDbdsfrqsOppeXl5Y+XVKdjFCTh+zGaVuj0d9zy05PPK3QzBamxdwtTCrzyg/2Rvf2EstUjordGwa/kx9mSJLr8mLLtCW8HHGJc2R5hS219IiF6PnTusOqcMl57gm0Z8kanKMAQg0qSyuZfn7zItsbGyO9QlnxY0eCuD1XL2ys/MsrQhltE7Ug0uFOzufJFE2PxBo/YAx8XPPdDwWN0MrDRYIZF0mSMKCNHgaIVFoBbNoLJ7tEQDKxGF0kcLQimojCZopv0OkNOyWCCg9XMVAi7ARJzQdM2QUh0gmBozjc3Skg6dSBRqDGYSUOu66Zg+I2fNZs/M3/f/Grl/XnyF1Gw3VKCez0PN5IUfFLqvgUN4C0qNqYs5YhPL+aVZYDE4IpUk57oSFnJm4FyCqqOE0jhY2SMyLFoo56zyo6becOS5UVDdj7Vih0zp+tcMhwRpBeLyqtIjlJKAIZSbI8SGSF3k0pA3mR5tHuwPFoa7N7reoq2bqCsAk1HqCu5uvI1n6JuRXI+S1Mco54YmYTwcn6Aeic+kssXi8XpXC4V3t7/ADuTNKaQJdScAAAAAElFTkSuQmCC)](https://mybinder.org/v2/gh/MDU-PHL/emmtyper/946ddb74e7ce92654567630bd5787430d5945451) 263 | 264 | ## Authors 265 | 266 | - Andre Tan 267 | - Torsten Seemann 268 | - Kristy Horan 269 | - Jake Lacey 270 | - Himal Shrestha 271 | - Raquel Cooper 272 | - Anders Gonçalves da Silva 273 | 274 | ## Acknowledgements 275 | The codebase for `emmtyper` was primarly written by Andre Tan as part of his Master's 276 | Degree in Bioinformatics. Torsten Seemann, Deborah Williamson, and Anders Gonçalves da Silva provided supervision and assistance. 277 | 278 | Hannah Frost contributed with EMM clustering by suggesting we incorporate it in to the code, and providing the necessary information to do so and test it. 279 | 280 | Validation was conducted within MDU-Bioinformatics `emmtyper`. 281 | 282 | ## Maintainer 283 | 284 | The code is actively maintained by MDU Bioinformatics Team. 285 | 286 | Contact the principal maintainer at MDU-Bioinformatics@unimelb.edu.au. 287 | 288 | ## Issues 289 | 290 | Please post bug reports, questions, suggestions in the [Issues](https://github.com/MDU-PHL/emmtyper/issues) section. 291 | 292 | ## References 293 | 294 | Frost, H. R., Davies, M. R., Velusamy, S., Delforge, V., Erhart, A., Darboe, S., Steer, A., Walker, M. J., Beall, B., Botteaux, A., & Smeesters, P. R. (2020). Updated emm-typing protocol for Streptococcus pyogenes. Clinical Microbiology and Infection: The Official Publication of the European Society of Clinical Microbiology and Infectious Diseases, 26(7), 946.e5–e946.e8. 295 | 296 | Kuhn, R. M., Haussler, D., & Kent, W. J. (2013). The UCSC genome browser and associated tools. Briefings in Bioinformatics, 14(2), 144–161. 297 | 298 | Whatmore, A. M., & Kehoe, M. A. (1994). Horizontal gene transfer in the evolution of group A streptococcal emm-like genes: gene mosaics and variation in Vir regulons. Molecular Microbiology, 11(2), 363–374. 299 | -------------------------------------------------------------------------------- /emmtyper/objects/clusterer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define the clustered class to determine the EMM type for each cluster of matches 3 | """ 4 | import numpy as np 5 | from scipy.cluster.hierarchy import linkage, fcluster 6 | 7 | import emmtyper.objects.emm as emm 8 | from emmtyper.objects.result_row import ResultRow, EmmImposters 9 | 10 | import logging 11 | 12 | logger = logging.getLogger(__name__) 13 | logger.setLevel(logging.INFO) 14 | 15 | short_header = "Isolate\tNumberOfClusters\tAnswers\tSuspectImposters\tAnswersClusters\n" 16 | verbose_header = "Isolate\tNumberOfHits\tNumberOfClusters\tAnswers\tAnswerPositions\tSuspectImposters\tSuspectPositions\tAnswersClusters\n" 17 | 18 | nullResult = ResultRow("0\tEMM0.0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0") 19 | 20 | 21 | class Clusterer: 22 | """ 23 | Class to identify distinct clusters of matching sequences 24 | """ 25 | 26 | def __init__( 27 | self, 28 | blastOutputFile, 29 | output_stream, 30 | output_type="short", 31 | distance=500, 32 | linkage="ward", 33 | header=False, 34 | ): 35 | self.isolate = blastOutputFile 36 | self.results = self.extractFromFile(blastOutputFile) 37 | self.header = header 38 | 39 | self.output_stream = output_stream 40 | self.output_type = output_type 41 | 42 | self.clust_distance = distance 43 | self.linkage = linkage 44 | 45 | self.cluster_number = 0 46 | self.ascii_vis = self.isolate 47 | 48 | def __repr__(self): 49 | string = "Clusterer for {} with clustering distance {}bp\n{} output to {}" 50 | 51 | return string.format( 52 | self.isolate, self.clust_distance, self.output_type, self.output_stream 53 | ) 54 | 55 | def extractFromFile(self, blastOutputFile): 56 | with open(blastOutputFile, "r") as handle: 57 | results = [ResultRow(line.strip()) for line in handle.readlines()] 58 | 59 | return results 60 | 61 | def list_to_string_emm(self, answers): 62 | string = "" 63 | logger.debug("There are {} answers".format(len(answers))) 64 | 65 | for answer in answers: 66 | if type(answer) is ResultRow: 67 | string += str(answer) 68 | elif type(answer) is list: 69 | positions = set([ans.queryStart for ans in answer]) 70 | for pos in positions: 71 | emm_types = [str(ans) 72 | for ans in answer if ans.queryStart == pos] 73 | emm_types_str = '({})'.format(';'.join(emm_types)) 74 | string += emm_types_str 75 | else: 76 | raise Exception("Answer is {}".format(type(answer))) 77 | 78 | string += ";" 79 | 80 | return string[:-1] 81 | 82 | def list_to_string_positions(self, answers): 83 | string = "" 84 | logger.debug("There are {} answers".format(len(answers))) 85 | 86 | for answer in answers: 87 | if type(answer) is ResultRow: 88 | string += "{}:{}".format(answer.query, answer.queryStart) 89 | elif type(answer) is list: 90 | positions = set([ans.queryStart for ans in answer]) 91 | for pos in positions: 92 | hits = [ 93 | '{}:{}'.format( 94 | ans.query, 95 | ans.queryStart 96 | ) 97 | for ans in answer 98 | if ans.queryStart == pos 99 | ] 100 | hits_str = '({})'.format(';'.join(hits)) 101 | string += hits_str 102 | else: 103 | raise Exception("Answer is {}".format(type(answer))) 104 | 105 | string += ";" 106 | 107 | return string[:-1] 108 | 109 | def list_to_string_emm_clusters(self, answers): 110 | string = "" 111 | logger.debug("There are {} answers".format(len(answers))) 112 | 113 | for answer in answers: 114 | if type(answer) is ResultRow: 115 | string += emm.EMM(answer.type).emm_cluster 116 | elif type(answer) is list: 117 | positions = set([ans.queryStart for ans in answer]) 118 | for pos in positions: 119 | clusters = [ 120 | emm.EMM(ans.type).emm_cluster for ans in answer if ans.queryStart == pos] 121 | clusters_str = '({})'.format(';'.join(clusters)) 122 | string += clusters_str 123 | else: 124 | raise Exception("Answer is {}".format(type(answer))) 125 | 126 | string += ";" 127 | 128 | return string.strip(";") if len(string) > 1 else "NA" 129 | 130 | def short_stringer(self): 131 | 132 | str_2 = self.list_to_string_emm(self.answers).replace("EMM", "_emm_") 133 | str_3 = self.list_to_string_emm(self.possible_imposters).replace("EMM", "_emm_") 134 | string = "{0}\t{1}\t{2}\t{3}\t{4}".format( 135 | self.isolate, 136 | self.cluster_number, 137 | #self.list_to_string_emm(self.answers), 138 | str_2, 139 | #self.list_to_string_emm(self.possible_imposters), 140 | str_3, 141 | self.list_to_string_emm_clusters(self.answers), 142 | ) 143 | 144 | string = short_header + string if self.header else string 145 | 146 | return string 147 | 148 | def verbose_stringer(self): 149 | str_2 = self.list_to_string_emm(self.answers).replace("EMM", "_emm_") 150 | str_3 = self.list_to_string_emm(self.possible_imposters).replace("EMM", "_emm_") 151 | string = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}".format( 152 | self.isolate, 153 | len(self.results), 154 | self.cluster_number, 155 | #self.list_to_string_emm(self.answers), 156 | str_2, 157 | self.list_to_string_positions(self.answers), 158 | #self.list_to_string_emm(self.possible_imposters), 159 | str_3, 160 | self.list_to_string_positions(self.possible_imposters), 161 | self.list_to_string_emm_clusters(self.answers), 162 | ) 163 | 164 | string = verbose_header + string if self.header else string 165 | return string 166 | 167 | def map_stringer(self, contig): 168 | # EXPERIMENTAL 169 | # Visual map of emm hits within WGS 170 | 171 | def determine_position(result): 172 | if type(result) is ResultRow: 173 | return result.queryStart 174 | elif type(result) is list: 175 | return sum([p.queryStart for p in result]) / len(result) 176 | else: 177 | raise Exception("Something is wrong in visualization.") 178 | 179 | contig = [result[1] for result in contig] 180 | string = "" 181 | 182 | for j, pos in enumerate(contig): # List of results with best score in cluster 183 | hit = str(pos) 184 | position = determine_position(pos) 185 | 186 | if j == 0: 187 | string += hit 188 | prev_pos = position 189 | else: 190 | distance = int((position - prev_pos) // self.clust_distance) 191 | if distance < 0: 192 | string = "{}{}{}".format(hit, "-" * abs(distance), string) 193 | else: 194 | string = "{}{}{}".format(string, "-" * abs(distance), hit) 195 | 196 | prev_pos = position 197 | 198 | return string 199 | 200 | def produce_final_result(self): 201 | if self.output_type == "short": 202 | return self.short_stringer() 203 | elif self.output_type == "verbose": 204 | return self.verbose_stringer() 205 | elif self.output_type == "visual": 206 | return self.ascii_vis 207 | else: 208 | raise Exception("Choice of output type is not provided.") 209 | 210 | def cluster(self, results): 211 | """ 212 | Cluster a list of results. 213 | """ 214 | if len(results) == 1: 215 | return [1] 216 | 217 | elif len(results) >= 2: 218 | # Only take positions in specific contig 219 | positions = [result.positions[1:2] for result in results] 220 | Z = linkage(positions, self.linkage) 221 | clusters = fcluster(Z, self.clust_distance, criterion="distance") 222 | 223 | return clusters 224 | 225 | else: 226 | raise Exception( 227 | "Cannot run with {} results.".format(len(positions))) 228 | 229 | def get_best_scoring(self, results): 230 | """ 231 | Returns the best scoring result, or results when there are multiple 100-scoring results. 232 | """ 233 | if len(results) > 0: 234 | maxScore = max([result.score for result in results]) 235 | maxResult = [ 236 | result for result in results if result.score == maxScore] 237 | 238 | if len(maxResult) == 1: 239 | return maxResult[0] 240 | else: 241 | if (set([result.score for result in maxResult])) == set([100]): 242 | return maxResult 243 | else: 244 | # If scores are not 100, take random result from the array 245 | pos = np.random.randint(len(maxResult), size=1)[0] 246 | return maxResult[pos] 247 | 248 | else: 249 | # When there is no result, return a null ResultRow object. 250 | return nullResult 251 | 252 | def best_in_cluster_in_contig(self, contig): 253 | """ 254 | Take an integer value representing the contig, and return best-scoring result(s) in every cluster within the contig. 255 | """ 256 | 257 | # Extract results that fall within contig and cluster them together 258 | within_contig = np.array( 259 | [result for result in self.results if result.positions[0] == contig], 260 | dtype=object 261 | ) 262 | contig_cluster = self.cluster(within_contig) 263 | 264 | # Look for best-scoring within each cluster and return as a list of best results in contig. 265 | if len(within_contig) == 1: 266 | return [(1, within_contig[0])] 267 | 268 | elif len(within_contig) > 1: 269 | answer = [] 270 | 271 | for cluster in set(contig_cluster): 272 | within_cluster = within_contig[contig_cluster == cluster] 273 | answer.append( 274 | (len(within_cluster), self.get_best_scoring(within_cluster)) 275 | ) 276 | 277 | else: 278 | raise Exception( 279 | "Cannot run with {} results".format(len(within_contig))) 280 | 281 | return answer 282 | 283 | def classify_expected_answer(self, max_iteration=10): 284 | def is_in(all_votes, answers): 285 | """ 286 | Find whether objects within a bigger list is in a smaller list, 287 | return boolean values to be used in numpy array indexing. 288 | """ 289 | bools = np.zeros(len(all_votes), dtype=bool) 290 | 291 | for index, vote in enumerate(all_votes): 292 | logger.debug("is {} in answers? {}".format( 293 | vote, vote in answers)) 294 | bools[index] = 1 if vote in answers else 0 295 | 296 | logger.debug("is_in() returns {}".format(bools)) 297 | return bools 298 | 299 | def process_answer_logic(voted_result): 300 | """ 301 | To use when imposters filter is still used. 302 | 303 | Take heed that the list of voted results can have objects in the form of ResultRow or list, 304 | list being there if ResultRow in the list all are 100-scoring. 305 | 306 | Consider results that follow along the arguments: 307 | If there is only 1 object or list, return if it is not imposter. 308 | If there are more than 1 object or list, return the best scoring that is not imposter. 309 | """ 310 | 311 | if voted_result.shape[0] == 1: 312 | # If there is only one, it is okay as long as it is not EmmImposters 313 | logger.debug("Voted result is singular") 314 | 315 | tmp_result = voted_result[0] 316 | answer = [] 317 | if type(tmp_result) == ResultRow: 318 | answer += ( 319 | [tmp_result] if ( 320 | tmp_result.type not in EmmImposters) else [] 321 | ) 322 | elif type(tmp_result) == list: 323 | # Make sure all in the list is not imposters, add as answer if all within the list follows if argument 324 | tmp_answer = [ 325 | result 326 | for result in tmp_result 327 | if (result.type not in EmmImposters) 328 | ] 329 | answer += [tmp_answer] if len( 330 | tmp_answer) == len(tmp_result) else [] 331 | 332 | elif voted_result.shape[0] > 1: 333 | # If there is more than one, score would come into play 334 | logger.debug("Voted result is non-singular") 335 | #logger.info(type(voted_result)) 336 | tmp_result = voted_result 337 | try: 338 | x = tmp_result[0][0] 339 | tmp_result = tmp_result[0] 340 | except: 341 | tmp_result = tmp_result 342 | max_score = max([result.score for result in tmp_result]) 343 | answer = [] 344 | for result in tmp_result: 345 | answer += ( 346 | [result] 347 | if ( 348 | result.type not in EmmImposters 349 | and result.score == max_score 350 | ) 351 | else [] 352 | ) 353 | 354 | return answer 355 | 356 | def process_answer_absurd(voted_result): 357 | """ 358 | To use when imposters filter is still used. 359 | 360 | Take heed that the list of voted results can have objects in the form of ResultRow or list, 361 | list being there if ResultRow in the list all are 100-scoring. 362 | 363 | Consider results that follow along the arguments: 364 | If there is only 1 object or list, return. 365 | If there are more than 1 object or list, return the best scoring. 366 | """ 367 | 368 | if voted_result.shape[0] == 1: 369 | logger.debug("Voted result is singular") 370 | 371 | tmp_result = voted_result[0] 372 | answer = [] 373 | if type(tmp_result) == ResultRow: 374 | answer += [tmp_result] 375 | 376 | elif type(tmp_result) == list: 377 | # Make sure all in the list is not imposters 378 | tmp_answer = [result for result in tmp_result] 379 | # Add as answer if all within the list follows if argument 380 | answer += [tmp_answer] if len( 381 | tmp_answer) == len(tmp_result) else [] 382 | 383 | elif voted_result.shape[0] > 1: 384 | logger.debug("Voted result is non-singular") 385 | 386 | tmp_result = voted_result 387 | try: 388 | x = tmp_result[0][0] 389 | tmp_result = tmp_result[0] 390 | except: 391 | tmp_result = tmp_result 392 | #max_score = max([result.score for result in tmp_result]) 393 | max_score = max([result.score for result in tmp_result]) 394 | answer = [] 395 | for result in tmp_result: 396 | #answer += [result] if result.score == max_score else [] 397 | answer += [result] if result.score == max_score else [] 398 | 399 | return answer 400 | 401 | """ 402 | Determine which cluster(s) is the best to return as answer, 403 | while returning the remaining clusters as possible imposters. 404 | """ 405 | 406 | votes = np.array([[item[0], item[1]] for item in self.best_in_clusters], dtype=object) 407 | votes_sorted = sorted(set(votes[:, 0]), reverse=True) 408 | logical_result = [] 409 | 410 | while logical_result == [] and len(votes_sorted) > 0: 411 | voted_result = votes[votes[:, 0] == votes_sorted.pop(0), 1] 412 | logical_result = process_answer_logic(voted_result) 413 | 414 | logger.debug("Votes remaining = {}".format(len(votes_sorted))) 415 | 416 | if logical_result == []: 417 | logger.debug("Move to ignore emm-like filter") 418 | 419 | votes = np.array([[item[0], item[1]] 420 | for item in self.best_in_clusters], dtype=object) 421 | votes_sorted = sorted(set(votes[:, 0]), reverse=True) 422 | 423 | while logical_result == [] and len(votes_sorted) > 0: 424 | voted_result = votes[votes[:, 0] == votes_sorted.pop(0), 1] 425 | logical_result = process_answer_absurd(voted_result) 426 | 427 | logger.debug("Votes remaining = {}".format(len(votes_sorted))) 428 | 429 | logger.debug( 430 | "This is illogical, but answer is = {}".format(logical_result)) 431 | 432 | logger.debug("The answer would be {}".format(logical_result)) 433 | 434 | self.answers = logical_result 435 | self.possible_imposters = votes[~is_in(votes[:, 1], self.answers), 1] 436 | 437 | def __call__(self): 438 | if len(self.results) > 0: 439 | self.best_in_clusters = [] 440 | 441 | for i in set( 442 | [result.positions[0] for result in self.results] 443 | ): # For every contig 444 | contig_best = self.best_in_cluster_in_contig(i) 445 | 446 | self.best_in_clusters.extend(contig_best) 447 | 448 | self.cluster_number += len(contig_best) 449 | self.ascii_vis += "\t" + self.map_stringer(contig_best) 450 | 451 | # Now get final answer 452 | self.classify_expected_answer() 453 | 454 | else: 455 | self.answers = [nullResult] 456 | self.possible_imposters = [nullResult] 457 | 458 | final_result = self.produce_final_result() 459 | 460 | if self.output_stream in [None, "None", "stdout"]: 461 | print(final_result) 462 | else: 463 | with open(self.output_stream, "a") as handle: 464 | handle.write(final_result + "\n") 465 | 466 | return final_result 467 | -------------------------------------------------------------------------------- /Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "f2a5d05bf8bba424aec64f96bcc585fe7fd348c4e9331807daab148fd6d50063" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": {}, 8 | "sources": [ 9 | { 10 | "name": "pypi", 11 | "url": "https://pypi.org/simple", 12 | "verify_ssl": true 13 | } 14 | ] 15 | }, 16 | "default": { 17 | "click": { 18 | "hashes": [ 19 | "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", 20 | "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" 21 | ], 22 | "index": "pypi", 23 | "version": "==7.0" 24 | }, 25 | "e1839a8": { 26 | "editable": true, 27 | "path": "." 28 | }, 29 | "numpy": { 30 | "hashes": [ 31 | "sha256:03f2ebcbffcce2dec8860633b89a93e80c6a239d21a77ae8b241450dc21e8c35", 32 | "sha256:078c8025da5ab9e8657edc9c2a1e9642e06e953bc7baa2e65c1aa9d9dfb7e98b", 33 | "sha256:0fbfa98c5d5c3c6489cc1e852ec94395d51f35d9ebe70c6850e47f465038cdf4", 34 | "sha256:1c841033f4fe6801648180c3033c45b3235a8bbd09bc7249010f99ea27bb6790", 35 | "sha256:2c0984a01ddd0aeec89f0ce46ef21d64761048cd76c0074d0658c91f9131f154", 36 | "sha256:4c166dcb0fff7cb3c0bbc682dfb5061852a2547efb6222e043a7932828c08fb5", 37 | "sha256:8c2d98d0623bd63fb883b65256c00454d5f53127a5a7bcdaa8bdc582814e8cb4", 38 | "sha256:8cb4b6ae45aad6d26712a1ce0a3f2556c5e1484867f9649e03496e45d6a5eba4", 39 | "sha256:93050e73c446c82065b7410221b07682e475ac51887cd9368227a5d944afae80", 40 | "sha256:a3f6b3024f8826d8b1490e6e2a9b99e841cd2c375791b1df62991bd8f4c00b89", 41 | "sha256:bede70fd8699695363f39e86c1e869b2c8b74fb5ef135a67b9e1eeebff50322a", 42 | "sha256:c304b2221f33489cd15a915237a84cdfe9420d7e4d4828c78a0820f9d990395c", 43 | "sha256:f11331530f0eff69a758d62c2461cd98cdc2eae0147279d8fc86e0464eb7e8ca", 44 | "sha256:fa5f2a8ef1e07ba258dc07d4dd246de23ef4ab920ae0f3fa2a1cc5e90f0f1888", 45 | "sha256:fb6178b0488b0ce6a54bc4accbdf5225e937383586555604155d64773f6beb2b", 46 | "sha256:fd5e830d4dc31658d61a6452cd3e842213594d8c15578cdae6829e36ad9c0930" 47 | ], 48 | "version": "==1.17.1" 49 | }, 50 | "python-dateutil": { 51 | "hashes": [ 52 | "sha256:7e6584c74aeed623791615e26efd690f29817a27c73085b78e4bad02493df2fb", 53 | "sha256:c89805f6f4d64db21ed966fda138f8a5ed7a4fdbc1a8ee329ce1b74e3c74da9e" 54 | ], 55 | "index": "pypi", 56 | "version": "==2.8.0" 57 | }, 58 | "scipy": { 59 | "hashes": [ 60 | "sha256:0baa64bf42592032f6f6445a07144e355ca876b177f47ad8d0612901c9375bef", 61 | "sha256:243b04730d7223d2b844bda9500310eecc9eda0cba9ceaf0cde1839f8287dfa8", 62 | "sha256:2643cfb46d97b7797d1dbdb6f3c23fe3402904e3c90e6facfe6a9b98d808c1b5", 63 | "sha256:396eb4cdad421f846a1498299474f0a3752921229388f91f60dc3eda55a00488", 64 | "sha256:3ae3692616975d3c10aca6d574d6b4ff95568768d4525f76222fb60f142075b9", 65 | "sha256:435d19f80b4dcf67dc090cc04fde2c5c8a70b3372e64f6a9c58c5b806abfa5a8", 66 | "sha256:46a5e55850cfe02332998b3aef481d33f1efee1960fe6cfee0202c7dd6fc21ab", 67 | "sha256:75b513c462e58eeca82b22fc00f0d1875a37b12913eee9d979233349fce5c8b2", 68 | "sha256:7ccfa44a08226825126c4ef0027aa46a38c928a10f0a8a8483c80dd9f9a0ad44", 69 | "sha256:89dd6a6d329e3f693d1204d5562dd63af0fd7a17854ced17f9cbc37d5b853c8d", 70 | "sha256:a81da2fe32f4eab8b60d56ad43e44d93d392da228a77e229e59b51508a00299c", 71 | "sha256:a9d606d11eb2eec7ef893eb825017fbb6eef1e1d0b98a5b7fc11446ebeb2b9b1", 72 | "sha256:ac37eb652248e2d7cbbfd89619dce5ecfd27d657e714ed049d82f19b162e8d45", 73 | "sha256:cbc0611699e420774e945f6a4e2830f7ca2b3ee3483fca1aa659100049487dd5", 74 | "sha256:d02d813ec9958ed63b390ded463163685af6025cb2e9a226ec2c477df90c6957", 75 | "sha256:dd3b52e00f93fd1c86f2d78243dfb0d02743c94dd1d34ffea10055438e63b99d" 76 | ], 77 | "version": "==1.3.1" 78 | }, 79 | "six": { 80 | "hashes": [ 81 | "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", 82 | "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" 83 | ], 84 | "version": "==1.12.0" 85 | } 86 | }, 87 | "develop": { 88 | "aspy.yaml": { 89 | "hashes": [ 90 | "sha256:463372c043f70160a9ec950c3f1e4c3a82db5fca01d334b6bc89c7164d744bdc", 91 | "sha256:e7c742382eff2caed61f87a39d13f99109088e5e93f04d76eb8d4b28aa143f45" 92 | ], 93 | "version": "==1.3.0" 94 | }, 95 | "atomicwrites": { 96 | "hashes": [ 97 | "sha256:03472c30eb2c5d1ba9227e4c2ca66ab8287fbfbbda3888aa93dc2e28fc6811b4", 98 | "sha256:75a9445bac02d8d058d5e1fe689654ba5a6556a1dfd8ce6ec55a0ed79866cfa6" 99 | ], 100 | "version": "==1.3.0" 101 | }, 102 | "attrs": { 103 | "hashes": [ 104 | "sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79", 105 | "sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399" 106 | ], 107 | "version": "==19.1.0" 108 | }, 109 | "bleach": { 110 | "hashes": [ 111 | "sha256:213336e49e102af26d9cde77dd2d0397afabc5a6bf2fed985dc35b5d1e285a16", 112 | "sha256:3fdf7f77adcf649c9911387df51254b813185e32b2c6619f690b593a617e19fa" 113 | ], 114 | "version": "==3.1.0" 115 | }, 116 | "bumpversion": { 117 | "hashes": [ 118 | "sha256:6744c873dd7aafc24453d8b6a1a0d6d109faf63cd0cd19cb78fd46e74932c77e", 119 | "sha256:6753d9ff3552013e2130f7bc03c1007e24473b4835952679653fb132367bdd57" 120 | ], 121 | "index": "pypi", 122 | "version": "==0.5.3" 123 | }, 124 | "certifi": { 125 | "hashes": [ 126 | "sha256:046832c04d4e752f37383b628bc601a7ea7211496b4638f6514d0e5b9acc4939", 127 | "sha256:945e3ba63a0b9f577b1395204e13c3a231f9bc0223888be653286534e5873695" 128 | ], 129 | "version": "==2019.6.16" 130 | }, 131 | "cfgv": { 132 | "hashes": [ 133 | "sha256:edb387943b665bf9c434f717bf630fa78aecd53d5900d2e05da6ad6048553144", 134 | "sha256:fbd93c9ab0a523bf7daec408f3be2ed99a980e20b2d19b50fc184ca6b820d289" 135 | ], 136 | "version": "==2.0.1" 137 | }, 138 | "chardet": { 139 | "hashes": [ 140 | "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", 141 | "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" 142 | ], 143 | "version": "==3.0.4" 144 | }, 145 | "coverage": { 146 | "hashes": [ 147 | "sha256:08907593569fe59baca0bf152c43f3863201efb6113ecb38ce7e97ce339805a6", 148 | "sha256:0be0f1ed45fc0c185cfd4ecc19a1d6532d72f86a2bac9de7e24541febad72650", 149 | "sha256:141f08ed3c4b1847015e2cd62ec06d35e67a3ac185c26f7635f4406b90afa9c5", 150 | "sha256:19e4df788a0581238e9390c85a7a09af39c7b539b29f25c89209e6c3e371270d", 151 | "sha256:23cc09ed395b03424d1ae30dcc292615c1372bfba7141eb85e11e50efaa6b351", 152 | "sha256:245388cda02af78276b479f299bbf3783ef0a6a6273037d7c60dc73b8d8d7755", 153 | "sha256:331cb5115673a20fb131dadd22f5bcaf7677ef758741312bee4937d71a14b2ef", 154 | "sha256:386e2e4090f0bc5df274e720105c342263423e77ee8826002dcffe0c9533dbca", 155 | "sha256:3a794ce50daee01c74a494919d5ebdc23d58873747fa0e288318728533a3e1ca", 156 | "sha256:60851187677b24c6085248f0a0b9b98d49cba7ecc7ec60ba6b9d2e5574ac1ee9", 157 | "sha256:63a9a5fc43b58735f65ed63d2cf43508f462dc49857da70b8980ad78d41d52fc", 158 | "sha256:6b62544bb68106e3f00b21c8930e83e584fdca005d4fffd29bb39fb3ffa03cb5", 159 | "sha256:6ba744056423ef8d450cf627289166da65903885272055fb4b5e113137cfa14f", 160 | "sha256:7494b0b0274c5072bddbfd5b4a6c6f18fbbe1ab1d22a41e99cd2d00c8f96ecfe", 161 | "sha256:826f32b9547c8091679ff292a82aca9c7b9650f9fda3e2ca6bf2ac905b7ce888", 162 | "sha256:93715dffbcd0678057f947f496484e906bf9509f5c1c38fc9ba3922893cda5f5", 163 | "sha256:9a334d6c83dfeadae576b4d633a71620d40d1c379129d587faa42ee3e2a85cce", 164 | "sha256:af7ed8a8aa6957aac47b4268631fa1df984643f07ef00acd374e456364b373f5", 165 | "sha256:bf0a7aed7f5521c7ca67febd57db473af4762b9622254291fbcbb8cd0ba5e33e", 166 | "sha256:bf1ef9eb901113a9805287e090452c05547578eaab1b62e4ad456fcc049a9b7e", 167 | "sha256:c0afd27bc0e307a1ffc04ca5ec010a290e49e3afbe841c5cafc5c5a80ecd81c9", 168 | "sha256:dd579709a87092c6dbee09d1b7cfa81831040705ffa12a1b248935274aee0437", 169 | "sha256:df6712284b2e44a065097846488f66840445eb987eb81b3cc6e4149e7b6982e1", 170 | "sha256:e07d9f1a23e9e93ab5c62902833bf3e4b1f65502927379148b6622686223125c", 171 | "sha256:e2ede7c1d45e65e209d6093b762e98e8318ddeff95317d07a27a2140b80cfd24", 172 | "sha256:e4ef9c164eb55123c62411f5936b5c2e521b12356037b6e1c2617cef45523d47", 173 | "sha256:eca2b7343524e7ba246cab8ff00cab47a2d6d54ada3b02772e908a45675722e2", 174 | "sha256:eee64c616adeff7db37cc37da4180a3a5b6177f5c46b187894e633f088fb5b28", 175 | "sha256:ef824cad1f980d27f26166f86856efe11eff9912c4fed97d3804820d43fa550c", 176 | "sha256:efc89291bd5a08855829a3c522df16d856455297cf35ae827a37edac45f466a7", 177 | "sha256:fa964bae817babece5aa2e8c1af841bebb6d0b9add8e637548809d040443fee0", 178 | "sha256:ff37757e068ae606659c28c3bd0d923f9d29a85de79bf25b2b34b148473b5025" 179 | ], 180 | "version": "==4.5.4" 181 | }, 182 | "coveralls": { 183 | "hashes": [ 184 | "sha256:9bc5a1f92682eef59f688a8f280207190d9a6afb84cef8f567fa47631a784060", 185 | "sha256:fb51cddef4bc458de347274116df15d641a735d3f0a580a9472174e2e62f408c" 186 | ], 187 | "index": "pypi", 188 | "version": "==1.8.2" 189 | }, 190 | "docopt": { 191 | "hashes": [ 192 | "sha256:49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491" 193 | ], 194 | "version": "==0.6.2" 195 | }, 196 | "docutils": { 197 | "hashes": [ 198 | "sha256:6c4f696463b79f1fb8ba0c594b63840ebd41f059e92b31957c46b74a4599b6d0", 199 | "sha256:9e4d7ecfc600058e07ba661411a2b7de2fd0fafa17d1a7f7361cd47b1175c827", 200 | "sha256:a2aeea129088da402665e92e0b25b04b073c04b2dce4ab65caaa38b7ce2e1a99" 201 | ], 202 | "version": "==0.15.2" 203 | }, 204 | "identify": { 205 | "hashes": [ 206 | "sha256:4f1fe9a59df4e80fcb0213086fcf502bc1765a01ea4fe8be48da3b65afd2a017", 207 | "sha256:d8919589bd2a5f99c66302fec0ef9027b12ae150b0b0213999ad3f695fc7296e" 208 | ], 209 | "version": "==1.4.7" 210 | }, 211 | "idna": { 212 | "hashes": [ 213 | "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", 214 | "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" 215 | ], 216 | "version": "==2.8" 217 | }, 218 | "importlib-metadata": { 219 | "hashes": [ 220 | "sha256:9ff1b1c5a354142de080b8a4e9803e5d0d59283c93aed808617c787d16768375", 221 | "sha256:b7143592e374e50584564794fcb8aaf00a23025f9db866627f89a21491847a8d" 222 | ], 223 | "markers": "python_version < '3.8'", 224 | "version": "==0.20" 225 | }, 226 | "invoke": { 227 | "hashes": [ 228 | "sha256:c52274d2e8a6d64ef0d61093e1983268ea1fc0cd13facb9448c4ef0c9a7ac7da", 229 | "sha256:f4ec8a134c0122ea042c8912529f87652445d9f4de590b353d23f95bfa1f0efd", 230 | "sha256:fc803a5c9052f15e63310aa81a43498d7c55542beb18564db88a9d75a176fa44" 231 | ], 232 | "index": "pypi", 233 | "version": "==1.3.0" 234 | }, 235 | "more-itertools": { 236 | "hashes": [ 237 | "sha256:409cd48d4db7052af495b09dec721011634af3753ae1ef92d2b32f73a745f832", 238 | "sha256:92b8c4b06dac4f0611c0729b2f2ede52b2e1bac1ab48f089c7ddc12e26bb60c4" 239 | ], 240 | "version": "==7.2.0" 241 | }, 242 | "nodeenv": { 243 | "hashes": [ 244 | "sha256:ad8259494cf1c9034539f6cced78a1da4840a4b157e23640bc4a0c0546b0cb7a" 245 | ], 246 | "version": "==1.3.3" 247 | }, 248 | "packaging": { 249 | "hashes": [ 250 | "sha256:a7ac867b97fdc07ee80a8058fe4435ccd274ecc3b0ed61d852d7d53055528cf9", 251 | "sha256:c491ca87294da7cc01902edbe30a5bc6c4c28172b5138ab4e4aa1b9d7bfaeafe" 252 | ], 253 | "version": "==19.1" 254 | }, 255 | "pkginfo": { 256 | "hashes": [ 257 | "sha256:7424f2c8511c186cd5424bbf31045b77435b37a8d604990b79d4e70d741148bb", 258 | "sha256:a6d9e40ca61ad3ebd0b72fbadd4fba16e4c0e4df0428c041e01e06eb6ee71f32" 259 | ], 260 | "version": "==1.5.0.1" 261 | }, 262 | "pluggy": { 263 | "hashes": [ 264 | "sha256:0825a152ac059776623854c1543d65a4ad408eb3d33ee114dff91e57ec6ae6fc", 265 | "sha256:b9817417e95936bf75d85d3f8767f7df6cdde751fc40aed3bb3074cbcb77757c" 266 | ], 267 | "version": "==0.12.0" 268 | }, 269 | "pre-commit": { 270 | "hashes": [ 271 | "sha256:1d3c0587bda7c4e537a46c27f2c84aa006acc18facf9970bf947df596ce91f3f", 272 | "sha256:fa78ff96e8e9ac94c748388597693f18b041a181c94a4f039ad20f45287ba44a" 273 | ], 274 | "index": "pypi", 275 | "version": "==1.18.3" 276 | }, 277 | "py": { 278 | "hashes": [ 279 | "sha256:64f65755aee5b381cea27766a3a147c3f15b9b6b9ac88676de66ba2ae36793fa", 280 | "sha256:dc639b046a6e2cff5bbe40194ad65936d6ba360b52b3c3fe1d08a82dd50b5e53" 281 | ], 282 | "version": "==1.8.0" 283 | }, 284 | "pygments": { 285 | "hashes": [ 286 | "sha256:71e430bc85c88a430f000ac1d9b331d2407f681d6f6aec95e8bcfbc3df5b0127", 287 | "sha256:881c4c157e45f30af185c1ffe8d549d48ac9127433f2c380c24b84572ad66297" 288 | ], 289 | "version": "==2.4.2" 290 | }, 291 | "pyparsing": { 292 | "hashes": [ 293 | "sha256:6f98a7b9397e206d78cc01df10131398f1c8b8510a2f4d97d9abd82e1aacdd80", 294 | "sha256:d9338df12903bbf5d65a0e4e87c2161968b10d2e489652bb47001d82a9b028b4" 295 | ], 296 | "version": "==2.4.2" 297 | }, 298 | "pytest": { 299 | "hashes": [ 300 | "sha256:95d13143cc14174ca1a01ec68e84d76ba5d9d493ac02716fd9706c949a505210", 301 | "sha256:b78fe2881323bd44fd9bd76e5317173d4316577e7b1cddebae9136a4495ec865" 302 | ], 303 | "index": "pypi", 304 | "version": "==5.1.2" 305 | }, 306 | "pytest-cov": { 307 | "hashes": [ 308 | "sha256:2b097cde81a302e1047331b48cadacf23577e431b61e9c6f49a1170bbe3d3da6", 309 | "sha256:e00ea4fdde970725482f1f35630d12f074e121a23801aabf2ae154ec6bdd343a" 310 | ], 311 | "index": "pypi", 312 | "version": "==2.7.1" 313 | }, 314 | "pyyaml": { 315 | "hashes": [ 316 | "sha256:0113bc0ec2ad727182326b61326afa3d1d8280ae1122493553fd6f4397f33df9", 317 | "sha256:01adf0b6c6f61bd11af6e10ca52b7d4057dd0be0343eb9283c878cf3af56aee4", 318 | "sha256:5124373960b0b3f4aa7df1707e63e9f109b5263eca5976c66e08b1c552d4eaf8", 319 | "sha256:5ca4f10adbddae56d824b2c09668e91219bb178a1eee1faa56af6f99f11bf696", 320 | "sha256:7907be34ffa3c5a32b60b95f4d95ea25361c951383a894fec31be7252b2b6f34", 321 | "sha256:7ec9b2a4ed5cad025c2278a1e6a19c011c80a3caaac804fd2d329e9cc2c287c9", 322 | "sha256:87ae4c829bb25b9fe99cf71fbb2140c448f534e24c998cc60f39ae4f94396a73", 323 | "sha256:9de9919becc9cc2ff03637872a440195ac4241c80536632fffeb6a1e25a74299", 324 | "sha256:a5a85b10e450c66b49f98846937e8cfca1db3127a9d5d1e31ca45c3d0bef4c5b", 325 | "sha256:b0997827b4f6a7c286c01c5f60384d218dca4ed7d9efa945c3e1aa623d5709ae", 326 | "sha256:b631ef96d3222e62861443cc89d6563ba3eeb816eeb96b2629345ab795e53681", 327 | "sha256:bf47c0607522fdbca6c9e817a6e81b08491de50f3766a7a0e6a5be7905961b41", 328 | "sha256:f81025eddd0327c7d4cfe9b62cf33190e1e736cc6e97502b3ec425f574b3e7a8" 329 | ], 330 | "version": "==5.1.2" 331 | }, 332 | "readme-renderer": { 333 | "hashes": [ 334 | "sha256:bb16f55b259f27f75f640acf5e00cf897845a8b3e4731b5c1a436e4b8529202f", 335 | "sha256:c8532b79afc0375a85f10433eca157d6b50f7d6990f337fa498c96cd4bfc203d" 336 | ], 337 | "version": "==24.0" 338 | }, 339 | "requests": { 340 | "hashes": [ 341 | "sha256:11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4", 342 | "sha256:9cf5292fcd0f598c671cfc1e0d7d1a7f13bb8085e9a590f48c010551dc6c4b31" 343 | ], 344 | "version": "==2.22.0" 345 | }, 346 | "requests-toolbelt": { 347 | "hashes": [ 348 | "sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f", 349 | "sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0" 350 | ], 351 | "version": "==0.9.1" 352 | }, 353 | "six": { 354 | "hashes": [ 355 | "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c", 356 | "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" 357 | ], 358 | "version": "==1.12.0" 359 | }, 360 | "toml": { 361 | "hashes": [ 362 | "sha256:229f81c57791a41d65e399fc06bf0848bab550a9dfd5ed66df18ce5f05e73d5c", 363 | "sha256:235682dd292d5899d361a811df37e04a8828a5b1da3115886b73cf81ebc9100e" 364 | ], 365 | "version": "==0.10.0" 366 | }, 367 | "tqdm": { 368 | "hashes": [ 369 | "sha256:1be3e4e3198f2d0e47b928e9d9a8ec1b63525db29095cec1467f4c5a4ea8ebf9", 370 | "sha256:7e39a30e3d34a7a6539378e39d7490326253b7ee354878a92255656dc4284457" 371 | ], 372 | "version": "==4.35.0" 373 | }, 374 | "twine": { 375 | "hashes": [ 376 | "sha256:0fb0bfa3df4f62076cab5def36b1a71a2e4acb4d1fa5c97475b048117b1a6446", 377 | "sha256:d6c29c933ecfc74e9b1d9fa13aa1f87c5d5770e119f5a4ce032092f0ff5b14dc" 378 | ], 379 | "index": "pypi", 380 | "version": "==1.13.0" 381 | }, 382 | "urllib3": { 383 | "hashes": [ 384 | "sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1", 385 | "sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232" 386 | ], 387 | "version": "==1.25.3" 388 | }, 389 | "virtualenv": { 390 | "hashes": [ 391 | "sha256:680af46846662bb38c5504b78bad9ed9e4f3ba2d54f54ba42494fdf94337fe30", 392 | "sha256:f78d81b62d3147396ac33fc9d77579ddc42cc2a98dd9ea38886f616b33bc7fb2" 393 | ], 394 | "version": "==16.7.5" 395 | }, 396 | "wcwidth": { 397 | "hashes": [ 398 | "sha256:3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e", 399 | "sha256:f4ebe71925af7b40a864553f761ed559b43544f8f71746c2d756c7fe788ade7c" 400 | ], 401 | "version": "==0.1.7" 402 | }, 403 | "webencodings": { 404 | "hashes": [ 405 | "sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78", 406 | "sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923" 407 | ], 408 | "version": "==0.5.1" 409 | }, 410 | "zipp": { 411 | "hashes": [ 412 | "sha256:3718b1cbcd963c7d4c5511a8240812904164b7f381b647143a89d3b98f9bcd8e", 413 | "sha256:f06903e9f1f43b12d371004b4ac7b06ab39a44adc747266928ae6debfa7b3335" 414 | ], 415 | "version": "==0.6.0" 416 | } 417 | } 418 | } 419 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------