pax_global_header00006660000000000000000000000064123700122620014505gustar00rootroot0000000000000052 comment=304e456baea2696e85b866752dd10984668f603d FLASH-1.2.11/000077500000000000000000000000001237001226200124245ustar00rootroot00000000000000FLASH-1.2.11/COPYING000066400000000000000000001045131237001226200134630ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . FLASH-1.2.11/Makefile000066400000000000000000000010411237001226200140600ustar00rootroot00000000000000# # Makefile for FLASH. Process this using GNU make by simply running # # $ make # # You may set CPPFLAGS, LDFLAGS, or CC in the environment if you would like to # use a non-default compiler, extra preprocessor flags (e.g. to find headers), # or extra linker flags (e.g. to find libraries). CFLAGS += -O2 -Wall -std=c99 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 LDLIBS := -lz -lpthread OBJ := combine_reads.o flash.o iostream.o read_io.o read_queue.o read_util.o util.o EXE := flash $(EXE):$(OBJ) clean: rm -f $(OBJ) $(EXE) .PHONY: clean FLASH-1.2.11/NEWS000066400000000000000000000155061237001226200131320ustar00rootroot00000000000000Version 1.2.11 -------------- - Fixed a bug that caused FLASH to crash under the following set of circumstances: the --allow-outies option (added in v1.2.10) was specified; and in a read pair, read 1 was longer than read 2; and the chosen merge aligned the end of read 2 to the very beginning of read 1, e.g. Read 1: -----------------------------------> Read 2: <------------------------- This bug was extremely likely to crash the program. Therefore, the output of successful runs of FLASH should not have been affected. Version 1.2.10 -------------- - FLASH now supports combining read pairs in outie orientation. See help for the new --allow-outies option. - Added warning messages in a few cases where it may be helpful to specify different parameters. Version 1.2.9 ------------------- - The core algorithm of FLASH has been optimized using SSE and SSE2 instructions. On x86_64 CPUs it now can run over twice as fast. - The help output of FLASH has been improved. - Added supported for tab-delimited input and output. - FLASH now displays more informative error messages in some cases. - Reorganized some of the code so that it's easier to modify. - Reading the data from standard input now works correctly. - With --to-stdout specified, informational messages are now written to standard error rather than omitted. Version 1.2.8 ------------------- - FLASH's default behavior when assigning quality scores to mismatch sites in the overlap region of combined reads has been improved. See the documentation for the new --cap-mismatch-quals option (which can be provided to request the old behavior if desired) for more information about this change. Version 1.2.7 ------------------- - FLASH is now supported on Windows. See the README. - Minor bug-fixes regarding printing of error messages. - Fixed a bug where the time that FLASH took to run may have been mis-calculated on 32-bit systems in an unlikely case. This only affected the printed informational output. - Updated PERFORMANCE section in README to be accurate for the current version of FLASH. Version 1.2.6 ------------------- - FLASH now works on files larger than 2GiB on 32-bit operating systems, unless the system zlib library does not support such files. 64-bit operating systems are unaffected as they already supported large files by default. Version 1.2.5 ------------------- - FLASH will now compile and run on Mac OS X. Version 1.2.4 ------------------- - Support for piping the output of FLASH through arbitrary compression programs has been added via the --compress-prog option. The --compress-prog-args and/or --output-suffix options also may be useful. - FLASH with the --interleaved option will now use an interleaved output format in addition to assuming interleaved input. Use --interleaved-input or --interleaved-output to specify only interleaved input or only interleaved output, respectively. - The entirely single-threaded configuration of FLASH is no longer supported. You can still use --threads=1 to use only 1 combiner thread, however. Version 1.2.3 ------------------- - Support for interleaved reads (-I, --interleaved), which may be read from one FASTQ file or piped in from stdin - Fix --read-len option - Fix default --fragment-len-stddev option - Fix reading FASTQ files with embedded zero bytes - Fix memory leaks - Added license file Version 1.2.2 ------------------- - Fix linking problem in Makefile Version 1.2.1 ------------------- - There is no longer any read length or tag length limit, although you may still specify the --read-len parameter for the purpose of automatically computing the maximum overlap. - FLASH now prints some informational output while it's running, unless running with --quiet or --to-stdout. Version 1.2 ------------------- - Support for writing extended fragments directly to standard output. - Support for writing compressed output files. - Support for multithreading. There are multiple I/O threads as well as multiple combiner threads. Speedup of 3.6 times has been observed. Compiling without support for multithreading is still supported. Version 1.1 ------------------- Rewrote the entire program. - Removed at least 3 instances of undefined behavior (such as using uninitialized variables). - Performance improvements. Neglecting I/O, the program now runs over twice as fast. This improvement is not due to a change in algorithm; I expect it is due mainly to the rewritten align_position() function. - Use getopt_long() for option parsing. Now, long options are accepted, and options do not have to be given after the mate pair FASTQ files. - Removed many fixed-size buffers. This saves memory, removes many buffer overflow problems, and removes the READ_LENGTH parameter. Note: the maximum tag length is still hard-coded as 1024 bytes. - Much more error checking, so the program will cleanly fail if something goes wrong. - Use a Makefile instead of a shell script. - The '.histogram' file is written a bit more narrowly (80 columns), but other than that, the output of the program should be the same (unless it was affected by any of the cases of undefined behavior I found). - Some changes to the MANUAL, although I didn't feel like changing the information that is redundant with the program help. - Note: I am calling this version 1.1, but feel free to call it something else. The version number is also listed in the version() function in flash.c. Version v1.0.3 -------------- 1. FLASH allows reads files to be in gzip format. 2. FLASH builds a histogram of fragment lengths produced by merged read pairs. 3. FLASH now allows for reads longer than 170bp to be processed (READ_LENGTH is utilities.h file still needs to be changed manually to the read length if it is greater than 170). 4. If original reads' ID contains barcode, the barcode is kept as a part of the ID in the output fragments. Version v1.0.2 -------------- Fixed bugs: 1. In combine function in combineReads.c: modified selection of the base when quality values of bases are the same. Instead of random selection of the base, first check whether any base is "N" to avoid selection of "N" if not necessary. Added options for easier handling of the program: 1. Added error messages in case no input files and no parameters are specified. 2. Added the parameter to print 'help' for running the program. 3. Added the option to specify prefix of the output files. 4. Added the option to specify directory of the output files. Functional changes: 1. Changed read length to 170. 2. Automatic calculation of maximum overlap length given average read length, average fragment length, and fragment standard deviation. Version v1.0.1 -------------- Fixed bugs: 1. In align_position function in combineReads.c: added the line *score=10001 when readLength2 < overlap. 2. idSet function in utilities.c: added the part of the condition to end reading the line of file1[0] if '\n' is found. FLASH-1.2.11/README000066400000000000000000000111601237001226200133030ustar00rootroot00000000000000 INTRODUCTION FLASH (Fast Length Adjustment of SHort reads) is an accurate and fast tool to merge paired-end reads that were generated from DNA fragments whose lengths are shorter than twice the length of reads. Merged read pairs result in unpaired longer reads, which are generally more desired in genome assembly and genome analysis processes. Briefly, the FLASH algorithm considers all possible overlaps at or above a minimum length between the reads in a pair and chooses the overlap that results in the lowest mismatch density (proportion of mismatched bases in the overlapped region). Ties between multiple overlaps are broken by considering quality scores at mismatch sites. When building the merged sequence, FLASH computes a consensus sequence in the overlapped region. More details can be found in the original publication (http://bioinformatics.oxfordjournals.org/content/27/21/2957.full). Limitations of FLASH include: - FLASH cannot merge paired-end reads that do not overlap. - FLASH is not designed for data that has a significant amount of indel errors (such as Sanger sequencing data). It is best suited for Illumina data. INSTALLATION On UNIX-compatible systems, including GNU/Linux and Mac OS X, you must compile FLASH from source. The only dependency, other than functions that are expected to be available in the C library, is the zlib data compression library. To install FLASH, download the tarball, untar it, and compile the code using the provided Makefile: $ tar xzf FLASH-1.2.11.tar.gz $ cd FLASH-1.2.11 $ make The executable file that is produced is named 'flash'. To run it from the command line you must copy it to a location on your $PATH variable, or else run it with a path including a directory, such as "./flash". FLASH also runs on Windows, and you can compile it on Windows using MinGW. However, for convenience you may instead download a standalone Windows binary from the SourceForge page (https://sourceforge.net/projects/flashpage/). USAGE Please compile FLASH and run `flash --help' to see command-line usage information and information about input/output files. MULTITHREADING By default, FLASH uses multiple threads. There are "combiner" threads that do the actual read combining, as well as up to 5 threads that are used for I/O (up to 2 readers, up to 3 writers). The default number of combiner threads is the number of processors; however, it can be adjusted with the -t option (long option: --threads). When multiple combiner threads are used, the order of the combined and uncombined reads in the output files will be nondeterministic. If you need to enforce that the output reads appear in the same order as the input, you must specify --threads=1. PERFORMANCE Since the FLASH algorithm considers each read pair independently, FLASH will, by default, process read pairs in parallel. FLASH v1.2.9 and later also make use of vector instructions available on modern x86 CPUs. Consequently, FLASH works quite fast, even with low-cost computing resources. As an example, we ran FLASH v1.2.9 on a laptop with a dual-core 2.3 GHz AMD x86_64 processor and it processed one million 101-bp read pairs in 11.6 seconds with the default parameters. Less than 2 MB of memory was used. Actual timing results will vary, but they will depend primarily on the number of CPUs available, the speed of each CPU, and on the I/O speed of reading the input files and writing the output files. FLASH is designed to be scalable to dozens of processors, although its speed may be limited by I/O in such cases. ACCURACY With reads' error rate of 1% or less, FLASH processes over 99% of read pairs correctly. With error rate of 2%, FLASH processes over 98% of read pairs correctly when default parameters are used. With more aggressive parameters (i.e., -x 0.35), FLASH processes over 90% of read pairs correctly even when the error rate is 5%. PUBLICATION Title: FLASH: fast length adjustment of short reads to improve genome assemblies Authors: Tanja Magoč and Steven L. Salzberg URL: http://bioinformatics.oxfordjournals.org/content/27/21/2957.full LICENSE FLASH is released under the GNU General Public License Version 3 or later (see COPYING). COMMENTS/QUESTIONS/REQUESTS Send an e-mail to flash.comment@gmail.com Other versions are available from the SourceForge page: https://sourceforge.net/projects/flashpage/ FLASH-1.2.11/combine_reads.c000066400000000000000000000367401237001226200153740ustar00rootroot00000000000000/* * combine_reads.c: This file contains the code implementing the core algorithm * to combine reads in FLASH. */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include "combine_reads.h" #include "read.h" #include "util.h" #include #include #include #include #if defined(__GNUC__) && defined(__SSE2__) # define WITH_SSE2 #endif #ifdef WITH_SSE2 # include # include #endif #ifdef WITH_SSE2 /* Sum the values an 8 x 8 bit vector and return a 32-bit result. */ static inline uint32_t hsum32_v8(__m128i v) { v = _mm_sad_epu8(v, _mm_set1_epi8(0)); return (uint32_t)_mm_extract_epi16(v, 0) + (uint32_t)_mm_extract_epi16(v, 4); } /* Sum the values an 8 x 16 bit vector and return a 32-bit result. */ static inline uint32_t hsum32_v16(__m128i v) { __m128i mask = _mm_set1_epi32(0x0000ffff); v = _mm_add_epi32(v & mask, _mm_srli_si128(v, 2) & mask); v = _mm_add_epi32(v, _mm_srli_si128(v, 4)); v = _mm_add_epi32(v, _mm_srli_si128(v, 8)); return _mm_cvtsi128_si32(v); } #endif /* WITH_SSE2 */ /* * Compute mismatch statistics between two sequences. * * @seq_1, @seq_2: * The two sequences to compare (ASCII characters A, C, G, T, N). * @qual_1, @qual_2: * Quality scores for the two sequences, based at 0. * @haveN * As an optimization, this can be set to %false to indicate that neither * sequence contains an uncalled base (represented as an N character). * @len_p * Pointer to the length of the sequence. This value will be updated to * subtract the number of positions at which an uncalled base (N) exists in * either sequence. * @num_mismatches_ret * Location into which to return the number of positions at which the bases * were mismatched. * @mismatch_qual_total_ret * Location into which to return the sum of lesser quality scores at * mismatch sites. */ static inline void compute_mismatch_stats(const char * restrict seq_1, const char * restrict seq_2, const char * restrict qual_1, const char * restrict qual_2, bool haveN, int * restrict len_p, unsigned * restrict num_mismatches_ret, unsigned * restrict mismatch_qual_total_ret) { int num_uncalled = 0; unsigned num_mismatches = 0; unsigned mismatch_qual_total = 0; int len = *len_p; if (haveN) { for (int i = 0; i < len; i++) { if (seq_1[i] == 'N' || seq_2[i] == 'N') { num_uncalled++; } else { if (seq_1[i] != seq_2[i]) { num_mismatches++; mismatch_qual_total += min(qual_1[i], qual_2[i]); } } } } else { /* This part of the 'if' statement is for optimization purposes * only; its behavior is equivalent to the block above, except * this block assumes there are no N characters in the input, * and therefore no further checks for N's are needed. * * Note: this optimization is only useful if most reads don't * contain N characters. */ #ifdef WITH_SSE2 /* Optional vectorized implementation (about twice as fast as * nonvectorized on x86_64). */ while (len >= 16) { /* 16 x 8 bit counters for number of mismatches */ __m128i num_mismatches_v8 = _mm_set1_epi8(0); /* 8 x 16 bit counters for mismatch quality total */ __m128i mismatch_qual_total_v16 = _mm_set1_epi16(0); /* The counters of num_mismatches_v8 will overflow if * 256 mismatches are detected at the same position * modulo 16 bytes. So, don't process 4096 or more * bytes before reducing the counters. * * mismatch_qual_total_v16 would overflow even faster, * but we use 16-bit counters for it. */ int todo = min(len, 255 * 16) & ~0xf; len -= todo; do { /* Load 16 bases */ __m128i s1_v8 = _mm_loadu_si128((const void *)seq_1); __m128i s2_v8 = _mm_loadu_si128((const void *)seq_2); /* Load 16 quality scores */ __m128i q1_v8 = _mm_loadu_si128((const void *)qual_1); __m128i q2_v8 = _mm_loadu_si128((const void *)qual_2); /* Compare bases with each other and negate the * result. This will produce 0xff in bytes * where the bases differ and 0x00 in bytes * where the bases were the same. */ __m128i cmpresult = ~_mm_cmpeq_epi8(s1_v8, s2_v8); /* Tally mismatched bases. Subtracting 0x00 and * 0xff is equivalent to adding 0 and 1, * respectively. */ num_mismatches_v8 = _mm_sub_epi8(num_mismatches_v8, cmpresult); /* Tally quality scores for mismatched bases. */ /* Get minimum of each quality score. */ __m128i qmin_v8 = _mm_min_epu8(q1_v8, q2_v8); /* Select only quality scores at mismatch sites */ __m128i qadd_v8 = qmin_v8 & cmpresult; /* Double the precision (8 => 16 bits) and tally */ __m128i qadd_v16_1 = _mm_unpacklo_epi8(qadd_v8, _mm_set1_epi8(0)); __m128i qadd_v16_2 = _mm_unpackhi_epi8(qadd_v8, _mm_set1_epi8(0)); mismatch_qual_total_v16 = _mm_add_epi16(mismatch_qual_total_v16, qadd_v16_1); mismatch_qual_total_v16 = _mm_add_epi16(mismatch_qual_total_v16, qadd_v16_2); /* Advance pointers */ seq_1 += 16, seq_2 += 16; qual_1 += 16, qual_2 += 16; todo -= 16; } while (todo); /* Reduce the counters. */ num_mismatches += hsum32_v8(num_mismatches_v8); mismatch_qual_total += hsum32_v16(mismatch_qual_total_v16); } #endif /* WITH_SSE2 */ #if 0 /* Verify the values computed by the vectorized implementation. */ { int veclen = *len_p & ~0xf; const char *_seq_1 = seq_1 - veclen; const char *_seq_2 = seq_2 - veclen; const char *_qual_1 = qual_1 - veclen; const char *_qual_2 = qual_2 - veclen; unsigned _num_mismatches = 0; unsigned _mismatch_qual_total = 0; for (int i = 0; i < veclen; i++) { if (_seq_1[i] != _seq_2[i]) { _num_mismatches++; _mismatch_qual_total += min(_qual_1[i], _qual_2[i]); } } assert(num_mismatches == _num_mismatches); assert(mismatch_qual_total == _mismatch_qual_total); } #endif /* Process any remainder that wasn't processed by the vectorized * implementation. */ for (int i = 0; i < len; i++) { if (seq_1[i] != seq_2[i]) { num_mismatches++; mismatch_qual_total += min(qual_1[i], qual_2[i]); } } } /* Return results in pointer arguments */ *num_mismatches_ret = num_mismatches; *mismatch_qual_total_ret = mismatch_qual_total; *len_p -= num_uncalled; } #define NO_ALIGNMENT INT_MIN static inline int pair_align(const struct read *read_1, const struct read *read_2, int min_overlap, int max_overlap, float max_mismatch_density, bool allow_outies, bool * was_outie) { bool haveN = memchr(read_1->seq, 'N', read_1->seq_len) || memchr(read_2->seq, 'N', read_2->seq_len); /* Best (smallest) mismatch density that has been found so far in an * overlap. */ float best_mismatch_density = max_mismatch_density + 1.0f; float best_qual_score = 0.0f; int best_position = NO_ALIGNMENT; bool best_was_outie; bool doing_outie = false; int start; int end; again: /* Require at least min_overlap bases overlap, and require that the * second read is not overlapped such that it is completely contained in * the first read. */ start = max(0, read_1->seq_len - read_2->seq_len); end = read_1->seq_len - min_overlap + 1; for (int i = start; i < end; i++) { unsigned num_mismatches; unsigned mismatch_qual_total; int overlap_len = read_1->seq_len - i; compute_mismatch_stats(read_1->seq + i, read_2->seq, read_1->qual + i, read_2->qual, haveN, &overlap_len, &num_mismatches, &mismatch_qual_total); if (overlap_len >= min_overlap) { float score_len = (float)min(overlap_len, max_overlap); float qual_score = mismatch_qual_total / score_len; float mismatch_density = num_mismatches / score_len; if (mismatch_density <= best_mismatch_density && (mismatch_density < best_mismatch_density || qual_score < best_qual_score)) { best_qual_score = qual_score; best_mismatch_density = mismatch_density; best_position = i; best_was_outie = doing_outie; } } } if (allow_outies) { const struct read *tmp = read_1; read_1 = read_2; read_2 = tmp; allow_outies = false; doing_outie = true; goto again; } if (best_mismatch_density > max_mismatch_density) return NO_ALIGNMENT; *was_outie = best_was_outie; return best_position; } /* Fills in the combined read from the specified alignment. */ static void generate_combined_read(const struct read *read_1, const struct read *read_2, struct read *combined_read, int overlap_begin, bool cap_mismatch_quals) { /* Length of the overlapping part of two reads. */ int overlap_len = read_1->seq_len - overlap_begin; /* Length of the part of the second read not overlapped with the first * read. */ int remaining_len = read_2->seq_len - overlap_len; int combined_seq_len = read_1->seq_len + remaining_len; const char * restrict seq_1 = read_1->seq; const char * restrict seq_2 = read_2->seq; const char * restrict qual_1 = read_1->qual; const char * restrict qual_2 = read_2->qual; char * restrict combined_seq; char * restrict combined_qual; if (combined_read->seq_bufsz < combined_seq_len) { combined_read->seq = xrealloc(combined_read->seq, combined_seq_len); combined_read->seq_bufsz = combined_seq_len; } if (combined_read->qual_bufsz < combined_seq_len) { combined_read->qual = xrealloc(combined_read->qual, combined_seq_len); combined_read->qual_bufsz = combined_seq_len; } combined_seq = combined_read->seq; combined_qual = combined_read->qual; combined_read->seq_len = combined_seq_len; combined_read->qual_len = combined_seq_len; /* Copy the beginning of read 1 (not in the overlapped region). */ while (overlap_begin--) { *combined_seq++ = *seq_1++; *combined_qual++ = *qual_1++; } /* Copy the overlapped region. */ while (overlap_len--) { if (*seq_1 == *seq_2) { /* Same base in both reads. Take the higher quality * value. */ *combined_seq = *seq_1; *combined_qual = max(*qual_1, *qual_2); } else { /* Different bases in the two reads; use the higher * quality one. * * The old way of calculating the resulting quality * value (params->cap_mismatch_quals == %true) is to use * the lower quality value, and use a quality value of * at most 2 (+ phred_offset in the final output--- here * the quality values are all scaled to start at 0). * The motivation for this behavior is that the read * combination shows there was sequencing error at the * mismatch location, so the corresponding base call in * the combined read should be given a low quality * score. * * The new way (params->cap_mismatch_quals == %false, * default as of FLASH v1.2.8) is to use the absolute * value of the difference in quality scores, but at * least 2. This allows a base call with a high quality * score to override a base call with a low quality * score without too much penalty. */ if (cap_mismatch_quals) *combined_qual = min(min(*qual_1, *qual_2), 2); else *combined_qual = max(abs(*qual_1 - *qual_2), 2); if (*qual_1 > *qual_2) { *combined_seq = *seq_1; } else if (*qual_1 < *qual_2) { *combined_seq = *seq_2; } else { /* Same quality value; take the base from the * first read if the base from the second read * is an 'N'; otherwise take the base from the * second read. */ if (*seq_2 == 'N') *combined_seq = *seq_1; else *combined_seq = *seq_2; } } combined_seq++; combined_qual++; seq_1++; seq_2++; qual_1++; qual_2++; } /* Copy the end of read 2 (not in the overlapped region). */ while (remaining_len--) { *combined_seq++ = *seq_2++; *combined_qual++ = *qual_2++; } } /* This is the entry point for the core algorithm of FLASH. The following * function attempts to combine @read_1 with @read_2, and writes the result into * @combined_read. COMBINED_AS_INNIE or COMBINED_AS_OUTIE is returned if * combination was successful. COMBINED_AS_OUTIE is only possible if * params->allow_outies is set. * * Note: @read_2 is provided to this function after having been * reverse-complemented. Hence, the code just aligns the reads in the forward * orientation, which is equivalent to aligning the original reads in the * desired reverse-complement orientation. * * Please see the help output of FLASH for the description of the min_overlap, * max_overlap, and max_mismatch_density parameters. (--min-overlap, * --max-overlap, and --max-mismatch-density on the command line). * * You may also want to read the original FLASH publication for a description of * the algorithm used here: * * Title: FLASH: fast length adjustment of short reads to improve genome assemblies * Authors: Tanja Magoč and Steven L. Salzberg * URL: http://bioinformatics.oxfordjournals.org/content/27/21/2957.full * */ enum combine_status combine_reads(const struct read *read_1, const struct read *read_2, struct read *combined_read, const struct combine_params *params) { int overlap_begin; enum combine_status status; bool was_outie; /* Do the alignment. */ overlap_begin = pair_align(read_1, read_2, params->min_overlap, params->max_overlap, params->max_mismatch_density, params->allow_outies, &was_outie); /* * If overlap_begin == NO_ALIGNMENT, then no sufficient overlap between * the reads was found. * * If !@was_outie, then the pair forms an "innie" overlap, and * overlap_begin is the 0-based position in read_1 at which read_2 * begins. (Shown below with read 2 already reverse complemented!) * * 0 overlap_begin * | | * Read 1: ------------------> * Read 2: ----------------------> * * If @was_outie, then the pair forms an "outie" overlap, and * overlap_begin is the 0-based position in read_2 at which read_1 * begins. (Shown below with read 2 already reverse complemented!) * * 0 overlap_begin * | | * Read 2: ------------------> * Read 1: ----------------------> */ if (overlap_begin == NO_ALIGNMENT) return NOT_COMBINED; if (!was_outie) { status = COMBINED_AS_INNIE; } else { const struct read *tmp; /* Simplify generation of the combined read by turning the outie * case into the innie case. */ tmp = read_1; read_1 = read_2; read_2 = tmp; status = COMBINED_AS_OUTIE; /* * Now it's just: * * 0 overlap_begin * | | * Read 1: ------------------> * Read 2: ----------------------> * * The same as the "innie" case. */ } /* Fill in the combined read. */ generate_combined_read(read_1, read_2, combined_read, overlap_begin, params->cap_mismatch_quals); return status; } FLASH-1.2.11/combine_reads.h000066400000000000000000000023571237001226200153760ustar00rootroot00000000000000#ifndef _FLASH_COMBINE_READS_H_ #define _FLASH_COMBINE_READS_H_ #include struct read; /* Parameters for the core algorithm of FLASH. See the help output for more * information. */ struct combine_params { /* --min-overlap */ int min_overlap; /* --max-overlap */ int max_overlap; /* --max-mismatch-density */ float max_mismatch_density; /* --cap-mismatch-quals */ bool cap_mismatch_quals; /* --allow-outies */ bool allow_outies; }; /* Result of a call to combine_reads() */ enum combine_status { /* The reads could not be combined. */ NOT_COMBINED = 0, /* The reads were combined in "innie" orientation, like the following: * * ----------> * <------------ * * (Note: read_2 is reverse complemented before the call to * combine_reads()). */ COMBINED_AS_INNIE, /* The reads were combined in "outie" orientation, like the following: * * <---------- * ------------> * * (Note: read_2 is reverse complemented before the call to * combine_reads()). */ COMBINED_AS_OUTIE, }; extern enum combine_status combine_reads(const struct read *read_1, const struct read *read_2, struct read *combined_read, const struct combine_params *params); #endif /* _FLASH_COMBINE_READS_H_ */ FLASH-1.2.11/flash.c000066400000000000000000001347371237001226200137040ustar00rootroot00000000000000/* * flash.c: parse arguments and set up and run the FLASH pipeline. * * Please see combine_reads.c if you are looking for the core algorithm used to * combine reads in FLASH. */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include #include #include #include #include #include #include #include #include #include #include "combine_reads.h" #include "iostream.h" #include "read.h" #include "read_io.h" #include "read_queue.h" #include "util.h" #define VERSION_STR "v1.2.11" #ifdef __WIN32__ # define PAGER "more" #else # define PAGER "less" #endif #define TO_PERCENT(n, d) \ ((d) == 0 ? 0 : ((double)(n) * 100 / (d))) static void usage(const char *argv0) { const char *usage_str = "Usage: flash [OPTIONS] MATES_1.FASTQ MATES_2.FASTQ\n" " flash [OPTIONS] --interleaved-input (MATES.FASTQ | -)\n" " flash [OPTIONS] --tab-delimited-input (MATES.TAB | -)\n" "\n" "----------------------------------------------------------------------------\n" " DESCRIPTION \n" "----------------------------------------------------------------------------\n" "\n" "FLASH (Fast Length Adjustment of SHort reads) is an accurate and fast tool\n" "to merge paired-end reads that were generated from DNA fragments whose\n" "lengths are shorter than twice the length of reads. Merged read pairs result\n" "in unpaired longer reads, which are generally more desired in genome\n" "assembly and genome analysis processes.\n" "\n" "Briefly, the FLASH algorithm considers all possible overlaps at or above a\n" "minimum length between the reads in a pair and chooses the overlap that\n" "results in the lowest mismatch density (proportion of mismatched bases in\n" "the overlapped region). Ties between multiple overlaps are broken by\n" "considering quality scores at mismatch sites. When building the merged\n" "sequence, FLASH computes a consensus sequence in the overlapped region.\n" "More details can be found in the original publication\n" "(http://bioinformatics.oxfordjournals.org/content/27/21/2957.full).\n" "\n" "Limitations of FLASH include:\n" " - FLASH cannot merge paired-end reads that do not overlap.\n" " - FLASH is not designed for data that has a significant amount of indel\n" " errors (such as Sanger sequencing data). It is best suited for Illumina\n" " data.\n" "\n" "----------------------------------------------------------------------------\n" " MANDATORY INPUT\n" "----------------------------------------------------------------------------\n" "\n" "The most common input to FLASH is two FASTQ files containing read 1 and read 2\n" "of each mate pair, respectively, in the same order.\n" "\n" "Alternatively, you may provide one FASTQ file, which may be standard input,\n" "containing paired-end reads in either interleaved FASTQ (see the\n" "--interleaved-input option) or tab-delimited (see the --tab-delimited-input\n" "option) format. In all cases, gzip compressed input is autodetected. Also,\n" "in all cases, the PHRED offset is, by default, assumed to be 33; use the\n" "--phred-offset option to change it.\n" "\n" "----------------------------------------------------------------------------\n" " OUTPUT\n" "----------------------------------------------------------------------------\n" "\n" "The default output of FLASH consists of the following files:\n" "\n" " - out.extendedFrags.fastq The merged reads.\n" " - out.notCombined_1.fastq Read 1 of mate pairs that were not merged.\n" " - out.notCombined_2.fastq Read 2 of mate pairs that were not merged.\n" " - out.hist Numeric histogram of merged read lengths.\n" " - out.histogram Visual histogram of merged read lengths.\n" "\n" "FLASH also logs informational messages to standard output. These can also be\n" "redirected to a file, as in the following example:\n" "\n" " $ flash reads_1.fq reads_2.fq 2>&1 | tee flash.log\n" "\n" "In addition, FLASH supports several features affecting the output:\n" "\n" " - Writing the merged reads directly to standard output (--to-stdout)\n" " - Writing gzip compressed output files (-z) or using an external\n" " compression program (--compress-prog)\n" " - Writing the uncombined read pairs in interleaved FASTQ format\n" " (--interleaved-output)\n" " - Writing all output reads to a single file in tab-delimited format\n" " (--tab-delimited-output)\n" "\n" "----------------------------------------------------------------------------\n" " OPTIONS\n" "----------------------------------------------------------------------------\n" "\n" " -m, --min-overlap=NUM The minimum required overlap length between two\n" " reads to provide a confident overlap. Default:\n" " 10bp.\n" "\n" " -M, --max-overlap=NUM Maximum overlap length expected in approximately\n" " 90% of read pairs. It is by default set to 65bp,\n" " which works well for 100bp reads generated from a\n" " 180bp library, assuming a normal distribution of\n" " fragment lengths. Overlaps longer than the maximum\n" " overlap parameter are still considered as good\n" " overlaps, but the mismatch density (explained below)\n" " is calculated over the first max_overlap bases in\n" " the overlapped region rather than the entire\n" " overlap. Default: 65bp, or calculated from the\n" " specified read length, fragment length, and fragment\n" " length standard deviation.\n" "\n" " -x, --max-mismatch-density=NUM\n" " Maximum allowed ratio between the number of\n" " mismatched base pairs and the overlap length.\n" " Two reads will not be combined with a given overlap\n" " if that overlap results in a mismatched base density\n" " higher than this value. Note: Any occurence of an\n" " 'N' in either read is ignored and not counted\n" " towards the mismatches or overlap length. Our\n" " experimental results suggest that higher values of\n" " the maximum mismatch density yield larger\n" " numbers of correctly merged read pairs but at\n" " the expense of higher numbers of incorrectly\n" " merged read pairs. Default: 0.25.\n" "\n" " -O, --allow-outies Also try combining read pairs in the \"outie\"\n" " orientation, e.g.\n" "\n" " Read 1: <-----------\n" " Read 2: ------------>\n" "\n" " as opposed to only the \"innie\" orientation, e.g.\n" "\n" " Read 1: <------------\n" " Read 2: ----------->\n" "\n" " FLASH uses the same parameters when trying each\n" " orientation. If a read pair can be combined in\n" " both \"innie\" and \"outie\" orientations, the\n" " better-fitting one will be chosen using the same\n" " scoring algorithm that FLASH normally uses.\n" "\n" " This option also causes extra .innie and .outie\n" " histogram files to be produced.\n" "\n" " -p, --phred-offset=OFFSET\n" " The smallest ASCII value of the characters used to\n" " represent quality values of bases in FASTQ files.\n" " It should be set to either 33, which corresponds\n" " to the later Illumina platforms and Sanger\n" " platforms, or 64, which corresponds to the\n" " earlier Illumina platforms. Default: 33.\n" "\n" " -r, --read-len=LEN\n" " -f, --fragment-len=LEN\n" " -s, --fragment-len-stddev=LEN\n" " Average read length, fragment length, and fragment\n" " standard deviation. These are convenience parameters\n" " only, as they are only used for calculating the\n" " maximum overlap (--max-overlap) parameter.\n" " The maximum overlap is calculated as the overlap of\n" " average-length reads from an average-size fragment\n" " plus 2.5 times the fragment length standard\n" " deviation. The default values are -r 100, -f 180,\n" " and -s 18, so this works out to a maximum overlap of\n" " 65 bp. If --max-overlap is specified, then the\n" " specified value overrides the calculated value.\n" "\n" " If you do not know the standard deviation of the\n" " fragment library, you can probably assume that the\n" " standard deviation is 10% of the average fragment\n" " length.\n" "\n" " --cap-mismatch-quals Cap quality scores assigned at mismatch locations\n" " to 2. This was the default behavior in FLASH v1.2.7\n" " and earlier. Later versions will instead calculate\n" " such scores as max(|q1 - q2|, 2); that is, the\n" " absolute value of the difference in quality scores,\n" " but at least 2. Essentially, the new behavior\n" " prevents a low quality base call that is likely a\n" " sequencing error from significantly bringing down\n" " the quality of a high quality, likely correct base\n" " call.\n" "\n" " --interleaved-input Instead of requiring files MATES_1.FASTQ and\n" " MATES_2.FASTQ, allow a single file MATES.FASTQ that\n" " has the paired-end reads interleaved. Specify \"-\"\n" " to read from standard input.\n" "\n" " --interleaved-output Write the uncombined pairs in interleaved FASTQ\n" " format.\n" "\n" " -I, --interleaved Equivalent to specifying both --interleaved-input\n" " and --interleaved-output.\n" "\n" " -Ti, --tab-delimited-input\n" " Assume the input is in tab-delimited format\n" " rather than FASTQ, in the format described below in\n" " '--tab-delimited-output'. In this mode you should\n" " provide a single input file, each line of which must\n" " contain either a read pair (5 fields) or a single\n" " read (3 fields). FLASH will try to combine the read\n" " pairs. Single reads will be written to the output\n" " file as-is if also using --tab-delimited-output;\n" " otherwise they will be ignored. Note that you may\n" " specify \"-\" as the input file to read the\n" " tab-delimited data from standard input.\n" "\n" " -To, --tab-delimited-output\n" " Write output in tab-delimited format (not FASTQ).\n" " Each line will contain either a combined pair in the\n" " format 'tag seq qual' or an uncombined\n" " pair in the format 'tag seq_1 qual_1\n" " seq_2 qual_2'.\n" "\n" " -o, --output-prefix=PREFIX\n" " Prefix of output files. Default: \"out\".\n" "\n" " -d, --output-directory=DIR\n" " Path to directory for output files. Default:\n" " current working directory.\n" "\n" " -c, --to-stdout Write the combined reads to standard output. In\n" " this mode, with FASTQ output (the default) the\n" " uncombined reads are discarded. With tab-delimited\n" " output, uncombined reads are included in the\n" " tab-delimited data written to standard output.\n" " In both cases, histogram files are not written,\n" " and informational messages are sent to standard\n" " error rather than to standard output.\n" "\n" " -z, --compress Compress the output files directly with zlib,\n" " using the gzip container format. Similar to\n" " specifying --compress-prog=gzip and --suffix=gz,\n" " but may be slightly faster.\n" "\n" " --compress-prog=PROG Pipe the output through the compression program\n" " PROG, which will be called as `PROG -c -',\n" " plus any arguments specified by --compress-prog-args.\n" " PROG must read uncompressed data from standard input\n" " and write compressed data to standard output when\n" " invoked as noted above.\n" " Examples: gzip, bzip2, xz, pigz.\n" "\n" " --compress-prog-args=ARGS\n" " A string of additional arguments that will be passed\n" " to the compression program if one is specified with\n" " --compress-prog=PROG. (The arguments '-c -' are\n" " still passed in addition to explicitly specified\n" " arguments.)\n" "\n" " --suffix=SUFFIX, --output-suffix=SUFFIX\n" " Use SUFFIX as the suffix of the output files\n" " after \".fastq\". A dot before the suffix is assumed,\n" " unless an empty suffix is provided. Default:\n" " nothing; or 'gz' if -z is specified; or PROG if\n" " --compress-prog=PROG is specified.\n" "\n" " -t, --threads=NTHREADS Set the number of worker threads. This is in\n" " addition to the I/O threads. Default: number of\n" " processors. Note: if you need FLASH's output to\n" " appear deterministically or in the same order as\n" " the original reads, you must specify -t 1\n" " (--threads=1).\n" "\n" " -q, --quiet Do not print informational messages.\n" "\n" " -h, --help Display this help and exit.\n" "\n" " -v, --version Display version.\n" ; fputs(usage_str, stdout); if (isatty(STDOUT_FILENO)) { /* Just to be extra user-friendly... */ printf("\nRun `%s --help | "PAGER"' to " "prevent this text from scrolling by.\n", argv0); } } static void usage_short(const char *argv0) { fprintf(stderr, "Usage: flash [OPTIONS] MATES_1.FASTQ MATES_2.FASTQ\n" "Run `%s --help | "PAGER"' for more information.\n", argv0); } static void version(void) { fputs( "FLASH "VERSION_STR"\n" "Copyright (C) 2012 Tanja Magoc\n" "Copyright (C) 2012, 2013, 2014 Eric Biggers\n" "License GPLv3+; GNU GPL version 3 or later .\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n" "\n" "Report bugs to flash.comment@gmail.com or https://sourceforge.net/p/flashpage/bugs\n" , stdout); } enum { INTERLEAVED_INPUT_OPTION = 257, INTERLEAVED_OUTPUT_OPTION, CAP_MISMATCH_QUALS_OPTION, COMPRESS_PROG_OPTION, COMPRESS_PROG_ARGS_OPTION, SUFFIX_OPTION, TAB_DELIMITED_INPUT_OPTION, TAB_DELIMITED_OUTPUT_OPTION, }; static const char *optstring = "m:M:x:p:Or:f:s:IT:o:d:czt:qhv"; static const struct option longopts[] = { {"min-overlap", required_argument, NULL, 'm'}, {"max-overlap", required_argument, NULL, 'M'}, {"max-mismatch-density", required_argument, NULL, 'x'}, {"phred-offset", required_argument, NULL, 'p'}, {"allow-outies", no_argument, NULL, 'O'}, {"read-len", required_argument, NULL, 'r'}, {"fragment-len", required_argument, NULL, 'f'}, {"fragment-len-stddev", required_argument, NULL, 's'}, {"cap-mismatch-quals", no_argument, NULL, CAP_MISMATCH_QUALS_OPTION}, {"interleaved", no_argument, NULL, 'I'}, {"interleaved-input", no_argument, NULL, INTERLEAVED_INPUT_OPTION}, {"interleaved-output", no_argument, NULL, INTERLEAVED_OUTPUT_OPTION}, {"tab-delimited-input", no_argument, NULL, TAB_DELIMITED_INPUT_OPTION}, {"tab-delimited-output", no_argument, NULL, TAB_DELIMITED_OUTPUT_OPTION}, {"output-prefix", required_argument, NULL, 'o'}, {"output-directory", required_argument, NULL, 'd'}, {"to-stdout", no_argument, NULL, 'c'}, {"compress", no_argument, NULL, 'z'}, {"compress-prog", required_argument, NULL, COMPRESS_PROG_OPTION}, {"compress-prog-args", required_argument, NULL, COMPRESS_PROG_ARGS_OPTION}, {"suffix", required_argument, NULL, SUFFIX_OPTION}, {"output-suffix", required_argument, NULL, SUFFIX_OPTION}, {"threads", required_argument, NULL, 't'}, {"quiet", no_argument, NULL, 'q'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0} }; static char * input_format_str(char *buf, size_t bufsize, const struct read_format_params *iparams, bool interleaved) { switch (iparams->fmt) { case READ_FORMAT_FASTQ: snprintf(buf, bufsize, "FASTQ, phred_offset=%d%s", iparams->phred_offset, (interleaved ? ", interleaved" : "")); break; case READ_FORMAT_TAB_DELIMITED: snprintf(buf, bufsize, "Tab-delimited, phred_offset=%d", iparams->phred_offset); break; default: assert(0); break; } return buf; } static char * output_format_str(char *buf, size_t bufsize, const struct read_format_params *oparams, bool interleaved_output, enum out_compression_type out_ctype, const char *compress_prog, const char *compress_prog_args) { input_format_str(buf, bufsize, oparams, interleaved_output); switch (out_ctype) { case OUT_COMPRESSION_NONE: if (compress_prog) { char *p = strchr(buf, '\0'); snprintf(p, &buf[bufsize] - p, ", filtered through '%s %s'", compress_prog, compress_prog_args); } break; case OUT_COMPRESSION_GZIP: { char *p = strchr(buf, '\0'); snprintf(p, &buf[bufsize] - p, ", gzip"); } break; } return buf; } /* This is just a dynamic array used as a histogram. It's needed to count the * frequencies of the lengths of the combined reads. */ struct histogram { uint64_t *array; size_t len; }; static void hist_init(struct histogram *hist) { hist->array = NULL; hist->len = 0; } static void hist_destroy(struct histogram *hist) { xfree(hist->array, hist->len * sizeof(hist->array[0])); } static void hist_add(struct histogram *hist, size_t idx, uint64_t amount) { uint64_t *array = hist->array; size_t old_len = hist->len; if (idx >= old_len) { size_t new_len = idx + 1; array = xrealloc(array, new_len * sizeof(array[0])); memset(&array[old_len], 0, (new_len - old_len) * sizeof(array[0])); hist->len = new_len; hist->array = array; } array[idx] += amount; } static void hist_inc(struct histogram *hist, size_t idx) { hist_add(hist, idx, 1); } static void hist_combine(struct histogram *hist, const struct histogram *other) { for (size_t i = 0; i < other->len; i++) hist_add(hist, i, other->array[i]); } static uint64_t hist_count_at(const struct histogram *hist, size_t idx) { assert(idx < hist->len); return hist->array[idx]; } static void hist_stats(const struct histogram *hist, uint64_t *max_freq_ret, long *first_nonzero_idx_ret, long *last_nonzero_idx_ret) { *max_freq_ret = 0; *first_nonzero_idx_ret = -1; *last_nonzero_idx_ret = -2; for (size_t i = 1; i < hist->len; i++) { uint64_t freq = hist->array[i]; if (freq != 0) { if (*first_nonzero_idx_ret == -1) *first_nonzero_idx_ret = i; *last_nonzero_idx_ret = i; if (freq > *max_freq_ret) *max_freq_ret = freq; } } } static void write_hist_file(const char *hist_file, const struct histogram *hist, long first_nonzero_idx, long last_nonzero_idx) { FILE *fp = xfopen(hist_file, "w"); for (long i = first_nonzero_idx; i <= last_nonzero_idx; i++) { uint64_t count = hist_count_at(hist, i); if (count != 0) if (fprintf(fp, "%ld\t%"PRIu64"\n", i, count) < 0) goto write_error; } xfclose(fp, hist_file); return; write_error: fatal_error_with_errno("Error writing to \"%s\"", hist_file); } static void write_histogram_file(const char *histogram_file, const struct histogram *hist, long first_nonzero_idx, long last_nonzero_idx, uint64_t max_freq) { const double max_num_asterisks = 72; double scale = max_num_asterisks / (double)max_freq; FILE *fp = xfopen(histogram_file, "w"); for (long i = first_nonzero_idx; i <= last_nonzero_idx; i++) { if (fprintf(fp, "%ld\t", i) < 0) goto write_error; size_t num_asterisks = (size_t)(scale * (double)hist_count_at(hist, i)); while (num_asterisks--) if (fputc('*', fp) == EOF) goto write_error; if (fputc('\n', fp) == EOF) goto write_error; } xfclose(fp, histogram_file); return; write_error: fatal_error_with_errno("Error writing to \"%s\"", histogram_file); } struct flash_stats { struct histogram innie_lens; struct histogram outie_lens; struct histogram overlap_lens; uint64_t num_uncombined; uint64_t num_innie; uint64_t num_outie; }; static void flash_stats_init(struct flash_stats *stats) { hist_init(&stats->innie_lens); hist_init(&stats->outie_lens); hist_init(&stats->overlap_lens); stats->num_uncombined = 0; stats->num_innie = 0; stats->num_outie = 0; } static void flash_stats_combine(struct flash_stats *stats, const struct flash_stats *other) { hist_combine(&stats->innie_lens, &other->innie_lens); hist_combine(&stats->outie_lens, &other->outie_lens); hist_combine(&stats->overlap_lens, &other->overlap_lens); stats->num_uncombined += other->num_uncombined; stats->num_innie += other->num_innie; stats->num_outie += other->num_outie; } static void flash_stats_destroy(struct flash_stats *stats) { hist_destroy(&stats->innie_lens); hist_destroy(&stats->outie_lens); hist_destroy(&stats->overlap_lens); } struct common_combiner_thread_params { struct read_io_handle *iohandle; struct combine_params alg_params; }; struct combiner_thread_params { struct common_combiner_thread_params *common; struct flash_stats *stats; }; /* Buffer for read_sets for which all the read pointers have been invalidated. */ struct empty_sets { struct read_set *q1[2]; struct read_set *q2[2]; }; static void hold_empty_set(struct read_set *q[2], struct read_set *s) { if (!q[0]) { q[0] = s; } else { assert(!q[1]); q[1] = s; } } static void hold_empty_sets(struct empty_sets *e, struct read_set *s1, struct read_set *s2) { hold_empty_set(e->q1, s1); hold_empty_set(e->q2, s2); } static struct read_set * get_empty_set(struct read_set *q[2]) { struct read_set *s; assert(q[0]); s = q[0]; q[0] = q[1]; q[1] = NULL; return s; } static void get_empty_sets(struct empty_sets *e, struct read_set **s1_ret, struct read_set **s2_ret) { *s1_ret = get_empty_set(e->q1); *s2_ret = get_empty_set(e->q2); } static void free_empty_sets(struct empty_sets *e) { free_read_set(e->q1[0]); free_read_set(e->q1[1]); free_read_set(e->q2[0]); free_read_set(e->q2[1]); } /* This procedure is executed in parallel by all the combiner threads. */ static void * combiner_thread_proc(void *_params) { struct combiner_thread_params *params = _params; struct flash_stats *stats = params->stats; struct read_io_handle *iohandle = params->common->iohandle; const struct combine_params *alg_params = ¶ms->common->alg_params; struct read_set *s_avail_1 = new_empty_read_set(iohandle); struct read_set *s_avail_2 = new_empty_read_set(iohandle); struct read_set *s_uncombined_1 = new_empty_read_set(iohandle); struct read_set *s_uncombined_2 = new_empty_read_set(iohandle); struct read_set *s_combined = get_avail_read_set(iohandle); struct empty_sets empty = {}; struct read_set *s1; struct read_set *s2; /* While there are read pairs to process ... */ while (get_unprocessed_read_pairs(iohandle, &s1, &s2)) { /* ... process each read pair. */ for (size_t i = 0; i < s1->filled; i++) { struct read *r1 = s1->reads[i]; struct read *r2 = s2->reads[i]; struct read *r_combined; enum combine_status status; s1->reads[i] = NULL; s2->reads[i] = NULL; reverse_complement(r2); /* Get available read in which to try the combination. */ r_combined = s_combined->reads[s_combined->filled]; /* Try combining the reads. */ status = combine_reads(r1, r2, r_combined, alg_params); switch (status) { case COMBINED_AS_INNIE: stats->num_innie++; hist_inc(&stats->innie_lens, r_combined->seq_len); goto combined; case COMBINED_AS_OUTIE: stats->num_outie++; hist_inc(&stats->outie_lens, r_combined->seq_len); goto combined; combined: /* Combination was successful. */ hist_inc(&stats->overlap_lens, r1->seq_len + r2->seq_len - r_combined->seq_len); /* Uncombined read structures are unneeded; mark * them as available. */ if (s_avail_1->filled == s_avail_1->num_reads) { put_avail_read_pairs(iohandle, s_avail_1, s_avail_2); get_empty_sets(&empty, &s_avail_1, &s_avail_2); } s_avail_1->reads[s_avail_1->filled++] = r1; s_avail_2->reads[s_avail_2->filled++] = r2; /* Compute tag for combined read. */ get_combined_tag(r1, r2, r_combined); /* Send combined read. */ if (++s_combined->filled == s_combined->num_reads) { put_combined_reads(iohandle, s_combined); s_combined = get_avail_read_set(iohandle); } break; case NOT_COMBINED: stats->num_uncombined++; /* Send uncombined reads. */ if (s_uncombined_1->filled == s_uncombined_1->num_reads) { put_uncombined_read_pairs(iohandle, s_uncombined_1, s_uncombined_2); get_empty_sets(&empty, &s_uncombined_1, &s_uncombined_2); } s_uncombined_1->reads[s_uncombined_1->filled++] = r1; s_uncombined_2->reads[s_uncombined_2->filled++] = r2; reverse_complement(r2); } } s1->filled = 0; s2->filled = 0; hold_empty_sets(&empty, s1, s2); } /* No more reads to combine. */ /* Free read sets owned by this thread */ free_read_set(s_avail_1); free_read_set(s_avail_2); free_empty_sets(&empty); /* Send out any remaining uncombined and combined reads. * If there are none, free the corresponding read sets. */ if (s_uncombined_1->filled) { put_uncombined_read_pairs(iohandle, s_uncombined_1, s_uncombined_2); } else { free_read_set(s_uncombined_1); free_read_set(s_uncombined_2); } if (s_combined->filled) put_combined_reads(iohandle, s_combined); else free_read_set(s_combined); notify_combiner_terminated(iohandle); xfree(params, sizeof(*params)); return NULL; } static void warn_about_long_overlaps(const struct flash_stats *stats, int max_overlap) { uint64_t long_overlap_count; double long_overlap_percent; long_overlap_count = 0; for (size_t i = max_overlap + 1; i < stats->overlap_lens.len; i++) long_overlap_count += hist_count_at(&stats->overlap_lens, i); long_overlap_percent = TO_PERCENT(long_overlap_count, stats->num_innie + stats->num_outie); if (long_overlap_percent > 10.0) { warning("An unexpectedly high proportion of combined pairs " "(%.2f%%)\n" "overlapped by more than %d bp, the --max-overlap (-M) " "parameter. Consider\n" "increasing this parameter. (As-is, FLASH is " "penalizing overlaps longer than\n" "%d bp when considering them for possible combining!)", long_overlap_percent, max_overlap, max_overlap); } } int main(int argc, char **argv) { infofile = stdout; const char *argv0 = argv[0]; struct combine_params alg_params = { .max_overlap = 0, .min_overlap = 10, .max_mismatch_density = 0.25, .cap_mismatch_quals = false, .allow_outies = false, }; bool max_overlap_specified = false; struct read_format_params iparams = { .fmt = READ_FORMAT_FASTQ, .phred_offset = 33, }; struct read_format_params oparams = { .fmt = READ_FORMAT_FASTQ, .phred_offset = 33, }; int read_len = 100; int fragment_len = 180; int fragment_len_stddev = 18; bool read_len_specified = false; bool fragment_len_specified = false; bool fragment_len_stddev_specified = false; const char *prefix = "out"; const char *output_dir = "."; bool to_stdout = false; bool verbose = true; bool interleaved_input = false; bool interleaved_output = false; struct input_stream *mates1_in = NULL; struct input_stream *mates2_in = NULL; enum out_compression_type out_ctype = OUT_COMPRESSION_NONE; const char *compress_prog = NULL; char *compress_prog_args = "-c -"; bool compress_prog_args_allocated = false; struct output_stream *out_combined = NULL; struct output_stream *out_notcombined_1 = NULL; struct output_stream *out_notcombined_2 = NULL; const char *out_filetype = "fastq"; char *out_suffix = ""; bool out_suffix_allocated = false; unsigned long num_combiner_threads = 0; int c; char *tmp; struct timeval start_time; gettimeofday(&start_time, NULL); while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != -1) { switch (c) { case 'm': alg_params.min_overlap = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || alg_params.min_overlap < 1) fatal_error("Minimum overlap must be a " "positive integer! Please check " "option -m."); break; case 'M': alg_params.max_overlap = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || alg_params.max_overlap < 1) fatal_error("Maximum overlap must be " "a positive integer! Please check " "option -M."); max_overlap_specified = true; break; case 'x': alg_params.max_mismatch_density = strtod(optarg, &tmp); if (tmp == optarg || *tmp || alg_params.max_mismatch_density < 0.0 || alg_params.max_mismatch_density > 1.0) { fatal_error("Max mismatch density must be a " "number in the interval [0, 1]! " "Please check option -x."); } break; case 'p': oparams.phred_offset = iparams.phred_offset = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || iparams.phred_offset < 0 || iparams.phred_offset > 127) { fatal_error("Phred offset must be an integer " "in the range [0, 127]! Please " "check option -p."); } if (iparams.phred_offset != 33 && iparams.phred_offset != 64) { warning("Phred offset is usually either " "64 (for earlier Illumina data) or 33 " "(for Sanger and later Illumina data)."); } break; case 'O': alg_params.allow_outies = true; break; case 'f': fragment_len = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || fragment_len <= 0) fatal_error("Fragment length must be a " "positive integer! Please check " "option -f."); fragment_len_specified = true; break; case 's': fragment_len_stddev = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || fragment_len_stddev <= 0) fatal_error("Fragment length standard deviation " "must be a positive integer! " "Please check option -s."); fragment_len_stddev_specified = true; break; case 'r': read_len = strtol(optarg, &tmp, 10); if (tmp == optarg || *tmp || read_len <= 0) fatal_error("Read length must be a " "positive integer! Please check " "option -r."); read_len_specified = true; break; case CAP_MISMATCH_QUALS_OPTION: alg_params.cap_mismatch_quals = true; break; case 'I': interleaved_input = true; interleaved_output = true; break; case INTERLEAVED_INPUT_OPTION: interleaved_input = true; break; case INTERLEAVED_OUTPUT_OPTION: interleaved_output = true; break; case 'T': if ((*optarg != 'i' && *optarg != 'o') || *(optarg + 1)) { fatal_error("Invalid option -T%s! Use -Ti " "(short for --tab-delimited-input)\n\t" "or -To (short for " "--tab-delimited-output)", optarg); } if (*optarg == 'i') { case TAB_DELIMITED_INPUT_OPTION: iparams.fmt = READ_FORMAT_TAB_DELIMITED; } else { case TAB_DELIMITED_OUTPUT_OPTION: oparams.fmt = READ_FORMAT_TAB_DELIMITED; out_filetype = "tab"; } break; case 'o': prefix = optarg; break; case 'd': output_dir = optarg; break; case 'c': to_stdout = true; infofile = stderr; break; case 'z': out_ctype = OUT_COMPRESSION_GZIP; if (out_suffix_allocated) free(out_suffix); out_suffix = ".gz"; out_suffix_allocated = false; compress_prog = NULL; break; case COMPRESS_PROG_OPTION: if (out_suffix_allocated) free(out_suffix); out_suffix = xmalloc(strlen(optarg) + 2); sprintf(out_suffix, ".%s", optarg); out_suffix_allocated = true; compress_prog = optarg; out_ctype = OUT_COMPRESSION_NONE; break; case COMPRESS_PROG_ARGS_OPTION: if (compress_prog_args_allocated) free(compress_prog_args); compress_prog_args = xmalloc(strlen(optarg) + 6); sprintf(compress_prog_args, "%s -c -", optarg); compress_prog_args_allocated = true; break; case SUFFIX_OPTION: if (out_suffix_allocated) free(out_suffix); if (*optarg) { out_suffix = xmalloc(strlen(optarg) + 2); sprintf(out_suffix, ".%s", optarg); out_suffix_allocated = true; } else { out_suffix = optarg; out_suffix_allocated = false; } break; case 't': num_combiner_threads = strtoul(optarg, &tmp, 10); if (tmp == optarg || *tmp || num_combiner_threads < 1 || num_combiner_threads > UINT_MAX) { fatal_error("Number of threads must be " "a positive integer! Please " "check option -t."); } break; case 'q': verbose = false; break; case 'v': version(); return 0; case 'h': usage(argv0); return 0; default: usage_short(argv0); return 2; } } if (max_overlap_specified) { if (read_len_specified) { warning("--read-len (-r) has no effect when " "--max-overlap (-M) is also\n" "specified!"); } if (fragment_len_specified) { warning("--fragment-len (-f) has no effect when " "--max-overlap (-M) is\n" "also specified!"); } if (fragment_len_stddev_specified) { warning("--fragment-len-stddev (-s) has no effect when " "--max-overlap\n" "(-M) is also specified!"); } } else { int count = (int)read_len_specified + (int)fragment_len_specified + (int)fragment_len_stddev_specified; alg_params.max_overlap = (int)(2 * read_len - fragment_len + 2.5 * fragment_len_stddev); if (count == 1 || count == 2) { warning("You specified at least one, but not all, " "of --read-len (-r),\n" "--fragment-len (-f), and " "--fragment-len-stddev (-s). FLASH is using\n" "read_len=%d, fragment_len=%d, and " "fragment_len_stddev=%d to compute\n" "max_overlap=%d. If this is not correct for " "your data you must either specify\n" "all these options or specify --max-overlap (-M).", read_len, fragment_len, fragment_len_stddev, alg_params.max_overlap); } #if 0 if (count == 0) { warning("Using default maximum overlap of %d bp! " "Use --max-overlap (-M)\n" "to change it. Or specify all of --read-len " "(-r), --fragment-len (-f), and\n" "--fragment-len-stddev (-s).", alg_params.max_overlap); } #endif } if (alg_params.max_overlap < alg_params.min_overlap) { fatal_error( "Maximum overlap (%d) cannot be less than the minimum overlap (%d).\n" "Please make sure you have provided the read length and fragment length\n" "correctly. Or, alternatively, specify the minimum and maximum overlap\n" "manually with the --min-overlap and --max-overlap options.", alg_params.max_overlap, alg_params.min_overlap); } if (num_combiner_threads == 0) num_combiner_threads = get_default_num_threads(); argc -= optind; argv += optind; if (argc == 0 || argc > 2) { usage_short(argv0); return 2; } if (interleaved_input && argc != 1) fatal_error("With --interleaved-input, only 1 input " "file is allowed!"); if (interleaved_input && iparams.fmt != READ_FORMAT_FASTQ) fatal_error("--interleaved-input is only relevant for FASTQ input!"); if (argc == 1 && !interleaved_input && iparams.fmt == READ_FORMAT_FASTQ) fatal_error("Only 1 input file was specified! Specify " "--interleaved-input\n" "\tif you're providing an interleaved FASTQ file, " "or --tab-delimited-input\n" "\tif you're providing a tab-delimited input file. " "Or specify two input\n" "\tfiles (for read 1 and read 2 of each pair)."); mates1_in = new_input_stream(argv[0]); if (argc > 1) mates2_in = new_input_stream(argv[1]); mkdir_p(output_dir); /* Open the output files. */ char name_buf[strlen(output_dir) + 1 + strlen(prefix) + 100 + strlen(out_suffix) + 1]; char *suffix; suffix = name_buf + sprintf(name_buf, "%s/%s", output_dir, prefix); if (oparams.fmt == READ_FORMAT_TAB_DELIMITED) { sprintf(suffix, ".readsAndPairs.%s%s", out_filetype, out_suffix); out_combined = new_output_stream(out_ctype, (to_stdout ? "-" : name_buf), compress_prog, compress_prog_args); } else { sprintf(suffix, ".extendedFrags.%s%s", out_filetype, out_suffix); out_combined = new_output_stream(out_ctype, (to_stdout ? "-" : name_buf), compress_prog, compress_prog_args); if (!to_stdout) { if (interleaved_output) { sprintf(suffix, ".notCombined.%s%s", out_filetype, out_suffix); out_notcombined_1 = new_output_stream(out_ctype, name_buf, compress_prog, compress_prog_args); } else { sprintf(suffix, ".notCombined_1.%s%s", out_filetype, out_suffix); out_notcombined_1 = new_output_stream(out_ctype, name_buf, compress_prog, compress_prog_args); sprintf(suffix, ".notCombined_2.%s%s", out_filetype, out_suffix); out_notcombined_2 = new_output_stream(out_ctype, name_buf, compress_prog, compress_prog_args); } } } *suffix = '\0'; if (verbose) { info("Starting FLASH " VERSION_STR); info("Fast Length Adjustment of SHort reads"); info(" "); info("Input files:"); info(" %s", input_stream_get_name(mates1_in)); if (mates2_in) info(" %s", input_stream_get_name(mates2_in)); info(" "); info("Output files:"); info(" %s", output_stream_get_name(out_combined)); if (out_notcombined_1) info(" %s", output_stream_get_name(out_notcombined_1)); if (out_notcombined_2) info(" %s", output_stream_get_name(out_notcombined_2)); if (!to_stdout) { info(" %s.hist", name_buf); info(" %s.histogram", name_buf); } info(" "); info("Parameters:"); info(" Min overlap: %d", alg_params.min_overlap); info(" Max overlap: %d", alg_params.max_overlap); info(" Max mismatch density: %f", alg_params.max_mismatch_density); info(" Allow \"outie\" pairs: %s", alg_params.allow_outies ? "true" : "false"); info(" Cap mismatch quals: %s", alg_params.cap_mismatch_quals ? "true" : "false"); info(" Combiner threads: %u", (unsigned)num_combiner_threads); char buf[256]; info(" Input format: %s", input_format_str(buf, ARRAY_LEN(buf), &iparams, interleaved_input)); info(" Output format: %s", output_format_str(buf, ARRAY_LEN(buf), &oparams, interleaved_output, out_ctype, compress_prog, compress_prog_args)); info(" "); } /* * We wish to do the following: * * "Go through each mate pair in the input files. Determine if it can * be combined, given the input parameters to the program. If it can, * write the combined read to the PREFIX.extendedFrags.fastq file. * Otherwise, write the reads in the mate pair to the * PREFIX.notCombined_1.fastq and PREFIX.notCombined_2.fastq files, or * PREFIX.notCombined.fastq for interleaved output. Or, if the -c / * --to-stdout option is specified, write the combined reads to standard * output, and ignore the uncombined reads." * * In the following implementation, there will be @num_combiner_threads * combiner threads created that will process the reads in parallel by * retrieving `struct read_set'-sized chunks of reads from the reader * thread(s), and providing `struct read_set'-sized chunks of combined * or uncombined reads to the writer threads. */ struct flash_stats stats[num_combiner_threads]; struct flash_stats *total_stats = &stats[num_combiner_threads - 1]; for (size_t i = 0; i < num_combiner_threads; i++) flash_stats_init(&stats[i]); struct read_io_handle *iohandle = start_readers_and_writers(mates1_in, mates2_in, out_combined, out_notcombined_1, out_notcombined_2, &iparams, &oparams, num_combiner_threads, verbose); struct common_combiner_thread_params common = { .iohandle = iohandle, .alg_params = alg_params, }; if (verbose) info("Starting %u combiner threads", (unsigned)num_combiner_threads); pthread_t other_combiner_threads[num_combiner_threads - 1]; for (unsigned i = 0; i < num_combiner_threads; i++) { struct combiner_thread_params *p; p = xmalloc(sizeof(*p)); p->common = &common; p->stats = &stats[i]; if (i < num_combiner_threads - 1) other_combiner_threads[i] = create_thread(combiner_thread_proc, p); else combiner_thread_proc(p); } for (unsigned i = 0; i < num_combiner_threads - 1; i++) { join_thread(other_combiner_threads[i]); flash_stats_combine(total_stats, &stats[i]); flash_stats_destroy(&stats[i]); } stop_readers_and_writers(iohandle); if (verbose) { uint64_t num_combined_pairs; uint64_t num_uncombined_pairs; uint64_t num_total_pairs; num_combined_pairs = total_stats->num_innie + total_stats->num_outie; num_uncombined_pairs = total_stats->num_uncombined; num_total_pairs = num_combined_pairs + num_uncombined_pairs; info(" "); info("Read combination statistics:"); info(" Total pairs: %"PRIu64, num_total_pairs); info(" Combined pairs: %"PRIu64, num_combined_pairs); if (alg_params.allow_outies) { info(" Innie pairs: %"PRIu64" " "(%.2f%% of combined)", total_stats->num_innie, TO_PERCENT(total_stats->num_innie, num_combined_pairs)); info(" Outie pairs: %"PRIu64" " "(%.2f%% of combined)", total_stats->num_outie, TO_PERCENT(total_stats->num_outie, num_combined_pairs)); } info(" Uncombined pairs: %"PRIu64, num_uncombined_pairs); info(" Percent combined: %.2f%%", TO_PERCENT(num_combined_pairs, num_total_pairs)); info(" "); } if (!to_stdout) { struct histogram _combined_read_lens; int hist_count; struct histogram *combined_read_lens; if (verbose) info("Writing histogram files."); if (alg_params.allow_outies) { hist_count = 3; hist_init(&_combined_read_lens); hist_combine(&_combined_read_lens, &total_stats->innie_lens); hist_combine(&_combined_read_lens, &total_stats->outie_lens); combined_read_lens = &_combined_read_lens; } else { hist_count = 1; combined_read_lens = &total_stats->innie_lens; } struct { const char *suffix; const struct histogram *hist; } hist_specs[] = { { "", combined_read_lens }, { ".innie", &total_stats->innie_lens }, { ".outie", &total_stats->outie_lens }, }; for (int i = 0; i < hist_count; i++) { uint64_t max_freq; long first_nonzero_idx; long last_nonzero_idx; hist_stats(hist_specs[i].hist, &max_freq, &first_nonzero_idx, &last_nonzero_idx); /* Write the raw numbers of the combined read length * histogram to the PREFIX.hist file. */ sprintf(suffix, ".hist%s", hist_specs[i].suffix); write_hist_file(name_buf, hist_specs[i].hist, first_nonzero_idx, last_nonzero_idx); /* Write a pretty representation of the combined read * length histogram to the PREFIX.histogram file. */ sprintf(suffix, ".histogram%s", hist_specs[i].suffix); write_histogram_file(name_buf, hist_specs[i].hist, first_nonzero_idx, last_nonzero_idx, max_freq); } if (alg_params.allow_outies) hist_destroy(combined_read_lens); } warn_about_long_overlaps(total_stats, alg_params.max_overlap); flash_stats_destroy(total_stats); if (verbose) { struct timeval end_time; gettimeofday(&end_time, NULL); uint64_t start_usec = (uint64_t)start_time.tv_sec * 1000000 + start_time.tv_usec; uint64_t end_usec = (uint64_t)end_time.tv_sec * 1000000 + end_time.tv_usec; info(" "); info("FLASH " VERSION_STR " complete!"); info("%.3f seconds elapsed", (double)(end_usec - start_usec) / 1000000); } if (warning_count > 0) { info("Finished with %lu warning%s (see above)", warning_count, warning_count == 1 ? "" : "s"); } if (out_suffix_allocated) free(out_suffix); if (compress_prog_args_allocated) free(compress_prog_args); return 0; } FLASH-1.2.11/iostream.c000066400000000000000000000452461237001226200144260ustar00rootroot00000000000000/* * iostream.c: Buffered file input and output streams with automatic error * checking and extra features such as gzip compression. */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include "iostream.h" #include "util.h" #include #include #include #include #include #include #include #include #include /* Return true iff the specified string is a single hyphen, which may represent * standard input or standard output. */ static bool string_is_hyphen(const char *str) { return str[0] == '-' && str[1] == '\0'; } static bool mode_is_writing(const char *mode) { return strchr(mode, 'w') != NULL; } static bool flags_is_writing(int flags) { int accmode = (flags & O_ACCMODE); return (accmode == O_WRONLY || accmode == O_RDWR); } static const char * access_mode_string(const char *mode) { return mode_is_writing(mode) ? "writing" : "reading"; } static const char * access_flags_string(int flags) { return flags_is_writing(flags) ? "writing" : "reading"; } static int mode_to_flags(const char *mode) { return mode_is_writing(mode) ? O_WRONLY | O_TRUNC | O_CREAT : O_RDONLY; } /* Returns a standard file descriptor depending on the flags: * * reading => standard input * writing => standard output */ static int standard_fd_from_flags(int flags) { return flags_is_writing(flags) ? STDOUT_FILENO : STDIN_FILENO; } /* Like fopen(), but aborts on error. */ void * xfopen(const char *path, const char *mode) { FILE *fp = fopen(path, mode); if (!fp) fatal_error_with_errno("Failed to open \"%s\" for %s", path, access_mode_string(mode)); return fp; } /* Like fclose(), but aborts on error. */ void xfclose(FILE *fp, const char *name) { if (fclose(fp)) fatal_error_with_errno("Error closing \"%s\"", name); } #ifndef O_BINARY # define O_BINARY 0 #endif /* Like open(), but aborts on error, and also interprets "-" as standard output * or standard input rather than a path, depending on the requested mode. Also * automatically provides O_BINARY on Windows. */ static void * xopen(const char *path, int flags, mode_t mode) { int fd; if (string_is_hyphen(path)) { fd = standard_fd_from_flags(flags); #ifdef __WIN32__ _setmode(fd, O_BINARY); #endif } else { fd = open(path, flags | O_BINARY, mode); } if (fd < 0) fatal_error_with_errno("Failed to open \"%s\" for %s", path, access_flags_string(flags)); /* XXX: autodetect whether posix_fadvise() is available or not. */ #ifdef __linux__ /* Advise the operating system that the file will be read or written * sequentially. */ posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); #endif return (void*)(intptr_t)fd; } /* Like gzopen(), but aborts on error, and also interprets "-" as standard * output or standard input rather than a path, depending on the requested mode. */ static void * xgzopen(const char *path, const char *mode) { gzFile gzf; int fd; fd = (int)(intptr_t)xopen(path, mode_to_flags(mode), 0644); errno = 0; gzf = gzdopen(fd, mode); if (!gzf) fatal_error_with_errno("Failed to open \"%s\" for %s", path, access_mode_string(mode)); return gzf; } /* Like gzclose(), but aborts on error. */ static void xgzclose(void *_fp, const char *name) { gzFile gzf = (gzFile)_fp; errno = 0; if (gzclose(gzf) != Z_OK) fatal_error_with_errno("Error closing \"%s\"", name); } /* Checks the error status on a gzFile. Returns only if no error occurred or if * the error was caused by an interruption (EINTR). */ static void check_gzerror(gzFile gzf, bool was_writing, const char *name) { int errnum; const char *error_str; error_str = gzerror(gzf, &errnum); switch (errnum) { case Z_OK: return; case Z_ERRNO: if (errno == EINTR) return; fatal_error_with_errno("Error %s \"%s\"", (was_writing ? "writing" : "reading"), name); default: fatal_error("zlib error %s \"%s\": %s", (was_writing ? "writing" : "reading"), name, error_str); } } /* Reads data from gzFile, with error checking. Returns the number of bytes * successfully read, which will be less than or equal to @count; 0 implies the * stream is at end-of-file. Aborts on error. */ static size_t xgzread(void *_fp, void *buf, size_t count, const char *name) { gzFile gzf = (gzFile)_fp; int trycount = min(count, INT_MAX); for (;;) { int ret = gzread(gzf, buf, trycount); if (ret >= 0) return ret; if (gzeof(gzf)) return 0; check_gzerror(gzf, false, name); } } /* Writes data to a gzFile, with error checking. */ static void xgzwrite(void *_fp, const void *_buf, size_t count, const char *name) { gzFile gzf = (gzFile)_fp; const char *ptr = _buf; while (count) { int trycount = min(count, INT_MAX); int ret = gzwrite(gzf, ptr, trycount); if (!ret) { check_gzerror(gzf, true, name); continue; } ptr += ret; count -= ret; } } /* Reads data from a file descriptor, with error checking. Returns the number * of bytes successfully read, which will be less than or equal to @count; 0 * implies end-of-file has been reached. Aborts on error. */ static size_t xread(void *_fp, void *buf, size_t count, const char *name) { int fd = (int)(intptr_t)_fp; ssize_t trycount = min(count, SSIZE_MAX); for (;;) { ssize_t ret = read(fd, buf, trycount); if (ret >= 0) return ret; if (errno != EINTR) fatal_error_with_errno("Error reading \"%s\"", name); } } /* Similar to xread(), but retries on short reads. */ static size_t full_xread(void *fp, void *_buf, size_t count, const char *name) { char *ptr = _buf; while (count) { size_t ret = xread(fp, ptr, count, name); if (ret == 0) break; ptr += ret; count -= ret; } return ptr - (char*)_buf; } /* Writes data to a file descriptor, with error checking. */ static void xwrite(void *_fp, const void *_buf, size_t count, const char *name) { int fd = (int)(intptr_t)_fp; const char *ptr = _buf; while (count) { ssize_t trycount = min(count, SSIZE_MAX); ssize_t ret = write(fd, ptr, trycount); if (ret < 0) { if (errno == EINTR) continue; fatal_error_with_errno("Error writing \"%s\"", name); } ptr += ret; count -= ret; } } /* Closes a file descriptor, with error checking. */ static void xclose(void *_fp, const char *name) { int fd = (int)(intptr_t)_fp; if (close(fd)) fatal_error_with_errno("Error closing \"%s\"", name); } /* Writes data to a FILE *, with error checking. */ static void xfwrite(void *_fp, const void *buf, size_t count, const char *name) { FILE *fp = (FILE*)_fp; if (fwrite(buf, 1, count, fp) != count) fatal_error_with_errno("Error writing \"%s\"", name); } /* Closes a FILE * opened with popen(), with error checking. */ static void xpclose(void *_fp, const char *name) { FILE *fp = (FILE*)_fp; int status = pclose(fp); if (status == -1) fatal_error_with_errno("Error closing pipe to \"%s\"", name); if (status) fatal_error("Program writing to \"%s\" " "exited with failure status", name); } #define IOSTREAM_BUFSIZE 32768 /***************************** * Input stream functions * *****************************/ static void * input_gzfile_open(const char *path) { return xgzopen(path, "rb"); } static void * input_fd_open(const char *path) { return xopen(path, O_RDONLY, 0); } struct input_stream { const struct input_stream_operations *ops; void *fp; char *name; char *buf_begin; char *buf_end; char *buf_cur_begin; char *buf_cur_end; }; struct input_stream_operations { /* Open the specified file for reading. */ void * (*open)(const char *path); /* Read data from the specified file (up to @count bytes; * return 0 if at end of file). */ size_t (*read)(void *fp, void *buf, size_t count, const char *name); /* Close the specified file. */ void (*close)(void *fp, const char *name); }; /* Input stream operations for reading raw data from a file descriptor */ static const struct input_stream_operations fd_input_stream_ops = { .open = input_fd_open, .read = xread, .close = xclose, }; /* Input stream operations for reading a gzip compressed file using zlib */ static const struct input_stream_operations gzfile_input_stream_ops = { .open = input_gzfile_open, .read = xgzread, .close = xgzclose, }; /* Auto-detects the correct input_stream_operations to use for the specified * file. */ static const struct input_stream_operations * select_input_stream_ops(const char *path) { /* XXX: We can't rewind standard input after checking for magic bytes, * so for that case we rely on the fact that gzread returns the literal * data if the stream does not, in fact, contain gzipped data. */ if (string_is_hyphen(path)) return &gzfile_input_stream_ops; /* Test for gzip magic bytes { 0x1f, 0x8b} */ unsigned char magic[2] = {0, 0}; void *tmp_fp; tmp_fp = input_fd_open(path); full_xread(tmp_fp, magic, sizeof(magic), path); xclose(tmp_fp, path); if (magic[0] == 0x1f && magic[1] == 0x8b) return &gzfile_input_stream_ops; /* Default to reading the raw data */ return &fd_input_stream_ops; } /* Creates an input stream to read lines from the file specified by @path. * * Gzip files are auto-detected. */ struct input_stream * new_input_stream(const char *path) { struct input_stream *in = xmalloc(sizeof(*in)); assert(path != NULL); /* Select input_stream_operations and open stream */ in->ops = select_input_stream_ops(path); in->fp = (*in->ops->open)(path); in->name = xstrdup(path); /* Allocate internal buffer */ in->buf_begin = xmalloc(IOSTREAM_BUFSIZE); in->buf_end = in->buf_begin + IOSTREAM_BUFSIZE; in->buf_cur_begin = in->buf_begin; in->buf_cur_end = in->buf_begin; return in; } /* Returns the name of the file being read. */ const char * input_stream_get_name(struct input_stream *in) { return in->name; } /* Returns a pointer to the next instance in any of the @delims in @buf of * length @size. * * There must be at least one delimiter. */ static char * find_delim(char *buf, size_t size, const char *delims) { /* Fast case: just one delimiter. */ if (delims[1] == '\0') return memchr(buf, delims[0], size); /* Multiple delimiters. */ for (size_t i = 0; i < size; i++) { const char *p = delims; do { if (buf[i] == *p) return &buf[i]; } while (*++p); } return NULL; } /* Reads delimited data from an input stream. Semantics are like getdelim(), * but aborts on read error and also allows multiple delimiters. */ ssize_t input_stream_getdelims(struct input_stream *in, char **lineptr, size_t *n, const char *delims) { assert(*delims != '\0'); /* offset = number of bytes copied to *lineptr buffer, excluding * terminating null byte */ size_t offset = 0; for (;;) { size_t navail; char *delim_ptr; size_t copysize; navail = in->buf_cur_end - in->buf_cur_begin; if (navail == 0) { /* No more data in internal buffer; try to fill it */ in->buf_cur_begin = in->buf_begin; navail = (*in->ops->read)(in->fp, in->buf_cur_begin, in->buf_end - in->buf_cur_begin, in->name); in->buf_cur_end = in->buf_cur_begin + navail; if (navail == 0) /* At end-of-file */ break; } /* Find the first delimiter in the internal buffer. If found, * copy up to and including the delimiter, then return (break * loop). If not found, copy all the data and try to read more * (continue loop). */ delim_ptr = find_delim(in->buf_cur_begin, navail, delims); if (delim_ptr) copysize = delim_ptr - in->buf_cur_begin + 1; else copysize = navail; if (offset + copysize + 1 < offset) { /* Very unlikely: size would overflow. */ fatal_error("Line or field in \"%s\" is too long!", in->name); } if (*n < offset + copysize + 1) { *n = max(*n * 3 / 2, offset + copysize + 1); *n = max(*n, 128); *lineptr = xrealloc(*lineptr, *n); } memcpy(*lineptr + offset, in->buf_cur_begin, copysize); offset += copysize; in->buf_cur_begin += copysize; if (delim_ptr) break; } if (offset == 0) return -1; (*lineptr)[offset] = '\0'; return offset; } /* Reads a line from an input stream. Semantics are like getline(), but aborts * on read error. */ ssize_t input_stream_getline(struct input_stream *in, char **lineptr, size_t *n) { return input_stream_getdelims(in, lineptr, n, "\n"); } /* Closes and frees an input stream. */ void free_input_stream(struct input_stream *in) { if (in) { (*in->ops->close)(in->fp, in->name); xfree(in->name, strlen(in->name)); xfree(in->buf_begin, IOSTREAM_BUFSIZE); xfree(in, sizeof(*in)); } } /***************************** * Output stream functions * *****************************/ static void * output_fd_open(const char *path, const char *filter_prog, const char *filter_prog_args) { assert(filter_prog == NULL); return xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); } static void * output_filter_open(const char *path, const char *filter_prog, const char *filter_prog_args) { assert(filter_prog != NULL); if (filter_prog_args == NULL) filter_prog_args = ""; size_t len = strlen(filter_prog) + 32 + strlen(path) + strlen(filter_prog_args); char command[len + 1]; FILE *f; char *p = command; p += sprintf(p, "%s %s", filter_prog, filter_prog_args); if (!string_is_hyphen(path)) sprintf(p, " > '%s'", path); f = popen(command, "w"); if (!f) fatal_error_with_errno("Failed to launch the command \"%s\"", command); return f; } static void * output_gzfile_open(const char *path, const char *filter_prog, const char *filter_prog_args) { assert(filter_prog == NULL); return xgzopen(path, "wb"); } struct output_stream_operations { /* Open the specified file for writing, possibly filtering the data * through a filter program. Must return the open file handle, * descriptor, or pointer cast to a void *. */ void *(*open)(const char *path, const char *filter_prog, const char *filter_prog_args); /* Write a buffer of data to the stream. */ void (*write)(void *fp, const void *buf, size_t count, const char *name); /* Flush and close the stream. */ void (*close)(void *fp, const char *name); }; /* Operations to write raw data to a file descriptor. */ static const struct output_stream_operations fd_output_stream_ops = { .open = output_fd_open, .write = xwrite, .close = xclose, }; /* Operations to write data through a filter program to the file. */ static const struct output_stream_operations filter_output_stream_ops = { .open = output_filter_open, .write = xfwrite, .close = xpclose, }; /* Operations to write gzip-compressed data. */ static const struct output_stream_operations gzfile_output_stream_ops = { .open = output_gzfile_open, .write = xgzwrite, .close = xgzclose, }; struct output_stream { const struct output_stream_operations *ops; void *fp; char *name; char *buf_begin; char *buf_end; char *buf_cur_end; }; /* Select the appropriate output_stream_operations based on the requested * compression type and whether a filter program was specified. */ static const struct output_stream_operations * select_output_stream_ops(enum out_compression_type ctype, bool have_filter_prog) { switch (ctype) { case OUT_COMPRESSION_NONE: if (have_filter_prog) return &filter_output_stream_ops; else return &fd_output_stream_ops; case OUT_COMPRESSION_GZIP: assert(!have_filter_prog); return &gzfile_output_stream_ops; default: assert(0); return NULL; } } /* * Creates a new output stream. * * @ctype * The compression type to use. * @path * Path to the file to write, or "-" for standard output. * @filter_prog * If non-NULL, the name of a program through which to filter the output, * and @ctype must be OUT_COMPRESSION_NONE. The filter program must read * from standard input and write to standard output. * @filter_prog_args * Additional text (arguments) to place on the command line for * @filter_prog. * * Returns the new, opened output stream; aborts on error. */ struct output_stream * new_output_stream(enum out_compression_type ctype, const char *path, const char *filter_prog, const char *filter_prog_args) { struct output_stream *out = xmalloc(sizeof(*out)); assert(path != NULL); /* Select output_stream_operations and open stream. */ out->ops = select_output_stream_ops(ctype, filter_prog != NULL); out->fp = (*out->ops->open)(path, filter_prog, filter_prog_args); out->name = xstrdup(path); /* Allocate internal buffer. */ out->buf_begin = xmalloc(IOSTREAM_BUFSIZE); out->buf_end = out->buf_begin + IOSTREAM_BUFSIZE; out->buf_cur_end = out->buf_begin; return out; } /* Returns the name of the file to which the output stream is writing. */ const char * output_stream_get_name(struct output_stream *out) { return out->name; } static void flush_output_stream(struct output_stream *out) { (*out->ops->write)(out->fp, out->buf_begin, out->buf_cur_end - out->buf_begin, out->name); out->buf_cur_end = out->buf_begin; } /* Writes a buffer of data to an output stream. */ void output_stream_write(struct output_stream *out, const void *_buf, size_t count) { const char *ptr = _buf; while (count) { if (out->buf_cur_end == out->buf_end) { /* Output buffer full; flush it. */ flush_output_stream(out); } /* Buffer as much data as possible. */ size_t tocopy = min(count, out->buf_end - out->buf_cur_end); memcpy(out->buf_cur_end, ptr, tocopy); out->buf_cur_end += tocopy; ptr += tocopy; count -= tocopy; } } /* Writes a null-terminated string to an output stream. */ void output_stream_fputs(struct output_stream *out, const char *s) { output_stream_write(out, s, strlen(s)); } /* Writes a byte to an output stream. */ void output_stream_fputc(struct output_stream *out, char c) { if (out->buf_cur_end == out->buf_end) flush_output_stream(out); *out->buf_cur_end++ = c; } /* Flushes, closes, and frees an output stream. */ void free_output_stream(struct output_stream *out) { if (out) { if (out->buf_cur_end > out->buf_begin) flush_output_stream(out); (*out->ops->close)(out->fp, out->name); xfree(out->name, strlen(out->name)); xfree(out->buf_begin, IOSTREAM_BUFSIZE); xfree(out, sizeof(*out)); } } FLASH-1.2.11/iostream.h000066400000000000000000000026341237001226200144250ustar00rootroot00000000000000#ifndef _FLASH_IOSTREAM_H_ #define _FLASH_IOSTREAM_H_ #include #include #include /* Input stream functions */ struct input_stream; extern struct input_stream * new_input_stream(const char *filename); extern const char * input_stream_get_name(struct input_stream *in); extern ssize_t input_stream_getdelims(struct input_stream *in, char **lineptr, size_t *n, const char *delims); extern ssize_t input_stream_getline(struct input_stream *in, char **lineptr, size_t *n); extern void free_input_stream(struct input_stream *in); /* Output stream functions */ struct output_stream; enum out_compression_type { OUT_COMPRESSION_NONE, OUT_COMPRESSION_GZIP, }; extern struct output_stream * new_output_stream(enum out_compression_type ctype, const char *path, const char *filter_prog, const char *filter_prog_args); extern const char * output_stream_get_name(struct output_stream *out); extern void output_stream_write(struct output_stream *out, const void *buf, size_t count); extern void output_stream_fputs(struct output_stream *out, const char *s); extern void output_stream_fputc(struct output_stream *out, char c); extern void free_output_stream(struct output_stream *out); /* fopen() and fclose() wrappers */ extern void * xfopen(const char *filename, const char *mode); extern void xfclose(FILE *fp, const char *name); #endif /* _FLASH_IOSTREAM_H_ */ FLASH-1.2.11/read.h000066400000000000000000000022371237001226200135140ustar00rootroot00000000000000#ifndef _FLASH_READ_H_ #define _FLASH_READ_H_ #include /* In-memory representation of a DNA sequence read. */ struct read { /* The "tag" that identifies the read. */ char *tag; /* The sequence of the read in ASCII characters (A, C, G, T, N). */ char *seq; /* The quality scores of the read, scaled to start at 0. */ char *qual; /* Length of the tag string. */ int tag_len; /* Length of the sequence string (number of bases in the read). */ int seq_len; /* Length of the quality string (will be equal to seq_len). */ int qual_len; /* Allocated sizes of the seq, tag, and qual buffers, respectively. */ size_t seq_bufsz; size_t tag_bufsz; size_t qual_bufsz; }; struct input_stream; #include extern void reverse_complement(struct read *r); extern void clean_read(struct read *r, int phred_offset, struct input_stream *in, uint64_t line_no); extern void clean_read_for_write(struct read *r, int phred_offset); extern void copy_tag(struct read *to, const struct read *from); extern void get_combined_tag(const struct read *read_1, const struct read *read_2, struct read *combined_read); #endif /* _FLASH_READ_H_ */ FLASH-1.2.11/read_io.c000066400000000000000000000257361237001226200142070ustar00rootroot00000000000000/* * read_io.c: Code for input and output of reads, e.g. from/to FASTQ files. */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include "iostream.h" #include "read.h" #include "read_io.h" #include "util.h" #include #include /****************************************** * Read input * ******************************************/ static bool load_fastq_read(struct input_stream *in, struct read *r, uint64_t *line_no_p) { ssize_t ret; /* tag * sequence * + * quality */ ret = input_stream_getline(in, &r->tag, &r->tag_bufsz); if (ret <= 0) return false; if (ret > INT_MAX) goto too_long; ++*line_no_p; r->tag_len = ret; ret = input_stream_getline(in, &r->seq, &r->seq_bufsz); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; ++*line_no_p; r->seq_len = ret; ret = input_stream_getline(in, &r->qual, &r->qual_bufsz); if (ret <= 0) goto unexpected_eof; if (r->qual[0] != '+') goto expected_plus; ++*line_no_p; ret = input_stream_getline(in, &r->qual, &r->qual_bufsz); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; ++*line_no_p; r->qual_len = ret; return true; unexpected_eof: fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", input_stream_get_name(in), *line_no_p); expected_plus: fatal_error("Expected '+' character in FASTQ separator in \"%s\" " "(line %"PRIu64")", input_stream_get_name(in), *line_no_p); too_long: fatal_error("Line %"PRIu64" in \"%s\" is too long", *line_no_p, input_stream_get_name(in)); } static bool load_tab_delimited_read(struct input_stream *in, struct read *r, uint64_t *line_no_p) { ssize_t ret; const char *delims = "\t\n"; /* tag sequence quality */ ret = input_stream_getdelims(in, &r->tag, &r->tag_bufsz, delims); if (ret <= 0) return false; if (ret > INT_MAX) goto too_long; if (r->tag[ret - 1] != '\t') goto expected_tab; r->tag_len = ret; ret = input_stream_getdelims(in, &r->seq, &r->seq_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; if (r->seq[ret - 1] != '\t') goto expected_tab; r->seq_len = ret; ret = input_stream_getdelims(in, &r->qual, &r->qual_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; if (r->qual[ret - 1] == '\t') goto expected_newline; r->qual_len = ret; ++*line_no_p; return true; too_long: fatal_error("Field in line %"PRIu64" of \"%s\" is too long", *line_no_p, input_stream_get_name(in)); unexpected_eof: fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", input_stream_get_name(in), *line_no_p); expected_tab: fatal_error("Invalid data in \"%s\": " "expected tab character (line %"PRIu64")", input_stream_get_name(in), *line_no_p); expected_newline: fatal_error("Invalid data in \"%s\": " "expected newline character (line %"PRIu64")", input_stream_get_name(in), *line_no_p); } static bool load_tab_delimited_pair(struct input_stream *in, struct read *r1, struct read *r2, uint64_t *line_no_p) { ssize_t ret; const char *delims = "\t\n"; /* tag seq_1 qual_1 seq_2 qual_2 */ ret = input_stream_getdelims(in, &r1->tag, &r1->tag_bufsz, delims); if (ret <= 0) return false; if (ret > INT_MAX) goto too_long; if (r1->tag[ret - 1] != '\t') goto expected_tab; r1->tag_len = ret; ret = input_stream_getdelims(in, &r1->seq, &r1->seq_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; if (r1->seq[ret - 1] != '\t') goto expected_tab; r1->seq_len = ret; ret = input_stream_getdelims(in, &r1->qual, &r1->qual_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; r1->qual_len = ret; if (r1->qual[ret - 1] == '\n') { /* Actually just a single read; use a void second read. */ r2->tag_len = 0; r2->seq_len = 0; r2->qual_len = 0; ++*line_no_p; return true; } /* Set tag of read 2 to be the same as the tag of read 1 */ copy_tag(r2, r1); ret = input_stream_getdelims(in, &r2->seq, &r2->seq_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; if (r2->seq[ret - 1] != '\t') goto expected_tab; r2->seq_len = ret; ret = input_stream_getdelims(in, &r2->qual, &r2->qual_bufsz, delims); if (ret <= 0) goto unexpected_eof; if (ret > INT_MAX) goto too_long; if (r2->qual[ret - 1] == '\t') goto expected_newline; r2->qual_len = ret; ++*line_no_p; return true; too_long: fatal_error("Field in line %"PRIu64" of \"%s\" is too long", *line_no_p, input_stream_get_name(in)); unexpected_eof: fatal_error("Unexpected EOF reading \"%s\" (line %"PRIu64")", input_stream_get_name(in), *line_no_p); expected_tab: fatal_error("Invalid data in \"%s\": " "expected tab character (line %"PRIu64")", input_stream_get_name(in), *line_no_p); expected_newline: fatal_error("Invalid data in \"%s\": " "expected newline character (line %"PRIu64")", input_stream_get_name(in), *line_no_p); } /* * Loads the next read from the stream @in. * * @iparams specifies the format being used; e.g. FASTQ with a certain phred * offset. * * In each resulting read, whitespace is stripped from the end of the sequence, * tag, and quality scores. The sequence is translated into only the characters * A, C, G, T, and N, and the quality values are re-scaled to start at 0. * * Returns true on success, false on end-of-file. Aborts on read error or if * the data is invalid. */ bool load_read(struct input_stream *in, const struct read_format_params *iparams, struct read *r, uint64_t *line_no_p) { bool ret; switch (iparams->fmt) { case READ_FORMAT_FASTQ: ret = load_fastq_read(in, r, line_no_p); break; case READ_FORMAT_TAB_DELIMITED: ret = load_tab_delimited_read(in, r, line_no_p); break; default: assert(0); ret = false; } if (ret) clean_read(r, iparams->phred_offset, in, *line_no_p); return ret; } /* * Similar to load_read(), but loads a pair of reads from the file instead. * This is only relevant (and must only be called) for file formats that store * both reads of the pair in the same sequential file. * * As a special case, this function may only fill in @r1, and set @r2->seq_len * to 0, to indicate that the next record in the file was actually an unpaired * read, not a read pair. This is possible in formats for which * read_format_supports_mixed_reads() returns true (e.g. tab-delimited). */ bool load_read_pair(struct input_stream *in, const struct read_format_params *iparams, struct read *r1, struct read *r2, uint64_t *line_no_p) { bool ret; switch (iparams->fmt) { case READ_FORMAT_FASTQ: ret = load_fastq_read(in, r1, line_no_p); if (ret && !load_fastq_read(in, r2, line_no_p)) fatal_error("Interleaved FASTQ file \"%s\" has an " "odd number of reads", input_stream_get_name(in)); break; case READ_FORMAT_TAB_DELIMITED: ret = load_tab_delimited_pair(in, r1, r2, line_no_p); break; default: assert(0); ret = false; } if (ret) { clean_read(r1, iparams->phred_offset, in, *line_no_p); clean_read(r2, iparams->phred_offset, in, *line_no_p); } return ret; } /****************************************** * Read output * ******************************************/ static void write_fastq_read(struct output_stream *out, const struct read *r) { /* Add '@' to tag if missing */ if (r->tag_len == 0 || r->tag[0] != '@') output_stream_fputc(out, '@'); output_stream_write(out, r->tag, r->tag_len); output_stream_fputc(out, '\n'); output_stream_write(out, r->seq, r->seq_len); output_stream_fputc(out, '\n'); output_stream_fputc(out, '+'); output_stream_fputc(out, '\n'); output_stream_write(out, r->qual, r->qual_len); output_stream_fputc(out, '\n'); } static void write_tab_delimited_read(struct output_stream *out, const struct read *r) { const char *tag = r->tag; int tag_len = r->tag_len; /* Strip '@' from tag */ if (tag_len > 0 && tag[0] == '@') tag++, tag_len--; output_stream_write(out, tag, tag_len); output_stream_fputc(out, '\t'); output_stream_write(out, r->seq, r->seq_len); output_stream_fputc(out, '\t'); output_stream_write(out, r->qual, r->qual_len); output_stream_fputc(out, '\n'); } static void write_tab_delimited_pair(struct output_stream *out, const struct read *r1, const struct read *r2) { const char *tag = r1->tag; int tag_len = r1->tag_len; /* Strip '@' and /1 or /2 from tag */ if (tag_len > 0 && tag[0] == '@') tag++, tag_len--; if (tag_len >= 2 && tag[tag_len - 2] == '/' && (tag[tag_len - 1] == '1' || tag[tag_len - 1] == '2')) tag_len -= 2; output_stream_write(out, tag, tag_len); output_stream_fputc(out, '\t'); output_stream_write(out, r1->seq, r1->seq_len); output_stream_fputc(out, '\t'); output_stream_write(out, r1->qual, r1->qual_len); output_stream_fputc(out, '\t'); output_stream_write(out, r2->seq, r2->seq_len); output_stream_fputc(out, '\t'); output_stream_write(out, r2->qual, r2->qual_len); output_stream_fputc(out, '\n'); } /* Writes a read to the specified output stream in the format specified by * @oparams. * * Modifies the qual string of @r! */ void write_read(struct output_stream *out, const struct read_format_params *oparams, struct read *r) { clean_read_for_write(r, oparams->phred_offset); switch (oparams->fmt) { case READ_FORMAT_FASTQ: write_fastq_read(out, r); break; case READ_FORMAT_TAB_DELIMITED: write_tab_delimited_read(out, r); break; default: assert(0); } } /* Writes a read pair to the specified output stream in the format specified by * @oparams. * * Modifies the qual string of @r1 and @r2! */ void write_read_pair(struct output_stream *out, const struct read_format_params *oparams, struct read *r1, struct read *r2) { clean_read_for_write(r1, oparams->phred_offset); clean_read_for_write(r2, oparams->phred_offset); switch (oparams->fmt) { case READ_FORMAT_FASTQ: /* Interleaved FASTQ format */ write_fastq_read(out, r1); write_fastq_read(out, r2); break; case READ_FORMAT_TAB_DELIMITED: /* Tab-delimited format, with two reads in a pair on one line */ write_tab_delimited_pair(out, r1, r2); break; default: assert(0); } } FLASH-1.2.11/read_io.h000066400000000000000000000021741237001226200142030ustar00rootroot00000000000000#ifndef _FLASH_READ_IO_H_ #define _FLASH_READ_IO_H_ #include #include struct output_stream; struct input_stream; struct read; struct read_format_params { enum { READ_FORMAT_FASTQ, READ_FORMAT_TAB_DELIMITED, } fmt; int phred_offset; }; /* Returns true iff the specified read format supports both unpaired and paired * reads in the same file. */ static inline bool read_format_supports_mixed_reads(const struct read_format_params *params) { return params->fmt == READ_FORMAT_TAB_DELIMITED; } extern void write_read(struct output_stream *out, const struct read_format_params *oparams, struct read *read); extern void write_read_pair(struct output_stream *out, const struct read_format_params *oparams, struct read *read_1, struct read *read_2); extern bool load_read(struct input_stream *in, const struct read_format_params *iparams, struct read *read, uint64_t *line_no_p); extern bool load_read_pair(struct input_stream *in, const struct read_format_params *iparams, struct read *read_1, struct read *read_2, uint64_t *line_no_p); #endif /* _FLASH_READ_IO_H_ */ FLASH-1.2.11/read_queue.c000066400000000000000000000522471237001226200147210ustar00rootroot00000000000000/* * read_queue.c: Code to set up reader/writer threads and shared queues to pass * reads between threads in memory. */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include "iostream.h" #include "read.h" #include "read_io.h" #include "read_queue.h" #include "util.h" #include #include #include #include #include #include static struct read * new_read(void) { return xzalloc(sizeof(struct read)); } static void free_read(struct read *r) { if (r) { xfree(r->tag, r->tag_bufsz); xfree(r->seq, r->seq_bufsz); xfree(r->qual, r->qual_bufsz); xfree(r, sizeof(*r)); } } static struct read_set * new_read_set(size_t num_reads, bool full) { struct read_set *s = xmalloc(sizeof(*s) + num_reads * sizeof(s->reads[0])); if (full) { for (size_t i = 0; i < num_reads; i++) s->reads[i] = new_read(); } else { for (size_t i = 0; i < num_reads; i++) s->reads[i] = NULL; } s->filled = 0; s->num_reads = num_reads; return s; } void free_read_set(struct read_set *s) { if (s) { for (size_t i = 0; i < s->num_reads; i++) free_read(s->reads[i]); xfree(s, sizeof(*s)); } } static void init_mutex(pthread_mutex_t *mutex) { if (pthread_mutex_init(mutex, NULL)) fatal_error_with_errno("Failed to initialize mutex"); } static void init_cond(pthread_cond_t *cond) { if (pthread_cond_init(cond, NULL)) fatal_error_with_errno("Failed to initialize condition variable"); } /* * Producer-consumer queue; it holds pointers to `struct read_sets', which can * be added or removed from the queue in a thread-safe manner using * read_queue_put() and read_queue_get(), respectively. */ struct read_queue { size_t size; size_t front; size_t filled; bool terminated; struct read_set **read_sets; pthread_mutex_t lock; pthread_cond_t read_set_avail_cond; pthread_cond_t space_avail_cond; }; static struct read_queue * new_read_queue(size_t size, size_t reads_per_set, bool full) { struct read_queue *q = xmalloc(sizeof(*q)); q->read_sets = xmalloc(size * sizeof(q->read_sets[0])); q->size = size; q->front = 0; if (full) { for (size_t i = 0; i < size; i++) q->read_sets[i] = new_read_set(reads_per_set, true); q->filled = size; } else { for (size_t i = 0; i < size; i++) q->read_sets[i] = NULL; q->filled = 0; } q->terminated = false; init_mutex(&q->lock); init_cond(&q->read_set_avail_cond); init_cond(&q->space_avail_cond); return q; } static void free_read_queue(struct read_queue *q) { if (q) { size_t filled = q->filled; size_t i = q->front; while (filled--) { free_read_set(q->read_sets[i]); i = (i + 1) % q->size; } xfree(q->read_sets, q->size * sizeof(q->read_sets[0])); pthread_mutex_destroy(&q->lock); pthread_cond_destroy(&q->read_set_avail_cond); pthread_cond_destroy(&q->space_avail_cond); xfree(q, sizeof(*q)); } } /* Retrieves the next available read set from the queue, blocking until one is * available. Or, returns NULL if the queue has terminated and no more read * sets are available. */ static struct read_set * read_queue_get(struct read_queue *q) { struct read_set *s; pthread_mutex_lock(&q->lock); while (q->filled == 0 && !q->terminated) pthread_cond_wait(&q->read_set_avail_cond, &q->lock); if (q->filled != 0) { s = q->read_sets[q->front]; q->front = (q->front + 1) % q->size; q->filled--; pthread_cond_signal(&q->space_avail_cond); } else s = NULL; pthread_mutex_unlock(&q->lock); return s; } /* Put a read set into the queue, blocking until there is an empty space * available. */ static void read_queue_put(struct read_queue *q, struct read_set *s) { pthread_mutex_lock(&q->lock); while (q->filled == q->size) pthread_cond_wait(&q->space_avail_cond, &q->lock); q->read_sets[(q->front + q->filled) % q->size] = s; q->filled++; pthread_cond_signal(&q->read_set_avail_cond); pthread_mutex_unlock(&q->lock); } /* "Terminate" the specified queue. This will cause read_queue_get() to return * NULL once the queue is empty. */ static void read_queue_terminate(struct read_queue *q) { pthread_mutex_lock(&q->lock); q->terminated = true; pthread_cond_broadcast(&q->read_set_avail_cond); pthread_mutex_unlock(&q->lock); } struct reader_params { struct input_stream *in; const struct read_format_params *iparams; bool verbose; struct read_queue *avail_read_q; struct read_queue *unprocessed_read_1_q; struct read_queue *unprocessed_read_2_q; struct read_queue *unpaired_read_q; }; struct writer_params { struct output_stream *out; const struct read_format_params *oparams; struct read_queue *to_write_queue_1; struct read_queue *to_write_queue_2; struct read_queue *avail_queue; }; static void processed(uint64_t pair_no) { info("Processed %"PRIu64" read pairs", pair_no); } static void * reader1_proc(void *_params) { struct reader_params *params = _params; uint64_t pair_no = 0; uint64_t line_no = 1; struct read_set *s; for (;;) { s = read_queue_get(params->avail_read_q); for (s->filled = 0; s->filled < s->num_reads; s->filled++) { if (!load_read(params->in, params->iparams, s->reads[s->filled], &line_no)) goto eof_reached; if (params->verbose && ++pair_no % 25000 == 0) processed(pair_no); } /* Note: although we're placing the set in * 'unprocessed_read_1_q', the set may in fact be read 2, not * read 1. This procedure works the same way in both cases. */ read_queue_put(params->unprocessed_read_1_q, s); } eof_reached: if (params->verbose && pair_no % 25000 != 0) processed(pair_no); if (s->filled) read_queue_put(params->unprocessed_read_1_q, s); else free_read_set(s); read_queue_terminate(params->unprocessed_read_1_q); free_input_stream(params->in); xfree(params, sizeof(*params)); return NULL; } static void * reader2_proc(void *_params) { struct reader_params *params = _params; struct read_set *s_read1, *s_read2, *s_unpaired = NULL; uint64_t pair_no = 0; uint64_t line_no = 1; s_read1 = read_queue_get(params->avail_read_q); s_read1->filled = 0; s_read2 = read_queue_get(params->avail_read_q); s_read2->filled = 0; if (params->unpaired_read_q) { s_unpaired = read_queue_get(params->avail_read_q); s_unpaired->filled = 0; } while (load_read_pair(params->in, params->iparams, s_read1->reads[s_read1->filled], s_read2->reads[s_read1->filled], &line_no)) { if (s_read2->reads[s_read1->filled]->seq_len) { /* Read pair. */ ++s_read1->filled; ++s_read2->filled; if (s_read1->filled == s_read1->num_reads) { read_queue_put(params->unprocessed_read_1_q, s_read1); read_queue_put(params->unprocessed_read_2_q, s_read2); s_read1 = read_queue_get(params->avail_read_q); s_read1->filled = 0; s_read2 = read_queue_get(params->avail_read_q); s_read2->filled = 0; } if (params->verbose && ++pair_no % 25000 == 0) processed(pair_no); } else if (params->unpaired_read_q) { /* Actually an unpaired read. */ struct read *r = s_read1->reads[s_read1->filled]; s_read1->reads[s_read1->filled] = s_unpaired->reads[s_unpaired->filled]; s_unpaired->reads[s_unpaired->filled] = r; ++s_unpaired->filled; if (s_unpaired->filled == s_unpaired->num_reads) { s_unpaired->type = READS_UNPAIRED; read_queue_put(params->unpaired_read_q, s_unpaired); s_unpaired = read_queue_get(params->avail_read_q); s_unpaired->filled = 0; } } } if (params->verbose && pair_no % 25000 != 0) processed(pair_no); if (s_read1->filled) read_queue_put(params->unprocessed_read_1_q, s_read1); else free_read_set(s_read1); if (s_read2->filled) read_queue_put(params->unprocessed_read_2_q, s_read2); else free_read_set(s_read2); if (s_unpaired) { if (s_unpaired->filled) { s_unpaired->type = READS_UNPAIRED; read_queue_put(params->unpaired_read_q, s_unpaired); } else { free_read_set(s_unpaired); } } read_queue_terminate(params->unprocessed_read_1_q); read_queue_terminate(params->unprocessed_read_2_q); free_input_stream(params->in); xfree(params, sizeof(*params)); return NULL; } static void * writer_proc(void *_params) { struct writer_params *params = _params; struct read_set *s1, *s2; for (;;) { s1 = read_queue_get(params->to_write_queue_1); if (!s1) break; if (params->to_write_queue_2 && s1->type == READS_UNCOMBINED) { /* Get other read in uncombined pair */ s2 = read_queue_get(params->to_write_queue_2); assert(s2); assert(s1->filled == s2->filled); } else { s2 = NULL; } for (size_t i = 0; i < s1->filled; i++) { if (s2) write_read_pair(params->out, params->oparams, s1->reads[i], s2->reads[i]); else write_read(params->out, params->oparams, s1->reads[i]); } read_queue_put(params->avail_queue, s1); if (s2) read_queue_put(params->avail_queue, s2); } free_output_stream(params->out); xfree(params, sizeof(*params)); return NULL; } static pthread_t start_reader2(struct input_stream *in, const struct read_format_params *iparams, bool verbose, struct read_queue *avail_read_q, struct read_queue *unprocessed_read_1_q, struct read_queue *unprocessed_read_2_q, struct read_queue *unpaired_read_q) { struct reader_params *params = xmalloc(sizeof(*params)); params->in = in; params->iparams = iparams; params->verbose = verbose; params->avail_read_q = avail_read_q; params->unprocessed_read_1_q = unprocessed_read_1_q; params->unprocessed_read_2_q = unprocessed_read_2_q; params->unpaired_read_q = unpaired_read_q; return create_thread(reader2_proc, params); } static pthread_t start_reader1(struct input_stream *in, const struct read_format_params *iparams, bool verbose, struct read_queue *avail_read_q, struct read_queue *unprocessed_read_q) { struct reader_params *params = xmalloc(sizeof(*params)); params->in = in; params->iparams = iparams; params->verbose = verbose; params->avail_read_q = avail_read_q; params->unprocessed_read_1_q = unprocessed_read_q; params->unprocessed_read_2_q = NULL; params->unpaired_read_q = NULL; return create_thread(reader1_proc, params); } static pthread_t start_writer2(struct output_stream *out, const struct read_format_params *oparams, struct read_queue *to_write_queue_1, struct read_queue *to_write_queue_2, struct read_queue *avail_queue) { struct writer_params *params = xmalloc(sizeof(*params)); params->out = out; params->oparams = oparams; params->to_write_queue_1 = to_write_queue_1; params->to_write_queue_2 = to_write_queue_2; params->avail_queue = avail_queue; return create_thread(writer_proc, params); } static pthread_t start_writer1(struct output_stream *out, const struct read_format_params *oparams, struct read_queue *to_write_queue, struct read_queue *avail_queue) { return start_writer2(out, oparams, to_write_queue, NULL, avail_queue); } struct read_io_handle { pthread_t reader_1; pthread_t reader_2; pthread_t writer_1; pthread_t writer_2; pthread_t writer_3; bool reader_1_started; bool reader_2_started; bool writer_1_started; bool writer_2_started; bool writer_3_started; unsigned combiner_threads_remaining; pthread_mutex_t combiner_threads_remaining_mutex; struct read_queue *avail_read_q; struct read_queue *unprocessed_read_1_q; struct read_queue *unprocessed_read_2_q; struct read_queue *combined_read_q; struct read_queue *uncombined_read_1_q; struct read_queue *uncombined_read_2_q; pthread_mutex_t get_unprocessed_pair_mutex; pthread_mutex_t put_uncombined_pair_mutex; }; /* Retrieves some unprocessed read pairs from the I/O layer. Returns %true iff * more reads were available; returns false if end of file was reached. */ bool get_unprocessed_read_pairs(struct read_io_handle *h, struct read_set **s1_p, struct read_set **s2_p) { /* get_unprocessed_pair_mutex ensures the reads are paired up correctly. */ struct read_set *s1, *s2; pthread_mutex_lock(&h->get_unprocessed_pair_mutex); s1 = read_queue_get(h->unprocessed_read_1_q); s2 = read_queue_get(h->unprocessed_read_2_q); pthread_mutex_unlock(&h->get_unprocessed_pair_mutex); if (s1 && s2) { if (s1->filled != s2->filled) goto mismatch; *s1_p = s1; *s2_p = s2; return true; } if (s1 || s2) goto mismatch; return false; mismatch: fatal_error("Input files do not contain the same number of reads"); } /* Submits a set of combined reads to the I/O layer to be written. */ void put_combined_reads(struct read_io_handle *h, struct read_set *s) { s->type = READS_COMBINED; read_queue_put(h->combined_read_q, s); } /* Submits a set of uncombined read pairs to the I/O layer to be written. */ void put_uncombined_read_pairs(struct read_io_handle *h, struct read_set *s1, struct read_set *s2) { s1->type = READS_UNCOMBINED; s2->type = READS_UNCOMBINED; /* put_unprocessed_pair_mutex ensures the reads are paired up correctly. */ pthread_mutex_lock(&h->put_uncombined_pair_mutex); read_queue_put(h->uncombined_read_1_q, s1); read_queue_put(h->uncombined_read_2_q, s2); pthread_mutex_unlock(&h->put_uncombined_pair_mutex); } /* Retrieve a read set (full of read structures) that is ready to be reused. */ struct read_set * get_avail_read_set(struct read_io_handle *h) { struct read_set *s; s = read_queue_get(h->avail_read_q); s->filled = 0; return s; } /* Return a set of read pairs to the pool for reuse. */ void put_avail_read_pairs(struct read_io_handle *h, struct read_set *s1, struct read_set *s2) { read_queue_put(h->avail_read_q, s1); read_queue_put(h->avail_read_q, s2); } /* Notify the I/O layer that a combiner thread has terminated. * When all the combiner threads have been terminated, the writers will shut * down. */ void notify_combiner_terminated(struct read_io_handle *h) { pthread_mutex_lock(&h->combiner_threads_remaining_mutex); if (--h->combiner_threads_remaining == 0) { /* Terminate the writer queues. */ read_queue_terminate(h->combined_read_q); if (h->uncombined_read_1_q != h->avail_read_q && h->uncombined_read_1_q != h->combined_read_q) read_queue_terminate(h->uncombined_read_1_q); if (h->uncombined_read_2_q != h->avail_read_q) read_queue_terminate(h->uncombined_read_2_q); } pthread_mutex_unlock(&h->combiner_threads_remaining_mutex); } struct read_set * new_empty_read_set(struct read_io_handle *h) { return new_read_set(BASE_READS_PER_READ_SET + (h->combiner_threads_remaining * PERTHREAD_READS_PER_READ_SET), false); } /* Starts the FLASH I/O layer, which is responsible for input/output of reads. * * If @in_2 is not NULL, then @in_1 and @in_2 are the input files for read 1 and * read 2 of the pairs, respectively. Otherwise @in_1 contains both read 1 and * read 2 of the pairs interleaved. * * Either 1, 2, or 3 output files may be specified --- see below for more * details. */ struct read_io_handle * start_readers_and_writers(struct input_stream *in_1, struct input_stream *in_2, struct output_stream *out_combined, struct output_stream *out_uncombined_1, struct output_stream *out_uncombined_2, const struct read_format_params *iparams, const struct read_format_params *oparams, unsigned num_combiner_threads, bool verbose) { assert(in_1 != NULL); assert(out_combined != NULL && (out_uncombined_1 != NULL || out_uncombined_2 == NULL)); assert(iparams != NULL); assert(oparams != NULL); assert(num_combiner_threads > 0); if (verbose) info("Starting reader and writer threads"); struct read_io_handle *h = xzalloc(sizeof(*h)); size_t reads_per_set = BASE_READS_PER_READ_SET + (num_combiner_threads * PERTHREAD_READS_PER_READ_SET); size_t queue_size = num_combiner_threads * QUEUE_SIZE_PER_THREAD; h->avail_read_q = new_read_queue(queue_size * 3, reads_per_set, true); h->unprocessed_read_1_q = new_read_queue(queue_size, reads_per_set, false); h->unprocessed_read_2_q = new_read_queue(queue_size, reads_per_set, false); h->combined_read_q = new_read_queue(queue_size, reads_per_set, false); init_mutex(&h->get_unprocessed_pair_mutex); init_mutex(&h->put_uncombined_pair_mutex); h->combiner_threads_remaining = num_combiner_threads; init_mutex(&h->combiner_threads_remaining_mutex); /* Start writers. */ if (out_uncombined_2) { /* All 3 output files specified: one for combined reads, one for * read 1 of uncombined pairs, and one for read 2 of uncombined * pairs. */ h->uncombined_read_1_q = new_read_queue(queue_size, reads_per_set, false); h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); h->writer_1 = start_writer1(out_combined, oparams, h->combined_read_q, h->avail_read_q); h->writer_1_started = true; h->writer_2 = start_writer1(out_uncombined_1, oparams, h->uncombined_read_1_q, h->avail_read_q); h->writer_2_started = true; h->writer_3 = start_writer1(out_uncombined_2, oparams, h->uncombined_read_2_q, h->avail_read_q); h->writer_3_started = true; } else if (out_uncombined_1) { /* 2 output files specified: one for combined reads and one for * uncombined pairs. */ h->uncombined_read_1_q = new_read_queue(queue_size, reads_per_set, false); h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); h->writer_1 = start_writer1(out_combined, oparams, h->combined_read_q, h->avail_read_q); h->writer_1_started = true; h->writer_2 = start_writer2(out_uncombined_1, oparams, h->uncombined_read_1_q, h->uncombined_read_2_q, h->avail_read_q); h->writer_2_started = true; } else { /* 1 output file specified: combined reads, plus optionally * uncombined pairs if supported by the format. */ if (read_format_supports_mixed_reads(oparams)) { h->uncombined_read_1_q = h->combined_read_q; h->uncombined_read_2_q = new_read_queue(queue_size, reads_per_set, false); h->writer_1 = start_writer2(out_combined, oparams, h->combined_read_q, h->uncombined_read_2_q, h->avail_read_q); h->writer_1_started = true; } else { /* Can only output combined reads. * Reroute uncombined reads back to the queue of * available (for reuse) reads. */ h->uncombined_read_1_q = h->avail_read_q; h->uncombined_read_2_q = h->avail_read_q; h->writer_1 = start_writer1(out_combined, oparams, h->combined_read_q, h->avail_read_q); h->writer_1_started = true; } } /* Start readers. */ if (in_2) { /* Two input files: read 1 in each pair comes from the first * file, and read 2 in each pair comes from the second file. * * Only set @verbose for one. */ h->reader_1 = start_reader1(in_1, iparams, verbose, h->avail_read_q, h->unprocessed_read_1_q); h->reader_1_started = true; h->reader_2 = start_reader1(in_2, iparams, false, h->avail_read_q, h->unprocessed_read_2_q); h->reader_2_started = true; } else { /* One input file: both reads in each pair come from the same * file. */ struct read_queue *unpaired_read_q = NULL; if (read_format_supports_mixed_reads(iparams)) { if (!out_uncombined_2 && read_format_supports_mixed_reads(oparams)) unpaired_read_q = h->uncombined_read_1_q; else warning("Any unpaired reads in the input file " "will be ignored!\n\t" "Use tab-delimited output to " "preserve them."); } h->reader_1 = start_reader2(in_1, iparams, verbose, h->avail_read_q, h->unprocessed_read_1_q, h->unprocessed_read_2_q, unpaired_read_q); h->reader_1_started = true; } return h; } /* Terminates the FLASH I/O layer, which is responsible for input/output of * reads. */ void stop_readers_and_writers(struct read_io_handle *h) { if (h->reader_1_started) join_thread(h->reader_1); if (h->reader_2_started) join_thread(h->reader_2); if (h->writer_1_started) join_thread(h->writer_1); if (h->writer_2_started) join_thread(h->writer_2); if (h->writer_3_started) join_thread(h->writer_3); free_read_queue(h->avail_read_q); free_read_queue(h->unprocessed_read_1_q); free_read_queue(h->unprocessed_read_2_q); free_read_queue(h->combined_read_q); if (h->uncombined_read_1_q != h->avail_read_q && h->uncombined_read_1_q != h->combined_read_q) free_read_queue(h->uncombined_read_1_q); if (h->uncombined_read_2_q != h->avail_read_q) free_read_queue(h->uncombined_read_2_q); pthread_mutex_destroy(&h->put_uncombined_pair_mutex); pthread_mutex_destroy(&h->get_unprocessed_pair_mutex); pthread_mutex_destroy(&h->combiner_threads_remaining_mutex); xfree(h, sizeof(*h)); } FLASH-1.2.11/read_queue.h000066400000000000000000000043231237001226200147160ustar00rootroot00000000000000#ifndef _FLASH_READ_QUEUE_H_ #define _FLASH_READ_QUEUE_H_ #include struct read; struct read_format_params; struct input_stream; struct output_stream; /* BASE_READS_PER_READ_SET: The base number of reads per read set (i.e. per * chunk processed by combiner threads). This number must be at least 1; it is * a heuristic value that affects performance only. The faster the core * algorithm runs, the higher it should be. * * PERTHREAD_READS_PER_READ_SET: Additional number of reads per read set per * combiner thread. */ #if defined(__GNUC__) && defined(__SSE2__) # define BASE_READS_PER_READ_SET 30 # define PERTHREAD_READS_PER_READ_SET 5 #else # define BASE_READS_PER_READ_SET 24 # define PERTHREAD_READS_PER_READ_SET 4 #endif /* NUmber of read sets to allocate per combiner thread. Must be at least 6. */ #define QUEUE_SIZE_PER_THREAD 8 struct read_io_handle; struct read_set { unsigned filled; unsigned num_reads; enum { READS_UNCOMBINED, READS_COMBINED, READS_UNPAIRED, } type; struct read *reads[]; }; extern struct read_io_handle * start_readers_and_writers(struct input_stream *in_1, struct input_stream *in_2, struct output_stream *out_combined, struct output_stream *out_uncombined_1, struct output_stream *out_uncombined_2, const struct read_format_params *iparams, const struct read_format_params *oparams, unsigned num_combiner_threads, bool verbose); extern struct read_set * get_avail_read_set(struct read_io_handle *handle); extern bool get_unprocessed_read_pairs(struct read_io_handle *handle, struct read_set **s1_ret, struct read_set **s2_ret); extern void put_combined_reads(struct read_io_handle *handle, struct read_set *s); extern void put_uncombined_read_pairs(struct read_io_handle *handle, struct read_set *s1, struct read_set *s2); extern void put_avail_read_pairs(struct read_io_handle *handle, struct read_set *s1, struct read_set *s2); extern void notify_combiner_terminated(struct read_io_handle *h); extern struct read_set * new_empty_read_set(struct read_io_handle *h); extern void free_read_set(struct read_set *s); extern void stop_readers_and_writers(struct read_io_handle *h); #endif /* _FLASH_READ_QUEUE_H_ */ FLASH-1.2.11/read_util.c000066400000000000000000000153111237001226200145410ustar00rootroot00000000000000/* * read_util.c: Utility functions for processing reads */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include "read.h" #include "iostream.h" #include "util.h" #include #include #include /* * A table mapping ASCII characters (actually, 8-bit bytes) to "canonical" form * for base processing: * * a, A => A * c, C => C * g, G => G * t, T => T * everything else => N */ static const char canonical_ascii_tab[256] = { 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', /* A */ 'A', 'N', /* C */ 'C', 'N', 'N', 'N', /* G */ 'G', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', /* T */ 'T', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', /* a */ 'A', 'N', /* c */ 'C', 'N', 'N', 'N', /* g */ 'G', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', /* t */ 'T', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', }; /* Turns lowercase a, c, g, t into uppercase; * uppercase A, C, G, T stay the same; * everything else turns into 'N'. */ static inline char canonical_ascii_char(char c) { return canonical_ascii_tab[(unsigned char)c]; } /* A table mapping an ASCII base character in canonical form to its complement. * Unknown bases (N's) stay unknown. */ static const char complement_tab[] = { ['A'] = 'T', ['C'] = 'G', ['G'] = 'C', ['T'] = 'A', ['N'] = 'N', }; /* Complements a canonical ASCII base (A, C, G, T, N). */ static inline char complement(char c) { return complement_tab[(unsigned char)c]; } static inline char identity_mapping(char c) { return c; } /* Reverse a sequence of @len chars, applying the mapping function @map_char to * each, including the middle char if @len is odd. */ static inline void reverse_with_mapping(char *p, size_t len, char (*map_char)(char)) { char tmp; char *pp = p + len; while (pp > p) { --pp; tmp = *p; *p = (*map_char)(*pp); *pp = (*map_char)(tmp); ++p; } } /* Reverse-complement a read in place. */ void reverse_complement(struct read *r) { reverse_with_mapping(r->seq, r->seq_len, complement); reverse_with_mapping(r->qual, r->seq_len, identity_mapping); } /* Remove all whitespace from the end of the line/string. Return the length of * the trimmed string. */ static inline int trim(char *s, int len) { while (len > 0 && isspace((unsigned char)s[len - 1])) s[--len] = '\0'; return len; } void clean_read(struct read *r, int phred_offset, struct input_stream *in, uint64_t line_no) { int seq_len; char *seq; char *qual; r->seq_len = trim(r->seq, r->seq_len); r->tag_len = trim(r->tag, r->tag_len); r->qual_len = trim(r->qual, r->qual_len); seq_len = r->seq_len; if (r->qual_len != seq_len) { fatal_error("Qual string length (%d) not the same as sequence " "length (%d) (file \"%s\", near line %"PRIu64")", r->qual_len, seq_len, input_stream_get_name(in), line_no); } seq = r->seq; for (int i = 0; i < seq_len; i++) { if (isspace((unsigned char)seq[i])) { fatal_error("Invalid sequence string: " "contains whitespace " "(file \"%s\", near line %"PRIu64")", input_stream_get_name(in), line_no); } seq[i] = canonical_ascii_char(seq[i]); } qual = r->qual; if (phred_offset > 0) { for (int i = 0; i < seq_len; i++) { if (qual[i] < phred_offset) { fatal_error("Qual string contains character " "under phred_offset = %d " "(file \"%s\", near line %"PRIu64")", phred_offset, input_stream_get_name(in), line_no); } qual[i] -= phred_offset; } } } void clean_read_for_write(struct read *r, int phred_offset) { assert(r->seq_len == r->qual_len); if (phred_offset > 0) { char *qual = r->qual; int qual_len = r->qual_len; for (int i = 0; i < qual_len; i++) qual[i] += phred_offset; } } void copy_tag(struct read *to, const struct read *from) { if (to->tag_bufsz < from->tag_len + 1) { to->tag = xrealloc(to->tag, from->tag_len + 1); to->tag_bufsz = from->tag_len + 1; } to->tag_len = from->tag_len; memcpy(to->tag, from->tag, from->tag_len + 1); } /* * Given the FASTQ tags of two paired-end reads, find the FASTQ tag to give to * the combined read. * * This is done by stripping off the characters trailing the '/' (e.g. "/1" and * "/2"), unless there is a "barcode" beginning with the '#' character, which is * kept. */ void get_combined_tag(const struct read *read_1, const struct read *read_2, struct read *combined_read) { char *p; copy_tag(combined_read, read_1); for (p = &combined_read->tag[combined_read->tag_len - 1]; p >= combined_read->tag; p--) { if (*p == '/') { /* Tags are different, and there's a forward slash in * the first tag. Remove everything after the forward * slash, unless there's a barcode, which we keep. */ if (*(p + 1) != '\0' && *(p + 2) == '#') { /* read ID has a barcode. */ do { *p = *(p + 2); } while (*(++p + 2) != '\0'); } *p = '\0'; combined_read->tag_len = p - combined_read->tag; break; } } } FLASH-1.2.11/util.c000066400000000000000000000150041237001226200135450ustar00rootroot00000000000000/* * util.c: miscellaneous useful functions for FLASH */ /* * Copyright (C) 2012 Tanja Magoc * Copyright (C) 2012, 2013, 2014 Eric Biggers * * This file is part of FLASH, a fast tool to merge overlapping paired-end * reads. * * FLASH is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * FLASH is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with FLASH; if not, see http://www.gnu.org/licenses/. */ #include #include #include #include #include #include #include #include #include #include #include #include "util.h" #ifdef __WIN32__ /* Get the pthread mutex declarations as a replacement for flockfile() and * funlockfile(). */ # include /* Get the GetSystemInfo() declaration as replacement for * sysconf(_SC_NPROCESSORS_ONLN). */ # include #endif #ifdef __WIN32__ static pthread_mutex_t infofile_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t stderr_lock = PTHREAD_MUTEX_INITIALIZER; #endif /* File to which to write informational messages. */ FILE *infofile; static void lock_infofile(void) { #ifdef __WIN32__ pthread_mutex_lock(&infofile_lock); #else flockfile(infofile); #endif } static void lock_stderr(void) { #ifdef __WIN32__ pthread_mutex_lock(&stderr_lock); #else flockfile(stderr); #endif } static void unlock_infofile(void) { #ifdef __WIN32__ pthread_mutex_unlock(&infofile_lock); #else funlockfile(infofile); #endif } static void unlock_stderr(void) { #ifdef __WIN32__ pthread_mutex_unlock(&stderr_lock); #else funlockfile(stderr); #endif } #define PROGRAM_TAG "[FLASH] " static void __noreturn fatal(void) { info("FLASH did not complete successfully; exiting with failure status (1)"); exit(1); } /* Prints an error message and exits the program with failure status. */ void fatal_error(const char *msg, ...) { va_list va; lock_stderr(); va_start(va, msg); fflush(stdout); fputs(PROGRAM_TAG "ERROR: ", stderr); vfprintf(stderr, msg, va); putc('\n', stderr); va_end(va); unlock_stderr(); fatal(); } /* Prints an error message, with added text for errno if it is nonzero, and * exits the program with failure status. */ void fatal_error_with_errno(const char *msg, ...) { va_list va; lock_stderr(); va_start(va, msg); fflush(stdout); fputs(PROGRAM_TAG "ERROR: ", stderr); vfprintf(stderr, msg, va); if (errno) fprintf(stderr, ": %s\n", strerror(errno)); else putc('\n', stderr); va_end(va); unlock_stderr(); fatal(); } unsigned long warning_count = 0; /* Prints a warning message. */ void warning(const char *msg, ...) { va_list va; lock_stderr(); warning_count++; va_start(va, msg); fputs(PROGRAM_TAG "WARNING: ", stderr); vfprintf(stderr, msg, va); putc('\n', stderr); va_end(va); unlock_stderr(); } /* Prints an informational message. */ void info(const char *msg, ...) { va_list va; lock_infofile(); va_start(va, msg); fputs(PROGRAM_TAG, infofile); vfprintf(infofile, msg, va); putc('\n', infofile); fflush(infofile); va_end(va); unlock_infofile(); } /* Like malloc(), but aborts if out of memory, and always returns non-NULL, even * if 0 bytes were requested. */ void * xmalloc(size_t size) { void *p = malloc(size); if (p) return p; if (!size) { p = malloc(1); if (p) return p; } fatal_error("Out of memory: tried to allocate %zu bytes", size); } void * xzalloc(size_t size) { return memset(xmalloc(size), 0, size); } /* Like strdup(), but aborts if out of memory. */ char * xstrdup(const char *str) { return strcpy(xmalloc(strlen(str) + 1), str); } /* Like realloc(), but aborts if out of memory, and always returns non-NULL, * even if 0 bytes were requested. */ void * xrealloc(void *ptr, size_t size) { void *p = realloc(ptr, size); if (p) return p; if (!size) { p = malloc(1); if (p) return p; } fatal_error("Out of memory: tried to reallocate %zu bytes", size); } #ifndef NDEBUG void xfree(void *p, size_t size) { if (p) { memset(p, 0xfd, size); free(p); } } #endif /* Returns the number of available processors if it can be determined. * Otherwise returns 1. */ unsigned get_default_num_threads(void) { #ifdef __WIN32__ SYSTEM_INFO si; GetSystemInfo(&si); if (si.dwNumberOfProcessors > 0 && si.dwNumberOfProcessors <= UINT_MAX) return si.dwNumberOfProcessors; #else long nproc = sysconf(_SC_NPROCESSORS_ONLN); if (nproc > 0 && nproc <= UINT_MAX) return nproc; #endif warning("Could not determine number of processors! Assuming 1"); return 1; } /* Returns true if the specified character is a path separator on the current * platform. */ static bool is_path_separator(char c) { #ifdef __WIN32__ return (c == '/') || (c == '\\'); #else return (c == '/'); #endif } /* mkdir() on Windows doesn't take a mode argument. */ #ifdef __WIN32__ # define mkdir(path, mode) mkdir(path) #endif /* Like `mkdir -p': create the specified directory, and all parent directories, * as needed, failing only if a needed directory cannot be created. */ void mkdir_p(const char *dir) { size_t len = strlen(dir); char dir_copy[len + 1]; char *p = dir_copy; /* Copy the directory name to the @dir_copy array, squashing together * consecutive path separators. */ for (size_t i = 0; i < len; i++) { if (!is_path_separator(dir[i]) || !is_path_separator(dir[i + 1])) *p++ = dir[i]; } *p = '\0'; p = dir_copy; do { if (p != dir_copy && (*p == '\0' || is_path_separator(*p))) { char orig_char = *p; *p = '\0'; if (mkdir(dir_copy, 0755) != 0 && errno != EEXIST) { fatal_error_with_errno("Failed to create " "directory \"%s\"", dir_copy); } *p = orig_char; } } while (*p++ != '\0'); } pthread_t create_thread(void *(*proc)(void *), void *params) { int result; pthread_t t; result = pthread_create(&t, NULL, proc, params); if (result) { errno = result; fatal_error_with_errno("Failed to create new thread"); } return t; } void join_thread(pthread_t t) { int result = pthread_join(t, NULL); if (result) { errno = result; fatal_error_with_errno("Failed to join thread"); } } FLASH-1.2.11/util.h000066400000000000000000000033371237001226200135600ustar00rootroot00000000000000#ifndef _FLASH_UTIL_H_ #define _FLASH_UTIL_H_ #include #include #include #define ARRAY_LEN(A) (sizeof(A) / sizeof((A)[0])) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) # define __cold __attribute__((cold)) # else # define __cold # endif # define __noreturn __attribute__((noreturn)) # define __format(type, format_str, args_start) \ __attribute__((format(type, format_str, args_start))) # define max(a,b) ({ __typeof__(a) _a = (a); __typeof__(b) _b = (b); _a > _b ? _a : _b; }) # define min(a,b) ({ __typeof__(a) _a = (a); __typeof__(b) _b = (b); _a < _b ? _a : _b; }) # define inline inline __attribute__((always_inline)) #else # define __noreturn # define __cold # define __format(type, format_str, args_start) # define max(a,b) (((a) > (b)) ? (a) : (b)) # define min(a,b) (((a) < (b)) ? (a) : (b)) #endif extern void fatal_error(const char *msg, ...) __noreturn __cold __format(printf, 1, 2); extern void fatal_error_with_errno(const char *msg, ...) __noreturn __cold __format(printf, 1, 2); extern unsigned long warning_count; extern void warning(const char *msg, ...) __cold __format(printf, 1, 2); extern FILE *infofile; extern void info(const char *msg, ...) __format(printf, 1, 2); extern void * xmalloc(size_t size); #ifdef NDEBUG # define xfree(p, size) free(p) #else extern void xfree(void *p, size_t size); #endif extern void * xzalloc(size_t size); extern char * xstrdup(const char *str); extern void * xrealloc(void *ptr, size_t size); extern unsigned get_default_num_threads(void); extern void mkdir_p(const char *dir); extern pthread_t create_thread(void *(*proc)(void *), void *params); extern void join_thread(pthread_t t); #endif /* _FLASH_UTIL_H_ */