pax_global_header00006660000000000000000000000064126335116000014507gustar00rootroot0000000000000052 comment=26c5d253a8830cd9a90ffc5dc5930f50b8225231 swarm-2.1.6/000077500000000000000000000000001263351160000126465ustar00rootroot00000000000000swarm-2.1.6/CITATION000066400000000000000000000024311263351160000140030ustar00rootroot00000000000000Please cite swarm as follows: Mahé F, Rognes T, Quince C, de Vargas C, Dunthorn M. (2014) Swarm: robust and fast clustering method for amplicon-based studies. PeerJ 2:e593 Bibtex format: @article{10.7717/peerj.593, title = {Swarm: robust and fast clustering method for amplicon-based studies}, author = {Mahé, Frédéric and Rognes, Torbjørn and Quince, Christopher and de Vargas, Colomban and Dunthorn, Micah}, year = {2014}, month = {9}, keywords = {Environmental diversity, Barcoding, Molecular operational taxonomic units}, abstract = {Popular \textit{de novo} amplicon clustering methods suffer from two fundamental flaws: arbitrary global clustering thresholds, and input-order dependency induced by centroid selection. Swarm was developed to address these issues by first clustering nearly identical amplicons iteratively using a local threshold, and then by using clusters’ internal structure and amplicon abundances to refine its results. This fast, scalable, and input-order independent approach reduces the influence of clustering parameters and produces robust operational taxonomic units.}, volume = {2}, pages = {e593}, journal = {PeerJ}, issn = {2167-8359}, url = {http://dx.doi.org/10.7717/peerj.593}, doi = {10.7717/peerj.593} } swarm-2.1.6/LICENSE000066400000000000000000001033301263351160000136530ustar00rootroot00000000000000 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see . swarm-2.1.6/README.md000066400000000000000000000607431263351160000141370ustar00rootroot00000000000000# swarm # A robust and fast clustering method for amplicon-based studies. The purpose of **swarm** is to provide a novel clustering algorithm that handles massive sets of amplicons. Traditional clustering algorithms results are strongly input-order dependent, and rely on an arbitrary **global** clustering threshold. **swarm** results are resilient to input-order changes and rely on a small **local** linking threshold *d*, the maximum number of differences between two amplicons. **swarm** forms stable, high-resolution clusters, with a high yield of biological information. **swarm** 2.0 introduces several novelties and improvements over swarm 1.0: * built-in breaking phase now performed automatically, * possibility to output OTU representatives in fasta format (option `-w`), * fast algorithm now used by default for *d* = 1 (linear time complexity), * a new option called *fastidious* that refines *d* = 1 results and reduces the number of small OTUs, Table of Content ================ * [Common misconceptions](#common_misconceptions) * [Quick start](#quick_start) * [Install](#install) * [Prepare amplicon fasta files](#prepare_amplicon) * [Linearization](#linearization) * [Dereplication](#dereplication) * [Launch swarm](#launch) * [Frequently asked questions](#FAQ) * [Refine swarm OTUs](#refine_OTUs) * [Count the number of amplicons per OTU](#OTU_sizes) * [Get the seed sequence for each swarm](#extract_seeds) * [Get fasta sequences for all amplicons in a swarm](#extract_all) * [Troubleshooting](#troubleshooting) * [Citation](#citation) * [Contact](#contact) * [Third-party pipelines](#pipelines) * [Alternatives](#alternatives) * [New features](#features) * [version 2.1.6](#version216) * [version 2.1.5](#version215) * [version 2.1.4](#version214) * [version 2.1.3](#version213) * [version 2.1.2](#version212) * [version 2.1.1](#version211) * [version 2.1.0](#version210) * [version 2.0.7](#version207) * [version 2.0.6](#version206) * [version 2.0.5](#version205) * [version 2.0.4](#version204) * [version 2.0.3](#version203) * [version 2.0.2](#version202) * [version 2.0.1](#version201) * [version 2.0.0](#version200) * [version 1.2.21](#version1221) * [version 1.2.20](#version1220) * [version 1.2.19](#version1219) * [version 1.2.18](#version1218) * [version 1.2.17](#version1217) * [version 1.2.16](#version1216) * [version 1.2.15](#version1215) * [version 1.2.14](#version1214) * [version 1.2.13](#version1213) * [version 1.2.12](#version1212) * [version 1.2.11](#version1211) * [version 1.2.10](#version1210) * [version 1.2.9](#version129) * [version 1.2.8](#version128) * [version 1.2.7](#version127) * [version 1.2.6](#version126) * [version 1.2.5](#version125) * [version 1.2.4](#version124) * [version 1.2.3](#version123) * [version 1.2.2](#version122) * [version 1.2.1](#version121) * [version 1.2.0](#version120) * [version 1.1.1](#version111) * [version 1.1.0](#version110) ## Common misconceptions ## **swarm** is a single-linkage clustering method, with some superficial similarities with other clustering methods (e.g., [Huse et al, 2010](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2909393/)). **swarm**'s novelty is its iterative growth process and the use of sequence abundance values to delineate OTUs. Swarm properly delineates large OTUs (high recall), while being able to distinguish OTUs with as little as two differences between their centers (high precision). **swarm** uses a local clustering threshold (*d*), not a global clustering threshold like other algorithms do. Users may be tempted to convert a 97%-global similarity threshold into a number of differences, and to use large *d* values. This is not a correct use of swarm. OTUs produced by swarm are naturally larger than *d*, and tests have shown that using the default *d* value (*d* = 1) gives good results on most datasets. Using the new fastidious option further improves the quality of results. For long amplicons or shallow sequencing, higher *d* values can be used (*d* = 2 or *d* = 3, very rarely more). **swarm** produces high-resolution results, especially when using *d* = 1. Under certain rare conditions though, a given marker may not evolve fast enough to distinguish molecular taxa. If it concerns abundant sequences, swarm may form an OTU with a large radius, whereas classic clustering methods will cut through randomly, forcing delineation where the 97%-threshold falls. So, keep in mind that molecular markers have limitations too. ## Quick start ## **swarm** most simple usage is: ```sh ./swarm amplicons.fasta ``` That command will apply default parameters to the fasta file `amplicons.fasta`. The fasta file must be formatted as follows: ``` >seqID1_1000 acgtacgtacgtacgt >seqID2_25 cgtcgtcgtcgtcgt ``` where sequence identifiers are unique and end with a value indicating the number of occurrences of the sequence (e.g., `_1000`). Alternative formats are possible, please see the [user manual](https://github.com/torognes/swarm/blob/master/man/swarm_manual.pdf). Swarm **requires** each fasta entry to present a number of occurrences to work properly. That crucial information can be produced during the [dereplication](#dereplication) step. Use `swarm -h` to get a short help, or see the [user manual](https://github.com/torognes/swarm/blob/master/man/swarm_manual.pdf) for a complete description of input/output formats and command line options. The memory footprint of **swarm** is roughly 1.6 times the size of the input fasta file. When using the fastidious option, memory footprint can increase significantly. See options `-c` and `-y` to control and cap swarm's memory consumption. ## Install ## Get the latest binaries for GNU/Linux or MacOSX from [the release page](https://github.com/torognes/swarm/releases "swarm tagged releases"). Get the source code from [GitHub](https://github.com/torognes/swarm "swarm public repository") using the [ZIP button](https://github.com/torognes/swarm/archive/master.zip "swarm zipped folder") or git, and compile swarm: ```sh git clone https://github.com/torognes/swarm.git cd swarm/src/ make cd ../bin/ ``` If you have administrator privileges, you can make **swarm** accessible for all users. Simply copy the binary to `/usr/bin/`. The man page can be installed this way: ```sh cd ./man/ gzip -c swarm.1 > swarm.1.gz mv swarm.1.gz /usr/share/man/man1/ ``` Once installed, the man page can be accessed with the command `man swarm`. ## Prepare amplicon fasta files ## To facilitate the use of **swarm**, we provide examples of shell commands that can be use to format and check the input fasta file. Warning, these examples may not be suitable for very large files. We assume your SFF or FASTQ files have been properly pair-assembled (with [pear](https://github.com/xflouris/PEAR) for example), trimmed from adaptors and primers (with [cutadapt](https://code.google.com/p/cutadapt/) for example), and converted to fasta. ### Linearization ### Swarm accepts wrapped fasta files as well as linear fasta files. However, linear fasta files where amplicons are written on two lines (one line for the fasta header, one line for the sequence) are easier to manipulate. For instance, many post-clustering queries can be easily done with `grep` when fasta files are linear. You can use the following code to linearize your fasta files. Code tested with GNU Awk 4.0.1. ```sh awk 'NR==1 {print ; next} {printf /^>/ ? "\n"$0"\n" : $1} END {printf "\n"}' amplicons.fasta > amplicons_linearized.fasta ``` ### Dereplication (mandatory) ### In a sample, or collection of sample, a given sequence is likely to appear several times. That number of strictly identical occurrences represents the *abundance* value of the sequence. Swarm requires all fasta entries to present abundance values to be able to produce high-resolution clusters, like this: ``` >seqID1_1000 acgtacgtacgtacgt >seqID2_25 cgtcgtcgtcgtcgt ``` were `seqID1` has an abundance of 1,000 and `seqID2` has an abundance of 25 (alternative formats are possible, please see the [user manual](https://github.com/torognes/swarm/blob/master/man/swarm_manual.pdf)). The role of the dereplication step is to identify, merge and sort identical sequences by decreasing abundance. Here is a command using [vsearch](https://github.com/torognes/vsearch) v1.3.3 or superior: ```sh vsearch \ --derep_fulllength amplicons.fasta \ --sizeout \ --relabel_sha1 \ --fasta_width 0 \ --output amplicons_linearized_dereplicated.fasta ``` The command performs the dereplication, the linearization (`--fasta_width 0`) and the renaming with hashing values (`--relabel_sha1`). If you can't or don't want to use vsearch, here is an example using standard command line tools: ```sh grep -v "^>" amplicons_linearized.fasta | \ grep -v [^ACGTacgt] | sort -d | uniq -c | \ while read abundance sequence ; do hash=$(printf "${sequence}" | sha1sum) hash=${hash:0:40} printf ">%s_%d_%s\n" "${hash}" "${abundance}" "${sequence}" done | sort -t "_" -k2,2nr -k1.2,1d | \ sed -e 's/\_/\n/2' > amplicons_linearized_dereplicated.fasta ``` Amplicons containing characters other than "ACGT" are discarded. The dereplicated amplicons receive a meaningful unique name (hash values), and are sorted by decreasing number of occurrences and by hash values (to guarantee a stable sorting). The use of a hashing function also provides an easy way to compare sets of amplicons. If two amplicons from two different sets have the same hash code, it means that the sequences they represent are identical. If for some reason your fasta entries don't have abundance values, and you still want to run swarm, you can easily add fake abundance values: ```sh sed '/^>/ s/$/_1/' amplicons.fasta > amplicons_with_abundances.fasta ``` Alternatively, you may specify a default abundance value with the `--append-abundance` (`-a`) option to be used when abundance information is missing from a sequence. ### Launch swarm ### Here is a typical way to use **swarm**: ```sh ./swarm -f -t 4 -w OTU_representatives.fasta amplicons.fasta > /dev/null ``` Swarm will partition your dataset with the finest resolution (local number of differences *d* = 1 by default, built-in elimination of potential chained OTUs, fastidious processing) using 4 CPU-cores. OTU representatives will be written to a new fasta file, other results will be discarded (`/dev/null`). See the [user manual](https://github.com/torognes/swarm/blob/master/man/swarm_manual.pdf) for details on swarm's options and parameters. ## Frequently asked questions ## To facilitate the use of **swarm**, we provide examples of options or shell commands that can be use to parse **swarm**'s output. We assume that the amplicon fasta file was prepared as describe above (linearization and dereplication). ### Refine swarm OTUs ### The chain-breaking, which used to be performed in a second step in swarm 1.0, is now built-in and performed by default. It is possible to deactivate it with the `--no-otu-breaking` option, but it is not recommended. The fastidious option is recommended when using *d* = 1, as it will reduce the number of small OTUs while maintaining a high clustering resolution. The principle of the fastidious option is described in the figure below: ![](https://github.com/frederic-mahe/swarm/blob/master/figures/swarm_2.0_fastidious_reduced.png) ### Count the number of amplicons per OTU ### You might want to check the size distribution of OTUs (number of amplicons in each OTU), and count the number of singletons (OTUs containing only one amplicon). It can be easily done with the `--statistics-file filename` option. Each line in the output file represents an OTU and provides different metrics. See the manual for a complete description. ### Get the seed sequence for each OTU ### It is frequent for subsequent analyses to keep only one representative amplicon per OTU (usually the seed) to reduce the computational burden. That operation is easily done with **swarm** by using the `-w filename` option. ### Get fasta sequences for all amplicons in a OTU ### For each OTU, get the fasta sequences for all amplicons. Warning, this loop can generate a very large number of files. To limit the number of files, a test can be added to exclude swarms with less than *n* elements. ```sh INPUT_SWARM="amplicons.swarms" INPUT_FASTA="amplicons.fasta" OUTPUT_FOLDER="swarms_fasta" AMPLICONS=$(mktemp) mkdir "${OUTPUT_FOLDER}" while read swarm ; do tr " " "\n" <<< "${swarm}" | sed -e 's/^/>/' > "${AMPLICONS}" seed=$(head -n 1 "${AMPLICONS}") grep -A 1 -F -f "${AMPLICONS}" "${INPUT_FASTA}" | sed -e '/^--$/d' > "./${OUTPUT_FOLDER}/${seed/>/}.fasta" done < "${INPUT_SWARM}" rm "${AMPLICONS}" ``` ## Troubleshooting ## If **swarm** exits with an error message saying `This program requires a processor with SSE2`, your computer is too old to run **swarm** (or based on a non x86-64 architecture). **swarm** only runs on CPUs with the SSE2 instructions, i.e. most Intel and AMD CPUs released since 2004. ## Citation ## To cite **swarm**, please refer to: Mahé F, Rognes T, Quince C, de Vargas C, Dunthorn M. (2014) Swarm: robust and fast clustering method for amplicon-based studies. PeerJ 2:e593 doi: [10.7717/peerj.593](http://dx.doi.org/10.7717/peerj.593) Mahé F, Rognes T, Quince C, de Vargas C, Dunthorn M. (2015) Swarm v2: highly-scalable and high-resolution amplicon clustering. PeerJ 3:e1420 doi: [10.7717/peerj.1420](http://dx.doi.org/10.7717/peerj.1420) ## Contact ## You are welcome to: * submit suggestions and bug-reports at: https://github.com/torognes/swarm/issues * send a pull request on: https://github.com/torognes/swarm/ * compose a friendly e-mail to: Frédéric Mahé and Torbjørn Rognes ## Third-party pipelines ## **swarm** is available in third-party pipelines: * [FROGS](https://github.com/geraldinepascal/FROGS): a [Galaxy](https://galaxyproject.org/)/CLI workflow designed to produce an OTU count matrix from high depth sequencing amplicon data. * [LotuS (v1.30)](http://psbweb05.psb.ugent.be/lotus/): extremely fast OTU building, annotation, phylogeny and abundance matrix pipeline, based on raw sequencer output. * [QIIME (v1.9)](http://qiime.org/): a multi-purpose pipeline for performing microbiome analysis from raw DNA sequencing data. ## Alternatives ## If you want to try alternative free and open-source clustering methods, here are some links: * [Vsearch](https://github.com/torognes/vsearch) * [DNAclust](http://dnaclust.sourceforge.net/) * [Crunchclust](https://code.google.com/p/crunchclust/) * [Sumaclust](http://metabarcoding.org/sumatra) ## New features## ### version 2.1.6 ### **swarm** 2.1.6 fixes problems with older compilers that do not have the x86intrin.h header file. It also fixes a bug in the output of seeds with the `-w` option when d>1. ### version 2.1.5 ### **swarm** 2.1.5 fixes minor bugs. ### version 2.1.4 ### **swarm** 2.1.4 fixes minor bugs in the swarm algorithm used for d=1. ### version 2.1.3 ### **swarm** 2.1.3 adds checks of numeric option arguments. ### version 2.1.2 ### **swarm** 2.1.2 adds the -a (--append-abundance) option to set a default abundance value to be used when abundance information is missing from the input file. If this option is not specified, missing abundance information will result in a fatal error. The error message in that case is improved. ### version 2.1.1 ### **swarm** 2.1.1 fixes a bug with the fastidious option that caused it to ignore some connections between heavy and light swarms. ### version 2.1.0 ### **swarm** 2.1.0 marks the first official release of swarm 2. ### version 2.0.7 ### **swarm** 2.0.7 writes abundance information in usearch style when using options `-w` (`--seeds`) in combination with `-z` (`--usearch-abundance`). ### version 2.0.6 ### **swarm** 2.0.6 fixes a minor bug. ### version 2.0.5 ### **swarm** 2.0.5 improves the implementation of the fastidious option and adds options to control memory usage of the Bloom filter (`-y` and `-c`). In addition, an option (`-w`) allows to output OTU representatives sequences with updated abundances (sum of all abundances inside each OTU). This version also enables dereplication when `d = 0`. ### version 2.0.4 ### **swarm** 2.0.4 includes a fully parallelized fastidious option. ### version 2.0.3 ### **swarm** 2.0.3 includes a working fastidious option. ### version 2.0.2 ### **swarm** 2.0.2 fixes SSSE3 problems. ### version 2.0.1 ### **swarm** 2.0.1 is a development release that partially implements the fastidious option. ### version 2.0.0 ### **swarm** 2.0.0 simplifies the usage of swarm by using the fast algorithm and the built-in OTU breaking by default. Some options are changed and some new output options are introduced. ### version 1.2.21 ### **swarm** 1.2.21 is supposed to fix some problems related to the use of the SSSE3 CPU instructions which are not always available. ### version 1.2.20 ### **swarm** 1.2.20 presents a production-ready version of the alternative algorithm (option `-a`), with optional built-in OTU breaking (option `-n`). That alternative algorithmic approach (usable only with *d* = 1) is considerably faster than currently used clustering algorithms, and can deal with datasets of 100 million unique amplicons or more in a few hours. Of course, results are rigourously identical to the results previously produced with swarm. That release also introduces new options to control swarm output (options `-i` and `-l`). ### version 1.2.19 ### **swarm** 1.2.19 fixes a problem related to abundance information when the sequence identifier includes multiple underscore characters. ### version 1.2.18 ### **swarm** 1.2.18 reenables the possibility of reading sequences from `stdin` if no file name is specified on the command line. It also fixes a bug related to CPU features detection. ### version 1.2.17 ### **swarm** 1.2.17 fixes a memory allocation bug introduced in version 1.2.15. ### version 1.2.16 ### **swarm** 1.2.16 fixes a bug in the abundance sort introduced in version 1.2.15. ### version 1.2.15 ### **swarm** 1.2.15 sorts the input sequences in order of decreasing abundance unless they are detected to be sorted already. When using the alternative algorithm for *d* = 1 it also sorts all subseeds in order of decreasing abundance. ### version 1.2.14 ### **swarm** 1.2.14 fixes a bug in the output with the swarm breaker option (`-b`) when using the alternative algorithm (`-a`). ### version 1.2.13 ### **swarm** 1.2.13 updates the citation. ### version 1.2.12 ### **swarm** 1.2.12 improves speed of new search strategy for *d* = 1. ### version 1.2.11 ### **swarm** 1.2.11 corrects the number of differences reported in the break swarms output. ### version 1.2.10 ### **swarm** 1.2.10 allows amplicon abundances to be specified using the usearch style in the sequence header (e.g. `>id;size=1`) when the `-z` option is chosen. Also fixes the bad URL shown in the previous version of swarm. ### version 1.2.9 ### **swarm** 1.2.9 includes a parallelized variant of the new search strategy for *d* = 1. It seems to be fairly scalable up to about 16 threads for longer reads (~400bp), while up to about 8 threads for shorter reads (~150bp). Using about 50% more threads than available physical cores is recommended. This version also includes the *d* parameter in the beginning of the mothur-style output (e.g., `swarm\_1`). Also, in the break_swarms output the real number of differences between the seed and the amplicon is indicated in the last column. ### version 1.2.8 ### **swarm** 1.2.8 fixes an error with the gap extension penalty. Previous versions effectively used a gap penalty twice as large as intended. This version also introduces an experimental new search strategy in the case where *d* = 1 that appears to be almost linear and faster at least for datasets of about half a million sequences or more. The new strategy can be turned on with the `-a` option. ### version 1.2.7 ### **swarm** 1.2.7 incorporates a few small changes and improvements to make it ready for integration into QIIME. ### version 1.2.6 ### **swarm** 1.2.6 add an option (`-r` or `--mothur`) to format the output file as a mothur-compatible list file instead of the native swarm format. When **swarm** encounters an illegal character in the input sequences it will now report the illegal character and the line number. ### version 1.2.5 ### **swarm** 1.2.5 can be run on CPUs without the POPCNT feature. It automatically checks whether the CPU feature is available and uses the appropriate code. The code that avoids POPCNT is just slightly slower. Only basic SSE2 is now required. ### version 1.2.4 ### **swarm** 1.2.4 changes the name of the new option from `--break_swarms` to `--break-swarms` for consistency with other options, and also adds a companion script `swarm_breaker.py` to refine swarm results (`scripts` folder). ### version 1.2.3 ### **swarm** 1.2.3 adds an option (`-b` or `--break_swarms`) to output all pairs of amplicons to `stderr`. The data can be used for post-processing of the results to refine the swarms. The syntax of the inline assembly code is also changed for compatibility with more compilers. ### version 1.2.2 ### **swarm** 1.2.2 fixes an issue with incorrect values in the statistics file (maximum generation and radius of swarms). This version is also a bit faster. ### version 1.2.1 ### **swarm** 1.2.1 removes the need for a SSE4.1 capable CPU and should now be able to run on most servers, desktops and laptops. ### version 1.2.0 ### **swarm** 1.2.0 introduces a pre-filtering of similar amplicons based on *k*-mers. This eliminates most of the time-consuming pairwise alignments and greatly improves speed. The speedup can be more than 100-fold compared to previous swarm versions when using a single thread with a large set of amplicons. Using multiple threads induces a computational overhead, but becomes more and more efficient as the size of the amplicon set increases. ### version 1.1.1 ### **swarm** now works on Apple computers. This version also corrects an issue in the pairwise global alignment step that could lead to sub-optimal alignments. Slightly different alignments may result relative to previous version, giving slightly different swarms. ### version 1.1.0 ### **swarm** 1.1.0 introduces new optimizations and is 20% faster than the previous version on our test dataset. It also introduces two new output options: `statistics` and `uclust-like` format. By specifying the `-s` option to **swarm** it will now output detailed statistics about each swarm to a specified file. It will print the number of unique amplicons, the number of occurrences, the name of the seed and its abundance, the number of singletons (amplicons with an abundance of 1), the number of iterations and the maximum radius of the swarm (i.e. number of differences between the seed and the furthermost amplicon). When using input data sorted by decreasing abundance, the seed is the most abundant amplicon in the swarm. Some pipelines use the [uclust output format](http://www.drive5.com/uclust/uclust_userguide_1_1_579.html#_Toc257997686 "page describing the uclust output format") as input for subsequent analyses. **swarm** can now output results in this format to a specified file with the `-u` option. swarm-2.1.6/man/000077500000000000000000000000001263351160000134215ustar00rootroot00000000000000swarm-2.1.6/man/swarm.1000066400000000000000000000546711263351160000146510ustar00rootroot00000000000000.\" ============================================================================ .TH swarm 1 "December 14, 2015" "version 2.1.6" "USER COMMANDS" .\" ============================================================================ .SH NAME swarm \(em find clusters of nearly-identical nucleotide amplicons .\" ============================================================================ .SH SYNOPSIS .B swarm [ .I options ] .I filename .\" ============================================================================ .SH DESCRIPTION Environmental or clinical molecular studies generate large volumes of amplicons (e.g., 16S or 18S SSU-rRNA sequences) that need to be clustered into molecular operational taxonomic units (OTUs). Common clustering methods are based on greedy, input-order dependent algorithms, with arbitrary selection of global cluster size and cluster centroids. To address that problem, we developed \fBswarm\fR, a fast and robust method that recursively groups amplicons with \fId\fR or less differences. \fBswarm\fR produces natural and stable clusters centered on local peaks of abundance, free from centroid selection induced input-order dependency. .PP Exact clustering is impractical on large data sets when using a naïve all-vs-all approach (more precisely a 2-combination without repetitions), as it implies unrealistic numbers of pairwise comparisons. \fBswarm\fR is based on a maximum number of differences \fId\fR between two amplicons, and focuses only on very close local relationships. For \fId\fR = 1 (default value), swarm uses an algorithm of linear complexity that performs exact-string matching by comparing hash-values. For \fId\fR = 2 or greater, swarm uses an algorithm of quadratic complexity that performs pairwise string comparisons. An efficient \fIk\fR-mer-based filtering and an astute use of comparisons results obtained during the clustering process allows to avoid most of the amplicon comparisons needed in a naïve approach. To speed up the remaining amplicon comparisons, \fBswarm\fR implements an extremely fast Needleman-Wunsch algorithm making use of the Streaming SIMD Extensions (SSE2) of modern x86-64 CPUs. If SSE2 instructions are not available, \fBswarm\fR exits with an error message. .PP \fBswarm\fR reads the named input \fIfilename\fR, a fasta file of nucleotide amplicons. The amplicon identifier is defined as the string comprised between the ">" symbol and the first space or the end of the line, whichever comes first. As \fBswarm\fR outputs lists of amplicon identifiers, amplicon identifiers must be unique to avoid ambiguity; swarm exits with an error message if identifiers are not unique. Amplicon identifiers must end with a "_" followed by a positive integer representing the amplicon copy number (or abundance annotation; usearch/vsearch users can use the option \-z to change that behavior). Abundance annotations play a crucial role in the clustering process, and swarm exits with an error message if that information is not available. The amplicon sequence is defined as a string of [acgt] or [acgu] symbols (case insensitive), starting after the end of the identifier line and ending before the next identifier line or the file end; \fBswarm\fR exits with an error message if any other symbol is present. .\" ---------------------------------------------------------------------------- .SS General options .TP 9 .BI \-b\fP,\fB\ \-\-boundary\~ "positive integer" when using the option \-\-fastidious (\-f), define the minimum mass of a large OTU as the number given with this option. The default value is 3, indicating that any OTU with mass 3 or more is considered "large". By default, an OTU is "small" if it has a mass of 2 or less, meaning that it is composed of either one amplicon of abundance 2, or two amplicons of abundance 1. Any positive value greater than 1 can be specified. Using higher boundary values will speed up the second pass, but also reduce the taxonomical resolution of \fBswarm\fR results. .TP .BI \-c\fP,\fB\ \-\-ceiling\~ "positive integer" when using the option \-\-fastidious (\-f), define \fBswarm\fR's maximum memory footprint (in megabytes). \fBswarm\fR will adjust the \-\-bloom\-bits (\-y) value of the Bloom filter to fit within the specified amount of memory. That option is not active by default. .TP .BI \-d\fP,\fB\ \-\-differences\~ "zero or positive integer" maximum number of differences allowed between two amplicons, meaning that two amplicons will be grouped if they have \fIinteger\fR (or less) differences. This is \fBswarm\fR's most important parameter. The number of differences is calculated as the number of mismatches (substitutions, insertions or deletions) between the two amplicons once the optimal pairwise global alignment has been found (see "pairwise alignment advanced options" to influencing that step). Any \fIinteger\fR between 0 and 256 can be used, but high \fId\fR values will decrease the taxonomical resolution of \fBswarm\fR results. Commonly used \fId\fR values are 1, 2 or 3, rarely higher. When using \fId\fR = 0, \fBswarm\fR will output results corresponding to a strict dereplication of the dataset, i.e. merging identical amplicons. Warning, \fBswarm\fR still requires fasta entries to present abundance values. Default number of differences is 1. .TP .B \-f\fP,\fB\ \-\-fastidious when working with \fId\fR = 1, perform a second clustering pass to reduce the number of small OTUs (recommended option). During the clustering process with \fId\fR = 1, an intermediate amplicon can be missing for purely stochastic reasons, interrupting the aggregation process. That option will create virtual amplicons, allowing to graft small OTUs upon bigger ones. By default, an OTU is "small" if it has a mass of 2 or less (see the \-\-boundary option to increase that value). To speed things up, \fBswarm\fR uses a Bloom filter to store intermediate results. Warning, that second pass can be 2 to 3 times slower than the first pass and requires much more memory. See the options \-\-bloom\-bits (\-y) or \-\-ceiling (\-c) to control the memory footprint of the Bloom filter. Warning, the fastidious option modifies clustering results. The output files produced by the options \-\-log (\-l), \-\-output\-file (\-o), \-\-mothur (\-r), \-\-uclust\-file, and \-\-seeds (\-w) are updated to reflect these modifications; the file \-\-statistics\-file (\-s) is partially updated (columns 6 and 7 are not updated); the output file \-\-internal\-structure (\-i) is not updated. .TP .B \-h\fP,\fB\ \-\-help display this help and exit. .TP .B \-n\fP,\fB\ \-\-no\-otu\-breaking deactivate the built-in OTU refinement (not recommended). Amplicon abundance values are used to identify transitions among in-contact OTUs and to separate them, yielding higher-resolution clustering results. That option prevents that separation, and in practice, allows the creation of a link between amplicons A and B, even if the abundance of B is higher than the abundance of A. .TP .BI \-t\fP,\fB\ \-\-threads\~ "positive integer" number of computation threads to use. The number of threads should be lesser or equal to the number of available CPU cores. Default number of threads is 1. .TP .B \-v\fP,\fB\ \-\-version output version information and exit. .TP .BI \-y\fP,\fB\ \-\-bloom\-bits\~ "positive integer" when using the option \-\-fastidious (\-f), define the size (in bits) of each entry in the Bloom filter. That option allows to balance the efficiency (i.e. speed) and the memory footprint of the Bloom filter. Large values will make the Bloom filter more efficient but will require more memory. Any value between 4 and 20 can be used. Default value is 16. See the \-\-ceiling (\-c) option for an alternative way to control the memory footprint. .LP .\" ---------------------------------------------------------------------------- .SS Input/output options .TP 9 .BI \-a\fP,\fB\ \-\-append\-abundance\~ "positive integer" set abundance value to use when some or all amplicons in the input file lack abundance values. Warning, it is not recommended to use \fBswarm\fR on datasets where abundance values are all identical. We provide that option as a courtesy to advanced users, please use it carefully. \fBswarm\fR exits with an error message if abundance values are missing and if this option is not used. .TP .BI \-i\fP,\fB\ \-\-internal\-structure \0filename output all pairs of nearly-identical amplicons to \fIfilename\fR using a five-columns tab-delimited format: .RS .RS .nr step 1 1 .IP \n[step]. 4 amplicon A label. .IP \n+[step]. amplicon B label. .IP \n+[step]. number of differences between amplicons A and B (\fIpositive integer\fR). .IP \n+[step]. OTU number (\fIpositive integer\fR). OTUs are numbered in their order of delineation, starting from 1. All pairs of amplicons belonging to the same OTU will receive the same number. .IP \n+[step]. number of steps from the OTU seed to amplicon B (\fIpositive integer\fR). .RE .RE .TP .BI \-l\fP,\fB\ \-\-log \0filename output all messages to \fIfilename\fR instead of \fIstandard error\fR, with the exception of error messages of course. That option is useful in situations where writing to \fIstandard error\fR is problematic (for example, with certain job schedulers). .TP .BI \-o\fP,\fB\ \-\-output\-file \0filename output clustering results to \fIfilename\fR. Results consist of a list of OTUs, one OTU per line. An OTU is a list of amplicon identifiers separated by spaces. Default is to write to standard output. .TP .B \-r\fP,\fB\ \-\-mothur output clustering results in a format compatible with Mothur. That option modifies \fBswarm\fR's default output format. .TP .BI \-s\fP,\fB\ \-\-statistics\-file \0filename output statistics to \fIfilename\fR. The file is a tab-separated table with one OTU per row and seven columns of information: .RS .RS .nr step 1 1 .IP \n[step]. 4 number of unique amplicons in the OTU, .IP \n+[step]. total copy number of amplicons in the OTU, .IP \n+[step]. identifier of the initial seed, .IP \n+[step]. initial seed copy number, .IP \n+[step]. number of amplicons with a copy number of 1 in the OTU, .IP \n+[step]. maximum number of iterations before the OTU reached its natural limits), .IP \n+[step]. theoretical maximum radius of the OTU (i.e., number of cummulated differences between the seed and the furthermost amplicon in the OTU). The actual maximum radius of the OTU is often much smaller. .RE .RE .TP .BI \-u\fP,\fB\ \-\-uclust\-file \0filename output clustering results in uclust-like file format to the specified file. That option does not modify \fBswarm\fR's default output format. .TP .BI \-w\fP,\fB\ \-\-seeds \0filename output OTU representatives to \fIfilename\fR in fasta format. The abundance value of each representative is the sum of the abundances of all the amplicons in the OTU. .TP .B \-z\fP,\fB\ \-\-usearch\-abundance accept amplicon abundance values in usearch/vsearch's style (>label;size=\fIinteger\fR[;]). That option influences the abundance annotation style used in output files. .\" which files are modified? -w at least. .LP .\" ---------------------------------------------------------------------------- .SS Pairwise alignment advanced options when using \fId\fR > 1, \fBswarm\fR recognizes advanced command-line options modifying the pairwise global alignment scoring parameters: .RS .TP 9 .BI \-m\fP,\fB\ \-\-match\-reward\~ "positive integer" set the reward for a nucleotide match. Default is 5. .TP .BI \-p\fP,\fB\ \-\-mismatch\-penalty\~ "positive integer" set the penalty for a nucleotide mismatch. Default is 4. .TP .BI \-g\fP,\fB\ \-\-gap\-opening\-penalty\~ "positive integer" set the gap open penalty. Default is 12. .TP .BI \-e\fP,\fB\ \-\-gap\-extension\-penalty\~ "positive integer" set the gap extension penalty. Default is 4. .LP .RE As \fBswarm\fR focuses on close relationships (i.e. \fId\fR = 2 or 3), clustering results are resilient to pairwise alignment model parameters modifications. Modifying model parameters has a stronger impact when clustering using a higher \fId\fR value. .\" classic parameters are +5/-4/-12/-1 .\" ============================================================================ .SH EXAMPLES .PP Clusterize the data set \fImyfile.fasta\fR into OTUs with the finest resolution possible (1 difference, built-in breaking, fastidious option) using 4 computation threads. OTUs are written to the file \fImyfile.swarms\fR, and OTU representatives are written to \fImyfile.representatives.fasta\fR. .PP .RS .B swarm \-t 4 \-f \-w .I myfile.representatives.fasta < myfile.fasta > myfile.swarms .RE .LP .\" ============================================================================ .\" .SH LIMITATIONS .\" List known limitations or bugs. .\" ============================================================================ .SH AUTHORS Concept by Frédéric Mahé, implementation by Torbjørn Rognes. .\" ============================================================================ .SH CITATION Mahé F, Rognes T, Quince C, de Vargas C, Dunthorn M. (2014) Swarm: robust and fast clustering method for amplicon-based studies. \fIPeerJ\fR 2:e593 .PP Mahé F, Rognes T, Quince C, de Vargas C, Dunthorn M. (2015) Swarm v2: highly-scalable and high-resolution amplicon clustering. \fIPeerJ\fR 3:e1420 .\" ============================================================================ .SH REPORTING BUGS Submit suggestions and bug-reports at , send a pull request on , or compose a friendly or curmudgeonly e-mail to Frédéric Mahé and Torbjørn Rognes . .\" ============================================================================ .SH AVAILABILITY The software is available from .\" ============================================================================ .SH COPYRIGHT Copyright (C) 2012, 2013, 2014, 2015 Frédéric Mahé & Torbjørn Rognes .PP This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. .PP 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 Affero General Public License for more details. .PP You should have received a copy of the GNU Affero General Public License along with this program. If not, see . .PP .\" ============================================================================ .SH SEE ALSO \fBswipe\fR, an extremely fast Smith-Waterman database search tool by Torbjørn Rognes (available from ). .PP \fBvsearch\fR, an open-source re-implementation of the classic uclust clustering method (by Robert C. Edgar), along with other amplicon filtering and searching tools. \fBvsearch\fR is implemented by Torbjørn Rognes and documented by Frédéric Mahé, and is available at . .PP .\" ============================================================================ .SH VERSION HISTORY New features and important modifications of \fBswarm\fR (short lived or minor bug releases are not mentioned): .RS .TP .BR v2.1.6\~ "released December 14, 2015" Version 2.1.6 fixes problems with older compilers that do not have the x86intrin.h header file. It also fixes a bug in the output of seeds with the `-w` option when d>1. .TP .BR v2.1.5\~ "released September 8, 2015" Version 2.1.5 fixes minor bugs. .TP .BR v2.1.4\~ "released September 4, 2015" Version 2.1.4 fixes minor bugs in the swarm algorithm used for \fId\fR = 1. .TP .BR v2.1.3\~ "released August 28, 2015" Version 2.1.3 adds checks of numeric option arguments. .TP .BR v2.1.1\~ "released March 31, 2015" Version 2.1.1 fixes a bug with the fastidious option that caused it to ignore some connections between large and small OTUs. .TP .BR v2.1.0\~ "released March 24, 2015" Version 2.1.0 marks the first official release of swarm v2. .TP .BR v2.0.7\~ "released March 18, 2015" Version 2.0.7 writes abundance information in usearch style when using options \-w (\-\-seeds) in combination with \-z (\-\-usearch\-abundance). .TP .BR v2.0.6\~ "released March 13, 2015" Version 2.0.6 fixes a minor bug. .TP .BR v2.0.5\~ "released March 13, 2015" Version 2.0.5 improves the implementation of the fastidious option and adds options to control memory usage of the Bloom filter (\-y and \-c). In addition, an option (\-w) allows to output OTU representatives sequences with updated abundances (sum of all abundances inside each OTU). This version also enables \fBswarm\fR to run with \fId\fR = 0. .TP .BR v2.0.4\~ "released March 6, 2015" Version 2.0.4 includes a fully parallelised implementation of the fastidious option. .TP .BR v2.0.3\~ "released March 4, 2015" Version 2.0.3 includes a working implementation of the fastidious option, but only the initial clustering is parallelized. .TP .BR v2.0.2\~ "released February 26, 2015" Version 2.0.2 fixes SSSE3 problems. .TP .BR v2.0.1\~ "released February 26, 2015" Version 2.0.1 is a development version that contains a partial implementation of the fastidious option, but it is not usable yet. .TP .BR v2.0.0\~ "released December 3, 2014" Version 2.0.0 is faster and easier to use, providing new output options (\-\-internal\-structure and \-\-log), new control options (\-\-boundary, \-\-fastidious, \-\-no\-otu\-breaking), and built-in OTU refinement (no need to use the python script anymore). When using default parameters, a novel and considerably faster algorithmic approach is used, guaranteeing \fBswarm\fR's scalability. .TP .BR v1.2.21\~ "released February 26, 2015" Version 1.2.21 is supposed to fix some problems related to the use of the SSSE3 CPU instructions which are not always available. .TP .BR v1.2.20\~ "released November 6, 2014" Version 1.2.20 presents a production-ready version of the alternative algorithm (option \-a), with optional built-in OTU breaking (option \-n). That alternative algorithmic approach (usable only with \fId\fR = 1) is considerably faster than currently used clustering algorithms, and can deal with datasets of 100 million unique amplicons or more in a few hours. Of course, results are rigourously identical to the results previously produced with swarm. That release also introduces new options to control swarm output (options \-i and \-l). .TP .BR v1.2.19\~ "released October 3, 2014" Version 1.2.19 fixes a problem related to abundance information when the sequence identifier includes multiple underscore characters. .TP .BR v1.2.18\~ "released September 29, 2014" Version 1.2.18 reenables the possibility of reading sequences from \fIstdin\fR if no file name is specified on the command line. It also fixes a bug related to CPU features detection. .TP .BR v1.2.17\~ "released September 28, 2014" Version 1.2.17 fixes a memory allocation bug introduced in version 1.2.15. .TP .BR v1.2.16\~ "released September 27, 2014" Version 1.2.16 fixes a bug in the abundance sort introduced in version 1.2.15. .TP .BR v1.2.15\~ "released September 27, 2014" Version 1.2.15 sorts the input sequences in order of decreasing abundance unless they are detected to be sorted already. When using the alternative algorithm for \fId\fR = 1 it also sorts all subseeds in order of decreasing abundance. .TP .BR v1.2.14\~ "released September 27, 2014" Version 1.2.14 fixes a bug in the output with the \-\-swarm_breaker option (\-b) when using the alternative algorithm (\-a). .TP .BR v1.2.12\~ "released August 18, 2014" Version 1.2.12 introduces an option \-\-alternative\-algorithm to use an extremely fast, experimental clustering algorithm for the special case \fId\fR = 1. Multithreading scalability of the default algorithm has been noticeably improved. .TP .BR v1.2.10\~ "released August 8, 2014" Version 1.2.10 allows amplicon abundances to be specified using the usearch style in the sequence header (e.g. ">id;size=1") when the \-z option is chosen. .TP .BR v1.2.8\~ "released August 5, 2014" Version 1.2.8 fixes an error with the gap extension penalty. Previous versions used a gap penalty twice as large as intended. That bug correction induces small changes in clustering results. .TP .BR v1.2.6\~ "released May 23, 2014" Version 1.2.6 introduces an option \-\-mothur to output clustering results in a format compatible with the microbial ecology community analysis software suite Mothur (). .TP .BR v1.2.5\~ "released April 11, 2014" Version 1.2.5 removes the need for a POPCNT hardware instruction to be present. \fBswarm\fR now automatically checks whether POPCNT is available and uses a slightly slower software implementation if not. Only basic SSE2 instructions are now required to run \fBswarm\fR. .TP .BR v1.2.4\~ "released January 30, 2014" Version 1.2.4 introduces an option \-\-break\-swarms to output all pairs of amplicons with \fId\fR differences to standard error. That option is used by the companion script `swarm_breaker.py` to refine \fBswarm\fR results. The syntax of the inline assembly code is changed for compatibility with more compilers. .TP .BR v1.2\~ "released May 16, 2013" Version 1.2 greatly improves speed by using alignment-free comparisons of amplicons based on \fIk\fR-mer word content. For each amplicon, the presence-absence of all possible 5-mers is computed and recorded in a 1024-bits vector. Vector comparisons are extremely fast and drastically reduce the number of costly pairwise alignments performed by \fBswarm\fR. While remaining exact, \fBswarm\fR 1.2 can be more than 100-times faster than \fBswarm\fR 1.1, when using a single thread with a large set of sequences. The minor version 1.1.1, published just before, adds compatibility with Apple computers, and corrects an issue in the pairwise global alignment step that could lead to sub-optimal alignments. .TP .BR v1.1\~ "released February 26, 2013" Version 1.1 introduces two new important options: the possibility to output clustering results using the uclust output format, and the possibility to output detailed statistics on each OTU. \fBswarm\fR 1.1 is also faster: new filterings based on pairwise amplicon sequence lengths and composition comparisons reduce the number of pairwise alignments needed and speed up the clustering. .TP .BR v1.0\~ "released November 10, 2012" First public release. .LP .\" ============================================================================ .\" NOTES .\" visualize and output to pdf .\" man -l swarm.1 .\" man -t <(sed -e 's/\\-/-/g' ./swarm.1) | ps2pdf -sPAPERSIZE=a4 - > swarm_manual.pdf .\" .\" INSTALL (sysadmin) .\" gzip -c swarm.1 > swarm.1.gz .\" mv swarm.1.gz /usr/share/man/man1/ swarm-2.1.6/man/swarm_manual.pdf000066400000000000000000000603401263351160000166050ustar00rootroot00000000000000%PDF-1.4 %쏢 5 0 obj <> stream xZv?O1)F<ܛw)$nN3cvPPԖ^d}~k_)Ό(Ķ$Z€3V_~~ W_2Gղ>]g8ݷWW!^0aWV~\7_o" W?Wocx^Ţ\?~O@WA8`(U}E?w< "2G>ҋ0ÌC-d("yDWd_-8adunaݩjd?VǦnTz\ < r%ݿ}ݛ;-PaR?Q@ ~)nă(Q4Ӑ8$W8 zo4+[jpL^_߼{+S1'HXezք-;e׶odujʁi[ˑe'r G$|A[DiPUĭJ9q%}pxzGWݽ_qh+RީGZ$N;XK&?dW> #lFژ¿xm#) Sة' =qcc߶},!bdX\Vw{oGVmLAM ^Q\6 iZVl+`ez:-{ğkSOC9(&)(s,G. LdJ}o`#9?_>Yގ$Dca3 %φ\]rCid %1C?Ac@>qo{" Kl7X)r΋*I*%*XGޢ1PB )tvTsF8K0_xIbͰ<í HɆ\b$"O3R; β//]<a]9sJ8_"E@&uQrOe/B ] U=` CvS-!-!u<ˍ#We*g, a8gDx#Ya粚 q zI',(Hn˩ǃiJ5F ʋ |*xø.x#bIάԸg>EMԝLy"(ZU7P!9u,z(ƔcYc9#~fU,je{=\L>VosݞZ# cǑ #ԊÍEjn9=JxrR|V XG-񬊬d_xwՀB b#Ut Tճ/U1@F648gL}j!RG+Xk 2_d pjiX1s"74J͔Hdf*[=S yE+ ?G>ɏ#qҶvy_pYZK:)ViaAd L 1PV*iP Uxœ!2K /)rޑZQ6fVnR }{Y8 dٰxsT %]p!Mm/Q@PLJ"o (n@Y4LlI?J;Vݛb?OkݶݽXq-<R>̏G1zEfPO>5 3 qŅD6oa__2Z>@;X傕 y@Uۖ?LlN 3SvNݾ! ,*pj60[Ac \3l=k^dA Y.G RU0;΃/隍vkO}㱬$ nTp*l^  %^"I-ȢF(wSbٓl@:S;4݋7(HN3SW:' !̊":H}c34XO(92둛1O8Uջ6K: 9H=?~X{\R#EvG4yT@cp>ʢML Vku7uGSRRUxcjrԑÍusl4 9.lO #ÆgzhHw#mu˃ЛZS8N"$[ASn/5WC)AN(v4zẔ<#VSG*`yz }O-=^(1S$JL R7㸥}_ Jc(:gjD YItu7ҥ K @e~#x~3HOHvE11ꐦrP\hZ7Ԍ,6R uif`iE<-1M%O~7k̂0z”IxZ4 -؉MЁ җs?Oe[\`\lPb@3=d_ܼadtY\>SmAq^ozJ` ԑYl!EE[gD1DzZ c9wQA2DQQ?T㗶utU z\2h${K9ƌo)+0/r ;~\|ԡțfO4#NUOҐJSdJ(IBPjIwsB Aup%;^7eKaM7tF)5:`?h:5R) Xc.Z$j@03ėM YϜDtodfPTĉ[\!Fn㹙\sppSx}0o/4p7]s̀{h[h>wӥ"I,zf/b4aͽ;o^ޓI-\ϱMCVzjpvQd%#Ui5 d4WǸ7'̺,1nژ4c']]@ /ՕQ˩qR\Q|_u8]"'~R. SD($7DD@3z~BMjq-Lܯs}sh?3@-D>~I~;5;d]Fo7:9M- ԃC"_&Hk)gC=6 Cr)p*{|}Қ$ZM΃{,lwa~>C@>5M,m j8gIa(z/* ܆77fˉj8 "z RbGĦ@=aز vvugSo&Q':sQc(zNYSai!pDF&\mlg#QV.hZo8c~dr|-K}1߻n&teNoض)a.օy;%-Epڪ2Hpq]Wx&?6s`xS|ShYj_3]6IEpgZMK/5؍ylzYK jE#d4w jiNX=.NM4\2b@d }ITuGA4. yEG/<- {=Ի`B4[Z1~ޠtX$+cp Wendstream endobj 6 0 obj 4398 endobj 14 0 obj <> stream xYr+ hF\YPIq"Q ciιf(V1sϽ\Uw~GfT{u9=_wB1iw+!x ?W".x$+;wov~޷?__exÂg~ם[(/Tcƭ^S~neewjj'~WQpMϿ~S(̑ |='0@f-m(^QNl+xQa\2(46x<섟|؅.JGep<ղ]ĵiċ"_-IK;~Ȇ=.LSz{9JX31h?[S+┧i Rυ0a.(*r6rU:ʞ=)Tx`O|4ܑ<JMB=FRGAn$`}΃Bx'uc@CcsQ)#0vdDԬji#s*'Q b4SW"?* +yzn2!Cfj|"T{I]'Zl88{($e8 vsM6l!.ya,K  l9ACs8Phը]x{iAG3$+6Pq^[NйR+Y33yQ#aCK$u:@4>['':=qbՌX#ԽeYc$"P8&&4F;IYBɹ#k"Gw%Ĺ-Ցuu'<݀Kbn.,vkSWAFF~%R*<<X+RkkFgNV_6k|aeG6n>`u%,i 0kulo;IAt]ㄾ=A?`V}cr>LLr-reʨT}*2VtS9 ]UCt.UdJx?iq(Rӗ-$K5IXm.ⓔx^9 A)QG;ytjK t>̿…/W?̋0^4Y1.5ղƴ01t%E6NS êf]ݚ]0%D(?#zQ6lvT6'f)%mH<'H^ثX=1*>AlJ:C@fNBH-ɥfύlk*cs8j)ɀ7m66!*BwGPIjRWoJ{% P#iiĐH ^ז kanɀф' Q_] KҐi,ޒbA%#o?Q%K663tI^@h]BЎ8C~67/x򉆪x>~C9Bt9h6Q UH,^B2Kj0XD&P+xy=D3!4*ji7yrHG h30GS j}f@[$Ez^OMG]05"x4GAF #ܑFu4p75l[Om"Qp:UDR<&b`WzɅ2գޖh= G)N4kXY"`]9V륊3_-ڋlc1Fb̊"J0MyD㤧TMY93(И=fkv6֜)iC7] )g[?'?2:f=iD?3ezGP(2p,/% )5 Vg*RTޑ᪶POk1HNey1FPpY 6C 743/zm!tdoytkZZnp) nL4t*-Ve0Ԗ{w3:yo@m{?9-r;, MH=jDX$g+H,[u^ MQAUdh:u9ueUٚ]~_*Bԗ3GEA_rt?BfQвq*6X̨ktNZQ /59_E$>H.}@_>>dZЪVr^ oee."va&o\O`xwX%=%ȷ+8]0(N^{44G۔}ɋjA%"@jRT6Zg#_lLO hV$h:UmZo2sײm5`JL95K@R*%]!tSYb>P.ߴk)Gpz: *60^눸6fXaɱ}2qDw/~ qI"017_RKqtlvnҜs; D7%Q`4Ūd.iF;|D>zw"B.6ʂ(ViaIF0K$Ͷ@"`>Ĩg^p!c8^JuQi`zGEJUM&υO2í>/9;_!P⽆*"1FzH~w{weendstream endobj 15 0 obj 3153 endobj 19 0 obj <> stream xYɒFWMDBaÎGLF32uR$IUY/L'>eWoIQx~5iRpca$ HdWxvnŒ~Dvw^wېf "W^/Md4Iͳj-8M2^WKz%PߋNqٰ=ً$Ig4K۽%R=[,چD,.۪=K㡂0M^ #lhw(ПUEj!e~\q=:ig@ LJa@؝Oyϵ Ur/ ,aNۄ!Ͳ NGx\a1̜ٷZII#Io9eIlîh/},Ĺ/(Pt]ۍҘ Xp.IA5 R #%D'ȥ$u_ ^l>?py-'S|zJ԰@:IVrC8˕`J*5-(sx$C%:y5QיMD_ ~Tog#xcߪ q='H1K)TT@ߩuBU@"1U4Rz$p{d){МT?ˎ~vmapاKDuXzo th}zgY2z[nȼһiƣ-;_{g\~λ"BRR6rX%^%PtpPDiL#D+NV0S 4y饎?b#= >'H&bW^2-B꫕=qt7GCf&3=<)HA.d(Zњ8L$:2ncOnNx -Ec : "@e!X hgE>O_{=Jx"hƙHRIo7 2kqUF& O{)ӵ|oȳ őa* 34X+jcH1ӎZ=Y M~#=褙>%[z"v}8yN_O==Tr2% w6[Lqڬ:Xփv+ jƕ!$-+U[%i~nbnX[PVCň&堓}X+; zK&㋡Jž* 30x6!3c2s~t5ʍ>8g.Isnx{ڝVˆD{Z^N:,[/Deu$D:)_Ϟw'!rӺKQ<+@ޠJmvLQEW̉.!dq겺ƵgZZ=MPn"{$ntYkthtSMSc~޶2f&7+*DY|fZEtr1U";Hܛ +{ʛ# ?ҿ,pdCņٷ҇˔f_ mՋ8q4Z y2emCZ) eYJPiB4S@̦ n>LT3 2W]xHP]5?jtIN ٢UɽkkjٌQVk ^BNG ؀BY7[D5x/E!0$@Yd^#z<ywendstream endobj 20 0 obj 2728 endobj 24 0 obj <> stream xYRH}+iFڙirm&U%Kn-oGqN.Z,`j;Zv#&)~hUy`oHņ0 `S76b 8KEoN5'qTEz2a@M )#ˡa|.-פFU9/eυJ$ZK/2^VeUgderrI,GLv-c -!ͨTuV$fǎSmGL_/x9Vd9B>M ēI^$ P]EU$x6.)"ЄOfXD스8U~-QN{!&3hCKiȦxn5l0fFզX&ä6vCɊq5%|6'o6|*L$Dْ#6!ʮ.{ASn/mtg,Fؼ@8= Qkuhfǘ=fy4P Z1wq \Gw!9!q@ORE7]Q\<[;k]M@s7w_h'4/F@iaʬ߷-'OTGY,耉$>Sj1n~:v߇k| >fe%ۃ`iW'Dd vLj>EFb bޏuZ xP:63а9lO^/˷:1˷j,d괛I0PeVoj2]!ۼpRAbUkdoBUy!!xԫ/(hse˓CDȶNSj!r%XBv04Nq%@6}脊H lK,.ӺMBj 52ЂhͿ/gZgsJc~"9W(]f Ek0gLO.uD1luz PONW-)BJl` pDf9]ءmߎEnP6=h%ח4rENʪHTY5h %S]uB` 9]J&jACoyƋ(%=ؑ\$ AHrI %d`Ґ XNa?:R0A(-M ڴhUɰK˹^>-ڇo %6GZNGUXEy K!65ʮYWZ% 12#gM` :7gM#uu5JXj8/ ,ORdQُze,ǘr8=s!E}kшv0EiV=c f#'d PgM bj"&hX[N<ՃĎzwTxž0=#ј~i:]=A:Aj( YHA8\eh=,YZ}{!MΒDD08!9rNWoC< Ԓ4577pbA˶$\cB Uԥzl}q6U+ z ˳(>Y*I,6gQˎXB^Tz@1ҟ:AK SAaéTC Q W+Ϣ(Ne Re8Ua\qd?As7 N@LhQ,#"Ria\ipjlU`s$oz JAV-hڗC?p4tH9^kXj#WFPDlHAU!;R74Eˌ-y7o!ϜsMd"n`u0^-!ũ֊vdbnW&Iάré~O ]g8qLu\B x2 e_oAʼ#p4JbMp#h-O$v$ua="0S]j8 :q'_(ӣf*lE3׮JRQ J rL}CR$T+I, ZZ6 f1m8O,XWu5%7(,Wn1Lݞ4DcW~ITjRF9~GcȳK md )zY\ NTGt iNVՊ/dג1sG)`@}-"yEcyVϮ4Dmmzp欨5celOc"I2 ᮤ'sɸ0H EzJ2!SǦhB;crs,<A֌9G94Bf<Q|&#2D;IMWsDsY) X|6 !jS#;-=,OeNirQ˭Ʀ/Q Fr{@>jb<іgDz""M+F ]:ypQ(%MU*5c[a&T]؛t=QFMat22$uݖ{6w(7uc/rn{yt(٤x vÎBTɒ[N~bS.NQ8F mrO꡺RDm&'Cclj"=Z1DoGbf|nex5+P{*ARɱHObbהǘEf:aMVT(uu=UJFʘPWY=kSCb*$@2J ZTZpfo; &2"dw6줬"QUbQ9U=]sAZ7Mx]ZŪ@i-n;~1Gendstream endobj 30 0 obj 2549 endobj 34 0 obj <> stream xYْ}W*5ĮxypeyI8Rղn3˪ͳCDl- ]БBWGal!ou48jb߸dצȚ\2v=^4y Y}QѲ9=S "ڮ +dS<}7Ju7LJ*^<_šs6Ig W[D>{Ĥodd,,b_d c:uッlؠ z5smGA zO8myȍR.V+Cn{chFqa\1]/@~YWl{5F&&"r8bnGt3먡فNSiwD/<\|-Nv%=Lu kq5wR$Nѫa?瑍p$"1)rm6'ְ HmտS4uǾF'bL/.ݠ\?ܓ?E06Qve->X^!dZgQ%-Bx Bxo/ش"Yk9w5mI U#4(gU+?T\a[ț5916 &ԛ/sܲ>vb_))kVuzdW@uzZ(x:MNX9^ Luu\LT7,er yHwϾ,wƴmwV:w; 1U! qBYvb1[* 3>סkɎĈGԹ5h(`   ?Opv[!QRIȤ4p@`(o8whO6n)o)d!G$B]UU5y~Țs#iY6I滋ꢢB$zL^gg&gIW}=Dul$PL2D8ZB| ЏSe޵;mU?fHYT{ӟ Z< ?dybq?Wۿs;?/O:HMEƕuu#y_~I ؕkR纽Ј'4^ꗬI4  4ь懯߂&e'DlT 7 Qizǟ.#}ƒ)Mk@!m$N a`[y8-jSШؙǁ[nEtR{DU|^!jъWUD#p$fbhux<9t,BX5'+.{憜}X&f=NԷ{ilXWvfZ3YݓXIbųsrhC?Ve͐ug{l,<zz*Ek V $B8fehDiH{a~-ftRE؜LU)t:7Vň4,N/%#>QlSC Dհ+,b4Ǭ*co*ÙlQ#&bAk=܍@Δ]sS#/&VJHFKƢ1< ~OG)Qv*R 1F[K30.%mx߀ {M`uۙ`4˓~U}#]EAJ\=OÒ@ЍK$?8Qj1z;&6YNӕb"'4u2i2..C'cibS ywZt طr*3L־F r:UAxuU> dg`WjJ)V;fW$y灭ihiT0_?/3"7LEtIAٱVB̄u3VL6+0EIb0U%BpT-a# ꪅwxD~E@{ʈ~ir?24-lub!bn+|| AAj'`p~3S jZG>BPTi$k0 /wf$^Qtca0,g$/Iɞ6a uukTHfZ3.14ddz)aWDJCN"ˊB݇B:B8c Jsvb4P> sa &SQ??YL`I˛L&V>C$Gs[ dOW< c.Gz^~L 5f"ɟc2W$}͘xİNr> stream x}P;o0+nL9NmC%  4S$O?a5L5lZ&`Î:*kx2z S !h֌TH\> /Contents 5 0 R >> endobj 13 0 obj <> /Contents 14 0 R >> endobj 18 0 obj <> /Contents 19 0 R >> endobj 23 0 obj <> /Contents 24 0 R >> endobj 28 0 obj <> /Contents 29 0 R >> endobj 33 0 obj <> /Contents 34 0 R >> endobj 38 0 obj <> /Contents 39 0 R >> endobj 3 0 obj << /Type /Pages /Kids [ 4 0 R 13 0 R 18 0 R 23 0 R 28 0 R 33 0 R 38 0 R ] /Count 7 >> endobj 1 0 obj <> endobj 7 0 obj <>endobj 11 0 obj <> endobj 12 0 obj <> endobj 16 0 obj <> endobj 17 0 obj <> endobj 21 0 obj <> endobj 22 0 obj <> endobj 26 0 obj <> endobj 27 0 obj <> endobj 31 0 obj <> endobj 32 0 obj <> endobj 36 0 obj <> endobj 37 0 obj <> endobj 41 0 obj <> endobj 42 0 obj <> endobj 10 0 obj <> endobj 43 0 obj <> endobj 9 0 obj <> endobj 44 0 obj <> endobj 8 0 obj <> endobj 45 0 obj <> endobj 46 0 obj <>stream 2015-12-14T10:54:53+01:00 2015-12-14T10:54:53+01:00 groff version 1.19.2 Untitled endstream endobj 2 0 obj <>endobj xref 0 47 0000000000 65535 f 0000021009 00000 n 0000023552 00000 n 0000020908 00000 n 0000019776 00000 n 0000000015 00000 n 0000004483 00000 n 0000021074 00000 n 0000021941 00000 n 0000021804 00000 n 0000021664 00000 n 0000021115 00000 n 0000021145 00000 n 0000019936 00000 n 0000004503 00000 n 0000007728 00000 n 0000021195 00000 n 0000021225 00000 n 0000020098 00000 n 0000007749 00000 n 0000010549 00000 n 0000021275 00000 n 0000021305 00000 n 0000020260 00000 n 0000010570 00000 n 0000013713 00000 n 0000021355 00000 n 0000021385 00000 n 0000020422 00000 n 0000013734 00000 n 0000016355 00000 n 0000021435 00000 n 0000021465 00000 n 0000020584 00000 n 0000016376 00000 n 0000019346 00000 n 0000021515 00000 n 0000021545 00000 n 0000020746 00000 n 0000019367 00000 n 0000019756 00000 n 0000021595 00000 n 0000021625 00000 n 0000021748 00000 n 0000021885 00000 n 0000022023 00000 n 0000022129 00000 n trailer << /Size 47 /Root 1 0 R /Info 2 0 R /ID [<4698FD6560D35D52BB6245ABB9C9C142><4698FD6560D35D52BB6245ABB9C9C142>] >> startxref 23706 %%EOF swarm-2.1.6/scripts/000077500000000000000000000000001263351160000143355ustar00rootroot00000000000000swarm-2.1.6/scripts/amplicon_contingency_table.py000066400000000000000000000072751263351160000222730ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Read all fasta files and build a sorted amplicon contingency table. Usage: python amplicon_contingency_table.py samples_*.fas """ from __future__ import print_function __author__ = "Frédéric Mahé " __date__ = "2015/03/15" __version__ = "$Revision: 2.0" import os import sys import operator #*****************************************************************************# # # # Functions # # # #*****************************************************************************# def fasta_parse(): """ Map amplicon ids, abundances and samples """ separator = ";size=" fasta_files = sys.argv[1:] all_amplicons = dict() samples = dict() amplicons2samples = dict() for fasta_file in fasta_files: sample = os.path.basename(fasta_file) sample = os.path.splitext(sample)[0] samples[sample] = samples.get(sample, 0) + 1 with open(fasta_file, "rU") as fasta_file: for line in fasta_file: if line.startswith(">"): amplicon, abundance = line.strip(">\n").split(separator) abundance = int(abundance) if amplicon not in amplicons2samples: amplicons2samples[amplicon] = {sample: abundance} else: # deal with duplicated samples amplicons2samples[amplicon][sample] = amplicons2samples[amplicon].get(sample, 0) + abundance all_amplicons[amplicon] = all_amplicons.get(amplicon, 0) + abundance # deal with duplicated samples duplicates = [sample for sample in samples if samples[sample] > 1] if duplicates: print("Warning: some samples are duplicated", file=sys.stderr) print("\n".join(duplicates), file=sys.stderr) samples = sorted(samples.keys()) return all_amplicons, amplicons2samples, samples def main(): """ Read all fasta files and build a sorted amplicon contingency table """ # Parse command line all_amplicons, amplicons2samples, samples = fasta_parse() # Sort amplicons by decreasing abundance (and by amplicon name) sorted_all_amplicons = sorted(all_amplicons.iteritems(), key=operator.itemgetter(1, 0)) sorted_all_amplicons.reverse() # Print table header print("amplicon", "\t".join(samples), "total", sep="\t", file=sys.stdout) # Print table content for amplicon, abundance in sorted_all_amplicons: abundances = [amplicons2samples[amplicon].get(sample, 0) for sample in samples] total = sum(abundances) abundances = [str(i) for i in abundances] # Sanity check if total == abundance: print(amplicon, "\t".join(abundances), total, sep="\t", file=sys.stdout) else: print("Abundance sum is not correct for this amplicon", amplicon, abundance, total, file=sys.stderr) sys.exit(-1) return #*****************************************************************************# # # # Body # # # #*****************************************************************************# if __name__ == '__main__': main() sys.exit(0) swarm-2.1.6/scripts/graph_plot.py000066400000000000000000000172701263351160000170550ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Visualize the internal structure of a swarm (color vertices by abundance). Requires the module igraph and python 2.7+. Limitations: amplicons grafted with the fastidious option will be discarded and will not be visualized. The script does not deal with ";size=" abundance annotations. """ from __future__ import print_function __author__ = "Frédéric Mahé " __date__ = "2015/04/22" __version__ = "$Revision: 3.0" import sys import os.path from igraph import Graph, plot from optparse import OptionParser #*****************************************************************************# # # # Functions # # # #*****************************************************************************# def option_parse(): """ Parse arguments from command line. """ desc = """Visualize the internal structure of a given OTU.""" parser = OptionParser(usage="usage: %prog -s FILE -i FILE -o INT", description=desc, version="%prog version 2.0") parser.add_option("-s", "--swarms", metavar="", action="store", dest="swarms", help=" contains swarm's results") parser.add_option("-i", "--internal_structure", metavar="", action="store", dest="internal_structure", help=" contains OTUs' internal structure") parser.add_option("-o", "--OTU", metavar="", action="store", type="int", dest="OTU", default=1, help="Select the nth OTU (first by default)") parser.add_option("-d", "--drop", metavar="", action="store", type="int", dest="drop", default=0, help="Drop amplicons seen or less times (0)") (options, args) = parser.parse_args() return options.swarms, options.internal_structure, \ options.OTU, options.drop def parse_files(swarms, internal_structure, OTU, drop): """ """ # List amplicon ids and abundances amplicons = list() with open(swarms, "rU") as swarms: for i, swarm in enumerate(swarms): if i == OTU - 1: # Deal with ";size=" in a rather clumsy way... but it works amplicons = [ tuple( item.replace(";size=", "_").rstrip(";").rsplit("_", 1)) for item in swarm.strip().split(" ")] break # Drop amplicons with a low abundance (remove connections too) if drop: amplicons = [amplicon for amplicon in amplicons if int(amplicon[1]) > drop] # Convert amplicon names to amplicon indexes (igraph uses # numerical ids, not names). Requires python 2.7+) amplicon_index = {amplicon[0]: i for (i, amplicon) in enumerate(amplicons)} amplicon_connected = {amplicon[0]: False for amplicon in amplicons} # List pairwise relations relations = list() with open(internal_structure, "rU") as internal_structure: for line in internal_structure: # Get the first four elements of the line ampliconA, ampliconB, d, OTU_number = line.strip().split("\t")[0:4] OTU_number = int(OTU_number) if OTU_number == OTU: amplicon_connected[ampliconA] = True amplicon_connected[ampliconB] = True if ampliconA in amplicon_index and ampliconB in amplicon_index: relations.append((amplicon_index[ampliconA], amplicon_index[ampliconB])) elif OTU_number > OTU: break # Drop amplicons grafted with the fastidious option amplicons = [amplicon for amplicon in amplicons if amplicon_connected[amplicon[0]]] # Deal with errors if not amplicons or not relations: print("Error: OTU does not exists or contains only one element.", file=sys.stderr) sys.exit(-1) return amplicons, relations def build_graph(amplicons, relations): """ Convert pairwise relations into a graph structure. """ # Create vertices (= number of unique amplicons) g = Graph(len(amplicons)) g.add_edges(relations) amplicon_ids = [amplicon[0] for amplicon in amplicons] abundances = [int(amplicon[1]) for amplicon in amplicons] minimum, maximum = min(abundances), max(abundances) # Determine canvas size if len(abundances) < 500: bbox = (1920, 1080) elif len(abundances) > 4000: bbox = (5760, 3240) else: bbox = (3840, 2160) # Compute node attributes node_colors = list() node_sizes = list() node_labels = list() for abundance in abundances: # Color is coded by a 3-tuple of float values (0.0 to 1.0) # Start from a max color in rgb(red, green, blue) max_color = (176, 196, 222) # light steel blue color = [1.0 * (c + (255 - c) / abundance) / 255 for c in max_color] node_colors.append(color) node_size = 30 + (abundance * 70 / maximum) node_sizes.append(node_size) # Label nodes with an abundance greater than 10 if abundance >= 10 or abundance == maximum: node_labels.append(str(abundance)) else: node_labels.append("") # Doesn't work with "None" g.vs["name"] = amplicon_ids g.vs["abundance"] = abundances g.vs["label"] = node_labels g.vs["color"] = node_colors g.vs["vertex_size"] = node_sizes return g, bbox def main(): """ Backbone of the script """ # Parse command line options. swarms, internal_structure, OTU, drop = option_parse() # Output file basename = os.path.splitext(swarms)[0] output_pdf = basename + "_OTU_" + str(OTU) + ".pdf" # output_svg = basename + "_OTU_" + str(OTU) + ".svg" output_graphml = basename + "_OTU_" + str(OTU) + ".graphml" # Collect data amplicons, relations = parse_files(swarms, internal_structure, OTU, drop) # Build the graph with igraph g, bbox = build_graph(amplicons, relations) # Select the attributes to display visual_style = dict() visual_style["vertex_size"] = g.vs["vertex_size"] visual_style["vertex_label"] = g.vs["label"] visual_style["vertex_color"] = g.vs["color"] visual_style["vertex_label_dist"] = 0 visual_style["layout"] = g.layout("fr") # alternatives: "kk", "drl" visual_style["bbox"] = bbox visual_style["margin"] = 20 # Output the graph (profiling shows that 98% of the computation # time is spent on "layout", no need to try to optimize the rest) g.write_graphml(output_graphml) plot(g, output_pdf, **visual_style) # # plot(g, output_svg, **visual_style) return #*****************************************************************************# # # # Body # # # #*****************************************************************************# if __name__ == '__main__': main() sys.exit(0) swarm-2.1.6/src/000077500000000000000000000000001263351160000134355ustar00rootroot00000000000000swarm-2.1.6/src/Makefile000066400000000000000000000031641263351160000151010ustar00rootroot00000000000000# SWARM # # Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # # Contact: Torbjorn Rognes , # Department of Informatics, University of Oslo, # PO Box 1080 Blindern, NO-0316 Oslo, Norway # Makefile for SWARM # Profiling options #COMMON=-pg -g COMMON=-g COMPILEOPT=-Wall -Wsign-compare -O3 -msse2 -mtune=core2 -Icityhash LIBS=-lpthread LINKFLAGS=$(COMMON) CXX=g++ CXXFLAGS=$(COMPILEOPT) $(COMMON) PROG=swarm OBJS=swarm.o db.o search8.o search16.o nw.o matrix.o util.o scan.o \ algo.o algod1.o qgram.o ssse3.o derep.o arch.o cityhash/city.o DEPS=Makefile swarm.h bitmap.h bloom.h cityhash/config.h cityhash/city.h \ threads.h .SUFFIXES:.o .cc %.o : %.cc $(DEPS) $(CXX) $(CXXFLAGS) -c -o $@ $< all : $(PROG) swarm : $(OBJS) $(CXX) $(LINKFLAGS) -o $@ $(OBJS) $(LIBS) mkdir -p ../bin cp -a swarm ../bin clean : rm -rf swarm *.o *~ ../bin/ gmon.out cityhash/*.o ../man/*~ ../*~ ssse3.o : ssse3.cc $(DEPS) $(CXX) -mssse3 $(CXXFLAGS) -c -o $@ $< swarm-2.1.6/src/algo.cc000066400000000000000000000450071263351160000146740ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #define BITS 8 static unsigned long count_comparisons_8; static unsigned long count_comparisons_16; static unsigned long targetcount; static unsigned long * targetindices; static unsigned long * targetampliconids; static unsigned long * scores; static unsigned long * diffs; static unsigned long * alignlengths; static unsigned long * qgramamps; static unsigned long * qgramdiffs; static unsigned long * qgramindices; static struct ampliconinfo_s { unsigned ampliconid; unsigned diffestimate; /* lower bound estimate of dist from initial seed */ unsigned swarmid; unsigned generation; unsigned radius; /* actual diff from initial seed */ } * amps; static unsigned long swarmed; static unsigned long seeded; void algo_run() { count_comparisons_8 = 0; count_comparisons_16 = 0; unsigned long searches = 0; #ifdef VERBOSE unsigned long estimates = 0; #endif unsigned long largestswarm = 0; unsigned long swarmsize = 0; unsigned long maxgenerations = 0; unsigned long amplicons = db_getsequencecount(); unsigned long longestamplicon = db_getlongestsequence(); db_qgrams_init(); qgram_diff_init(); amps = (struct ampliconinfo_s *) xmalloc(amplicons * sizeof(struct ampliconinfo_s)); targetampliconids = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); targetindices = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); scores = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); diffs = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); alignlengths = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); qgramamps = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); qgramdiffs = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); qgramindices = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); unsigned long * hits = (unsigned long *) xmalloc(amplicons * sizeof(unsigned long)); unsigned long diff_saturation = MIN(255 / penalty_mismatch, 255 / (penalty_gapopen + penalty_gapextend)); unsigned char * dir = 0; unsigned long * hearray = 0; if (uclustfile) { dir = (unsigned char *) xmalloc(longestamplicon*longestamplicon); hearray = (unsigned long *) xmalloc(2 * longestamplicon * sizeof(unsigned long)); } /* set ampliconid for all */ for(unsigned long i=0; i 0) { search_do(seedampliconid, targetcount, targetampliconids, scores, diffs, alignlengths, bits); searches++; if (bits == 8) count_comparisons_8 += targetcount; else count_comparisons_16 += targetcount; for(unsigned long t=0; tswarmed; j--) { amps[j] = amps[j-1]; } amps[swarmed] = temp; } amps[swarmed].swarmid = swarmid; amps[swarmed].generation = 1; if (maxgen < 1) maxgen = 1; amps[swarmed].radius = diff; if (diff > maxradius) maxradius = diff; unsigned poolampliconid = amps[swarmed].ampliconid; hits[hitcount++] = poolampliconid; if (opt_internal_structure) { fprint_id_noabundance(internal_structure_file, seedampliconid); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, poolampliconid); fprintf(internal_structure_file, "\t%u", diff); fprintf(internal_structure_file, "\t%lu\t1", swarmid); fprintf(internal_structure_file, "\n"); } abundance = db_getabundance(poolampliconid); amplicons_copies += abundance; if (abundance == 1) singletons++; swarmsize++; swarmed++; } } while (seeded < swarmed) { /* process each subseed */ unsigned subseedampliconid; unsigned subseedradius; unsigned long subseedindex; unsigned long subseedgeneration; unsigned long subseedabundance; subseedindex = seeded; subseedampliconid = amps[subseedindex].ampliconid; subseedradius = amps[subseedindex].radius; subseedgeneration = amps[subseedindex].generation; subseedabundance = db_getabundance(subseedampliconid); seeded++; targetcount = 0; unsigned long listlen=0; for(unsigned long i=swarmed; i 0) { search_do(subseedampliconid, targetcount, targetampliconids, scores, diffs, alignlengths, bits); searches++; if (bits == 8) count_comparisons_8 += targetcount; else count_comparisons_16 += targetcount; for(unsigned long t=0; t seeded) && (amps[pos-1].ampliconid > targetampliconid) && (amps[pos-1].generation > subseedgeneration)) pos--; if (pos < i) { struct ampliconinfo_s temp = amps[i]; for(unsigned j=i; j>pos; j--) { amps[j] = amps[j-1]; } amps[pos] = temp; } amps[pos].swarmid = swarmid; amps[pos].generation = subseedgeneration + 1; if (maxgen < amps[pos].generation) maxgen = amps[pos].generation; amps[pos].radius = subseedradius + diff; if (amps[pos].radius > maxradius) maxradius = amps[pos].radius; unsigned poolampliconid = amps[pos].ampliconid; hits[hitcount++] = poolampliconid; if (opt_internal_structure) { fprint_id_noabundance(internal_structure_file, subseedampliconid); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, poolampliconid); fprintf(internal_structure_file, "\t%u", diff); fprintf(internal_structure_file, "\t%lu\t%lu", swarmid, subseedgeneration + 1); fprintf(internal_structure_file, "\n"); } abundance = db_getabundance(poolampliconid); amplicons_copies += abundance; if (abundance == 1) singletons++; swarmsize++; swarmed++; } } } } } if (swarmsize > largestswarm) largestswarm = swarmsize; if (maxgen > maxgenerations) maxgenerations = maxgen; if (uclustfile) { fprintf(uclustfile, "C\t%lu\t%lu\t*\t*\t*\t*\t*\t", swarmid-1, swarmsize); fprint_id(uclustfile, seedampliconid); fprintf(uclustfile, "\t*\n"); fprintf(uclustfile, "S\t%lu\t%lu\t*\t*\t*\t*\t*\t", swarmid-1, db_getsequencelen(seedampliconid)); fprint_id(uclustfile, seedampliconid); fprintf(uclustfile, "\t*\n"); fflush(uclustfile); for(unsigned long i=1; i 0 ? nwalignment : "="); fprint_id(uclustfile, hit); fprintf(uclustfile, "\t"); fprint_id(uclustfile, seedampliconid); fprintf(uclustfile, "\n"); fflush(uclustfile); if (nwalignment) free(nwalignment); } } if (statsfile) { abundance = db_getabundance(seedampliconid); fprintf(statsfile, "%lu\t%lu\t", swarmsize, amplicons_copies); fprint_id_noabundance(statsfile, seedampliconid); fprintf(statsfile, "\t%lu\t%lu\t%lu\t%lu\n", abundance, singletons, maxgen, maxradius); } progress_update(seeded); } progress_done(); if (uclustfile) { free(dir); free(hearray); } /* output results */ if (amplicons > 0) { char sep_amplicons; char sep_swarms; if (mothur) { /* mothur list file output */ sep_amplicons = ','; sep_swarms = '\t'; fprintf(outfile, "swarm_%ld\t%lu\t", resolution, swarmid); } else { /* native swarm output */ sep_amplicons = SEPCHAR; /* usually a space */ sep_swarms = '\n'; } fprint_id(outfile, amps[0].ampliconid); long previd = amps[0].swarmid; for (unsigned long i=1; i 0)) { progress_init("Writing seeds: ", amplicons); unsigned long mass = 0; unsigned previd = amps[0].swarmid; unsigned prevamp = amps[0].ampliconid; unsigned seed = prevamp; mass += db_getabundance(prevamp); for (unsigned long i=1; i"); fprint_id_with_new_abundance(fp_seeds, seed, mass); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, prevamp, 0); mass = 0; seed = amps[i].ampliconid; } previd = id; prevamp = amps[i].ampliconid; mass += db_getabundance(prevamp); progress_update(i); } fprintf(fp_seeds, ">"); fprint_id_with_new_abundance(fp_seeds, seed, mass); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, prevamp, 0); progress_done(); } free(qgramdiffs); free(qgramamps); free(qgramindices); free(hits); free(alignlengths); free(diffs); free(scores); free(targetindices); free(targetampliconids); free(amps); db_qgrams_done(); qgram_diff_done(); fprintf(logfile, "\n"); fprintf(logfile, "Number of swarms: %lu\n", swarmid); fprintf(logfile, "Largest swarm: %lu\n", largestswarm); fprintf(logfile, "Max generations: %lu\n", maxgenerations); #ifdef VERBOSE fprintf(logfile, "\n"); fprintf(logfile, "Estimates: %lu\n", estimates); fprintf(logfile, "Searches: %lu\n", searches); fprintf(logfile, "\n"); fprintf(logfile, "Comparisons (8b): %lu (%.2lf%%)\n", count_comparisons_8, (200.0 * count_comparisons_8 / amplicons / (amplicons+1))); fprintf(logfile, "Comparisons (16b): %lu (%.2lf%%)\n", count_comparisons_16, (200.0 * count_comparisons_16 / amplicons / (amplicons+1))); fprintf(logfile, "Comparisons (tot): %lu (%.2lf%%)\n", count_comparisons_8 + count_comparisons_16, (200.0 * (count_comparisons_8 + count_comparisons_16) / amplicons / (amplicons+1))); #endif } swarm-2.1.6/src/algod1.cc000066400000000000000000001226711263351160000151240ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ /* This version of the swarm algorithm uses Frederic's idea for d=1 to enumerate all of the maximum 7L+4 possible variants of a sequence with only one difference, where L is the length of the sequence. */ #include "swarm.h" #define HASH hash_cityhash64 #define HASHFILLFACTOR 0.5 #define POWEROFTWO //#define HASHSTATS /* Information about each amplicon */ static struct ampinfo_s { int swarmid; int parent; int generation; int next; /* amp id of next amplicon in swarm */ int graft_cand; /* amp id of potential grafting parent (fastitdious) */ } * ampinfo = 0; /* Information about each swarm (OTU) */ static struct swarminfo_s { int seed; /* amplicon id of the initial seed of this swarm */ int last; /* amplicon id of the last seed in this swarm */ int size; /* total number of amplicons in this swarm */ int singletons; /* number of amplicons with abundance 1 */ int maxgen; /* the generation of the amplicon farthest from the seed */ long mass; /* the sum of abundances of amplicons in this swarm */ long sumlen; /* sum of length of amplicons in swarm */ bool attached; /* this is a small swarm attached to a large (fastidious) */ } * swarminfo = 0; static long swarminfo_alloc = 0; /* Information about potential grafts */ static long graft_candidates = 0; static pthread_mutex_t graft_mutex; #define NO_SWARM (-1) static int current_swarm_tail; static unsigned long hash_tablesize = 0; /* overall statistics */ static int maxgen = 0; static int largest = 0; static long swarmcount_adjusted = 0; /* per swarm statistics */ static unsigned long singletons = 0; static unsigned long abundance_sum = 0; /* = mass */ static int swarmsize = 0; static int swarm_maxgen = 0; static unsigned long swarm_sumlen = 0; static struct thread_info_s { pthread_t pthread; pthread_mutex_t workmutex; pthread_cond_t workcond; int work; unsigned char * varseq; int seed; unsigned long mut_start; unsigned long mut_length; int * hits_data; int hits_alloc; int hits_count; } * ti; static pthread_attr_t attr; #ifdef HASHSTATS unsigned long probes = 0; unsigned long hits = 0; unsigned long success = 0; unsigned long tries = 0; unsigned long bingo = 0; unsigned long collisions = 0; #endif static int hash_shift; static unsigned long hash_mask; static unsigned char * hash_occupied = 0; static unsigned long * hash_values = 0; static int * hash_data = 0; static int * global_hits_data = 0; static int global_hits_alloc = 0; static int global_hits_count = 0; inline unsigned int hash_getindex(unsigned long hash) { #ifdef POWEROFTWO return hash & hash_mask; #else return hash % hash_tablesize; #endif } inline unsigned int hash_getnextindex(unsigned int j) { #ifdef POWEROFTWO return (j+1) & hash_mask; #else return (j+1) % hash_tablesize; #endif } void hash_alloc(unsigned long amplicons) { hash_tablesize = 1; hash_shift = 0; while (amplicons > HASHFILLFACTOR * hash_tablesize) { hash_tablesize <<= 1; hash_shift++; } hash_mask = hash_tablesize - 1; hash_occupied = (unsigned char *) xmalloc((hash_tablesize + 63) / 8); memset(hash_occupied, 0, (hash_tablesize + 63) / 8); hash_values = (unsigned long *) xmalloc(hash_tablesize * sizeof(unsigned long)); hash_data = (int *) xmalloc(hash_tablesize * sizeof(int)); } void hash_free() { free(hash_occupied); free(hash_values); free(hash_data); } inline void hash_set_occupied(unsigned int j) { hash_occupied[j >> 3] |= (1 << (j & 7)); } inline int hash_is_occupied(unsigned int j) { return hash_occupied[j >> 3] & (1 << (j & 7)); } inline void hash_set_value(unsigned int j, unsigned long hash) { hash_values[j] = hash; } inline int hash_compare_value(unsigned int j, unsigned long hash) { return (hash_values[j] == hash); } inline void hash_insert(int amp, unsigned char * key, unsigned long keylen) { unsigned long hash = HASH(key, keylen); unsigned int j = hash_getindex(hash); /* find the first empty bucket */ while (hash_is_occupied(j)) j = hash_getnextindex(j); hash_set_occupied(j); hash_set_value(j, hash); hash_data[j] = amp; } void find_variant_matches(unsigned long thread, unsigned char * seq, unsigned long seqlen, int seed) { unsigned long max_abundance; if (opt_no_otu_breaking) max_abundance = ULONG_MAX; else max_abundance = db_getabundance(seed); /* compute hash and corresponding hash table index */ unsigned long hash = HASH(seq, seqlen); unsigned int j = hash_getindex(hash); /* find matching buckets */ #ifdef HASHSTATS tries++; probes++; #endif while (hash_is_occupied(j)) { #ifdef HASHSTATS hits++; #endif if (hash_compare_value(j, hash)) { #ifdef HASHSTATS success++; #endif /* check if not already swarmed */ int amp = hash_data[j]; struct ampinfo_s * bp = ampinfo + amp; if ((bp->swarmid == NO_SWARM) && (db_getabundance(amp) <= max_abundance)) { unsigned long ampseqlen = db_getsequencelen(amp); unsigned char * ampseq = (unsigned char *) db_getsequence(amp); /* make sure sequences are identical even though hashes are */ if ((ampseqlen == seqlen) && (!memcmp(ampseq, seq, seqlen))) { #ifdef HASHSTATS bingo++; #endif struct thread_info_s * tip = ti + thread; if (tip->hits_count + 1 > tip->hits_alloc) { tip->hits_alloc <<= 1; tip->hits_data = (int*)realloc(tip->hits_data, tip->hits_alloc * sizeof(int)); } tip->hits_data[tip->hits_count++] = amp; } #ifdef HASHSTATS else { collisions++; fprintf(logfile, "Hash collision between "); fprint_id_noabundance(logfile, seed); fprintf(logfile, " and "); fprint_id_noabundance(logfile, amp); fprintf(logfile, ".\n"); } #endif } } j = hash_getnextindex(j); #ifdef HASHSTATS probes++; #endif } } void generate_variants(unsigned long thread, int seed, unsigned long start, unsigned long len) { /* Generate all possible variants involving mutations from position start and extending len nucleotides. Insertions in front of those positions are included, but not those after. Positions are zero-based. The range may extend beyond the length of the sequence indicating that inserts at the end of the sequence should be generated. The last thread will handle insertions at the end of the sequence, as well as identical sequences (no mutations). */ unsigned char * varseq = ti[thread].varseq; unsigned char * seq = (unsigned char*) db_getsequence(seed); unsigned long seqlen = db_getsequencelen(seed); unsigned long end = MIN(seqlen,start+len); ti[thread].hits_count = 0; /* make an exact copy */ memcpy(varseq, seq, seqlen); #if 1 /* identical non-variant */ if (thread == threads - 1) find_variant_matches(thread, varseq, seqlen, seed); #endif /* substitutions */ for(unsigned int i=start; iworkmutex); /* loop until signalled to quit */ while (tip->work >= 0) { /* wait for work available */ if (tip->work == 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); if (tip->work > 0) { generate_variants(t, tip->seed, tip->mut_start, tip->mut_length); tip->work = 0; pthread_cond_signal(&tip->workcond); } } pthread_mutex_unlock(&tip->workmutex); return 0; } void threads_init() { pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* allocate memory for thread info, incl the variant sequences */ unsigned long longestamplicon = db_getlongestsequence(); ti = (struct thread_info_s *) xmalloc(threads * sizeof(struct thread_info_s)); /* init and create worker threads */ for(unsigned long t=0; tvarseq = (unsigned char*) xmalloc(longestamplicon+1); tip->hits_alloc = 7 * longestamplicon + 4; tip->hits_data = (int*) xmalloc(tip->hits_alloc * sizeof(int)); tip->work = 0; pthread_mutex_init(&tip->workmutex, NULL); pthread_cond_init(&tip->workcond, NULL); if (pthread_create(&tip->pthread, &attr, worker, (void*)(long)t)) fatal("Cannot create thread"); } } void threads_done() { /* finish and clean up worker threads */ for(unsigned long t=0; tworkmutex); tip->work = -1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); /* wait for worker to quit */ if (pthread_join(tip->pthread, NULL)) fatal("Cannot join thread"); pthread_cond_destroy(&tip->workcond); pthread_mutex_destroy(&tip->workmutex); free(tip->varseq); free(tip->hits_data); } free(ti); pthread_attr_destroy(&attr); } void swarm_breaker_info(int amp) { /* output info for swarm_breaker script */ if (opt_internal_structure) { long seed = ampinfo[amp].parent; fprint_id_noabundance(internal_structure_file, seed); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, amp); fprintf(internal_structure_file, "\t%d", 1); fprintf(internal_structure_file, "\t%d\t%d", ampinfo[seed].swarmid + 1, ampinfo[amp].generation); fprintf(internal_structure_file, "\n"); } } void add_amp_to_swarm(int amp) { /* add to swarm */ ampinfo[current_swarm_tail].next = amp; current_swarm_tail = amp; swarm_breaker_info(amp); } void process_seed(int seed, int subseed) { unsigned long seqlen = db_getsequencelen(subseed); unsigned long thr = threads; if (thr > seqlen + 1) thr = seqlen+1; /* prepare work for the threads */ unsigned long start = 0; for(unsigned long t=0; tseed = subseed; tip->mut_start = start; tip->mut_length = length; start += length; pthread_mutex_lock(&tip->workmutex); tip->work = 1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); } /* wait for theads to finish their work */ for(unsigned int t=0; tworkmutex); while (tip->work > 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); pthread_mutex_unlock(&tip->workmutex); } /* join hits from the threads */ for(unsigned int t=0; t global_hits_alloc) { global_hits_alloc <<= 1; global_hits_data = (int*)xrealloc(global_hits_data, global_hits_alloc * sizeof(int)); } for(int i=0; i < ti[t].hits_count; i++) { long amp = ti[t].hits_data[i]; /* add to list for this generation */ global_hits_data[global_hits_count++] = amp; /* update info */ ampinfo[amp].swarmid = ampinfo[subseed].swarmid; ampinfo[amp].generation = ampinfo[subseed].generation + 1; ampinfo[amp].parent = subseed; } } } void update_stats(int amp) { /* update swarm stats */ struct ampinfo_s * bp = ampinfo + amp; swarmsize++; if (bp->generation > swarm_maxgen) swarm_maxgen = bp->generation; unsigned long abundance = db_getabundance(amp); abundance_sum += abundance; if (abundance == 1) singletons++; swarm_sumlen += db_getsequencelen(amp); } void attach(int seed, int amp) { /* graft light swarm (amp) on heavy swarm (seed) */ #if 0 fprintf(logfile, "\nGrafting light swarm with amplicon %d on " "heavy swarm with amplicon %d (swarm ids: %d %d)\n", amp, seed, ampinfo[amp].swarmid, ampinfo[seed].swarmid); #endif swarminfo_s * hp = swarminfo + ampinfo[seed].swarmid; swarminfo_s * lp = swarminfo + ampinfo[amp].swarmid; // attach the seed of the light swarm to the tail of the heavy swarm ampinfo[hp->last].next = lp->seed; hp->last = lp->last; // Update swarm info hp->size += lp->size; hp->singletons += lp->singletons; hp->mass += lp->mass; hp->sumlen += lp->sumlen; /* maxgen is untouched */ /* flag attachment to avoid doing it again */ lp->attached = true; // Update overall stats if (hp->size > largest) largest = hp->size; swarmcount_adjusted--; } void add_graft_candidate(int seed, int amp) { pthread_mutex_lock(&graft_mutex); graft_candidates++; if ((ampinfo[amp].graft_cand == NO_SWARM)||(ampinfo[amp].graft_cand > seed)) ampinfo[amp].graft_cand = seed; pthread_mutex_unlock(&graft_mutex); } struct graft_cand { int parent; int child; } * graft_array; int compare_grafts(const void * a, const void * b) { struct graft_cand * x = (struct graft_cand *) a; struct graft_cand * y = (struct graft_cand *) b; if (x->parent < y->parent) return -1; else if (x->parent > y->parent) return +1; else if (x->child < y->child) return -1; else if (x->child > y->child) return +1; else return 0; } int attach_candidates(int amplicons) { /* count pairs */ int pair_count = 0; for(int i=0; i < amplicons; i++) if (ampinfo[i].graft_cand != NO_SWARM) pair_count++; int grafts = 0; progress_init("Grafting light swarms on heavy swarms", pair_count); /* allocate memory */ graft_array = (struct graft_cand *) xmalloc(pair_count * sizeof(struct graft_cand)); /* fill in */ int j = 0; for(int i=0; i < amplicons; i++) if (ampinfo[i].graft_cand != NO_SWARM) { graft_array[j].parent = ampinfo[i].graft_cand; graft_array[j].child = i; j++; } /* sort */ qsort(graft_array, pair_count, sizeof(struct graft_cand), compare_grafts); /* attach in order */ for(int i=0; i < pair_count; i++) { int parent = graft_array[i].parent; int child = graft_array[i].child; if (!swarminfo[ampinfo[child].swarmid].attached) { /* attach child to parent */ attach(parent, child); grafts++; } progress_update(i+1); } progress_done(); free(graft_array); return grafts; } bool hash_check_attach(char * seq, unsigned long seqlen, int seed) { /* compute hash and corresponding hash table index */ unsigned long hash = HASH((unsigned char*)seq, seqlen); unsigned int j = hash_getindex(hash); /* find matching buckets */ while (hash_is_occupied(j)) { if (hash_compare_value(j, hash)) { /* check that mass is below threshold */ int amp = hash_data[j]; struct swarminfo_s * smallp = swarminfo + ampinfo[amp].swarmid; if (smallp->mass < opt_boundary) { unsigned long ampseqlen = db_getsequencelen(amp); unsigned char * ampseq = (unsigned char *) db_getsequence(amp); /* make absolutely sure sequences are identical */ if ((ampseqlen == seqlen) && (!memcmp(ampseq, seq, seqlen))) { add_graft_candidate(seed, amp); return 1; } } } j = hash_getnextindex(j); } return 0; } long expected_variant_count(char * seq, int len) { int c = 0; for(int i=1; iset(varseq, seqlen); variants++; } varseq[i] = seq[i]; } /* deletions */ if (seqlen > 1) memcpy(varseq, seq+1, seqlen-1); for(unsigned int i=0; iset(varseq, seqlen-1); variants++; } varseq[i] = seq[i]; } /* insertions */ memcpy(varseq+1, seq, seqlen); for(unsigned int i=0; iset(varseq, seqlen+1); variants++; } } if (i 1) memcpy(varseq, seq+1, seqlen-1); for(unsigned int i=0; iget(varseq, seqlen)) matches += fastidious_check_large_var_2(varseq, seqlen, buffer2, seed); } varseq[i] = seq[i]; } /* deletions */ if (seqlen > 1) memcpy(varseq, seq+1, seqlen-1); for(unsigned int i=0; iget(varseq, seqlen-1)) matches += fastidious_check_large_var_2(varseq, seqlen-1, buffer2, seed); } varseq[i] = seq[i]; } /* insertions */ memcpy(varseq+1, seq, seqlen); for(unsigned int i=0; iget(varseq, seqlen+1)) matches += fastidious_check_large_var_2(varseq, seqlen+1, buffer2, seed); } } if (i *y) return +1; else return 0; } static pthread_mutex_t light_mutex; static long light_variants; static long light_progress; static long light_amplicon_count; static int light_amplicon; BloomFilter * bloomp; void mark_light_thread(long t) { char * buffer1 = (char*) xmalloc(db_getlongestsequence() + 2); pthread_mutex_lock(&light_mutex); while (light_progress < light_amplicon_count) { int a = light_amplicon--; if (swarminfo[ampinfo[a].swarmid].mass < opt_boundary) { progress_update(++light_progress); pthread_mutex_unlock(&light_mutex); long v = fastidious_mark_small_var(bloomp, buffer1, a); pthread_mutex_lock(&light_mutex); light_variants += v; } } pthread_mutex_unlock(&light_mutex); free(buffer1); } static pthread_mutex_t heavy_mutex; static long heavy_variants; static long heavy_progress; static long heavy_amplicon_count; static int heavy_amplicon; static long amplicons; void check_heavy_thread(long t) { char * buffer1 = (char*) xmalloc(db_getlongestsequence() + 2); char * buffer2 = (char*) xmalloc(db_getlongestsequence() + 3); pthread_mutex_lock(&heavy_mutex); while ((heavy_amplicon < amplicons) && (heavy_progress < heavy_amplicon_count)) { int a = heavy_amplicon++; if (swarminfo[ampinfo[a].swarmid].mass >= opt_boundary) { progress_update(++heavy_progress); pthread_mutex_unlock(&heavy_mutex); long m, v; fastidious_check_large_var(bloomp, buffer1, buffer2, a, &m, &v); pthread_mutex_lock(&heavy_mutex); heavy_variants += v; } } pthread_mutex_unlock(&heavy_mutex); free(buffer2); free(buffer1); } void algo_d1_run() { unsigned long longestamplicon = db_getlongestsequence(); amplicons = db_getsequencecount(); threads_init(); ampinfo = (struct ampinfo_s *) xmalloc(amplicons * sizeof(struct ampinfo_s)); global_hits_alloc = longestamplicon * 7 + 4; global_hits_data = (int *) xmalloc(global_hits_alloc * sizeof(int)); /* compute hash for all amplicons and store them in a hash table */ hash_alloc(amplicons); progress_init("Hashing sequences:", amplicons); for(unsigned int i=0; igeneration = 0; bp->swarmid = NO_SWARM; bp->next = NO_SWARM; bp->graft_cand = NO_SWARM; hash_insert(i, seq, seqlen); progress_update(i); } progress_done(); unsigned char * dir = 0; unsigned long * hearray = 0; if (uclustfile) { dir = (unsigned char *) xmalloc(longestamplicon*longestamplicon); hearray = (unsigned long *) xmalloc(2 * longestamplicon * sizeof(unsigned long)); } /* for each non-swarmed amplicon look for subseeds ... */ long swarmid = 0; progress_init("Clustering: ", amplicons); for(unsigned int seed = 0; seed < amplicons; seed++) { struct ampinfo_s * ap = ampinfo + seed; if (ap->swarmid == NO_SWARM) { /* start a new swarm with a new initial seed */ ap->swarmid = swarmid; ap->generation = 0; ap->parent = NO_SWARM; ap->next = NO_SWARM; /* link up this initial seed in the list of swarms */ current_swarm_tail = seed; /* initialize swarm stats */ swarmsize = 0; swarm_maxgen = 0; abundance_sum = 0; singletons = 0; swarm_sumlen = 0; update_stats(seed); /* init list */ global_hits_count = 0; /* find the first generation matches */ process_seed(seed, seed); /* sort hits */ qsort(global_hits_data, global_hits_count, sizeof(int), compare_amp); /* add subseeds on list to current swarm */ for(int i = 0; i < global_hits_count; i++) add_amp_to_swarm(global_hits_data[i]); /* find later generation matches */ int subseed = ap->next; while(subseed != NO_SWARM) { /* process all subseeds of this generation */ global_hits_count = 0; while(subseed != NO_SWARM) { process_seed(seed, subseed); update_stats(subseed); subseed = ampinfo[subseed].next; } /* sort all of this generation */ qsort(global_hits_data, global_hits_count, sizeof(int), compare_amp); /* add them to the swarm */ for(int i = 0; i < global_hits_count; i++) add_amp_to_swarm(global_hits_data[i]); /* start with most abundant amplicon of next generation */ if (global_hits_count) subseed = global_hits_data[0]; else subseed = NO_SWARM; } if (swarmid >= swarminfo_alloc) { /* allocate memory for more swarms... */ swarminfo_alloc += 1000; swarminfo = (struct swarminfo_s *) xrealloc (swarminfo, swarminfo_alloc * sizeof(swarminfo_s)); } struct swarminfo_s * sp = swarminfo + swarmid; sp->seed = seed; sp->size = swarmsize; sp->mass = abundance_sum; sp->sumlen = swarm_sumlen; sp->singletons = singletons; sp->maxgen = swarm_maxgen; sp->last = current_swarm_tail; sp->attached = false; /* update overall stats */ if (swarmsize > largest) largest = swarmsize; if (swarm_maxgen > maxgen) maxgen = swarm_maxgen; swarmid++; } progress_update(seed+1); } progress_done(); long swarmcount = swarmid; swarmcount_adjusted = swarmcount; /* fastidious */ if (opt_fastidious) { fprintf(logfile, "\n"); fprintf(logfile, "Results before fastidious processing:\n"); fprintf(logfile, "Number of swarms: %ld\n", swarmcount); fprintf(logfile, "Largest swarm: %d\n", largest); fprintf(logfile, "\n"); long small_otus = 0; long amplicons_in_small_otus = 0; long nucleotides_in_small_otus = 0; progress_init("Counting amplicons in heavy and light swarms", swarmcount); for(long i = 0; i < swarmcount; i++) { struct swarminfo_s * sp = swarminfo + i; if (sp->mass < opt_boundary) { amplicons_in_small_otus += sp->size; nucleotides_in_small_otus += sp->sumlen; small_otus++; } progress_update(i+1); } progress_done(); long amplicons_in_large_otus = amplicons - amplicons_in_small_otus; long large_otus = swarmcount - small_otus; fprintf(logfile, "Heavy swarms: %ld, with %ld amplicons\n", large_otus, amplicons_in_large_otus); fprintf(logfile, "Light swarms: %ld, with %ld amplicons\n", small_otus, amplicons_in_small_otus); fprintf(logfile, "Total length of amplicons in light swarms: %ld\n", nucleotides_in_small_otus); if ((small_otus == 0) || (large_otus == 0)) { fprintf(logfile, "Only light or heavy swarms found - " "no need for further analysis.\n"); } else { /* m: total size of Bloom filter in bits */ /* k: number of hash functions */ /* n: number of entries in the bloom filter */ /* here: k=12 and m/n=18, that is 18 bits/entry */ long bits = opt_bloom_bits; /* 18 */ long k = int(bits * 0.693); /* 12 */ long m = bits * 7 * nucleotides_in_small_otus; long memtotal = arch_get_memtotal(); long memused = arch_get_memused(); if (opt_ceiling) { long memrest = 1024 * 1024 * opt_ceiling - memused; long new_bits = 8 * memrest / (7 * nucleotides_in_small_otus); if (new_bits < bits) { if (new_bits < 2) fatal("Insufficient memory remaining for Bloom filter"); fprintf(logfile, "Reducing memory used for Bloom filter due to --ceiling option.\n"); bits = new_bits; k = int(bits * 0.693); m = bits * 7 * nucleotides_in_small_otus; } } if (memused + m/8 > memtotal) { fprintf(logfile, "WARNING: Memory usage will probably exceed total amount of memory available.\n"); fprintf(logfile, "Try to reduce memory footprint using the --bloom-bits or --ceiling options.\n"); } fprintf(logfile, "Bloom filter: bits=%ld, m=%ld, k=%ld, size=%.1lfMB\n", bits, m, k, 1.0 * m / (8*1024*1024)); bloomp = new BloomFilter(m, k); char * buffer1 = (char*) xmalloc(db_getlongestsequence() + 2); char * buffer2 = (char*) xmalloc(db_getlongestsequence() + 3); progress_init("Adding light swarm amplicons to Bloom filter", amplicons_in_small_otus); /* process amplicons in order from least to most abundant */ /* but stop when all amplicons in small otus are processed */ light_variants = 0; #if 1 pthread_mutex_init(&light_mutex, NULL); light_progress = 0; light_amplicon_count = amplicons_in_small_otus; light_amplicon = amplicons - 1; ThreadRunner * tr = new ThreadRunner(threads, mark_light_thread); tr->run(); delete tr; pthread_mutex_destroy(&light_mutex); #else int a = amplicons - 1; long x = 0; while (x < amplicons_in_small_otus) { if (swarminfo[ampinfo[a].swarmid].mass < opt_boundary) { light_variants += fastidious_mark_small_var(bloomp, buffer1, a); x++; progress_update(x); } a--; } #endif progress_done(); fprintf(logfile, "Generated %ld variants from light swarms\n", light_variants); progress_init("Checking heavy swarm amplicons against Bloom filter", amplicons_in_large_otus); /* process amplicons in order from most to least abundant */ /* but stop when all amplicons in large otus are processed */ pthread_mutex_init(&graft_mutex, NULL); heavy_variants = 0; #if 1 pthread_mutex_init(&heavy_mutex, NULL); heavy_progress = 0; heavy_amplicon_count = amplicons_in_large_otus; heavy_amplicon = 0; ThreadRunner * heavy_tr = new ThreadRunner(threads, check_heavy_thread); heavy_tr->run(); delete heavy_tr; pthread_mutex_destroy(&heavy_mutex); #else long i = 0; for(int a = 0; (a < amplicons) && (i < amplicons_in_large_otus); a++) { int swarmid = ampinfo[a].swarmid; int mass = swarminfo[swarmid].mass; if (mass >= opt_boundary) { long m, v; fastidious_check_large_var(bloomp, buffer1, buffer2, a, &m, &v); heavy_variants += v; progress_update(++i); } } #endif progress_done(); free(buffer1); free(buffer2); delete bloomp; pthread_mutex_destroy(&graft_mutex); fprintf(logfile, "Heavy variants: %ld\n", heavy_variants); fprintf(logfile, "Got %ld graft candidates\n", graft_candidates); int grafts = attach_candidates(amplicons); fprintf(logfile, "Made %d grafts\n", grafts); fprintf(logfile, "\n"); } } /* dump swarms */ progress_init("Writing swarms: ", swarmcount); if (mothur) fprintf(outfile, "swarm_%ld\t%ld", resolution, swarmcount_adjusted); for(int i = 0; i < swarmcount; i++) { if (!swarminfo[i].attached) { int seed = swarminfo[i].seed; for (int a = seed; a >= 0; a = ampinfo[a].next) { if (mothur) { if (a == seed) fputc('\t', outfile); else fputc(',', outfile); } else { if (a != seed) fputc(SEPCHAR, outfile); } fprint_id(outfile, a); } if (!mothur) fputc('\n', outfile); } progress_update(i+1); } if (mothur) fputc('\n', outfile); progress_done(); /* dump seeds in fasta format with sum of abundances */ if (opt_seeds) { progress_init("Writing seeds: ", swarmcount_adjusted); for(int i=0; i < swarmcount; i++) { if (!swarminfo[i].attached) { int seed = swarminfo[i].seed; fprintf(fp_seeds, ">"); fprint_id_with_new_abundance(fp_seeds, seed, swarminfo[i].mass); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, seed, 0); } progress_update(i+1); } progress_done(); } /* output swarm in uclust format */ if (uclustfile) { progress_init("Writing UCLUST: ", swarmcount); for(unsigned int swarmid = 0; swarmid < swarmcount ; swarmid++) { if (!swarminfo[swarmid].attached) { int seed = swarminfo[swarmid].seed; struct ampinfo_s * bp = ampinfo + seed; fprintf(uclustfile, "C\t%u\t%d\t*\t*\t*\t*\t*\t", swarmid, swarminfo[swarmid].size); fprint_id(uclustfile, seed); fprintf(uclustfile, "\t*\n"); fprintf(uclustfile, "S\t%u\t%lu\t*\t*\t*\t*\t*\t", swarmid, db_getsequencelen(seed)); fprint_id(uclustfile, seed); fprintf(uclustfile, "\t*\n"); for (int a = bp->next; a >= 0; a = ampinfo[a].next) { char * dseq = db_getsequence(a); char * dend = dseq + db_getsequencelen(a); char * qseq = db_getsequence(seed); char * qend = qseq + db_getsequencelen(seed); unsigned long nwscore = 0; unsigned long nwdiff = 0; char * nwalignment = NULL; unsigned long nwalignmentlength = 0; nw(dseq, dend, qseq, qend, score_matrix_63, gapopen, gapextend, & nwscore, & nwdiff, & nwalignmentlength, & nwalignment, dir, hearray, 0, 0); double percentid = 100.0 * (nwalignmentlength - nwdiff) / nwalignmentlength; fprintf(uclustfile, "H\t%d\t%lu\t%.1f\t+\t0\t0\t%s\t", ampinfo[seed].swarmid, db_getsequencelen(a), percentid, nwdiff > 0 ? nwalignment : "="); fprint_id(uclustfile, a); fprintf(uclustfile, "\t"); fprint_id(uclustfile, seed); fprintf(uclustfile, "\n"); if (nwalignment) free(nwalignment); } } progress_update(swarmid); } progress_done(); } /* output statistics to file */ if (statsfile) { progress_init("Writing stats: ", swarmcount); for(long i = 0; i < swarmcount; i++) { swarminfo_s * sp = swarminfo + i; if (!sp->attached) { fprintf(statsfile, "%d\t%ld\t", sp->size, sp->mass); fprint_id_noabundance(statsfile, sp->seed); fprintf(statsfile, "\t%lu\t%d\t%d\t%d\n", db_getabundance(sp->seed), sp->singletons, sp->maxgen, sp->maxgen); } progress_update(i); } progress_done(); } fprintf(logfile, "\n"); fprintf(logfile, "Number of swarms: %ld\n", swarmcount_adjusted); fprintf(logfile, "Largest swarm: %d\n", largest); fprintf(logfile, "Max generations: %d\n", maxgen); threads_done(); hash_free(); if(swarminfo) free(swarminfo); free(ampinfo); free(global_hits_data); if (uclustfile) { free(dir); free(hearray); } #ifdef HASHSTATS fprintf(logfile, "Tries: %lu\n", tries); fprintf(logfile, "Probes: %lu\n", probes); fprintf(logfile, "Hits: %lu\n", hits); fprintf(logfile, "Success: %lu\n", success); fprintf(logfile, "Bingo: %lu\n", bingo); fprintf(logfile, "Collisions: %lu\n", collisions); #endif } swarm-2.1.6/src/arch.cc000066400000000000000000000035211263351160000146620ustar00rootroot00000000000000/* Copyright (C) 2014-2015 Torbjorn Rognes This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" unsigned long arch_get_memused() { struct rusage r_usage; getrusage(RUSAGE_SELF, & r_usage); #if defined __APPLE__ /* Mac: ru_maxrss gives the size in bytes */ return r_usage.ru_maxrss; #else /* Linux: ru_maxrss gives the size in kilobytes */ return r_usage.ru_maxrss * 1024; #endif } unsigned long arch_get_memtotal() { #if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) long phys_pages = sysconf(_SC_PHYS_PAGES); long pagesize = sysconf(_SC_PAGESIZE); if ((phys_pages == -1) || (pagesize == -1)) fatal("Cannot determine amount of memory"); return pagesize * phys_pages; #elif defined(__APPLE__) int mib [] = { CTL_HW, HW_MEMSIZE }; int64_t ram = 0; size_t length = sizeof(ram); if(sysctl(mib, 2, &ram, &length, NULL, 0) == -1) fatal("Cannot determine amount of memory"); return ram; #else struct sysinfo si; if (sysinfo(&si)) fatal("Cannot determine amount of memory"); return si.totalram * si.mem_unit; #endif } swarm-2.1.6/src/bitmap.h000066400000000000000000000033551263351160000150700ustar00rootroot00000000000000/* Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ class Bitmap { private: size_t size; /* size in bits */ unsigned char * data; /* the actual bitmap */ public: Bitmap(size_t _size) { size = _size; data = (unsigned char *) xmalloc((size+7)/8); } ~Bitmap() { if (data) free(data); } bool get(size_t x) { return (data[x >> 3] >> (x & 7)) & 1; } void reset_all() { memset(data, 0, (size+7)/8); } void set_all() { memset(data, 255, (size+7)/8); } void reset(size_t x) { // data[x >> 3] &= ~ (1 << (x & 7)); __sync_fetch_and_and(data + (x >> 3), ~(1 << (x & 7))); } void set(size_t x) { // data[x >> 3] |= 1 << (x & 7); __sync_fetch_and_or(data + (x >> 3), 1 << (x & 7)); } void flip(size_t x) { // data[x >> 3] ^= 1 << (x & 7); __sync_fetch_and_xor(data + (x >> 3), 1 << (x & 7)); } }; swarm-2.1.6/src/bloom.h000066400000000000000000000033231263351160000147170ustar00rootroot00000000000000/* Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ class BloomFilter { private: Bitmap bitmap; size_t m; /* total number of bits in bitmap */ int k; /* number of hash functions */ public: BloomFilter(unsigned long _m, int _k) : bitmap(_m) { bitmap.reset_all(); m = _m; k = _k; } bool get(const char * buf, size_t len) { uint128 hash = CityHash128(buf, len); uint64 h0 = Uint128Low64(hash); uint64 h1 = Uint128High64(hash); for(int i=0; i #include #include // for memcpy and memset using namespace std; static uint64 UNALIGNED_LOAD64(const char *p) { uint64 result; memcpy(&result, p, sizeof(result)); return result; } static uint32 UNALIGNED_LOAD32(const char *p) { uint32 result; memcpy(&result, p, sizeof(result)); return result; } #ifdef _MSC_VER #include #define bswap_32(x) _byteswap_ulong(x) #define bswap_64(x) _byteswap_uint64(x) #elif defined(__APPLE__) // Mac OS X / Darwin features #include #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) #elif defined(__NetBSD__) #include #include #if defined(__BSWAP_RENAME) && !defined(__bswap_32) #define bswap_32(x) bswap32(x) #define bswap_64(x) bswap64(x) #endif #else #include #endif #ifdef WORDS_BIGENDIAN #define uint32_in_expected_order(x) (bswap_32(x)) #define uint64_in_expected_order(x) (bswap_64(x)) #else #define uint32_in_expected_order(x) (x) #define uint64_in_expected_order(x) (x) #endif #if !defined(LIKELY) #if HAVE_BUILTIN_EXPECT #define LIKELY(x) (__builtin_expect(!!(x), 1)) #else #define LIKELY(x) (x) #endif #endif static uint64 Fetch64(const char *p) { return uint64_in_expected_order(UNALIGNED_LOAD64(p)); } static uint32 Fetch32(const char *p) { return uint32_in_expected_order(UNALIGNED_LOAD32(p)); } // Some primes between 2^63 and 2^64 for various uses. static const uint64 k0 = 0xc3a5c85c97cb3127ULL; static const uint64 k1 = 0xb492b66fbe98f273ULL; static const uint64 k2 = 0x9ae16a3b2f90404fULL; // Magic numbers for 32-bit hashing. Copied from Murmur3. static const uint32_t c1 = 0xcc9e2d51; static const uint32_t c2 = 0x1b873593; // A 32-bit to 32-bit integer hash copied from Murmur3. static uint32 fmix(uint32 h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } static uint32 Rotate32(uint32 val, int shift) { // Avoid shifting by 32: doing so yields an undefined result. return shift == 0 ? val : ((val >> shift) | (val << (32 - shift))); } #undef PERMUTE3 #define PERMUTE3(a, b, c) do { std::swap(a, b); std::swap(a, c); } while (0) static uint32 Mur(uint32 a, uint32 h) { // Helper from Murmur3 for combining two 32-bit values. a *= c1; a = Rotate32(a, 17); a *= c2; h ^= a; h = Rotate32(h, 19); return h * 5 + 0xe6546b64; } static uint32 Hash32Len13to24(const char *s, size_t len) { uint32 a = Fetch32(s - 4 + (len >> 1)); uint32 b = Fetch32(s + 4); uint32 c = Fetch32(s + len - 8); uint32 d = Fetch32(s + (len >> 1)); uint32 e = Fetch32(s); uint32 f = Fetch32(s + len - 4); uint32 h = len; return fmix(Mur(f, Mur(e, Mur(d, Mur(c, Mur(b, Mur(a, h))))))); } static uint32 Hash32Len0to4(const char *s, size_t len) { uint32 b = 0; uint32 c = 9; for (uint32 i = 0; i < len; i++) { signed char v = s[i]; b = b * c1 + v; c ^= b; } return fmix(Mur(b, Mur(len, c))); } static uint32 Hash32Len5to12(const char *s, size_t len) { uint32 a = len, b = len * 5, c = 9, d = b; a += Fetch32(s); b += Fetch32(s + len - 4); c += Fetch32(s + ((len >> 1) & 4)); return fmix(Mur(c, Mur(b, Mur(a, d)))); } uint32 CityHash32(const char *s, size_t len) { if (len <= 24) { return len <= 12 ? (len <= 4 ? Hash32Len0to4(s, len) : Hash32Len5to12(s, len)) : Hash32Len13to24(s, len); } // len > 24 uint32 h = len, g = c1 * len, f = g; uint32 a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2; uint32 a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2; uint32 a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2; uint32 a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2; uint32 a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2; h ^= a0; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; h ^= a2; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; g ^= a1; g = Rotate32(g, 19); g = g * 5 + 0xe6546b64; g ^= a3; g = Rotate32(g, 19); g = g * 5 + 0xe6546b64; f += a4; f = Rotate32(f, 19); f = f * 5 + 0xe6546b64; size_t iters = (len - 1) / 20; do { uint32 a0 = Rotate32(Fetch32(s) * c1, 17) * c2; uint32 a1 = Fetch32(s + 4); uint32 a2 = Rotate32(Fetch32(s + 8) * c1, 17) * c2; uint32 a3 = Rotate32(Fetch32(s + 12) * c1, 17) * c2; uint32 a4 = Fetch32(s + 16); h ^= a0; h = Rotate32(h, 18); h = h * 5 + 0xe6546b64; f += a1; f = Rotate32(f, 19); f = f * c1; g += a2; g = Rotate32(g, 18); g = g * 5 + 0xe6546b64; h ^= a3 + a1; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; g ^= a4; g = bswap_32(g) * 5; h += a4 * 5; h = bswap_32(h); f += a0; PERMUTE3(f, h, g); s += 20; } while (--iters != 0); g = Rotate32(g, 11) * c1; g = Rotate32(g, 17) * c1; f = Rotate32(f, 11) * c1; f = Rotate32(f, 17) * c1; h = Rotate32(h + g, 19); h = h * 5 + 0xe6546b64; h = Rotate32(h, 17) * c1; h = Rotate32(h + f, 19); h = h * 5 + 0xe6546b64; h = Rotate32(h, 17) * c1; return h; } // Bitwise right rotate. Normally this will compile to a single // instruction, especially if the shift is a manifest constant. static uint64 Rotate(uint64 val, int shift) { // Avoid shifting by 64: doing so yields an undefined result. return shift == 0 ? val : ((val >> shift) | (val << (64 - shift))); } static uint64 ShiftMix(uint64 val) { return val ^ (val >> 47); } static uint64 HashLen16(uint64 u, uint64 v) { return Hash128to64(uint128(u, v)); } static uint64 HashLen16(uint64 u, uint64 v, uint64 mul) { // Murmur-inspired hashing. uint64 a = (u ^ v) * mul; a ^= (a >> 47); uint64 b = (v ^ a) * mul; b ^= (b >> 47); b *= mul; return b; } static uint64 HashLen0to16(const char *s, size_t len) { if (len >= 8) { uint64 mul = k2 + len * 2; uint64 a = Fetch64(s) + k2; uint64 b = Fetch64(s + len - 8); uint64 c = Rotate(b, 37) * mul + a; uint64 d = (Rotate(a, 25) + b) * mul; return HashLen16(c, d, mul); } if (len >= 4) { uint64 mul = k2 + len * 2; uint64 a = Fetch32(s); return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); } if (len > 0) { uint8 a = s[0]; uint8 b = s[len >> 1]; uint8 c = s[len - 1]; uint32 y = static_cast(a) + (static_cast(b) << 8); uint32 z = len + (static_cast(c) << 2); return ShiftMix(y * k2 ^ z * k0) * k2; } return k2; } // This probably works well for 16-byte strings as well, but it may be overkill // in that case. static uint64 HashLen17to32(const char *s, size_t len) { uint64 mul = k2 + len * 2; uint64 a = Fetch64(s) * k1; uint64 b = Fetch64(s + 8); uint64 c = Fetch64(s + len - 8) * mul; uint64 d = Fetch64(s + len - 16) * k2; return HashLen16(Rotate(a + b, 43) + Rotate(c, 30) + d, a + Rotate(b + k2, 18) + c, mul); } // Return a 16-byte hash for 48 bytes. Quick and dirty. // Callers do best to use "random-looking" values for a and b. static pair WeakHashLen32WithSeeds( uint64 w, uint64 x, uint64 y, uint64 z, uint64 a, uint64 b) { a += w; b = Rotate(b + a + z, 21); uint64 c = a; a += x; a += y; b += Rotate(a, 44); return make_pair(a + z, b + c); } // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. static pair WeakHashLen32WithSeeds( const char* s, uint64 a, uint64 b) { return WeakHashLen32WithSeeds(Fetch64(s), Fetch64(s + 8), Fetch64(s + 16), Fetch64(s + 24), a, b); } // Return an 8-byte hash for 33 to 64 bytes. static uint64 HashLen33to64(const char *s, size_t len) { uint64 mul = k2 + len * 2; uint64 a = Fetch64(s) * k2; uint64 b = Fetch64(s + 8); uint64 c = Fetch64(s + len - 24); uint64 d = Fetch64(s + len - 32); uint64 e = Fetch64(s + 16) * k2; uint64 f = Fetch64(s + 24) * 9; uint64 g = Fetch64(s + len - 8); uint64 h = Fetch64(s + len - 16) * mul; uint64 u = Rotate(a + g, 43) + (Rotate(b, 30) + c) * 9; uint64 v = ((a + g) ^ d) + f + 1; uint64 w = bswap_64((u + v) * mul) + h; uint64 x = Rotate(e + f, 42) + c; uint64 y = (bswap_64((v + w) * mul) + g) * mul; uint64 z = e + f + c; a = bswap_64((x + z) * mul + y) + b; b = ShiftMix((z + a) * mul + d + h) * mul; return b + x; } uint64 CityHash64(const char *s, size_t len) { if (len <= 32) { if (len <= 16) { return HashLen0to16(s, len); } else { return HashLen17to32(s, len); } } else if (len <= 64) { return HashLen33to64(s, len); } // For strings over 64 bytes we hash the end first, and then as we // loop we keep 56 bytes of state: v, w, x, y, and z. uint64 x = Fetch64(s + len - 40); uint64 y = Fetch64(s + len - 16) + Fetch64(s + len - 56); uint64 z = HashLen16(Fetch64(s + len - 48) + len, Fetch64(s + len - 24)); pair v = WeakHashLen32WithSeeds(s + len - 64, len, z); pair w = WeakHashLen32WithSeeds(s + len - 32, y + k1, x); x = x * k1 + Fetch64(s); // Decrease len to the nearest multiple of 64, and operate on 64-byte chunks. len = (len - 1) & ~static_cast(63); do { x = Rotate(x + y + v.first + Fetch64(s + 8), 37) * k1; y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch64(s + 40); z = Rotate(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16)); std::swap(z, x); s += 64; len -= 64; } while (len != 0); return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z, HashLen16(v.second, w.second) + x); } uint64 CityHash64WithSeed(const char *s, size_t len, uint64 seed) { return CityHash64WithSeeds(s, len, k2, seed); } uint64 CityHash64WithSeeds(const char *s, size_t len, uint64 seed0, uint64 seed1) { return HashLen16(CityHash64(s, len) - seed0, seed1); } // A subroutine for CityHash128(). Returns a decent 128-bit hash for strings // of any length representable in signed long. Based on City and Murmur. static uint128 CityMurmur(const char *s, size_t len, uint128 seed) { uint64 a = Uint128Low64(seed); uint64 b = Uint128High64(seed); uint64 c = 0; uint64 d = 0; signed long l = len - 16; if (l <= 0) { // len <= 16 a = ShiftMix(a * k1) * k1; c = b * k1 + HashLen0to16(s, len); d = ShiftMix(a + (len >= 8 ? Fetch64(s) : c)); } else { // len > 16 c = HashLen16(Fetch64(s + len - 8) + k1, a); d = HashLen16(b + len, c + Fetch64(s + len - 16)); a += d; do { a ^= ShiftMix(Fetch64(s) * k1) * k1; a *= k1; b ^= a; c ^= ShiftMix(Fetch64(s + 8) * k1) * k1; c *= k1; d ^= c; s += 16; l -= 16; } while (l > 0); } a = HashLen16(a, c); b = HashLen16(d, b); return uint128(a ^ b, HashLen16(b, a)); } uint128 CityHash128WithSeed(const char *s, size_t len, uint128 seed) { if (len < 128) { return CityMurmur(s, len, seed); } // We expect len >= 128 to be the common case. Keep 56 bytes of state: // v, w, x, y, and z. pair v, w; uint64 x = Uint128Low64(seed); uint64 y = Uint128High64(seed); uint64 z = len * k1; v.first = Rotate(y ^ k1, 49) * k1 + Fetch64(s); v.second = Rotate(v.first, 42) * k1 + Fetch64(s + 8); w.first = Rotate(y + z, 35) * k1 + x; w.second = Rotate(x + Fetch64(s + 88), 53) * k1; // This is the same inner loop as CityHash64(), manually unrolled. do { x = Rotate(x + y + v.first + Fetch64(s + 8), 37) * k1; y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch64(s + 40); z = Rotate(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16)); std::swap(z, x); s += 64; x = Rotate(x + y + v.first + Fetch64(s + 8), 37) * k1; y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch64(s + 40); z = Rotate(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16)); std::swap(z, x); s += 64; len -= 128; } while (LIKELY(len >= 128)); x += Rotate(v.first + z, 49) * k0; y = y * k0 + Rotate(w.second, 37); z = z * k0 + Rotate(w.first, 27); w.first *= 9; v.first *= k0; // If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s. for (size_t tail_done = 0; tail_done < len; ) { tail_done += 32; y = Rotate(x + y, 42) * k0 + v.second; w.first += Fetch64(s + len - tail_done + 16); x = x * k0 + w.first; z += w.second + Fetch64(s + len - tail_done); w.second += v.first; v = WeakHashLen32WithSeeds(s + len - tail_done, v.first + z, v.second); v.first *= k0; } // At this point our 56 bytes of state should contain more than // enough information for a strong 128-bit hash. We use two // different 56-byte-to-8-byte hashes to get a 16-byte final result. x = HashLen16(x, v.first); y = HashLen16(y + z, w.first); return uint128(HashLen16(x + v.second, w.second) + y, HashLen16(x + w.second, y + v.second)); } uint128 CityHash128(const char *s, size_t len) { return len >= 16 ? CityHash128WithSeed(s + 16, len - 16, uint128(Fetch64(s), Fetch64(s + 8) + k0)) : CityHash128WithSeed(s, len, uint128(k0, k1)); } #ifdef __SSE4_2__ #include #include // Requires len >= 240. static void CityHashCrc256Long(const char *s, size_t len, uint32 seed, uint64 *result) { uint64 a = Fetch64(s + 56) + k0; uint64 b = Fetch64(s + 96) + k0; uint64 c = result[0] = HashLen16(b, len); uint64 d = result[1] = Fetch64(s + 120) * k0 + len; uint64 e = Fetch64(s + 184) + seed; uint64 f = 0; uint64 g = 0; uint64 h = c + d; uint64 x = seed; uint64 y = 0; uint64 z = 0; // 240 bytes of input per iter. size_t iters = len / 240; len -= iters * 240; do { #undef CHUNK #define CHUNK(r) \ PERMUTE3(x, z, y); \ b += Fetch64(s); \ c += Fetch64(s + 8); \ d += Fetch64(s + 16); \ e += Fetch64(s + 24); \ f += Fetch64(s + 32); \ a += b; \ h += f; \ b += c; \ f += d; \ g += e; \ e += z; \ g += x; \ z = _mm_crc32_u64(z, b + g); \ y = _mm_crc32_u64(y, e + h); \ x = _mm_crc32_u64(x, f + a); \ e = Rotate(e, r); \ c += e; \ s += 40 CHUNK(0); PERMUTE3(a, h, c); CHUNK(33); PERMUTE3(a, h, f); CHUNK(0); PERMUTE3(b, h, f); CHUNK(42); PERMUTE3(b, h, d); CHUNK(0); PERMUTE3(b, h, e); CHUNK(33); PERMUTE3(a, h, e); } while (--iters > 0); while (len >= 40) { CHUNK(29); e ^= Rotate(a, 20); h += Rotate(b, 30); g ^= Rotate(c, 40); f += Rotate(d, 34); PERMUTE3(c, h, g); len -= 40; } if (len > 0) { s = s + len - 40; CHUNK(33); e ^= Rotate(a, 43); h += Rotate(b, 42); g ^= Rotate(c, 41); f += Rotate(d, 40); } result[0] ^= h; result[1] ^= g; g += h; a = HashLen16(a, g + z); x += y << 32; b += x; c = HashLen16(c, z) + h; d = HashLen16(d, e + result[0]); g += e; h += HashLen16(x, f); e = HashLen16(a, d) + g; z = HashLen16(b, c) + a; y = HashLen16(g, h) + c; result[0] = e + z + y + x; a = ShiftMix((a + y) * k0) * k0 + b; result[1] += a + result[0]; a = ShiftMix(a * k0) * k0 + c; result[2] = a + result[1]; a = ShiftMix((a + e) * k0) * k0; result[3] = a + result[2]; } // Requires len < 240. static void CityHashCrc256Short(const char *s, size_t len, uint64 *result) { char buf[240]; memcpy(buf, s, len); memset(buf + len, 0, 240 - len); CityHashCrc256Long(buf, 240, ~static_cast(len), result); } void CityHashCrc256(const char *s, size_t len, uint64 *result) { if (LIKELY(len >= 240)) { CityHashCrc256Long(s, len, 0, result); } else { CityHashCrc256Short(s, len, result); } } uint128 CityHashCrc128WithSeed(const char *s, size_t len, uint128 seed) { if (len <= 900) { return CityHash128WithSeed(s, len, seed); } else { uint64 result[4]; CityHashCrc256(s, len, result); uint64 u = Uint128High64(seed) + result[0]; uint64 v = Uint128Low64(seed) + result[1]; return uint128(HashLen16(u, v + result[2]), HashLen16(Rotate(v, 32), u * k0 + result[3])); } } uint128 CityHashCrc128(const char *s, size_t len) { if (len <= 900) { return CityHash128(s, len); } else { uint64 result[4]; CityHashCrc256(s, len, result); return uint128(result[2], result[3]); } } #endif swarm-2.1.6/src/cityhash/city.h000066400000000000000000000114421263351160000163740ustar00rootroot00000000000000// Copyright (c) 2011 Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // CityHash, by Geoff Pike and Jyrki Alakuijala // // http://code.google.com/p/cityhash/ // // This file provides a few functions for hashing strings. All of them are // high-quality functions in the sense that they pass standard tests such // as Austin Appleby's SMHasher. They are also fast. // // For 64-bit x86 code, on short strings, we don't know of anything faster than // CityHash64 that is of comparable quality. We believe our nearest competitor // is Murmur3. For 64-bit x86 code, CityHash64 is an excellent choice for hash // tables and most other hashing (excluding cryptography). // // For 64-bit x86 code, on long strings, the picture is more complicated. // On many recent Intel CPUs, such as Nehalem, Westmere, Sandy Bridge, etc., // CityHashCrc128 appears to be faster than all competitors of comparable // quality. CityHash128 is also good but not quite as fast. We believe our // nearest competitor is Bob Jenkins' Spooky. We don't have great data for // other 64-bit CPUs, but for long strings we know that Spooky is slightly // faster than CityHash on some relatively recent AMD x86-64 CPUs, for example. // Note that CityHashCrc128 is declared in citycrc.h. // // For 32-bit x86 code, we don't know of anything faster than CityHash32 that // is of comparable quality. We believe our nearest competitor is Murmur3A. // (On 64-bit CPUs, it is typically faster to use the other CityHash variants.) // // Functions in the CityHash family are not suitable for cryptography. // // Please see CityHash's README file for more details on our performance // measurements and so on. // // WARNING: This code has been only lightly tested on big-endian platforms! // It is known to work well on little-endian platforms that have a small penalty // for unaligned reads, such as current Intel and AMD moderate-to-high-end CPUs. // It should work on all 32-bit and 64-bit platforms that allow unaligned reads; // bug reports are welcome. // // By the way, for some hash functions, given strings a and b, the hash // of a+b is easily derived from the hashes of a and b. This property // doesn't hold for any hash functions in this file. #ifndef CITY_HASH_H_ #define CITY_HASH_H_ #include // for size_t. #include #include typedef uint8_t uint8; typedef uint32_t uint32; typedef uint64_t uint64; typedef std::pair uint128; inline uint64 Uint128Low64(const uint128& x) { return x.first; } inline uint64 Uint128High64(const uint128& x) { return x.second; } // Hash function for a byte array. uint64 CityHash64(const char *buf, size_t len); // Hash function for a byte array. For convenience, a 64-bit seed is also // hashed into the result. uint64 CityHash64WithSeed(const char *buf, size_t len, uint64 seed); // Hash function for a byte array. For convenience, two seeds are also // hashed into the result. uint64 CityHash64WithSeeds(const char *buf, size_t len, uint64 seed0, uint64 seed1); // Hash function for a byte array. uint128 CityHash128(const char *s, size_t len); // Hash function for a byte array. For convenience, a 128-bit seed is also // hashed into the result. uint128 CityHash128WithSeed(const char *s, size_t len, uint128 seed); // Hash function for a byte array. Most useful in 32-bit binaries. uint32 CityHash32(const char *buf, size_t len); // Hash 128 input bits down to 64 bits of output. // This is intended to be a reasonably good hash function. inline uint64 Hash128to64(const uint128& x) { // Murmur-inspired hashing. const uint64 kMul = 0x9ddfea08eb382d69ULL; uint64 a = (Uint128Low64(x) ^ Uint128High64(x)) * kMul; a ^= (a >> 47); uint64 b = (Uint128High64(x) ^ a) * kMul; b ^= (b >> 47); b *= kMul; return b; } #endif // CITY_HASH_H_ swarm-2.1.6/src/cityhash/citycrc.h000066400000000000000000000035061263351160000170660ustar00rootroot00000000000000// Copyright (c) 2011 Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // CityHash, by Geoff Pike and Jyrki Alakuijala // // This file declares the subset of the CityHash functions that require // _mm_crc32_u64(). See the CityHash README for details. // // Functions in the CityHash family are not suitable for cryptography. #ifndef CITY_HASH_CRC_H_ #define CITY_HASH_CRC_H_ #include // Hash function for a byte array. uint128 CityHashCrc128(const char *s, size_t len); // Hash function for a byte array. For convenience, a 128-bit seed is also // hashed into the result. uint128 CityHashCrc128WithSeed(const char *s, size_t len, uint128 seed); // Hash function for a byte array. Sets result[0] ... result[3]. void CityHashCrc256(const char *s, size_t len, uint64 *result); #endif // CITY_HASH_CRC_H_ swarm-2.1.6/src/cityhash/config.h000066400000000000000000000000341263351160000166640ustar00rootroot00000000000000/* config.h for cityhash */ swarm-2.1.6/src/db.cc000066400000000000000000000357511263351160000143440ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" //#define HASH hash_fnv_1a_64 #define HASH hash_cityhash64 #define MEMCHUNK 1048576 #define LINEALLOC LINE_MAX char map_nt[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; char map_hex[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; unsigned long sequences = 0; unsigned long nucleotides = 0; unsigned long headerchars = 0; int longest = 0; int longestheader = 0; seqinfo_t * seqindex = 0; char * datap = 0; qgramvector_t * qgrams = 0; void showseq(char * seq) { char * p = seq; while (char c = *p++) { putchar(sym_nt[(unsigned int)c]); } } void fprint_id(FILE * stream, unsigned long x) { fprintf(stream, "%.*s", seqindex[x].headeridlen, seqindex[x].header); } void fprint_id_noabundance(FILE * stream, unsigned long x) { seqinfo_t * sp = seqindex + x; char * h = sp->header; int hdrlen = sp->headeridlen; if (sp->abundance_start < sp->abundance_end) { /* print start of header */ fprintf(stream, "%.*s", sp->abundance_start, h); if (usearch_abundance) { /* print semicolon if the abundance is not at either end */ if ((sp->abundance_start > 0) && (sp->abundance_end < hdrlen)) fprintf(stream, ";"); /* print remaining part */ fprintf(stream, "%.*s", hdrlen - sp->abundance_end, h + sp->abundance_end); } } else { fprintf(stream, "%s", h); } } void fprint_id_with_new_abundance(FILE * stream, unsigned long seqno, unsigned long abundance) { seqinfo_t * sp = seqindex + seqno; if (usearch_abundance) fprintf(stream, "%.*s%ssize=%lu;%.*s", sp->abundance_start, sp->header, sp->abundance_start > 0 ? ";" : "", abundance, sp->headeridlen - sp->abundance_end, sp->header + sp->abundance_end); else fprintf(stream, "%.*s_%lu", sp->abundance_start, sp->header, abundance); } int db_compare_abundance(const void * a, const void * b) { seqinfo_t * x = (seqinfo_t *) a; seqinfo_t * y = (seqinfo_t *) b; if (x->abundance > y->abundance) return -1; else if (x->abundance < y->abundance) return +1; else { if (x < y) return -1; else if (x > y) return +1; else return 0; } } void db_read(const char * filename) { /* allocate space */ unsigned long dataalloc = MEMCHUNK; datap = (char *) xmalloc(dataalloc); unsigned long datalen = 0; longest = 0; longestheader = 0; sequences = 0; nucleotides = 0; headerchars = 0; FILE * fp = NULL; if (filename) { fp = fopen(filename, "r"); if (!fp) fatal("Error: Unable to open input data file (%s).", filename); } else fp = stdin; /* get file size */ long filesize = 0; if (filename) { if (fseek(fp, 0, SEEK_END)) fatal("Error: Unable to seek in database file (%s)", filename); filesize = ftell(fp); rewind(fp); } char line[LINEALLOC]; line[0] = 0; if (!fgets(line, LINEALLOC, fp)) line[0] = 0; unsigned int lineno = 1; progress_init("Reading database: ", filesize); while(line[0]) { /* read header */ /* the header ends at a space character, a newline or a nul character */ if (line[0] != '>') fatal("Illegal header line in fasta file."); long headerlen = 0; if (char * stop = strpbrk(line+1, " \n")) headerlen = stop - (line+1); else headerlen = strlen(line+1); headerchars += headerlen; if (headerlen > longestheader) longestheader = headerlen; /* store the line number */ while (datalen + sizeof(unsigned int) > dataalloc) { dataalloc += MEMCHUNK; datap = (char *) xrealloc(datap, dataalloc); } memcpy(datap + datalen, & lineno, sizeof(unsigned int)); datalen += sizeof(unsigned int); /* store the header */ while (datalen + headerlen + 1 > dataalloc) { dataalloc += MEMCHUNK; datap = (char *) xrealloc(datap, dataalloc); } memcpy(datap + datalen, line + 1, headerlen); *(datap + datalen + headerlen) = 0; datalen += headerlen + 1; /* get next line */ line[0] = 0; if (!fgets(line, LINEALLOC, fp)) line[0] = 0; lineno++; /* read and store sequence */ unsigned long seqbegin = datalen; while (line[0] && (line[0] != '>')) { char m; char c; char * p = line; while((c = *p++)) if ((m = map_nt[(int)c]) >= 0) { while (datalen >= dataalloc) { dataalloc += MEMCHUNK; datap = (char *) xrealloc(datap, dataalloc); } *(datap+datalen) = m; datalen++; } else if (c != '\n') { char msg[100]; snprintf(msg, 100, "Illegal character '%c' in sequence on line %u", c, lineno); fatal(msg); } line[0] = 0; if (!fgets(line, LINEALLOC, fp)) line[0] = 0; lineno++; } while (datalen >= dataalloc) { dataalloc += MEMCHUNK; datap = (char *) xrealloc(datap, dataalloc); } long length = datalen - seqbegin; nucleotides += length; if (length > longest) longest = length; *(datap+datalen) = 0; datalen++; sequences++; if (filename) progress_update(ftell(fp)); } progress_done(); fclose(fp); /* set up hash to check for unique headers */ unsigned long hdrhashsize = 2 * sequences; seqinfo_t * * hdrhashtable = (seqinfo_t **) xmalloc(hdrhashsize * sizeof(seqinfo_t *)); memset(hdrhashtable, 0, hdrhashsize * sizeof(seqinfo_t *)); unsigned long duplicatedidentifiers = 0; /* create indices */ seqindex = (seqinfo_t *) xmalloc(sequences * sizeof(seqinfo_t)); seqinfo_t * seqindex_p = seqindex; regex_t db_regexp; regmatch_t pmatch[4]; if (usearch_abundance) { if (regcomp(&db_regexp, "(^|;)size=([0-9]+)(;|$)", REG_EXTENDED)) fatal("Regular expression compilation failed"); } else { if (regcomp(&db_regexp, "(_)([0-9]+)$", REG_EXTENDED)) fatal("Regular expression compilation failed"); } long lastabundance = LONG_MAX; int presorted = 1; int missingabundance = 0; unsigned int missingabundance_lineno = 0; char * p = datap; progress_init("Indexing database:", sequences); for(unsigned long i=0; iheader = p; seqindex_p->headerlen = strlen(seqindex_p->header); seqindex_p->headeridlen = seqindex_p->headerlen; p += seqindex_p->headerlen + 1; /* get amplicon abundance */ seqindex_p->abundance = 0; if (!regexec(&db_regexp, seqindex_p->header, 4, pmatch, 0)) { seqindex_p->abundance = atol(seqindex_p->header + pmatch[2].rm_so); seqindex_p->abundance_start = pmatch[0].rm_so; seqindex_p->abundance_end = pmatch[0].rm_eo; } else { seqindex_p->abundance_start = 0; seqindex_p->abundance_end = 0; } if (seqindex_p->abundance < 1) { if (opt_append_abundance > 0) { seqindex_p->abundance = opt_append_abundance; } else { missingabundance++; if (missingabundance == 1) missingabundance_lineno = lineno; } } if (seqindex_p->abundance > lastabundance) presorted = 0; lastabundance = seqindex_p->abundance; /* check hash, fatal error if found, otherwize insert new */ unsigned long hdrhash = HASH((unsigned char*)seqindex_p->header, seqindex_p->headeridlen); seqindex_p->hdrhash = hdrhash; unsigned long hashindex = hdrhash % hdrhashsize; seqinfo_t * found; while ((found = hdrhashtable[hashindex])) { if ((found->hdrhash == hdrhash) && (found->headeridlen == seqindex_p->headeridlen) && (strncmp(found->header, seqindex_p->header, found->headeridlen) == 0)) break; hashindex = (hashindex + 1) % hdrhashsize; } if (found) { duplicatedidentifiers++; fprintf(logfile, "WARNING: Duplicated sequence identifier: %s\n", seqindex_p->header); } hdrhashtable[hashindex] = seqindex_p; seqindex_p->seq = p; seqindex_p->seqlen = strlen(p); p += seqindex_p->seqlen + 1; seqindex_p++; progress_update(i); } progress_done(); if (missingabundance) { char * msg; if (asprintf(&msg, "Abundance annotations not found for %d sequences, " "starting on line %u.\n" "Fasta headers must end with abundance annotations " "(_INT or ;size=INT)\n" "Abundance annotations can be produced by " "dereplicating the sequences\n", missingabundance, missingabundance_lineno) == -1) fatal("Out of memory"); else fatal(msg); } if (!presorted) { progress_init("Abundance sorting:", 1); qsort(seqindex, sequences, sizeof(seqinfo_t), db_compare_abundance); progress_done(); } regfree(&db_regexp); free(hdrhashtable); if (duplicatedidentifiers) exit(1); } void db_qgrams_init() { qgrams = (qgramvector_t *) xmalloc(sequences * sizeof(qgramvector_t)); seqinfo_t * seqindex_p = seqindex; progress_init("Find qgram vects: ", sequences); for(unsigned int i=0; iseq, seqindex_p->seqlen, qgrams[i]); seqindex_p++; progress_update(i); } progress_done(); } void db_qgrams_done() { free(qgrams); } unsigned long db_getsequencecount() { return sequences; } unsigned long db_getnucleotidecount() { return nucleotides; } unsigned long db_getlongestheader() { return longestheader; } unsigned long db_getlongestsequence() { return longest; } seqinfo_t * db_getseqinfo(unsigned long seqno) { return seqindex+seqno; } char * db_getsequence(unsigned long seqno) { return seqindex[seqno].seq; } void db_getsequenceandlength(unsigned long seqno, char ** address, long * length) { *address = seqindex[seqno].seq; *length = (long)(seqindex[seqno].seqlen); } unsigned long db_getsequencelen(unsigned long seqno) { return seqindex[seqno].seqlen; } char * db_getheader(unsigned long seqno) { return seqindex[seqno].header; } unsigned long db_getheaderlen(unsigned long seqno) { return seqindex[seqno].headerlen; } unsigned long db_getabundance(unsigned long seqno) { return seqindex[seqno].abundance; } void db_putseq(long seqno) { char * seq; long len; db_getsequenceandlength(seqno, & seq, & len); for(int i=0; i= 1025) free(buf); } swarm-2.1.6/src/derep.cc000066400000000000000000000226701263351160000150520ustar00rootroot00000000000000/* Copyright (C) 2014-2015 Torbjorn Rognes This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" //#define REVCOMP struct bucket { unsigned long hash; unsigned int seqno_first; unsigned int seqno_last; unsigned long mass; unsigned int size; unsigned int singletons; }; int derep_compare(const void * a, const void * b) { struct bucket * x = (struct bucket *) a; struct bucket * y = (struct bucket *) b; /* highest abundance first, otherwise keep order */ if (x->mass < y->mass) return +1; else if (x->mass > y->mass) return -1; else { if (x->seqno_first < y->seqno_first) return -1; else if (x->seqno_first > y->seqno_first) return +1; else return 0; } } #ifdef REVCOMP char map_complement[5] = { 0, 4, 3, 2, 1 }; void reverse_complement(char * rc, char * seq, long len) { /* Write the reverse complementary sequence to rc. The memory for rc must be long enough for the rc of the sequence (identical to the length of seq + 1). */ for(long i=0; i 0.7) hashtablesize <<= 1; int hash_mask = hashtablesize - 1; struct bucket * hashtable = (struct bucket *) xmalloc(sizeof(bucket) * hashtablesize); memset(hashtable, 0, sizeof(bucket) * hashtablesize); long swarmcount = 0; unsigned long maxmass = 0; unsigned int maxsize = 0; /* alloc and init table of links to other sequences in cluster */ unsigned int * nextseqtab = (unsigned int *) xmalloc(sizeof(unsigned int) * dbsequencecount); memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount); #ifdef REVCOMP /* allocate memory for reverse complementary sequence */ char * rc_seq = (char*) xmalloc(db_getlongestsequence() + 1); #endif progress_init("Dereplicating: ", dbsequencecount); for(long i=0; imass) && ((bp->hash != hash) || (seqlen != db_getsequencelen(bp->seqno_first)) || (strcmp(seq, db_getsequence(bp->seqno_first))))) { bp++; j++; if (bp >= hashtable + hashtablesize) { bp = hashtable; j = 0; } } #ifdef REVCOMP if (! bp->mass) { /* no match on plus strand */ /* check minus strand as well */ reverse_complement(rc_seq, seq, seqlen); unsigned long rc_hash = CityHash64(rc_seq, seqlen); struct bucket * rc_bp = hashtable + rc_hash % hashtablesize; unsigned long k = rc_hash & hash_mask; while ((rc_bp->mass) && ((rc_bp->hash != rc_hash) || (seqlen != db_getsequencelen(rc_bp->seqno_first)) || (strcmp(rc_seq, db_getsequence(rc_bp->seqno_first))))) { rc_bp++; k++; if (rc_bp >= hashtable + hashtablesize) { rc_bp = hashtable; k++; } } if (rc_bp->mass) { bp = rc_bp; j = k; } } #endif long ab = db_getabundance(i); if (bp->mass) { /* at least one identical sequence already */ nextseqtab[bp->seqno_last] = i; } else { /* no identical sequences yet, start a new cluster */ swarmcount++; bp->hash = hash; bp->seqno_first = i; bp->size = 0; bp->singletons = 0; } bp->size++; bp->seqno_last = i; bp->mass += ab; if (ab == 1) bp->singletons++; if (bp->mass > maxmass) maxmass = bp->mass; if (bp->size > maxsize) maxsize = bp->size; progress_update(i); } progress_done(); #ifdef REVCOMP free(rc_seq); #endif progress_init("Sorting: ", 1); qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare); progress_done(); /* dump swarms */ progress_init("Writing swarms: ", swarmcount); if (mothur) fprintf(outfile, "swarm_%ld\t%ld", resolution, swarmcount); for(int i = 0; i < swarmcount; i++) { int seed = hashtable[i].seqno_first; if (mothur) fputc('\t', outfile); fprint_id(outfile, seed); int a = nextseqtab[seed]; while (a) { if (mothur) fputc(',', outfile); else fputc(SEPCHAR, outfile); fprint_id(outfile, a); a = nextseqtab[a]; } if (!mothur) fputc('\n', outfile); progress_update(i+1); } if (mothur) fputc('\n', outfile); progress_done(); /* dump seeds in fasta format with sum of abundances */ if (opt_seeds) { progress_init("Writing seeds: ", swarmcount); for(int i=0; i < swarmcount; i++) { int seed = hashtable[i].seqno_first; fprintf(fp_seeds, ">"); fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, seed, 0); progress_update(i+1); } progress_done(); } /* output swarm in uclust format */ if (uclustfile) { progress_init("Writing UCLUST: ", swarmcount); for(unsigned int swarmid = 0; swarmid < swarmcount ; swarmid++) { struct bucket * bp = hashtable + swarmid; int seed = bp->seqno_first; fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t", swarmid, bp->size); fprint_id(uclustfile, seed); fprintf(uclustfile, "\t*\n"); fprintf(uclustfile, "S\t%u\t%lu\t*\t*\t*\t*\t*\t", swarmid, db_getsequencelen(seed)); fprint_id(uclustfile, seed); fprintf(uclustfile, "\t*\n"); int a = nextseqtab[seed]; while (a) { fprintf(uclustfile, "H\t%u\t%lu\t%.1f\t+\t0\t0\t%s\t", swarmid, db_getsequencelen(a), 100.0, "="); fprint_id(uclustfile, a); fprintf(uclustfile, "\t"); fprint_id(uclustfile, seed); fprintf(uclustfile, "\n"); a = nextseqtab[a]; } progress_update(swarmid+1); } progress_done(); } /* output internal structure to file */ if (opt_internal_structure) { progress_init("Writing structure:", swarmcount); for(long i = 0; i < swarmcount; i++) { struct bucket * sp = hashtable + i; long seed = sp->seqno_first; int a = nextseqtab[seed]; while (a) { fprint_id_noabundance(internal_structure_file, seed); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, a); fprintf(internal_structure_file, "\t%d\t%ld\t%d\n", 0, i+1, 0); a = nextseqtab[a]; } progress_update(i); } progress_done(); } /* output statistics to file */ if (statsfile) { progress_init("Writing stats: ", swarmcount); for(long i = 0; i < swarmcount; i++) { struct bucket * sp = hashtable + i; fprintf(statsfile, "%u\t%lu\t", sp->size, sp->mass); fprint_id_noabundance(statsfile, sp->seqno_first); fprintf(statsfile, "\t%lu\t%u\t%u\t%u\n", db_getabundance(sp->seqno_first), sp->singletons, 0, 0); progress_update(i); } progress_done(); } fprintf(logfile, "\n"); fprintf(logfile, "Number of swarms: %ld\n", swarmcount); fprintf(logfile, "Largest swarm: %u\n", maxsize); fprintf(logfile, "Heaviest swarm: %lu\n", maxmass); free(nextseqtab); free(hashtable); } swarm-2.1.6/src/matrix.cc000066400000000000000000000052441263351160000152550ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" long SCORELIMIT_7 = 0; long SCORELIMIT_8; long SCORELIMIT_16; long SCORELIMIT_32; long SCORELIMIT_63; char BIAS; unsigned char * score_matrix_8 = NULL; unsigned short * score_matrix_16 = NULL; long * score_matrix_63 = NULL; void score_matrix_dump() { fprintf(logfile, " "); for(int i=0; i<16; i++) fprintf(logfile, "%2d", i); fprintf(logfile, "\n"); fprintf(logfile, " "); for(int i=0; i<16; i++) fprintf(logfile, " %c", sym_nt[i]); fprintf(logfile, "\n"); for(int i=0; i<16; i++) { fprintf(logfile, "%2d %c ", i, sym_nt[i]); for(int j=0; j<16; j++) { fprintf(logfile, "%2ld", score_matrix_63[(i<<5) + j]); } fprintf(logfile, "\n"); } } void score_matrix_read() { int a, b; long sc, lo, hi; score_matrix_8 = (unsigned char *) xmalloc(32*32*sizeof(char)); score_matrix_16 = (unsigned short *) xmalloc(32*32*sizeof(short)); score_matrix_63 = (long *) xmalloc(32*32*sizeof(long)); hi = -1000; lo = 1000; for(a=0;a<16;a++) for(b=0;b<16;b++) { sc = ((a==b)&&(a>0)&&(b>0)) ? 0 : penalty_mismatch; // sc = (a==b) ? matchscore : mismatchscore; if (sc < lo) lo = sc; if (sc > hi) hi = sc; score_matrix_63[(a<<5) + b] = sc; } SCORELIMIT_8 = 256 - hi; SCORELIMIT_16 = 65536 - hi; for(a=0;a<32;a++) for(b=0;b<32;b++) { sc = score_matrix_63[(a<<5) + b]; score_matrix_8[(a<<5) + b] = (unsigned char) sc; score_matrix_16[(a<<5) + b] = (unsigned short) sc; } } void score_matrix_init() { score_matrix_read(); // score_matrix_dump(); } void score_matrix_free() { free(score_matrix_8); score_matrix_8 = NULL; free(score_matrix_16); score_matrix_16 = NULL; free(score_matrix_63); score_matrix_63 = NULL; } swarm-2.1.6/src/nw.cc000066400000000000000000000151001263351160000143650ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" void pushop(char newop, char ** cigarendp, char * op, int * count) { if (newop == *op) (*count)++; else { *--*cigarendp = *op; if (*count > 1) { char buf[25]; int len = sprintf(buf, "%d", *count); *cigarendp -= len; strncpy(*cigarendp, buf, len); } *op = newop; *count = 1; } } void finishop(char ** cigarendp, char * op, int * count) { if ((op) && (count)) { *--*cigarendp = *op; if (*count > 1) { char buf[25]; int len = sprintf(buf, "%d", *count); *cigarendp -= len; strncpy(*cigarendp, buf, len); } *op = 0; *count = 0; } } const unsigned char maskup = 1; const unsigned char maskleft = 2; const unsigned char maskextup = 4; const unsigned char maskextleft = 8; /* Needleman/Wunsch/Sellers aligner finds a global alignment with minimum cost there should be positive costs/penalties for gaps and for mismatches matches should have zero cost (0) alignment priority when backtracking (from lower right corner): 1. left/insert/e (gap in query sequence (qseq)) 2. align/diag/h (match/mismatch) 3. up/delete/f (gap in database sequence (dseq)) qseq: the reference/query/upper/vertical/from sequence dseq: the sample/database/lower/horisontal/to sequence typical costs: match: 0 mismatch: 3 gapopen: 4 gapextend: 3 input dseq: pointer to start of database sequence dend: pointer after database sequence qseq: pointer to start of query sequence qend: pointer after database sequence score_matrix: 32x32 matrix of longs with scores for aligning two symbols gapopen: positive number indicating penalty for opening a gap of length zero gapextend: positive number indicating penalty for extending a gap output nwscore: the global alignment score nwdiff: number of non-identical nucleotides in one optimal global alignment nwalignmentlength: the length of one optimal alignment nwalignment: cigar string with one optimal alignment */ void nw(char * dseq, char * dend, char * qseq, char * qend, long * score_matrix, unsigned long gapopen, unsigned long gapextend, unsigned long * nwscore, unsigned long * nwdiff, unsigned long * nwalignmentlength, char ** nwalignment, unsigned char * dir, unsigned long * hearray, unsigned long queryno, unsigned long dbseqno) { /* dir must point to at least qlen*dlen bytes of allocated memory hearray must point to at least 2*qlen longs of allocated memory (8*qlen bytes) */ long n, e; long unsigned *hep; long qlen = qend - qseq; long dlen = dend - dseq; memset(dir, 0, qlen*dlen); long i, j; for(i=0; i0) && (j>0)) { int d = dir[qlen*(j-1)+(i-1)]; alength++; if ((op == 'I') && (d & maskextleft)) { score += gapextend; j--; pushop('I', &cigarend, &op, &count); } else if ((op == 'D') && (d & maskextup)) { score += gapextend; i--; pushop('D', &cigarend, &op, &count); } else if (d & maskleft) { score += gapextend; if (op != 'I') score += gapopen; j--; pushop('I', &cigarend, &op, &count); } else if (d & maskup) { score += gapextend; if (op != 'D') score +=gapopen; i--; pushop('D', &cigarend, &op, &count); } else { score += score_matrix[(dseq[j-1] << 5) + qseq[i-1]]; if (qseq[i-1] == dseq[j-1]) matches++; i--; j--; pushop('M', &cigarend, &op, &count); } } while(i>0) { alength++; score += gapextend; if (op != 'D') score += gapopen; i--; pushop('D', &cigarend, &op, &count); } while(j>0) { alength++; score += gapextend; if (op != 'I') score += gapopen; j--; pushop('I', &cigarend, &op, &count); } finishop(&cigarend, &op, &count); /* move and reallocate cigar */ long cigarlength = cigar+qlen+dlen-cigarend; memmove(cigar, cigarend, cigarlength+1); cigar = (char*) xrealloc(cigar, cigarlength+1); * nwscore = dist; * nwdiff = alength - matches; * nwalignmentlength = alength; * nwalignment = cigar; if (score != dist) { fprintf(stderr, "WARNING: Error with query no %lu and db sequence no %lu:\n", queryno, dbseqno); fprintf(stderr, "Initial and recomputed alignment score disagreement: %ld %ld\n", dist, score); fprintf(stderr, "Alignment: %s\n", cigar); } } swarm-2.1.6/src/qgram.cc000066400000000000000000000213101263351160000150500ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2014 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" static pthread_attr_t attr; static struct thread_info_s { /* generic thread info */ pthread_t pthread; pthread_mutex_t workmutex; pthread_cond_t workcond; int work; /* specialized thread info */ unsigned long seed; unsigned long listlen; unsigned long * amplist; unsigned long * difflist; } * ti; void printqgrams(unsigned char * qgramvector) { /* print qgramvector */ fprintf(logfile, "qgram vector:\n"); for(int i = 0; i < QGRAMVECTORBYTES; i++) { fprintf(logfile, "%02x", qgramvector[i]); if ((i % 32) == 31) fprintf(logfile, "\n"); } } void findqgrams(unsigned char * seq, unsigned long seqlen, unsigned char * qgramvector) { /* set qgram bit vector by xoring occurrences of qgrams in sequence */ memset(qgramvector, 0, QGRAMVECTORBYTES); unsigned long qgram = 0; unsigned long i = 0; while((i < QGRAMLENGTH-1) && (i> 3) & (QGRAMVECTORBYTES-1)] ^= (1 << (qgram & 7)); i++; } } /* Unable to get the Mac gcc compiler v 4.2.1 produce the real popcnt instruction. Therefore resorting to assembly code. */ #define popcnt_asm(x,y) \ __asm__ __volatile__ ("popcnt %1,%0" : "=r"(y) : "r"(x)); inline unsigned long popcount(unsigned long x) { unsigned long y; popcnt_asm(x,y); return y; } unsigned long popcount_128(__m128i x) { __m128i mask1 = _mm_set_epi8(0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55); __m128i mask2 = _mm_set_epi8(0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33); __m128i mask4 = _mm_set_epi8(0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f); __m128i zero = _mm_setzero_si128(); /* add together 2 bits: 0+1, 2+3, 3+4, ... 126+127 */ __m128i a = _mm_srli_epi64(x, 1); __m128i b = _mm_and_si128(x, mask1); __m128i c = _mm_and_si128(a, mask1); __m128i d = _mm_add_epi64(b, c); /* add together 4 bits: (0+1)+(2+3), ... (124+125)+(126+127) */ __m128i e = _mm_srli_epi64(d, 2); __m128i f = _mm_and_si128(d, mask2); __m128i g = _mm_and_si128(e, mask2); __m128i h = _mm_add_epi64(f, g); /* add together 8 bits: (0..3)+(4..7), ... (120..123)+(124..127) */ __m128i i = _mm_srli_epi64(h, 4); __m128i j = _mm_add_epi64(h, i); __m128i k = _mm_and_si128(j, mask4); /* add together 8 bytes: (0..63) and (64..127) */ __m128i l = _mm_sad_epu8(k, zero); /* add together 64-bit values into final 128 bit value */ __m128i m = _mm_srli_si128(l, 8); __m128i n = _mm_add_epi64(m, l); /* return low 64 bits: return value is always in range 0 to 128 */ unsigned long o = (unsigned long) _mm_movepi64_pi64(n); return o; } unsigned long compareqgramvectors_128(unsigned char * a, unsigned char * b) { /* Count number of different bits */ /* Uses SSE2 but not POPCNT instruction */ /* input MUST be 16-byte aligned */ __m128i * ap = (__m128i *) a; __m128i * bp = (__m128i *) b; unsigned long count = 0; while ((unsigned char*)ap < a + QGRAMVECTORBYTES) count += popcount_128(_mm_xor_si128(*ap++, *bp++)); return count; } unsigned long compareqgramvectors_64(unsigned char * a, unsigned char * b) { /* Count number of different bits */ /* Uses the POPCNT instruction, requires CPU with this feature */ unsigned long *ap = (unsigned long*)a; unsigned long *bp = (unsigned long*)b; unsigned long count = 0; while ((unsigned char*) ap < a + QGRAMVECTORBYTES) count += popcount(*ap++ ^ *bp++); return count; } unsigned long compareqgramvectors(unsigned char * a, unsigned char * b) { if (popcnt_present) return compareqgramvectors_64(a,b); else return compareqgramvectors_128(a,b); } inline unsigned long qgram_diff(unsigned long a, unsigned long b) { unsigned long diffqgrams = compareqgramvectors(db_getqgramvector(a), db_getqgramvector(b)); unsigned long mindiff = (diffqgrams + 2*QGRAMLENGTH - 1)/(2*QGRAMLENGTH); return mindiff; } void qgram_work_diff(thread_info_s * tip) { unsigned long seed = tip->seed; unsigned long listlen = tip->listlen; unsigned long * amplist = tip->amplist; unsigned long * difflist = tip->difflist; for(unsigned long i=0; iworkmutex); /* loop until signalled to quit */ while (tip->work >= 0) { /* wait for work available */ pthread_cond_wait(&tip->workcond, &tip->workmutex); if (tip->work > 0) { qgram_work_diff(tip); tip->work = 0; pthread_cond_signal(&tip->workcond); } } pthread_mutex_unlock(&tip->workmutex); return 0; } void qgram_diff_init() { pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* allocate memory for thread info */ ti = (struct thread_info_s *) xmalloc(threads * sizeof(struct thread_info_s)); /* init and create worker threads */ for(unsigned long t=0; twork = 0; pthread_mutex_init(&tip->workmutex, NULL); pthread_cond_init(&tip->workcond, NULL); if (pthread_create(&tip->pthread, &attr, qgram_worker, (void*)(long)t)) fatal("Cannot create thread"); } } void qgram_diff_done() { /* finish and clean up worker threads */ for(unsigned long t=0; tworkmutex); tip->work = -1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); /* wait for worker to quit */ if (pthread_join(tip->pthread, NULL)) fatal("Cannot join thread"); pthread_cond_destroy(&tip->workcond); pthread_mutex_destroy(&tip->workmutex); } free(ti); pthread_attr_destroy(&attr); } void qgram_diff_fast(unsigned long seed, unsigned long listlen, unsigned long * amplist, unsigned long * difflist) { long thr = threads; const unsigned long m = 150; if (listlen < m*thr) thr = (listlen+m-1)/m; unsigned long * next_amplist = amplist; unsigned long * next_difflist = difflist; unsigned long listrest = listlen; unsigned long thrrest = thr; /* distribute work */ for(long t=0; tseed = seed; tip->amplist = next_amplist; tip->difflist = next_difflist; tip->listlen = chunk; next_amplist += chunk; next_difflist += chunk; listrest -= chunk; thrrest--; } if (thr == 1) { qgram_work_diff(ti); } else { /* wake up threads */ for(long t=0; tworkmutex); tip->work = 1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); } /* wait for threads to finish their work */ for(int t=0; tworkmutex); while (tip->work > 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); pthread_mutex_unlock(&tip->workmutex); } } } swarm-2.1.6/src/scan.cc000066400000000000000000000222001263351160000146640ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" static pthread_attr_t attr; static struct thread_info_s { /* generic thread info */ pthread_t pthread; pthread_mutex_t workmutex; pthread_cond_t workcond; int work; /* specialized thread info */ unsigned long seed; unsigned long listlen; unsigned long * amplist; unsigned long * difflist; } * ti; pthread_mutex_t workmutex = PTHREAD_MUTEX_INITIALIZER; queryinfo_t query; struct search_data { BYTE ** qtable; WORD ** qtable_w; BYTE * dprofile; WORD * dprofile_w; BYTE * hearray; unsigned long * dir_array; unsigned long target_count; unsigned long target_index; }; struct search_data * sd; unsigned long master_next; unsigned long master_length; unsigned long remainingchunks; unsigned long * master_targets; unsigned long * master_scores; unsigned long * master_diffs; unsigned long * master_alignlengths; int master_bits; unsigned long longestdbsequence; unsigned long dirbufferbytes; void search_alloc(struct search_data * sdp) { dirbufferbytes = 8 * longestdbsequence * ((longestdbsequence+3)/4) * 4; sdp->qtable = (BYTE**) xmalloc(longestdbsequence * sizeof(BYTE*)); sdp->qtable_w = (WORD**) xmalloc(longestdbsequence * sizeof(WORD*)); sdp->dprofile = (BYTE*) xmalloc(4*16*32); sdp->dprofile_w = (WORD*) xmalloc(4*2*8*32); sdp->hearray = (BYTE*) xmalloc(longestdbsequence * 32); sdp->dir_array = (unsigned long *) xmalloc(dirbufferbytes); memset(sdp->hearray, 0, longestdbsequence*32); memset(sdp->dir_array, 0, dirbufferbytes); } void search_free(struct search_data * sdp) { free(sdp->qtable); free(sdp->qtable_w); free(sdp->dprofile); free(sdp->dprofile_w); free(sdp->hearray); free(sdp->dir_array); } void search_init(struct search_data * sdp) { for (long i = 0; i < query.len; i++ ) { sdp->qtable[i] = sdp->dprofile + 64*query.seq[i]; sdp->qtable_w[i] = sdp->dprofile_w + 32*query.seq[i]; } } void search_chunk(struct search_data * sdp, long bits) { if (sdp->target_count == 0) return; #if 0 for(unsigned long i=0; itarget_count; i++) { char * dseq; long dlen; char * nwalignment; unsigned long seqno = master_targets[sdp->target_index + i]; db_getsequenceandlength(seqno, & dseq, & dlen); nw(query.seq, query.seq + query.len, dseq, dseq + dlen, score_matrix_63, penalty_gapopen, penalty_gapextend, master_scores + sdp->target_index + i, master_diffs + sdp->target_index + i, master_alignlengths + sdp->target_index + i, & nwalignment, (unsigned char *) sdp->dir_array, (unsigned long int *) sdp->hearray, query.qno, seqno); free(nwalignment); } return; #endif if (bits == 16) search16(sdp->qtable_w, penalty_gapopen, penalty_gapextend, (WORD*) score_matrix_16, sdp->dprofile_w, (WORD*) sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, query.len, dirbufferbytes/8, sdp->dir_array); else search8(sdp->qtable, penalty_gapopen, penalty_gapextend, (BYTE*) score_matrix_8, sdp->dprofile, sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, query.len, dirbufferbytes/8, sdp->dir_array); } int search_getwork(unsigned long * countref, unsigned long * firstref) { // * countref = how many sequences to search // * firstref = index into master_targets/scores/diffs where thread should start unsigned long status = 0; pthread_mutex_lock(&workmutex); if (master_next < master_length) { unsigned long chunksize = ((master_length - master_next + remainingchunks - 1) / remainingchunks); * countref = chunksize; * firstref = master_next; master_next += chunksize; remainingchunks--; status = 1; } pthread_mutex_unlock(&workmutex); return status; } void master_dump() { printf("master_dump\n"); printf(" i t s d\n"); for(unsigned long i=0; i< 1403; i++) { printf("%4lu %4lu %4lu %4lu\n", i, master_targets[i], master_scores[i], master_diffs[i]); } } void search_worker_core(int t) { search_init(sd+t); while(search_getwork(& sd[t].target_count, & sd[t].target_index)) search_chunk(sd+t, master_bits); } void * search_worker(void * vp) { long t = (long) vp; struct thread_info_s * tip = ti + t; pthread_mutex_lock(&tip->workmutex); /* loop until signalled to quit */ while (tip->work >= 0) { /* wait for work available */ pthread_cond_wait(&tip->workcond, &tip->workmutex); if (tip->work > 0) { search_worker_core(t); tip->work = 0; pthread_cond_signal(&tip->workcond); } } pthread_mutex_unlock(&tip->workmutex); return 0; } void search_do(unsigned long query_no, unsigned long listlength, unsigned long * targets, unsigned long * scores, unsigned long * diffs, unsigned long * alignlengths, long bits) { query.qno = query_no; db_getsequenceandlength(query_no, &query.seq, &query.len); master_next = 0; master_length = listlength; master_targets = targets; master_scores = scores; master_diffs = diffs; master_alignlengths = alignlengths; master_bits = bits; unsigned long thr = threads; if (bits == 8) { if (master_length <= (unsigned long)(15 * thr) ) thr = (master_length + 15) / 16; } else { if (master_length <= (unsigned long)(7 * thr) ) thr = (master_length + 7) / 8; } remainingchunks = thr; if (thr == 1) { search_worker_core(0); } else { /* wake up threads */ for(unsigned long t=0; tworkmutex); tip->work = 1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); } /* wait for threads to finish their work */ for(unsigned long t=0; tworkmutex); while (tip->work > 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); pthread_mutex_unlock(&tip->workmutex); } } } void search_begin() { longestdbsequence = db_getlongestsequence(); sd = (struct search_data *) xmalloc(sizeof(search_data) * threads); for(unsigned long t=0; twork = 0; pthread_mutex_init(&tip->workmutex, NULL); pthread_cond_init(&tip->workcond, NULL); if (pthread_create(&tip->pthread, &attr, search_worker, (void*)(long)t)) fatal("Cannot create thread"); } } void search_end() { /* finish and clean up worker threads */ for(unsigned long t=0; tworkmutex); tip->work = -1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); /* wait for worker to quit */ if (pthread_join(tip->pthread, NULL)) fatal("Cannot join thread"); pthread_cond_destroy(&tip->workcond); pthread_mutex_destroy(&tip->workmutex); } free(ti); pthread_attr_destroy(&attr); for(unsigned long t=0; t. Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #define CHANNELS 8 #define CDEPTH 4 #define SHUFFLE 1 void dprofile_dump16(WORD * dprofile) { char * s = sym_nt; printf("\ndprofile:\n"); for(int i=0; i<32; i++) { printf("%c: ",s[i]); for(int k=0; k=0) && (j>=0)) { aligned++; unsigned long d = dirbuffer[(offset + longestdbsequence*4*(j/4) + 4*i + (j&3)) % dirbuffersize]; if ((op == 'I') && (d & maskextleft)) { j--; } else if ((op == 'D') && (d & maskextup)) { i--; } else if (d & maskleft) { j--; op = 'I'; } else if (d & maskup) { i--; op = 'D'; } else { if (qseq[i] == dseq[j]) matches++; i--; j--; op = 'M'; } } aligned += i + j + 2; * alignmentlengthp = aligned; return aligned - matches; } void search16(WORD * * q_start, WORD gap_open_penalty, WORD gap_extend_penalty, WORD * score_matrix, WORD * dprofile, WORD * hearray, unsigned long sequences, unsigned long * seqnos, unsigned long * scores, unsigned long * diffs, unsigned long * alignmentlengths, unsigned long qlen, unsigned long dirbuffersize, unsigned long * dirbuffer) { __m128i Q, R, T, M, T0, MQ, MR; __m128i *hep, **qp; BYTE * d_begin[CHANNELS]; BYTE * d_end[CHANNELS]; unsigned long d_offset[CHANNELS]; BYTE * d_address[CHANNELS]; unsigned long d_length[CHANNELS]; __m128i dseqalloc[CDEPTH]; __m128i H0; __m128i F0; __m128i S[4]; BYTE * dseq = (BYTE*) & dseqalloc; BYTE zero; long seq_id[CHANNELS]; unsigned long next_id = 0; unsigned long done; T0 = _mm_set_epi16(0, 0, 0, 0, 0, 0, 0, 0xffff); Q = _mm_set1_epi16(gap_open_penalty+gap_extend_penalty); R = _mm_set1_epi16(gap_extend_penalty); zero = 0; done = 0; hep = (__m128i*) hearray; qp = (__m128i**) q_start; for (int c=0; c= 0) { // printf("Completed channel %d, sequence %ld\n", c, cand_id); // save score char * dbseq = (char*) d_address[c]; long dbseqlen = d_length[c]; long z = (dbseqlen+3) % 4; long score = ((WORD*)S)[z*CHANNELS+c]; scores[cand_id] = score; unsigned long diff; if (score < 65535) { long offset = d_offset[c]; diff = backtrack16(query.seq, dbseq, qlen, dbseqlen, dirbuffer, offset, dirbuffersize, c, alignmentlengths + cand_id); } else { diff = MIN((65535 / penalty_mismatch), (65535 - penalty_gapopen) / penalty_gapextend); } diffs[cand_id] = diff; done++; } if (next_id < sequences) { // get next sequence seq_id[c] = next_id; long seqno = seqnos[next_id]; char* address; long length; db_getsequenceandlength(seqno, & address, & length); // printf("Seqno: %ld Address: %p\n", seqno, address); d_address[c] = (BYTE*) address; d_length[c] = length; d_begin[c] = (unsigned char*) address; d_end[c] = (unsigned char*) address + length; d_offset[c] = dir - dirbuffer; next_id++; ((WORD*)&H0)[c] = 0; ((WORD*)&F0)[c] = gap_open_penalty + gap_extend_penalty; // fill channel for(int j=0; j= dirbuffer + dirbuffersize) { dir -= dirbuffersize; } } } swarm-2.1.6/src/search8.cc000066400000000000000000001034561263351160000153120ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2014 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #define CHANNELS 16 #define CDEPTH 4 #define MATRIXWIDTH 16 void dprofile_dump8(BYTE * dprofile) { char * ss = sym_nt; printf("\ndprofile:\n"); for(int k=0; k<4; k++) { printf("k=%d 0 1 2 3 4 5 6 7 8 9 a b c d e f\n", k); for(int i=0; i<16; i++) { printf("%c: ",ss[i]); for(int j=0; j<16; j++) printf("%2d", (char) dprofile[i*64+16*k+j]); printf("\n"); } } printf("\n"); exit(1); } int dumpcounter = 0; char lines[4*16*1000]; void dseq_dump8(BYTE * dseq) { char * s = sym_nt; if (dumpcounter < 21) { for(int i=0; i=0) && (j>=0)) { aligned++; unsigned long d = dirbuffer[(offset + longestdbsequence*4*(j/4) + 4*i + (j&3)) % dirbuffersize]; if ((op == 'I') && (d & maskextleft)) { j--; } else if ((op == 'D') && (d & maskextup)) { i--; } else if (d & maskleft) { j--; op = 'I'; } else if (d & maskup) { i--; op = 'D'; } else { if (qseq[i] == dseq[j]) matches++; i--; j--; op = 'M'; } } aligned += i + j + 2; * alignmentlengthp = aligned; return aligned - matches; } void search8(BYTE * * q_start, BYTE gap_open_penalty, BYTE gap_extend_penalty, BYTE * score_matrix, BYTE * dprofile, BYTE * hearray, unsigned long sequences, unsigned long * seqnos, unsigned long * scores, unsigned long * diffs, unsigned long * alignmentlengths, unsigned long qlen, unsigned long dirbuffersize, unsigned long * dirbuffer) { __m128i Q, R, T, M, T0, MQ, MR; __m128i *hep, **qp; BYTE * d_begin[CHANNELS]; BYTE * d_end[CHANNELS]; unsigned long d_offset[CHANNELS]; BYTE * d_address[CHANNELS]; unsigned long d_length[CHANNELS]; __m128i dseqalloc[CDEPTH]; __m128i H0, F0; __m128i S[4]; BYTE * dseq = (BYTE*) & dseqalloc; BYTE zero; long seq_id[CHANNELS]; unsigned long next_id = 0; unsigned long done; T0 = _mm_set_epi8(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff); Q = _mm_set1_epi8(gap_open_penalty+gap_extend_penalty); R = _mm_set1_epi8(gap_extend_penalty); zero = 0; done = 0; hep = (__m128i*) hearray; qp = (__m128i**) q_start; for (int c=0; c= 0) { // save score char * dbseq = (char*) d_address[c]; long dbseqlen = d_length[c]; long z = (dbseqlen+3) % 4; long score = ((BYTE*)S)[z*16+c]; scores[cand_id] = score; unsigned long diff; if (score < 255) { long offset = d_offset[c]; diff = backtrack(query.seq, dbseq, qlen, dbseqlen, dirbuffer, offset, dirbuffersize, c, alignmentlengths + cand_id); } else { diff = 255; } diffs[cand_id] = diff; done++; } if (next_id < sequences) { // get next sequence seq_id[c] = next_id; long seqno = seqnos[next_id]; char* address; long length; db_getsequenceandlength(seqno, & address, & length); d_address[c] = (BYTE*) address; d_length[c] = length; d_begin[c] = (unsigned char*) address; d_end[c] = (unsigned char*) address + length; d_offset[c] = dir - dirbuffer; next_id++; ((BYTE*)&H0)[c] = 0; ((BYTE*)&F0)[c] = gap_open_penalty + gap_extend_penalty; // fill channel for(int j=0; j= dirbuffer + dirbuffersize) dir -= dirbuffersize; } } swarm-2.1.6/src/ssse3.cc000066400000000000000000000075121263351160000150110ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2014 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" /* Please note: This code requires the pshufb instruction, which is part of the SSSE3 instruction set for x86_64 cpus. It seems not to be present on AMD cpus and not on the first generation Intel x86_64 cpus. */ /* 8-bit version with 16 channels */ void dprofile_shuffle8(BYTE * dprofile, BYTE * score_matrix, BYTE * dseq_byte) { __m128i m0, m1, m2, m3, t0, t1, t2, t3, t4; __m128i * dseq = (__m128i*) dseq_byte; m0 = _mm_load_si128(dseq); m1 = _mm_load_si128(dseq+1); m2 = _mm_load_si128(dseq+2); m3 = _mm_load_si128(dseq+3); #define profline8(j) \ t0 = _mm_load_si128((__m128i*)(score_matrix)+2*j); \ t1 = _mm_shuffle_epi8(t0, m0); \ t2 = _mm_shuffle_epi8(t0, m1); \ t3 = _mm_shuffle_epi8(t0, m2); \ t4 = _mm_shuffle_epi8(t0, m3); \ _mm_store_si128((__m128i*)(dprofile)+4*j+0, t1); \ _mm_store_si128((__m128i*)(dprofile)+4*j+1, t2); \ _mm_store_si128((__m128i*)(dprofile)+4*j+2, t3); \ _mm_store_si128((__m128i*)(dprofile)+4*j+3, t4) profline8(0); profline8(1); profline8(2); profline8(3); profline8(4); } /* 16-bit version with 8 channels */ void dprofile_shuffle16(WORD * dprofile, WORD * score_matrix, BYTE * dseq_byte) { __m128i m0, m1, m2, m3; __m128i t0, t1, t2, t3, t4, t5; __m128i u0, u1, u2, u3, u4; __m128i zero, one; __m128i * dseq = (__m128i*) dseq_byte; zero = _mm_setzero_si128(); one = _mm_set1_epi16(1); t0 = _mm_load_si128(dseq+0); m0 = _mm_unpacklo_epi8(t0, zero); m0 = _mm_slli_epi16(m0, 1); t1 = _mm_adds_epu16(m0, one); t1 = _mm_slli_epi16(t1, 8); m0 = _mm_or_si128(m0, t1); m1 = _mm_unpackhi_epi8(t0, zero); m1 = _mm_slli_epi16(m1, 1); t2 = _mm_adds_epu16(m1, one); t2 = _mm_slli_epi16(t2, 8); m1 = _mm_or_si128(m1, t2); t3 = _mm_load_si128(dseq+1); m2 = _mm_unpacklo_epi8(t3, zero); m2 = _mm_slli_epi16(m2, 1); t4 = _mm_adds_epu16(m2, one); t4 = _mm_slli_epi16(t4, 8); m2 = _mm_or_si128(m2, t4); m3 = _mm_unpackhi_epi8(t3, zero); m3 = _mm_slli_epi16(m3, 1); t5 = _mm_adds_epu16(m3, one); t5 = _mm_slli_epi16(t5, 8); m3 = _mm_or_si128(m3, t5); #define profline16(j) \ u0 = _mm_load_si128((__m128i*)(score_matrix)+4*j); \ u1 = _mm_shuffle_epi8(u0, m0); \ u2 = _mm_shuffle_epi8(u0, m1); \ u3 = _mm_shuffle_epi8(u0, m2); \ u4 = _mm_shuffle_epi8(u0, m3); \ _mm_store_si128((__m128i*)(dprofile)+4*j+0, u1); \ _mm_store_si128((__m128i*)(dprofile)+4*j+1, u2); \ _mm_store_si128((__m128i*)(dprofile)+4*j+2, u3); \ _mm_store_si128((__m128i*)(dprofile)+4*j+3, u4) profline16(0); profline16(1); profline16(2); profline16(3); profline16(4); } swarm-2.1.6/src/swarm.cc000066400000000000000000000402541263351160000151020ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" /* ARGUMENTS AND THEIR DEFAULTS */ #define DEFAULT_GAPOPEN 12 #define DEFAULT_GAPEXTEND 4 #define DEFAULT_MATCHSCORE 5 #define DEFAULT_MISMATCHSCORE (-4) #define DEFAULT_THREADS 1 #define DEFAULT_RESOLUTION 1 #define DEFAULT_BREAK_SWARMS 0 #define DEFAULT_MOTHUR 0 #define DEFAULT_USEARCH_ABUNDANCE 0 #define DEFAULT_INTERNAL_STRUCTURE 0 #define DEFAULT_LOG 0 #define DEFAULT_NO_OTU_BREAKING 0 #define DEFAULT_FASTIDIOUS 0 #define DEFAULT_BOUNDARY 3 char * outfilename; char * statsfilename; char * uclustfilename; char * progname; char * databasename; long gapopen; long gapextend; long matchscore; long mismatchscore; unsigned long threads; long resolution; long break_swarms; long mothur; long usearch_abundance; char * opt_log; char * opt_internal_structure; char * opt_seeds; long opt_no_otu_breaking; long opt_fastidious; long opt_boundary; long opt_bloom_bits; long opt_ceiling; long opt_append_abundance; long penalty_factor; long penalty_gapextend; long penalty_gapopen; long penalty_mismatch; /* Other variables */ long mmx_present = 0; long sse_present = 0; long sse2_present = 0; long sse3_present = 0; long ssse3_present = 0; long sse41_present = 0; long sse42_present = 0; long popcnt_present = 0; long avx_present = 0; long avx2_present = 0; unsigned long dbsequencecount = 0; FILE * outfile; FILE * statsfile; FILE * uclustfile; FILE * logfile = stderr; FILE * internal_structure_file; FILE * fp_seeds = 0; char sym_nt[] = "-acgt "; #define cpuid(f1, f2, a, b, c, d) \ __asm__ __volatile__ ("cpuid" \ : "=a" (a), "=b" (b), "=c" (c), "=d" (d) \ : "a" (f1), "c" (f2)); void cpu_features_detect() { unsigned int a, b, c, d; cpuid(0, 0, a, b, c, d); unsigned int maxlevel = a & 0xff; if (maxlevel >= 1) { cpuid(1, 0, a, b, c, d); mmx_present = (d >> 23) & 1; sse_present = (d >> 25) & 1; sse2_present = (d >> 26) & 1; sse3_present = (c >> 0) & 1; ssse3_present = (c >> 9) & 1; sse41_present = (c >> 19) & 1; sse42_present = (c >> 20) & 1; popcnt_present = (c >> 23) & 1; avx_present = (c >> 28) & 1; if (maxlevel >= 7) { cpuid(7, 0, a, b, c, d); avx2_present = (b >> 5) & 1; } } } void cpu_features_show() { fprintf(logfile, "CPU features: "); if (mmx_present) fprintf(logfile, " mmx"); if (sse_present) fprintf(logfile, " sse"); if (sse2_present) fprintf(logfile, " sse2"); if (sse3_present) fprintf(logfile, " sse3"); if (ssse3_present) fprintf(logfile, " ssse3"); if (sse41_present) fprintf(logfile, " sse4.1"); if (sse42_present) fprintf(logfile, " sse4.2"); if (popcnt_present) fprintf(logfile, " popcnt"); if (avx_present) fprintf(logfile, " avx"); if (avx2_present) fprintf(logfile, " avx2"); fprintf(logfile, "\n"); } long args_long(char * str, const char * option) { char * endptr; long temp = strtol(str, & endptr, 10); if (*endptr) fatal("Invalid numeric argument for option %s", option); return temp; } void args_show() { cpu_features_show(); fprintf(logfile, "Database file: %s\n", databasename ? databasename : "(stdin)"); fprintf(logfile, "Output file: %s\n", outfilename ? outfilename : "(stdout)"); if (statsfilename) fprintf(logfile, "Statistics file: %s\n", statsfilename); if (uclustfilename) fprintf(logfile, "Uclust file: %s\n", uclustfilename); fprintf(logfile, "Resolution (d): %ld\n", resolution); fprintf(logfile, "Threads: %lu\n", threads); fprintf(logfile, "Scores: match: %ld, mismatch: %ld\n", matchscore, mismatchscore); fprintf(logfile, "Gap penalties: opening: %ld, extension: %ld\n", gapopen, gapextend); fprintf(logfile, "Converted costs: mismatch: %ld, gap opening: %ld, gap extension: %ld\n", penalty_mismatch, penalty_gapopen, penalty_gapextend); fprintf(logfile, "Break OTUs: %s\n", opt_no_otu_breaking ? "No" : "Yes"); if (opt_fastidious) fprintf(logfile, "Fastidious: Yes, with boundary %ld\n", opt_boundary); else fprintf(logfile, "Fastidious: No\n"); } void args_usage() { /* 0 1 2 3 4 5 6 7 */ /* 01234567890123456789012345678901234567890123456789012345678901234567890123456789 */ fprintf(stderr, "Usage: swarm [OPTIONS] [filename]\n"); fprintf(stderr, " -b, --boundary INTEGER min mass of large OTU for fastidious (3)\n"); fprintf(stderr, " -c, --ceiling INTEGER max memory in MB used for fastidious\n"); fprintf(stderr, " -d, --differences INTEGER resolution (1)\n"); fprintf(stderr, " -f, --fastidious link nearby low-abundance swarms\n"); fprintf(stderr, " -h, --help display this help and exit\n"); fprintf(stderr, " -n, --no-otu-breaking never break OTUs\n"); fprintf(stderr, " -t, --threads INTEGER number of threads to use (1)\n"); fprintf(stderr, " -v, --version display version information and exit\n"); fprintf(stderr, " -y, --bloom-bits INTEGER bits used per Bloom filter entry (16)\n"); fprintf(stderr, "Input/output options:\n"); fprintf(stderr, " -a, --append-abundance INTEGER value to use when abundance is missing\n"); fprintf(stderr, " -i, --internal-structure FILENAME write internal swarm structure to file\n"); fprintf(stderr, " -l, --log FILENAME log to file, not to stderr\n"); fprintf(stderr, " -o, --output-file FILENAME output result filename (stdout)\n"); fprintf(stderr, " -r, --mothur output in mothur list file format\n"); fprintf(stderr, " -s, --statistics-file FILENAME dump swarm statistics to file\n"); fprintf(stderr, " -u, --uclust-file FILENAME output in UCLUST-like format to file\n"); fprintf(stderr, " -w, --seeds FILENAME write seed seqs with abundances to FASTA\n"); fprintf(stderr, " -z, --usearch-abundance abundance annotation in usearch style\n"); fprintf(stderr, "Pairwise alignment advanced options:\n"); fprintf(stderr, " -m, --match-reward INTEGER reward for nucleotide match (5)\n"); fprintf(stderr, " -p, --mismatch-penalty INTEGER penalty for nucleotide mismatch (4)\n"); fprintf(stderr, " -g, --gap-opening-penalty INTEGER gap open penalty (12)\n"); fprintf(stderr, " -e, --gap-extension-penalty INTEGER gap extension penalty (4)\n"); fprintf(stderr, "\n"); fprintf(stderr, "See 'man swarm' for more details.\n"); } void show_header() { char title[] = "Swarm " SWARM_VERSION; char ref[] = "Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe"; char url[] = "https://github.com/torognes/swarm"; fprintf(logfile, "%s [%s %s]\n%s\n%s\n\n", title, __DATE__, __TIME__, ref, url); fprintf(logfile, "Please cite: Mahe F, Rognes T, Quince C, de Vargas C, Dunthorn M (2014)\n"); fprintf(logfile, "Swarm: robust and fast clustering method for amplicon-based studies.\n"); fprintf(logfile, "PeerJ 2:e593 https://dx.doi.org/10.7717/peerj.593\n"); fprintf(logfile, "\n"); } void args_init(int argc, char **argv) { /* Set defaults */ progname = argv[0]; databasename = NULL; outfilename = NULL; statsfilename = NULL; resolution = DEFAULT_RESOLUTION; threads = DEFAULT_THREADS; matchscore = DEFAULT_MATCHSCORE; mismatchscore = DEFAULT_MISMATCHSCORE; gapopen = DEFAULT_GAPOPEN; gapextend = DEFAULT_GAPEXTEND; mothur = DEFAULT_MOTHUR; usearch_abundance = DEFAULT_USEARCH_ABUNDANCE; opt_log = DEFAULT_LOG; opt_internal_structure = DEFAULT_INTERNAL_STRUCTURE; opt_no_otu_breaking = DEFAULT_NO_OTU_BREAKING; opt_fastidious = DEFAULT_FASTIDIOUS; opt_boundary = DEFAULT_BOUNDARY; opt_bloom_bits = 16; opt_seeds = 0; opt_ceiling = 0; opt_append_abundance = 0; opterr = 1; char short_options[] = "d:ho:t:vm:p:g:e:s:u:rzi:l:nfb:w:y:c:a:"; static struct option long_options[] = { {"differences", required_argument, NULL, 'd' }, {"help", no_argument, NULL, 'h' }, {"output-file", required_argument, NULL, 'o' }, {"threads", required_argument, NULL, 't' }, {"version", no_argument, NULL, 'v' }, {"match-reward", required_argument, NULL, 'm' }, {"mismatch-penalty", required_argument, NULL, 'p' }, {"gap-opening-penalty", required_argument, NULL, 'g' }, {"gap-extension-penalty", required_argument, NULL, 'e' }, {"statistics-file", required_argument, NULL, 's' }, {"uclust-file", required_argument, NULL, 'u' }, {"mothur", no_argument, NULL, 'r' }, {"usearch-abundance", no_argument, NULL, 'z' }, {"internal-structure", required_argument, NULL, 'i' }, {"log", required_argument, NULL, 'l' }, {"no-otu-breaking", no_argument, NULL, 'n' }, {"fastidious", no_argument, NULL, 'f' }, {"boundary", required_argument, NULL, 'b' }, {"seeds", required_argument, NULL, 'w' }, {"bloom-bits", required_argument, NULL, 'y' }, {"ceiling", required_argument, NULL, 'c' }, {"append-abundance", required_argument, NULL, 'a' }, { 0, 0, 0, 0 } }; int option_index = 0; int c; while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { switch(c) { case 'd': /* differences (resolution) */ resolution = args_long(optarg, "-d or --differences"); break; case 'h': /* help */ show_header(); args_usage(); exit(1); break; case 'o': /* output-file */ outfilename = optarg; break; case 't': /* threads */ threads = args_long(optarg, "-t or --threads"); break; case 'v': /* version */ show_header(); exit(1); break; case 'm': /* match-reward */ matchscore = args_long(optarg, "-m or --match-reward"); break; case 'p': /* mismatch-penalty */ mismatchscore = - args_long(optarg, "-p or --mismatch-penalty"); break; case 'g': /* gap-opening-penalty */ gapopen = args_long(optarg, "-g or --gap-opening-penalty"); break; case 'e': /* gap extension penalty */ gapextend = args_long(optarg, "-e or --gap-extension-penalty"); break; case 's': /* statistics-file */ statsfilename = optarg; break; case 'u': /* uclust-file */ uclustfilename = optarg; break; case 'r': /* mothur */ mothur = 1; break; case 'z': /* usearch-abundance */ usearch_abundance = 1; break; case 'i': /* internal-structure */ opt_internal_structure = optarg; break; case 'l': /* log */ opt_log = optarg; break; case 'n': /* no-otu-breaking */ opt_no_otu_breaking = 1; break; case 'f': /* fastidious */ opt_fastidious = 1; break; case 'b': /* boundary */ opt_boundary = args_long(optarg, "-b or --boundary"); break; case 'w': /* seeds */ opt_seeds = optarg; break; case 'y': /* bloom-bits */ opt_bloom_bits = args_long(optarg, "-y or --bloom-bits"); break; case 'c': /* ceiling */ opt_ceiling = args_long(optarg, "-c or --ceiling"); break; case 'a': /* append-abundance */ opt_append_abundance = args_long(optarg, "-a or --append-abundance"); break; default: show_header(); args_usage(); exit(1); break; } } if (optind < argc) databasename = argv[optind]; if (resolution < 0) fatal("Illegal resolution specified."); if ((threads < 1) || (threads > MAX_THREADS)) fatal("Illegal number of threads specified"); if ((gapopen < 0) || (gapextend < 0) || ((gapopen + gapextend) < 1)) fatal("Illegal gap penalties specified."); if (matchscore < 1) fatal("Illegal match reward specified."); if (mismatchscore > -1) fatal("Illegal mismatch penalty specified."); if ((opt_bloom_bits < 2) || (opt_bloom_bits > 64)) fatal("Illegal number of Bloom filter bits specified (must be 2..64)."); if (opt_ceiling < 0) fatal("Illegal memory ceiling"); if (opt_append_abundance < 0) fatal("Illegal abundance value specified"); if (outfilename) { outfile = fopen(outfilename, "w"); if (! outfile) fatal("Unable to open output file for writing."); } else outfile = stdout; if (opt_seeds) { fp_seeds = fopen(opt_seeds, "w"); if (! fp_seeds) fatal("Unable to open seeds file for writing."); } else fp_seeds = 0; if (statsfilename) { statsfile = fopen(statsfilename, "w"); if (! statsfile) fatal("Unable to open statistics file for writing."); } else statsfile = 0; if (uclustfilename) { uclustfile = fopen(uclustfilename, "w"); if (! uclustfile) fatal("Unable to open uclust file for writing."); } else uclustfile = 0; if (opt_log) { logfile = fopen(opt_log, "w"); if (! logfile) fatal("Unable to open log file for writing."); } else logfile = stderr; if (opt_internal_structure) { internal_structure_file = fopen(opt_internal_structure, "w"); if (! internal_structure_file) fatal("Unable to open internal structure file for writing."); } else internal_structure_file = stderr; if (opt_fastidious && (resolution != 1)) fatal("The fastidious option only works when the resolution (d) is 1.\n"); } int main(int argc, char** argv) { cpu_features_detect(); if (!sse2_present) fatal("This program requires a processor with SSE2 instructions.\n"); args_init(argc, argv); penalty_mismatch = 2 * matchscore - 2 * mismatchscore; penalty_gapopen = 2 * gapopen; penalty_gapextend = 2 * matchscore + gapextend; penalty_factor = gcd(gcd(penalty_mismatch, penalty_gapopen), penalty_gapextend); penalty_mismatch /= penalty_factor; penalty_gapopen /= penalty_factor; penalty_gapextend /= penalty_factor; show_header(); args_show(); fprintf(logfile, "\n"); db_read(databasename); fprintf(logfile, "Database info: %lu nt", db_getnucleotidecount()); fprintf(logfile, " in %lu sequences,", db_getsequencecount()); fprintf(logfile, " longest %lu nt\n", db_getlongestsequence()); dbsequencecount = db_getsequencecount(); score_matrix_init(); search_begin(); switch (resolution) { case 0: dereplicate(); break; case 1: algo_d1_run(); break; default: algo_run(); break; } search_end(); score_matrix_free(); db_free(); if (opt_seeds) fclose(fp_seeds); if (uclustfile) fclose(uclustfile); if (statsfile) fclose(statsfile); if (outfilename) fclose(outfile); } swarm-2.1.6/src/swarm.h000066400000000000000000000213731263351160000147450ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include #include #include #include #include #include #include #include #include #include #ifdef __APPLE__ #include #else #include #endif #ifdef __SSE2__ #include #endif #ifdef __SSSE3__ #include #endif /* constants */ #ifndef LINE_MAX #define LINE_MAX 2048 #endif #define SWARM_VERSION "2.1.6" #define WIDTH 32 #define WIDTH_SHIFT 5 #define BLOCKWIDTH 32 #define MAX_THREADS 256 #define SEPCHAR ' ' #ifdef BIASED #define ZERO 0x00 #else #define ZERO 0x80 #endif #ifndef MIN #define MIN(x,y) ((x)<(y)?(x):(y)) #endif #define QGRAMLENGTH 5 #define QGRAMVECTORBITS (1<<(2*QGRAMLENGTH)) #define QGRAMVECTORBYTES (QGRAMVECTORBITS/8) /* structures and data types */ typedef unsigned int UINT32; typedef unsigned short WORD; typedef unsigned char BYTE; typedef BYTE VECTOR[16]; typedef unsigned char qgramvector_t[QGRAMVECTORBYTES]; struct seqinfo_s { char * header; char * seq; unsigned int headerlen; unsigned int headeridlen; unsigned int seqlen; unsigned int abundance; unsigned int clusterid; unsigned int hdrhash; int abundance_start; int abundance_end; }; typedef struct seqinfo_s seqinfo_t; extern seqinfo_t * seqindex; extern qgramvector_t * qgrams; struct queryinfo { unsigned long qno; long len; char * seq; }; typedef struct queryinfo queryinfo_t; /* common data */ extern char * queryname; extern char * matrixname; extern long gapopen; extern long gapextend; extern long gapopenextend; extern long matchscore; extern long mismatchscore; extern unsigned long threads; extern char * databasename; extern long resolution; extern long mothur; extern long usearch_abundance; extern char map_ncbi_nt4[]; extern char map_ncbi_nt16[]; extern char map_ncbi_aa[]; extern char map_sound[]; extern long penalty_factor; extern long penalty_gapextend; extern long penalty_gapopen; extern long penalty_mismatch; extern FILE * outfile; extern FILE * statsfile; extern FILE * uclustfile; extern FILE * internal_structure_file; extern FILE * logfile; extern FILE * fp_seeds; extern char * opt_log; extern char * opt_internal_structure; extern char * opt_seeds; extern long opt_no_otu_breaking; extern long opt_fastidious; extern long opt_boundary; extern long opt_bloom_bits; extern long opt_ceiling; extern long opt_append_abundance; extern long SCORELIMIT_7; extern long SCORELIMIT_8; extern long SCORELIMIT_16; extern long SCORELIMIT_32; extern long SCORELIMIT_63; extern char BIAS; extern long mmx_present; extern long sse_present; extern long sse2_present; extern long sse3_present; extern long ssse3_present; extern long sse41_present; extern long sse42_present; extern long popcnt_present; extern long avx_present; extern long avx2_present; extern unsigned char * score_matrix_8; extern unsigned short * score_matrix_16; extern long * score_matrix_63; extern char sym_nt[]; extern unsigned long longestdbsequence; extern queryinfo_t query; /* functions in util.cc */ long gcd(long a, long b); void fatal(const char * msg); void fatal(const char * format, const char * message); void * xmalloc(size_t size); void * xrealloc(void * ptr, size_t size); char * xstrchrnul(char *s, int c); unsigned long hash_fnv_1a_64(unsigned char * s, unsigned long n); unsigned int hash_fnv_1a_32(unsigned char * s, unsigned long n); unsigned long hash_djb2(unsigned char * s, unsigned long n); unsigned long hash_djb2a(unsigned char * s, unsigned long n); unsigned long hash_cityhash64(unsigned char * s, unsigned long n); void progress_init(const char * prompt, unsigned long size); void progress_update(unsigned long progress); void progress_done(); /* functions in qgram.cc */ void findqgrams(unsigned char * seq, unsigned long seqlen, unsigned char * qgramvector); unsigned long qgram_diff(unsigned long a, unsigned long b); void qgram_diff_fast(unsigned long seed, unsigned long listlen, unsigned long * amplist, unsigned long * difflist); void qgram_diff_init(); void qgram_diff_done(); /* functions in db.cc */ void db_read(const char * filename); unsigned long db_getsequencecount(); unsigned long db_getnucleotidecount(); unsigned long db_getlongestheader(); unsigned long db_getlongestsequence(); seqinfo_t * db_getseqinfo(unsigned long seqno); char * db_getsequence(unsigned long seqno); unsigned long db_getsequencelen(unsigned long seqno); void db_getsequenceandlength(unsigned long seqno, char ** address, long * length); char * db_getheader(unsigned long seqno); unsigned long db_getheaderlen(unsigned long seqno); unsigned long db_getabundance(unsigned long seqno); void db_showsequence(unsigned long seqno); void db_showall(); void db_free(); void db_putseq(long seqno); void db_qgrams_init(); void db_qgrams_done(); void db_fprintseq(FILE * fp, int a, int width); inline unsigned char * db_getqgramvector(unsigned long seqno) { return (unsigned char*)(qgrams + seqno); } void fprint_id(FILE * stream, unsigned long x); void fprint_id_noabundance(FILE * stream, unsigned long x); void fprint_id_with_new_abundance(FILE * stream, unsigned long seqno, unsigned long abundance); /* functions in ssse3.cc */ void dprofile_shuffle8(BYTE * dprofile, BYTE * score_matrix, BYTE * dseq_byte); void dprofile_shuffle16(WORD * dprofile, WORD * score_matrix, BYTE * dseq_byte); /* functions in search8.cc */ void search8(BYTE * * q_start, BYTE gap_open_penalty, BYTE gap_extend_penalty, BYTE * score_matrix, BYTE * dprofile, BYTE * hearray, unsigned long sequences, unsigned long * seqnos, unsigned long * scores, unsigned long * diffs, unsigned long * alignmentlengths, unsigned long qlen, unsigned long dirbuffersize, unsigned long * dirbuffer); /* functions in search16.cc */ void search16(WORD * * q_start, WORD gap_open_penalty, WORD gap_extend_penalty, WORD * score_matrix, WORD * dprofile, WORD * hearray, unsigned long sequences, unsigned long * seqnos, unsigned long * scores, unsigned long * diffs, unsigned long * alignmentlengths, unsigned long qlen, unsigned long dirbuffersize, unsigned long * dirbuffer); /* functions in nw.cc */ void nw(char * dseq, char * dend, char * qseq, char * qend, long * score_matrix, unsigned long gapopen, unsigned long gapextend, unsigned long * nwscore, unsigned long * nwdiff, unsigned long * nwalignmentlength, char ** nwalignment, unsigned char * dir, unsigned long * hearray, unsigned long queryno, unsigned long dbseqno); /* functions in matrix.cc */ void score_matrix_init(); void score_matrix_free(); /* functions in scan.cc */ void search_all(unsigned long query_no); void search_do(unsigned long query_no, unsigned long listlength, unsigned long * targets, unsigned long * scores, unsigned long * diffs, unsigned long * alignlengths, long bits); void search_begin(); void search_end(); /* functions in algo.cc */ void algo_run(); void algo_d1_run(); /* functions in derep.cc */ void dereplicate(); /* functions in arch.cc */ unsigned long arch_get_memused(); unsigned long arch_get_memtotal(); /* new header files */ #include "bitmap.h" #include "bloom.h" #include "threads.h" swarm-2.1.6/src/threads.h000066400000000000000000000076631263351160000152540ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2015 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ class ThreadRunner { private: long thread_count; pthread_attr_t attr; struct thread_s { long t; void (*fun)(long t); pthread_t pthread; pthread_mutex_t workmutex; pthread_cond_t workcond; int work; /* 1: work available, 0: wait, -1: quit */ } * thread_array; static void * worker(void * vp) { struct thread_s * tip = (struct thread_s *) vp; pthread_mutex_lock(&tip->workmutex); /* loop until signalled to quit */ while (tip->work >= 0) { /* wait for work available */ if (tip->work == 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); if (tip->work > 0) { (*tip->fun)(tip->t); tip->work = 0; pthread_cond_signal(&tip->workcond); } } pthread_mutex_unlock(&tip->workmutex); return 0; } public: ThreadRunner(int t, void (*f)(long t)) { thread_count = t; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* allocate memory for thread data */ thread_array = (struct thread_s *) xmalloc(thread_count * sizeof(struct thread_s)); /* init and create worker threads */ for(long i=0; it = i; tip->work = 0; tip->fun = f; pthread_mutex_init(&tip->workmutex, NULL); pthread_cond_init(&tip->workcond, NULL); if (pthread_create(&tip->pthread, &attr, worker, (void*)(thread_array + i))) fatal("Cannot create thread"); } } ~ThreadRunner() { /* ask threads to quit */ /* sleep until they have quit */ /* destroy threads */ /* finish and clean up worker threads */ for(long i=0; iworkmutex); tip->work = -1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); /* wait for worker to quit */ if (pthread_join(tip->pthread, NULL)) fatal("Cannot join thread"); pthread_cond_destroy(&tip->workcond); pthread_mutex_destroy(&tip->workmutex); } free(thread_array); pthread_attr_destroy(&attr); } void run() { /* wake up threads */ for(long i=0; iworkmutex); tip->work = 1; pthread_cond_signal(&tip->workcond); pthread_mutex_unlock(&tip->workmutex); } /* wait for threads to finish their work */ for(long i=0; iworkmutex); while (tip->work > 0) pthread_cond_wait(&tip->workcond, &tip->workmutex); pthread_mutex_unlock(&tip->workmutex); } } }; swarm-2.1.6/src/util.cc000066400000000000000000000100621263351160000147200ustar00rootroot00000000000000/* SWARM Copyright (C) 2012-2014 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Contact: Torbjorn Rognes , Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" static const char * progress_prompt; static unsigned long progress_next; static unsigned long progress_size; static unsigned long progress_chunk; static const unsigned long progress_granularity = 200; void progress_init(const char * prompt, unsigned long size) { progress_prompt = prompt; progress_size = size; progress_chunk = size < progress_granularity ? 1 : size / progress_granularity; progress_next = 0; if (opt_log) fprintf(logfile, "%s", prompt); else fprintf(logfile, "%s %.0f%%", prompt, 0.0); } void progress_update(unsigned long progress) { if ((!opt_log) && (progress >= progress_next)) { fprintf(logfile, " \r%s %.0f%%", progress_prompt, 100.0 * progress / progress_size); progress_next = progress + progress_chunk; } } void progress_done() { if (opt_log) fprintf(logfile, " %.0f%%\n", 100.0); else fprintf(logfile, " \r%s %.0f%%\n", progress_prompt, 100.0); } long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } void fatal(const char * msg) { fprintf(stderr, "Error: %s\n", msg); exit(1); } void fatal(const char * format, const char * message) { fprintf(stderr, format, message); fprintf(stderr, "\n"); exit(1); } void * xmalloc(size_t size) { const size_t alignment = 16; void * t = NULL; if (posix_memalign(& t, alignment, size)) fatal("Unable to allocate enough memory."); if (!t) fatal("Unable to allocate enough memory."); return t; } void * xrealloc(void *ptr, size_t size) { void * t = realloc(ptr, size); if (!t) fatal("Unable to allocate enough memory."); return t; } char * xstrchrnul(char *s, int c) { char * r = strchr(s, c); if (r) return r; else return (char *)s + strlen(s); } unsigned long hash_fnv_1a_64(unsigned char * s, unsigned long n) { const unsigned long fnv_offset = 14695981039346656037UL; const unsigned long fnv_prime = 1099511628211; /* 2^40 - 435 */ unsigned long hash = fnv_offset; for(unsigned long i = 0; i < n; i++) { unsigned char c = *s++; hash = (hash ^ c) * fnv_prime; } return hash; } unsigned int hash_fnv_1a_32(unsigned char * s, unsigned long n) { const unsigned int fnv_offset = 2166136261; const unsigned int fnv_prime = 16777619; unsigned int hash = fnv_offset; for(unsigned long i = 0; i < n; i++) { unsigned char c = *s++; hash = (hash ^ c) * fnv_prime; } return hash; } unsigned long hash_djb2(unsigned char * s, unsigned long n) { const unsigned long djb2_offset = 5381; unsigned long hash = djb2_offset; for(unsigned long i = 0; i < n; i++) { unsigned char c = *s++; hash = ((hash << 5) + hash) + c; /* hash = hash * 33 + c */ } return hash; } unsigned long hash_djb2a(unsigned char * s, unsigned long n) { const unsigned long djb2_offset = 5381; unsigned long hash = djb2_offset; for(unsigned long i = 0; i < n; i++) { unsigned char c = *s++; hash = ((hash << 5) + hash) ^ c; /* hash = hash * 33 ^ c */ } return hash; } unsigned long hash_cityhash64(unsigned char * s, unsigned long n) { return CityHash64((const char*)s, n); }