diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..d9e5fb7 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,52 @@ +v0.10.3-beta: +* remove Fatal.pm use in kraken-report +* fixed false success message on make failure in installer +* explicitly require g++ as C++ compiler in Makefile +* change to quickfile.cpp to do proper syncing on close +* fixed kraken-build bug w/ --work-on-disk (cause of some major build stalls) +* changed hash size calculation to use Perl +* close input files explicitly in db_sort/db_shrink to reduce reported memory +* allow db_shrink to work in RAM +* updates to README file + +v0.10.2-beta: +* fixed kraken-report bug w/ --show-zeros +* fixed kraken-report installation bug +* updates to README file + +v0.10.1-beta: +* fixed 2nd bug in build_kraken.sh in calculating hash size (thanks T. Antao) +* fixed bug in add_to_library.sh for some bash versions (thanks T. Antao) +* fixed issue where search window wasn't cached until a failure (query speedup) +* added $KRAKEN_DIR fallback for kraken/kraken-build (thanks S. Koren) + +v0.10.0-beta: +* added CHANGELOG +* fixed quick mode hit list output +* updated README citation +* changed minimizer sort order (query speedup), changes database structure +* use linear search with small windows (query speedup) +* changed query procedure (query speedup); search w/o 1st calculating minimizer +* changed readlink in installer to perl Cwd::abs_path (portability) +* removed MAP_POPULATE for preloading, uses read loop instead (bugfix/port.) +* added --work-on-disk switch to kraken-build +* added kraken-report script +* fixed bug in build_kraken.sh in calculating hash size (thanks T. Antao) + +v0.9.1b: +* fixed bug to allow kraken-build --shrink + +v0.9.0b: +* full rewrite +* minimizers used to speed queries, prefix index removed + +v0.3: +* DB build parallelized, Jellyfish removed from LCA assignment + +v0.2: +* full rewrite, most progs. changed to C++ +* Jellyfish removed from classification step +* prefix index used to speed queries + +v0.1: +* initial version, mostly Perl diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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. + + + Copyright (C) + + 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: + + Copyright (C) + 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 +. diff --git a/install_kraken.sh b/install_kraken.sh new file mode 100755 index 0000000..8e0674f --- /dev/null +++ b/install_kraken.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +set -e + +VERSION="0.10.3-beta" + +if [ -z "$1" ] || [ -n "$2" ] +then + echo "Usage: $(basename $0) KRAKEN_DIR" + exit 64 +fi + +if [ "$1" = "KRAKEN_DIR" ] +then + echo "Please replace \"KRAKEN_DIR\" with the name of the directory" + echo "that you want to install Kraken in." + exit 1 +fi + +# Perl cmd used to canonicalize dirname - "readlink -f" doesn't work +# on OS X. +export KRAKEN_DIR=$(perl -MCwd=abs_path -le 'print abs_path(shift)' "$1") + +(cd src && make) +mkdir -p "$KRAKEN_DIR" +for file in scripts/*.broken +do + perl -pl -e 'BEGIN { while (@ARGV) { $_ = shift; ($k,$v) = split /=/, $_, 2; $H{$k} = $v } }'\ + -e 's/#####=(\w+)=#####/$H{$1}/g' \ + "KRAKEN_DIR=$KRAKEN_DIR" "VERSION=$VERSION" \ + < "$file" > "$KRAKEN_DIR/$(basename $file .broken)" +done +cp scripts/*.sh "$KRAKEN_DIR" +make -C src install +chmod -R +x "$KRAKEN_DIR" + +echo +echo "Kraken installation complete." +echo +echo "To make things easier for you, you may want to copy/symlink the following" +echo "files into a directory in your PATH:" +echo " $KRAKEN_DIR/kraken" +echo " $KRAKEN_DIR/kraken-build" +echo " $KRAKEN_DIR/kraken-report" diff --git a/scripts/add_to_library.sh b/scripts/add_to_library.sh new file mode 100755 index 0000000..fa25dc6 --- /dev/null +++ b/scripts/add_to_library.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Copy specified file into a Kraken library + +set -u # Protect against uninitialized vars. +set -e # Stop on error + +LIBRARY_DIR="$KRAKEN_DB_NAME/library" + +if [ ! -e "$1" ] +then + echo "Can't add \"$1\": file does not exist" + exit 1 +fi +if [ ! -f "$1" ] +then + echo "Can't add \"$1\": not a regular file" + exit 1 +fi + +if ! head -1 "$1" | perl -nle 'exit 1 unless /^>gi\|(\d+)\|/' +then + echo "Can't add \"$1\": could not find GI number" + exit 1 +fi +seq_ct=$(grep -m2 '^>' "$1" | wc -l) +if (( seq_ct > 1 )) +then + echo "Can't add \"$1\": multiple sequences found" + exit 1 +fi + +mkdir -p "$LIBRARY_DIR/added" +ct=0 +freefile="" +while [ -z "$freefile" ] +do + freefile=$(seq -f '%015g' $ct $ct).fna + if [ -e "$LIBRARY_DIR/added/$freefile" ] + then + ct=$(($ct + 1)) + freefile="" + fi +done +cp "$1" "$LIBRARY_DIR/added/$freefile" +echo "Added \"$1\" to library ($KRAKEN_DB_NAME)" diff --git a/scripts/build_kraken_db.sh b/scripts/build_kraken_db.sh new file mode 100755 index 0000000..c9a29dd --- /dev/null +++ b/scripts/build_kraken_db.sh @@ -0,0 +1,186 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Build a Kraken database +# Designed to be called by kraken_build + +set -u # Protect against uninitialized vars. +set -e # Stop on error +set -o pipefail # Stop on failures in non-final pipeline commands + +function report_time_elapsed() { + curr_time=$(date "+%s.%N") + perl -e '$time = $ARGV[1] - $ARGV[0];' \ + -e '$sec = int($time); $nsec = $time - $sec;' \ + -e '$min = int($sec/60); $sec %= 60;' \ + -e '$hr = int($min/60); $min %= 60;' \ + -e 'print "${hr}h" if $hr;' \ + -e 'print "${min}m" if $min || $hr;' \ + -e 'printf "%.3fs", $sec + $nsec;' \ + $1 $curr_time +} + +start_time=$(date "+%s.%N") + +DATABASE_DIR="$KRAKEN_DB_NAME" + +if [ ! -d "$DATABASE_DIR" ] +then + echo "Can't find Kraken DB directory \"$KRAKEN_DB_NAME\"" + exit 1 +fi +cd "$DATABASE_DIR" + +MEMFLAG="" +if [ -z "$KRAKEN_WORK_ON_DISK" ] +then + MEMFLAG="-M" + echo "Kraken build set to minimize disk writes." +else + echo "Kraken build set to minimize RAM usage." +fi + +if [ -e "database.jdb" ] +then + echo "Skipping step 1, k-mer set already exists." +else + echo "Creating k-mer set (step 1 of 6)..." + start_time1=$(date "+%s.%N") + + # Estimate hash size as 1.15 * chars in library FASTA files + if [ -z "$KRAKEN_HASH_SIZE" ] + then + KRAKEN_HASH_SIZE=$(find library/ -name '*.fna' -printf '%s\n' | perl -nle '$sum += $_; END {printf "%d\n", 1.15 * $sum}') + echo "Hash size not specified, using '$KRAKEN_HASH_SIZE'" + fi + + find library/ -name '*.fna' -print0 | xargs -0 cat | \ + jellyfish count -m $KRAKEN_KMER_LEN -s $KRAKEN_HASH_SIZE -C -t $KRAKEN_THREAD_CT \ + -o database /dev/fd/0 + + # Merge only if necessary + if [ -e "database_1" ] + then + jellyfish merge -o database.jdb.tmp database_* + else + mv database_0 database.jdb.tmp + fi + + # Once here, DB is finalized, can put file in place. + mv database.jdb.tmp database.jdb + + echo "K-mer set created. [$(report_time_elapsed $start_time1)]" +fi + +if [ -z "$KRAKEN_MAX_DB_SIZE" ] +then + echo "Skipping step 2, no database reduction requested." +else + if [ -e "database.jdb.big" ] + then + echo "Skipping step 2, database reduction already done." + else + start_time1=$(date "+%s.%N") + kdb_size=$(stat -c '%s' database.jdb) + idx_size=$(echo "8 * (4 ^ $KRAKEN_MINIMIZER_LEN + 2)" | bc) + resize_needed=$(echo "scale = 10; ($kdb_size+$idx_size)/(2^30) > $KRAKEN_MAX_DB_SIZE" | bc) + if (( resize_needed == 0 )) + then + echo "Skipping step 2, database reduction unnecessary." + else + echo "Reducing database size (step 2 of 6)..." + max_kdb_size=$(echo "$KRAKEN_MAX_DB_SIZE*2^30 - $idx_size" | bc) + if (( $(echo "$max_kdb_size < 0" | bc) == 1 )) + then + echo "Maximum database size too small, aborting reduction." + exit 1 + fi + # Key ct is 8 byte int stored 48 bytes from start of file + key_ct=$(perl -MFcntl -le 'open F, "database.jdb"; seek F, 48, SEEK_SET; read F, $b, 8; $a = unpack("Q", $b); print $a') + overage=$(echo "($kdb_size - $max_kdb_size + 11) / 12" | bc) + percentage=$(echo "100 * ($key_ct - $overage) / $key_ct" | bc) + echo "Using $percentage percent of original database." + db_shrink $MEMFLAG -d database.jdb -o database.jdb.small -p $percentage + mv database.jdb database.jdb.big.tmp + mv database.jdb.small database.jdb + mv database.jdb.big.tmp database.jdb.big + echo "Database reduced. [$(report_time_elapsed $start_time1)]" + fi + fi +fi + +if [ -e "database.kdb" ] +then + echo "Skipping step 3, k-mer set already sorted." +else + echo "Sorting k-mer set (step 3 of 6)..." + start_time1=$(date "+%s.%N") + db_sort -z $MEMFLAG -t $KRAKEN_THREAD_CT -n $KRAKEN_MINIMIZER_LEN \ + -d database.jdb -o database.kdb.tmp \ + -i database.idx + + # Once here, DB is sorted, can put file in proper place. + mv database.kdb.tmp database.kdb + + echo "K-mer set sorted. [$(report_time_elapsed $start_time1)]" +fi + +if [ -e "gi2file.map" ] +then + echo "Skipping step 4, GI number to file map already complete." +else + echo "Creating GI number to file map (step 4 of 6)..." + start_time1=$(date "+%s.%N") + find library/ -name '*.fna' -print0 | \ + xargs -0 grep -m1 -H '^>' | \ + awk -F '\\|' '{ sub(/:>gi$/, "", $1); print $2 "|" $1 }' \ + > gi2file.map.tmp + mv gi2file.map.tmp gi2file.map + + echo "GI number to file map created. [$(report_time_elapsed $start_time1)]" +fi + +if [ -e "file2taxon.map" ] +then + echo "Skipping step 5, file to taxon map already complete." +else + echo "Creating file to taxon map (step 5 of 6)..." + start_time1=$(date "+%s.%N") + make_file_to_taxon_map taxonomy/gi_taxid_nucl.dmp gi2file.map \ + > file2taxon.map.tmp + mv file2taxon.map.tmp file2taxon.map + line_ct=$(wc -l file2taxon.map | awk '{print $1}') + + echo "$line_ct files mapped to taxa. [$(report_time_elapsed $start_time1)]" +fi + +if [ -e "lca.complete" ] +then + echo "Skipping step 6, LCAs already set." +else + echo "Setting LCAs in database (step 6 of 6)..." + start_time1=$(date "+%s.%N") + set_lcas $MEMFLAG -x -d database.kdb -i database.idx \ + -n taxonomy/nodes.dmp -t $KRAKEN_THREAD_CT -f file2taxon.map + touch "lca.complete" + + echo "Database LCAs set. [$(report_time_elapsed $start_time1)]" +fi + +echo "Database construction complete. [Total: $(report_time_elapsed $start_time)]" diff --git a/scripts/clean_db.sh b/scripts/clean_db.sh new file mode 100755 index 0000000..84bf208 --- /dev/null +++ b/scripts/clean_db.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Clean unneeded files from a database + +set -u # Protect against uninitialized vars. +set -e # Stop on error + +cd "$KRAKEN_DB_NAME" + +[ -e "database.kdb" ] || (echo "Incomplete database, clean aborted."; exit 1) +[ -e "database.idx" ] || (echo "Incomplete database, clean aborted."; exit 1) +[ -e "taxonomy/nodes.dmp" ] || (echo "Incomplete database, clean aborted."; exit 1) +[ -e "taxonomy/names.dmp" ] || (echo "Incomplete database, clean aborted."; exit 1) + +rm -rf library +rm -f database.jdb* database_* *.map lca.complete +mkdir newtaxo +mv taxonomy/{nodes,names}.dmp newtaxo +rm -rf taxonomy +mv newtaxo taxonomy diff --git a/scripts/download_genomic_library.sh b/scripts/download_genomic_library.sh new file mode 100755 index 0000000..d567b22 --- /dev/null +++ b/scripts/download_genomic_library.sh @@ -0,0 +1,95 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Download specific genomic libraries for use with Kraken. +# Supported choices are: +# bacteria - NCBI RefSeq complete bacterial/archaeal genomes +# viruses - NCBI RefSeq complete viral genomes +# human - NCBI RefSeq GRCh37 human reference genome + +set -u # Protect against uninitialized vars. +set -e # Stop on error + +LIBRARY_DIR="$KRAKEN_DB_NAME/library" +NCBI_SERVER="ftp.ncbi.nih.gov" +FTP_SERVER="ftp://$NCBI_SERVER" +RSYNC_SERVER="rsync://$NCBI_SERVER" +THIS_DIR=$PWD + +case "$1" in + "bacteria") + mkdir -p $LIBRARY_DIR/Bacteria + cd $LIBRARY_DIR/Bacteria + if [ ! -e "lib.complete" ] + then + rm -f all.fna.tar.gz + wget $FTP_SERVER/genomes/Bacteria/all.fna.tar.gz + echo -n "Unpacking..." + tar zxf all.fna.tar.gz + rm all.fna.tar.gz + echo " complete." + touch "lib.complete" + else + echo "Skipping download of bacterial genomes, already downloaded here." + fi + ;; + "viruses") + mkdir -p $LIBRARY_DIR/Viruses + cd $LIBRARY_DIR/Viruses + if [ ! -e "lib.complete" ] + then + rm -f all.fna.tar.gz + wget $FTP_SERVER/genomes/Viruses/all.fna.tar.gz + echo -n "Unpacking..." + tar zxf all.fna.tar.gz + rm all.fna.tar.gz + echo " complete." + touch "lib.complete" + else + echo "Skipping download of viral genomes, already downloaded here." + fi + ;; + "human") + if [ ! -e "$LIBRARY_DIR/H_sapiens/lib.complete" ] + then + rsync -avz --include "H_sapiens/" --include "*/CHR_*/" --include "hs_ref_GRCh37*.fa.gz" --exclude "*" \ + $RSYNC_SERVER/genomes/H_sapiens $LIBRARY_DIR + for gzfile in $LIBRARY_DIR/H_sapiens/*/*.gz + do + dir=$(dirname $gzfile) + cd $dir + gunzip $(basename $gzfile) + echo "Unzipped $(basename $gzfile)" + cd $THIS_DIR + done + for fafile in $LIBRARY_DIR/H_sapiens/*/*.fa + do + mv $fafile ${fafile%.fa}.fna + echo "Renamed $(basename $fafile)" + done + touch "$LIBRARY_DIR/H_sapiens/lib.complete" + else + echo "Skipping download of human genome, already downloaded here." + fi + ;; + *) + echo "Unsupported library. Valid options are: " + echo " bacteria virus human" + ;; +esac diff --git a/scripts/download_taxonomy.sh b/scripts/download_taxonomy.sh new file mode 100755 index 0000000..2b35a86 --- /dev/null +++ b/scripts/download_taxonomy.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Download NCBI taxonomy information for Kraken. +# Designed to be called by kraken_build + +set -u # Protect against uninitialized vars. +set -e # Stop on error + +TAXONOMY_DIR="$KRAKEN_DB_NAME/taxonomy" +NCBI_SERVER="ftp.ncbi.nih.gov" +FTP_SERVER="ftp://$NCBI_SERVER" +THIS_DIR=$PWD + +mkdir -p "$TAXONOMY_DIR" +cd "$TAXONOMY_DIR" + +if [ ! -e "gimap.dlflag" ] +then + wget $FTP_SERVER/pub/taxonomy/gi_taxid_nucl.dmp.gz + touch gimap.dlflag + echo "Downloaded GI to taxon map" +fi + +if [ ! -e "taxdump.dlflag" ] +then + wget $FTP_SERVER/pub/taxonomy/taxdump.tar.gz + touch taxdump.dlflag + echo "Downloaded taxonomy tree data" +fi + +if [ ! -e "gimap.flag" ] +then + gunzip gi_taxid_nucl.dmp.gz + touch gimap.flag + echo "Uncompressed GI to taxon map" +fi + +if [ ! -e "taxdump.flag" ] +then + tar zxf taxdump.tar.gz + touch taxdump.flag + echo "Uncompressed taxonomy tree data" +fi diff --git a/scripts/kraken-build.broken b/scripts/kraken-build.broken new file mode 100755 index 0000000..37804cf --- /dev/null +++ b/scripts/kraken-build.broken @@ -0,0 +1,286 @@ +#!/usr/bin/perl + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +use strict; +use warnings; +use File::Basename; +use Getopt::Long; + +my $PROG = basename $0; +my $KRAKEN_DIR = "#####=KRAKEN_DIR=#####"; + +# Test to see if the executables got moved, try to recover if we can +if (! -e "$KRAKEN_DIR/classify") { + use Cwd 'abs_path'; + $KRAKEN_DIR = dirname abs_path($0); +} + +$ENV{"KRAKEN_DIR"} = $KRAKEN_DIR; +$ENV{"PATH"} = "$KRAKEN_DIR:$ENV{PATH}"; + +my $DEF_MINIMIZER_LEN = 15; +my $DEF_KMER_LEN = 31; +my $DEF_THREAD_CT = 1; + +my @VALID_LIBRARY_TYPES = qw/bacteria viruses human/; + +# Option/task option variables +my ( + $db, + $threads, + $minimizer_len, + $kmer_len, + $new_db, + $hash_size, + $max_db_size, + $work_on_disk, + + $dl_taxonomy, + $dl_library, + $add_to_library, + $build, + $shrink, + $standard, + $upgrade, + $clean, +); + +$threads = $DEF_THREAD_CT; +$minimizer_len = $DEF_MINIMIZER_LEN; +$kmer_len = $DEF_KMER_LEN; +$work_on_disk = ""; +$hash_size = ""; +$max_db_size = ""; + +# variables corresponding to task options +my @TASK_LIST = ( + \$dl_taxonomy, + \$dl_library, + \$add_to_library, + \$build, + \$shrink, + \$standard, + \$upgrade, + \$clean, +); + +GetOptions( + "help" => \&display_help, + "version" => \&display_version, + + "db=s" => \$db, + "threads=i" => \$threads, + "minimizer-len=i", \$minimizer_len, + "kmer-len=i", \$kmer_len, + "new-db=s", \$new_db, + "jellyfish-hash-size=s", \$hash_size, + "max-db-size=s", \$max_db_size, + "work-on-disk", \$work_on_disk, + + "download-taxonomy" => \$dl_taxonomy, + "download-library=s" => \$dl_library, + "add-to-library=s" => \$add_to_library, + "build" => \$build, + "shrink=i" => \$shrink, + "upgrade" => \$upgrade, + "standard" => \$standard, + "clean" => \$clean, +) or usage(); + +if (@ARGV) { + warn "Extra arguments on command line.\n"; + usage(); +} +my $task_options = 0; +for my $flag_ref (@TASK_LIST) { + defined($$flag_ref) and $task_options++; +} +if ($task_options > 1) { + warn "More than one task option selected.\n"; + usage(); +} +if ($task_options == 0) { + warn "Must select a task option.\n"; + usage(); +} + +if (! defined $db) { + die "Must specify a database name\n"; +} +if ($threads <= 0) { + die "Can't use nonpositive thread count of $threads\n"; +} +if ($minimizer_len >= $kmer_len) { + die "Minimizer length ($minimizer_len) must be less than k ($kmer_len)\n"; +} +if ($minimizer_len <= 0) { + die "Can't use nonpositive minimizer length of $minimizer_len\n"; +} +if ($kmer_len <= 2) { + die "Can't use k of $kmer_len (must be >= 2)\n"; +} +if ($kmer_len > 31) { + die "Can't use k of $kmer_len (must be <= 31)\n"; +} +if ($hash_size !~ /^(\d+[kKmMgG]?)?$/) { + die "Illegal hash size string\n"; +} +if ($max_db_size !~ /^$/ && $max_db_size <= 0) { + die "Can't have negative max database size.\n"; +} + +$ENV{"KRAKEN_DB_NAME"} = $db; +$ENV{"KRAKEN_THREAD_CT"} = $threads; +$ENV{"KRAKEN_MINIMIZER_LEN"} = $minimizer_len; +$ENV{"KRAKEN_KMER_LEN"} = $kmer_len; +$ENV{"KRAKEN_HASH_SIZE"} = $hash_size; +$ENV{"KRAKEN_MAX_DB_SIZE"} = $max_db_size; +$ENV{"KRAKEN_WORK_ON_DISK"} = $work_on_disk; + +if ($dl_taxonomy) { + download_taxonomy(); +} +elsif (defined($dl_library)) { + download_library($dl_library); +} +elsif (defined($add_to_library)) { + add_to_library($add_to_library); +} +elsif (defined($shrink)) { + shrink_db($shrink); +} +elsif ($standard) { + standard_installation(); +} +elsif ($build) { + build_database(); +} +elsif ($clean) { + clean_database(); +} +elsif ($upgrade) { + upgrade_database(); +} +else { + usage(); +} + +exit -1; +# END OF MAIN CODE. + +sub usage { + my $exit_code = @_ ? shift : 64; + print STDERR < 0)\n"; + } + if ($percentage >= 100) { + die "Can't use shrink percentage of $percentage (must be < 100)\n"; + } + if (! defined($new_db)) { + die "Must specify new database name to perform shrink task\n"; + } + exec "shrink_db.sh", $percentage, $new_db; +} + +sub standard_installation { + exec "standard_installation.sh"; +} + +sub build_database { + exec "build_kraken_db.sh"; +} + +sub clean_database { + exec "clean_db.sh"; +} + +sub upgrade_database { + exec "upgrade_db.sh"; +} diff --git a/scripts/kraken-report.broken b/scripts/kraken-report.broken new file mode 100755 index 0000000..eb60d15 --- /dev/null +++ b/scripts/kraken-report.broken @@ -0,0 +1,133 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use File::Basename; +use Getopt::Long; + +my $PROG = basename $0; +my $show_zeros = 0; +my $db_prefix = ""; + +GetOptions( + "help" => \&display_help, + "version" => \&display_version, + "show-zeros" => \$show_zeros, + "db=s" => \$db_prefix, +); + +sub display_help { + print STDERR "Usage: $PROG --db KRAKEN_DB_NAME [--show-zeros] \n"; + exit 0; +} + +sub display_version { + print "Kraken version #####=VERSION=#####\n"; + print "Copyright 2013, Derrick Wood (dwood\@cs.umd.edu)\n"; + exit 0; +} + +my (%child_lists, %name_map, %rank_map); +load_taxonomy($db_prefix); + +my %taxo_counts; +my $seq_count = 0; +$taxo_counts{0} = 0; +while (<>) { + my @fields = split; + $taxo_counts{$fields[2]}++; + $seq_count++; +} +my $classified_count = $seq_count - $taxo_counts{0}; + +my %clade_counts = %taxo_counts; +dfs_summation(1); + +for (keys %name_map) { + $clade_counts{$_} ||= 0; +} + +printf "%6.2f\t%d\t%d\t%s\t%d\t%s%s\n", + $clade_counts{0} * 100 / $seq_count, + $clade_counts{0}, $taxo_counts{0}, "U", + 0, "", "unclassified"; +dfs_report(1, 0); + +sub dfs_report { + my $node = shift; + my $depth = shift; + if (! $clade_counts{$node} && ! $show_zeros) { + return; + } + printf "%6.2f\t%d\t%d\t%s\t%d\t%s%s\n", + ($clade_counts{$node} || 0) * 100 / $seq_count, + ($clade_counts{$node} || 0), + ($taxo_counts{$node} || 0), + rank_code($rank_map{$node}), + $node, + " " x $depth, + $name_map{$node}; + my $children = $child_lists{$node}; + if ($children) { + my @sorted_children = sort { $clade_counts{$b} <=> $clade_counts{$a} } @$children; + for my $child (@sorted_children) { + dfs_report($child, $depth + 1); + } + } +} + +sub rank_code { + my $rank = shift; + for ($rank) { + $_ eq "species" and return "S"; + $_ eq "genus" and return "G"; + $_ eq "family" and return "F"; + $_ eq "order" and return "O"; + $_ eq "class" and return "C"; + $_ eq "phylum" and return "P"; + } + return "-"; +} + +sub dfs_summation { + my $node = shift; + my $children = $child_lists{$node}; + if ($children) { + for my $child (@$children) { + dfs_summation($child); + $clade_counts{$node} += ($clade_counts{$child} || 0); + } + } +} + +sub load_taxonomy { + my $prefix = shift; + + open NAMES, "<", "$prefix/taxonomy/names.dmp" + or die "$PROG: can't open names file: $!\n"; + while () { + chomp; + s/\t\|$//; + my @fields = split /\t\|\t/; + my ($node_id, $name, $type) = @fields[0,1,3]; + if ($type eq "scientific name") { + $name_map{$node_id} = $name; + } + } + close NAMES; + + open NODES, "<", "$prefix/taxonomy/nodes.dmp" + or die "$PROG: can't open nodes file: $!\n"; + while () { + chomp; + my @fields = split /\t\|\t/; + my ($node_id, $parent_id, $rank) = @fields[0,1,2]; + if ($node_id == 1) { + $parent_id = 0; + } + $child_lists{$parent_id} ||= []; + push @{ $child_lists{$parent_id} }, $node_id; + $rank_map{$node_id} = $rank; + } + close NODES; +} diff --git a/scripts/kraken.broken b/scripts/kraken.broken new file mode 100755 index 0000000..39027b0 --- /dev/null +++ b/scripts/kraken.broken @@ -0,0 +1,131 @@ +#!/usr/bin/perl + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +use strict; +use warnings; +use File::Basename; +use Getopt::Long; + +my $PROG = basename $0; +my $KRAKEN_DIR = "#####=KRAKEN_DIR=#####"; + +# Test to see if the executables got moved, try to recover if we can +if (! -e "$KRAKEN_DIR/classify") { + use Cwd 'abs_path'; + $KRAKEN_DIR = dirname abs_path($0); +} + +my $CLASSIFY = "$KRAKEN_DIR/classify"; + +my $quick = 0; +my $min_hits = 1; +my $fastq_input = 0; +my $db_prefix = ""; +my $threads = 1; +my $preload = 0; +my $unclassified_out; +my $classified_out; +my $outfile; + +GetOptions( + "help" => \&display_help, + "version" => \&display_version, + "db=s" => \$db_prefix, + "threads=i" => \$threads, + "fastq-input" => \$fastq_input, + "quick" => \$quick, + "min-hits=i" => \$min_hits, + "unclassified-out=s" => \$unclassified_out, + "classified-out=s" => \$classified_out, + "output=s" => \$outfile, + "preload" => \$preload +); + +if (! @ARGV) { + print STDERR "Need to specify input filenames!\n"; + usage(); +} + +my $taxonomy = "$db_prefix/taxonomy/nodes.dmp"; +if ($quick) { + undef $taxonomy; # Skip loading nodes file, not needed in quick mode +} + +my $kdb_file = "$db_prefix/database.kdb"; +my $idx_file = "$db_prefix/database.idx"; +if (! -e $kdb_file) { + die "$PROG: $kdb_file does not exist!\n"; +} +if (! -e $idx_file) { + die "$PROG: $idx_file does not exist!\n"; +} + +if ($min_hits > 1 && ! $quick) { + die "$PROG: --min_hits requires --quick to be specified\n"; +} + +my @flags; +push @flags, "-d", $kdb_file; +push @flags, "-i", $idx_file; +push @flags, "-t", $threads if $threads > 1; +push @flags, "-n", $taxonomy if defined $taxonomy; +push @flags, "-q" if $quick; +push @flags, "-m", $min_hits if $min_hits > 1; +push @flags, "-f" if $fastq_input; +push @flags, "-U", $unclassified_out if defined $unclassified_out; +push @flags, "-C", $classified_out if defined $classified_out; +push @flags, "-o", $outfile if defined $outfile; +push @flags, "-M" if $preload; + +exec $CLASSIFY, @flags, @ARGV; + +sub usage { + my $exit_code = @_ ? shift : 64; + print STDERR < + +Options: + --db NAME Name for Kraken DB + --threads NUM Number of threads + --fastq-input Input is FASTQ, not FASTA format + --quick Quick operation (use first hit or hits) + --min-hits NUM In quick op., number of hits req'd for classification + NOTE: this is ignored if --quick is not specified + --unclassified-out FILENAME + Print unclassified sequences to filename + --classified-out FILENAME + Print classified sequences to filename + --output FILENAME Print output to filename (def. is stdout); "-" will + suppress normal output + --preload Loads DB into memory before classification + --help Print this message + --version Print version information +EOF + exit $exit_code; +} + +sub display_help { + usage(0); +} + +sub display_version { + print "Kraken version #####=VERSION=#####\n"; + print "Copyright 2013, Derrick Wood (dwood\@cs.umd.edu)\n"; + exit 0; +} diff --git a/scripts/shrink_db.sh b/scripts/shrink_db.sh new file mode 100755 index 0000000..b247eed --- /dev/null +++ b/scripts/shrink_db.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Shrink a Kraken database +# Designed to be called by kraken_build + +set -u # Protect against uninitialized vars. +set -e # Stop on error +set -o pipefail # Stop on failures in non-final pipeline commands + +percentage="$1" +new_db="$2" + +OLD_DB_DIR="$KRAKEN_DB_NAME" +NEW_DB_DIR="$new_db" + +if [ -e "$NEW_DB_DIR" ] +then + echo "$new_db already exists ($NEW_DB_DIR), aborting shrink operation." + exit 1 +else + mkdir -p "$NEW_DB_DIR/taxonomy" +fi + +cp "$OLD_DB_DIR/taxonomy/nodes.dmp" "$NEW_DB_DIR/taxonomy" +cp "$OLD_DB_DIR/taxonomy/names.dmp" "$NEW_DB_DIR/taxonomy" +db_shrink -p $percentage -d "$OLD_DB_DIR/database.kdb" \ + -o "$NEW_DB_DIR/database.jdb.tmp" +mv "$NEW_DB_DIR/database.jdb.tmp" "$NEW_DB_DIR/database.jdb" +echo "Reduced database created, now sorting..." +db_sort -M -t $KRAKEN_THREAD_CT -n $KRAKEN_MINIMIZER_LEN \ + -d "$NEW_DB_DIR/database.jdb" -o "$NEW_DB_DIR/database.kdb.tmp" \ + -i "$NEW_DB_DIR/database.idx" +mv "$NEW_DB_DIR/database.kdb.tmp" "$NEW_DB_DIR/database.kdb" +echo "Sort complete, database is ready." diff --git a/scripts/standard_installation.sh b/scripts/standard_installation.sh new file mode 100755 index 0000000..b97fb9e --- /dev/null +++ b/scripts/standard_installation.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Build the standard Kraken database +# Designed to be called by kraken_build + +set -u # Protect against uninitialized vars. +set -e # Stop on error +set -o pipefail # Stop on failures in non-final pipeline commands + +WOD_FLAG="" +if [ -n "$KRAKEN_WORK_ON_DISK" ] +then + WOD_FLAG="--work-on-disk" +fi + +kraken-build --db $KRAKEN_DB_NAME --download-taxonomy +kraken-build --db $KRAKEN_DB_NAME --download-library bacteria +kraken-build --db $KRAKEN_DB_NAME --download-library viruses +kraken-build --db $KRAKEN_DB_NAME --build --threads $KRAKEN_THREAD_CT \ + --jellyfish-hash-size "$KRAKEN_HASH_SIZE" \ + --max-db-size "$KRAKEN_MAX_DB_SIZE" \ + --minimizer-len $KRAKEN_MINIMIZER_LEN \ + --kmer-len $KRAKEN_KMER_LEN \ + $WOD_FLAG diff --git a/scripts/upgrade_db.sh b/scripts/upgrade_db.sh new file mode 100755 index 0000000..211e4f3 --- /dev/null +++ b/scripts/upgrade_db.sh @@ -0,0 +1,85 @@ +#!/bin/bash + +# Copyright 2013, Derrick Wood +# +# This file is part of the Kraken taxonomic sequence classification system. +# +# Kraken 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. +# +# Kraken 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 Kraken. If not, see . + +# Upgrade a pre-v0.10.0-beta Kraken DB to use scrambled minimizer order +# Designed to be called by kraken_build + +set -u # Protect against uninitialized vars. +set -e # Stop on error +set -o pipefail # Stop on failures in non-final pipeline commands + +function report_time_elapsed() { + curr_time=$(date "+%s.%N") + perl -e '$time = $ARGV[1] - $ARGV[0];' \ + -e '$sec = int($time); $nsec = $time - $sec;' \ + -e '$min = int($sec/60); $sec %= 60;' \ + -e '$hr = int($min/60); $min %= 60;' \ + -e 'print "${hr}h" if $hr;' \ + -e 'print "${min}m" if $min || $hr;' \ + -e 'printf "%.3fs", $sec + $nsec;' \ + $1 $curr_time +} + +start_time=$(date "+%s.%N") + +DATABASE_DIR="$KRAKEN_DB_NAME" + +if [ ! -d "$DATABASE_DIR" ] +then + echo "Can't find Kraken DB directory \"$KRAKEN_DB_NAME\"" + exit 1 +fi +cd "$DATABASE_DIR" + +MEMFLAG="" +if [ -n "$KRAKEN_WORK_ON_DISK" ] +then + MEMFLAG="-M" +fi + +if [ -e "old_database.kdb" ] +then + echo "old_database.kdb found - it appears database is already upgraded." + exit 1 +fi + +if [ ! -e "database.kdb" ] +then + echo "Can't find database.kdb file!" + exit 1 +fi +if [ ! -e "database.idx" ] +then + echo "Can't find database.idx file!" + exit 1 +fi + +idx_size=$(stat -c '%s' database.idx) +# Calculate minimizer length based on existing index size +minimizer_len=$(perl -le 'print int(log(shift() / 8 - 2) / log(4))' $idx_size) + +db_sort $MEMFLAG -t $KRAKEN_THREAD_CT -n $minimizer_len -d database.kdb \ + -o newdb.kdb -i newdb.idx +mv database.idx old_database.idx +mv database.kdb old_database.kdb +mv newdb.idx database.idx +mv newdb.kdb database.kdb + +echo "Database upgrade complete. [$(report_time_elapsed $start_time)]" +echo "Old database files are at $KRAKEN_DB_NAME/old_database.{kdb,idx}" diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..3ae5f94 --- /dev/null +++ b/src/Makefile @@ -0,0 +1,35 @@ +CXX = g++ +CXXFLAGS = -Wall -fopenmp -O3 +PROGS = db_sort set_lcas classify make_file_to_taxon_map db_shrink + +.PHONY: all install clean + +all: $(PROGS) + +install: $(PROGS) + cp $(PROGS) $(KRAKEN_DIR)/ + +clean: + rm -f $(PROGS) *.o + +db_shrink: krakendb.o quickfile.o + +db_sort: krakendb.o quickfile.o + +set_lcas: krakendb.o quickfile.o krakenutil.o seqreader.o + +classify: krakendb.o quickfile.o krakenutil.o seqreader.o + +make_file_to_taxon_map: quickfile.o + +krakenutil.o: krakenutil.cpp krakenutil.hpp + $(CXX) $(CXXFLAGS) -c krakenutil.cpp + +krakendb.o: krakendb.cpp krakendb.hpp quickfile.hpp + $(CXX) $(CXXFLAGS) -c krakendb.cpp + +seqreader.o: seqreader.cpp seqreader.hpp quickfile.hpp + $(CXX) $(CXXFLAGS) -c seqreader.cpp + +quickfile.o: quickfile.cpp quickfile.hpp + $(CXX) $(CXXFLAGS) -c quickfile.cpp diff --git a/src/classify.cpp b/src/classify.cpp new file mode 100644 index 0000000..f312c58 --- /dev/null +++ b/src/classify.cpp @@ -0,0 +1,446 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "krakendb.hpp" +#include "krakenutil.hpp" +#include "quickfile.hpp" +#include "seqreader.hpp" + +const size_t DEF_WORK_UNIT_SIZE = 500000; + +using namespace std; +using namespace kraken; + +void parse_command_line(int argc, char **argv); +void usage(int exit_code=EX_USAGE); +void process_file(char *filename); +void classify_sequence(DNASequence &dna, ostringstream &koss, + ostringstream &coss, ostringstream &uoss); +string hitlist_string(vector &taxa, vector &ambig); +set get_ancestry(uint32_t taxon); +void report_stats(struct timeval time1, struct timeval time2); + +int Num_threads = 1; +string DB_filename, Index_filename, Nodes_filename; +bool Quick_mode = false; +bool Fastq_input = false; +bool Print_classified = false; +bool Print_unclassified = false; +bool Print_kraken = true; +bool Populate_memory = false; +uint32_t Minimum_hit_count = 1; +map Parent_map; +KrakenDB Database; +string Classified_output_file, Unclassified_output_file, Kraken_output_file; +ostream *Classified_output; +ostream *Unclassified_output; +ostream *Kraken_output; +size_t Work_unit_size = DEF_WORK_UNIT_SIZE; + +uint64_t total_classified = 0; +uint64_t total_sequences = 0; +uint64_t total_bases = 0; + +int main(int argc, char **argv) { + #ifdef _OPENMP + omp_set_num_threads(1); + #endif + + parse_command_line(argc, argv); + if (! Nodes_filename.empty()) + Parent_map = build_parent_map(Nodes_filename); + + if (Populate_memory) + cerr << "Loading database... "; + + QuickFile db_file; + db_file.open_file(DB_filename); + if (Populate_memory) + db_file.load_file(); + Database = KrakenDB(db_file.ptr()); + KmerScanner::set_k(Database.get_k()); + + QuickFile idx_file; + idx_file.open_file(Index_filename); + if (Populate_memory) + idx_file.load_file(); + KrakenDBIndex db_index(idx_file.ptr()); + Database.set_index(&db_index); + + if (Populate_memory) + cerr << "complete." << endl; + + if (Print_classified) { + if (Classified_output_file == "-") + Classified_output = &cout; + else + Classified_output = new ofstream(Classified_output_file.c_str()); + } + + if (Print_unclassified) { + if (Unclassified_output_file == "-") + Unclassified_output = &cout; + else + Unclassified_output = new ofstream(Unclassified_output_file.c_str()); + } + + if (! Kraken_output_file.empty()) { + if (Kraken_output_file == "-") + Print_kraken = false; + else + Kraken_output = new ofstream(Kraken_output_file.c_str()); + } + else + Kraken_output = &cout; + + struct timeval tv1, tv2; + gettimeofday(&tv1, NULL); + for (int i = optind; i < argc; i++) + process_file(argv[i]); + gettimeofday(&tv2, NULL); + + report_stats(tv1, tv2); + + return 0; +} + +void report_stats(struct timeval time1, struct timeval time2) { + time2.tv_usec -= time1.tv_usec; + time2.tv_sec -= time1.tv_sec; + if (time2.tv_usec < 0) { + time2.tv_sec--; + time2.tv_usec += 1000000; + } + double seconds = time2.tv_usec; + seconds /= 1e6; + seconds += time2.tv_sec; + + cerr << "\r"; + fprintf(stderr, + "%llu sequences (%.2f Mbp) processed in %.3fs (%.1f Kseq/m, %.2f Mbp/m).\n", + (unsigned long long) total_sequences, total_bases / 1.0e6, seconds, + total_sequences / 1.0e3 / (seconds / 60), + total_bases / 1.0e6 / (seconds / 60) ); + fprintf(stderr, " %llu sequences classified (%.2f%%)\n", + (unsigned long long) total_classified, total_classified * 100.0 / total_sequences); + fprintf(stderr, " %llu sequences unclassified (%.2f%%)\n", + (unsigned long long) (total_sequences - total_classified), + (total_sequences - total_classified) * 100.0 / total_sequences); +} + +void process_file(char *filename) { + string file_str(filename); + DNASequenceReader *reader; + DNASequence dna; + + if (Fastq_input) + reader = new FastqReader(file_str); + else + reader = new FastaReader(file_str); + + vector work_units[Num_threads]; + ostringstream kraken_output[Num_threads], + classified_output[Num_threads], + unclassified_output[Num_threads]; + while (reader->is_valid()) { + // Get work for each thread + for (int i = 0; i < Num_threads; i++) { + work_units[i].clear(); + size_t total_nt = 0; + while (total_nt < Work_unit_size) { + dna = reader->next_sequence(); + if (! reader->is_valid()) + break; + total_sequences++; + work_units[i].push_back(dna); + total_nt += dna.seq.size(); + } + total_bases += total_nt; + } + + // Classification loop + #pragma omp parallel for + for (int i = 0; i < Num_threads; i++) { + if (Print_kraken) + kraken_output[i].str(""); + if (Print_classified) + classified_output[i].str(""); + if (Print_unclassified) + unclassified_output[i].str(""); + for (size_t j = 0; j < work_units[i].size(); j++) + classify_sequence( work_units[i][j], kraken_output[i], + classified_output[i], unclassified_output[i] ); + } + + // Report loop + for (int i = 0; i < Num_threads; i++) { + if (Print_kraken) + (*Kraken_output) << kraken_output[i].str(); + if (Print_classified) + (*Classified_output) << classified_output[i].str(); + if (Print_unclassified) + (*Unclassified_output) << unclassified_output[i].str(); + } + + cerr << "\rProcessed " << total_sequences << " sequences (" << total_bases << " bp) ..."; + } + + delete reader; +} + +void classify_sequence(DNASequence &dna, ostringstream &koss, + ostringstream &coss, ostringstream &uoss) { + vector taxa; + vector ambig_list; + map hit_counts; + uint64_t *kmer_ptr; + uint32_t taxon = 0; + uint32_t hits = 0; // only maintained if in quick mode + + uint64_t current_bin_key; + int64_t current_min_pos = 1; + int64_t current_max_pos = 0; + + if (dna.seq.size() >= Database.get_k()) { + KmerScanner scanner(dna.seq); + while ((kmer_ptr = scanner.next_kmer()) != NULL) { + taxon = 0; + if (scanner.ambig_kmer()) { + ambig_list.push_back(1); + } + else { + ambig_list.push_back(0); + uint32_t *val_ptr = Database.kmer_query( + Database.canonical_representation(*kmer_ptr), + ¤t_bin_key, + ¤t_min_pos, ¤t_max_pos + ); + taxon = val_ptr ? *val_ptr : 0; + if (taxon) { + hit_counts[taxon]++; + if (Quick_mode && ++hits >= Minimum_hit_count) + break; + } + } + taxa.push_back(taxon); + } + } + + uint32_t call = 0; + if (Quick_mode) + call = hits >= Minimum_hit_count ? taxon : 0; + else + call = resolve_tree(hit_counts, Parent_map); + + if (call) + #pragma omp atomic + total_classified++; + + if (Print_unclassified || Print_classified) { + ostringstream *oss_ptr = call ? &coss : &uoss; + bool print = call ? Print_classified : Print_unclassified; + if (print) { + if (Fastq_input) { + (*oss_ptr) << "@" << dna.id << endl + << dna.seq << endl + << "+" << endl + << dna.quals << endl; + } + else { + (*oss_ptr) << ">" << dna.id << endl + << dna.seq << endl; + } + } + } + + if (! Print_kraken) + return; + + if (call) { + koss << "C\t"; + } + else { + koss << "U\t"; + } + koss << dna.id << "\t" << call << "\t" << dna.seq.size() << "\t"; + + if (Quick_mode) { + koss << "Q:" << hits; + } + else { + if (taxa.empty()) + koss << "0:0"; + else + koss << hitlist_string(taxa, ambig_list); + } + + koss << endl; +} + +string hitlist_string(vector &taxa, vector &ambig) +{ + int64_t last_code; + int code_count = 1; + ostringstream hitlist; + + if (ambig[0]) { last_code = -1; } + else { last_code = taxa[0]; } + + for (size_t i = 1; i < taxa.size(); i++) { + int64_t code; + if (ambig[i]) { code = -1; } + else { code = taxa[i]; } + + if (code == last_code) { + code_count++; + } + else { + if (last_code >= 0) { + hitlist << last_code << ":" << code_count << " "; + } + else { + hitlist << "A:" << code_count << " "; + } + code_count = 1; + last_code = code; + } + } + if (last_code >= 0) { + hitlist << last_code << ":" << code_count; + } + else { + hitlist << "A:" << code_count; + } + return hitlist.str(); +} + +set get_ancestry(uint32_t taxon) { + set path; + + while (taxon > 0) { + path.insert(taxon); + taxon = Parent_map[taxon]; + } + return path; +} + +void parse_command_line(int argc, char **argv) { + int opt; + int sig; + + if (argc > 1 && strcmp(argv[1], "-h") == 0) + usage(0); + while ((opt = getopt(argc, argv, "d:i:t:u:n:m:o:qfC:U:M")) != -1) { + switch (opt) { + case 'd' : + DB_filename = optarg; + break; + case 'i' : + Index_filename = optarg; + break; + case 't' : + sig = atoi(optarg); + if (sig <= 0) + errx(EX_USAGE, "can't use nonpositive thread count"); + #ifdef _OPENMP + Num_threads = sig; + omp_set_num_threads(Num_threads); + #endif + break; + case 'n' : + Nodes_filename = optarg; + break; + case 'q' : + Quick_mode = true; + break; + case 'm' : + sig = atoi(optarg); + if (sig <= 0) + errx(EX_USAGE, "can't use nonpositive minimum hit count"); + Minimum_hit_count = sig; + break; + case 'f' : + Fastq_input = true; + break; + case 'C' : + Print_classified = true; + Classified_output_file = optarg; + break; + case 'U' : + Print_unclassified = true; + Unclassified_output_file = optarg; + break; + case 'o' : + Kraken_output_file = optarg; + break; + case 'u' : + sig = atoi(optarg); + if (sig <= 0) + errx(EX_USAGE, "can't use nonpositive work unit size"); + Work_unit_size = sig; + break; + case 'M' : + Populate_memory = true; + break; + default: + usage(); + break; + } + } + + if (DB_filename.empty()) { + cerr << "Missing mandatory option -d" << endl; + usage(); + } + if (Index_filename.empty()) { + cerr << "Missing mandatory option -i" << endl; + usage(); + } + if (Nodes_filename.empty() && ! Quick_mode) { + cerr << "Must specify one of -q or -n" << endl; + usage(); + } + if (optind == argc) { + cerr << "No sequence data files specified" << endl; + } +} + +void usage(int exit_code) { + cerr << "Usage: classify [options] " << endl + << endl + << "Options: (*mandatory)" << endl + << "* -d filename Kraken DB filename" << endl + << "* -i filename Kraken DB index filename" << endl + << " -n filename NCBI Taxonomy nodes file" << endl + << " -o filename Output file for Kraken output" << endl + << " -t # Number of threads" << endl + << " -u # Thread work unit size (in bp)" << endl + << " -q Quick operation" << endl + << " -m # Minimum hit count (ignored w/o -q)" << endl + << " -C filename Print classified sequences" << endl + << " -U filename Print unclassified sequences" << endl + << " -f Input is in FASTQ format" << endl + << " -M Preload database files" << endl + << " -h Print this message" << endl + << endl + << "At least one FASTA or FASTQ file must be specified." << endl + << "Kraken output is to standard output by default." << endl; + exit(exit_code); +} diff --git a/src/db_shrink.cpp b/src/db_shrink.cpp new file mode 100644 index 0000000..abb4f58 --- /dev/null +++ b/src/db_shrink.cpp @@ -0,0 +1,126 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" +#include "krakendb.hpp" + +using namespace std; +using namespace kraken; + +string Input_DB_filename, Output_DB_filename; +int Shrink_percentage = 0; +bool Operate_in_RAM = false; + +static void parse_command_line(int argc, char **argv); +static void usage(int exit_code=EX_USAGE); + +int main(int argc, char **argv) { + #ifdef _OPENMP + omp_set_num_threads(1); + #endif + + parse_command_line(argc, argv); + + QuickFile input_db_file(Input_DB_filename); + KrakenDB input_db(input_db_file.ptr()); + + size_t new_file_size = input_db.header_size(); + uint64_t key_ct = input_db.get_key_ct(); + uint64_t new_key_ct = key_ct * Shrink_percentage / 100; + uint64_t pair_size = input_db.pair_size(); + new_file_size += new_key_ct * pair_size; + + QuickFile output_file; + char *temp_file = NULL; + char *outptr; + if (Operate_in_RAM) { + temp_file = new char[new_file_size]; + } + else { + output_file.open_file(Output_DB_filename, "rw", new_file_size); + temp_file = output_file.ptr(); + } + outptr = temp_file; + // Copy input header to output file + memcpy(outptr, input_db.get_ptr(), input_db.header_size()); + // Change key count + memcpy(outptr + 48, &new_key_ct, 8); + outptr += input_db.header_size(); + + char *inptr = input_db.get_pair_ptr(); + // For each 100 consecutive pairs, select the last P pairs of the block + for (uint64_t i = 0; i < new_key_ct; i += Shrink_percentage) { + inptr += (100 - Shrink_percentage) * pair_size; + outptr += Shrink_percentage * pair_size; + memcpy(outptr, inptr, Shrink_percentage * pair_size); + inptr += Shrink_percentage * pair_size; + } + + input_db_file.close_file(); + + if (Operate_in_RAM) { + // Actual file hasn't been opened yet if -M used + output_file.open_file(Output_DB_filename, "w", new_file_size); + memcpy(output_file.ptr(), temp_file, new_file_size); + delete temp_file; + } + + output_file.close_file(); + + return 0; +} + +void parse_command_line(int argc, char **argv) { + int opt; + int sig; + + if (argc > 1 && strcmp(argv[1], "-h") == 0) + usage(0); + while ((opt = getopt(argc, argv, "d:o:p:M")) != -1) { + switch (opt) { + case 'p' : + sig = atoi(optarg); + if (sig < 1 || sig >= 100) + errx(EX_USAGE, "shrink percentage out of range"); + Shrink_percentage = sig; + break; + case 'd' : + Input_DB_filename = optarg; + break; + case 'o' : + Output_DB_filename = optarg; + break; + case 'M' : + Operate_in_RAM = true; + break; + default: + usage(); + break; + } + } + + if (Input_DB_filename.empty() || Output_DB_filename.empty() || ! Shrink_percentage) + usage(); +} + +void usage(int exit_code) { + cerr << "Usage: db_shrink [-M] <-d input db> <-o output db> <-p percentage>\n"; + exit(exit_code); +} diff --git a/src/db_sort.cpp b/src/db_sort.cpp new file mode 100644 index 0000000..1d87d5a --- /dev/null +++ b/src/db_sort.cpp @@ -0,0 +1,187 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" +#include "krakendb.hpp" + +using namespace std; +using namespace kraken; + +string Input_DB_filename, Output_DB_filename, Index_filename; +uint8_t Bin_key_nt = 15; +int Num_threads = 1; +bool Zero_vals = false; +bool Operate_in_RAM = false; +#ifdef _OPENMP +omp_lock_t *Locks; +#endif + +static void parse_command_line(int argc, char **argv); +static void bin_and_sort_data(KrakenDB &in, KrakenDB &out); +static void usage(int exit_code=EX_USAGE); + +int main(int argc, char **argv) { + #ifdef _OPENMP + omp_set_num_threads(1); + #endif + + parse_command_line(argc, argv); + + QuickFile input_db_file(Input_DB_filename); + KrakenDB input_db(input_db_file.ptr()); + + input_db.make_index(Index_filename, Bin_key_nt); + QuickFile index_file(Index_filename); + KrakenDBIndex db_index(index_file.ptr()); + input_db.set_index(&db_index); + + // Copy header from input DB to output DB, reopen output DB in R/W + // open/reopen necessary due to "feature" of QuickFile/KrakenDB code + // (could be skipped if we didn't want to use KrakenDB features in basd() + QuickFile output_file; + char *temp_file; + if (Operate_in_RAM) { + temp_file = new char[ input_db_file.size() ]; + } + else { + output_file.open_file(Output_DB_filename, "w", input_db_file.size()); + temp_file = output_file.ptr(); + } + memcpy(temp_file, input_db_file.ptr(), input_db.header_size()); + if (! Operate_in_RAM) { + output_file.close_file(); + output_file.open_file(Output_DB_filename, "rw"); + temp_file = output_file.ptr(); + } + KrakenDB output_db(temp_file); + + bin_and_sort_data(input_db, output_db); + + if (Operate_in_RAM) { + size_t filesize = input_db_file.size(); + input_db_file.close_file(); + output_file.open_file(Output_DB_filename, "w", filesize); + memcpy(output_file.ptr(), temp_file, filesize); + } + return 0; +} + +static void bin_and_sort_data(KrakenDB &in, KrakenDB &out) { + char *in_ptr = in.get_pair_ptr(); + char *out_ptr = out.get_pair_ptr(); + uint8_t nt = in.get_index()->indexed_nt(); + uint64_t *offsets = in.get_index()->get_array(); + uint64_t entries = 1ull << (nt * 2); + + #ifdef _OPENMP + Locks = new omp_lock_t[entries]; + for (uint64_t i = 0; i < entries; i++) + omp_init_lock(&Locks[i]); + #endif + + // Create a copy of the offsets array for use as insertion positions + vector pos(offsets, offsets + entries); + #pragma omp parallel for schedule(dynamic,400) + for (uint64_t i = 0; i < in.get_key_ct(); i++) { + uint64_t bin_key = in.bin_key(* (uint64_t *)(in_ptr + i * in.pair_size())); + #ifdef _OPENMP + omp_set_lock(&Locks[bin_key]); + #endif + #pragma omp flush(pos) + char *pair_pos = out_ptr + in.pair_size() * pos[bin_key]; + // Copy pair into correct bin (but not final position) + memcpy(pair_pos, in_ptr + i * in.pair_size(), in.pair_size()); + if (Zero_vals) + memset(pair_pos + in.get_key_len(), 0, in.get_val_len()); + #pragma omp flush(pos) + pos[bin_key]++; + #ifdef _OPENMP + omp_unset_lock(&Locks[bin_key]); + #endif + } + + #ifdef _OPENMP + for (uint64_t i = 0; i < entries; i++) + omp_destroy_lock(&Locks[i]); + delete Locks; + #endif + + // Sort all bins + #pragma omp parallel for schedule(dynamic) + for (uint64_t i = 0; i < entries; i++) { + qsort(out_ptr + offsets[i] * out.pair_size(), + offsets[i+1] - offsets[i], out.pair_size(), + KrakenDB::pair_cmp); + } +} + +void parse_command_line(int argc, char **argv) { + int opt; + int sig; + + if (argc > 1 && strcmp(argv[1], "-h") == 0) + usage(0); + while ((opt = getopt(argc, argv, "n:d:o:i:t:zM")) != -1) { + switch (opt) { + case 'n' : + sig = atoi(optarg); + if (sig < 1 || sig > 31) + errx(EX_USAGE, "bin key length out of range"); + Bin_key_nt = (uint8_t) sig; + break; + case 'd' : + Input_DB_filename = optarg; + break; + case 'o' : + Output_DB_filename = optarg; + break; + case 'i' : + Index_filename = optarg; + break; + case 'M' : + Operate_in_RAM = true; + break; + case 't' : + sig = atoi(optarg); + if (sig <= 0) + errx(EX_USAGE, "can't use nonpositive thread count"); + #ifdef _OPENMP + Num_threads = sig; + omp_set_num_threads(Num_threads); + #endif + break; + case 'z' : + Zero_vals = true; + break; + default: + usage(); + break; + } + } + + if (Input_DB_filename.empty() || Output_DB_filename.empty() + || Index_filename.empty()) + usage(); +} + +void usage(int exit_code) { + cerr << "Usage: db_sort [-z] [-M] [-t threads] [-n nt] <-d input db> <-o output db> <-i output idx>\n"; + exit(exit_code); +} diff --git a/src/kraken_headers.hpp b/src/kraken_headers.hpp new file mode 100644 index 0000000..0b691f7 --- /dev/null +++ b/src/kraken_headers.hpp @@ -0,0 +1,31 @@ +#ifndef KRAKEN_HEADERS_HPP +#define KRAKEN_HEADERS_HPP + +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 1 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/src/krakendb.cpp b/src/krakendb.cpp new file mode 100644 index 0000000..d9088cb --- /dev/null +++ b/src/krakendb.cpp @@ -0,0 +1,326 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "krakendb.hpp" +#include "quickfile.hpp" + +using std::string; +using std::vector; + +namespace kraken { + +// File type code for Jellyfish/Kraken DBs +static const char * DATABASE_FILE_TYPE = "JFLISTDN"; + +// File type code on Kraken DB index +// Next byte determines # of indexed nt +static const char * KRAKEN_INDEX_STRING = "KRAKIDX"; + +// File type code for Kraken DB index (v2) +// v2 index corresponds to DB sorted by scrambled order +// Next byte determines # of indexed nt +static const char * KRAKEN_INDEX2_STRING = "KRAKIX2"; + +// XOR mask for minimizer bin keys (allows for better distribution) +// scrambles minimizer sort order +static const uint64_t INDEX2_XOR_MASK = 0xe37e28c4271b5a2dULL; + +// Basic constructor +KrakenDB::KrakenDB() { + fptr = NULL; + index_ptr = NULL; + key_ct = 0; + val_len = 0; + key_len = 0; + key_bits = 0; + k = 0; +} + +// Assumes ptr points to start of a readable mmap'ed file +KrakenDB::KrakenDB(char *ptr) { + index_ptr = NULL; + fptr = ptr; + if (strncmp(ptr, DATABASE_FILE_TYPE, strlen(DATABASE_FILE_TYPE))) + errx(EX_DATAERR, "database in improper format"); + memcpy(&key_bits, ptr + 8, 8); + memcpy(&val_len, ptr + 16, 8); + memcpy(&key_ct, ptr + 48, 8); + if (val_len != 4) + errx(EX_DATAERR, "can only handle 4 byte DB values"); + k = key_bits / 2; + key_len = key_bits / 8 + !! (key_bits % 8); +} + +// Creates an index, indicating starting positions of each bin +// Bins contain k-mer/taxon pairs with k-mers that share a bin key +void KrakenDB::make_index(string index_filename, uint8_t nt) { + uint64_t entries = 1ull << (nt * 2); + vector bin_counts(entries); + char *ptr = get_pair_ptr(); + #pragma omp parallel for schedule(dynamic,400) + for (uint64_t i = 0; i < key_ct; i++) { + uint64_t b_key = bin_key(* (uint64_t *) (ptr + i * pair_size()), nt); + #pragma omp atomic + bin_counts[b_key]++; + } + + uint64_t *bin_offsets = new uint64_t[ entries + 1 ]; + bin_offsets[0] = 0; + for (uint64_t i = 1; i <= entries; i++) + bin_offsets[i] = bin_offsets[i-1] + bin_counts[i-1]; + + QuickFile idx_file(index_filename, "w", + strlen(KRAKEN_INDEX2_STRING) + 1 + sizeof(*bin_offsets) * (entries + 1)); + char *idx_ptr = idx_file.ptr(); + memcpy(idx_ptr, KRAKEN_INDEX2_STRING, strlen(KRAKEN_INDEX2_STRING)); + idx_ptr += strlen(KRAKEN_INDEX2_STRING); + memcpy(idx_ptr++, &nt, 1); + memcpy(idx_ptr, bin_offsets, sizeof(*bin_offsets) * (entries + 1)); +} + +// Simple accessor +char *KrakenDB::get_ptr() { + return fptr; +} + +// Returns start of k-mer/taxon pair array (skips header) +char *KrakenDB::get_pair_ptr() { + return fptr == NULL ? NULL : fptr + header_size(); +} + +// Simple accessor +KrakenDBIndex *KrakenDB::get_index() { + return index_ptr; +} + +// Associates the index with this database +void KrakenDB::set_index(KrakenDBIndex *i_ptr) { + index_ptr = i_ptr; +} + +// Used for sorting pairs within a bin +// Compares k-mers at a and b by simple numeric (as well as lexico.) value +int KrakenDB::pair_cmp(const void *a, const void *b) { + return * ((uint64_t *) a) < * ((uint64_t *) b) + ? -1 + : * ((uint64_t *) a) > * ((uint64_t *) b) + ? 1 : 0; +} + +// Simple accessors/convenience methods +uint8_t KrakenDB::get_k() { return k; } +uint64_t KrakenDB::get_key_bits() { return key_bits; } +uint64_t KrakenDB::get_key_len() { return key_len; } +uint64_t KrakenDB::get_val_len() { return val_len; } +uint64_t KrakenDB::get_key_ct() { return key_ct; } +uint64_t KrakenDB::pair_size() { return key_len + val_len; } +size_t KrakenDB::header_size() { return 72 + 2 * (4 + 8 * key_bits); } + +// Bin key: each k-mer is made of several overlapping m-mers, m < k +// The bin key is the m-mer whose canonical representation is "smallest" +// ("smallest" can refer to lexico. ordering or some other ordering) +uint64_t KrakenDB::bin_key(uint64_t kmer, uint64_t idx_nt) { + uint8_t nt = idx_nt; + uint64_t xor_mask = INDEX2_XOR_MASK; + uint64_t mask = 1 << (nt * 2); + mask--; + xor_mask &= mask; + uint64_t min_bin_key = ~0; + for (uint64_t i = 0; i < key_bits / 2 - nt + 1; i++) { + uint64_t temp_bin_key = xor_mask ^ canonical_representation(kmer & mask, nt); + if (temp_bin_key < min_bin_key) + min_bin_key = temp_bin_key; + kmer >>= 2; + } + return min_bin_key; +} + +// Separate functions to avoid a conditional in the function +// This probably isn't necessary... +uint64_t KrakenDB::bin_key(uint64_t kmer) { + uint8_t nt = index_ptr->indexed_nt(); + uint8_t idx_type = index_ptr->index_type(); + uint64_t xor_mask = idx_type == 1 ? 0 : INDEX2_XOR_MASK; + uint64_t mask = 1 << (nt * 2); + mask--; + xor_mask &= mask; + uint64_t min_bin_key = ~0; + for (uint64_t i = 0; i < key_bits / 2 - nt + 1; i++) { + uint64_t temp_bin_key = xor_mask ^ canonical_representation(kmer & mask, nt); + if (temp_bin_key < min_bin_key) + min_bin_key = temp_bin_key; + kmer >>= 2; + } + return min_bin_key; +} + +// Code mostly from Jellyfish 1.6 source +uint64_t KrakenDB::reverse_complement(uint64_t kmer, uint8_t n) { + kmer = ((kmer >> 2) & 0x3333333333333333UL) | ((kmer & 0x3333333333333333UL) << 2); + kmer = ((kmer >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((kmer & 0x0F0F0F0F0F0F0F0FUL) << 4); + kmer = ((kmer >> 8) & 0x00FF00FF00FF00FFUL) | ((kmer & 0x00FF00FF00FF00FFUL) << 8); + kmer = ((kmer >> 16) & 0x0000FFFF0000FFFFUL) | ((kmer & 0x0000FFFF0000FFFFUL) << 16); + kmer = ( kmer >> 32 ) | ( kmer << 32); + return (((uint64_t)-1) - kmer) >> (8 * sizeof(kmer) - (n << 1)); +} + +// Code mostly from Jellyfish 1.6 source +uint64_t KrakenDB::reverse_complement(uint64_t kmer) { + kmer = ((kmer >> 2) & 0x3333333333333333UL) | ((kmer & 0x3333333333333333UL) << 2); + kmer = ((kmer >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((kmer & 0x0F0F0F0F0F0F0F0FUL) << 4); + kmer = ((kmer >> 8) & 0x00FF00FF00FF00FFUL) | ((kmer & 0x00FF00FF00FF00FFUL) << 8); + kmer = ((kmer >> 16) & 0x0000FFFF0000FFFFUL) | ((kmer & 0x0000FFFF0000FFFFUL) << 16); + kmer = ( kmer >> 32 ) | ( kmer << 32); + return (((uint64_t)-1) - kmer) >> (8 * sizeof(kmer) - (k << 1)); +} + +// Lexicographically smallest of k-mer and reverse comp. of k-mer +uint64_t KrakenDB::canonical_representation(uint64_t kmer, uint8_t n) { + uint64_t revcom = reverse_complement(kmer, n); + return kmer < revcom ? kmer : revcom; +} + +uint64_t KrakenDB::canonical_representation(uint64_t kmer) { + uint64_t revcom = reverse_complement(kmer, k); + return kmer < revcom ? kmer : revcom; +} + +// perform search over last range to speed up queries +// NOTE: retry_on_failure implies all pointer params are non-NULL +uint32_t *KrakenDB::kmer_query(uint64_t kmer, uint64_t *last_bin_key, + int64_t *min_pos, int64_t *max_pos, + bool retry_on_failure) +{ + int64_t min, max, mid; + uint64_t comp_kmer; + uint64_t b_key; + char *ptr = get_pair_ptr(); + size_t pair_sz = pair_size(); + + // Use provided values if they exist and are valid + if (retry_on_failure && *min_pos <= *max_pos) { + b_key = *last_bin_key; + min = *min_pos; + max = *max_pos; + } + else { + b_key = bin_key(kmer); + min = index_ptr->at(b_key); + max = index_ptr->at(b_key + 1) - 1; + // Invalid min/max values + retry_on_failure means min/max need to be + // initialized and set in caller + if (retry_on_failure) { + *last_bin_key = b_key; + *min_pos = min; + *max_pos = max; + } + } + + // Binary search with large window + while (min + 15 <= max) { + mid = min + (max - min) / 2; + comp_kmer = * (uint64_t *) (ptr + pair_sz * mid); + comp_kmer &= (1ull << key_bits) - 1; // trim any excess + if (kmer > comp_kmer) + min = mid + 1; + else if (kmer < comp_kmer) + max = mid - 1; + else + return (uint32_t *) (ptr + pair_sz * mid + key_len); + } + // Linear search once window shrinks + for (mid = min; mid <= max; mid++) { + comp_kmer = * (uint64_t *) (ptr + pair_sz * mid); + comp_kmer &= (1ull << key_bits) - 1; // trim any excess + if (kmer == comp_kmer) + return (uint32_t *) (ptr + pair_sz * mid + key_len); + } + + uint32_t *answer = NULL; + // ROF implies the provided values might be out of date + // If they are, we'll update them and search again + if (retry_on_failure) { + b_key = bin_key(kmer); + // If bin key hasn't changed, search fails + if (b_key == *last_bin_key) + return NULL; + min = index_ptr->at(b_key); + max = index_ptr->at(b_key + 1) - 1; + // Recursive call w/ adjusted search params and w/o retry + answer = kmer_query(kmer, &b_key, &min, &max, false); + // Update caller's search params due to bin key change + if (last_bin_key != NULL) { + *last_bin_key = b_key; + *min_pos = min; + *max_pos = max; + } + } + return answer; +} + +// Binary search w/in the k-mer's bin +uint32_t *KrakenDB::kmer_query(uint64_t kmer) { + return kmer_query(kmer, NULL, NULL, NULL, false); +} + +KrakenDBIndex::KrakenDBIndex() { + fptr = NULL; + idx_type = 1; + nt = 0; +} + +KrakenDBIndex::KrakenDBIndex(char *ptr) { + fptr = ptr; + idx_type = 1; + if (strncmp(ptr, KRAKEN_INDEX_STRING, strlen(KRAKEN_INDEX_STRING))) { + idx_type = 2; + if (strncmp(ptr, KRAKEN_INDEX2_STRING, strlen(KRAKEN_INDEX2_STRING))) + errx(EX_DATAERR, "illegal Kraken DB index format"); + } + ptr += strlen(KRAKEN_INDEX_STRING); + memcpy(&nt, ptr, 1); +} + +// Index version (v2 uses different minimizer sort order) +uint8_t KrakenDBIndex::index_type() { + return idx_type; +} + +// How long are bin keys (i.e., what is minimizer length in bp?) +uint8_t KrakenDBIndex::indexed_nt() { + return nt; +} + +// Return start of index array (skips header) +uint64_t *KrakenDBIndex::get_array() { + return (uint64_t *) (fptr + strlen(KRAKEN_INDEX_STRING) + 1); +} + +// Convenience method, allows for testing guard +uint64_t KrakenDBIndex::at(uint64_t idx) { + uint64_t *array = get_array(); + #ifdef TESTING + if (idx > 1 + (1ull << (nt * 2))) + errx(EX_SOFTWARE, "KrakenDBIndex::at() called with illegal index"); + #endif + return array[idx]; +} + +} // namespace diff --git a/src/krakendb.hpp b/src/krakendb.hpp new file mode 100644 index 0000000..dc44096 --- /dev/null +++ b/src/krakendb.hpp @@ -0,0 +1,103 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#ifndef KRAKENDB_HPP +#define KRAKENDB_HPP + +#include "kraken_headers.hpp" + +namespace kraken { + class KrakenDBIndex { + public: + KrakenDBIndex(); + // ptr points to mmap'ed existing file opened in read or read/write mode + KrakenDBIndex(char *ptr); + + uint8_t index_type(); + uint8_t indexed_nt(); + uint64_t *get_array(); + uint64_t at(uint64_t idx); + + private: + uint8_t idx_type; + char *fptr; + uint8_t nt; + }; + + class KrakenDB { + public: + // Compares key/value pairs in DB, - => a a=b, + => a>b + static int pair_cmp(const void *a, const void *b); + + char *get_ptr(); // Return the file pointer + char *get_pair_ptr(); // Return pointer to start of pairs + KrakenDBIndex *get_index(); // Return ptr to assoc'd index obj + uint8_t get_k(); // how many nt are in each key? + uint64_t get_key_bits(); // how many bits are in each key? + uint64_t get_key_len(); // how many bytes does each key occupy? + uint64_t get_val_len(); // how many bytes does each value occupy? + uint64_t get_key_ct(); // how many key/value pairs are there? + uint64_t pair_size(); // how many bytes does each pair occupy? + + size_t header_size(); // Jellyfish uses variable header sizes + uint32_t *kmer_query(uint64_t kmer); // return ptr to pair w/ kmer + + // perform search over last range to speed up queries + uint32_t *kmer_query(uint64_t kmer, uint64_t *last_bin_key, + int64_t *min_pos, int64_t *max_pos, + bool retry_on_failure=true); + + // return "bin key" for kmer, based on index + // If idx_nt not specified, use index's value + uint64_t bin_key(uint64_t kmer, uint64_t idx_nt); + uint64_t bin_key(uint64_t kmer); + + // Code from Jellyfish, rev. comp. of a k-mer with n nt. + // If n is not specified, use k in DB, otherwise use first n nt in kmer + uint64_t reverse_complement(uint64_t kmer, uint8_t n); + uint64_t reverse_complement(uint64_t kmer); + + // Return lexicographically smallest of kmer/revcom(kmer) + // If n is not specified, use k in DB, otherwise use first n nt in kmer + uint64_t canonical_representation(uint64_t kmer, uint8_t n); + uint64_t canonical_representation(uint64_t kmer); + + void make_index(std::string index_filename, uint8_t nt); + + void set_index(KrakenDBIndex *i_ptr); + + // Null constructor + KrakenDB(); + + // ptr points to start of mmap'ed DB in read or read/write mode + KrakenDB(char *ptr); + + private: + + char *fptr; + KrakenDBIndex *index_ptr; + uint8_t k; + uint64_t key_bits; + uint64_t key_len; + uint64_t val_len; + uint64_t key_ct; + }; +} + +#endif diff --git a/src/krakenutil.cpp b/src/krakenutil.cpp new file mode 100644 index 0000000..d73e4bb --- /dev/null +++ b/src/krakenutil.cpp @@ -0,0 +1,181 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "krakenutil.hpp" + +using namespace std; + +namespace kraken { + // Build a node->parent map from NCBI Taxonomy nodes.dmp file + map build_parent_map(string filename) { + map pmap; + uint32_t node_id, parent_id; + string line; + ifstream ifs(filename.c_str()); + if (ifs.rdstate() & ifstream::failbit) { + err(EX_NOINPUT, "error opening %s", filename.c_str()); + } + + while (ifs.good()) { + getline(ifs, line); + if (line.empty()) + break; + sscanf(line.c_str(), "%d\t|\t%d", &node_id, &parent_id); + pmap[node_id] = parent_id; + } + pmap[1] = 0; + return pmap; + } + + // Return lowest common ancestor of a and b + // LCA(0,x) = LCA(x,0) = x + // Default ancestor is 1 (root of tree) + uint32_t lca(map &parent_map, + uint32_t a, uint32_t b) + { + if (a == 0 || b == 0) + return a ? a : b; + + set a_path; + while (a > 0) { + a_path.insert(a); + a = parent_map[a]; + } + while (b > 0) { + if (a_path.count(b) > 0) + return b; + b = parent_map[b]; + } + return 1; + } + + // Tree resolution: take all hit taxa (plus ancestors), then + // return leaf of highest weighted leaf-to-root path. + uint32_t resolve_tree(map &hit_counts, + map &parent_map) + { + set max_taxa; + uint32_t max_taxon = 0, max_score = 0; + map::iterator it = hit_counts.begin(); + + // Sum each taxon's LTR path + while (it != hit_counts.end()) { + uint32_t taxon = it->first; + uint32_t node = taxon; + uint32_t score = 0; + while (node > 0) { + score += hit_counts[node]; + node = parent_map[node]; + } + + if (score > max_score) { + max_taxa.clear(); + max_score = score; + max_taxon = taxon; + } + else if (score == max_score) { + if (max_taxa.empty()) + max_taxa.insert(max_taxon); + max_taxa.insert(taxon); + } + + it++; + } + + // If two LTR paths are tied for max, return LCA of all + if (! max_taxa.empty()) { + set::iterator sit = max_taxa.begin(); + max_taxon = *sit; + for (sit++; sit != max_taxa.end(); sit++) + max_taxon = lca(parent_map, max_taxon, *sit); + } + + return max_taxon; + } + + uint8_t KmerScanner::k = 0; + uint64_t KmerScanner::kmer_mask = 0; + uint32_t KmerScanner::mini_kmer_mask = 0; + + // Create a scanner for the string over the interval [start, finish) + KmerScanner::KmerScanner(string &seq, size_t start, size_t finish) { + if (! k) + errx(EX_SOFTWARE, "KmerScanner created w/o setting k"); + if (finish > seq.size()) + finish = seq.size(); + + kmer = 0; + ambig = 0; + str = &seq; + curr_pos = start; + pos1 = start; + pos2 = finish; + loaded_nt = 0; + if (pos2 - pos1 + 1 < k) + curr_pos = pos2; + } + + uint8_t KmerScanner::get_k() { return k; } + + void KmerScanner::set_k(uint8_t n) { + if (k) // Only allow one setting per execution + return; + k = n; + kmer_mask = ~0; + kmer_mask >>= sizeof(kmer_mask) * 8 - (k * 2); + mini_kmer_mask = ~0; + mini_kmer_mask >>= sizeof(mini_kmer_mask) * 8 - k; + } + + uint64_t *KmerScanner::next_kmer() { + if (curr_pos >= pos2) + return NULL; + if (loaded_nt) + loaded_nt--; + while (loaded_nt < k) { + loaded_nt++; + kmer <<= 2; + ambig <<= 1; + switch ((*str)[curr_pos++]) { + case 'A': case 'a': + break; + case 'C': case 'c': + kmer |= 1; + break; + case 'G': case 'g': + kmer |= 2; + break; + case 'T': case 't': + kmer |= 3; + break; + default: + ambig |= 1; + break; + } + kmer &= kmer_mask; + ambig &= mini_kmer_mask; + } + return &kmer; + } + + bool KmerScanner::ambig_kmer() { + return !! ambig; + } +} diff --git a/src/krakenutil.hpp b/src/krakenutil.hpp new file mode 100644 index 0000000..e8b1f4b --- /dev/null +++ b/src/krakenutil.hpp @@ -0,0 +1,63 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#ifndef KRAKENUTIL_HPP +#define KRAKENUTIL_HPP + +#include "kraken_headers.hpp" + +namespace kraken { + // Build a map of node to parent from an NCBI taxonomy nodes.dmp file + std::map build_parent_map(std::string filename); + + // Return the lowest common ancestor of a and b, according to parent_map + // NOTE: LCA(0,x) = LCA(x,0) = x + uint32_t lca(std::map &parent_map, + uint32_t a, uint32_t b); + + // Resolve classification tree + uint32_t resolve_tree(std::map &hit_counts, + std::map &parent_map); + + class KmerScanner { + public: + + KmerScanner(std::string &seq, size_t start=0, size_t finish=~0); + uint64_t *next_kmer(); // NULL when seq exhausted + bool ambig_kmer(); // does last returned kmer have non-ACGT? + + + static uint8_t get_k(); + // MUST be called before first invocation of KmerScanner() + static void set_k(uint8_t n); + + private: + std::string *str; + size_t curr_pos, pos1, pos2; + uint64_t kmer; // the kmer, address is returned (don't share b/t thr.) + uint32_t ambig; // is there an ambiguous nucleotide in the kmer? + int64_t loaded_nt; + + static uint8_t k; // init. to 0 b/c static + static uint64_t kmer_mask; + static uint32_t mini_kmer_mask; + }; +} + +#endif diff --git a/src/make_file_to_taxon_map.cpp b/src/make_file_to_taxon_map.cpp new file mode 100644 index 0000000..f3d9c0d --- /dev/null +++ b/src/make_file_to_taxon_map.cpp @@ -0,0 +1,87 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" + +using namespace std; +using namespace kraken; + +map requests; +uint64_t request_count = 0; + +void fill_request_map(char *filename); +void report_taxo_numbers(char *filename); + +int main(int argc, char **argv) { + if (argc < 3) { + cerr << "Usage: make_file_to_taxon_map " + << endl; + return 1; + } + char *map_filename = argv[1]; + char *list_filename = argv[2]; + fill_request_map(list_filename); + report_taxo_numbers(map_filename); + + return 0; +} + +void report_taxo_numbers(char *filename) { + string file_str = filename; + QuickFile file(file_str); + char *fptr, *fptr_start; + fptr_start = fptr = file.ptr(); + size_t file_size = file.size(); + + while (request_count > 0 && (size_t)(fptr - fptr_start) < file_size) { + char *nl_ptr = strchr(fptr, '\n'); + uint64_t gi = atoll(fptr); + + if (requests.count(gi) > 0) { + char *tab_ptr = strchr(fptr, '\t'); + cout << requests[gi] << "\t"; + cout.write(tab_ptr + 1, nl_ptr - tab_ptr); + request_count--; + } + + fptr = nl_ptr + 1; + } + + file.close_file(); +} + +void fill_request_map(char *filename) { + string file_str = filename; + QuickFile file(file_str); + char *fptr, *fptr_start; + fptr_start = fptr = file.ptr(); + size_t file_size = file.size(); + + while ((size_t)(fptr - fptr_start) < file_size) { + char *nl_ptr = strchr(fptr, '\n'); + char *sep_ptr = strchr(fptr, '|'); + uint64_t gi = atoll(fptr); + requests[gi] = string(sep_ptr + 1, nl_ptr - sep_ptr - 1); + request_count++; + fptr = nl_ptr + 1; + } + + file.close_file(); +} diff --git a/src/quickfile.cpp b/src/quickfile.cpp new file mode 100644 index 0000000..d5662d0 --- /dev/null +++ b/src/quickfile.cpp @@ -0,0 +1,132 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" + +using std::string; + +namespace kraken { + +QuickFile::QuickFile() { + valid = false; + fptr = NULL; + filesize = 0; + fd = -1; +} + +QuickFile::QuickFile(string filename_str, string mode, size_t size) { + open_file(filename_str, mode, size); +} + +void QuickFile::open_file(string filename_str, string mode, size_t size) { + const char *filename = filename_str.c_str(); + int o_flags = mode == "w" + ? O_RDWR | O_CREAT | O_TRUNC + : mode == "r" ? O_RDONLY : O_RDWR; + int m_flags = mode == "r" ? MAP_PRIVATE : MAP_SHARED; + + fd = open(filename, o_flags, 0666); + // Second try for R/W if failure was due to non-existence + if (fd < 0 && mode == "rw" && errno == ENOENT) { + o_flags |= O_CREAT; + fd = open(filename, o_flags, 0666); + } + if (fd < 0) + err(EX_OSERR, "unable to open %s", filename); + + if (o_flags & O_CREAT) { + if (lseek(fd, size - 1, SEEK_SET) < 0) + err(EX_OSERR, "unable to lseek (%s)", filename); + if (write(fd, "", 1) < 0) + err(EX_OSERR, "write error (%s)", filename); + filesize = size; + } + else { + struct stat sb; + if (fstat(fd, &sb) < 0) + err(EX_OSERR, "unable to fstat %s", filename); + filesize = sb.st_size; + } + + fptr = (char *)mmap(0, filesize, PROT_READ | PROT_WRITE, m_flags, fd, 0); + if (fptr == MAP_FAILED) + err(EX_OSERR, "unable to mmap %s", filename); + valid = true; +} + +void QuickFile::load_file() { + int thread_ct = 1; + int thread = 0; + #ifdef _OPENMP + int old_thread_ct = omp_get_max_threads(); + if (old_thread_ct > 4) + omp_set_num_threads(4); + thread_ct = omp_get_max_threads(); + #endif + + size_t page_size = getpagesize(); + char buf[thread_ct][page_size]; + + #pragma omp parallel + { + #ifdef _OPENMP + thread = omp_get_thread_num(); + #endif + + #pragma omp for schedule(dynamic) + for (size_t pos = 0; pos < filesize; pos += page_size) { + size_t this_page_size = filesize - pos; + if (this_page_size > page_size) + this_page_size = page_size; + memcpy(buf[thread], fptr + pos, this_page_size); + } + } + + #ifdef _OPENMP + omp_set_num_threads(old_thread_ct); + #endif +} + +char * QuickFile::ptr() { + return valid ? fptr : NULL; +} + +size_t QuickFile::size() { + return valid ? filesize : 0; +} + +QuickFile::~QuickFile() { + close_file(); +} + +void QuickFile::sync_file() { + msync(fptr, filesize, MS_SYNC); +} + +void QuickFile::close_file() { + if (! valid) + return; + sync_file(); + munmap(fptr, filesize); + close(fd); + valid = false; +} + +} // namespace diff --git a/src/quickfile.hpp b/src/quickfile.hpp new file mode 100644 index 0000000..c713ce9 --- /dev/null +++ b/src/quickfile.hpp @@ -0,0 +1,48 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#ifndef QUICKFILE_HPP +#define QUICKFILE_HPP + +#include "kraken_headers.hpp" + +namespace kraken { + class QuickFile { + public: + + QuickFile(); + QuickFile(std::string filename, std::string mode="r", size_t size=0); + ~QuickFile(); + void open_file(std::string filename, std::string mode="r", size_t size=0); + char *ptr(); + size_t size(); + void load_file(); + void sync_file(); + void close_file(); + + protected: + + bool valid; + int fd; + char *fptr; + size_t filesize; + }; +} + +#endif diff --git a/src/seqreader.cpp b/src/seqreader.cpp new file mode 100644 index 0000000..d090dd8 --- /dev/null +++ b/src/seqreader.cpp @@ -0,0 +1,127 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" +#include "seqreader.hpp" + +using namespace std; + +namespace kraken { + FastaReader::FastaReader(string filename) { + file.open_file(filename); + ptr = file.ptr(); + valid = true; + } + + DNASequence FastaReader::next_sequence() { + DNASequence dna; + + if (! valid || ! ptr || (size_t)(ptr - file.ptr()) >= file.size()) { + valid = false; + return dna; + } + + size_t remaining = file.size() - (ptr - file.ptr()); + char *end_ptr = ptr; + size_t end_rem = remaining; + while (end_ptr) { + end_ptr = (char *) memchr(end_ptr+1, '>', end_rem-1); + if (! end_ptr || *(end_ptr - 1) == '\n') + break; + end_rem = remaining - (end_ptr - ptr); + } + + size_t record_len = end_ptr ? end_ptr - ptr : remaining; + string fasta_record(ptr, record_len); + ptr += record_len; + + istringstream iss(fasta_record); + string line; + + getline(iss, line); + if (line[0] != '>') + errx(EX_DATAERR, "malformed fasta file"); + istringstream line_ss(line.substr(1)); + + line_ss >> dna.id; + dna.seq = ""; + while (iss.good()) { + getline(iss, line); + if (line.empty()) + break; + dna.seq.append(line); + } + + return dna; + } + + bool FastaReader::is_valid() { + return valid; + } + + FastqReader::FastqReader(string filename) { + file.open(filename.c_str()); + if (file.rdstate() & ifstream::failbit) { + err(EX_NOINPUT, "can't open %s", filename.c_str()); + } + valid = true; + } + + DNASequence FastqReader::next_sequence() { + DNASequence dna; + + if (! valid || ! file.good()) { + valid = false; + return dna; + } + + string line; + getline(file, line); + if (line.empty()) { + valid = false; // Sometimes FASTQ files have empty last lines + return dna; + } + if (line[0] != '@') { + if (line[0] != '\r') + warnx("malformed fastq file - sequence header (%s)", line.c_str()); + valid = false; + return dna; + } + istringstream line_ss(line.substr(1)); + + line_ss >> dna.id; + getline(file, dna.seq); + + getline(file, line); + if (line.empty() || line[0] != '+') { + if (line[0] != '\r') + warnx("malformed fastq file - quality header (%s)", line.c_str()); + valid = false; + return dna; + } + getline(file, dna.quals); + + return dna; + } + + bool FastqReader::is_valid() { + return valid; + } +} // namespace diff --git a/src/seqreader.hpp b/src/seqreader.hpp new file mode 100644 index 0000000..276e87b --- /dev/null +++ b/src/seqreader.hpp @@ -0,0 +1,64 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#ifndef SEQREADER_HPP +#define SEQREADER_HPP + +#include "kraken_headers.hpp" +#include "quickfile.hpp" + +namespace kraken { + typedef struct { + std::string id; + std::string seq; + std::string quals; + } DNASequence; + + class DNASequenceReader { + public: + virtual DNASequence next_sequence() = 0; + virtual bool is_valid() = 0; + virtual ~DNASequenceReader() {} + }; + + class FastaReader : public DNASequenceReader { + public: + FastaReader(std::string filename); + DNASequence next_sequence(); + bool is_valid(); + + private: + QuickFile file; + char *ptr; + bool valid; + }; + + class FastqReader : public DNASequenceReader { + public: + FastqReader(std::string filename); + DNASequence next_sequence(); + bool is_valid(); + + private: + std::ifstream file; + bool valid; + }; +} + +#endif diff --git a/src/set_lcas.cpp b/src/set_lcas.cpp new file mode 100644 index 0000000..7608463 --- /dev/null +++ b/src/set_lcas.cpp @@ -0,0 +1,259 @@ +/* + * Copyright 2013, Derrick Wood + * + * This file is part of the Kraken taxonomic sequence classification system. + * + * Kraken 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. + * + * Kraken 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 Kraken. If not, see . + */ + +#include "kraken_headers.hpp" +#include "quickfile.hpp" +#include "krakendb.hpp" +#include "krakenutil.hpp" +#include "seqreader.hpp" + +#define SKIP_LEN 50000 + +using namespace std; +using namespace kraken; + +void parse_command_line(int argc, char **argv); +void usage(int exit_code=EX_USAGE); +void process_files(); +void process_single_file(); +void process_file(string filename, uint32_t taxid); +void set_lcas(uint32_t taxid, string &seq, size_t start, size_t finish); + +int Num_threads = 1; +string DB_filename, Index_filename, Nodes_filename, + File_to_taxon_map_filename, + ID_to_taxon_map_filename, Multi_fasta_filename; +bool Allow_extra_kmers = false; +bool Operate_in_RAM = false; +bool One_FASTA_file = false; +map Parent_map; +map ID_to_taxon_map; +KrakenDB Database; + +int main(int argc, char **argv) { + #ifdef _OPENMP + omp_set_num_threads(1); + #endif + + parse_command_line(argc, argv); + Parent_map = build_parent_map(Nodes_filename); + + QuickFile db_file(DB_filename, "rw"); + Database = KrakenDB(db_file.ptr()); + KmerScanner::set_k(Database.get_k()); + + char *temp_ptr = NULL; + if (Operate_in_RAM) { + temp_ptr = new char[ db_file.size() ]; + memcpy(temp_ptr, db_file.ptr(), db_file.size()); + Database = KrakenDB(temp_ptr); + } + + QuickFile idx_file(Index_filename); + KrakenDBIndex db_index(idx_file.ptr()); + Database.set_index(&db_index); + + if (One_FASTA_file) + process_single_file(); + else + process_files(); + + if (Operate_in_RAM) { + memcpy(db_file.ptr(), temp_ptr, db_file.size()); + delete temp_ptr; + } + + return 0; +} + +void process_single_file() { + ifstream map_file(ID_to_taxon_map_filename.c_str()); + if (map_file.rdstate() & ifstream::failbit) { + err(EX_NOINPUT, "can't open %s", ID_to_taxon_map_filename.c_str()); + } + string line; + while (map_file.good()) { + getline(map_file, line); + if (line.empty()) + break; + string seq_id; + uint32_t taxid; + istringstream iss(line); + iss >> seq_id; + iss >> taxid; + ID_to_taxon_map[seq_id] = taxid; + } + + FastaReader reader(Multi_fasta_filename); + DNASequence dna; + uint32_t seqs_processed = 0; + + while (reader.is_valid()) { + dna = reader.next_sequence(); + if (! reader.is_valid()) + break; + uint32_t taxid = ID_to_taxon_map[dna.id]; + if (taxid) { + #pragma omp parallel for schedule(dynamic) + for (size_t i = 0; i < dna.seq.size(); i += SKIP_LEN) + set_lcas(taxid, dna.seq, i, i + SKIP_LEN + Database.get_k() - 1); + } + cerr << "\rProcessed " << ++seqs_processed << " sequences"; + } + cerr << "\r "; + cerr << "\rFinished processing " << seqs_processed << " sequences" << endl; +} + +void process_files() { + ifstream map_file(File_to_taxon_map_filename.c_str()); + if (map_file.rdstate() & ifstream::failbit) { + err(EX_NOINPUT, "can't open %s", File_to_taxon_map_filename.c_str()); + } + string line; + uint32_t seqs_processed = 0; + + while (map_file.good()) { + getline(map_file, line); + if (line.empty()) + break; + string filename; + uint32_t taxid; + istringstream iss(line); + iss >> filename; + iss >> taxid; + process_file(filename, taxid); + cerr << "\rProcessed " << ++seqs_processed << " sequences"; + } + cerr << "\r "; + cerr << "\rFinished processing " << seqs_processed << " sequences" << endl; +} + +void process_file(string filename, uint32_t taxid) { + FastaReader reader(filename); + DNASequence dna; + + // For the purposes of this program, we assume these files are + // single-fasta files. + dna = reader.next_sequence(); + + #pragma omp parallel for schedule(dynamic) + for (size_t i = 0; i < dna.seq.size(); i += SKIP_LEN) + set_lcas(taxid, dna.seq, i, i + SKIP_LEN + Database.get_k() - 1); +} + +void set_lcas(uint32_t taxid, string &seq, size_t start, size_t finish) { + KmerScanner scanner(seq, start, finish); + uint64_t *kmer_ptr; + uint32_t *val_ptr; + + while ((kmer_ptr = scanner.next_kmer()) != NULL) { + if (scanner.ambig_kmer()) + continue; + val_ptr = Database.kmer_query( + Database.canonical_representation(*kmer_ptr) + ); + if (val_ptr == NULL) { + if (! Allow_extra_kmers) + errx(EX_DATAERR, "kmer found in sequence that is not in database"); + else + continue; + } + *val_ptr = lca(Parent_map, taxid, *val_ptr); + } +} + +void parse_command_line(int argc, char **argv) { + int opt; + int sig; + + if (argc > 1 && strcmp(argv[1], "-h") == 0) + usage(0); + while ((opt = getopt(argc, argv, "f:d:i:t:n:m:F:xM")) != -1) { + switch (opt) { + case 'f' : + File_to_taxon_map_filename = optarg; + break; + case 'd' : + DB_filename = optarg; + break; + case 'i' : + Index_filename = optarg; + break; + case 'F' : + Multi_fasta_filename = optarg; + break; + case 'm' : + ID_to_taxon_map_filename = optarg; + break; + case 't' : + sig = atoi(optarg); + if (sig <= 0) + errx(EX_USAGE, "can't use nonpositive thread count"); + #ifdef _OPENMP + Num_threads = sig; + omp_set_num_threads(Num_threads); + #endif + break; + case 'n' : + Nodes_filename = optarg; + break; + case 'x' : + Allow_extra_kmers = true; + break; + case 'M' : + Operate_in_RAM = true; + break; + default: + usage(); + break; + } + } + + if (DB_filename.empty() || Index_filename.empty() || + Nodes_filename.empty()) + usage(); + if (File_to_taxon_map_filename.empty() && + (Multi_fasta_filename.empty() || ID_to_taxon_map_filename.empty())) + usage(); + + if (! File_to_taxon_map_filename.empty()) + One_FASTA_file = false; + else + One_FASTA_file = true; +} + +void usage(int exit_code) { + cerr << "Usage: set_lcas [options]" << endl + << endl + << "Options: (*mandatory)" << endl + << "* -d filename Kraken DB filename" << endl + << "* -i filename Kraken DB index filename" << endl + << "* -n filename NCBI Taxonomy nodes file" << endl + << " -t # Number of threads" << endl + << " -M Copy DB to RAM during operation" << endl + << " -x K-mers not found in DB do not cause errors" << endl + << " -f filename File to taxon map" << endl + << " -F filename Multi-FASTA file with sequence data" << endl + << " -m filename Sequence ID to taxon map" << endl + << " -h Print this message" << endl + << endl + << "-F and -m must be specified together. If -f is given, " + << "-F/-m are ignored." << endl; + exit(exit_code); +}