[
  {
    "path": ".gitignore",
    "content": "!*.md\n!*.py\n!*install\n!lib/*\n!data/\n!example/*\nexample/*.stats.txt\nexample/a*\nexample/test*\n.DS_Store\n!setup*\n!requirements.txt\n!blobtools\n!MANIFEST.in\ndata/n*\nsamtools/\n*.pyc\n*.gz\n*.fq\n*.png\n!blobplot.png\n*.sam\n\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM continuumio/miniconda3\nMAINTAINER Nick Waters <nickp60@gmail.com>\nRUN conda install -c anaconda matplotlib docopt tqdm wget pyyaml git\nRUN conda install -c bioconda pysam --update-deps\nRUN git clone https://github.com/DRL/blobtools.git\nWORKDIR blobtools\n\nRUN ./blobtools -h\n# RUN ./blobtools create -i example/assembly.fna -b example/mapping_1.bam -t example/blast.out -o example/test\nRUN wget ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz -P data/\nRUN tar zxf data/taxdump.tar.gz -C data/ nodes.dmp names.dmp\nRUN ./blobtools nodesdb --nodes data/nodes.dmp --names data/names.dmp\n"
  },
  {
    "path": "LICENSE.md",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.md\ninclude requirements.txt"
  },
  {
    "path": "README.md",
    "content": "BlobTools v1.1\n===============================\nA modular command-line solution for visualisation, quality control and taxonomic partitioning of genome datasets\n\n- Discussions, questions and answers: [BlobTools GoogleGroup](https://groups.google.com/forum/#!forum/blobtools)\n- Issues, bug reports and feature requests: [GitHub issues](https://github.com/DRL/blobtools/issues)\n- Documentation: [blobtools.readme.io](https://blobtools.readme.io)\n- Citation: [Laetsch DR and Blaxter ML, 2017](https://f1000research.com/articles/6-1287/v1)\n\n![](https://github.com/DRL/blobtools/blob/master/example/blobplot.png)\n\nObtaining BlobTools\n------------\n- **Option A**: Download latest [release](https://github.com/DRL/blobtools/releases/latest)\n- **Option B**: Clone repository\n  ```\n  git clone https://github.com/DRL/blobtools.git\n  ```\n\nEnter directory\n------------\n  ```\n  cd blobtools\n  ```\n\nInstall dependencies\n------------\n- Create [Conda](https://conda.io/en/latest/miniconda.html) environment and install dependencies\n\n  ```\n  conda create -n blobtools\n  conda activate blobtools\n  conda install -c anaconda -c bioconda matplotlib docopt tqdm wget pyyaml git pysam\n  ```\n  \nDownload NCBI taxdump and create nodesdb\n------------\n  ```\n  wget ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz -P data/\n  tar zxf data/taxdump.tar.gz -C data/ nodes.dmp names.dmp\n  ./blobtools nodesdb --nodes data/nodes.dmp --names data/names.dmp\n  ```\n\nCreate blobplot\n------------\n  ```\n  ./blobtools create -i example/assembly.fna -b example/mapping_1.sorted.bam -t example/blast.out -o example/test && \\\n  ./blobtools view -i example/test.blobDB.json && \\\n  ./blobtools plot -i example/test.blobDB.json\n  ```\nUsage\n-----\n```\n    ./blobtools --help\n```\n\nDocker\n------\n\nA docker container can be build using the following command:\n```\n     docker build -t drl/blobtools .\n```\nThis docker image can be run with sample data as follows:\n```\n     docker run -v $PWD/example:/example/  -t  drl/blobtools ./blobtools create -i /example/assembly.fna -b /example/mapping_1.sorted.bam -t /example/blast.out -o /example/test\n```\n"
  },
  {
    "path": "__init__.py",
    "content": ""
  },
  {
    "path": "blobtools",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom lib.interface import main\n\nif __name__ == '__main__':\n    main()"
  },
  {
    "path": "data/__init__.py",
    "content": ""
  },
  {
    "path": "example/blast.out",
    "content": "contig_1    979556  200\ncontig_2    979556  500\ncontig_2    979556  1000\ncontig_2    979556  500\ncontig_2    979556  300\ncontig_3    979556  10000\ncontig_4    979556  1000\ncontig_5    6252    2000\ncontig_6    232323  2000\ncontig_6    6252    2000\ncontig_6    979556  2000\ncontig_6    232323  2000\ncontig_7    6252    2000\ncontig_8    6252    2000\ncontig_8    979556  2000\ncontig_9    6252    200\n"
  },
  {
    "path": "example/blobDB.json",
    "content": "{\"tax_collision_random\": false, \"min_score\": 0.0, \"nodesDB_f\": \"/Users/dom/git/blobtools/data/nodesDB.txt\", \"title\": \"blobDB.json\", \"lineages\": {\"6252\": {\"superkingdom\": \"Eukaryota\", \"family\": \"Ascarididae\", \"order\": \"Ascaridida\", \"phylum\": \"Nematoda\", \"genus\": \"Ascaris\", \"species\": \"Ascaris lumbricoides\"}, \"232323\": {\"superkingdom\": \"Eukaryota\", \"family\": \"Hypsibiidae\", \"order\": \"Parachela\", \"phylum\": \"Tardigrada\", \"genus\": \"Hypsibius\", \"species\": \"Hypsibius dujardini\"}, \"979556\": {\"superkingdom\": \"Bacteria\", \"family\": \"Microbacteriaceae\", \"order\": \"Micrococcales\", \"phylum\": \"Actinobacteria\", \"genus\": \"Microbacterium\", \"species\": \"Microbacterium testaceum\"}}, \"taxrules\": [\"bestsum\"], \"hitLibs\": {\"tax0\": {\"fmt\": \"tax\", \"name\": \"tax0\", \"f\": \"/Users/dom/git/blobtools/example/blast.out\"}}, \"length\": 18477, \"version\": \"blobtools v1.0\", \"n_count\": 0, \"order_of_blobs\": [\"contig_1\", \"contig_2\", \"contig_3\", \"contig_4\", \"contig_5\", \"contig_6\", \"contig_7\", \"contig_8\", \"contig_9\", \"contig_10\"], \"seqs\": 10, \"min_diff\": 0.0, \"dict_of_blobs\": {\"contig_10\": {\"hits\": {}, \"name\": \"contig_10\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}, \"family\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}, \"order\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}, \"phylum\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}, \"genus\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}, \"species\": {\"score\": 0.0, \"tax\": \"no-hit\", \"c_index\": 0}}}, \"agct_count\": 6273, \"length\": 6273, \"gc\": 0.3067, \"n_count\": 0, \"covs\": {\"cov0\": 310.634}, \"read_cov\": {\"cov0\": 8741}}, \"contig_9\": {\"hits\": {\"tax0\": [{\"score\": 200.0, \"name\": \"contig_9\", \"taxId\": \"6252\"}]}, \"name\": \"contig_9\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 200.0, \"tax\": \"Eukaryota\", \"c_index\": 0}, \"family\": {\"score\": 200.0, \"tax\": \"Ascarididae\", \"c_index\": 0}, \"order\": {\"score\": 200.0, \"tax\": \"Ascaridida\", \"c_index\": 0}, \"phylum\": {\"score\": 200.0, \"tax\": \"Nematoda\", \"c_index\": 0}, \"genus\": {\"score\": 200.0, \"tax\": \"Ascaris\", \"c_index\": 0}, \"species\": {\"score\": 200.0, \"tax\": \"Ascaris lumbricoides\", \"c_index\": 0}}}, \"agct_count\": 1599, \"length\": 1599, \"gc\": 0.2439, \"n_count\": 0, \"covs\": {\"cov0\": 74.757}, \"read_cov\": {\"cov0\": 554}}, \"contig_8\": {\"hits\": {\"tax0\": [{\"score\": 2000.0, \"name\": \"contig_8\", \"taxId\": \"6252\"}, {\"score\": 2000.0, \"name\": \"contig_8\", \"taxId\": \"979556\"}]}, \"name\": \"contig_8\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}, \"family\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}, \"order\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}, \"phylum\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}, \"genus\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}, \"species\": {\"score\": 2000.0, \"tax\": \"unresolved\", \"c_index\": 1}}}, \"agct_count\": 2346, \"length\": 2346, \"gc\": 0.2801, \"n_count\": 0, \"covs\": {\"cov0\": 91.742}, \"read_cov\": {\"cov0\": 1008}}, \"contig_1\": {\"hits\": {\"tax0\": [{\"score\": 200.0, \"name\": \"contig_1\", \"taxId\": \"979556\"}]}, \"name\": \"contig_1\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 200.0, \"tax\": \"Bacteria\", \"c_index\": 0}, \"family\": {\"score\": 200.0, \"tax\": \"Microbacteriaceae\", \"c_index\": 0}, \"order\": {\"score\": 200.0, \"tax\": \"Micrococcales\", \"c_index\": 0}, \"phylum\": {\"score\": 200.0, \"tax\": \"Actinobacteria\", \"c_index\": 0}, \"genus\": {\"score\": 200.0, \"tax\": \"Microbacterium\", \"c_index\": 0}, \"species\": {\"score\": 200.0, \"tax\": \"Microbacterium testaceum\", \"c_index\": 0}}}, \"agct_count\": 756, \"length\": 756, \"gc\": 0.2606, \"n_count\": 0, \"covs\": {\"cov0\": 90.406}, \"read_cov\": {\"cov0\": 369}}, \"contig_3\": {\"hits\": {\"tax0\": [{\"score\": 10000.0, \"name\": \"contig_3\", \"taxId\": \"979556\"}]}, \"name\": \"contig_3\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 10000.0, \"tax\": \"Bacteria\", \"c_index\": 0}, \"family\": {\"score\": 10000.0, \"tax\": \"Microbacteriaceae\", \"c_index\": 0}, \"order\": {\"score\": 10000.0, \"tax\": \"Micrococcales\", \"c_index\": 0}, \"phylum\": {\"score\": 10000.0, \"tax\": \"Actinobacteria\", \"c_index\": 0}, \"genus\": {\"score\": 10000.0, \"tax\": \"Microbacterium\", \"c_index\": 0}, \"species\": {\"score\": 10000.0, \"tax\": \"Microbacterium testaceum\", \"c_index\": 0}}}, \"agct_count\": 602, \"length\": 602, \"gc\": 0.2342, \"n_count\": 0, \"covs\": {\"cov0\": 43.761}, \"read_cov\": {\"cov0\": 188}}, \"contig_2\": {\"hits\": {\"tax0\": [{\"score\": 500.0, \"name\": \"contig_2\", \"taxId\": \"979556\"}, {\"score\": 1000.0, \"name\": \"contig_2\", \"taxId\": \"979556\"}, {\"score\": 500.0, \"name\": \"contig_2\", \"taxId\": \"979556\"}, {\"score\": 300.0, \"name\": \"contig_2\", \"taxId\": \"979556\"}]}, \"name\": \"contig_2\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 2300.0, \"tax\": \"Bacteria\", \"c_index\": 0}, \"family\": {\"score\": 2300.0, \"tax\": \"Microbacteriaceae\", \"c_index\": 0}, \"order\": {\"score\": 2300.0, \"tax\": \"Micrococcales\", \"c_index\": 0}, \"phylum\": {\"score\": 2300.0, \"tax\": \"Actinobacteria\", \"c_index\": 0}, \"genus\": {\"score\": 2300.0, \"tax\": \"Microbacterium\", \"c_index\": 0}, \"species\": {\"score\": 2300.0, \"tax\": \"Microbacterium testaceum\", \"c_index\": 0}}}, \"agct_count\": 1060, \"length\": 1060, \"gc\": 0.2623, \"n_count\": 0, \"covs\": {\"cov0\": 168.409}, \"read_cov\": {\"cov0\": 844}}, \"contig_5\": {\"hits\": {\"tax0\": [{\"score\": 2000.0, \"name\": \"contig_5\", \"taxId\": \"6252\"}]}, \"name\": \"contig_5\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 2000.0, \"tax\": \"Eukaryota\", \"c_index\": 0}, \"family\": {\"score\": 2000.0, \"tax\": \"Ascarididae\", \"c_index\": 0}, \"order\": {\"score\": 2000.0, \"tax\": \"Ascaridida\", \"c_index\": 0}, \"phylum\": {\"score\": 2000.0, \"tax\": \"Nematoda\", \"c_index\": 0}, \"genus\": {\"score\": 2000.0, \"tax\": \"Ascaris\", \"c_index\": 0}, \"species\": {\"score\": 2000.0, \"tax\": \"Ascaris lumbricoides\", \"c_index\": 0}}}, \"agct_count\": 614, \"length\": 614, \"gc\": 0.329, \"n_count\": 0, \"covs\": {\"cov0\": 163.557}, \"read_cov\": {\"cov0\": 456}}, \"contig_4\": {\"hits\": {\"tax0\": [{\"score\": 1000.0, \"name\": \"contig_4\", \"taxId\": \"979556\"}]}, \"name\": \"contig_4\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 1000.0, \"tax\": \"Bacteria\", \"c_index\": 0}, \"family\": {\"score\": 1000.0, \"tax\": \"Microbacteriaceae\", \"c_index\": 0}, \"order\": {\"score\": 1000.0, \"tax\": \"Micrococcales\", \"c_index\": 0}, \"phylum\": {\"score\": 1000.0, \"tax\": \"Actinobacteria\", \"c_index\": 0}, \"genus\": {\"score\": 1000.0, \"tax\": \"Microbacterium\", \"c_index\": 0}, \"species\": {\"score\": 1000.0, \"tax\": \"Microbacterium testaceum\", \"c_index\": 0}}}, \"agct_count\": 951, \"length\": 951, \"gc\": 0.3155, \"n_count\": 0, \"covs\": {\"cov0\": 456.313}, \"read_cov\": {\"cov0\": 2096}}, \"contig_7\": {\"hits\": {\"tax0\": [{\"score\": 2000.0, \"name\": \"contig_7\", \"taxId\": \"6252\"}]}, \"name\": \"contig_7\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 2000.0, \"tax\": \"Eukaryota\", \"c_index\": 0}, \"family\": {\"score\": 2000.0, \"tax\": \"Ascarididae\", \"c_index\": 0}, \"order\": {\"score\": 2000.0, \"tax\": \"Ascaridida\", \"c_index\": 0}, \"phylum\": {\"score\": 2000.0, \"tax\": \"Nematoda\", \"c_index\": 0}, \"genus\": {\"score\": 2000.0, \"tax\": \"Ascaris\", \"c_index\": 0}, \"species\": {\"score\": 2000.0, \"tax\": \"Ascaris lumbricoides\", \"c_index\": 0}}}, \"agct_count\": 4060, \"length\": 4060, \"gc\": 0.2584, \"n_count\": 0, \"covs\": {\"cov0\": 52.312}, \"read_cov\": {\"cov0\": 1005}}, \"contig_6\": {\"hits\": {\"tax0\": [{\"score\": 2000.0, \"name\": \"contig_6\", \"taxId\": \"232323\"}, {\"score\": 2000.0, \"name\": \"contig_6\", \"taxId\": \"6252\"}, {\"score\": 2000.0, \"name\": \"contig_6\", \"taxId\": \"979556\"}, {\"score\": 2000.0, \"name\": \"contig_6\", \"taxId\": \"232323\"}]}, \"name\": \"contig_6\", \"taxonomy\": {\"bestsum\": {\"superkingdom\": {\"score\": 6000.0, \"tax\": \"Eukaryota\", \"c_index\": 1}, \"family\": {\"score\": 4000.0, \"tax\": \"Hypsibiidae\", \"c_index\": 2}, \"order\": {\"score\": 4000.0, \"tax\": \"Parachela\", \"c_index\": 2}, \"phylum\": {\"score\": 4000.0, \"tax\": \"Tardigrada\", \"c_index\": 2}, \"genus\": {\"score\": 4000.0, \"tax\": \"Hypsibius\", \"c_index\": 2}, \"species\": {\"score\": 4000.0, \"tax\": \"Hypsibius dujardini\", \"c_index\": 2}}}, \"agct_count\": 216, \"length\": 216, \"gc\": 0.1944, \"n_count\": 0, \"covs\": {\"cov0\": 25.88}, \"read_cov\": {\"cov0\": 52}}}, \"assembly_f\": \"/Users/dom/git/blobtools/example/assembly.fna\", \"covLibs\": {\"cov0\": {\"reads_unmapped\": 0, \"mean_cov\": 147.7771, \"cov_sum\": 1477.771, \"name\": \"cov0\", \"f\": \"/Users/dom/git/blobtools/example/mapping_1.bam.cov\", \"fmt\": \"cov\", \"reads_total\": 15313, \"reads_mapped\": 15313}}}"
  },
  {
    "path": "example/blobDB.table.txt",
    "content": "## blobtools v1.0\n## assembly\t: /Users/dom/git/blobtools/example/assembly.fna\n## coverage\t: cov0 - /Users/dom/git/blobtools/example/mapping_1.bam.cov\n## taxonomy\t: tax0 - /Users/dom/git/blobtools/example/blast.out\n## nodesDB\t: /Users/dom/git/blobtools/data/nodesDB.txt\n## taxrule\t: bestsum\n## min_score\t: 0.0\n## min_diff\t: 0.0\n## tax_collision_random\t: False\n##\n# name\tlength\tGC\tN\tcov0\tphylum.t.6\tphylum.s.7\tphylum.c.8\ncontig_1\t756\t0.2606\t0\t90.406\tActinobacteria\t200.0\t0\ncontig_2\t1060\t0.2623\t0\t168.409\tActinobacteria\t2300.0\t0\ncontig_3\t602\t0.2342\t0\t43.761\tActinobacteria\t10000.0\t0\ncontig_4\t951\t0.3155\t0\t456.313\tActinobacteria\t1000.0\t0\ncontig_5\t614\t0.329\t0\t163.557\tNematoda\t2000.0\t0\ncontig_6\t216\t0.1944\t0\t25.88\tTardigrada\t4000.0\t2\ncontig_7\t4060\t0.2584\t0\t52.312\tNematoda\t2000.0\t0\ncontig_8\t2346\t0.2801\t0\t91.742\tunresolved\t2000.0\t1\ncontig_9\t1599\t0.2439\t0\t74.757\tNematoda\t200.0\t0\ncontig_10\t6273\t0.3067\t0\t310.634\tno-hit\t0.0\t0"
  },
  {
    "path": "example/catcolour.txt",
    "content": "contig_1,A\ncontig_2,A\ncontig_3,A\ncontig_4,B\ncontig_5,B\ncontig_6,B\ncontig_7,B\ncontig_8,B\ncontig_9,C\ncontig_10,C\n"
  },
  {
    "path": "example/colours.txt",
    "content": "Nematoda,#48a365\nTardigrada,#48a365\nActinobacteria,#926eb3\nother,#ffffff\n"
  },
  {
    "path": "example/diamond.out",
    "content": "contig_1    232323  200\ncontig_2    232323  500\ncontig_2    232323  1000\ncontig_2    232323  500\ncontig_2    979556  300\ncontig_3    979556  10000\ncontig_4    979556  1000\ncontig_5    6252    1000\ncontig_6    232323  1000\ncontig_6    6252    1000\ncontig_6    979556  1000\ncontig_6    232323  1000\ncontig_7    6252    1000\ncontig_9    6252    100\n"
  },
  {
    "path": "example/refcov.txt",
    "content": "cov0,15313,15300\nbam0,15313,15300\ncov1,37278,15300\nbam1,37278,15300\ncovsum,52591,30600 "
  },
  {
    "path": "lib/BtCore.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile        : BtCore.py\nAuthor      : Dominik R. Laetsch, dominik.laetsch at gmail dot com\n\"\"\"\n\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\nimport lib.BtTax as BtTax\nfrom os.path import abspath, isfile, basename, join\nimport re\nfrom collections import defaultdict\nimport sys\nfrom tqdm import tqdm\n\nclass BlobDb():\n    '''\n    class BlobDB holds all information parsed from files\n    '''\n    def __init__(self, title):\n        self.title = title\n        self.assembly_f = ''\n        self.dict_of_blobs = {}\n        self.order_of_blobs = [] # ordereddict\n        self.set_of_taxIds = set()\n        self.lineages = {}\n        self.length = 0\n        self.seqs = 0\n        self.n_count = 0\n        self.covLibs = {}\n        self.hitLibs = {}\n        self.nodesDB_f = ''\n        self.taxrules = []\n        self.version = ''\n        self.view_dir = ''\n        self.min_score = 0.0\n        self.min_diff = 0.0\n        self.tax_collision_random = False\n\n    def view(self, **kwargs):\n        # arguments\n        viewObjs = kwargs['viewObjs']\n        ranks = kwargs['ranks']\n        taxrule = kwargs['taxrule']\n        hits_flag = kwargs['hits_flag']\n        seqs = kwargs['seqs']\n        cov_libs = kwargs['cov_libs']\n        # Default sequences if no subset\n        if not (seqs):\n            seqs = self.order_of_blobs\n        # Default cov_libs if no subset\n        cov_lib_names = cov_libs\n        if not (cov_libs):\n            cov_lib_names = [covLib for covLib in self.covLibs]\n        tax_lib_names = [taxLib for taxLib in sorted(self.hitLibs)]\n        lineages = self.lineages\n        # setup\n\n        for viewObj in viewObjs:\n            #print(\"in view:\", viewObj.name)\n            if viewObj.name == 'table':\n                viewObj.header = self.getTableHeader(taxrule, ranks, hits_flag, cov_lib_names)\n            if viewObj.name == 'concoct_cov':\n                viewObj.header = self.getConcoctCovHeader(cov_lib_names)\n            if viewObj.name == 'covlib':\n                viewObj.header = self.getCovHeader(cov_lib_names)\n            if viewObj.name == 'experimental':\n                viewObj.covs = {cov_lib: [] for cov_lib in cov_lib_names}\n                viewObj.covs[\"covsum\"] = []\n                for taxrule in self.taxrules:\n                    viewObj.tax[taxrule] = {rank: [] for rank in BtTax.RANKS}\n        # bodies\n        print(\"[+] Generating data for view\")\n        with tqdm(total=len(seqs), desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n            for seq in seqs:\n                blob = self.dict_of_blobs[seq]\n                for viewObj in viewObjs:\n                    if viewObj.name == 'table':\n                        viewObj.body.append(self.getTableLine(blob, taxrule, ranks, hits_flag, cov_lib_names, tax_lib_names, lineages))\n                    if viewObj.name == 'concoct_cov':\n                        viewObj.body.append(self.getConcoctCovLine(blob, cov_lib_names))\n                    if viewObj.name == 'experimental':\n                        viewObj.names.append(blob['name'])\n                        viewObj.gc.append(blob['gc'])\n                        viewObj.length.append(blob['length'])\n                        cov_sum = 0.0\n                        for cov_lib in blob['covs']:\n                            viewObj.covs[cov_lib].append(blob['covs'][cov_lib])\n                            cov_sum += blob['covs'][cov_lib]\n                        viewObj.covs['covsum'].append(cov_sum)\n                        for taxrule in blob['taxonomy']:\n                            for rank in blob['taxonomy'][taxrule]:\n                                viewObj.tax[taxrule][rank].append(blob['taxonomy'][taxrule][rank]['tax'])\n                    if viewObj.name == 'concoct_tax':\n                        for rank in ranks:\n                            if not rank in viewObj.body:\n                                viewObj.body[rank] = []\n                            viewObj.body[rank].append(self.getConcoctTaxLine(blob, rank, taxrule))\n                    if viewObj.name == 'covlib':\n                        viewObj.body.append(self.getCovLine(blob, cov_lib_names))\n                pbar.update()\n        for viewObj in viewObjs:\n            #print(viewObj.name)\n            viewObj.output()\n\n    def getCovHeader(self, cov_lib_names):\n        cov_lib_name = cov_lib_names[0]\n        header = '## %s\\n' % (self.version)\n        if isinstance(self.covLibs[cov_lib_name], CovLibObj):\n            # CovLibObjs\n            header += \"## Total Reads = %s\\n\" % (self.covLibs[cov_lib_name].reads_total)\n            header += \"## Mapped Reads = %s\\n\" % (self.covLibs[cov_lib_name].reads_mapped)\n            header += \"## Unmapped Reads = %s\\n\" % (self.covLibs[cov_lib_name].reads_total - self.covLibs[cov_lib_name].reads_mapped)\n            header += \"## Source(s) : %s\\n\" % (self.covLibs[cov_lib_name].f)\n        else:\n            # CovLibObjs turned dicts\n            header += \"## Total Reads = %s\\n\" % (self.covLibs[cov_lib_name]['reads_total'])\n            header += \"## Mapped Reads = %s\\n\" % (self.covLibs[cov_lib_name]['reads_mapped'])\n            header += \"## Unmapped Reads = %s\\n\" % (self.covLibs[cov_lib_name]['reads_total'] - self.covLibs[cov_lib_name]['reads_mapped'])\n            header += \"## Source(s) : %s\\n\" % (self.covLibs[cov_lib_name]['f'])\n        header += \"# %s\\t%s\\t%s\\n\" % (\"contig_id\", \"read_cov\", \"base_cov\")\n        return header\n\n    def getCovLine(self, blob, cov_lib_names):\n        if isinstance(blob, BlObj):\n            # BlobObj\n            return \"%s\\t%s\\t%s\\n\" % (blob.name, blob.read_cov.get(cov_lib_names[0], 0), blob.covs.get(cov_lib_names[0], 0.0))\n        else:\n            # BlobObj turned dict\n            return \"%s\\t%s\\t%s\\n\" % (blob['name'], blob['read_cov'].get(cov_lib_names[0], 0), blob['covs'].get(cov_lib_names[0], 0.0))\n\n    def getConcoctCovHeader(self, cov_lib_names):\n        return \"contig\\t%s\\n\" % \"\\t\".join(cov_lib_names)\n\n    def getConcoctTaxLine(self, blob, rank, taxrule):\n        if taxrule in blob['taxonomy']:\n            return \"%s,%s\\n\" % (blob['name'], blob['taxonomy'][taxrule][rank]['tax'])\n\n    def getConcoctCovLine(self, blob, cov_lib_names):\n        return \"%s\\t%s\\n\" % (blob['name'], \"\\t\".join(map(str, [ blob['covs'][covLib] for covLib in cov_lib_names])))\n\n    def getTableHeader(self, taxrule, ranks, hits_flag, cov_lib_names):\n        header = []\n        header.append('## %s' % (self.version))\n        header.append(\"## assembly\\t: %s\" % self.assembly_f)\n        for libname in sorted(self.covLibs):\n            covLib = self.covLibs[libname]\n            header.append(\"## coverage\\t %s - %s\" % (covLib['name'], covLib[\"f\"]))\n        if (self.hitLibs):\n            for libname in sorted(self.hitLibs):\n                hitLib = self.hitLibs[libname]\n                header.append(\"## taxonomy\\t %s - %s\" % (hitLib['name'], hitLib[\"f\"]))\n        else:\n            header.append(\"## taxonomy\\t: no taxonomy information found\")\n        header.append(\"## nodesDB\\t: %s\" % self.nodesDB_f)\n        header.append(\"## taxrule\\t: %s\" % taxrule)\n        try:\n            header.append(\"## min_score\\t: %s\" % self.min_score)\n            header.append(\"## min_diff\\t: %s\" % self.min_diff)\n            header.append(\"## tax_collision_random\\t: %s\" % self.tax_collision_random)\n        except AttributeError():\n            header.append(\"## min_score\\t: %s\" % 0.0)\n            header.append(\"## min_diff\\t: %s\" % 0.0)\n            header.append(\"## tax_collision_random\\t: %s\" % False)\n        header.append(\"##\")\n        main_header = []\n        main_header.append(\"# %s\" % \"\\t\".join(map(str, [\"name\", \"length\", \"GC\", \"N\"])))\n        col = 4\n        main_header.append(\"%s\" % (\"\\t\".join([cov_lib_name for cov_lib_name in cov_lib_names])))\n        col += len(cov_lib_names)\n        if (len(cov_lib_names)) > 1:\n            col += 1\n            main_header.append(\"%s\" % \"cov_sum\")\n        for rank in ranks:\n            main_header.append(\"%s\" % \"\\t\".join([rank + \".t.\" + str(col + 1), rank + \".s.\" + str(col + 2), rank + \".c.\" + str(col + 3)]))\n            col += 3\n            if hits_flag:\n                main_header.append(\"%s\" % rank + \".hits.\" + str(col + 1))\n                col += 1\n        header.append(\"\\t\".join(main_header))\n        return \"\\n\".join(header)\n\n    def getTableLine(self, blob, taxrule, ranks, hits_flag, cov_lib_names, tax_lib_names, lineages):\n        sep = \"\\t\"\n        line = ''\n        line += \"\\n%s\" % sep.join(map(str, [ blob['name'], blob['length'], blob['gc'], blob['n_count']  ]))\n        line += sep\n        line += \"%s\" % sep.join(map(str, [ blob['covs'][covLib] for covLib in cov_lib_names]))\n        if len(cov_lib_names) > 1:\n            line += \"%s%s\" % (sep, sum([ blob['covs'][covLib] for covLib in cov_lib_names]))\n        for rank in ranks:\n            line += sep\n            tax, score, c_index = 'N/A', 'N/A', 'N/A'\n            if taxrule in blob['taxonomy']:\n                tax = blob['taxonomy'][taxrule][rank]['tax']\n                score = blob['taxonomy'][taxrule][rank]['score']\n                c_index = blob['taxonomy'][taxrule][rank]['c_index']\n            line += \"%s\" % sep.join(map(str, [tax, score, c_index ]))\n            if (hits_flag) and (taxrule in blob['taxonomy']):\n                line += sep\n                for tax_lib_name in tax_lib_names:\n                    if tax_lib_name in blob['hits']:\n                        line += \"%s=\" % tax_lib_name\n                        sum_dict = {}\n                        for hit in blob['hits'][tax_lib_name]:\n                            tax_rank = lineages[hit['taxId']][rank]\n                            sum_dict[tax_rank] = sum_dict.get(tax_rank, 0.0) + hit['score']\n                        line += \"%s\" % \"|\".join([\":\".join(map(str, [tax_rank, sum_dict[tax_rank]])) for tax_rank in sorted(sum_dict, key=sum_dict.get, reverse=True)])\n                    else:\n                        line += \"%s=no-hit:0.0\" % (tax_lib_name)\n                    line += \";\"\n        return line\n\n    def dump(self):\n        dump = {'title' : self.title,\n                'assembly_f' : self.assembly_f,\n                'lineages' : self.lineages,\n                'order_of_blobs' : self.order_of_blobs,\n                'dict_of_blobs' : {name : blObj.__dict__ for name, blObj in self.dict_of_blobs.items()},\n                'length' : self.length,\n                'seqs' : self.seqs,\n                'n_count' : self.n_count,\n                'nodesDB_f' : self.nodesDB_f,\n                'covLibs' : {name : covLibObj.__dict__ for name, covLibObj in self.covLibs.items()},\n                'hitLibs' : {name : hitLibObj.__dict__ for name, hitLibObj in self.hitLibs.items()},\n                'taxrules' : self.taxrules,\n                'version' : self.version,\n                'min_score' : self.min_score,\n                'min_diff' : self.min_diff,\n                'tax_collision_random' : self.tax_collision_random\n                }\n        return dump\n\n    def load(self, BlobDb_f):\n        blobDict = BtIO.parseJson(BlobDb_f)\n        for k, v in blobDict.items():\n            setattr(self, k, v)\n        self.set_of_taxIds = blobDict['lineages'].keys()\n\n    def getPlotData(self, rank, min_length, hide_nohits, taxrule, c_index, catcolour_dict):\n        data_dict = {}\n        #read_cov_dict = {}\n        max_cov = 0.0\n        min_cov = 1000.0\n        cov_lib_dict = self.covLibs\n        cov_lib_names_l = self.covLibs.keys() # does not include cov_sum\n        if len(cov_lib_names_l) > 1:\n            # more than one cov_lib, cov_sum_lib has to be created\n            cov_lib_dict['covsum'] = CovLibObj('covsum', 'covsum', 'Sum of cov in %s' % basename(self.title)).__dict__ # ugly\n            cov_lib_dict['covsum']['reads_total'] = sum([self.covLibs[x]['reads_total'] for x in self.covLibs])\n            cov_lib_dict['covsum']['reads_mapped'] = sum([self.covLibs[x]['reads_mapped'] for x in self.covLibs])\n            cov_lib_dict['covsum']['cov_sum'] = sum([self.covLibs[x]['cov_sum'] for x in self.covLibs])\n            cov_lib_dict['covsum']['mean_cov'] = cov_lib_dict['covsum']['cov_sum']/self.seqs\n        for blob in self.dict_of_blobs.values():\n            name, gc, length, group = blob['name'], blob['gc'], blob['length'], ''\n            if (catcolour_dict): # annotation with categories specified in catcolour\n                group = str(catcolour_dict[name])\n            elif (c_index): # annotation with c_index instead of taxonomic group\n                if taxrule not in self.taxrules:\n                    BtLog.error('11', taxrule, self.taxrules)\n                else:\n                    group = str(blob['taxonomy'][taxrule][rank]['c_index'])\n            else: # annotation with taxonomic group\n                if not (taxrule) or taxrule not in self.taxrules:\n                    BtLog.warn_d['9'] % (taxrule, self.taxrules)\n                if taxrule in blob['taxonomy']:\n                    group = str(blob['taxonomy'][taxrule][rank]['tax'])\n            if not group in data_dict:\n                data_dict[group] = {\n                                    'name' : [],\n                                    'length' : [],\n                                    'gc' : [],\n                                    'covs' : {covLib : [] for covLib in cov_lib_dict.keys()},           # includes cov_sum if it exists\n                                    'reads_mapped' : {covLib : 0 for covLib in cov_lib_dict.keys()},    # includes cov_sum if it exists\n                                    'count' : 0,\n                                    'count_hidden' : 0,\n                                    'count_visible' : 0,\n                                    'span': 0,\n                                    'span_hidden' : 0,\n                                    'span_visible' : 0,\n                                    }\n            data_dict[group]['count'] = data_dict[group].get('count', 0) + 1\n            data_dict[group]['span'] = data_dict[group].get('span', 0) + int(length)\n            if ((hide_nohits) and group == 'no-hit') or length < min_length: # hidden\n                data_dict[group]['count_hidden'] = data_dict[group].get('count_hidden', 0) + 1\n                data_dict[group]['span_hidden'] = data_dict[group].get('span_hidden', 0) + int(length)\n            else: # visible\n                data_dict[group]['count_visible'] = data_dict[group].get('count_visible', 0) + 1\n                data_dict[group]['span_visible'] = data_dict[group].get('span_visible', 0) + int(length)\n                data_dict[group]['name'].append(name)\n                data_dict[group]['length'].append(length)\n                data_dict[group]['gc'].append(gc)\n                cov_sum = 0.0\n                reads_mapped_sum = 0\n                for cov_lib in sorted(cov_lib_names_l):\n                    if cov_lib == 'covsum':\n                        continue\n                    cov = float(blob['covs'][cov_lib])\n                    if cov < 0.1:\n                        cov = 0.1\n                    if cov < min_cov:\n                        min_cov = cov\n                    # increase max_cov\n                    if cov > max_cov:\n                        max_cov = cov\n                    # add cov of blob to group\n                    data_dict[group]['covs'][cov_lib].append(cov)\n                    cov_sum += cov\n                    # add readcov\n                    if cov_lib in blob['read_cov']:\n                        reads_mapped = blob['read_cov'][cov_lib]\n                        data_dict[group]['reads_mapped'][cov_lib] += reads_mapped\n                        reads_mapped_sum += reads_mapped\n                if len(cov_lib_names_l) > 1:\n                    if cov_sum <= 0.1 * len(cov_lib_names_l): # puts no-cov contigs at 0.1\n                        cov_sum = 0.1\n                    data_dict[group]['covs']['covsum'].append(cov_sum)\n                    if cov_sum > max_cov:\n                        max_cov = cov_sum\n                    if (reads_mapped_sum):\n                        data_dict[group]['reads_mapped']['covsum'] += reads_mapped_sum\n\n        return data_dict, min_cov, max_cov, cov_lib_dict\n\n    def addCovLib(self, covLib):\n        self.covLibs[covLib.name] = covLib\n        for blObj in self.dict_of_blobs.values():\n            blObj.addCov(covLib.name, 0.0)\n\n    def parseFasta(self, fasta_f, fasta_type):\n        print(BtLog.status_d['1'] % ('FASTA', fasta_f))\n        self.assembly_f = abspath(fasta_f)\n        if (fasta_type):\n            # Set up CovLibObj for coverage in assembly header\n            self.covLibs[fasta_type] = CovLibObj(fasta_type, fasta_type, fasta_f)\n\n        for name, seq in BtIO.readFasta(fasta_f):\n            blObj = BlObj(name, seq)\n            if not blObj.name in self.dict_of_blobs:\n                self.seqs += 1\n                self.length += blObj.length\n                self.n_count += blObj.n_count\n\n                if (fasta_type):\n                    cov = BtIO.parseCovFromHeader(fasta_type, blObj.name)\n                    self.covLibs[fasta_type].cov_sum += cov\n                    blObj.addCov(fasta_type, cov)\n\n                self.order_of_blobs.append(blObj.name)\n                self.dict_of_blobs[blObj.name] = blObj\n            else:\n                BtLog.error('5', blObj.name)\n\n        if self.seqs == 0 or self.length == 0:\n            BtLog.error('1')\n\n    def parseCoverage(self, **kwargs):\n        # arguments\n        covLibObjs = kwargs['covLibObjs']\n        estimate_cov = kwargs['estimate_cov']\n\n        for covLib in covLibObjs:\n            self.addCovLib(covLib)\n            print(BtLog.status_d['1'] % (covLib.name, covLib.f))\n            if covLib.fmt == 'bam':\n                base_cov_dict = {}\n                base_cov_dict, covLib.reads_total, covLib.reads_mapped, read_cov_dict = BtIO.parseBam(covLib.f, set(self.dict_of_blobs), estimate_cov)\n                if covLib.reads_total == 0:\n                    print(BtLog.warn_d['4'] % covLib.f)\n\n                for name, base_cov in base_cov_dict.items():\n                    cov = 0.0\n                    if not self.dict_of_blobs[name].agct_count == 0:\n                        cov = base_cov / self.dict_of_blobs[name].agct_count\n                    covLib.cov_sum += cov\n                    self.dict_of_blobs[name].addCov(covLib.name, cov)\n                    self.dict_of_blobs[name].addReadCov(covLib.name, read_cov_dict[name])\n                # Create COV file for future use\n                out_f = BtIO.getOutFile(covLib.f, kwargs.get('prefix', None), None)\n                covView = ViewObj(name=\"covlib\", out_f=out_f, suffix=\"cov\", header=\"\", body=[])\n                self.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[covLib.name], progressbar=False)\n\n            elif covLib.fmt == 'cas':\n                cov_dict, covLib.reads_total, covLib.reads_mapped, read_cov_dict = BtIO.parseCas(covLib.f, self.order_of_blobs)\n                if covLib.reads_total == 0:\n                    print(BtLog.warn_d['4'] % covLib.f)\n                for name, cov in cov_dict.items():\n                    covLib.cov_sum += cov\n                    self.dict_of_blobs[name].addCov(covLib.name, cov)\n                    self.dict_of_blobs[name].addReadCov(covLib.name, read_cov_dict[name])\n                out_f = BtIO.getOutFile(covLib.f, kwargs.get('prefix', None), None)\n                covView = ViewObj(name=\"covlib\", out_f=out_f, suffix=\"cov\", header=\"\", body=[])\n                self.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[covLib.name], progressbar=False)\n\n            elif covLib.fmt == 'cov':\n                base_cov_dict, covLib.reads_total, covLib.reads_mapped, covLib.reads_unmapped, read_cov_dict = BtIO.parseCov(covLib.f, set(self.dict_of_blobs))\n                #cov_dict = BtIO.readCov(covLib.f, set(self.dict_of_blobs))\n                if not len(base_cov_dict) == self.seqs:\n                    print(BtLog.warn_d['4'] % covLib.f)\n                for name, cov in base_cov_dict.items():\n                    covLib.cov_sum += cov\n                    self.dict_of_blobs[name].addCov(covLib.name, cov)\n                    if name in read_cov_dict:\n                        self.dict_of_blobs[name].addReadCov(covLib.name, read_cov_dict[name])\n            else:\n                pass\n            covLib.mean_cov = covLib.cov_sum/self.seqs\n            if covLib.cov_sum == 0.0:\n                print(BtLog.warn_d['6'] % (covLib.name))\n            self.covLibs[covLib.name] = covLib\n\n\n    def parseHits(self, hitLibs):\n        for hitLib in hitLibs:\n            self.hitLibs[hitLib.name] = hitLib\n            print(BtLog.status_d['1'] % (hitLib.name, hitLib.f))\n            # only accepts format 'seqID\\ttaxID\\tscore'\n            for hitDict in BtIO.readTax(hitLib.f, set(self.dict_of_blobs)):\n                if \";\" in hitDict['taxId']:\n                    hitDict['taxId'] = hitDict['taxId'].split(\";\")[0]\n                    #print(BtLog.warn_d['5'] % (hitDict['name'], hitLib))\n                self.set_of_taxIds.add(hitDict['taxId'])\n                self.dict_of_blobs[hitDict['name']].addHits(hitLib.name, hitDict)\n\n    def computeTaxonomy(self, taxrules, nodesDB, min_score, min_bitscore_diff, tax_collision_random):\n        print(BtLog.status_d['6'] % \",\".join(taxrules))\n        tree_lists = BtTax.getTreeList(self.set_of_taxIds, nodesDB)\n        self.lineages = BtTax.getLineages(tree_lists, nodesDB)\n        self.taxrules = taxrules\n        self.min_score = min_score\n        self.min_diff = min_bitscore_diff\n        self.tax_collision_random = tax_collision_random\n\n        with tqdm(total=self.seqs, desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n            for blObj in self.dict_of_blobs.values():\n                for taxrule in taxrules:\n                    if (blObj.hits):\n                        blObj.taxonomy[taxrule] = BtTax.taxRule(taxrule, blObj.hits, self.lineages, min_score, min_bitscore_diff, tax_collision_random)\n                    else:\n                        blObj.taxonomy[taxrule] = BtTax.noHit()\n                pbar.update()\n            self.set_of_taxIds = set()\n\n    def getBlobs(self):\n        for blObj in [self.dict_of_blobs[key] for key in self.order_of_blobs]:\n            yield blObj\n\nclass BlObj():\n    def __init__(self, name, seq):\n        self.name = name\n        self.length = len(seq)\n        self.n_count = seq.count('N')\n        self.agct_count = self.length - self.n_count\n        self.gc = round(self.calculateGC(seq), 4)\n        self.covs = {}\n        self.read_cov = {}\n        self.hits = {}\n        self.taxonomy = {}\n\n    def calculateGC(self, seq):\n        return float((seq.count('G') + seq.count('C') ) / self.agct_count \\\n                     if self.agct_count > 0 else 0.0)\n\n    def addCov(self, lib_name, cov):\n        self.covs[lib_name] = float(\"{0:.4f}\".format(cov)) # changed to three decimal digits\n\n    def addReadCov(self, lib_name, read_cov):\n        self.read_cov[lib_name] = read_cov\n\n    def addHits(self, hitLibName, hitDict):\n        if not hitLibName in self.hits:\n            self.hits[hitLibName] = []\n        self.hits[hitLibName].append(hitDict)\n\nclass CovLibObj():\n    def __init__(self, name, fmt, f):\n        self.name = name\n        self.fmt = fmt\n        self.f = abspath(f) if isfile(f) else f # pass file/string/''\n        self.cov_sum = 0.0\n        self.reads_total = 0\n        self.reads_mapped = 0\n        self.reads_unmapped = 0\n        self.mean_cov = 0.0\n\nclass HitLibObj():\n    def __init__(self, name, fmt, f):\n        self.name = name\n        self.fmt = fmt\n        self.f = abspath(f) if isfile(f) else f # pass file/string/''\n\n\nclass ViewObj():\n    def __init__(self, name='', out_f='', suffix='', header='', body=''):\n        self.name = name\n        self.out_f = out_f\n        self.suffix = suffix\n        self.header = header\n        self.body = body\n\n    def output(self):\n        if isinstance(self.body, dict):\n            for category in self.body:\n                out_f = \"%s.%s.%s\" % (self.out_f, category, self.suffix)\n                print(BtLog.status_d['13'] % (out_f))\n                with open(out_f, \"w\") as fh:\n                    fh.write(self.header + \"\".join(self.body[category]))\n        elif isinstance(self.body, list):\n            out_f = \"%s.%s\" % (self.out_f, self.suffix)\n            print(BtLog.status_d['13'] % (out_f))\n            with open(out_f, \"w\") as fh:\n                fh.write(self.header + \"\".join(self.body))\n        else:\n            sys.exit(\"[ERROR] - 001\")\n\n#class newBlobDb():\n#    def __init__(self, name='blobdb'):\n#        # meta\n#        self.title = title\n#        self.path = path\n#        self.version = version\n#        self.blob_count = 0\n#        self.tax_hit_count = 0\n#        self.sources = {}\n#        self.files = {}\n#        self.cov_lib = []\n#        self.tax_lib = []\n#        self.tax_rule = []\n#        self.reads_total = {}\n#        self.reads_mapped = {}\n#        self.ranks = []\n#\n#        self.blobs_list = []\n#        self.blobs_dict = {}\n#\n#        self.blob_id = []\n#        self.length = []\n#        self.gc = []\n#        self.n_count = []\n#        self.agct_count = []\n#\n#        self.cov_base = {}\n#        self.cov_read = {}\n#        self.tax = {}\n#        self.tax_hit = {}\n#        self.tax_id = {}\n#\n#        self.meta = {}\n#\n#    def _set_meta(self):\n#        self.meta = {\n#            \"title\" : self.title,\n#            \"version\" : self.version,\n#            \"count\" : self.count,\n#            \"sources\" : self.sources,\n#            \"files\" : self.files,\n#            \"cov_lib\" : self.cov_lib,\n#            \"tax_lib\" : self.tax_lib,\n#            \"tax_rule\" : self.tax_rule,\n#            \"reads_total\" : self.reads_total,\n#            \"reads_mapped\" : self.reads_mapped,\n#            \"tax_hit_count\" : self.tax_hit_count\n#        }\n#\n#    def _parse_meta(self, meta_f):\n#        pass\n#\n#\n#    def _set_files(self):\n#        self.files = {\n#            # primary\n#            'meta' : \"%s\" % join(self.path, \"meta\"),\n#            'blob_id' : \"%s\" % join(self.path, \"blob_id\"),\n#            'length' : \"%s\" % join(self.path, \"length\"),\n#            'gc' : \"%s\" % join(self.path, \"gc\"),\n#            'n_count' : \"%s\" % join(self.path, \"n_count\"),\n#            'agct_count' : \"%s\" % join(self.path, \"agct_count\"),\n#            'tax_id' : \"%s\" % join(self.path, tax_id),\n#            # secondary\n#            'cov_base' : {cov_lib : \"%s\" % join(self.path, \"cov_base\") for cov_lib in self.cov_lib},\n#            'cov_read' : {cov_lib : \"%s\" % join(self.path, \"cov_read\") for cov_lib in self.cov_lib},\n#            'tax' : {tax_rule : \"%s\" % join(self.path, \"tax\") for tax_rule in self.tax_rule},\n#            'tax_hit' : {tax_lib : \"%s\" % join(self.path, \"tax_hit\") for tax_lib in self.tax_lib}\n#            }\n#\n#    def _write_output(self):\n#        primary = ['meta', 'blob_id', 'length', 'gc', 'n_count', 'agct_count', 'tax_id']\n#        secondary = ['cov_base', 'cov_read', 'tax', 'tax_hit']\n#        directory = BtIO.create_dir(self.path)\n#        out_fs = []\n#        if (directory):\n#            out_fs = []\n#            strings = []\n#            for key in self.files:\n#                if key in primary:\n#                    out_f.append(self.files[key])\n#                    data.append(getattr(self, key))\n#                elif key in secondary:\n#                    for key2 in self.files[key]:\n#                        out_f.append(self.files[key][key2])\n#                        data.append(getattr(self, key)[key2])\n#                else:\n#                    pass\n#            with tarfile.open(out_f, \"a:gz\") as tar:\n#                for out_f, string in zip(out_fs, strings):\n#                    with open(out_f, 'w') as fh:\n#                        json.dump(string, fh, indent=1, separators=(',', ' : '))\n#                    tar.add(out_f)\n#\n#    def dump(self):\n#        self._set_files()\n#        self._set_meta()\n#        self._write_output()\n#\n#    def load(self, blobdb):\n#        try:\n#            meta_f = blobdb.getmember('meta')\n#        except KeyError:\n#            pass\n#\n#    def yield_blob(self, fields):\n#        Blob = collections.namedtuple('Blob', fields)\n#        for idx, blob_id in enumerate(self.blob_id):\n#            data = [x for x in getattr(self, fields)]\n#            blob = Blob()\n#\n#    def get_idxs_by_ids(self, ids):\n#        # list of blob_ids\n#        if (ids) and isinstance(ids, list):\n#            return [int(self.blob_dict[id_]) for _id_ in ids]\n#\n#    def get_data(self, *key, **kwargs):\n#        idxs = []\n#        # sort out which idxs\n#        if (kwargs['ids']): # delimited by list of ids\n#            idxs = self.get_idxs_by_ids(kwargs['ids'])\n#        elif (kwargs['idxs']): # delimited by list of idxs\n#            idxs = kwargs['idxs']\n#        else: # all\n#            idxs = range(self.count)\n#\n#        # return data based on idxs\n#        if args[0] == \"name\":\n#            return [self.name[idx] for idx in idxs]\n#        elif args[0] == \"length\":\n#            return [self.length[idx] for idx in idxs]\n#        elif args[0] == \"gc\":\n#            return [self.gc[idx] for idx in idxs]\n#        elif args[0] == \"n_count\":\n#            return [self.n_count[idx] for idx in idxs]\n#        elif args[0] == \"cov_base\":\n#            if args[1] in self.cov_lib:\n#                return [self.cov_base[idx] for idx in idxs]\n#        elif args[0] == \"cov_read\":\n#            if args[1] in self.cov_lib:\n#                return [self.cov_read[idx] for idx in idxs]\n#        elif args[0] == \"tax\":\n#            if args[1] in self.tax_rule:\n#                if args[2] in self.ranks:\n#                    return [self.tax[idx] for idx in idxs]\n#        elif args[0] == \"tax_hit\":\n#            if args[1] in self.tax_lib:\n#                return [self.tax_hit[idx] for idx in idxs]\n#        else:\n#            return None\n#\n#    # Parse\n#    def parse_meta(self, meta_f):\n#        meta = BtIO.read_meta(meta_f)\n#        for key, value in meta.items():\n#            setattr(key, value)\n#        self.name = meta['name']\n#        self.covlib = meta['covlib']\n#        self.taxrule = meta['taxrule']\n#        self.taxlib = meta['taxlib']\n#        self.files = meta['files']\n#        self.blobs_count = meta['count']\n#        self.ranks = meta['ranks']\n#\n#    def parse_data(self, key, exp_count):\n#        data = BtIO.read_json_list(self.files[key])\n#        if not len(data) == exp_count:\n#            # error\n#            pass\n#        else:\n#            setattr(self, key, data)\n#\n#    def output(self):\n#        # meta\n#        meta = self.get_meta()\n#        meta_f = join(self.view_dir, \"meta.json\")\n#        BtIO.writeJson(meta, meta_f, indent=2)\n#        # gc\n#        gc_f = join(self.view_dir, \"gc.json\")\n#        print(BtLog.status_d['13'] % (gc_f))\n#        BtIO.writeJson(self.gc, gc_f, indent=1)\n#        # length\n#        length_f = join(self.view_dir, \"length.json\")\n#        print(BtLog.status_d['13'] % (length_f))\n#        BtIO.writeJson(self.length, length_f, indent=1)\n#        # names\n#        names_f = join(self.view_dir, \"names.json\")\n#        print(BtLog.status_d['13'] % (names_f))\n#        BtIO.writeJson(self.names, names_f, indent=1)\n#        # cov\n#        cov_d = join(self.view_dir, \"covs\")\n#        BtIO.create_dir(directory=cov_d)\n#        for cov_lib, cov in self.covs.items():\n#            cov_f = join(cov_d, \"%s.json\" % cov_lib)\n#            print(BtLog.status_d['13'] % (cov_f))\n#            BtIO.writeJson(cov, cov_f, indent=1)\n#        # tax\n#        taxrule_d = join(self.view_dir, \"taxrule\")\n#        BtIO.create_dir(directory=taxrule_d)\n#        for taxrule in self.tax:\n#            tax_d = join(taxrule_d, taxrule)\n#            BtIO.create_dir(directory=tax_d)\n#            for rank in self.tax[taxrule]:\n#                tax = self.tax[taxrule][rank]\n#                rank_f = join(tax_d, \"%s.json\" % rank)\n#                BtIO.writeJson(tax, rank_f, indent=1)\n\nclass ExperimentalViewObj():\n    def __init__(self, name='experimental', view_dir='',blobDb={},meta={}):\n        self.name = name\n        self.view_dir = re.sub(\".blobDB\", \"\", view_dir)\n        self.length = []\n        self.gc = []\n        self.n_count = []\n        self.names = []\n        self.tax = {}\n        self.covs = {}\n        self.read_covs = defaultdict(list)\n        self.tax_scores = {}\n        self.blobDb = blobDb\n        self.meta = meta\n        BtIO.create_dir(self.view_dir)\n\n    def _format_float(self,l,min_val=-float(\"inf\")):\n        if min_val:\n            l = map(lambda x:max(x,min_val),l)\n        return map(lambda x:float(\"%.4f\" % x),l)\n\n    def _remove_cov_suffix(self,id,meta):\n        rep_list = ['.bam','.bam.cov','.cas','.cas.cov','.cov','.sam','.sam.cov']\n        rep_list += list(map(lambda x: \"%s.\" % x, self.view_dir.split('.')))\n        name = id\n        if id in meta:\n            name = re.sub(\"|\".join(rep_list), \"\", basename(meta[id]['f']))\n        return name if name else id\n\n    def get_meta(self):\n        meta = self.meta\n        meta[\"id\"] = self.view_dir\n        meta[\"name\"] = self.view_dir\n        meta[\"records\"] = len(self.names)\n        meta[\"record_type\"] = \"contigs\"\n        meta[\"fields\"] = [\n            { \"id\":\"length\", \"name\":\"Length\", \"type\":\"variable\", \"datatype\":\"integer\", \"range\":[min(self.length),max(self.length)], \"scale\":\"scaleLog\", \"preload\":True },\n            { \"id\":\"gc\", \"name\":\"GC\", \"type\":\"variable\", \"datatype\":\"float\", \"range\":self._format_float([min(self.gc),max(self.gc)]), \"scale\":\"scaleLinear\", \"preload\":True },\n        ]\n        meta[\"plot\"] = {\n            \"x\":\"gc\",\n            \"z\":\"length\"\n        }\n        cov_names = filter(lambda name: name != \"covsum\",self.covs)\n        for taxrule in self.tax:\n            self.tax_scores[taxrule] = defaultdict(lambda: {'score':[],'c_index':[]})\n        for _id in self.blobDb.order_of_blobs:\n            blob = self.blobDb.dict_of_blobs[_id]\n            self.read_covs['covsum'].append(0)\n            for cov_name in cov_names:\n                self.read_covs[cov_name].append(blob['read_cov'][cov_name])\n                self.read_covs['covsum'][-1] += blob['read_cov'][cov_name]\n            for taxrule in self.tax:\n                for rank in self.tax[taxrule]:\n                    self.tax_scores[taxrule][rank]['score'].append(blob['taxonomy'][taxrule][rank]['score'])\n                    self.tax_scores[taxrule][rank]['c_index'].append(blob['taxonomy'][taxrule][rank]['c_index'])\n            self.n_count.append(blob['length']-blob['agct_count'])\n        if max(self.n_count) > 0:\n            meta['fields'].append({ \"id\":\"ncount\", \"name\":\"N count\", \"type\":\"variable\", \"datatype\":\"integer\", \"range\":[max(0.1,min(self.n_count)),max(self.n_count)], \"scale\":\"scaleLinear\"})\n        if len(self.covs) > 0:\n            for cov in ['cov','read_cov']:\n                cov_libs = []\n                for cov_name in self.covs:\n                    name = self._remove_cov_suffix(cov_name,self.blobDb.covLibs)\n                    _id = \"%s_%s\" % (name,cov)\n                    cov_lib_meta = {\"id\": _id, \"name\":name }\n                    if cov_name == \"cov0\" and cov == \"cov\":\n                        cov_lib_meta[\"preload\"] = True\n                        meta['plot']['y'] = _id\n                    cov_libs.append(cov_lib_meta)\n                cov_meta = {\"id\":\"%s\" % cov, \"name\":\"Coverage\", \"type\":\"variable\", \"datatype\":\"float\", \"scale\":\"scaleLog\", \"range\":self._format_float([0.02,max(self.covs[\"covsum\"])])}\n                if cov == 'read_cov':\n                    cov_meta['name'] = \"Read coverage\"\n                    cov_meta['datatype'] = \"integer\"\n                    cov_meta['range'] = [0.2,max(self.read_covs[\"covsum\"])]\n                cov_meta['children'] = sorted(cov_libs, key=lambda k: k['name'])\n                meta['fields'].append(cov_meta)\n        if len(self.tax) > 0:\n            tax_rules = []\n            for taxrule in self.tax:\n                taxrule_meta = {\"id\":taxrule, \"name\":taxrule, \"children\":[] }\n                for rank in self.tax[taxrule]:\n                    _id = \"%s_%s\" % (taxrule,rank)\n                    tax_rank_data = []\n                    tax_rank_data.append({ \"id\":\"%s_score\" % _id, \"name\":\"%s score\" % _id, \"type\":\"variable\", \"datatype\":\"float\", \"scale\":\"scaleLog\", \"range\":[0.2,max(self.tax_scores[taxrule][rank]['score'])], \"preload\":False, \"active\":False })\n                    tax_rank_data.append({ \"id\":\"%s_cindex\" % _id, \"name\":\"%s c-index\" % _id, \"type\":\"variable\", \"datatype\":\"integer\", \"scale\":\"scaleLinear\", \"range\":[0,max(self.tax_scores[taxrule][rank]['c_index'])], \"preload\":False, \"active\":False })\n                    tax_rank_meta = { \"id\":_id, \"name\":_id, \"data\": tax_rank_data }\n                    if rank == \"phylum\":\n                        tax_rank_meta[\"preload\"] = True\n                        meta['plot']['cat'] = _id\n                    taxrule_meta['children'].append(tax_rank_meta)\n                tax_rules.append(taxrule_meta)\n            tax_meta = {\"id\":\"taxonomy\", \"name\":\"Taxonomy\", \"type\":\"category\", \"datatype\":\"string\"}\n            tax_meta['children'] = sorted(tax_rules, key=lambda k: k['name'])\n            meta['fields'].append(tax_meta)\n        #for taxrule in self.tax:\n        #    meta['datatypes'][taxrule] = {\"name\": taxrule, \"type\":\"category\"}\n        #for rank in BtTax.RANKS:\n        #    meta['datatypes'][rank] = {\"name\": rank, \"type\":\"category\", \"levels\" : 7}\n        return meta\n\n    def _keyed_list(self,l):\n        d = {}\n        i = 0\n        o = []\n        for v in l:\n            if v not in d:\n                d[v] = i\n                i += 1\n            o.append(d[v])\n        return {'values':o,'keys':sorted(d, key=d.get)}\n\n    def output(self):\n        # meta\n        meta = self.get_meta()\n        meta_f = join(self.view_dir, \"meta.json\")\n        BtIO.writeJson(meta, meta_f)\n        # gc\n        gc_f = join(self.view_dir, \"gc.json\")\n        print(BtLog.status_d['13'] % (gc_f))\n        BtIO.writeJson({\"values\":self._format_float(self.gc)}, gc_f, indent=1)\n        # length\n        length_f = join(self.view_dir, \"length.json\")\n        print(BtLog.status_d['13'] % (length_f))\n        BtIO.writeJson({\"values\":self.length}, length_f, indent=1)\n        # Ns\n        if max(self.n_count) > 0:\n            n_f = join(self.view_dir, \"ncount.json\")\n            print(BtLog.status_d['13'] % (n_f))\n            BtIO.writeJson({\"values\":map(lambda x:max(x,0.2),self.n_count)}, n_f, indent=1)\n        # identifiers\n        ids_f = join(self.view_dir, \"identifiers.json\")\n        print(BtLog.status_d['13'] % (ids_f))\n        BtIO.writeJson(self.names, ids_f, indent=1)\n        # cov\n        for cov_name, cov in self.covs.items():\n            name = self._remove_cov_suffix(cov_name,self.blobDb.covLibs)\n            cov_f = join(self.view_dir, \"%s_cov.json\" % name)\n            print(BtLog.status_d['13'] % (cov_f))\n            BtIO.writeJson({\"values\":self._format_float(cov,0.02)}, cov_f, indent=1)\n        # read_cov\n        for cov_name, cov in self.read_covs.items():\n            name = self._remove_cov_suffix(cov_name,self.blobDb.covLibs)\n            cov_f = join(self.view_dir, \"%s_read_cov.json\" % name)\n            print(BtLog.status_d['13'] % (cov_f))\n            BtIO.writeJson({\"values\":map(lambda x:max(x,0.2),cov)}, cov_f, indent=1)\n        # tax\n        for taxrule in self.tax:\n            for rank in self.tax[taxrule]:\n                tax = self._keyed_list(self.tax[taxrule][rank])\n                rank_f = join(self.view_dir, \"%s_%s.json\" % (taxrule,rank))\n                BtIO.writeJson(tax, rank_f, indent=1)\n                score = self.tax_scores[taxrule][rank]['score']\n                score_f = join(self.view_dir, \"%s_%s_score.json\" % (taxrule,rank))\n                BtIO.writeJson({\"values\":map(lambda x:max(x,0.2),score)}, score_f, indent=1)\n                cindex = self.tax_scores[taxrule][rank]['c_index']\n                cindex_f = join(self.view_dir, \"%s_%s_cindex.json\" % (taxrule,rank))\n                BtIO.writeJson({\"values\":cindex}, cindex_f, indent=1)\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "lib/BtIO.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile        : BtIO.py\nAuthor      : Dominik R. Laetsch, dominik.laetsch at gmail dot com\n\"\"\"\n\nfrom __future__ import division\nimport re\nimport subprocess\nimport os\nimport pysam\nfrom collections import defaultdict\nfrom os.path import basename, isfile, splitext, join, isdir\nimport shutil\nimport lib.BtLog as BtLog\nimport sys\nfrom tqdm import tqdm\nimport yaml\n# CONSTs\nCOMPLEMENT = {'A':'T','C':'G','G':'C','T':'A','N':'N'}\n\ndef create_dir(directory=\"\", overwrite=True):\n    if directory:\n        if not isdir(directory):\n            os.makedirs(directory)\n        else:\n            if overwrite:\n                shutil.rmtree(directory)           #removes all the subdirectories!\n                os.makedirs(directory)\n        return directory\n    else:\n        return None\n\ndef parseList(infile):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    with open(infile) as fh:\n        items = []\n        for l in fh:\n            items.append(l.rstrip(\"\\n\"))\n    return items\n\ndef parseReferenceCov(infile):\n    refcov_dict = {}\n    if infile:\n        if not isfile(infile):\n            BtLog.error('0', infile)\n        with open(infile) as fh:\n            for l in fh:\n                try:\n                    cov_lib, reads_total_ref, reads_mapped_ref = l.split(\",\")\n                    refcov_dict[cov_lib] = {'reads_total' : int(reads_total_ref),\n                                            'reads_mapped' : int(reads_mapped_ref)}\n                except:\n                    BtLog.error('21', infile)\n    return refcov_dict\n\ndef parseCmdlist(temp):\n    _list = []\n    if temp:\n        if \",\" in temp:\n            _list = temp.split(\",\")\n        else:\n            _list.append(temp)\n    return _list\n\ndef parseCmdLabels(labels):\n    label_d = {}\n    name, groups = '', ''\n    if labels:\n        try:\n            for label in labels:\n                name, groups = str(label).split(\"=\")\n                if \",\" in groups:\n                    for group in groups.split(\",\"):\n                        label_d[group] = name\n                else:\n                    label_d[groups] = name\n        except:\n            BtLog.error('17', labels)\n    return label_d\n\ndef parseCatColour(infile):\n    catcolour_dict = {}\n    if infile:\n        if not isfile(infile):\n            BtLog.error('0', infile)\n        with open(infile) as fh:\n            for l in fh:\n                try:\n                    seq_name, category = l.rstrip(\"\\n\").split(\",\")\n                    catcolour_dict[seq_name] = category\n                except:\n                    BtLog.error('23', infile)\n    return catcolour_dict\n\ndef parseDict(infile, key, value):\n    items = {}\n    if infile:\n        if not isfile(infile):\n            BtLog.error('0', infile)\n        with open(infile) as fh:\n            items = {}\n            k_idx = int(key)\n            v_idx = int(value)\n            for l in fh:\n                temp = l.rstrip(\"\\n\").split()\n                items[temp[k_idx]] = temp[v_idx]\n    return items\n\ndef parseColours(infile):\n    items = {}\n    if infile:\n        if not isfile(infile):\n            BtLog.error('0', infile)\n        with open(infile) as fh:\n            for l in fh:\n                temp = l.rstrip(\"\\n\").split(\",\")\n                items[temp[0]] = temp[1]\n    return items\n\ndef parseSet(infile):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    with open(infile) as fh:\n        items = set()\n        for l in fh:\n            items.add(l.rstrip(\"\\n\").lstrip(\">\"))\n    return items\n\ndef parseFastaNameOrder(infile):\n    fasta_order = []\n    for name, seq in readFasta(infile):\n        fasta_order.append(name)\n    return fasta_order\n\ndef readFasta(infile):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    with open(infile) as fh:\n        header, seqs = '', []\n        for l in fh:\n            if l[0] == '>':\n                if header:\n                    yield header, ''.join(seqs).upper()\n                header, seqs = l[1:-1].split()[0], [] # Header is split at first whitespace\n            else:\n                seqs.append(l[:-1])\n        yield header, ''.join(seqs).upper()\n\ndef runCmd(**kwargs):\n    command = kwargs['command']\n    cmd = command.split() # sanitation\n    p = subprocess.Popen(cmd,\n                         stdout=subprocess.PIPE,\n                         stderr=subprocess.STDOUT,\n                         universal_newlines=True,\n                         bufsize=-1) # buffersize of system\n    wait = kwargs.get('wait', False)\n    if wait :\n        p.wait()\n        if p.returncode == 0:\n            pass\n    else:\n        return iter(p.stdout.readline, b'')\n\ndef which(program):\n    def is_exe(fpath):\n        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n    fpath, fname = os.path.split(program)\n    if fpath:\n        if is_exe(program):\n            return program\n    else:\n        for path in os.environ[\"PATH\"].split(os.pathsep):\n            path = path.strip('\"')\n            exe_file = os.path.join(path, program)\n            if is_exe(exe_file):\n                return exe_file\n    return None\n\ndef checkAlnIndex(aln):\n    try:\n        index_flag = aln.check_index()\n    except ValueError:\n        index_flag = False\n    return index_flag\n\ndef getAlnHeaderIntersection(aln, headers):\n    aln_set = set(aln.references)\n    headers_set = set(headers)\n    headers_aln_intersection = headers_set.intersection(aln_set)\n    return (len(headers_set), len(aln_set), len(headers_aln_intersection))\n\ndef estimate_read_lengths(aln, set_of_blobs):\n    _read_lengths = []\n    while len(_read_lengths) < 10000:\n        for header in set_of_blobs:\n            for read in aln.fetch(header):\n                _read_lengths.append(read.query_length)\n    return round(sum(_read_lengths)/len(_read_lengths), 4)\n\ndef checkBam(aln, set_of_blobs):   \n    if not checkAlnIndex(aln):\n        print(\"[X] Please (sort and) index your BAM file\")\n        sys.exit()\n    len_headers, len_aln, len_intersection = getAlnHeaderIntersection(aln, set_of_blobs)\n    if len_intersection == 0:\n        print(\"[X] Headers in FASTA and BAM don't seem to match\")\n        sys.exit()\n    print(\"[+] -> %.2f (%s/%s) of sequences have reads aligned to them.\" % ((len_intersection / len_headers) * 100, len_intersection, len_headers))\n    reads_total = aln.mapped + aln.unmapped\n    print(\"[+] -> %.2f (%s/%s) of reads are mapped.\" % ((aln.mapped / reads_total) * 100, aln.mapped, reads_total))\n    return reads_total, aln.mapped\n\ndef parseBam(infile, set_of_blobs, estimate_cov):\n    # no_base_cov_flag [deprecated]\n    reads_total, reads_mapped = 0, 0\n    with pysam.AlignmentFile(infile) as aln:\n        reads_total, reads_mapped = checkBam(aln, set_of_blobs)\n        if estimate_cov:\n            base_cov_dict, read_cov_dict = estimate_coverage(aln, set_of_blobs)\n        else:\n            base_cov_dict, read_cov_dict = calculate_coverage(aln, reads_mapped, set_of_blobs)\n    return base_cov_dict, reads_total, reads_mapped, read_cov_dict\n\ndef estimate_coverage(aln, set_of_blobs):\n    base_cov_dict = {blob : 0.0 for blob in set_of_blobs}\n    read_cov_dict = {blob : 0 for blob in set_of_blobs}\n    est_read_length = estimate_read_lengths(aln, set_of_blobs)\n    with tqdm(total=len(set_of_blobs), desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n        for header in set_of_blobs:\n            read_count = aln.count(header, read_callback=check_mapped_read)\n            base_cov_dict[header] = read_count * est_read_length\n            read_cov_dict[header] += read_count\n            pbar.update()\n    return base_cov_dict, read_cov_dict\n\ndef check_mapped_read(read):\n    if read.is_unmapped or read.is_secondary or read.is_supplementary:\n        return False\n    return True\n\ndef calculate_coverage(aln, reads_mapped, set_of_blobs):\n    _base_cov_dict = {blob : [] for blob in set_of_blobs}\n    read_cov_dict = {blob : 0 for blob in set_of_blobs}\n    allowed_operations = set([0, 7, 8])\n    with tqdm(total=reads_mapped, desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n        for read in aln.fetch(until_eof=True):\n            if not check_mapped_read(read):\n                continue\n            for operation, length in read.cigartuples:\n                if operation in allowed_operations:\n                    _base_cov_dict[read.reference_name].append(length)\n            read_cov_dict[read.reference_name] += 1\n            pbar.update()\n    base_cov_dict = {ref_name: sum(_base_cov) for ref_name, _base_cov in _base_cov_dict.items()}\n    return base_cov_dict, read_cov_dict \n\ndef write_read_pair_seqs(pair_count_by_type, seqs_by_type, out_fs_by_type):\n    for pair_type, pair_count in pair_count_by_type.items():\n        print(BtLog.status_d['23'] % (pair_type, pair_count))\n        if pair_count:\n            out_fs = out_fs_by_type[pair_type]\n            if len(set(out_fs)) == 1:\n                out_f = out_fs[0]\n                with open(out_f, 'w') as out_fh:\n                    print(BtLog.status_d['24'] % out_f)\n                    #out_fh.write(\"\\n\".join(seqs_by_type[pair_type]) + \"\\n\")\n                    out_fh.write(\"\\n\".join([pair for pair in seqs_by_type[pair_type]]) + \"\\n\")\n            else:\n                out_f = out_fs[0]\n                with open(out_f, 'w') as out_fh:\n                    print(BtLog.status_d['24'] % out_f)\n                    out_fh.write(\"\\n\".join([pair for pair in seqs_by_type[pair_type][0::2]]) + \"\\n\")    \n                out_f = out_fs[1]\n                with open(out_f, 'w') as out_fh:\n                    print(BtLog.status_d['24'] % out_f)\n                    out_fh.write(\"\\n\".join([pair for pair in seqs_by_type[pair_type][1::2]]) + \"\\n\")    \n\n\ndef get_read_pair_fasta(read, read_format):\n    name = read.query_name\n    seq = read.get_forward_sequence()\n    if read_format == \"fq\":\n        qual = ''\n        if not read.is_reverse:\n            qual = read.qual\n        else:\n            qual = read.qual[::-1]\n        return \"@{name}\\n{seq}\\n+\\n{qual}\".format(name=name, seq=seq, qual=qual)\n    else:\n        return \">{name}\\n{seq}\".format(name=name, seq=seq)\n\n\ndef init_read_pairs(outfile, include_unmapped, noninterleaved, include, exclude, read_format):\n    read_pair_types = []\n    if include or exclude:\n        read_pair_types = ['InUn', 'InIn', 'ExIn']  # strings have to be sorted alphabetically ('ExIn', not 'InEx')\n    else:\n        read_pair_types = ['InUn', 'InIn']  # strings have to be sorted alphabetically\n    if include_unmapped:\n        read_pair_types.append('UnUn')\n    pair_count_by_type = {read_pair_type : 0 for read_pair_type in read_pair_types}\n    # initialise read_pair tuples\n    # read_pair_seqs = {read_pair_type : tuple() for read_pair_type in read_pair_types}\n    read_pair_seqs = {read_pair_type : [] for read_pair_type in read_pair_types}\n    # initialise read_pair files\n    read_pair_out_fs = defaultdict(lambda: [])\n    if noninterleaved:\n        for read_pair_type in read_pair_types:\n            read_pair_out_fs[read_pair_type].append(getOutFile(outfile, None, read_pair_type + \".1.\" + read_format))\n            read_pair_out_fs[read_pair_type].append(getOutFile(outfile, None, read_pair_type + \".2.\" + read_format))\n    else:\n        for read_pair_type in read_pair_types:\n            read_pair_out_fs[read_pair_type].append(getOutFile(outfile, None, read_pair_type + \".\" + read_format))\n    return pair_count_by_type, read_pair_seqs, read_pair_out_fs\n\ndef print_bam(read_pair_out_fs, read_pair_type, read1, read2):\n    with open(read_pair_out_fs[read_pair_type] + \".txt\", 'a') as fh:\n        fh.write(\"\\t\".join(read1) + \"\\n\")\n        fh.write(\"\\t\".join(read2) + \"\\n\")\n\ndef read_pair_generator(aln, region_string=None):\n    \"\"\"\n    Generate read pairs in a BAM file or within a region string.\n    Reads are added to read_dict until a pair is found.\n    \"\"\"\n    read_dict = defaultdict(lambda: [None, None])\n    for read in aln.fetch(until_eof=True):\n        if read.is_secondary or read.is_supplementary:\n            continue\n        qname = read.query_name\n        if qname not in read_dict:\n            if read.is_read1:\n                read_dict[qname][0] = read\n            else:\n                read_dict[qname][1] = read\n        else:\n            if read.is_read1:\n                yield read, read_dict[qname][1]\n            else:\n                yield read_dict[qname][0], read\n            del read_dict[qname]\n\ndef parseBamForFilter(infile, include_unmapped, noninterleaved, outfile, include, exclude, read_format):\n    '''\n    parse BAM to extract readpairs\n    '''\n\n    pair_count_by_type, seqs_by_type, out_fs_by_type = init_read_pairs(outfile, include_unmapped, noninterleaved, include, exclude, read_format)\n    if include:\n        sequence_to_type_dict = defaultdict(lambda: 'Ex')\n        for incl in include:\n            sequence_to_type_dict[incl] = 'In'\n        sequence_to_type_dict[None] = 'Un'\n    elif exclude:\n        sequence_to_type_dict = defaultdict(lambda: 'In')\n        for excl in exclude:\n            sequence_to_type_dict[excl] = 'Ex'\n        sequence_to_type_dict[None] = 'Un'\n    else:\n        sequence_to_type_dict = defaultdict(lambda: 'In')\n        sequence_to_type_dict[None] = 'Un'\n\n    seen_reads = 0\n    print(BtLog.status_d['26'] % infile)\n    with pysam.AlignmentFile(infile) as aln:\n        with tqdm(total=(aln.mapped + aln.unmapped) / 2, desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n            for read1, read2 in read_pair_generator(aln):\n                seen_reads += 2\n                read_pair_type = \"\".join(sorted([sequence_to_type_dict[read1.reference_name], sequence_to_type_dict[read2.reference_name]]))\n                \n                if read_pair_type in seqs_by_type:\n                    seqs_by_type[read_pair_type].append(get_read_pair_fasta(read1, read_format))\n                    seqs_by_type[read_pair_type].append(get_read_pair_fasta(read2, read_format))\n                    pair_count_by_type[read_pair_type] += 1\n                pbar.update()\n    write_read_pair_seqs(pair_count_by_type, seqs_by_type, out_fs_by_type)\n    # info log\n    info_string = []\n    info_string.append(('Total pairs', \"{:,}\".format(int(seen_reads / 2)), '{0:.1%}'.format(1.00)))\n    for read_pair_type, count in pair_count_by_type.items():\n        info_string.append((read_pair_type + ' pairs', \"{:,}\".format(count), '{0:.1%}'.format(count / int(seen_reads / 2))))\n    info_out_f = getOutFile(outfile, None, \"info.txt\")\n    with open(info_out_f, 'w') as info_fh:\n        print(BtLog.status_d['24'] % info_out_f)\n        info_fh.write(get_table(info_string))\n    return 1\n\ndef get_table(table):\n    col_width = [max(len(x) for x in col) for col in zip(*table)]\n    table_string = []\n    for line in table:\n        table_string.append('| %s | %s | %s |' % (line[0].rjust(col_width[0]), line[1].rjust(col_width[1]), line[2].rjust(col_width[2])))\n    return \"\\n\".join(table_string) + \"\\n\"\n\n\ndef parseCovFromHeader(fasta_type, header):\n    '''\n    Returns the coverage from the header of a FASTA\n    sequence depending on the assembly type\n    '''\n    ASSEMBLY_TYPES = [None, 'spades', 'velvet', 'platanus']\n    if not fasta_type in ASSEMBLY_TYPES:\n        BtLog.error('2', \",\".join(ASSEMBLY_TYPES[1:]))\n    if fasta_type == 'spades':\n        spades_match_re = re.compile(r\"_cov_(\\d+\\.*\\d*)\")\n        #cov = re.findall(r\"_cov_(\\d+\\.*\\d*)\", header)\n        return float(spades_match_re.findall(header)[0])\n    elif fasta_type == 'velvet':\n        return float(header.split(\"_\")[-1])\n    #elif fasta_type == 'abyss' or fasta_type == 'soap':\n    #    temp = header.split(\" \")\n    #    return float(temp[2]/(temp[1]+1-75))\n    elif fasta_type == 'platanus':\n        temp = header.rstrip(\"\\n\").split(\"_\")\n        if len(temp) >= 3:\n            return float(temp[2].replace(\"cov\", \"\")) # scaffold/scaffoldBubble/contig\n        else:\n            return float(temp[1].replace(\"cov\", \"\")) # gapClosed\n    else:\n        pass\n\ndef parseCov(infile, set_of_blobs):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    base_cov_dict = {}\n\n    cov_line_re = re.compile(r\"^(\\S+)\\t(\\d+\\.*\\d*)\\t(\\d+\\.*\\d*)\")\n    reads_total = 0\n    reads_mapped = 0\n    reads_unmapped = 0\n    read_cov_dict = {}\n\n    with tqdm(total=len(set_of_blobs), desc=\"[%] \", ncols=200, unit_scale=True) as pbar: \n        with open(infile) as fh:\n            for line in fh:  \n                if line.startswith('#'):\n                    if line.startswith(\"## Total Reads\"):\n                        reads_total = int(line.split(\" = \")[1])\n                    elif line.startswith(\"## Mapped Reads\"):\n                        reads_mapped = int(line.split(\" = \")[1])\n                    elif line.startswith(\"## Unmapped Reads\"):\n                        reads_unmapped = int(line.split(\" = \")[1])\n                    else:\n                        pass\n                else:\n                    match = cov_line_re.search(line)\n                    if match:\n                        \n                        name, read_cov, base_cov = match.group(1), int(match.group(2)), float(match.group(3))\n                        if name not in set_of_blobs:\n                            print(BtLog.warn_d['2'] % (name))\n                        else:\n                            read_cov_dict[name] = read_cov\n                            base_cov_dict[name] = base_cov\n                    pbar.update()\n                \n        #BtLog.progress(len(set_of_blobs), progress_unit, len(set_of_blobs))\n    return base_cov_dict, reads_total, reads_mapped, reads_unmapped, read_cov_dict\n\ndef checkCas(infile):\n    print(BtLog.status_d['12'])\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    if not (which('clc_mapping_info')):\n        BtLog.error('20')\n    seqs_total_re = re.compile(r\"\\s+Contigs\\s+(\\d+)\")\n    reads_total_re = re.compile(r\"\\s+Reads\\s+(\\d+)\")\n    reads_mapping_re = re.compile(r\"\\s+Mapped reads\\s+(\\d+)\\s+(\\d+.\\d+)\\s+\\%\")\n    seqs_total, reads_total, reads_mapped = 0, 0, 0\n    output = ''\n    command = \"clc_mapping_info -s \" + infile\n    for line in runCmd(command=command):\n        output += line\n    seqs_total = int(seqs_total_re.search(output).group(1))\n    reads_mapped = int(reads_mapping_re.search(output).group(1))\n    reads_total = int(reads_total_re.search(output).group(1))\n    print(BtLog.status_d['11'] % ('{:,}'.format(reads_mapped), '{:,}'.format(reads_total), '{0:.1%}'.format(reads_mapped/reads_total)))\n    return seqs_total, reads_total, reads_mapped\n\ndef parseCas(infile, order_of_blobs):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    seqs_total, reads_total, reads_mapped = checkCas(infile)\n    progress_unit = int(len(order_of_blobs)/100)\n    cas_line_re = re.compile(r\"\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+.\\d{2})\\s+(\\d+)\\s+(\\d+.\\d{2})\")\n    command = \"clc_mapping_info -n \" + infile\n    cov_dict = {}\n    read_cov_dict = {}\n    seqs_parsed = 0\n    if (runCmd(command=command)):\n        for line in runCmd(command=command):\n            cas_line_match = cas_line_re.search(line)\n            if cas_line_match:\n                idx = int(cas_line_match.group(1)) - 1 # -1 because index of contig list starts with zero\n                try:\n                    name = order_of_blobs[idx]\n                    reads = int(cas_line_match.group(3))\n                    cov = float(cas_line_match.group(6))\n                    cov_dict[name] = cov\n                    read_cov_dict[name] = reads\n                    seqs_parsed += 1\n                except:\n                    pass\n                BtLog.progress(seqs_parsed, progress_unit, seqs_total)\n    return cov_dict, reads_total, reads_mapped, read_cov_dict\n\ndef readTax(infile, set_of_blobs):\n    '''\n    If more fields need to be parsed:\n        - add as key-value pairs to hitDict\n    '''\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    #hit_line_re = re.compile(r\"^(\\S+)\\s+(\\d+)[\\;?\\d+]*\\s+(\\d+\\.*\\d*)\") # TEST TEST , if not split it afterwards\n    with open(infile) as fh:\n        for line in fh:\n            #match = hit_line_re.search(line)\n            #if match:\n            col = line.split()\n            try:\n                hitDict = {\n                    'name' : col[0],\n                    'taxId' : col[1], # string because if int, conversion is a nightmare ...\n                    'score' : float(col[2])\n                    }\n            except ValueError:\n                BtLog.error('46', infile, col[2])\n            if hitDict['name'] not in set_of_blobs:\n                #print(BtLog.warn_d['13'] % (hitDict['name'], infile))\n                BtLog.error('19', hitDict['name'], infile)\n            yield hitDict\n                #hitDict = {\n                #    'name' : match.group(1),\n                #    'taxId' : match.group(2), # string because if int, conversion is a nightmare ...\n                #    'score' : float(match.group(3))\n                #    }\n                #if hitDict['name'] not in set_of_blobs:\n                #    print(BtLog.warn_d['13'] % (hitDict['name'], infile))\n                #    #BtLog.error('19', hitDict['name'], infile)\n                #if hitDict['taxId'] == 'N/A':\n                #    BtLog.error('22', infile)\n                #yield hitDict\n\ndef getOutFile(base_file, prefix, suffix):\n    EXTENSIONS = ['.fasta', '.fa', '.fna', '.txt', '.cov', '.out', '.json']\n    out_f, extension = splitext(basename(base_file))\n    if not extension in EXTENSIONS:\n        out_f = '%s%s' % (out_f, extension)\n    if (prefix):\n        if prefix.endswith(\"/\"):\n            out_f = \"%s\" % (join(prefix, out_f))\n        else:\n            out_f = \"%s.%s\" % (prefix, out_f)\n    if (suffix):\n        out_f = \"%s.%s\" % (out_f, suffix)\n    return out_f\n\ndef parseNodesDB(**kwargs):\n    '''\n    Parsing names.dmp and nodes.dmp into the 'nodes_db' dict of dicts that\n    gets JSON'ed into blobtools/data/nodes_db.json if this file\n    does not exist. Nodes_db.json is used if neither \"--names\" and \"--nodes\"\n    nor \"--db\" is specified. If all three are specified and \"--db\" does not\n    exist, then write 'nodes_db' to file specified by \"--db\". If all three\n    are specified and \"--db\" exists, error out.\n    '''\n    nodesDB = {}\n    names_f = kwargs['names']\n    nodes_f = kwargs['nodes']\n    nodesDB_f = kwargs['nodesDB']\n    nodesDB_default = kwargs['nodesDBdefault']\n\n    if (nodes_f and names_f):\n        if not isfile(names_f):\n            BtLog.error('0', names_f)\n        if not isfile(nodes_f):\n            BtLog.error('0', nodes_f)\n        if (nodesDB_f):\n            if isfile(nodesDB_f):\n                BtLog.error('47', nodesDB_f)\n            BtLog.status_d['27'] % (nodesDB_f, nodes_f, names_f)\n        else:\n            print(BtLog.status_d['3'] % (nodes_f, names_f))\n        try:\n            nodesDB = readNamesNodes(names_f, nodes_f)\n        except:\n            BtLog.error('3', nodes_f, names_f)\n    elif (nodesDB_f):\n        if not isfile(nodesDB_f):\n            BtLog.error('0', nodesDB_f)\n        print(BtLog.status_d['4'] % (nodesDB_f))\n        try:\n            nodesDB = readNodesDB(nodesDB_f)\n        except:\n            BtLog.error('27', nodesDB_f)\n    elif (nodesDB_default):\n        if not isfile(nodesDB_default):\n            BtLog.error('28')\n        print(BtLog.status_d['4'] % (nodesDB_default))\n        try:\n            nodesDB = readNodesDB(nodesDB_default)\n        except:\n            BtLog.error('27', nodesDB_default)\n\n    # Write nodesDB if names, nodes, nodesDB all given and nodesDB does not\n    # exist.  Otherwise, write to nodesDB_default if it does not exist, unless\n    # nodesDB given, then do nothing with nodesDB_default.\n    if (nodes_f and names_f and nodesDB_f):\n        print(BtLog.status_d['28'] % nodesDB_f)\n        writeNodesDB(nodesDB, nodesDB_f)\n    elif (not nodesDB_f and not isfile(nodesDB_default)):\n        nodesDB_f = nodesDB_default\n        print(BtLog.status_d['5'] % nodesDB_f)\n        writeNodesDB(nodesDB, nodesDB_f)\n\n    return nodesDB, nodesDB_f\n\ndef readNamesNodes(names_f, nodes_f):\n    nodesDB = {}\n    nodes_count = 0\n    with open(nodes_f) as fh:\n        for line in fh:\n            nodes_col = line.split(\"\\t\")\n            node = {}\n            node_id = nodes_col[0]\n            node['parent'] = nodes_col[2]\n            node['rank'] = nodes_col[4]\n            nodesDB[node_id] = node\n            nodes_count += 1\n    with open(names_f) as fh:\n        for line in fh:\n            names_col = line.split(\"\\t\")\n            if names_col[6] == \"scientific name\":\n                nodesDB[names_col[0]]['name'] = names_col[2]\n    nodesDB['nodes_count'] = nodes_count\n    return nodesDB\n\ndef readNodesDB(nodesDB_f):\n    nodesDB = {}\n    with open(nodesDB_f) as fh:\n        nodes_count = int(fh.readline().lstrip(\"# nodes_count = \").rstrip(\"\\n\"))\n        with tqdm(total=nodes_count, desc=\"[%] \", ncols=200, unit_scale=True) as pbar: \n            for line in fh:\n                if line.startswith(\"#\"):\n                    pass\n                else:\n                    node, rank, name, parent = line.rstrip(\"\\n\").split(\"\\t\")\n                    nodesDB[node] = {'rank' : rank, 'name' : name, 'parent' : parent}\n                    pbar.update()\n    nodesDB['nodes_count'] = nodes_count\n    return nodesDB\n\ndef writeNodesDB(nodesDB, nodesDB_f):\n    nodes_count = nodesDB['nodes_count']\n    with open(nodesDB_f, 'w') as fh:\n        fh.write(\"# nodes_count = %s\\n\" % nodes_count)\n        with tqdm(total=nodes_count, desc=\"[%] \", ncols=200, unit_scale=True) as pbar: \n            for node in nodesDB:\n                if not node == \"nodes_count\":\n                    fh.write(\"%s\\t%s\\t%s\\t%s\\n\" % (node, nodesDB[node]['rank'], nodesDB[node]['name'], nodesDB[node]['parent']))\n                    pbar.update()\n\ndef byteify(input):\n    '''\n    http://stackoverflow.com/a/13105359\n    '''\n    if isinstance(input, dict):\n        return {byteify(key):byteify(value) for key, value in input.items}\n    elif isinstance(input, list):\n        return [byteify(element) for element in input]\n    #elif isinstance(input, unicode):\n    #    return input.encode('utf-8')\n    else:\n        return input\n\n\n\ndef writeJsonGzip(obj, outfile):\n    import json\n    import gzip\n    with gzip.open(outfile, 'wb') as fh:\n        json.dump(obj, fh)\n\ndef writeJson(obj, outfile, indent=0, separators=(',', ': ')):\n    import json\n    with open(outfile, 'w') as fh:\n        #if (indent):\n        #    json.dump(obj, fh, indent=indent, separators=separators)\n        #else:\n        #    json.dump(obj, fh)            \n        json.dump(obj, fh)            \n        #json.dump(obj, fh, indent=4, separators=(',', ': ')) #\n\ndef parseJsonGzip(infile):\n    import json\n    import gzip\n    with gzip.open(infile, 'rb') as fh:\n        #obj = json.loads(fh.read().decode(\"ascii\"))\n        obj = json.loads(fh.read())\n    #return byteify(obj)\n    return obj\n\ndef parseJson(infile):\n    '''http://artem.krylysov.com/blog/2015/09/29/benchmark-python-json-libraries/'''\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    import time\n    start = time.time()\n    json_parser = ''\n    with open(infile, 'r') as fh:\n        print(BtLog.status_d['15'])\n        json_string = fh.read()\n    try:\n        import ujson as json # fastest\n        json_parser = 'ujson'\n        print(BtLog.status_d['16'] % json_parser)\n    except ImportError:\n        try:\n            import simplejson as json # fast\n            json_parser = 'simplejson'\n        except ImportError:\n            import json # default\n            json_parser = 'json'\n        print(BtLog.status_d['17'] % json_parser)\n    try:\n        #obj = json.loads(json_string.decode(\"ascii\"))\n        obj = json.loads(json_string)\n    except ValueError:\n        BtLog.error('37', infile, \"BlobDB\")\n    #data = byteify(obj)\n    data = obj\n    print(BtLog.status_d['20'] % (time.time() - start))\n    return data\n\ndef readYaml(infile):\n    if not isfile(infile):\n        BtLog.error('0', infile)\n    with open(infile) as fh:\n        str = \"\".join(fh.readlines())\n    try:\n        data = yaml.safeload(str)\n    except yaml.YAMLError:\n        BtLog.error('37', infile, \"yaml\")\n    return data\n\nif __name__ == \"__main__\":\n    pass\n"
  },
  {
    "path": "lib/BtLog.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile        : BtLog.py\nAuthor      : Dominik R. Laetsch, dominik.laetsch at gmail dot com\n\"\"\"\n\nfrom __future__ import division\nimport sys\n\ndef error(message, *argv):\n    if argv is None:\n        sys.exit(error_d[message])\n    else:\n        sys.exit(error_d[message] % (argv))\n    #exit(1)  # change to exit with the actual ERROR number (different than 0)\n\nerror_d = {\n    '0': '[ERROR:0]\\t: File %s does not exist.',\n    '1': '[ERROR:1]\\t: Please provide coverage information.',\n    '2': '[ERROR:2]\\t: Assembly type is not valid (%s).',\n    '3': '[ERROR:3]\\t: names.dmp/nodes.dmp (\"--names\", \"--nodes\") could not be read. %s, %s',\n    '4': '[ERROR:4]\\t: BlobDB.parseFasta() - no sequences found. Check FASTA file.',\n    '5': '[ERROR:5]\\t: Sequence header %s is not unique.',\n    '6': '[ERROR:6]\\t: BlobDB.readBam() - sequence header %s in %s was not in FASTA.',\n    '7': '[ERROR:7]\\t: Please add \"samtools\" to you PATH variable.',\n    '8': '[ERROR:8]\\t: Unsupported taxrule \"%s\".',\n    '9': '[ERROR:9]\\t: Unsupported taxonomic rank \"%s\".',\n    '10': '[ERROR:10]\\t: Unsupported output format \"%s\".',\n    '11': '[ERROR:11]\\t: Taxrule \"%s\" was not computed for this BlobDb. Available taxrule(s) : %s.',\n    '12': '[ERROR:12]\\t: Please provide an output file.',\n    '13': '[ERROR:13]\\t: %s does not appear to be a comma-separated list or a file.',\n    '14': '[ERROR:14]\\t: Unsupported sort order for plotting : %s. Must be either \"span\" or \"count\".',\n    '15': '[ERROR:15]\\t: Unsupported histogram type for plotting : %s. Must be either \"span\" or \"count\".',\n    '16': '[ERROR:16]\\t: Group \"%s\" was specified in multiple clusters.',\n    '17': '[ERROR:17]\\t: Label could not be parsed from \"%s\".',\n    '18': '[ERROR:18]\\t: Please provide a tax file in BLAST format.',\n    '19': '[ERROR:19]\\t: Sequence %s in file %s is not part of the assembly.',\n    '20': '[ERROR:20]\\t: Please add \"clc_mapping_info\" to your PATH variable.',\n    '21': '[ERROR:21]\\t: Refcov file %s does not seem to have the right format.',\n    '23': '[ERROR:23]\\t: Catcolour file %s does not seem to have the right format.',\n    '24': '[ERROR:24]\\t: Catcolour file incompatible with c-index colouring.',\n    '25': '[ERROR:25]\\t: COV file %s does not seem to have the right format.',\n    '26': '[ERROR:26]\\t: TaxID must be integer.',\n    '27': '[ERROR:27]\\t: nodesDB (\"--db\") %s could not be read.',\n    '28': '[ERROR:28]\\t: Please specify \"--names\" and \"--nodes\", or \"--db\"',\n    '29': '[ERROR:29]\\t: No mapping reads found in %s',\n    '30': '[ERROR:30]\\t: The module docopt is not installed. Please install it to run blobtools\\n\\tpip install docopt',\n    '31': '[ERROR:31]\\t: Please specify a read mapping file (BAM/SAM/CAS)',\n    '32': '[ERROR:32]\\t: Choose either --cumulative or --multiplot',\n    '33': '[ERROR:33] : CovLib(s) not found. The available covlibs are: \\n%s',\n    '34': '[ERROR:34] : Invalid plot type : %s',\n    '35': '[ERROR:35] : Directory %s could not be created',\n    '36': '[ERROR:36] : View %s could not be created',\n    '37': '[ERROR:37] : %s does not seem to be a valid %s file',\n    '38': '[ERROR:38] : %s is not an integer',\n    '39': '[ERROR:39] : Please specify a taxid file (mapping subjects to taxids)',\n    '40': '[ERROR:40] : CovLib \\'%s\\' not specified in refcov file',\n    '41': '[ERROR:41] : Please specify either a mapping file or a taxID.',\n    '42': '[ERROR:42] : SubjectID %s not found in mapping file %s.',\n    '43': '[ERROR:43] : %s could not be found.',\n    '44': '[ERROR:44] : Please specify integers for --map_col_sseqid and --map_col_taxid.',\n    '45': '[ERROR:45] : Both --min_score and --min_diff must be numbers.',\n    '46': '[ERROR:46] : Score in %s must be a float, not \\'%s\\'.',\n    '47': '[ERROR:47] : Cannot create new \"--db\" file from \"--names\", \"--nodes\", \"--db\" file exists. %s'\n}\n\nwarn_d = {\n    '0': '[-] No tax files specified.',\n    '1': '[-] %s not in colour file %s ...',\n    '2': '[-] %s is not part of the assembly',\n    '3': '\\n[-] Based on samtools flagstat: expected %s reads, %s reads were parsed',\n    '4': '[-] No coverage data found in %s',\n    '5': '[-] Hit for sequence %s in tax file %s has multiple taxIds, only first one is used.',\n    '6': '[-] Sum of coverage in cov lib %s is 0.0. Please ignore this warning if \"--no_base_cov\" was specified.',\n    '7': '[-] No taxonomy information found.',\n    '8': '[-] Duplicated sequences found :\\n\\t\\t\\t%s',\n    '9': '[-] Taxrule \"%s\" was not computed for this BlobDb. Available taxrule(s) : %s. Will proceed without taxonomic annotation ...',\n    '10': '[-] Line %s: sequence \"%s\" already has TaxID \"%s\". Skipped. (use --force to overwrite)',\n    '11': '\\n[-] The BAM file appears to be truncated.',\n    '12': '[-] sseqid %s not found in ID-to-taxID mapping file %s.',\n    '13': '[-] Sequence %s in file %s is not part of the assembly.'\n}\nstatus_d = {\n    '0': '[+] Nothing to be done. %s',\n    '1': '[+] Parsing %s - %s',\n    '2': '[+] Done',\n    '3': '[+] Creating nodesDB from %s and %s',\n    '4': '[+] names.dmp/nodes.dmp not specified. Retrieving nodesDB from %s',\n    '5': '[+] Store nodesDB in default location %s',\n    '6': '[+] Computing taxonomy using taxrule(s) %s',\n    '7': '[+] Generating BlobDB and writing to file %s',\n    '8': '[+] Plotting %s',\n    '9': '[+] Reading BlobDB %s',\n    '10': '[+] \\tChecking with \\'samtools flagstat\\'',\n    '11': '[+] \\tMapping reads = %s, total reads = %s (mapping rate = %s)',\n    '12': '[+] \\tChecking with \\'clc_mapping_info\\'',\n    '13': '[+] \\tWriting %s',\n    '14': '[+] Preparing view(s) ...',\n    '15': '[+] \\tLoading BlobDB into memory ...',\n    '16': '[+] \\tDeserialising BlobDB (using \\'%s\\' module) (this may take a while) ...',\n    '17': '[+] \\tDeserialising BlobDB (using \\'%s\\' module) (this may take a while, consider installing the \\'ujson\\' module) ...',\n    '18': '[+] Extracting data for plots ...',\n    '19': '[+] Writing output ...',\n    '20': '[+] \\tFinished in %ss',\n    '22': '[+] Filtering %s ...',\n    '23': '[+] Filtered %s (pairs=%s) ...',\n    '24': '[+] Writing %s',\n    '25': '[+] Gzip\\'ing %s',\n    '26': '[+] Reading %s',\n    '27': '[+] Creating nodesDB %s from %s and %s',\n    '28': '[+] Store nodesDB in %s',\n}\n\ninfo_d = {\n    '0': '[I]\\t%s : sequences = %s, span = %s MB, N50 = %s nt'\n    }\n\nif __name__ == \"__main__\":\n    pass\n"
  },
  {
    "path": "lib/BtPlot.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile        : BtPlot.py\nAuthor      : Dominik R. Laetsch, dominik.laetsch at gmail dot com\n\"\"\"\n\nfrom numpy import array, arange, logspace, mean, std\nimport math\nimport lib.BtLog as BtLog\nimport lib.BtTax as BtTax\nimport matplotlib as mat\nfrom matplotlib import cm\nfrom matplotlib.ticker import NullFormatter, MultipleLocator, AutoMinorLocator\nfrom matplotlib.lines import Line2D\nfrom matplotlib.colors import rgb2hex\nmat.use('agg')\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\n#from itertools import izip\n\nmat.rcParams.update({'font.size': 36})\nmat.rcParams['xtick.major.pad'] = '8'\nmat.rcParams['ytick.major.pad'] = '8'\nmat.rcParams['lines.antialiased'] = True\n\nLEGEND_FONTSIZE = 20\nCOLOURMAP = \"tab10\" # \"Set1\", \"Paired\", \"Set2\", \"Spectral\"\n#GREY, BGGREY, WHITE, DGREY = '#d3d3d3', '#F0F0F5', '#ffffff', '#4d4d4d'\nGREY, BGGREY, BGCOLOUR, WHITE, DGREY = '#d3d3d3', '#F0F0F5', '#F8F8F8', '#ffffff', '#4d4d4d'\nnullfmt = NullFormatter()\n\ndef n50(list_of_lengths):\n    total_span = 0\n    sorted_list_of_lengths=sorted(list_of_lengths, reverse=True)\n    for contig_length in sorted_list_of_lengths:\n        total_span += contig_length\n    teoN50 = total_span/2.0\n    running_sum = 0\n    N50 = 0\n    for contig_length in sorted_list_of_lengths:\n        running_sum += contig_length\n        if teoN50 <= running_sum:\n            N50 = contig_length\n            break\n    return N50\n\ndef getSortedGroups(data_dict, sort_order, sort_first=()):\n    \"\"\" Returns list of sorted groups based on span or count. \"\"\"\n    sorted_groups = []\n    visible_by_group = {}\n    if sort_order == 'span':\n        visible_by_group = {group: _dict['span_visible'] for group, _dict in data_dict.items()}\n        #sorted_groups = sorted(data_dict, key = lambda x : data_dict[x]['span_visible'] if data_dict[x]['span_visible'] > 0 else 0, reverse=True)\n        #sorted_groups = sorted(data_dict, key = lambda x : max(data_dict[x]['span_visible'], 0), reverse=True)\n    elif sort_order == 'count':\n        visible_by_group = {group: _dict['count_visible'] for group, _dict in data_dict.items()}\n        #sorted_groups = sorted(data_dict, key = lambda x : data_dict[x]['count_visible'] if data_dict[x]['count_visible'] > 0 else 0, reverse=True)\n        #sorted_groups = sorted(data_dict, key = lambda x : max(data_dict[x]['count_visible'], 0), reverse=True)\n    else:\n        pass\n    for group, visible in sorted(visible_by_group.items(), key=itemgetter(1), reverse=True):\n        if visible > 0:\n            sorted_groups.append(group)\n\n    # Now shuffle the stuff in sort_first to the front\n    for sf in reversed(sort_first):\n        try:\n            sorted_groups.remove(sf)\n            sorted_groups.insert(0, sf)\n        except ValueError:\n            #It wasn't in the list then. No probs.\n            pass\n    return sorted_groups\n\ndef generateColourDict(colour_groups, groups):\n    cmap = [rgb2hex(rgb) for rgb in cm.get_cmap(name=COLOURMAP).colors]\n    # remove green\n    del cmap[2]\n    # remove brown\n    del cmap[4]\n    colour_d = {}\n    idx_delay = 0\n    for idx, group in enumerate(groups):\n        if group in colour_groups:\n            #print(group,)\n            if group == 'no-hit' or group == 'None':\n                colour_d[group] = GREY\n                #print(\"GREY\")\n                idx_delay -= 1\n            else:\n                colour_d[group] = cmap[idx+idx_delay]\n                #print(colour_d[group], idx+idx_delay)\n    return colour_d\n\ndef set_canvas():\n    left, width = 0.1, 0.60\n    bottom, height = 0.1, 0.60\n    bottom_h = left_h = left+width+0.02\n    rect_scatter = [left, bottom, width, height]\n    rect_histx = [left, bottom_h, width, 0.2]\n    rect_histy = [left_h, bottom, 0.2, height]\n    rect_legend = [left_h, bottom_h, 0.2, 0.2]\n    return rect_scatter, rect_histx, rect_histy, rect_legend\n\ndef set_format_scatterplot(axScatter, **kwargs):\n    min_x, max_x = None, None\n    min_y, max_y = None, None\n    if kwargs['plot'] == 'blobplot':\n        min_x, max_x = 0, 1\n        major_xticks = MultipleLocator(0.2)\n        minor_xticks = AutoMinorLocator(20)\n        min_y, max_y = kwargs['min_cov']*0.1, kwargs['max_cov']+100\n        axScatter.set_yscale('log')\n        axScatter.set_xscale('linear')\n        axScatter.xaxis.set_major_locator(major_xticks)\n        axScatter.xaxis.set_minor_locator(minor_xticks)\n    elif kwargs['plot'] == 'covplot':\n        min_x, max_x = kwargs['min_cov']*0.1, kwargs['max_cov']+100\n        min_y, max_y = kwargs['min_cov']*0.1, kwargs['max_cov']+100\n        axScatter.set_yscale('log')\n        axScatter.set_xscale('log')\n    else:\n        BtLog.error('34' % kwargs['plot'])\n    axScatter.set_xlim( (min_x, max_x) )\n    axScatter.set_ylim( (min_y, max_y) ) # This sets the max-Coverage so that all libraries + sum are at the same scale\n    axScatter.grid(True, which=\"major\", lw=2., color=BGGREY, linestyle='-')\n    axScatter.set_axisbelow(True)\n    axScatter.xaxis.labelpad = 20\n    axScatter.yaxis.labelpad = 20\n    axScatter.yaxis.get_major_ticks()[0].label1.set_visible(False)\n    axScatter.tick_params(axis='both', which='both', direction='out')\n    return axScatter\n\ndef set_format_hist_x(axHistx, axScatter):\n    axHistx.set_xlim(axScatter.get_xlim())\n    axHistx.set_xscale(axScatter.get_xscale())\n    axHistx.grid(True, which=\"major\", lw=2., color=BGGREY, linestyle='-')\n    axHistx.xaxis.set_major_locator(axScatter.xaxis.get_major_locator()) # no labels since redundant\n    axHistx.xaxis.set_minor_locator(axScatter.xaxis.get_minor_locator())\n    axHistx.xaxis.set_major_formatter(nullfmt) # no labels since redundant\n    axHistx.set_axisbelow(True)\n    axHistx.yaxis.labelpad = 20\n    axHistx.tick_params(axis='both', which='both', direction='out')\n    return axHistx\n\ndef set_format_hist_y(axHisty, axScatter):\n    axHisty.set_ylim(axScatter.get_ylim())\n    axHisty.set_yscale(axScatter.get_yscale())\n    axHisty.grid(True, which=\"major\", lw=2., color=BGGREY, linestyle='-')\n    axHisty.yaxis.set_major_formatter(nullfmt) # no labels since redundant\n    axHisty.set_axisbelow(True)\n    axHisty.xaxis.labelpad = 20\n    axHisty.tick_params(axis='both', which='both', direction='out')\n    return axHisty\n\ndef get_ref_label(max_length, max_marker_size, fraction):\n    length = int(math.ceil(fraction * max_length / 100.0)) * 100\n    string = \"%snt\" % \"{:,}\".format(length)\n    markersize = length/max_length * max_marker_size\n    return length, string, markersize\n\ndef plot_ref_legend(axScatter, max_length, max_marker_size, ignore_contig_length):\n    if not (ignore_contig_length):\n        ref1_length, ref1_string, ref1_markersize = get_ref_label(max_length, max_marker_size, 0.05)\n        ref2_length, ref2_string, ref2_markersize = get_ref_label(max_length, max_marker_size, 0.1)\n        ref3_length, ref3_string, ref3_markersize = get_ref_label(max_length, max_marker_size, 0.25)\n        # markersize in scatter is in \"points^2\", markersize in Line2D is in \"points\" ... that's why we need math.sqrt()\n        ref_1 = (Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=math.sqrt(ref1_markersize), markeredgecolor=WHITE, markerfacecolor=GREY))\n        ref_2 = (Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=math.sqrt(ref2_markersize), markeredgecolor=WHITE, markerfacecolor=GREY))\n        ref_3 = (Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=math.sqrt(ref3_markersize), markeredgecolor=WHITE, markerfacecolor=GREY))\n        axScatter.legend([ref_1,ref_2,ref_3], [ref1_string, ref2_string, ref3_string], numpoints=1, ncol = 3, loc = 8, fontsize=LEGEND_FONTSIZE, borderpad=1.2, labelspacing=1.8, handlelength=1, handletextpad=1)\n\ndef plot_legend(fig, axLegend, out_f, legend_flag, format, cumulative_flag):\n    if (legend_flag):\n        extent = axLegend.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n        legend_out_f = '%s.%s.%s' % (out_f, \"legend\", format)\n        print(BtLog.status_d['8'] % legend_out_f)\n        fig.savefig('%s' % legend_out_f, bbox_inches=extent, format=format)\n        fig.delaxes(axLegend)\n    return fig\n\ndef check_input(args):\n    rank = args['--rank']\n    c_index = args['--cindex']\n    multiplot = args['--multiplot']\n    sort_order = args['--sort']\n    sort_first = args['--sort_first']\n    taxrule = args['--taxrule']\n    hist_type = args['--hist']\n    catcolour_f = args['--catcolour']\n    cumulative_flag = args['--cumulative']\n\n    #Convert sort_first to a list\n    if sort_first:\n        args['--sort_first'] = sort_first.split(',')\n    else:\n        args['--sort_first'] = ()\n\n    if 'blobplot' in args or 'covplot' in args:\n        # Are ranks sane ?\n        if rank not in BtTax.RANKS:\n            BtLog.error('9', rank)\n        # is taxrule provided?\n        if taxrule not in BtTax.TAXRULES:\n            BtLog.error('8', taxrule)\n        # Are sort_order and hist_type sane?\n        if not sort_order in ['span', 'count']:\n            BtLog.error('14', sort_order)\n        if not hist_type in ['span', 'count']:\n            BtLog.error('15', hist_type)\n        if (catcolour_f) and (c_index):\n            BtLog.error('24')\n        if (cumulative_flag) and (multiplot):\n            BtLog.error('32')\n    return args\n\nclass PlotObj():\n    def __init__(self, data_dict, cov_lib_dict, cov_lib_selection, plot_type, sort_first=()):\n        self.labels = {'all'}\n        self.plot = plot_type # type of plot\n        self.group_labels = {}\n        self.cov_lib_dict = cov_lib_dict\n        self.cov_libs = self.subselect_cov_libs(cov_lib_dict, cov_lib_selection)\n        self.cov_libs_total_reads_dict = self.get_cov_libs_total_reads_dict(cov_lib_dict)\n        self.cov_libs_mapped_reads_dict = self.get_cov_libs_mapped_reads_dict(cov_lib_dict)\n        self.data_dict = data_dict\n        self.stats = {}\n        self.exclude_groups = []\n        self.version = None\n        self.colours = {}\n        self.group_order = []\n        self.plot_order = []\n        self.sort_first = sort_first\n        self.min_cov = 0.1\n        self.max_cov = 0.0\n        self.out_f = ''\n        self.no_title = ''\n        self.max_group_plot = 0\n        self.format = ''\n        self.legend_flag = ''\n        self.cumulative_flag = ''\n        self.dpi = 200\n        self.scatter_size = (35, 35)\n        self.readcov_size = (30, 10)\n        self.cov_y_dict = {}\n        self.xlabel = None\n        self.ylabel = None\n\n        self.refcov_dict = {}\n\n    def subselect_cov_libs(self, cov_lib_dict, cov_lib_selection):\n        selected_cov_libs = []\n        cov_lib_selection_error = 0\n        if (cov_lib_selection):\n            if cov_lib_selection == 'covsum':\n                selected_cov_libs.append('covsum')\n            elif \",\" in cov_lib_selection:\n                selected_cov_libs = cov_lib_selection.split(\",\")\n                if not set(selected_cov_libs).issubset(set(cov_lib_dict.keys())):\n                    cov_lib_selection_error = 1\n            else:\n                selected_cov_libs.append(cov_lib_selection)\n                if not cov_lib_selection in cov_lib_dict:\n                    cov_lib_selection_error = 1\n        else:\n            selected_cov_libs = cov_lib_dict.keys()\n        if cov_lib_selection_error:\n            covlib_string = []\n            for covlib in cov_lib_dict:\n                cov_lib_f = cov_lib_dict[covlib]['f']\n                if not cov_lib_f:\n                    cov_lib_f = \"sum of coverages from all covlibs\"\n                covlib_string.append(\"\\t\\t%s : %s\" % (covlib, cov_lib_f))\n            BtLog.error('33', \"\\n\".join(covlib_string))\n        return selected_cov_libs\n\n    def get_cov_libs_total_reads_dict(self, cov_lib_dict):\n        return { x : cov_lib_dict[x]['reads_total'] for x in self.cov_libs}\n\n    def get_cov_libs_mapped_reads_dict(self, cov_lib_dict):\n        return { x : cov_lib_dict[x]['reads_mapped'] for x in self.cov_libs}\n\n    def get_stats_for_group(self, group):\n        stats = { 'name' : group,\n                  'count_total' : \"{:,}\".format(self.stats[group]['count']),\n                  'count_visible' : \"{:,}\".format(self.stats[group]['count_visible']),\n                  'count_visible_perc' : '{0:.1%}'.format(self.stats[group]['count_visible']/self.stats[group]['count']) if self.stats[group]['count'] > 0 else '{0:.1%}'.format(0.0),\n                  'span_visible' : \"{:,}\".format(self.stats[group]['span_visible']),\n                  'span_total' : \"{:,}\".format(self.stats[group]['span']),\n                  'span_visible_perc' : '{0:.1%}'.format(self.stats[group]['span_visible']/self.stats[group]['span']) if self.stats[group]['span'] > 0 else '{0:.1%}'.format(0.0),\n                  'colour' : str(self.colours[group] if group in self.colours else None),\n                  'n50' : \"{:,}\".format(self.stats[group]['n50']),\n                  'gc_mean' : \"{0:.2}\".format(self.stats[group]['gc_mean']),\n                  'gc_std' : \"{0:.2}\".format(self.stats[group]['gc_std']),\n                  'cov_mean' : {cov_lib : \"{0:0.1f}\".format(cov_mean) for cov_lib, cov_mean in self.stats[group]['cov_mean'].items()},\n                  'cov_std' : {cov_lib : \"{0:0.1f}\".format(cov_std) for cov_lib, cov_std in self.stats[group]['cov_std'].items()},\n                  'reads_mapped' : {cov_lib : \"{:,}\".format(reads_mapped) for cov_lib, reads_mapped in self.stats[group]['reads_mapped'].items()},\n                  'reads_mapped_perc' : {cov_lib : '{0:.1%}'.format(reads_mapped_perc) for cov_lib, reads_mapped_perc in self.stats[group]['reads_mapped_perc'].items()}\n                }\n        return stats\n\n    def write_stats(self, out_f):\n        stats = []\n        stats.append(self.get_stats_for_group('all'))\n        for group in self.plot_order: # group/label/other that has been plotted\n            stats.append(self.get_stats_for_group(group))\n            if not group in self.group_labels: # it is either a label or \"other\"\n                label = group\n                for g, labels in self.group_labels.items():\n                    if label in labels:\n                        stats.append(self.get_stats_for_group(g))\n        output = []\n        output.append('## %s' % self.version)\n        for cov_lib, cov_lib_dict in self.cov_lib_dict.items():\n           if cov_lib in self.cov_libs:\n                output.append(\"## %s=%s\" % (cov_lib, cov_lib_dict['f']))\n        fields = ['name', 'colour', 'count_visible', 'count_visible_perc', 'span_visible','span_visible_perc', 'n50', 'gc_mean', 'gc_std']\n        header = [field for field in fields]\n        for cov_lib in sorted(self.cov_libs):\n            header.append('%s_mean' % cov_lib)\n            header.append('%s_std' % cov_lib)\n            header.append('%s_read_map' % cov_lib)\n            header.append('%s_read_map_p' % cov_lib)\n        output.append('# %s' % \"\\t\".join(header))\n        for stat in stats:\n            line = []\n            for field in fields:\n                line.append(stat[field])\n            for cov_lib in sorted(self.cov_libs):\n                line.append(stat['cov_mean'][cov_lib])\n                line.append(stat['cov_std'][cov_lib])\n                line.append(stat['reads_mapped'][cov_lib])\n                line.append(stat['reads_mapped_perc'][cov_lib])\n            output.append(\"%s\" % \"\\t\".join(line))\n        out_f = \"%s.stats.txt\" % out_f\n        with open(out_f, 'w') as fh:\n            print(BtLog.status_d['24'] % (\"%s\" % out_f))\n            fh.write(\"\\n\".join(output))\n\n    def compute_stats(self):\n        stats = {}\n        for label in self.labels:\n            stats[label] = {\n                            'name' : [],\n                            'gc' : [],\n                            'length': [],\n                            'covs' : {cov_lib : [] for cov_lib in self.cov_libs},\n                            'cov_mean' : {cov_lib : 0.0 for cov_lib in self.cov_libs},\n                            'cov_std' : {cov_lib : 0.0 for cov_lib in self.cov_libs},\n                            'reads_mapped' : {cov_lib : 0 for cov_lib in self.cov_libs},\n                            'reads_mapped_perc' : {cov_lib: 0.0 for cov_lib in self.cov_libs},\n                            'n50' : 0,\n                            'gc_mean' : 0.0,\n                            'gc_std' : 0.0,\n                            'groups' : set(),\n                            'count' : 0,\n                            'span' : 0,\n                            'count_visible' : 0,\n                            'span_visible' : 0,\n                            'count_hidden' : 0,\n                            'span_hidden' : 0\n                            }\n\n        for group, labels in self.group_labels.items():\n            for label in labels:\n                stats[label]['name'] = stats[label]['name'] + self.data_dict[group]['name']\n                stats[label]['groups'].add(group)\n                stats[label]['gc'] = stats[label]['gc'] + self.data_dict[group]['gc']\n                stats[label]['length'] = stats[label]['length'] + self.data_dict[group]['length']\n                stats[label]['count'] += self.data_dict[group]['count']\n                stats[label]['span'] += self.data_dict[group]['span']\n                stats[label]['count_visible'] += self.data_dict[group]['count_visible']\n                stats[label]['count_hidden'] += self.data_dict[group]['count_hidden']\n                stats[label]['span_visible'] += self.data_dict[group]['span_visible']\n                stats[label]['span_hidden'] += self.data_dict[group]['span_hidden']\n                for cov_lib in self.cov_libs:\n                    stats[label]['covs'][cov_lib] = stats[label]['covs'][cov_lib] + self.data_dict[group]['covs'][cov_lib]\n                    stats[label]['reads_mapped'][cov_lib] += self.data_dict[group]['reads_mapped'][cov_lib]\n        for label in stats:\n            stats[label]['gc_mean'] = mean(array(stats[label]['gc'])) if stats[label]['count_visible'] > 0.0 else 0.0\n            stats[label]['gc_std'] = std(array(stats[label]['gc'])) if stats[label]['count_visible'] > 0.0 else 0.0\n            stats[label]['n50'] = n50(stats[label]['length']) if stats[label]['count_visible'] > 0.0 else 0.0\n            for cov_lib in self.cov_libs:\n                stats[label]['cov_mean'][cov_lib] = mean(array(stats[label]['covs'][cov_lib])) if stats[label]['count_visible'] > 0.0 else 0.0\n                stats[label]['cov_std'][cov_lib] = std(array(stats[label]['covs'][cov_lib])) if stats[label]['count_visible'] > 0.0 else 0.0\n                if self.cov_libs_total_reads_dict[cov_lib]:\n                    stats[label]['reads_mapped_perc'][cov_lib] = stats[label]['reads_mapped'][cov_lib]/self.cov_libs_total_reads_dict[cov_lib]\n        self.stats = stats\n\n    def relabel_and_colour(self, colour_dict, user_labels):\n        #print(user_labels)\n        groups = self.group_order[0:self.max_group_plot]\n        if (colour_dict):\n            groups_not_in_colour_dict = set(groups) - set(colour_dict.keys())\n            for _group in groups_not_in_colour_dict:\n                colour_dict[_group] = WHITE\n        else:\n            #print(groups)\n            colour_groups = list(set([_group if not (_group in user_labels) else user_labels[_group] for _group in groups]))\n            #print(colour_groups)\n            colour_dict = generateColourDict(colour_groups, groups)\n            #print(colour_dict)\n        for idx, group in enumerate(self.group_order):\n            if group in self.exclude_groups:\n                pass\n            elif group in user_labels:\n                #print(group, \"in user_labels\")\n                label = user_labels[group]\n                #print(label)\n                self.group_labels[group].add(label)\n                #print(self.group_labels[group])\n                self.group_labels[group].add(group)\n                #print(self.group_labels[group])\n                self.colours[label] = colour_dict[user_labels[group]]\n                if label not in self.plot_order:\n                    self.plot_order.append(label)\n            elif group in colour_dict:\n                self.group_labels[group].add(group)\n                self.colours[group] = colour_dict[group]\n                self.plot_order.append(group)\n            elif idx > self.max_group_plot:\n                self.group_labels[group].add('other')\n                self.group_labels[group].add(group)\n                self.colours['other'] = WHITE\n                self.labels.add('other')\n            else:\n                self.group_labels[group].add('other')\n                self.group_labels[group].add(group)\n                self.colours['other'] = WHITE\n                self.labels.add('other')\n            self.group_labels[group].add('all')\n        if 'other' in self.labels:\n            if 'other' in self.sort_first:\n                #Slightly tricky. We need to insert 'other' after the location of\n                #the last thing before 'other' in self.sort_first that appears in\n                #self.plot_order, or else put it at the start.\n                ipos = 0\n                for l in reversed(self.sort_first[:self.sort_first.index('other')]):\n                    try:\n                        ipos = self.plot_order.index(l) + 1\n                        break\n                    except ValueError:\n                        #keep looking\n                        pass\n                self.plot_order.insert(ipos, 'other')\n            else:\n                # 'other' gets plotted last by default\n                self.plot_order.append('other')\n\n\n    def setupPlot(self, plot):\n        if plot == 'blobplot' or plot == 'covplot':\n            rect_scatter, rect_histx, rect_histy, rect_legend = set_canvas()\n            # Setting up plots and axes\n            fig = plt.figure(1, figsize=self.scatter_size, dpi=self.dpi)\n            try:\n                axScatter = plt.axes(rect_scatter, facecolor=BGCOLOUR)\n            except AttributeError:\n                axScatter = plt.axes(rect_scatter, axisbg=BGCOLOUR)\n            axScatter = set_format_scatterplot(axScatter, min_cov=self.min_cov, max_cov=self.max_cov, plot=plot)\n            axScatter.set_xlabel(self.xlabel)\n            axScatter.set_ylabel(self.ylabel)\n            try:\n                axHistx = plt.axes(rect_histx, facecolor=BGCOLOUR)\n                axHisty = plt.axes(rect_histy, facecolor=BGCOLOUR)\n            except AttributeError:\n                axHistx = plt.axes(rect_histx, axisbg=BGCOLOUR)\n                axHisty = plt.axes(rect_histy, axisbg=BGCOLOUR)\n            axHistx = set_format_hist_x(axHistx, axScatter)\n            axHisty = set_format_hist_y(axHisty, axScatter)\n            if self.hist_type == \"span\":\n                axHistx.set_ylabel(\"Span (kb)\")\n                axHisty.set_xlabel(\"Span (kb)\", rotation='horizontal')\n            else:\n                axHistx.set_ylabel(\"Count\")\n                axHisty.set_xlabel(\"Count\", rotation='horizontal')\n            for xtick in axHisty.get_xticklabels(): # rotate text for ticks in cov histogram\n                xtick.set_rotation(270)\n            try:\n                axLegend = plt.axes(rect_legend, facecolor=WHITE)\n            except AttributeError:\n                axLegend = plt.axes(rect_legend, axisbg=WHITE)\n            axLegend.xaxis.set_major_locator(plt.NullLocator())\n            axLegend.xaxis.set_major_formatter(nullfmt)\n            axLegend.yaxis.set_major_locator(plt.NullLocator())\n            axLegend.yaxis.set_major_formatter(nullfmt)\n            top_bins, right_bins = None, None\n            if plot == 'blobplot':\n                top_bins = arange(0, 1, 0.01)\n                if self.min_cov >= 1:\n                    right_bins = logspace(0, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                elif self.min_cov >= 0.1:\n                    right_bins = logspace(-1, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                else:\n                    right_bins = logspace(-2, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n            elif plot == 'covplot':\n                if self.min_cov >= 1:\n                    top_bins = logspace(0, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                    right_bins = logspace(0, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                elif self.min_cov >= 0.1:\n                    top_bins = logspace(-1, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                    right_bins = logspace(-1, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                else:\n                    top_bins = logspace(-2, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n                    right_bins = logspace(-2, (int(math.log(self.max_cov)) + 1), 200, base=10.0)\n            else:\n                pass\n            return fig, axScatter, axHistx, axHisty, axLegend, top_bins, right_bins\n        elif plot == 'readcov':\n            main_columns = 2\n            if (self.refcov_dict):\n                main_columns += 2\n            group_columns = len(self.plot_order)\n            fig = plt.figure(1, figsize=self.readcov_size, dpi=self.dpi)\n            gs = mat.gridspec.GridSpec(1, 2, width_ratios=[main_columns, group_columns])\n\n            ax_main = plt.subplot(gs[0])\n            try:\n                ax_main.set_facecolor(WHITE)\n            except AttributeError:\n                ax_main.set_color(WHITE)\n            ax_main.set_ylim(0, 1.1)\n            ax_main.set_yticklabels(['{:.0f}%'.format(x*100) for x in ax_main.get_yticks()])\n            ax_main.grid(True,  axis='y', which=\"major\", lw=2., color=BGGREY, linestyle='--')\n\n            ax_group = plt.subplot(gs[1])\n            try:\n                ax_group.set_facecolor(WHITE)\n            except AttributeError:\n                ax_group.set_color(WHITE)\n            ax_group.set_ylim(0, 1.1)\n            ax_group.set_yticklabels(['{:.0f}%'.format(x*100) for x in ax_group.get_yticks()])\n            ax_group.grid(True,  axis='y', which=\"major\", lw=2., color=BGGREY, linestyle='--')\n\n            x_pos_main = arange(main_columns)\n            x_pos_group = arange(len(self.plot_order))\n            return fig, ax_main, ax_group, x_pos_main, x_pos_group\n        else:\n            return None\n\n    def plotBar(self, cov_lib, out_f):\n        fig, ax_main, ax_group, x_pos_main, x_pos_group = self.setupPlot('readcov')\n        ax_main_data = {'labels' : [], 'values' : [], 'colours' : [] }\n        ax_group_data = {'labels' : [], 'values' : [], 'colours' : [] }\n        reads_total = self.cov_libs_total_reads_dict[cov_lib]\n        reads_mapped = self.stats['all']['reads_mapped'][cov_lib]\n        reads_unmapped = reads_total - self.stats['all']['reads_mapped'][cov_lib]\n        ax_main_data['labels'].append('Unmapped (assembly)')\n        ax_main_data['values'].append(reads_unmapped/reads_total)\n        ax_main_data['colours'].append(DGREY)\n        ax_main_data['labels'].append('Mapped (assembly)')\n        ax_main_data['values'].append(reads_mapped/reads_total)\n        ax_main_data['colours'].append(DGREY)\n        if (self.refcov_dict):\n            if cov_lib in self.refcov_dict:\n                reads_total_ref = self.refcov_dict[cov_lib]['reads_total']\n                reads_mapped_ref = self.refcov_dict[cov_lib]['reads_mapped']\n                reads_unmapped_ref = reads_total_ref - reads_mapped_ref\n                ax_main_data['labels'].append('Unmapped (ref)')\n                ax_main_data['values'].append(reads_unmapped_ref/reads_total_ref)\n                ax_main_data['colours'].append(DGREY)\n                ax_main_data['labels'].append('Mapped (ref)')\n                ax_main_data['values'].append(reads_mapped_ref/reads_total_ref)\n                ax_main_data['colours'].append(DGREY)\n            else:\n                BtLog.error('40', cov_lib)\n\n        # mapped plotted groups\n        for group in self.plot_order:\n           ax_group_data['labels'].append(group)\n           ax_group_data['values'].append(self.stats[group]['reads_mapped_perc'][cov_lib])\n           ax_group_data['colours'].append(self.colours[group])\n        rect_group = ax_group.bar(x_pos_group, ax_group_data['values'], width = 0.5, tick_label=ax_group_data['labels'], align='center', color = ax_group_data['colours'])\n        for rect_g in rect_group:\n            height_g = float(rect_g.get_height())\n            ax_group.text(rect_g.get_x() + rect_g.get_width()/2., 0.005 + height_g, '{:.2f}%'.format(height_g*100), ha='center', va='bottom', fontsize=LEGEND_FONTSIZE)\n        rect_main = ax_main.bar(x_pos_main, ax_main_data['values'], width = 0.5, tick_label=ax_main_data['labels'], align='center', color = ax_main_data['colours'])\n        for rect_m in rect_main:\n            height_m = float(rect_m.get_height())\n            ax_main.text(rect_m.get_x() + rect_m.get_width()/2., 0.005 + height_m, '{:.2f}%'.format(height_m*100), ha='center', va='bottom', fontsize=LEGEND_FONTSIZE)\n\n        ax_main.set_xticklabels(ax_main_data['labels'], rotation=45, ha='center', fontsize=LEGEND_FONTSIZE)\n        ax_group.set_xticklabels(ax_group_data['labels'], rotation=45, ha='center', fontsize=LEGEND_FONTSIZE)\n        #figsuptitle = fig.suptitle(out_f, verticalalignment='top')\n        out_f = \"%s.read_cov.%s\" % (out_f, cov_lib)\n        print(BtLog.status_d['8'] % \"%s.%s\" % (out_f, self.format))\n        fig.tight_layout()\n        #fig.savefig(\"%s.%s\" % (out_f, self.format), format=self.format,  bbox_extra_artists=(figsuptitle,))\n        fig.savefig(\"%s.%s\" % (out_f, self.format), format=self.format)\n        plt.close(fig)\n\n    def plotScatter(self, cov_lib, info_flag, out_f):\n\n        fig, axScatter, axHistx, axHisty, axLegend, top_bins, right_bins = self.setupPlot(self.plot)\n        # empty handles for big legend\n        legend_handles = []\n        legend_labels = []\n        # marker size scaled by biggest blob (size in points^2)\n        max_length = max(array(self.stats['all']['length'])) # length of biggest blob\n        max_marker_size = 12500 # marker size for biggest blob, i.e. area of 12500^2 pixel\n        for idx, group in enumerate(self.plot_order):\n            idx += 1\n            lw, alpha = 0.5, 0.8\n            if group == 'no-hit':\n                alpha = 0.5\n            group_length_array = array(self.stats[group]['length'])\n            if len(group_length_array) > 0 and group not in self.exclude_groups:\n                colour = self.colours[group]\n                group_x_array = ''\n                group_y_array = ''\n                if self.plot == 'blobplot':\n                    group_x_array = array(self.stats[group]['gc'])\n                    group_y_array = array(self.stats[group]['covs'][cov_lib])\n                elif self.plot == 'covplot':\n                    group_x_array = array(self.stats[group]['covs'][cov_lib])\n                    group_y_array = array([self.cov_y_dict.get(name, 0.02) for name in self.stats[group]['name']])\n                else:\n                    BtLog.error('34', self.plot)\n                marker_size_array = []\n                if (self.ignore_contig_length): # no scaling\n                    if group == \"no-hit\":\n                        s = 20\n                    else:\n                        s = 100\n                    marker_size_array = [s for length in group_length_array]\n                else: # scaling by max_length\n                    marker_size_array = [(length/max_length)*max_marker_size for length in group_length_array]\n                # generate label for legend\n                group_span_in_mb = round(self.stats[group]['span_visible']/1000000, 2)\n                group_number_of_seqs = self.stats[group]['count_visible']\n                group_n50 = self.stats[group]['n50']\n                fmt_seqs = \"{:,}\".format(group_number_of_seqs)\n                fmt_span = \"{:,}\".format(group_span_in_mb)\n                fmt_n50 = \"{:,}\".format(group_n50)\n                label = \"%s (%s;%sMB;%snt)\" % (group, fmt_seqs, fmt_span, fmt_n50)\n                if (info_flag):\n                    print(BtLog.info_d['0'] % (group, fmt_seqs, fmt_span, fmt_n50))\n                if group == \"other\":\n                    legend_handles.append(Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=24, markeredgecolor=DGREY, markerfacecolor=colour))\n                else:\n                    legend_handles.append(Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=24, markeredgecolor=WHITE, markerfacecolor=colour))\n                legend_labels.append(label)\n\n                weights_array = None\n                if self.hist_type == \"span\":\n                    weights_array = group_length_array/1000\n\n                axHistx.hist(group_x_array, weights=weights_array, color = colour, bins = top_bins, histtype='step', lw = 3)\n                axHisty.hist(group_y_array, weights=weights_array, color = colour, bins = right_bins, histtype='step', orientation='horizontal', lw = 3)\n                if group == 'other':\n                    axScatter.scatter(group_x_array, group_y_array, color = colour, s = marker_size_array, lw = lw, alpha=alpha, edgecolor=DGREY, label=label)\n                else:\n                    axScatter.scatter(group_x_array, group_y_array, color = colour, s = marker_size_array, lw = lw, alpha=alpha, edgecolor=WHITE, label=label)\n                axLegend.axis('off')\n                if (self.multiplot):\n                    fig_m, axScatter_m, axHistx_m, axHisty_m, axLegend_m, top_bins, right_bins = self.setupPlot(self.plot)\n                    legend_handles_m = []\n                    legend_labels_m = []\n                    legend_handles_m.append(Line2D([0], [0], linewidth = 0.5, linestyle=\"none\", marker=\"o\", alpha=1, markersize=24, markeredgecolor=WHITE, markerfacecolor=colour))\n                    legend_labels_m.append(label)\n                    axHistx_m.hist(group_x_array, weights=weights_array, color = colour, bins = top_bins, histtype='step', lw = 3)\n                    axHisty_m.hist(group_y_array, weights=weights_array, color = colour, bins = right_bins, histtype='step', orientation='horizontal', lw = 3)\n                    if group == 'other':\n                        axScatter_m.scatter(group_x_array, group_y_array, color = colour, s = marker_size_array, lw = lw, alpha=alpha, edgecolor=DGREY, label=label)\n                    else:\n                        axScatter_m.scatter(group_x_array, group_y_array, color = colour, s = marker_size_array, lw = lw, alpha=alpha, edgecolor=WHITE, label=label)\n                    axLegend_m.axis('off')\n                    axLegend_m.legend(legend_handles_m, legend_labels_m, loc=6, numpoints=1, fontsize=LEGEND_FONTSIZE, frameon=True)\n                    plot_ref_legend(axScatter_m, max_length, max_marker_size, self.ignore_contig_length)\n                    m_out_f = \"%s.%s.%s.%s\" % (out_f, cov_lib, idx, group.replace(\"/\", \"_\").replace(\" \", \"_\"))\n                    fig_m = plot_legend(fig_m, axLegend_m, m_out_f, self.legend_flag, self.format, self.cumulative_flag)\n                    print(BtLog.status_d['8'] % \"%s.%s\" % (m_out_f, self.format))\n                    fig_m.savefig(\"%s.%s\" % (m_out_f, self.format), format=self.format)\n                    plt.close(fig_m)\n                elif (self.cumulative_flag):\n                    axLegend.legend(legend_handles, legend_labels, loc=6, numpoints=1, fontsize=LEGEND_FONTSIZE, frameon=True)\n                    plot_ref_legend(axScatter, max_length, max_marker_size, self.ignore_contig_length)\n                    m_out_f = \"%s.%s.%s.%s\" % (out_f, cov_lib, idx, group.replace(\"/\", \"_\").replace(\" \", \"_\"))\n                    fig.add_axes(axLegend)\n                    fig = plot_legend(fig, axLegend, m_out_f, self.legend_flag, self.format, self.cumulative_flag)\n                    if not (self.no_title):\n                        fig.suptitle(out_f, fontsize=35, verticalalignment='top')\n                    print(BtLog.status_d['8'] % \"%s.%s\" % (m_out_f, self.format))\n                    fig.savefig(\"%s.%s\" % (m_out_f, self.format), format=self.format)\n                else:\n                    pass\n        plot_ref_legend(axScatter, max_length, max_marker_size, self.ignore_contig_length)\n        axLegend.legend(legend_handles, legend_labels, numpoints=1, fontsize=LEGEND_FONTSIZE, frameon=True, loc=6 )\n        out_f = \"%s.%s\" % (out_f, cov_lib)\n        fig.add_axes(axLegend)\n        fig = plot_legend(fig, axLegend, out_f, self.legend_flag, self.format, self.cumulative_flag)\n        if not (self.no_title):\n            fig.suptitle(out_f, fontsize=35, verticalalignment='top')\n        print(BtLog.status_d['8'] % \"%s.%s\" % (out_f, self.format))\n        fig.savefig(\"%s.%s\" % (out_f, self.format), format=self.format)\n        plt.close(fig)\n\nif __name__ == \"__main__\":\n    pass\n"
  },
  {
    "path": "lib/BtTax.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile        : BtTax.py\nAuthor      : Dominik R. Laetsch, dominik.laetsch at gmail dot com\n\"\"\"\n\nRANKS = ['species', 'genus', 'family', 'order', 'phylum', 'superkingdom']\nTAXRULES = ['bestsum', 'bestsumorder'] # this should be re-named colour rules at one point\n\ndef noHit():\n    return {rank : {'tax' : 'no-hit', 'score' : 0.0, 'c_index' : 0} for rank in RANKS}\n\ndef getTreeList(taxIds, nodesDB):\n    known_tree_lists = {}\n    for taxId in taxIds:\n        if not taxId in known_tree_lists:\n            tree_list = []\n            nextTaxId = [taxId]\n            while nextTaxId:\n                thisTaxId = nextTaxId.pop(0)\n                if (not thisTaxId == '1') and (thisTaxId in nodesDB):\n                    parent = nodesDB[thisTaxId]['parent']\n                    nextTaxId.append(parent)\n                    tree_list.append(thisTaxId)\n                else:\n                    tree_list.append('1')\n            known_tree_lists[taxId] = tree_list\n    return known_tree_lists\n\ndef getLineages(tree_lists, nodesDB):\n    lineage = {}\n    for tree_list_id, tree_list in tree_lists.items():\n        lineage[tree_list_id] = {rank : 'undef' for rank in RANKS}\n        for taxId in tree_list:\n            node = nodesDB[taxId]\n            if node['rank'] in RANKS:\n                lineage[tree_list_id][node['rank']] = node['name']\n        # traverse ranks again so that undef is \"higher_def_rank\" + \"-\" + undef\n        def_rank = ''\n        for rank in reversed(list(RANKS)):\n            if not lineage[tree_list_id][rank] == 'undef':\n                def_rank = lineage[tree_list_id][rank]\n            else:\n                if (def_rank):\n                    lineage[tree_list_id][rank] = def_rank + \"-\" + lineage[tree_list_id][rank]\n    return lineage\n\ndef taxRuleBestSum(taxDict, taxonomy, min_bitscore, min_bitscore_diff, tax_collision_random):\n    tempTax = { rank : {} for rank in RANKS }\n    for lib in sorted(taxDict):\n        for rank in RANKS:\n            for tax, score in sorted(taxDict[lib][rank].items()):\n                tempTax[rank][tax] = tempTax[rank].get(tax, 0.0) + score\n    for rank in tempTax:\n        for tax, score in sorted(tempTax[rank].items(), key=lambda x: x[1], reverse=True):\n            if taxonomy[rank]['tax'] == 'no-hit':\n                taxonomy[rank]['score'] = score\n                if score >= min_bitscore:\n                    taxonomy[rank]['tax'] = tax\n                    #taxonomy_assigned_in_hit_lib = lib\n            else:\n                if score == taxonomy[rank]['score']:  # equal score in subsequent hit\n                    if not tax_collision_random:\n                        taxonomy[rank]['tax'] = 'unresolved'\n                elif (taxonomy[rank]['score'] - score) <= min_bitscore_diff:\n                        taxonomy[rank]['tax'] = 'unresolved'\n                else:\n                    pass\n                if not taxonomy[rank]['tax'] == tax:\n                    taxonomy[rank]['c_index'] += 1\n    return taxonomy\n\ndef taxRuleBestSumOrder(taxDict, taxonomy, min_bitscore, min_bitscore_diff, tax_collision_random):\n    for rank in RANKS:\n        taxonomy_assigned_in_hit_lib = ''\n        for lib in sorted(taxDict):\n            for tax, score in sorted(taxDict[lib][rank].items(), key=lambda x: x[1], reverse=True):\n                if not taxonomy_assigned_in_hit_lib:  # has not been taxonomically annotated yet\n                    if taxonomy[rank]['tax'] == 'no-hit':\n                        taxonomy[rank]['score'] = score\n                        if score >= min_bitscore:\n                            taxonomy[rank]['tax'] = tax\n                            taxonomy_assigned_in_hit_lib = lib\n                elif taxonomy_assigned_in_hit_lib == lib:\n                    if score == taxonomy[rank]['score']:  # equal score in subsequent hit\n                        if not tax_collision_random:\n                            taxonomy[rank]['tax'] = 'unresolved'\n                    elif (taxonomy[rank]['score'] - score) <= min_bitscore_diff:\n                        taxonomy[rank]['tax'] = 'unresolved'\n                    else:\n                        pass\n                    if not taxonomy[rank]['tax'] == tax:\n                        taxonomy[rank]['c_index'] += 1\n                else:\n                    pass\n    return taxonomy\n\ndef taxRule(taxrule, hits, lineages, min_score, min_bitscore_diff, tax_collision_random):\n    taxonomy = {rank: {'tax': 'no-hit', 'score': 0.0, 'c_index': 0 } for rank in RANKS }\n    taxDict = getTaxDict(hits, lineages)  # here libs are separated\n    if taxrule == 'bestsum':\n        taxonomy = taxRuleBestSum(taxDict, taxonomy, min_score, min_bitscore_diff, tax_collision_random)\n    elif taxrule == 'bestsumorder':\n        taxonomy = taxRuleBestSumOrder(taxDict, taxonomy, min_score, min_bitscore_diff, tax_collision_random)\n    else:\n        pass\n    return taxonomy\n\ndef getTaxDict(hits, lineages):\n    taxDict = {}\n    for lib, hits in hits.items():\n        taxDict[lib] = {}\n        for hit in hits:\n            taxId = hit['taxId']\n            score = hit['score']\n            for rank in RANKS:\n                name = lineages[taxId][rank]\n                if not rank in taxDict[lib]:\n                    taxDict[lib][rank] = {name : 0.0}\n                taxDict[lib][rank][name] = taxDict[lib][rank].get(name, 0.0) + score\n    return taxDict\n\nif __name__ == \"__main__\":\n    pass\n"
  },
  {
    "path": "lib/__init__.py",
    "content": ""
  },
  {
    "path": "lib/bamfilter.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools bamfilter  -b FILE [-i FILE] [-e FILE] [-U] [-n] [-o PREFIX] [-f FORMAT]\n                                [-h|--help]\n\n    Options:\n        -h --help                   show this\n        -b, --bam FILE              BAM file (sorted by name)\n        -i, --include FILE          List of contigs whose reads are included\n                                    - writes FASTAs of pairs where at least\n                                        one read maps sequences in list\n                                        (InUn.fq, InIn.fq, ExIn.fq)\n        -e, --exclude FILE          List of contigs whose reads are excluded (outputs reads that do not map to sequences in list)\n                                    - writes FASTAs of pairs where at least\n                                        one read does not maps to sequences in list\n                                        (InUn.fq, InIn.fq, ExIn.fq)\n        -U, --exclude_unmapped      Exclude pairs where both reads are unmapped\n        -n, --noninterleaved        Use if fw and rev reads should be in separate files  \n        -f, --read_format FORMAT    FASTQ = fq, FASTA = fa [default: fa]      \n        -o, --out PREFIX            Output prefix\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\n\nimport sys\n\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\n\ndef main():\n    args = docopt(__doc__)\n    #print(args)\n    bam_f = args['--bam']\n    include_f = args['--include']\n    exclude_f = args['--exclude']\n    out_prefix = args['--out']\n    read_format = args['--read_format']\n    if not read_format in set(['fq', 'fa']):\n        sys.exit(\"[X] Read format must be fq or fa!\")\n    noninterleaved = args['--noninterleaved']\n    include_unmapped = True\n    if args['--exclude_unmapped']:\n        include_unmapped = False\n    out_f = BtIO.getOutFile(bam_f, out_prefix, None)\n    if include_f and exclude_f:\n        print(BtLog.error('43'))\n    elif include_f:\n        sequence_list = BtIO.parseList(include_f)\n        BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, sequence_list, None, read_format)\n    elif exclude_f:\n        sequence_list = BtIO.parseList(exclude_f)\n        BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, None, sequence_list, read_format)\n    else:\n        BtIO.parseBamForFilter(bam_f, include_unmapped, noninterleaved, out_f, None, None, read_format)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/blobplot.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools plot -i <BLOBDB>\n                                [-p INT] [-l INT] [--cindex] [-n] [-s]\n                                [-r RANK] [-x TAXRULE] [--label GROUPS...]\n                                [--lib COVLIB] [-o PREFIX] [-m]\n                                [--sort ORDER] [--sort_first LABELS] [--hist HIST] [--notitle] [--filelabel]\n                                [--colours FILE] [--exclude FILE]\n                                [--refcov FILE] [--catcolour FILE]\n                                [--format FORMAT] [--noblobs] [--noreads] [--legend]\n                                [--cumulative] [--multiplot]\n                                [-h|--help]\n\n    Options:\n        -h --help                   show this\n        -i, --infile BLOBDB         BlobDB file (created with \"blobtools create\")\n        --lib COVLIB                Plot only certain covlib(s). Separated by \",\"\n        --notitle                   Do not add filename as title to plot\n        --filelabel                 Label axis based on filenames\n        -p, --plotgroups INT        Number of (taxonomic) groups to plot, remaining\n                                     groups are placed in 'other' [default: 8]\n        -l, --length INT            Minimum sequence length considered for plotting [default: 100]\n        --cindex                    Colour blobs by 'c index' [default: False]\n        -n, --nohit                 Hide sequences without taxonomic annotation [default: False]\n        -s, --noscale               Do not scale sequences by length [default: False]\n        --legend                    Plot legend of blobplot in separate figure\n        -m, --multiplot             Multi-plot. Print blobplot for each (taxonomic) group separately\n        --cumulative                Print plot after addition of each (taxonomic) group\n        --sort <ORDER>              Sort order for plotting [default: span]\n                                     span  : plot with decreasing span\n                                     count : plot with decreasing count\n        --sort_first <L1,L2,...>    Labels that should always be plotted first, regardless of sort order\n                                     (\"no-hit,other,undef\" is often a useful setting)\n        --hist <HIST>               Data for histograms [default: span]\n                                     span  : span-weighted histograms\n                                     count : count histograms\n        -r, --rank <RANK>           Taxonomic rank used for colouring of blobs [default: phylum]\n                                     (Supported: species, genus, family, order,\n                                        phylum, superkingdom)\n        -x, --taxrule <TAXRULE>     Taxrule which has been used for computing taxonomy\n                                     (Supported: bestsum, bestsumorder) [default: bestsum]\n        --format FORMAT             Figure format for plot (png, pdf, eps, jpeg,\n                                        ps, svg, svgz, tiff) [default: png]\n        --noblobs                   Omit blobplot [default: False]\n        --noreads                   Omit plot of reads mapping [default: False]\n\n        -o, --out PREFIX            Output prefix\n\n        --label GROUPS...           Relabel (taxonomic) groups, can be used several times.\n                                     e.g. \"A=Actinobacteria,Proteobacteria\"\n        --colours COLOURFILE        File containing colours for (taxonomic) groups. This allows having more than 9 colours.\n        --exclude GROUPS            Exclude these (taxonomic) groups (also works for 'other')\n                                     e.g. \"Actinobacteria,Proteobacteria,other\"\n        --refcov <FILE>               File containing number of \"total\" and \"mapped\" reads\n                                     per coverage file. (e.g.: bam0,900,100). If provided, info\n                                     will be used in read coverage plot(s).\n        --catcolour <FILE>            Colour plot based on categories from FILE\n                                     (format : \"seq\\tcategory\").\n\n\"\"\"\nfrom docopt import docopt\n\nfrom os.path import basename\nimport sys\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\nimport lib.BtCore as BtCore\nimport lib.BtPlot as BtPlot\nimport lib.interface as interface\n\ndef main():\n    args = docopt(__doc__)\n    args = BtPlot.check_input(args)\n\n    blobdb_f = args['--infile']\n    rank = args['--rank']\n    min_length = int(args['--length'])\n    max_group_plot = int(args['--plotgroups'])\n    colour_f = args['--colours']\n    if max_group_plot > 8 and not colour_f:\n        sys.exit(\"[X] '--plotgroups' must be less than 9 for using automatic colour assignation.\")\n    hide_nohits = args['--nohit']\n    taxrule = args['--taxrule']\n    c_index = args['--cindex']\n    exclude_groups = args['--exclude']\n    labels = args['--label']\n    colour_f = args['--colours']\n    refcov_f = args['--refcov']\n    catcolour_f = args['--catcolour']\n\n    multiplot = args['--multiplot']\n    out_prefix = args['--out']\n    sort_order = args['--sort']\n    sort_first = args['--sort_first']\n    hist_type = args['--hist']\n    no_title = args['--notitle']\n    ignore_contig_length = args['--noscale']\n    format_plot = args['--format']\n    no_plot_blobs = args['--noblobs']\n    no_plot_reads = args['--noreads']\n    legend_flag = args['--legend']\n    cumulative_flag = args['--cumulative']\n    cov_lib_selection = args['--lib']\n\n    filelabel = args['--filelabel']\n\n    exclude_groups = BtIO.parseCmdlist(exclude_groups)\n    refcov_dict = BtIO.parseReferenceCov(refcov_f)\n    user_labels = BtIO.parseCmdLabels(labels)\n    catcolour_dict = BtIO.parseCatColour(catcolour_f)\n    colour_dict = BtIO.parseColours(colour_f)\n\n    # Load BlobDb\n    print(BtLog.status_d['9'] % blobdb_f)\n    blobDb = BtCore.BlobDb('blobplot')\n    blobDb.version = interface.__version__\n    blobDb.load(blobdb_f)\n\n    # Generate plot data\n    print(BtLog.status_d['18'])\n    data_dict, min_cov, max_cov, cov_lib_dict = blobDb.getPlotData(rank, min_length, hide_nohits, taxrule, c_index, catcolour_dict)\n    plotObj = BtPlot.PlotObj(data_dict, cov_lib_dict, cov_lib_selection, 'blobplot', sort_first)\n    plotObj.exclude_groups = exclude_groups\n    plotObj.version = blobDb.version\n    plotObj.format = format_plot\n    plotObj.max_cov = max_cov\n    plotObj.min_cov = min_cov\n    plotObj.no_title = no_title\n    plotObj.multiplot = multiplot\n    plotObj.hist_type = hist_type\n    plotObj.ignore_contig_length = ignore_contig_length\n    plotObj.max_group_plot = max_group_plot\n    plotObj.legend_flag = legend_flag\n    plotObj.cumulative_flag = cumulative_flag\n    # order by which to plot (should know about user label)\n    plotObj.group_order = BtPlot.getSortedGroups(data_dict, sort_order, sort_first)\n    # labels for each level of stats\n    plotObj.labels.update(plotObj.group_order)\n    # plotObj.group_labels is dict that contains labels for each group : all/other/user_label\n    if (user_labels):\n        for group, label in user_labels.items():\n            plotObj.labels.add(label)\n    plotObj.group_labels = {group : set() for group in plotObj.group_order}\n    plotObj.relabel_and_colour(colour_dict, user_labels)\n    plotObj.compute_stats()\n    plotObj.refcov_dict = refcov_dict\n    # Plotting\n    info_flag = 1\n    out_f = ''\n    for cov_lib in plotObj.cov_libs:\n        plotObj.ylabel = \"Coverage\"\n        plotObj.xlabel = \"GC proportion\"\n        if (filelabel):\n            plotObj.ylabel = basename(cov_lib_dict[cov_lib]['f'])\n        out_f = \"%s.%s.%s.p%s.%s.%s\" % (blobDb.title, taxrule, rank, max_group_plot, hist_type, min_length)\n        if catcolour_dict:\n            out_f = \"%s.%s\" % (out_f, \"catcolour\")\n        if ignore_contig_length:\n            out_f = \"%s.%s\" % (out_f, \"noscale\")\n        if c_index:\n            out_f = \"%s.%s\" % (out_f, \"c_index\")\n        if exclude_groups:\n            out_f = \"%s.%s\" % (out_f, \"exclude_\" + \"_\".join(exclude_groups))\n        if labels:\n            out_f = \"%s.%s\" % (out_f, \"userlabel_\" + \"_\".join(set([name for name in user_labels.values()])))\n        out_f = \"%s.%s\" % (out_f, \"blobplot\")\n        if (plotObj.cumulative_flag):\n            out_f = \"%s.%s\" % (out_f, \"cumulative\")\n        if (plotObj.multiplot):\n            out_f = \"%s.%s\" % (out_f, \"multiplot\")\n        out_f = BtIO.getOutFile(out_f, out_prefix, None)\n        if not (no_plot_blobs):\n            plotObj.plotScatter(cov_lib, info_flag, out_f)\n            info_flag = 0\n        if not (no_plot_reads) and (plotObj.cov_libs_total_reads_dict[cov_lib]):\n            # prevent plotting if --noreads or total_reads == 0\n            plotObj.plotBar(cov_lib, out_f)\n    plotObj.write_stats(out_f)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/covplot.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools covplot  -i BLOBDB -c COV [--max FLOAT]\n                                [--xlabel XLABEL] [--ylabel YLABEL]\n                                [--lib COVLIB] [-o PREFIX] [-m]\n                                [-p INT] [-l INT] [--cindex] [-n] [-s]\n                                [-r RANK] [-x TAXRULE] [--label GROUPS...]\n                                [--sort ORDER] [--sort_first LABELS]\n                                [--hist HIST] [--notitle]\n                                [--colours FILE] [--exclude FILE]\n                                [--refcov FILE] [--catcolour FILE]\n                                [--format FORMAT] [--noblobs] [--noreads] [--legend]\n                                [--cumulative]\n                                [-h|--help]\n\n    Options:\n        -h --help                   show this\n        -i, --infile BLOBDB         BlobDB file\n        -c, --cov COV               COV file to be used in y-axis\n\n        --xlabel XLABEL             Label for x-axis\n        --ylabel YLABEL             Label for y-axis\n        --max FLOAT                 Maximum values for x/y-axis [default: 1e10]\n\n        --lib COVLIB                Plot only certain covlib(s). Separated by \",\"\n        --notitle                   Do not add filename as title to plot\n        -p, --plotgroups INT        Number of (taxonomic) groups to plot, remaining\n                                     groups are placed in 'other' [default: 7]\n        -l, --length INT            Minimum sequence length considered for plotting [default: 100]\n        --cindex                    Colour blobs by 'c index' [default: False]\n        -n, --nohit                 Hide sequences without taxonomic annotation [default: False]\n        -s, --noscale               Do not scale sequences by length [default: False]\n        --legend                    Plot legend of blobplot in separate figure\n        -m, --multiplot             Multi-plot. Print blobplot for each (taxonomic) group separately\n        --cumulative                Print plot after addition of each (taxonomic) group\n        --sort <ORDER>              Sort order for plotting [default: span]\n                                     span  : plot with decreasing span\n                                     count : plot with decreasing count\n        --sort_first <L1,L2,...>    Labels that should always be plotted first, regardless of sort order\n                                     (\"no-hit,other,undef\" is often a useful setting)\n        --hist <HIST>               Data for histograms [default: span]\n                                     span  : span-weighted histograms\n                                     count : count histograms\n        -r, --rank <RANK>           Taxonomic rank used for colouring of blobs [default: phylum]\n                                     (Supported: species, genus, family, order,\n                                        phylum, superkingdom)\n        -x, --taxrule <TAXRULE>     Taxrule which has been used for computing taxonomy\n                                     (Supported: bestsum, bestsumorder) [default: bestsum]\n        --format FORMAT             Figure format for plot (png, pdf, eps, jpeg,\n                                        ps, svg, svgz, tiff) [default: png]\n        --noblobs                   Omit blobplot [default: False]\n        --noreads                   Omit plot of reads mapping [default: False]\n        -o, --out PREFIX            Output prefix\n        --label GROUPS...           Relabel (taxonomic) groups, can be used several times.\n                                     e.g. \"A=Actinobacteria,Proteobacteria\"\n        --colours COLOURFILE        File containing colours for (taxonomic) groups\n        --exclude GROUPS            Exclude these (taxonomic) groups (also works for 'other')\n                                     e.g. \"Actinobacteria,Proteobacteria,other\"\n        --refcov <FILE>               File containing number of \"total\" and \"mapped\" reads\n                                     per coverage file. (e.g.: bam0,900,100). If provided, info\n                                     will be used in read coverage plot(s).\n        --catcolour <FILE>            Colour plot based on categories from FILE\n                                     (format : \"seq,category\").\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\n\nfrom os.path import basename\n\nimport lib.interface as interface\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\nimport lib.BtCore as Bt\nimport lib.BtPlot as BtPlot\n\ndef main():\n    args = docopt(__doc__)\n    args = BtPlot.check_input(args)\n    blobdb_f = args['--infile']\n    cov_f = args['--cov']\n    rank = args['--rank']\n    min_length = int(args['--length'])\n    max_group_plot = int(args['--plotgroups'])\n    hide_nohits = args['--nohit']\n    taxrule = args['--taxrule']\n    c_index = args['--cindex']\n    exclude_groups = args['--exclude']\n    labels = args['--label']\n    colour_f = args['--colours']\n    refcov_f = args['--refcov']\n    catcolour_f = args['--catcolour']\n    sort_order = args['--sort']\n    sort_first = args['--sort_first']\n    multiplot = args['--multiplot']\n    out_prefix = args['--out']\n    sort_order = args['--sort']\n    hist_type = args['--hist']\n    no_title = args['--notitle']\n    ignore_contig_length = args['--noscale']\n    format_plot = args['--format']\n    no_plot_blobs = args['--noblobs']\n    #no_plot_reads = args['--noreads']\n    legend_flag = args['--legend']\n    cumulative_flag = args['--cumulative']\n    cov_lib_selection = args['--lib']\n\n    xlabel = args['--xlabel']\n    ylabel = args['--ylabel']\n    axis_max = float(args['--max'])\n\n    exclude_groups = BtIO.parseCmdlist(exclude_groups)\n    refcov_dict = BtIO.parseReferenceCov(refcov_f)\n    user_labels = BtIO.parseCmdLabels(labels)\n    catcolour_dict = BtIO.parseCatColour(catcolour_f)\n    colour_dict = BtIO.parseColours(colour_f)\n\n    # Load BlobDb\n    print(BtLog.status_d['9'] % blobdb_f)\n    blobDb = Bt.BlobDb('blobplot')\n    blobDb.version = interface.__version__\n    blobDb.load(blobdb_f)\n\n    # Generate plot data\n    print(BtLog.status_d['1'] % ('cov_y_axis', cov_f))\n    cov_y_dict, reads_total, reads_mapped, reads_unmapped, read_cov_dict = BtIO.parseCov(cov_f, set(blobDb.dict_of_blobs))\n    print(BtLog.status_d['18'])\n    data_dict, min_cov, max_cov, cov_lib_dict = blobDb.getPlotData(rank, min_length, hide_nohits, taxrule, c_index, catcolour_dict)\n    plotObj = BtPlot.PlotObj(data_dict, cov_lib_dict, cov_lib_selection, 'covplot', sort_first)\n    # set lowest coverage to 0.01\n    for contig in cov_y_dict:\n        if cov_y_dict[contig] < 0.1:\n            cov_y_dict[contig] = 0.1\n    plotObj.cov_y_dict = cov_y_dict\n    plotObj.exclude_groups = exclude_groups\n    plotObj.version = blobDb.version\n    plotObj.format = format_plot\n    plotObj.max_cov = axis_max\n    plotObj.no_title = no_title\n    plotObj.multiplot = multiplot\n    plotObj.hist_type = hist_type\n    plotObj.ignore_contig_length = ignore_contig_length\n    plotObj.max_group_plot = max_group_plot\n    plotObj.legend_flag = legend_flag\n    plotObj.cumulative_flag = cumulative_flag\n    # order by which to plot (should know about user label)\n    plotObj.group_order = BtPlot.getSortedGroups(data_dict, sort_order)\n    # labels for each level of stats\n    plotObj.labels.update(plotObj.group_order)\n    # plotObj.group_labels is dict that contains labels for each group : all/other/user_label\n    if (user_labels):\n        for group, label in user_labels.items():\n            plotObj.labels.add(label)\n    plotObj.group_labels = {group : set() for group in plotObj.group_order}\n    plotObj.relabel_and_colour(colour_dict, user_labels)\n    plotObj.compute_stats()\n    plotObj.refcov_dict = refcov_dict\n    # Plotting\n    info_flag = 1\n\n    out_f = ''\n    for cov_lib in plotObj.cov_libs:\n        plotObj.xlabel = basename(cov_lib_dict[cov_lib]['f'])\n        plotObj.ylabel = cov_f\n        if (ylabel):\n            plotObj.ylabel = ylabel\n        if (xlabel):\n            plotObj.xlabel = xlabel\n        out_f = \"%s.%s.%s.p%s.%s.%s\" % (blobDb.title, taxrule, rank, max_group_plot, hist_type, min_length)\n        if catcolour_dict:\n            out_f = \"%s.%s\" % (out_f, \"catcolour\")\n        if ignore_contig_length:\n            out_f = \"%s.%s\" % (out_f, \"noscale\")\n        if c_index:\n            out_f = \"%s.%s\" % (out_f, \"c_index\")\n        if exclude_groups:\n            out_f = \"%s.%s\" % (out_f, \"exclude_\" + \"_\".join(exclude_groups))\n        if labels:\n            out_f = \"%s.%s\" % (out_f, \"userlabel_\" + \"_\".join(set([name for name in user_labels.values()])))\n        out_f = \"%s.%s\" % (out_f, \"covplot\")\n        if (plotObj.cumulative_flag):\n            out_f = \"%s.%s\" % (out_f, \"cumulative\")\n        if (plotObj.multiplot):\n            out_f = \"%s.%s\" % (out_f, \"multiplot\")\n        out_f = BtIO.getOutFile(out_f, out_prefix, None)\n        if not (no_plot_blobs):\n            plotObj.plotScatter(cov_lib, info_flag, out_f)\n            info_flag = 0\n    plotObj.write_stats(out_f)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/create.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools create     -i FASTA [-y FASTATYPE] [-o PREFIX] [--title TITLE]\n                              [-b BAM...] [-C] [-a CAS...] [-c COV...]\n                              [--nodes <NODES>] [--names <NAMES>] [--db <NODESDB>]\n                              [-t HITS...] [-x TAXRULE...] [-m FLOAT] [-d FLOAT] [--tax_collision_random]\n                              [-h|--help]\n\n    Options:\n        -h --help                       show this\n        -i, --infile FASTA              FASTA file of assembly. Headers are split at whitespaces.\n        -y, --type FASTATYPE            Assembly program used to create FASTA. If specified,\n                                        coverage will be parsed from FASTA header.\n                                        (Parsing supported for 'spades', 'velvet', 'platanus')\n        -t, --hitsfile HITS...          Hits file in format (qseqid\\\\ttaxid\\\\tbitscore)\n                                        (e.g. BLAST output \"--outfmt '6 qseqid staxids bitscore'\")\n                                        Can be specified multiple times\n        -x, --taxrule <TAXRULE>...      Taxrule determines how taxonomy of blobs\n                                        is computed (by default both are calculated)\n                                        \"bestsum\"       : sum bitscore across all\n                                                          hits for each taxonomic rank\n                                        \"bestsumorder\"  : sum bitscore across all\n                                                          hits for each taxonomic rank.\n                                                  - If first <TAX> file supplies hits, bestsum is calculated.\n                                                  - If no hit is found, the next <TAX> file is used.\n        -m, --min_score <FLOAT>         Minimal score necessary to be considered for taxonomy calculaton, otherwise set to 'no-hit'\n                                        [default: 0.0]\n        -d, --min_diff <FLOAT>          Minimal score difference between highest scoring\n                                        taxonomies (otherwise \"unresolved\") [default: 0.0]\n        --tax_collision_random          Random allocation of taxonomy if highest scoring\n                                        taxonomies have equal scores (otherwise \"unresolved\") [default: False]\n        --nodes <NODES>                 NCBI nodes.dmp file. Not required if '--db'\n        --names <NAMES>                 NCBI names.dmp file. Not required if '--db'\n        --db <NODESDB>                  NodesDB file (default: $BLOBTOOLS/data/nodesDB.txt).  If --nodes, --names and --db\n                                        are all given and NODESDB does not exist, create it from NODES and NAMES.\n        -b, --bam <BAM>...              BAM file(s), can be specified multiple times\n        -a, --cas <CAS>...              CAS file(s) (requires clc_mapping_info in $PATH), can be specified multiple times\n        -c, --cov <COV>...              COV file(s), can be specified multiple times\n        -C, --calculate_cov             Legacy coverage when getting coverage from BAM (does not apply to COV parsing). \n                                            New default is to estimate coverages which is faster,\n        -o, --out <PREFIX>              BlobDB output prefix\n        --title TITLE                   Title of BlobDB [default: output prefix)\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\n\nfrom os.path import join, dirname, abspath\n\nimport lib.BtCore as BtCore\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\nimport lib.interface as interface\n\ndef main():\n\n    #main_dir = dirname(__file__)\n    args = docopt(__doc__)\n    fasta_f = args['--infile']\n    fasta_type = args['--type']\n    bam_fs = args['--bam']\n    cov_fs = args['--cov']\n    cas_fs = args['--cas']\n    hit_fs = args['--hitsfile']\n    prefix = args['--out']\n    nodesDB_f = args['--db']\n    names_f = args['--names']\n    estimate_cov_flag = True if not args['--calculate_cov'] else False\n    nodes_f = args['--nodes']\n    taxrules = args['--taxrule']\n    try:\n        min_bitscore_diff = float(args['--min_diff'])\n        min_score = float(args['--min_score'])\n    except ValueError():\n        BtLog.error('45')\n    tax_collision_random = args['--tax_collision_random']\n    title = args['--title']\n\n    # outfile\n    out_f = BtIO.getOutFile(\"blobDB\", prefix, \"json\")\n    if not (title):\n        title = out_f\n\n    # coverage\n    if not (fasta_type) and not bam_fs and not cov_fs and not cas_fs:\n        BtLog.error('1')\n    cov_libs = [BtCore.CovLibObj('bam' + str(idx), 'bam', lib_f) for idx, lib_f in enumerate(bam_fs)] + \\\n           [BtCore.CovLibObj('cas' + str(idx), 'cas', lib_f) for idx, lib_f in enumerate(cas_fs)] + \\\n           [BtCore.CovLibObj('cov' + str(idx), 'cov', lib_f) for idx, lib_f in enumerate(cov_fs)]\n\n    # taxonomy\n    hit_libs = [BtCore.HitLibObj('tax' + str(idx), 'tax', lib_f) for idx, lib_f in enumerate(hit_fs)]\n\n    # Create BlobDB object\n    blobDb = BtCore.BlobDb(title)\n    blobDb.version = interface.__version__\n    # Parse FASTA\n    blobDb.parseFasta(fasta_f, fasta_type)\n\n    # Parse nodesDB OR names.dmp, nodes.dmp\n    nodesDB_default = join(dirname(abspath(__file__)), \"../data/nodesDB.txt\")\n    nodesDB, nodesDB_f = BtIO.parseNodesDB(nodes=nodes_f, names=names_f, nodesDB=nodesDB_f, nodesDBdefault=nodesDB_default)\n    blobDb.nodesDB_f = nodesDB_f\n\n    # Parse similarity hits\n    if (hit_libs):\n        blobDb.parseHits(hit_libs)\n        if not taxrules:\n            if len(hit_libs) > 1:\n                taxrules = ['bestsum', 'bestsumorder']\n            else:\n                taxrules = ['bestsum']\n        blobDb.computeTaxonomy(taxrules, nodesDB, min_score, min_bitscore_diff, tax_collision_random)\n    else:\n        print(BtLog.warn_d['0'])\n\n    # Parse coverage\n    blobDb.parseCoverage(covLibObjs=cov_libs, estimate_cov=estimate_cov_flag, prefix=prefix)\n\n    # Generating BlobDB and writing to file\n    print(BtLog.status_d['7'] % out_f)\n    BtIO.writeJson(blobDb.dump(), out_f)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/interface.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nblobtools\n\n    Usage:\n        ./blobtools [<module>] [<args>...] [-h] [-v]        \n\n    Modules:\n        create        create a BlobDB\n        view          generate tabular view, CONCOCT input or COV files from BlobDB\n        plot          generate a BlobPlot from a BlobDB\n        covplot       generate a CovPlot from a BlobDB and a COV file\n    \n        map2cov       generate a COV file from BAM file\n        taxify        generate a BlobTools compatible HITS file (TSV)\n        bamfilter     subset paired-end reads from a BAM file\n        seqfilter     subset sequences in FASTA file based sequence IDs in list\n        nodesdb       create nodesdb based on NCBI Taxdump's names.dmp and nodes.dmp\n\n    Options\n        -h, --help      show this\n        -v, --version   show version number\n\n    See 'blobtools <command> --help' for more information on a specific command.\n\n    Further documentation is available at https://blobtools.readme.io/\n\n    Examples:\n\n        # 1. Create a BlobDB\n        ./blobtools create -i example/assembly.fna -b example/mapping_1.bam -t example/blast.out -o example/test\n    \n        # 2. Generate a tabular view\n        ./blobtools view -i example/test.blobDB.json\n    \n        # 3. Generate a blobplot\n        ./blobtools plot -i example/test.blobDB.json\n\n\"\"\"\n\nimport sys\nfrom docopt import docopt, DocoptExit\nfrom timeit import default_timer as timer\n\n__version__ = '1.1.1'\n\ndef main():\n    try:\n        start_time = timer()\n        try:\n            args = docopt(__doc__, version=__version__, options_first=True)\n        except DocoptExit:\n            print(__doc__)\n        else:\n            if args['<module>']:\n                if args['<module>'] == 'create':\n                    import lib.create as create\n                    create.main()\n                elif args['<module>'] == 'view':\n                    import lib.view as view\n                    view.main()\n                elif args['<module>'] == 'plot':\n                    import lib.blobplot as plot\n                    plot.main()\n                elif args['<module>'] == 'map2cov':\n                    import lib.map2cov as map2cov\n                    map2cov.main()\n                elif args['<module>'] == 'seqfilter':\n                    import lib.seqfilter as seqfilter\n                    seqfilter.main()\n                elif args['<module>'] == 'covplot':\n                    import lib.covplot as covplot\n                    covplot.main()\n                elif args['<module>'] == 'taxify':\n                    import lib.taxify as taxify\n                    taxify.main()\n                elif args['<module>'] == 'bamfilter':\n                    import lib.bamfilter as bamfilter\n                    bamfilter.main()\n                elif args['<module>'] == 'nodesdb':\n                    import lib.nodesdb as nodesdb\n                    nodesdb.main()\n                else:\n                    sys.exit(\"%r is not a blobtools module. See 'blobtools -h'.\" % args['<module>'])\n            else:\n\n                print(__doc__)\n    except KeyboardInterrupt:\n        sys.stderr.write(\"\\n[X] Interrupted by user after %i seconds!\\n\" % (timer() - start_time))\n        sys.exit(-1)\n\n"
  },
  {
    "path": "lib/map2cov.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools map2cov         -i FASTA [-b BAM...] [-a CAS...]\n                                    [-o PREFIX] [-c]\n                                    [-h|--help]\n\n    Options:\n        -h --help                   show this\n        -i, --infile FASTA          FASTA file of assembly. Headers are split at whitespaces.\n        -b, --bam <BAM>...          BAM file (requires pysam)\n        -a, --cas <CAS>...          CAS file (requires clc_mapping_info in $PATH)\n        -o, --output <PREFIX>       Output prefix\n        -c, --calculate_cov         Legacy coverage, slower. New default is to estimate coverages \n                                        based on read lengths of first 10K reads.\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\n\nimport lib.BtLog as BtLog\nimport lib.BtCore as BtCore\nimport lib.interface as interface\n\ndef main():\n    args = docopt(__doc__)\n    fasta_f = args['--infile']\n    bam_fs = args['--bam']\n    cas_fs = args['--cas']\n    prefix = args['--output']\n    estimate_cov_flag = True if not args['--calculate_cov'] else False\n\n    # Make covLibs\n    cov_libs = [BtCore.CovLibObj('bam' + str(idx), 'bam', lib_f) for idx, lib_f in enumerate(bam_fs)] + \\\n           [BtCore.CovLibObj('cas' + str(idx), 'cas', lib_f) for idx, lib_f in enumerate(cas_fs)]\n    if not (cov_libs):\n        BtLog.error('31')\n    blobDb = BtCore.BlobDb('cov')\n    blobDb.version = interface.__version__\n    blobDb.parseFasta(fasta_f, None)\n    blobDb.parseCoverage(covLibObjs=cov_libs, estimate_cov=estimate_cov_flag, prefix=prefix)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/nodesdb.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools nodesdb             --nodes <NODES> --names <NAMES>\n                                        [-h|--help]\n\n    Options:\n        -h --help                       show this\n        --nodes <NODES>                 NCBI nodes.dmp file.\n        --names <NAMES>                 NCBI names.dmp file.\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\n\nfrom os.path import join, dirname, abspath\n\nimport lib.BtIO as BtIO\n\ndef main():\n    args = docopt(__doc__)\n    names_f = args['--names']\n    nodes_f = args['--nodes']\n\n    # Parse names.dmp, nodes.dmp\n    nodesDB_default = join(dirname(abspath(__file__)), \"../data/nodesDB.txt\")\n    nodesDB, nodesDB_f = BtIO.parseNodesDB(nodes=nodes_f, names=names_f, nodesDB=None, nodesDBdefault=nodesDB_default)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/seqfilter.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools seqfilter       -i FASTA -l LIST [-o PREFIX] [-v]\n                                    [-h|--help]\n\n    Options:\n        -h --help                   show this\n\n        -i, --infile <FASTA>        FASTA file of sequences (Headers are split at whitespaces)\n        -l, --list <LIST>           TXT file containing headers of sequences to keep\n        -o, --out <PREFIX>          Output prefix\n        -v, --invert                Invert filtering (Sequences w/ headers NOT in list)\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\nfrom tqdm import tqdm\n\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\n\ndef main():\n    args = docopt(__doc__)\n    fasta_f = args['--infile']\n    list_f = args['--list']\n    invert = args['--invert']\n    prefix = args['--out']\n\n    output = []\n    out_f = BtIO.getOutFile(fasta_f, prefix, \"filtered.fna\")\n\n    print(BtLog.status_d['1'] % (\"list\", list_f))\n    items = BtIO.parseSet(list_f)\n    items_count = len(items)\n    print(BtLog.status_d['22'] % fasta_f)\n    items_parsed = []\n    \n    with tqdm(total=items_count, desc=\"[%] \", ncols=200, unit_scale=True) as pbar:\n        for header, sequence in BtIO.readFasta(fasta_f):\n            if header in items:\n                if not (invert):\n                    items_parsed.append(header)\n                    output.append(\">%s\\n%s\\n\" % (header, sequence))\n            else:\n                if (invert):\n                    items_parsed.append(header)\n                    output.append(\">%s\\n%s\\n\" % (header, sequence))\n        pbar.update()\n\n    items_parsed_count = len(items_parsed)\n\n    items_parsed_count_unique = len(set(items_parsed))\n    if not items_parsed_count == items_parsed_count_unique:\n        print(BtLog.warn_d['8'] % \"\\n\\t\\t\\t\".join(list(set([x for x in items_parsed if items_parsed.count(x) > 1]))))\n\n    with open(out_f, \"w\") as fh:\n        print(BtLog.status_d['24'] % out_f)\n        fh.write(\"\".join(output))\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/taxify.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools taxify          -f FILE [-a INT] [-b INT] [-c INT]\n                                    [-m FILE] [-s INT] [-t INT]\n                                    [-i FILE] [-x INT] [-v FLOAT]\n                                    [-o PREFIX] [-h|--help]\n\n    Options:\n        -h --help                           show this\n\n    Options for similarity search input\n        -f, --hit_file <FILE>               BLAST/Diamond similarity search result (TSV format).\n                                                Defaults assume \"-outfmt '6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore'\"\n        -a, --hit_column_qseqid <INT>       Zero-based column of qseqid in similarity search result [default: 0]\n                                                Change if different format than (-outfmt '6')\n        -b, --hit_column_sseqid <INT>       Zero-based column of sseqid in similarity search result [default: 1]\n                                                Change if different format than (-outfmt '6')\n        -c, --hit_column_score <INT>        Zero-based column of (bit)score in similarity search result [default: 11]\n                                                Change if different format than (-outfmt '6')\n    Options for TaxID mapping file\n        -m, --taxid_mapping_file <FILE>     TaxID mapping file (contains seqid and taxid)\n        -s, --map_col_sseqid <INT>          Zero-based column of sseqid in TaxID mapping file (it will search for sseqid in this column)\n        -t, --map_col_taxid <INT>           Zero-based Column of taxid in TaxID mapping file (it will extract for taxid from this column)\n\n    Options for custom input\n        -i, --custom <FILE>                 File containing list of sequence IDs\n        -x, --custom_taxid <INT>            TaxID to assign to all sequence IDs in list\n        -v, --custom_score <FLOAT>          Score to assign to all sequence IDs in list\n\n    General\n        -o, --out <PREFIX>                  Output prefix\n\"\"\"\n\nfrom __future__ import division\nfrom docopt import docopt\nfrom collections import defaultdict\n\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\n\ndef main():\n    args = docopt(__doc__)\n    out_f, hit_f, map_f, taxid_d = None, None, None, {}\n    hit_f = args['--hit_file']\n    hit_col_qseqid = args['--hit_column_qseqid']\n    hit_col_sseqid = args['--hit_column_sseqid']\n    hit_col_score = args['--hit_column_score']\n    map_f = args['--taxid_mapping_file']\n    map_col_sseqid = args['--map_col_sseqid']\n    map_col_taxid = args['--map_col_taxid']\n    #custom_f = args['--custom']\n    custom_taxid = args['--custom_taxid']\n    #custom_score = args['--custom_score']\n    prefix = args['--out']\n\n    try:\n        hit_col_qseqid = int(hit_col_qseqid)\n        hit_col_sseqid = int(hit_col_sseqid)\n        hit_col_score = int(hit_col_score)\n    except ValueError:\n        BtLog.error('41' % (\"--hit_column_qseqid, --hit_column_sseqid and --hit_column_score\"))\n\n    if custom_taxid:\n        try:\n            custom_taxid = int(custom_taxid)\n        except TypeError:\n            BtLog.error('26')\n        out_f = BtIO.getOutFile(hit_f, prefix, \"taxID_%s.out\" % custom_taxid)\n        taxid_d = defaultdict(lambda: custom_taxid)\n    elif map_f:\n        if map_col_sseqid and map_col_taxid:\n            try:\n                map_col_sseqid = int(map_col_sseqid)\n                map_col_taxid = int(map_col_taxid)\n            except ValueError:\n                BtLog.error('44')\n            print(BtLog.status_d['1'] % (\"Mapping file\", map_f))\n            taxid_d = BtIO.parseDict(map_f, map_col_sseqid, map_col_taxid)\n            out_f = BtIO.getOutFile(hit_f, prefix, \"taxified.out\")\n        else:\n            BtLog.error('44')\n    else:\n        BtLog.error('41')\n\n    output = []\n    print(BtLog.status_d['1'] % (\"similarity search result\", hit_f))\n    with open(hit_f) as fh:\n        for idx, line in enumerate(fh):\n            col = line.rstrip(\"\\n\").split()\n            qseqid = col[hit_col_qseqid]\n            sseqid = col[hit_col_sseqid]\n            score = col[hit_col_score]\n            tax_id = None\n            if custom_taxid:\n                tax_id = taxid_d[sseqid]\n            else:\n                if sseqid not in taxid_d:\n                    BtLog.warn_d['12'] % (sseqid, map_f)\n                tax_id = taxid_d.get(sseqid, \"N/A\")\n            output.append(\"%s\\t%s\\t%s\\t%s\" % (qseqid, tax_id, score, sseqid))\n    if output:\n        with open(out_f, \"w\") as fh:\n            print(BtLog.status_d['24'] % out_f)\n            fh.write(\"\\n\".join(output) + \"\\n\")\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/view.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"usage: blobtools view    -i <BLOBDB> [-x <TAXRULE>] [--rank <TAXRANK>...] [--hits]\n                            [--list <LIST>] [--out <OUT>] [--notable]\n                            [--concoct] [--cov] [--experimental <META>]\n                            [--h|--help]\n\n    Options:\n        --h --help                  show this\n        -i, --input <BLOBDB>        BlobDB file (created with \"blobtools create\")\n        -o, --out <OUT>             Output prefix\n        -l, --list <LIST>           List of sequence names (file).\n        -x, --taxrule <TAXRULE>     Taxrule used for computing taxonomy\n                                    (supported: \"bestsum\", \"bestsumorder\")\n                                    [default: bestsum]\n        -r, --rank <TAXRANK>...     Taxonomic rank(s) at which output will be written.\n                                    (supported: 'species', 'genus', 'family', 'order',\n                                    'phylum', 'superkingdom', 'all') [default: phylum]\n        -b, --hits                  Displays taxonomic hits from tax files\n                                    that contributed to the taxonomy.\n        --concoct                   Generate concoct files [default: False]\n        --cov                       Generate cov files [default: False]\n        --experimental <META>       Experimental output [default: False]\n        -n, --notable               Do not generate table view [default: False]\n\"\"\"\n\nfrom docopt import docopt\nfrom os.path import isfile\n\nimport lib.BtCore as BtCore\nimport lib.BtLog as BtLog\nimport lib.BtIO as BtIO\nimport lib.interface as interface\nTAXRULES = ['bestsum', 'bestsumorder']\nRANKS = ['species', 'genus', 'family', 'order', 'phylum', 'superkingdom', 'all']\n\ndef main():\n    #print(data_dir)\n    args = docopt(__doc__)\n    blobdb_f = args['--input']\n    prefix = args['--out']\n    ranks = args['--rank']\n    taxrule = args['--taxrule']\n    hits_flag = args['--hits']\n    seq_list_f = args['--list']\n    concoct = args['--concoct']\n    cov = args['--cov']\n    notable = args['--notable']\n    experimental = args['--experimental']\n    # Does blobdb_f exist ?\n    if not isfile(blobdb_f):\n        BtLog.error('0', blobdb_f)\n\n    out_f = BtIO.getOutFile(blobdb_f, prefix, None)\n\n    # Are ranks sane ?\n    if 'all' in ranks:\n        temp_ranks = RANKS[0:-1]\n        ranks = temp_ranks[::-1]\n    else:\n        for rank in ranks:\n            if rank not in RANKS:\n                BtLog.error('9', rank)\n\n    # Does seq_list file exist?\n    seqs = []\n    if (seq_list_f):\n        if isfile(seq_list_f):\n            seqs = BtIO.parseList(seq_list_f)\n        else:\n            BtLog.error('0', seq_list_f)\n\n    # Load BlobDb\n    blobDb = BtCore.BlobDb('new')\n    print(BtLog.status_d['9'] % (blobdb_f))\n    blobDb.load(blobdb_f)\n    blobDb.version = interface.__version__\n\n    # Is taxrule sane and was it computed?\n    if (blobDb.hitLibs) and taxrule not in blobDb.taxrules:\n        BtLog.error('11', taxrule, blobDb.taxrules)\n\n    # view(s)\n    viewObjs = []\n    print(BtLog.status_d['14'])\n    if not (notable):\n        tableView = None\n        if len(blobDb.hitLibs) > 1:\n            tableView = BtCore.ViewObj(name=\"table\", out_f=out_f, suffix=\"%s.table.txt\" % (taxrule), body=[])\n        else:\n            tableView = BtCore.ViewObj(name=\"table\", out_f=out_f, suffix=\"table.txt\", body=[])\n        viewObjs.append(tableView)\n    if not experimental == 'False':\n        meta = {}\n        if isfile(experimental):\n            meta = BtIO.readYaml(experimental)\n        experimentalView = BtCore.ExperimentalViewObj(name = \"experimental\", view_dir=out_f, blobDb=blobDb, meta=meta)\n        viewObjs.append(experimentalView)\n    if (concoct):\n        concoctTaxView = None\n        concoctCovView = None\n        if len(blobDb.hitLibs) > 1:\n            concoctTaxView = BtCore.ViewObj(name=\"concoct_tax\", out_f=out_f, suffix=\"%s.concoct_taxonomy_info.csv\" % (taxrule), body=dict())\n            concoctCovView = BtCore.ViewObj(name=\"concoct_cov\", out_f=out_f, suffix=\"%s.concoct_coverage_info.tsv\" % (taxrule), body=[])\n        else:\n            concoctTaxView = BtCore.ViewObj(name=\"concoct_tax\", out_f=out_f, suffix=\"concoct_taxonomy_info.csv\", body=dict())\n            concoctCovView = BtCore.ViewObj(name=\"concoct_cov\", out_f=out_f, suffix=\"concoct_coverage_info.tsv\", body=[])\n        viewObjs.append(concoctTaxView)\n        viewObjs.append(concoctCovView)\n    if (cov):\n        for cov_lib_name, covLibDict in blobDb.covLibs.items():\n            out_f = BtIO.getOutFile(covLibDict['f'], prefix, None)\n            covView = BtCore.ViewObj(name=\"covlib\", out_f=out_f, suffix=\"cov\", body=[])\n            blobDb.view(viewObjs=[covView], ranks=None, taxrule=None, hits_flag=None, seqs=None, cov_libs=[cov_lib_name], progressbar=True)\n    if (viewObjs):\n        #for viewObj in viewObjs:\n        #    print(viewObj.name)\n        blobDb.view(viewObjs=viewObjs, ranks=ranks, taxrule=taxrule, hits_flag=hits_flag, seqs=seqs, cov_libs=[], progressbar=True)\n    print(BtLog.status_d['19'])\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "requirements.txt",
    "content": "docopt\nmatplotlib\ntqdm\npysam\npyyaml>=4.2b1"
  },
  {
    "path": "setup.cfg",
    "content": "[bdist_wheel]\nuniversal=1\n\n[metadata]\ndescription-file=README.md"
  },
  {
    "path": "setup.py",
    "content": "import pip\nfrom setuptools import setup, find_packages\n\n__version__ = '1.1'\n\n# Get the long description from the README file\nwith open('README.md', 'r') as readme:\n    long_description = readme.read()\n\n# get the dependencies and installs\nwith open('requirements.txt', 'r') as requirements:\n    reqs = requirements.read().splitlines()\n\nsetup(\n    name='blobtools',\n    version=__version__,\n    description='A modular command-line solution for visualisation, quality control and taxonomic partitioning of genome datasets',\n    long_description=long_description,\n    url='https://github.com/DRL/blobtools',\n    download_url='https://github.com/DRL/blobtools/tarball/' + __version__,\n    license='GnuGPL3',\n    classifiers=[\n      'Development Status :: 4 - Beta',\n      'Operating System :: POSIX',\n      'Topic :: Scientific/Engineering :: Bio-Informatics',\n      'Topic :: Scientific/Engineering :: Visualization',\n      'Programming Language :: Python :: 3',\n    ],\n    keywords='Bioinformatics visualisation genome assembly QC',\n    packages=find_packages(exclude=['docs', 'tests*']),\n    include_package_data=True,\n    author='Dominik R Laetsch',\n    entry_points={\n        'console_scripts': [\n            \"blobtools=lib.interface:main\",\n            ],\n        },\n    author_email='dominik.laetsch@gmail.com'\n)\n"
  },
  {
    "path": "test/meta.json",
    "content": "{\"id\": \"test\", \"name\": \"test\", \"records\": 10, \"record_type\": \"contigs\", \"fields\": [{\"id\": \"length\", \"name\": \"Length\", \"type\": \"variable\", \"datatype\": \"integer\", \"range\": [216, 6273], \"scale\": \"scaleLog\", \"preload\": true}, {\"id\": \"gc\", \"name\": \"GC\", \"type\": \"variable\", \"datatype\": \"float\", \"range\": "
  }
]