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