diff --git a/License b/License
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/License
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/NEWS b/NEWS
new file mode 100644
index 0000000..e4a90eb
--- /dev/null
+++ b/NEWS
@@ -0,0 +1,2 @@
+Date: 21 May 2017
+- First submission
\ No newline at end of file
diff --git a/R/FuSeq.R b/R/FuSeq.R
new file mode 100644
index 0000000..d039c9c
--- /dev/null
+++ b/R/FuSeq.R
@@ -0,0 +1,188 @@
+##############
+##### analyze input: Rscript test.R in=inputFeqDir txfasta=txFastaFile sqlite=gtfSqlite txanno=txAnnofile out=outputDir params=paramsFn
+inputFeqDir=txFastaFile=gtfSqlite=txAnnofile=outputDir=paramsFn=NA
+#get command information
+args = commandArgs(trailingOnly=TRUE)
+cat("\nNumber of arguments: ",length(args))
+cat("\nList of arguments: ",args)
+for (i in 1:length(args)){
+ res=unlist(strsplit(args[i],"="))
+ if (res[1]=="in") inputFeqDir=res[2]
+ if (res[1]=="txfasta") txFastaFile=res[2]
+ if (res[1]=="sqlite") gtfSqlite=res[2]
+ if (res[1]=="txanno") txAnnofile=res[2]
+ if (res[1]=="params") paramsFn=res[2]
+ if (res[1]=="out") outputDir=res[2]
+}
+
+
+
+#check input information
+validatedCommand=TRUE
+if (is.na(inputFeqDir)){
+ cat("\nThere is no input folder. Stop!")
+ validatedCommand=FALSE
+}
+if (is.na(txFastaFile)){
+ cat("\nThere is no transcript fasta file. Stop!")
+ validatedCommand=FALSE
+}
+if (is.na(gtfSqlite)){
+ cat("\nThere is no sqlite file. Stop!")
+ validatedCommand=FALSE
+}
+if (is.na(txAnnofile)){
+ cat("\nThere is no txAnno file. Stop!")
+ validatedCommand=FALSE
+}
+
+if (is.na(outputDir)){
+ cat("\n-----")
+ cat("\nThere is no output directory from user, the output will be saved into the input directory of fusion equivalence classes.")
+ outputDir=inputFeqDir
+}else{
+ if (dir.exists(outputDir)){
+ cat("\nCan not create the output directory. Stop!")
+ validatedCommand=FALSE
+ }else dir.create(outputDir)
+}
+
+if (is.na(paramsFn)){
+ cat("\n-----")
+ cat("\nThere is no params file. Default settings will be used.")
+ FuSeq.params=list()
+ FuSeq.params$readStrands="UN"
+ FuSeq.params$chromRef=as.character(c(1:22,"X","Y"))
+ FuSeq.params$onlyProteinCodingGenes=TRUE
+ FuSeq.params$maxSharedCount=5e-2
+ FuSeq.params$minGeneDist=1e5
+ FuSeq.params$minJunctionDist=1e5
+ FuSeq.params$maxInvertedFusionCount=0.01
+ FuSeq.params$maxMRfusionFc=2
+ FuSeq.params$maxMRfusionNum=2
+ FuSeq.params$sgtMRcount=10
+ FuSeq.params$minMR=2
+ FuSeq.params$minNonDupMR=2
+ FuSeq.params$minSR=1
+ FuSeq.params$minScore=3
+ FuSeq.params$keepRData=FALSE
+ FuSeq.params$exportFasta=FALSE
+}else{
+ paramIn=read.table(paramsFn, sep="=", header=FALSE)
+ FuSeq.params=list()
+ FuSeq.params$readStrands=as.character(paramIn[which(paramIn[,1]=="readStrands"),2])
+ FuSeq.params$chromRef=trimws(unlist(strsplit(as.character(paramIn[which(paramIn[,1]=="chromRef"),2]),",")))
+ FuSeq.params$onlyProteinCodingGenes=as.logical(as.character(paramIn[which(paramIn[,1]=="onlyProteinCodingGenes"),2]))
+ FuSeq.params$maxSharedCount=as.double(as.character(paramIn[which(paramIn[,1]=="maxSharedCount"),2]))
+ FuSeq.params$minGeneDist=as.double(as.character(paramIn[which(paramIn[,1]=="minGeneDist"),2]))
+ FuSeq.params$minJunctionDist=as.double(as.character(paramIn[which(paramIn[,1]=="minJunctionDist"),2]))
+ FuSeq.params$maxInvertedFusionCount=as.double(as.character(paramIn[which(paramIn[,1]=="maxInvertedFusionCount"),2]))
+ FuSeq.params$maxMRfusionFc=as.double(as.character(paramIn[which(paramIn[,1]=="maxMRfusionFc"),2]))
+ FuSeq.params$maxMRfusionNum=as.double(as.character(paramIn[which(paramIn[,1]=="maxMRfusionNum"),2]))
+ FuSeq.params$sgtMRcount=as.double(as.character(paramIn[which(paramIn[,1]=="sgtMRcount"),2]))
+ FuSeq.params$minMR=as.double(as.character(paramIn[which(paramIn[,1]=="minMR"),2]))
+ FuSeq.params$minNonDupMR=as.double(as.character(paramIn[which(paramIn[,1]=="minNonDupMR"),2]))
+ FuSeq.params$minSR=as.double(as.character(paramIn[which(paramIn[,1]=="minSR"),2]))
+ FuSeq.params$minScore=as.double(as.character(paramIn[which(paramIn[,1]=="minScore"),2]))
+ FuSeq.params$keepRData=as.logical(as.character(paramIn[which(paramIn[,1]=="keepRData"),2]))
+ FuSeq.params$exportFasta=as.logical(as.character(paramIn[which(paramIn[,1]=="exportFasta"),2]))
+}
+
+
+
+if (validatedCommand){
+ cat("\n-----")
+ cat("\nParameter settings:")
+ cat("\n readStrands=",FuSeq.params$readStrands)
+ cat("\n chromRef="); cat(FuSeq.params$chromRef,sep = ",")
+ cat("\n maxSharedCount=",FuSeq.params$maxSharedCount)
+ cat("\n onlyProteinCodingGenes=",FuSeq.params$onlyProteinCodingGenes)
+ cat("\n minGeneDist=",FuSeq.params$minGeneDist)
+ cat("\n minJunctionDist=",FuSeq.params$minJunctionDist)
+ cat("\n maxInvertedFusionCount=",FuSeq.params$maxInvertedFusionCount)
+ cat("\n maxMRfusionFc=",FuSeq.params$maxMRfusionFc)
+ cat("\n maxMRfusionNum=",FuSeq.params$maxMRfusionNum)
+ cat("\n sgtMRcount=",FuSeq.params$sgtMRcount)
+ cat("\n minMR=",FuSeq.params$minMR)
+ cat("\n minNonDupMR=",FuSeq.params$minNonDupMR)
+ cat("\n minSR=",FuSeq.params$minSR)
+ cat("\n minScore=",FuSeq.params$minScore)
+ cat("\n keepRData=",FuSeq.params$keepRData)
+ cat("\n exportFasta=",FuSeq.params$exportFasta)
+}
+cat("\n-------------------------\n")
+
+if (validatedCommand){
+ #load gtf annotation information
+ suppressMessages(library("GenomicFeatures"))
+ anntxdb <- loadDb(gtfSqlite)
+ load(txAnnofile)
+ #load R functions
+ source("/path/to/FuSeq_functions.R")
+ source("/path/to/processFEQ.R")
+ source("/path/to/detectJunctionBreaks.R")
+ source("/path/to/doBiologicalFilter.R")
+ source("/path/to/processMappedRead.R")
+ source("/path/to/processSplitRead.R")
+ source("/path/to/postProcessMappedRead.R")
+ source("/path/to/postProcessSplitRead.R")
+ source("/path/to/integrateFusion.R")
+
+ inPath=inputFeqDir
+ myFusionOut=NULL;
+
+ FuSeq.MR=processMappedRead(inPath,geneAnno=geneAnno, anntxdb=anntxdb, geeqMap=geeqMap,FuSeq.params=FuSeq.params)
+ FuSeq.SR=processSplitRead(inPath,geneAnno=geneAnno, anntxdb=anntxdb, geeqMap=geeqMap,FuSeq.params=FuSeq.params, txFastaFile=txFastaFile)
+
+ FuSeq.MR.postPro=postProcessMappedRead(inPath, anntxdb, FuSeq.SR, FuSeq.MR, FuSeq.params)
+ FuSeq.SR.postPro=postProcessSplitRead(inPath, anntxdb, FuSeq.SR, FuSeq.MR, txFastaFile, FuSeq.params)
+
+ myFusionFinal.MR=FuSeq.MR.postPro$myFusionFinal
+ myFusionFinal.SR=FuSeq.SR.postPro$myFusionFinal
+
+ fragmentInfo=FuSeq.MR$fragmentInfo
+ FuSeq.integration=integrateFusion(myFusionFinal.MR, myFusionFinal.SR, FuSeq.params, fragmentInfo=fragmentInfo, paralog.fc.thres=2.0)
+ myFusionFinal=FuSeq.integration$myFusionFinal
+
+ if (nrow(myFusionFinal)==0){
+ myFusionExport= "# No fusion genes existing"
+ write.table(myFusionExport, file=outputDir, col.names=FALSE, row.names = FALSE,quote = FALSE, sep="\t")
+ } else{
+ myFusionOut=myFusionFinal
+ myFusionOut=myFusionOut[order(myFusionOut$score, decreasing = TRUE),]
+
+ myFusionExport=myFusionOut[,c("gene5","chrom5p","strand5p","brpos5.start","brpos5.end","gene3","chrom3p","strand3p","brpos3.start","brpos3.end","fusionName","supportRead","score")]
+
+ colnames(myFusionExport)=c("gene5","chrom5","strand5","brpos5.start","brpos5.end","gene3","chrom3","strand3","brpos3.start","brpos3.end","fusionName","supportRead","score")
+
+ #Detect extra information here
+ myFusionExport$info=rep("",nrow(myFusionExport))
+ myID=unique(c(which(!is.na(myFusionOut$mitoTrans5)),which(!is.na(myFusionOut$mitoTrans3))))
+ myFusionExport$info[myID]=paste(myFusionExport$info[myID],"mitochondrial translation, ",sep="")
+ myID=unique(c(which(!is.na(myFusionOut$ribSub5)),which(!is.na(myFusionOut$ribSub3))))
+ myFusionExport$info[myID]=paste(myFusionExport$info[myID],"cytosolic ribosomal subunit, ",sep="")
+ myID=unique(c(which(!is.na(myFusionOut$ribonupro5)),which(!is.na(myFusionOut$ribonupro3))))
+ myFusionExport$info[myID]=paste(myFusionExport$info[myID],"ribonucleoprotein, ",sep="")
+
+ write.table(myFusionExport, file=paste(outputDir,"/fusions.FuSeq",sep=""), col.names=TRUE, row.names = FALSE,quote = FALSE, sep="\t")
+ #####
+ #keep all RData
+ if (FuSeq.params$keepRData){
+ cat("\n Saving all data of FuSeq process...")
+ save(inPath,outputDir, myFusionFinal,myFusionExport,FuSeq.params, FuSeq.MR, FuSeq.SR, FuSeq.MR.postPro, FuSeq.SR.postPro,FuSeq.integration, file=paste(outputDir,"/FuSeq_process.RData",sep=""))
+ }
+
+ ##### Export fasta sequence
+ if (FuSeq.params$exportFasta){
+ cat("\n Export supporing read sequences to files...")
+ fastaOut=paste(outputDir,"/FuSeq_",sep="")
+ exportMappedFusionReads(inPath, readStrands=FuSeq.params$readStrands, fastaOut=fastaOut, junctInfo=FuSeq.MR$junctBr$junctInfo, fusionName=as.character(myFusionFinal$fusionName),fsizeLadder=FuSeq.MR$junctBr$fsizeLadder)
+ exportSplitFusionReads(inPath, readStrands=FuSeq.params$readStrands, fastaOut=fastaOut, splitReads=FuSeq.SR$splitReads, fusionName=as.character(myFusionFinal$fusionName))
+ }
+
+ }
+
+cat("\n Done! \n")
+}
+
+
diff --git a/R/FuSeq_functions.R b/R/FuSeq_functions.R
new file mode 100644
index 0000000..30b598d
--- /dev/null
+++ b/R/FuSeq_functions.R
@@ -0,0 +1,1123 @@
+#Date:19/05/2017
+#- Fix and clean codes
+###################
+##### Several functions for fusion gene detection
+
+chromFilter <- function(myfusionTx,chromRef=NULL){
+ ##### Filtering by chromosomes
+ if (is.null(chromRef)) chromRef=as.character(c(1:22,"X","Y"))
+ keepID=which(!is.na(match(as.character(myfusionTx$chrom1),chromRef)))
+ myfusionTx=myfusionTx[keepID,]
+ keepID=which(!is.na(match(as.character(myfusionTx$chrom2),chromRef)))
+ myfusionTx=myfusionTx[keepID,]
+ return(myfusionTx)
+}
+
+
+
+convertChrPos <- function(txname,txpos,exonInfo=NULL,readLen=100,txExonMat=NULL){
+ ##### Converting trancript positions to chromosome positions. Be aware of the direction of strands and read mapping
+ if (is.null(txExonMat)) txExonMat=exonInfo[which(exonInfo$TXNAME==txname),]
+
+ if (txExonMat$TXSTRAND[1]=="+") {
+ txExonMat=txExonMat[order(txExonMat$EXONSTART),]#sort exons by increasing order for forward strand
+ txlen=sum(txExonMat$EXONEND-txExonMat$EXONSTART+1);
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ chrPos=NULL
+ for (i in 1:length(txpos)){
+ exID=which(exonlenCumSum>txpos[i])[1]
+ if (!is.na(exID)) posOffset=exonlen[exID]-(exonlenCumSum[exID]-txpos[i])
+ else{
+ #if position outside the range, use the last exon
+ exID=length(exonlen)
+ posOffset=exonlen[exID]+(txpos[i]-exonlenCumSum[exID])
+ }
+ chrPos=c(chrPos,txExonMat$EXONSTART[exID]+posOffset)
+ }
+ return(chrPos)
+ }else{
+ txExonMat=txExonMat[order(txExonMat$EXONEND, decreasing=TRUE),]#sort exons by decreasing order for reverse strand
+ txlen=sum(txExonMat$EXONEND-txExonMat$EXONSTART+1);
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ chrPos=NULL
+ for (i in 1:length(txpos)){
+ exID=which(exonlenCumSum>txpos[i])[1]
+ if (!is.na(exID)) posOffset=exonlenCumSum[exID]-txpos[i]-1
+ else{
+ exID=length(exonlen)
+ posOffset=exonlenCumSum[exID]-txpos[i]
+ }
+ chrPos=c(chrPos,txExonMat$EXONSTART[exID]+posOffset)
+ }
+ return(chrPos)
+ }
+}
+
+
+convertGenePos <- function(txname,txpos,genename,exonInfo,readLen=100){
+ ##### Converting trancript positions to gene positions. Be aware of the direction of strands and read mapping
+ mygeneEx=exonInfo[exonInfo$GENEID==genename,]
+
+ if (mygeneEx$TXSTRAND[1]=="+") {
+ mygeneEx=mygeneEx[order(mygeneEx$EXONID),] #sort exons by increasing order for forward strand
+ brStart=unique(mygeneEx$EXONSTART)
+ brEnd=unique(mygeneEx$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-mygeneEx$EXONSTART)/1e8*(x-mygeneEx$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-mygeneEx$EXONSTART)/1e8*(x-mygeneEx$EXONEND)<0))
+ brStart=brStart[exStartStatus==0] #none-overlap start
+ brEnd=brEnd[exEndStatus==0]#none-overlap end
+ brCumsum=cumsum(brEnd-brStart+1)
+ mytx=mygeneEx[mygeneEx$TXNAME==txname,]
+ mytxChrPos=min(mytx$EXONSTART)
+ brID=which((mytxChrPos-brStart)/1e8*(mytxChrPos-brEnd)<=0) #which segment the transcript belongs to
+ mytxGenePos=ifelse(brID==1,0,brCumsum[brID-1])+mytxChrPos-brStart[brID] #position of the tx at the gene
+ genePos=min(mytxGenePos)+txpos
+ return(genePos)
+ }else{
+ mygeneEx=mygeneEx[order(mygeneEx$EXONID, decreasing=TRUE),] #sort exons by decreasing order for reverse strand
+ brStart=unique(mygeneEx$EXONSTART)
+ brEnd=unique(mygeneEx$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-mygeneEx$EXONSTART)/1e8*(x-mygeneEx$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-mygeneEx$EXONSTART)/1e8*(x-mygeneEx$EXONEND)<0))
+ brStart=brStart[exStartStatus==0] #none-overlap start
+ brEnd=brEnd[exEndStatus==0] #none-overlap end
+ brCumsum=cumsum(brEnd-brStart+1)
+ mytx=mygeneEx[mygeneEx$TXNAME==txname,]
+ mytxlen=sum(mytx$EXONEND-mytx$EXONSTART+1)
+ mytxChrPos=min(mytx$EXONSTART)
+ brID=which((mytxChrPos-brStart)/1e8*(mytxChrPos-brEnd)<=0)#which segment the transcript belongs to
+ mytxGenePos=max(brCumsum)-(brCumsum[brID]-(mytxChrPos-brStart[brID])) #position of the tx at the gene
+ genePos=min(mytxGenePos) + mytxlen - txpos #This should be the leftmost position of the gene
+ return(genePos)
+ }
+}
+
+
+convertChrPosGenePos<- function (chrPos,genename=NULL,exonInfo=NULL,geneExonMat=NULL){
+ if (is.null(geneExonMat)) geneExonMat=exonInfo[exonInfo$GENEID==genename,]
+ if (geneExonMat$TXSTRAND[1]=="+") {
+ geneExonMat=geneExonMat[order(geneExonMat$EXONID),] #sort exons by increasing order for forward strand
+ brStart=unique(geneExonMat$EXONSTART)
+ brEnd=unique(geneExonMat$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ brStart=brStart[exStartStatus==0] #none-overlap start
+ brEnd=brEnd[exEndStatus==0]#none-overlap end
+ brCumsum=cumsum(brEnd-brStart+1)
+ genePos=NULL;
+ for (i in 1:length(chrPos)){
+ brID=which((chrPos[i]-brStart)/1e8*(chrPos[i]-brEnd)<=0) #which segment the chrPos belongs to
+ myGenePos=ifelse(brID==1,0,brCumsum[brID-1])+chrPos[i]-brStart[brID] #position of the chrPos at the gene
+ genePos=c(genePos,min(myGenePos))
+ }
+ return(genePos)
+ }else{
+ geneExonMat=geneExonMat[order(geneExonMat$EXONID, decreasing=TRUE),] #sort exons by decreasing order for reverse strand
+ brStart=unique(geneExonMat$EXONSTART)
+ brEnd=unique(geneExonMat$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ brStart=brStart[exStartStatus==0] #none-overlap start
+ brEnd=brEnd[exEndStatus==0] #none-overlap end
+ brCumsum=cumsum(brEnd-brStart+1)
+ genePos=NULL;
+ for (i in 1:length(chrPos)){
+ brID=which((chrPos[i]-brStart)/1e8*(chrPos[i]-brEnd)<=0)#which segment the chrPos belongs to
+ myGenePos=max(brCumsum)-(brCumsum[brID]-(chrPos[i]-brStart[brID])) #position of the chrPos at the gene
+ genePos=c(genePos,min(myGenePos)) #This should be the leftmost position of the gene
+ }
+ return(genePos)
+ }
+
+}
+
+
+detectExonID <- function(chrPos,txname,exonInfo){
+ myTxEx=exonInfo[exonInfo$TXNAME==txname,]
+ exID=lapply(chrPos,function(x){
+ myExid=which((myTxEx$EXONSTART-x)/1e8*(myTxEx$EXONEND-x)<=0)
+ return(myTxEx$EXONID[myExid])
+ })
+ exID=unique(unlist(exID))
+ return(exID)
+}
+
+detectExonID2 <- function(chrPos,seqLen,txname,exonInfo){
+ myTxEx=exonInfo[exonInfo$TXNAME==txname,]
+ if (myTxEx$TXSTRAND[1]=="+") chrPos2=chrPos+seqLen else chrPos2=chrPos-seqLen
+
+ exID=lapply(cbind(chrPos,chrPos2),function(x){
+ myExid1=which((myTxEx$EXONSTART-x[1])/1e8*(myTxEx$EXONEND-x[1])<=0)
+ myExid2=which((myTxEx$EXONSTART-x[2])/1e8*(myTxEx$EXONEND-x[2])<=0)
+ myExid=unique(c(myExid1,myExid2))
+ return(myTxEx$EXONID[myExid])
+ })
+ exID=unique(unlist(exID))
+ return(exID)
+}
+
+
+detectExonID3 <- function(txname,txpos,seqLen, exonInfo){
+ txExonMat=exonInfo[which(exonInfo$TXNAME==txname),]
+
+ if (txExonMat$TXSTRAND[1]=="+") {
+ txExonMat=txExonMat[order(txExonMat$EXONSTART),]#sort exons by increasing order for forward strand
+ txlen=sum(txExonMat$EXONEND-txExonMat$EXONSTART+1);
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ exList=NULL
+ for (i in 1:length(txpos)){
+ exID=which(exonlenCumSum>txpos[i])[1]
+ if (!is.na(exID)){
+ exID2=which(exonlenCumSum>txpos[i]+seqLen[i])[1]
+ if (is.na(exID2)) exID2=length(exonlen)
+ exList=c(exList,exID:exID2)
+
+ }
+ else{
+ #if position outside the range, use the last exon
+ exID=length(exonlen)
+ exList=c(exList,exID)
+ }
+ }
+ return(txExonMat$EXONID[unique(exList)])
+ }else{
+ txExonMat=txExonMat[order(txExonMat$EXONEND, decreasing=TRUE),]#sort exons by decreasing order for reverse strand
+ txlen=sum(txExonMat$EXONEND-txExonMat$EXONSTART+1);
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ exList=NULL
+ for (i in 1:length(txpos)){
+ #txpos[i]=txlen-txpos[i]-readLen #convert pos3 to pos5
+ exID=which(exonlenCumSum>txpos[i])[1]
+ if (!is.na(exID)){
+ exID2=which(exonlenCumSum>txpos[i]+seqLen[i])[1]
+ if (is.na(exID2)) exID2=length(exonlen)
+ exList=c(exList,exID:exID2)
+ }
+ else{
+ #if position outside the range, use the last exon
+ exID=length(exonlen)
+ exList=c(exList,exID)
+ }
+ }
+ return(txExonMat$EXONID[unique(exList)])
+ }
+}
+
+
+
+getGeneLen <-function(genename=NULL,exonInfo=NULL,geneExonMat=NULL){
+ if (is.null(geneExonMat)) geneExonMat=exonInfo[exonInfo$GENEID==genename,]
+ if (geneExonMat$TXSTRAND[1]=="+") {
+ geneExonMat=geneExonMat[order(geneExonMat$EXONID),] #sort exons by increasing order for forward strand
+ brStart=unique(geneExonMat$EXONSTART)
+ brEnd=unique(geneExonMat$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ brStart=brStart[exStartStatus==0] #none-overlap start
+ brEnd=brEnd[exEndStatus==0]#none-overlap end
+ brCumsum=cumsum(brEnd-brStart+1)
+ return(max(brCumsum))
+ }else{
+ geneExonMat=geneExonMat[order(geneExonMat$EXONID, decreasing=TRUE),] #sort exons by decreasing order for reverse strand
+ brStart=unique(geneExonMat$EXONSTART)
+ brEnd=unique(geneExonMat$EXONEND)
+ exStartStatus=sapply(brStart, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ exEndStatus=sapply(brEnd, function(x) sum((x-geneExonMat$EXONSTART)/1e8*(x-geneExonMat$EXONEND)<0))
+ brStart=brStart[exStartStatus==0]
+ brEnd=brEnd[exEndStatus==0]
+ brCumsum=cumsum(brEnd-brStart+1)
+ return(max(brCumsum))
+ }
+}
+
+
+
+# Filtering by dupGene
+filterBydupGene <- function(myfusionTx,dupGene.thres=4){
+ dupGene1=table(myfusionTx$gene1)
+ dupGene2=table(myfusionTx$gene2)
+ myfusionTx=cbind(myfusionTx,as.integer(dupGene1[match(as.character(myfusionTx$gene1),names(dupGene1))]))
+ myfusionTx=cbind(myfusionTx,as.integer(dupGene2[match(as.character(myfusionTx$gene2),names(dupGene2))]))
+ colnames(myfusionTx)[c(ncol(myfusionTx)-1,ncol(myfusionTx))]=c("dupGene1","dupGene2")
+ keepID=which(myfusionTx$dupGene1 <= dupGene.thres & myfusionTx$dupGene2<=dupGene.thres)
+ myfusionTx=myfusionTx[keepID,]
+ return(myfusionTx)
+}
+
+computeDupGene <- function(myfusionTx,dupGene.thres=4){
+ dupGene1=table(myfusionTx$gene1)
+ dupGene2=table(myfusionTx$gene2)
+ myfusionTx=cbind(myfusionTx,as.integer(dupGene1[match(as.character(myfusionTx$gene1),names(dupGene1))]))
+ myfusionTx=cbind(myfusionTx,as.integer(dupGene2[match(as.character(myfusionTx$gene2),names(dupGene2))]))
+ colnames(myfusionTx)[c(ncol(myfusionTx)-1,ncol(myfusionTx))]=c("dupGene1","dupGene2")
+
+ if (dupGene.thres<0) return(myfusionTx[,c(ncol(myfusionTx)-1,ncol(myfusionTx))])
+
+ keepID=which(myfusionTx$dupGene1 <= dupGene.thres & myfusionTx$dupGene2<=dupGene.thres)
+ myfusionTx=myfusionTx[keepID,]
+ return(myfusionTx)
+}
+
+
+computeReversedFusionCount <- function(myfusionTx){
+ #similar to filterByReverseStrand, however, we consider only gene-level with real count
+ matchID=match(myfusionTx$name12, myfusionTx$name21)
+ name21Count=myfusionTx$supportCount[matchID]
+ name21Count[is.na(name21Count)]=0
+ return(name21Count)
+}
+
+
+computeGeneDistance <- function(myfusionTx,anntxdb,minGeneDist=1e5){
+ res1=select(anntxdb, keys=as.character(myfusionTx$gene1), columns=c("TXSTART","TXEND"), keytype = "GENEID")
+ res2=select(anntxdb, keys=as.character(myfusionTx$gene2), columns=c("TXSTART","TXEND"), keytype = "GENEID")
+
+ minRes1=tapply(res1$TXSTART,as.character(res1$GENEID),min)
+ maxRes1=tapply(res1$TXEND,as.character(res1$GENEID),max)
+ minRes1=minRes1[match(as.character(myfusionTx$gene1),names(minRes1))]
+ maxRes1=maxRes1[match(as.character(myfusionTx$gene1),names(maxRes1))]
+
+ minRes2=tapply(res2$TXSTART,as.character(res2$GENEID),min)
+ maxRes2=tapply(res2$TXEND,as.character(res2$GENEID),max)
+ minRes2=minRes2[match(as.character(myfusionTx$gene2),names(minRes2))]
+ maxRes2=maxRes2[match(as.character(myfusionTx$gene2),names(maxRes2))]
+
+ geneDist=unlist(apply(cbind(abs(minRes1-maxRes2),abs(minRes1-minRes2),abs(maxRes1-maxRes2),abs(maxRes1-minRes2)),1,min))
+ if (minGeneDist < 0) return(geneDist);
+
+ myfusionTx$geneDist=geneDist
+ myfusionTx=myfusionTx[myfusionTx$geneDist>=minGeneDist,]
+ return(myfusionTx)
+}
+
+
+
+estimateCountEM <- function(alp0,alpOut,feq,fgeFeqMap,itNum=2,alpDiff.thres=0.01){
+ ##### Estimating count from fusion-equivalence classes using EM
+ isConvergered=FALSE
+ alpIn=alp0
+ for (k in 1:itNum){
+ for (i in 1:length(feq)){
+ feqID=i;
+ feqCount=feq[feqID]
+ geneID=unlist(fgeFeqMap[feqID])
+ if (length(geneID) > 1){
+ weights=rep(1/length(geneID),length(geneID))
+ v=alpIn[geneID] * weights;
+ denom=sum(v)
+ invt_denom = feqCount / denom;
+ alpOut[geneID]=alpOut[geneID]+v*invt_denom
+ }else{
+ alpOut[geneID]=alpOut[geneID]+feqCount
+ }
+ }
+ alpDiff = abs(alpIn - alpOut) / alpOut;
+ if (sum(alpDiff > alpDiff.thres) == 0){
+ isConvergered=TRUE
+ k=itNum+1
+ }
+ alpIn=alpOut
+ alpOut=rep(0,length(alpOut))
+ }
+ res=list(correctedCount=alpIn,isConvergered=isConvergered)
+ return(res)
+}
+
+
+convertReverseComplement<-function(DNAseq){
+ DNAarr=unlist(strsplit(DNAseq,""))
+ #reverse
+ DNAarr=rev(DNAarr)
+ #complement
+ Aid=which(DNAarr=="A")
+ Tid=which(DNAarr=="T")
+ Gid=which(DNAarr=="G")
+ Cid=which(DNAarr=="C")
+ DNAarr[Aid]="T"
+ DNAarr[Tid]="A"
+ DNAarr[Gid]="C"
+ DNAarr[Cid]="G"
+ #result
+ DNAseqRc=paste(DNAarr,collapse = "")
+ return(DNAseqRc)
+}
+
+
+
+matchFusionReads <- function(inPath, readStrands, fastaOut, junctInfo, splitReads, fusionCandidate,fsizeLadder){
+ ##### do "pseudo de novo" alignment based on the mapped positions of reads and match reads between 5 prime and 3 prime sites
+ fusionName=fusionCandidate$fusionName
+ fastaDat2=fastaDat1=list();
+ fastaSplit2=fastaSplit1=list();
+ frfiles=list.files(inPath,paste(readStrands,"_fusionMappedReadsChunk_*",sep=""))
+ for (i in 1:length(frfiles)){
+ #read fasta files of mapped reads
+ ftag=rev(strsplit(strsplit(frfiles[i],"\\.")[[1]][1],"_")[[1]])[1]
+ con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat1[[frfiles[i]]]=mydata
+
+ con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat2[[frfiles[i]]]=mydata
+
+ #read fasta files of split reads
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaSplit1[[frfiles[i]]]=mydata
+
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaSplit2[[frfiles[i]]]=mydata
+
+ }
+
+ fastaSplit1=unlist(fastaSplit1)
+ fastaSplit2=unlist(fastaSplit2)
+
+
+ ###### de novo assembly by alignment
+ matchInfo=list();
+ consensusEntropy=consensusErr=consensusProp=NULL
+ for (i in 1:nrow(fusionCandidate)){
+ fName=fusionCandidate$fusionName[i]
+ res=junctInfo[[fName]]
+ myreadID=res$readID
+ rID=unlist(myreadID)
+ fID=unlist(lapply(rID, function(x) which(fsizeLadder>=x)[1]))
+ rID.adj=unlist(lapply(seq_along(rID), function(x) if (fID[x] > 1) return(rID[x]-fsizeLadder[fID[x]-1]) else return(rID[x])))
+
+ if (readStrands=="FR" ||readStrands=="FF"){ #read1 for 5' and read 2 for 3'
+ if (fusionCandidate$strand1[i]=="+"){
+ offset1=-unlist(res$readL.seqLen)+1-unlist(res$readL.Pos)+unlist(res$readL.ReadPos)
+ mypos1=unlist(res$adj.readL.GenePos)+offset1
+ }else{
+ offset1=unlist(res$readL.seqLen)-1+unlist(res$readL.Pos)-unlist(res$readL.ReadPos)
+ mypos1=unlist(res$adj.readL.GenePos)+offset1
+ }
+ if (fusionCandidate$strand2[i]=="+"){
+ offset2=-unlist(res$readR.Pos)+unlist(res$readR.ReadPos)
+ mypos2=unlist(res$adj.readR.GenePos)+offset2
+ } else{
+ offset2=unlist(res$readR.Pos)-unlist(res$readR.ReadPos)
+ mypos2=unlist(res$adj.readR.GenePos)+offset2
+ }
+ if (fusionCandidate$strand1[i]=="-"){
+ mypos1=-mypos1
+ offset1=-offset1
+ }
+ if (fusionCandidate$strand2[i]=="-"){
+ mypos2=-mypos2
+ offset2=-offset2
+ }
+
+ mypos1=mypos1-min(mypos1)
+ mypos2=mypos2-min(mypos2)
+
+ mySeq1=mySeq2=NULL
+ mySeq1N=mySeq2N=NULL
+ for (j in 1:length(rID.adj)){
+ mySeq1=c(mySeq1,fastaDat1[[fID[j]]][rID.adj[j]*2])
+ mySeq2=c(mySeq2,fastaDat2[[fID[j]]][rID.adj[j]*2])
+
+ mySeq1N=c(mySeq1N,paste(paste(rep("N",mypos1[j]),collapse = ""),mySeq1[j],sep=""))
+
+ mySeqRc=convertReverseComplement(mySeq2[j]) #make sure read2 is reverse complement
+ mySeq2N=c(mySeq2N,paste(paste(rep("N",mypos2[j]),collapse = ""),mySeqRc,sep=""))
+ }
+ #Sometimes, the alignment is not optimal, we might need a re-alignment step here
+ estBr5=max(mypos1-offset1)
+ estBr3=min(mypos2-offset2)
+ mySeq5N=mySeq1N
+ mySeq3N=mySeq2N
+ #####get split reads
+ myreadID=which(splitReads$name12==fName)
+ myheader=as.character(splitReads$header[myreadID])
+ rID.adj=match(myheader,fastaSplit1)
+ mySplit5N=fastaSplit1[rID.adj+1]
+ mySplit3N=fastaSplit2[rID.adj+1]
+
+ } else{ #if readStrands=RF, UN or RR, so read1 for 3' and read 2 for 5'
+
+ if (fusionCandidate$strand1[i]=="+"){
+ #offset1=-unlist(res$readL.seqLen)+1-unlist(res$readL.Pos)+unlist(res$readL.ReadPos)
+ offset1=-unlist(res$readL.Pos)+unlist(res$readL.ReadPos)
+ mypos1=unlist(res$adj.readL.GenePos)+offset1
+ }else{
+ #offset1=unlist(res$readL.seqLen)-1+unlist(res$readL.Pos)-unlist(res$readL.ReadPos)
+ offset1=unlist(res$readL.Pos)-unlist(res$readL.ReadPos)
+ mypos1=unlist(res$adj.readL.GenePos)+offset1
+ }
+
+ if (fusionCandidate$strand2[i]=="+"){
+ offset2=-unlist(res$readR.seqLen)+1-unlist(res$readR.Pos)+unlist(res$readR.ReadPos)
+ mypos2=unlist(res$adj.readR.GenePos)+offset2
+ }else{
+ offset2=unlist(res$readR.seqLen)-1+unlist(res$readR.Pos)-unlist(res$readR.ReadPos)
+ mypos2=unlist(res$adj.readR.GenePos)+offset2
+ }
+
+ if (fusionCandidate$strand1[i]=="-"){
+ mypos1=-mypos1
+ offset1=-offset1
+ }
+ if (fusionCandidate$strand2[i]=="-"){
+ mypos2=-mypos2
+ offset2=-offset2
+ }
+
+ mypos1=mypos1-min(mypos1)
+ mypos2=mypos2-min(mypos2)
+
+ mySeq1=mySeq2=NULL
+ mySeq1N=mySeq2N=NULL
+ for (j in 1:length(rID.adj)){
+ mySeq1=c(mySeq1,fastaDat1[[fID[j]]][rID.adj[j]*2])
+ mySeq2=c(mySeq2,fastaDat2[[fID[j]]][rID.adj[j]*2])
+ mySeqRc=convertReverseComplement(mySeq1[j]) #make sure read1 is reverse complement
+ mySeq1N=c(mySeq1N,paste(paste(rep("N",mypos1[j]),collapse = ""),mySeqRc,sep=""))
+
+ mySeq2N=c(mySeq2N,paste(paste(rep("N",mypos2[j]),collapse = ""),mySeq2[j],sep=""))
+
+ }
+ #Sometimes, the alignment is not optimal, we might need a re-alignment step here
+ estBr5=max(mypos2-offset2)
+ estBr3=min(mypos1-offset1)
+ mySeq5N=mySeq2N
+ mySeq3N=mySeq1N
+
+ #####get split reads
+ myreadID=which(splitReads$name12==fName)
+ myheader=as.character(splitReads$header[myreadID])
+ rID.adj=match(myheader,fastaSplit1)
+ mySplit5N=fastaSplit2[rID.adj+1]
+ mySplit3N=fastaSplit1[rID.adj+1]
+
+ }
+
+
+ ##### do alignment
+
+ myseq5len=max(nchar(mySeq5N))
+ myseq3len=max(nchar(mySeq3N))
+ res5=sapply(mySeq5N,function(x) strsplit(x,""))
+ res3=sapply(mySeq3N,function(x) strsplit(x,""))
+
+ res5=lapply(res5,function(x) x=c(x,rep("N",myseq5len-length(x))))
+ res3=lapply(res3,function(x) x=c(x,rep("N",myseq3len-length(x))))
+ #get nucleotide frequencies
+ nuc <- c("A","T","G","C","N")
+ res=do.call(rbind,res5)
+ nucFreq5=NULL
+ for (j in 1:ncol(res)){
+ nucFreq5=rbind(nucFreq5,table(c(nuc,res[,j])))
+ }
+ nucFreq5=nucFreq5-1
+
+ res=do.call(rbind,res3)
+ nucFreq3=NULL
+ for (j in 1:ncol(res)){
+ nucFreq3=rbind(nucFreq3,table(c(nuc,res[,j])))
+ }
+ nucFreq3=nucFreq3-1
+
+ nucFreq5=nucFreq5[,-4]
+ nucFreq3=nucFreq3[,-4]
+ #find the break points
+ # start5=estBr5-1
+ # start3=estBr3+1
+ start5=myseq5len
+ start3=myseq3len
+
+ fcErr=fcProp=NULL
+ entropy3=entropy5=entropyInter=NULL
+ for (j in 10:start3){ #at least 10 bases (1/1e6 by chance) overlapped between two transcripts
+ newstart3=j
+ #get new match
+ inter5StarPos=start5-(newstart3-1)
+ if (inter5StarPos < 1) inter5StarPos=1
+ inter5=nucFreq5[inter5StarPos:myseq5len,]
+
+ inter3EndPos=newstart3+myseq5len-start5 # we fix start5=myseq5len, so it will add zero
+ if (inter3EndPos > myseq3len) inter3EndPos=myseq3len
+ inter3=nucFreq3[1:inter3EndPos,]
+
+ if (nrow(inter5)!=nrow(inter3)) break();
+
+ consProp5=apply(inter5,1,max)/rowSums(inter5)
+ consProp3=apply(inter3,1,max)/rowSums(inter3)
+ consProp5[is.na(consProp5)]=1
+ consProp3[is.na(consProp3)]=1
+ consPropInter=apply(inter3+inter5,1,max)/rowSums(inter3+inter5)
+ consPropInter[is.na(consPropInter)]=1e-9
+
+ fcProp=c(fcProp,(sum(consProp5>consPropInter)+sum(consProp3>consPropInter))/(2*length(consPropInter)))
+ fcErr=c(fcErr,(mean(consProp5-consPropInter)+mean(consProp3-consPropInter))/2)
+ # fcProp=c(fcProp,2*mean(consPropInter)/(mean(consProp5)+mean(consProp3)))
+ entropyInter=c(entropyInter,-sum(consPropInter*log(consPropInter)))
+ entropy3=c(entropy3,-sum(consProp3*log(consProp3)))
+ entropy5=c(entropy5,-sum(consProp5*log(consProp5)))
+ }
+
+
+ res=list()
+ res$estBr5=estBr5
+ res$estBr3=estBr3
+ res$myseq5len=myseq5len
+ res$myseq3len=myseq3len
+ res$mySeq5N=mySeq5N
+ res$mySeq3N=mySeq3N
+ res$mySplit5N=mySplit5N
+ res$mySplit3N=mySplit3N
+ res$nucFreq5=nucFreq5
+ res$nucFreq3=nucFreq3
+ res$fcProp=fcProp
+ res$fcErr=fcErr
+ res$entropyInter=entropyInter
+ res$entropy3=entropy3
+ res$entropy5=entropy5
+
+ matchInfo[[fName]]=res
+
+
+ consensusProp=c(consensusProp,min(fcProp))
+ consensusErr=c(consensusErr,min(fcErr))
+ consensusEntropy=c(consensusEntropy,min(entropyInter))
+
+ }
+
+ fusionCandidate$consensusEntropy=consensusEntropy
+ fusionCandidate$consensusProp=consensusProp
+ fusionCandidate$consensusErr=consensusErr
+ fusionCandidate$consensusScore=fusionCandidate$consensusErr*fusionCandidate$consensusProp
+
+ return(list(fusionCandidate=fusionCandidate,matchInfo=matchInfo))
+}
+
+
+
+exportMappedFusionReads <- function(inPath, readStrands, fastaOut, junctInfo, fusionName,fsizeLadder){
+ ##### export mapped reads of fusion genes to files
+ fastaDat2=fastaDat1=list();
+ frfiles=list.files(inPath,paste(readStrands,"_fusionMappedReadsChunk_*",sep=""))
+ for (i in 1:length(frfiles)){
+ #read fasta files
+ ftag=rev(strsplit(strsplit(frfiles[i],"\\.")[[1]][1],"_")[[1]])[1]
+ con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat1[[frfiles[i]]]=mydata
+
+ con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat2[[frfiles[i]]]=mydata
+ }
+
+ if (is.null(fastaOut) || is.na(fastaOut)) fastaOut=""
+ con1 <- file(paste(fastaOut,readStrands,"_fusionReads_1.fa",sep=""), "w", blocking = FALSE)
+ con2 <- file(paste(fastaOut,readStrands,"_fusionReads_2.fa",sep=""), "w", blocking = FALSE)
+
+ ###########
+ #detect read positions in fasta files
+ for (fName in fusionName){
+ res=junctInfo[[fName]]
+ if (length(res)>0){
+ myreadID=res$readID
+ rID=unlist(myreadID)
+ rID=sort(rID)
+ fID=unlist(lapply(rID, function(x) which(fsizeLadder>=x)[1]))
+ rID.adj=unlist(lapply(seq_along(rID), function(x) if (fID[x] > 1) return(rID[x]-fsizeLadder[fID[x]-1]) else return(rID[x])))
+ #export reads to file
+ for (j in 1:length(rID.adj)){
+ readHead=paste(">FuSeq__MR__",unlist(res$readL.ReadPos)[j],"__",unlist(res$readR.ReadPos)[j],"__",fName," /1",sep="")
+ writeLines(readHead,con1)
+ writeLines(fastaDat1[[fID[j]]][rID.adj[j]*2],con1)
+
+ readHead=paste(">FuSeq__MR__",unlist(res$readL.ReadPos)[j],"__",unlist(res$readR.ReadPos)[j],"__",fName," /2",sep="")
+ writeLines(readHead,con2)
+ writeLines(fastaDat2[[fID[j]]][rID.adj[j]*2],con2)
+ }
+ }
+ }
+ close(con1)
+ close(con2)
+}
+
+
+
+exportSplitFusionReads <- function(inPath, readStrands, fastaOut, splitReads, fusionName){
+ ##### export read paids of the split reads of fusion genes to files
+ fastaDat2=fastaDat1=list();
+ frfiles=list.files(inPath,paste("splitReadInfo_*",sep=""))
+ for (i in 1:length(frfiles)){
+ #read fasta files
+ ftag=rev(strsplit(strsplit(frfiles[i],"\\.")[[1]][1],"_")[[1]])[1]
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat1[[frfiles[i]]]=mydata
+
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaDat2[[frfiles[i]]]=mydata
+ }
+
+ fastaDat1=unlist(fastaDat1)
+ fastaDat2=unlist(fastaDat2)
+
+ if (is.null(fastaOut) || is.na(fastaOut)) fastaOut=""
+ con1 <- file(paste(fastaOut,readStrands,"_fusionReads_1.fa",sep=""), "a", blocking = FALSE)
+ con2 <- file(paste(fastaOut,readStrands,"_fusionReads_2.fa",sep=""), "a", blocking = FALSE)
+
+
+ #detect read positions in fasta files
+ for (fName in fusionName){
+ myreadID=which(splitReads$name12==fName)
+ if (length(myreadID)>0){
+ myheader=as.character(splitReads$header[myreadID])
+ rID.adj=match(myheader,fastaDat1)
+ #export reads to file
+ for (j in rID.adj){
+ readHead=paste(">FuSeq__SR__",splitReads$front_hitpos[j],"__",splitReads$back_hitpos[j],"__",fName," /1",sep="")
+ writeLines(readHead,con1)
+ writeLines(fastaDat1[j+1],con1)
+
+ readHead=paste(">FuSeq__SR__",splitReads$front_hitpos[j],"__",splitReads$back_hitpos[j],"__",fName," /2",sep="")
+ writeLines(readHead,con2)
+ writeLines(fastaDat2[j+1],con2)
+ }
+ }
+ }
+ close(con1)
+ close(con2)
+}
+
+
+testFtxlen <- function(mu, sig, r, ftxlen, kmerlen,fragDist,M=10000){
+ # to get a distribution of one side fragments with the limitation of k-mer length
+ x = runif(M, min=0, max= min(ftxlen,mu+2*sig))
+ len = sample(fragDist[,1], M, replace=TRUE, prob = fragDist[,2])
+ #limit x by the kmerlen
+ keepID=which(x>=kmerlen)
+ x=x[keepID]
+ len=len[keepID]
+ return(list(x=x, len=len))
+}
+
+
+
+refineJunctionBreak <-function(junctBr, anntxdb, fragmentInfo, readStrands, fragDist){
+ ##########################
+ #### revisit junction breaks to remove outliers and detect splicing sites
+ ##########################
+ exonInfo=select(anntxdb, keys=unique(c(as.character(junctBr$myFusionFinal$gene1),as.character(junctBr$myFusionFinal$gene2))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+
+ junctBr$myFusionFinal$adjFragmentNum=junctBr$myFusionFinal$outlierNum=NA
+ junctBr$myFusionFinal$ftxLenProp=junctBr$myFusionFinal$ftxMedianLen=junctBr$myFusionFinal$ftxMeanLen=NA
+ junctBr$myFusionFinal$ftx5LenSd=junctBr$myFusionFinal$ftx5LenMean=junctBr$myFusionFinal$ftx3LenSd=junctBr$myFusionFinal$ftx3LenMean=NA
+
+ junctBr$myFusionFinal$crt.tx5GapMean=junctBr$myFusionFinal$crt.tx3GapMean=junctBr$myFusionFinal$crt.tx5GapSd=junctBr$myFusionFinal$crt.tx3GapSd=junctBr$myFusionFinal$crt.tx5LenMean=junctBr$myFusionFinal$crt.tx3LenMean=junctBr$myFusionFinal$crt.tx5LenSd=junctBr$myFusionFinal$crt.tx3LenSd=NA
+ for (i in 1:nrow(junctBr$myFusionFinal)){
+ #which(junctBr$myFusionFinal$fusionName=="ENSG00000076864-ENSG00000138079")
+ fgeName=as.character(junctBr$myFusionFinal$name12)[i]
+ gene1=as.character(junctBr$myFusionFinal$gene1[i])
+ gene2=as.character(junctBr$myFusionFinal$gene2[i])
+
+ res=junctBr$junctInfo[[i]]
+
+ #detect outliers
+ adjPosL=unlist(res$adj.readL.GenePos)
+ adjPosR=unlist(res$adj.readR.GenePos)
+ rmID=NULL
+
+ #need empirical fragment length distribution here
+ flenRef=rep(fragDist[,1],fragDist[,2])
+ flenRef=flenRef-mean(flenRef)
+
+ ###### use qqplot to detect outliers: build a line by y=bx+a and compute the distance of value to the line
+ # flenRef=flenRef[flenRefquantile(flenRef,0.05)]
+ # quanValRef=quantile(flenRef,probs=c(0.25,0.75))
+ #
+ # #left
+ # adjPosL=adjPosL-median(adjPosL)
+ # myorder=order(adjPosL,decreasing = FALSE)
+ # adjPosL=adjPosL[myorder]
+ # quanVal=quantile(adjPosL,probs=c(0.25,0.75))
+ # qqpos = qqplot(flenRef,adjPosL,plot.it = FALSE)
+ # bval=diff(quanVal)/diff(quanValRef)
+ # a=quanVal[1]-bval*quanValRef[1]
+ # ref.val = a+ bval*qqpos$x
+ # #points(qqpos$x, ref.val, col='red')
+ # res.val = qqpos$y - ref.val
+ # sig = diff(quanVal)/(qnorm(0.75)-qnorm(0.25))
+ # stdres = res.val/sig
+ # outlierID=which(stdres< -2)
+ # #adjPosL[outlierID]
+ # outlierID=myorder[outlierID]
+ # #get back the original values of adjPosL
+ # adjPosL=unlist(res$adj.readL.GenePos)
+ # #adjPosL=adjPosL[myorder[order(myorder)]]
+ # #adjPosL[outlierID]
+ # rmID=c(rmID,outlierID)
+ #
+ # #right
+ # adjPosR=adjPosR-median(adjPosR)
+ # myorder=order(adjPosR,decreasing = FALSE)
+ # adjPosR=adjPosR[myorder]
+ # quanVal=quantile(adjPosR,probs=c(0.25,0.75))
+ # qqpos = qqplot(flenRef,adjPosR,plot.it = FALSE)
+ # bval=diff(quanVal)/diff(quanValRef)
+ # a=quanVal[1]-bval*quanValRef[1]
+ # ref.val = a+ bval*qqpos$x
+ # #points(qqpos$x, ref.val, col='red')
+ # res.val = qqpos$y - ref.val
+ # sig = diff(quanVal)/(qnorm(0.75)-qnorm(0.25))
+ # stdres = res.val/sig
+ # outlierID=which(stdres< -2)
+ # #adjPosR[outlierID]
+ # outlierID=myorder[outlierID]
+ # #get back the original values of adjPosL
+ # adjPosR=unlist(res$adj.readR.GenePos)
+ # #adjPosR=adjPosR[myorder[order(myorder)]]
+ # #adjPosR[outlierID]
+ # rmID=c(rmID,outlierID)
+ #
+ # rmID=unique(rmID)
+
+ ###### test directly by median
+ # medL=median(adjPosL)
+ # distL=adjPosL-medL
+ # propL=pnorm(abs(distL), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ # medR=median(adjPosR)
+ # distR=adjPosR-medR
+ # propR=pnorm(abs(distR), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ # rmID=c(which(propL>0.99),which(propR>0.99)) #0.99 is too big that still allows many outliers. That might lead to decide an incorrect junction break later on
+ #
+
+ ##### test the variance based on empirical variance of fragment length distribution
+ medL=mean(adjPosL)
+ distL=adjPosL-medL
+ propL=1-sapply(distL, function(x){ min(sum(flenRef>x),sum(flenRef>x))/10000 })
+
+ #propL=pnorm(abs(distL), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ medR=mean(adjPosR)
+ distR=adjPosR-medR
+ propR=1-sapply(distR, function(x){ min(sum(flenRef>x),sum(flenRef>x))/10000 })
+ #propR=pnorm(abs(distR), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ rmID=c(which(propL<0.01),which(propR<0.01)) #0.99 is too big that still allows many outliers. That might lead to decide an incorrect junction break later on
+
+ #get chrPos
+ chrPosL=unlist(res$readL.chrPos)
+ chrPosR=unlist(res$readR.chrPos)
+ seqLenL=unlist(res$readL.seqLen)
+ seqLenR=unlist(res$readR.seqLen)
+ offsetL=unlist(res$readL.Pos)-unlist(res$readL.ReadPos)
+ offsetR=unlist(res$readR.Pos)-unlist(res$readR.ReadPos)
+ if (length(rmID)>0){
+ adjPosL=adjPosL[-rmID]
+ adjPosR=adjPosR[-rmID]
+ chrPosL=chrPosL[-rmID]
+ chrPosR=chrPosR[-rmID]
+ seqLenL=seqLenL[-rmID]
+ seqLenR=seqLenR[-rmID]
+ offsetL=offsetL[-rmID]
+ offsetR=offsetR[-rmID]
+ }
+
+ geneExonMatL=exonInfo[exonInfo$GENEID==gene1,]
+ geneExonMatR=exonInfo[exonInfo$GENEID==gene2,]
+
+ if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){ #read1 for 3prime and read2 for 5prime
+ if (length(chrPosL) > 0){
+ if (junctBr$myFusionFinal$strand1[i]=="+"){
+ nearest3Chrpos=min(chrPosL)
+ diffL=geneExonMatL$EXONEND-nearest3Chrpos
+ } else{
+ nearest3Chrpos=max(chrPosL)
+ diffL=nearest3Chrpos-geneExonMatL$EXONSTART
+ }
+ exIDL=which.min(abs(diffL))
+
+ if (junctBr$myFusionFinal$strand2[i]=="+"){
+ nearest5Chrpos=max(chrPosR)
+ diffR=nearest5Chrpos-geneExonMatR$EXONSTART
+ }else{
+ nearest5Chrpos=min(chrPosR)
+ diffR=geneExonMatR$EXONEND-nearest5Chrpos
+ }
+ exIDR=which.min(abs(diffR))
+ diffL[exIDL]
+ diffR[exIDR]
+ #true breaking points
+ if (junctBr$myFusionFinal$strand1[i]=="+") res$tx3br=geneExonMatL$EXONSTART[exIDL] else res$tx3br=geneExonMatL$EXONEND[exIDL]
+ if (junctBr$myFusionFinal$strand2[i]=="+") res$tx5br=geneExonMatR$EXONEND[exIDR] else res$tx5br=geneExonMatR$EXONSTART[exIDR]
+
+ #find the position of the true breaking points in the read distributions
+ fexonL=sort(unique(c(unlist(res$readL.ExonID),geneExonMatL$EXONID[exIDL])))
+ mygeneExL=geneExonMatL[match(fexonL,geneExonMatL$EXONID),]
+ #chrReadPosL=unlist(res$readL.chrReadPos)
+ chrReadPosL=chrPosL
+ ftxReadPosL=convertChrPosGenePos(chrReadPosL,geneExonMat=mygeneExL)
+
+ ftx3brPos=convertChrPosGenePos(res$tx3br,geneExonMat=mygeneExL)
+ #if (junctBr$myFusionFinal$strand1[i]=="+") ftx5len=ftx5brPos-ftxReadPosL+seqLenL+offsetL else ftx5len=ftxReadPosL-ftx5brPos+seqLenL+offsetL
+ if (junctBr$myFusionFinal$strand1[i]=="+") ftx3len=ftxReadPosL-ftx3brPos - offsetL + fragmentInfo$readlen else ftx3len=ftx3brPos-ftxReadPosL - offsetL + fragmentInfo$readlen
+
+ fexonR=sort(unique(c(unlist(res$readR.ExonID),geneExonMatR$EXONID[exIDR])))
+ mygeneExR=geneExonMatR[match(fexonR,geneExonMatR$EXONID),]
+ #chrReadPosR=unlist(res$readR.chrReadPos)
+ chrReadPosR=chrPosR
+ ftxReadPosR=convertChrPosGenePos(chrReadPosR,geneExonMat=mygeneExR)
+ ftx5brPos=convertChrPosGenePos(res$tx5br,geneExonMat=mygeneExR)
+ #if (junctBr$myFusionFinal$strand2[i]=="+") ftx3len=ftxReadPosR-ftx3brPos - offsetR + fragmentInfo$readlen else ftx3len=ftx3brPos-ftxReadPosR - offsetR + fragmentInfo$readlen
+ if (junctBr$myFusionFinal$strand2[i]=="+") ftx5len=ftx5brPos-ftxReadPosR+seqLenR+offsetR else ftx5len=ftxReadPosR-ftx5brPos+seqLenR+offsetR
+
+ ftxLen=ftx5len+ftx3len
+
+ res$fexonL=fexonL
+ res$fexonR=fexonR
+
+
+ res$ftxReadPosL=ftxReadPosL
+ res$ftxReadPosR=ftxReadPosR
+
+ res$ftx5brPos=ftx5brPos
+ res$ftx5len=ftx5len
+
+ res$ftx3brPos=ftx3brPos
+ res$ftx3len=ftx3len
+
+ res$ftxMedianLen=median(ftxLen)
+ res$ftxMeanLen=mean(ftxLen)
+
+ ftxLenProp=pnorm(mean(ftxLen), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ res$ftxLenProp=ftxLenProp
+ }
+
+ }else{ #read1 for 5prime and read2 for 3prime
+
+ if (length(chrPosL) > 0){
+ if (junctBr$myFusionFinal$strand1[i]=="+"){
+ nearest5Chrpos=max(chrPosL)
+ diffL=geneExonMatL$EXONEND-nearest5Chrpos
+ } else{
+ nearest5Chrpos=min(chrPosL)
+ diffL=nearest5Chrpos-geneExonMatL$EXONSTART
+ }
+ exIDL=which.min(abs(diffL))
+
+ if (junctBr$myFusionFinal$strand2[i]=="+"){
+ nearest3Chrpos=min(chrPosR)
+ diffR=nearest3Chrpos-geneExonMatR$EXONSTART
+ }else{
+ nearest3Chrpos=max(chrPosR)
+ diffR=geneExonMatR$EXONEND-nearest3Chrpos
+ }
+ exIDR=which.min(abs(diffR))
+ diffL[exIDL]
+ diffR[exIDR]
+ #true breaking points
+ if (junctBr$myFusionFinal$strand1[i]=="+") res$tx5br=geneExonMatL$EXONEND[exIDL] else res$tx5br=geneExonMatL$EXONSTART[exIDL]
+ if (junctBr$myFusionFinal$strand2[i]=="+") res$tx3br=geneExonMatR$EXONSTART[exIDR] else res$tx3br=geneExonMatR$EXONEND[exIDR]
+ #find the position of the true breaking points in the read distributions
+
+ fexonL=sort(unique(c(unlist(res$readL.ExonID),geneExonMatL$EXONID[exIDL])))
+ mygeneExL=geneExonMatL[match(fexonL,geneExonMatL$EXONID),]
+ # chrReadPosL=unlist(res$readL.chrReadPos)
+ chrReadPosL=chrPosL
+ ftxReadPosL=convertChrPosGenePos(chrReadPosL,geneExonMat=mygeneExL)
+ ftx5brPos=convertChrPosGenePos(res$tx5br,geneExonMat=mygeneExL)
+ if (junctBr$myFusionFinal$strand1[i]=="+") ftx5len=ftx5brPos-ftxReadPosL+seqLenL+offsetL else ftx5len=ftxReadPosL-ftx5brPos+seqLenL+offsetL
+
+ fexonR=sort(unique(c(unlist(res$readR.ExonID),geneExonMatR$EXONID[exIDR])))
+ mygeneExR=geneExonMatR[match(fexonR,geneExonMatR$EXONID),]
+ #chrReadPosR=unlist(res$readR.chrReadPos)
+ chrReadPosR=chrPosR
+ ftxReadPosR=convertChrPosGenePos(chrReadPosR,geneExonMat=mygeneExR)
+ ftx3brPos=convertChrPosGenePos(res$tx3br,geneExonMat=mygeneExR)
+ if (junctBr$myFusionFinal$strand2[i]=="+") ftx3len=ftxReadPosR-ftx3brPos - offsetR + fragmentInfo$readlen else
+ ftx3len=ftx3brPos-ftxReadPosR - offsetR + fragmentInfo$readlen
+
+ ftxLen=ftx5len+ftx3len
+
+ res$fexonL=fexonL
+ res$fexonR=fexonR
+
+ res$ftxReadPosL=ftxReadPosL
+ res$ftxReadPosR=ftxReadPosR
+
+ res$ftx5brPos=ftx5brPos
+ res$ftx5len=ftx5len
+
+ res$ftx3brPos=ftx3brPos
+ res$ftx3len=ftx3len
+
+ res$ftxMedianLen=median(ftxLen)
+ res$ftxMeanLen=mean(ftxLen)
+
+ ftxLenProp=pnorm(mean(ftxLen), mean = fragmentInfo$fragLengthMean, sd = fragmentInfo$fragLengthSd, lower.tail = TRUE, log.p = FALSE)
+ res$ftxLenProp=ftxLenProp
+ }
+ }
+ res$outlierID=rmID
+ res$outlierNum=length(rmID)
+ junctBr$junctInfo[[i]]=res
+
+ #update junctBr$myFusionFinal table
+ junctBr$myFusionFinal$adjFragmentNum[i]=junctBr$myFusionFinal$fragmentNum[i]- junctBr$junctInfo[[i]]$outlierNum
+ if (junctBr$myFusionFinal$adjFragmentNum[i] > 0){
+ junctBr$myFusionFinal$outlierNum[i]= junctBr$junctInfo[[i]]$outlierNum
+ junctBr$myFusionFinal$ftxLenProp[i]=junctBr$junctInfo[[i]]$ftxLenProp
+ junctBr$myFusionFinal$ftxMedianLen[i]=junctBr$junctInfo[[i]]$ftxMedianLen
+ junctBr$myFusionFinal$ftxMeanLen[i]=junctBr$junctInfo[[i]]$ftxMeanLen
+
+ junctBr$myFusionFinal$ftx5LenMean[i]=mean(junctBr$junctInfo[[i]]$ftx5len)
+ junctBr$myFusionFinal$ftx5LenSd[i]=sd(junctBr$junctInfo[[i]]$ftx5len)
+ junctBr$myFusionFinal$ftx3LenMean[i]=mean(junctBr$junctInfo[[i]]$ftx3len)
+ junctBr$myFusionFinal$ftx3LenSd[i]=sd(junctBr$junctInfo[[i]]$ftx3len)
+
+ #update other information
+ if (res$outlierNum > 0){
+ res$crt.tx3.gap=res$tx3.gap[-rmID]
+ res$crt.tx5.gap=res$tx5.gap[-rmID]
+ res$crt.tx3.len=res$tx3.len[-rmID]
+ res$crt.tx5.len=res$tx5.len[-rmID]
+
+ if (sum(res$crt.tx3.gap==1)==0){
+ res$crt.tx3.len=res$crt.tx3.len-min(res$crt.tx3.gap)+1
+ res$crt.tx3.gap=res$crt.tx3.gap-min(res$crt.tx3.gap)+1
+ }
+
+ if (sum(res$crt.tx5.gap==1)==0){
+ res$crt.tx5.len=res$crt.tx5.len-min(res$crt.tx5.gap)+1
+ res$crt.tx5.gap=res$crt.tx5.gap-min(res$crt.tx5.gap)+1
+ }
+
+ res$crt.estFragLen=res$crt.tx3.len+res$crt.tx5.len
+
+ junctBr$myFusionFinal$crt.tx5GapMean[i]=mean(res$crt.tx5.gap)
+ junctBr$myFusionFinal$crt.tx3GapMean[i]=mean(res$crt.tx3.gap)
+ junctBr$myFusionFinal$crt.tx5GapSd[i]=sd(res$crt.tx5.gap)
+ junctBr$myFusionFinal$crt.tx3GapSd[i]=sd(res$crt.tx3.gap)
+
+ junctBr$myFusionFinal$crt.tx5LenMean[i]=mean(res$crt.tx5.len)
+ junctBr$myFusionFinal$crt.tx3LenMean[i]=mean(res$crt.tx3.len)
+ junctBr$myFusionFinal$crt.tx5LenSd[i]=sd(res$crt.tx5.len)
+ junctBr$myFusionFinal$crt.tx3LenSd[i]=sd(res$crt.tx3.len)
+
+ }
+ }
+
+ }
+
+ return(junctBr)
+
+}
+
+
+
+
+checkEndExon <-function(myFusionFinal, junctBr=NULL, anntxdb, readStrands,shrinkLen=5, type="SR"){
+ ##### checking the start/ending exon of gene
+ rmID=NULL
+ if (type=="SR"){
+ if (nrow(myFusionFinal)>0){
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionFinal$front_gene), as.character(myFusionFinal$back_gene))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ rmID=NULL
+ for (i in 1:nrow(myFusionFinal)){
+ #####5 prime
+ #check exon at gene-level
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene1[i],]
+ exStartID=which(geExonMat$EXONSTART==min(geExonMat$EXONSTART))
+ exEndID=which(geExonMat$EXONEND==max(geExonMat$EXONEND))
+ diffS=unlist(lapply(myFusionFinal$brchposEx5[i],function(x) x-geExonMat$EXONSTART))
+ diffE=unlist(lapply(myFusionFinal$brchposEx5[i],function(x) x-geExonMat$EXONEND))
+ if (geExonMat$TXSTRAND[1]=="-") diff=diffS else diff=diffE
+ if (min(abs(diff)) < shrinkLen) {
+ myExID=which(abs(diff) < shrinkLen)
+ if (geExonMat$TXSTRAND[1]=="-") exBoundID=exStartID else exBoundID=exEndID
+ if (sum(is.na(match(myExID,exBoundID)))==0){
+ rmID=c(rmID,i)
+ }
+ } #else{} # if so, the exon of the junction can be detected as the follow: choose the other diff(diffS/diffE) and select the start/end of the next/previous exon of the transcripts in the genes. However, that mean this one is not the start/end exon of the gene. Thus we don't need to determine the exon ID anymore
+ ####3 prime
+ #check exon at gene-level
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene2[i],]
+ exStartID=which(geExonMat$EXONSTART==min(geExonMat$EXONSTART))
+ exEndID=which(geExonMat$EXONEND==max(geExonMat$EXONEND))
+ diffS=unlist(lapply(myFusionFinal$brchposEx3[i],function(x) x-geExonMat$EXONSTART))
+ diffE=unlist(lapply(myFusionFinal$brchposEx3[i],function(x) x-geExonMat$EXONEND))
+ if (geExonMat$TXSTRAND[1]=="+") diff=diffS else diff=diffE
+
+ if (min(abs(diff)) < shrinkLen) {
+ myExID=which(abs(diff) < shrinkLen)
+ if (geExonMat$TXSTRAND[1]=="+") exBoundID=exStartID else exBoundID=exEndID
+ if (sum(is.na(match(myExID,exBoundID)))==0){
+ rmID=c(rmID,i)
+ }
+ }#else{} # if so, the exon of the junction can be detected as the follow: choose the other diff(diffE/diffS) and select the start/end of the next/previous exon of the transcripts in the genes. However, that mean this one is not the start/end exon of the gene. Thus we don't need to determine the exon ID anymore
+ }
+ }
+ }
+
+ if (type=="MR"){
+ if (nrow(myFusionFinal)>0){
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionFinal$gene1), as.character(myFusionFinal$gene2))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+
+ for (i in 1:nrow(myFusionFinal)){
+ myfge=myFusionFinal$fusionName[i]
+ myjbr=junctBr$junctInfo[[myfge]]
+ ##### check 5 prime
+ if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){ #read1 for 3prime and read2 for 5prime
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene2[i],]
+ }else{ #read1 for 5prime and read2 for 3prime
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene1[i],]
+ }
+
+ exStartID=which(geExonMat$EXONSTART==min(geExonMat$EXONSTART))
+ exEndID=which(geExonMat$EXONEND==max(geExonMat$EXONEND))
+
+ if (geExonMat$TXSTRAND[1]=="-") exBoundID=exStartID else exBoundID=exEndID
+ if (geExonMat$TXSTRAND[1]=="-") myExID=geExonMat$EXONID[which(geExonMat$EXONSTART==myjbr$tx5br)] else myExID=geExonMat$EXONID[which(geExonMat$EXONEND==myjbr$tx5br)]
+
+ if(sum(!is.na(match(unique(geExonMat$EXONID[exBoundID]),unique(myExID))))>0) rmID=c(rmID,i)
+
+
+ ##### check 3 prime
+ if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){ #read1 for 3prime and read2 for 5prime
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene1[i],]
+
+ }else{ #read1 for 5prime and read2 for 3prime
+ geExonMat=exonInfo[exonInfo$GENEID==myFusionFinal$gene2[i],]
+ }
+
+ exStartID=which(geExonMat$EXONSTART==min(geExonMat$EXONSTART))
+ exEndID=which(geExonMat$EXONEND==max(geExonMat$EXONEND))
+ if (geExonMat$TXSTRAND[1]=="+") exBoundID=exStartID else exBoundID=exEndID
+ if (geExonMat$TXSTRAND[1]=="+") myExID=geExonMat$EXONID[which(geExonMat$EXONSTART==myjbr$tx3br)] else myExID=geExonMat$EXONID[which(geExonMat$EXONEND==myjbr$tx3br)]
+ if(sum(!is.na(match(unique(geExonMat$EXONID[exBoundID]),unique(myExID))))>0) rmID=c(rmID,i)
+
+ }
+ }
+ }
+
+ return(rmID)
+}
+
+
+
+
+
+
+
+
diff --git a/R/createSqlite.R b/R/createSqlite.R
new file mode 100644
index 0000000..1e7f964
--- /dev/null
+++ b/R/createSqlite.R
@@ -0,0 +1,13 @@
+#####
+# create sqlite from gtf using GenomicFeatures, for example Homo_sapiens.GRCh37.75.sqlite
+# Rscript createSqlite.R Homo_sapiens.GRCh37.75.gtf Homo_sapiens.GRCh37.75.sqlite
+############################################################
+args = commandArgs(trailingOnly=TRUE)
+gtfFile=args[1];
+gtfSqliteFn=args[2];
+library(GenomicFeatures);
+gtfTxdb <- makeTxDbFromGFF(file=gtfFile,
+ format="gtf",
+ dataSource=paste("Link to the source",sep=""),
+ organism="Homo sapiens")
+saveDb(gtfTxdb,file=gtfSqliteFn)
\ No newline at end of file
diff --git a/R/detectJunctionBreaks.R b/R/detectJunctionBreaks.R
new file mode 100644
index 0000000..d6c8ea0
--- /dev/null
+++ b/R/detectJunctionBreaks.R
@@ -0,0 +1,369 @@
+############################################################
+##### detect junction break positions from mapped reads
+detectJunctionBreaks <-function(fgeList,inPath,feq, feqFgeMap, anntxdb, readStrands="UN", shrinkLen=3){
+ myFusionFinal=fgeList
+ ##### input fusion reads
+ #load fusion reads
+ cat("\n Get mapped fusion reads")
+ frfiles=list.files(inPath,paste(readStrands,"_fusionMappedReadsChunk_*",sep=""))
+ fusionRead=NULL;
+ fsizes=NULL;
+ for (i in 1:length(frfiles)){
+ tmpDat=read.csv(paste(inPath,"/",frfiles[i],sep=""), header =FALSE, sep="\t")
+ fusionRead=rbind(fusionRead,tmpDat)
+ fsizes=c(fsizes,nrow(tmpDat))
+ }
+ fsizeLadder=cumsum(fsizes)
+ colnames(fusionRead)=c("read1","read2","read1Pos","read2Pos","seq1Pos","seq2Pos","seq1Len","seq2Len")
+ #dim(fusionRead)
+ cat("\n The number of mapped fusion reads: ",nrow(fusionRead))
+ fre1=as.character(fusionRead$read1)
+ fre1=trimws(fre1)
+ fre2=as.character(fusionRead$read2)
+ fre2=trimws(fre2)
+ read1Pos=as.character(fusionRead$read1Pos)
+ read2Pos=as.character(fusionRead$read2Pos)
+ seq1Pos=as.character(fusionRead$seq1Pos)
+ seq2Pos=as.character(fusionRead$seq2Pos)
+ seq1Len=as.character(fusionRead$seq1Len)
+ seq2Len=as.character(fusionRead$seq2Len)
+
+
+ #load fragment info - this is not neccessary thi moment
+ fragmentInfo=read.csv(paste(inPath,"/fragmentInfo.txt",sep=""), header =TRUE, sep="\t")
+ readLen=fragmentInfo[1,1]
+ #load the feq file
+ feqRaw=read.csv(paste(inPath,"/feq_",readStrands,".txt",sep=""), header =TRUE, sep="\t")
+ feqRead1=feqRaw[feqRaw$Read==1,]
+ feqRead2=feqRaw[feqRaw$Read==2,]
+ #get feq-fge map
+ # feqFgeMap=feqInfo$feqFgeMap
+ # feq=feqInfo$feq
+ cat("\n Preparing other information ...")
+ feqFtxMap1=tapply(as.character(feqRead1$Transcript),feqRead1$Feq,c)
+ feqRead1Name=unlist(lapply(feqFtxMap1,function(x) paste(x,collapse =" ")))
+ feqFtxMap2=tapply(as.character(feqRead2$Transcript),feqRead2$Feq,c)
+ feqRead2Name=unlist(lapply(feqFtxMap2,function(x) paste(x,collapse =" ")))
+
+ read1Pos=lapply(read1Pos,function(x) as.integer(unlist(strsplit(x," "))))
+ read2Pos=lapply(read2Pos,function(x) as.integer(unlist(strsplit(x," "))))
+ seq1Pos=lapply(seq1Pos,function(x) as.integer(unlist(strsplit(x," "))))
+ seq2Pos=lapply(seq2Pos,function(x) as.integer(unlist(strsplit(x," "))))
+ seq1Len=lapply(seq1Len,function(x) as.integer(unlist(strsplit(x," "))))
+ seq2Len=lapply(seq2Len,function(x) as.integer(unlist(strsplit(x," "))))
+
+
+ #get some annotations
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionFinal$gene1),as.character(myFusionFinal$gene2))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ txToGene=select(anntxdb, keys=unique(as.character(feqRaw[,1])), columns=c("GENEID","TXCHROM"), keytype = "TXNAME")
+
+
+ cat("\n Detect positions of junction breaks")
+ brpos5.start=brpos5.end=brpos3.start=brpos3.end=NULL
+ genebrpos5.start=genebrpos5.end=genebrpos3.start=genebrpos3.end=NULL
+ fragmentMean=fragmentSd=fragmentNum=fragmentTest=NULL;
+ tx5LenMean=tx3LenMean=tx5LenSd=tx3LenSd=NULL;
+ tx5GapMean=tx3GapMean=tx5GapSd=tx3GapSd=NULL;
+ flen5=flen3=NULL;
+ splitRNum5=splitRNum3=exNum1=exNum2=NULL;
+ nondupCount=NULL;
+
+ junctInfo=list();
+
+ for (i in 1:nrow(myFusionFinal)){
+ fgeName=as.character(myFusionFinal$name12)[i]
+
+ gene1=as.character(myFusionFinal$gene1[i])
+ gene2=as.character(myFusionFinal$gene2[i])
+ myfeqID=feqFgeMap[[fgeName]]
+
+ readL.seqLen=readR.seqLen=readID=readL.chrPos=readR.chrPos=readL.Pos=readR.Pos=readL.GenePos=readR.GenePos=readL.tx=readR.tx=list();
+ readL.chrReadPos=readR.chrReadPos=readR.ReadPos=readL.ReadPos=list();
+ readL.ExonID=readR.ExonID=list();
+
+ for (j in 1:length(myfeqID)){
+ feqName=names(feq[myfeqID[j]])
+ #keepID=which(fre1==feqRead1Name[myfeqID[j]] & fre2==feqRead2Name[myfeqID[j]])
+ keepID1=which(fre1==feqRead1Name[myfeqID[j]])
+ keepID=keepID1[which(fre2[keepID1]==feqRead2Name[myfeqID[j]])]
+
+ readID[[feqName]]=keepID
+
+ xl=unlist(feqFtxMap1[myfeqID[j]])
+ xr=unlist(feqFtxMap2[myfeqID[j]])
+
+
+ IDl=which(txToGene[match(xl,txToGene$TXNAME),]$GENEID==gene1)
+ IDr=which(txToGene[match(xr,txToGene$TXNAME),]$GENEID==gene2)
+ #select only one because the others will locate to the same posistion
+ posl=IDl[1]
+ posr=IDr[1]
+
+ readposl=sapply(read1Pos[keepID],function(x) x[posl])
+ readposr=sapply(read2Pos[keepID],function(x) x[posr])
+ txposl=sapply(seq1Pos[keepID],function(x) x[posl])
+ txposr=sapply(seq2Pos[keepID],function(x) x[posr])
+
+ txSeqlenl=sapply(seq1Len[keepID],function(x) x[posl])
+ txSeqlenr=sapply(seq2Len[keepID],function(x) x[posr])
+
+ #reduce length of match kmer shrinkLen=3 or prop=0.25^3=0.015625
+ readposl=readposl+shrinkLen
+ readposr=readposr+shrinkLen
+ txposl=txposl+shrinkLen
+ txposr=txposr+shrinkLen
+ txSeqlenl=txSeqlenl-shrinkLen
+ txSeqlenr=txSeqlenr-shrinkLen
+
+ #save the information
+ readL.Pos[[feqName]]=txposl
+ readR.Pos[[feqName]]=txposr
+ readL.ReadPos[[feqName]]=readposl
+ readR.ReadPos[[feqName]]=readposr
+ readL.seqLen[[feqName]]=txSeqlenl
+ readR.seqLen[[feqName]]=txSeqlenr
+
+
+
+ #find position at chromosome level
+ txnamel=xl[posl]
+ txchrposl=convertChrPos(txnamel,txposl,exonInfo)
+ readL.chrPos[[feqName]]=txchrposl
+ txnamer=xr[posr]
+ txchrposr=convertChrPos(txnamer,txposr,exonInfo)
+ readR.chrPos[[feqName]]=txchrposr
+
+ readL.chrReadPos[[feqName]]=convertChrPos(txnamel,readposl,exonInfo)
+ readR.chrReadPos[[feqName]]=convertChrPos(txnamer,readposr,exonInfo)
+
+
+ #find the position at gene-level
+ readL.GenePos[[feqName]]=convertChrPosGenePos(txchrposl,gene1,exonInfo)
+ readR.GenePos[[feqName]]=convertChrPosGenePos(txchrposr,gene2,exonInfo)
+
+ readL.ExonID[[feqName]]=detectExonID3(txnamel,txposl,txSeqlenl,exonInfo)
+ readR.ExonID[[feqName]]=detectExonID3(txnamer,txposr,txSeqlenr, exonInfo)
+
+ readL.tx[[feqName]]=txnamel
+ readR.tx[[feqName]]=txnamer
+
+
+ }
+
+ res=list(readL.ReadPos=readL.ReadPos,readR.ReadPos=readR.ReadPos,readL.seqLen=readL.seqLen, readR.seqLen=readR.seqLen,readL.chrPos=readL.chrPos,readR.chrPos=readR.chrPos,readL.Pos=readL.Pos,readR.Pos=readR.Pos, readL.GenePos=readL.GenePos,readR.GenePos=readR.GenePos,readL.ExonID=readL.ExonID,readR.ExonID=readR.ExonID,readID=readID,readL.tx=readL.tx,readR.tx=readR.tx,readL.chrReadPos=readL.chrReadPos,readR.chrReadPos=readR.chrReadPos)
+
+ res$new.readL.GenePos=res$new.readR.GenePos=list()
+ mygeneExL=exonInfo[match(sort(unique(unlist(res$readL.ExonID))),exonInfo$EXONID),]
+ for (j in 1:length(myfeqID)) res$new.readL.GenePos[[names(res$readL.chrPos[j])]]=convertChrPosGenePos(res$readL.chrPos[[j]],geneExonMat=mygeneExL)
+ mygeneExR=exonInfo[match(sort(unique(unlist(res$readR.ExonID))),exonInfo$EXONID),]
+ for (j in 1:length(myfeqID)) res$new.readR.GenePos[[names(res$readR.chrPos[j])]]=convertChrPosGenePos(res$readR.chrPos[[j]],geneExonMat=mygeneExR)
+
+ ######
+ exNum1=c(exNum1,length(unique(unlist(res$readL.ExonID))))
+ exNum2=c(exNum2,length(unique(unlist(res$readR.ExonID))))
+ #update trueStartPos of fusion-gene
+ nondupCount=c(nondupCount,length(unique(paste(unlist(res$readL.chrReadPos),unlist(res$readR.chrReadPos),sep=""))))
+ readDirectTag=c(0,0)
+
+ res$adj.readL.GenePos=res$new.readL.GenePos
+ res$adj.readR.GenePos=res$new.readR.GenePos
+
+ ### In real data, we always work on RF direction even for UN (unstranded), so 5prime is in the Right side (read2) and 3prime is in the leftSide (read1)
+ # If RR happens, it might be a reorder of genes or due to protocols that should be investigate further.
+ if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){ #read1 for 3prime and read2 for 5prime
+ readDirectTag=c(3,5)
+ flen3=c(flen3,getGeneLen(geneExonMat=mygeneExL))
+ flen5=c(flen5,getGeneLen(geneExonMat=mygeneExR))
+ if (myFusionFinal$strand1[i] == "+"){
+ brpos3.start=c(brpos3.start,min(unlist(res$readL.chrPos)))
+ brpos3.end=c(brpos3.end,max(unlist(res$readL.chrPos)))
+ genebrpos3.start=c(genebrpos3.start,min(unlist(res$adj.readL.GenePos)))
+ genebrpos3.end=c(genebrpos3.end,max(unlist(res$adj.readL.GenePos)))
+ mySR3=0
+ for (myid in 1:length(res$adj.readL.GenePos)) mySR3=mySR3+sum(res$adj.readL.GenePos[[myid]]-(res$readL.Pos[[myid]]-res$readL.ReadPos[[myid]])genebrpos3.start[length(genebrpos3.start)]+shrinkLen)
+ splitRNum3=c(splitRNum3,mySR3)
+ }
+
+ if (myFusionFinal$strand2[i] == "+"){
+ for (myid in 1:length(res$adj.readR.GenePos)) res$adj.readR.GenePos[[myid]]=res$adj.readR.GenePos[[myid]]+res$readR.seqLen[[myid]]-1
+ brpos5.start=c(brpos5.start,max(unlist(res$readR.chrPos)))
+ brpos5.end=c(brpos5.end,min(unlist(res$readR.chrPos)))
+ genebrpos5.start=c(genebrpos5.start,max(unlist(res$adj.readR.GenePos)))
+ genebrpos5.end=c(genebrpos5.end,min(unlist(res$adj.readR.GenePos)))
+ mySR5=0
+ for (myid in 1:length(res$adj.readR.GenePos)) mySR5=mySR5+sum(res$adj.readR.GenePos[[myid]]-(res$readR.Pos[[myid]]-res$readR.ReadPos[[myid]])-(res$readR.seqLen[[myid]]-1)+fragmentInfo$readlen-1>genebrpos5.start[length(genebrpos5.start)]+shrinkLen)
+ splitRNum5=c(splitRNum5,mySR5)
+ } else{
+ for (myid in 1:length(res$adj.readR.GenePos)) res$adj.readR.GenePos[[myid]]=res$adj.readR.GenePos[[myid]]-res$readR.seqLen[[myid]]+1
+ brpos5.start=c(brpos5.start,min(unlist(res$readR.chrPos)))
+ brpos5.end=c(brpos5.end,max(unlist(res$readR.chrPos)))
+ genebrpos5.start=c(genebrpos5.start,min(unlist(res$adj.readR.GenePos)))
+ genebrpos5.end=c(genebrpos5.end,max(unlist(res$adj.readR.GenePos)))
+ mySR5=0
+ for (myid in 1:length(res$adj.readR.GenePos)) mySR5=mySR5+sum(res$adj.readR.GenePos[[myid]]+(res$readR.Pos[[myid]]-res$readR.ReadPos[[myid]])+(res$readR.seqLen[[myid]]-1)-fragmentInfo$readlen+1genebrpos5.start[length(genebrpos5.start)]+shrinkLen)
+ splitRNum5=c(splitRNum5,mySR5)
+ }else{
+ for (myid in 1:length(res$adj.readL.GenePos)) res$adj.readL.GenePos[[myid]]=res$adj.readL.GenePos[[myid]]-res$readL.seqLen[[myid]]+1
+ brpos5.start=c(brpos5.start,min(unlist(res$readL.chrPos)))
+ brpos5.end=c(brpos5.end,max(unlist(res$readL.chrPos)))
+ genebrpos5.start=c(genebrpos5.start,min(unlist(res$adj.readL.GenePos)))
+ genebrpos5.end=c(genebrpos5.end,max(unlist(res$adj.readL.GenePos)))
+ mySR5=0
+ for (myid in 1:length(res$adj.readL.GenePos)) mySR5=mySR5+sum(res$adj.readL.GenePos[[myid]]+(res$readL.Pos[[myid]]-res$readL.ReadPos[[myid]])+(res$readL.seqLen[[myid]]-1)-fragmentInfo$readlen+1genebrpos3.start[length(genebrpos3.start)]+shrinkLen)
+ splitRNum3=c(splitRNum3,mySR3)
+ }
+ }
+
+ #extract fragment distributions
+ if (readDirectTag[1]==3){
+ tx3.gap=abs(unlist(res$adj.readL.GenePos)-genebrpos3.start[length(genebrpos3.start)])+1
+ tx5.gap=abs(unlist(res$adj.readR.GenePos)-genebrpos5.start[length(genebrpos5.start)])+1
+ tx3.len=tx3.gap+unlist(res$readL.seqLen)
+ tx5.len=tx5.gap+unlist(res$readR.seqLen)
+ #fragLen=tx3.len+tx5.len+unlist(res$readL.seqLen)+unlist(res$readR.seqLen)
+ }else{
+ tx5.gap=abs(unlist(res$adj.readL.GenePos)-genebrpos5.start[length(genebrpos5.start)])+1
+ tx3.gap=abs(unlist(res$adj.readR.GenePos)-genebrpos3.start[length(genebrpos3.start)])+1
+
+ tx5.len=tx5.gap+unlist(res$readL.seqLen)
+ tx3.len=tx3.gap+unlist(res$readR.seqLen)
+ #fragLen=tx3.len+tx5.len+unlist(res$readR.seqLen)+unlist(res$readL.seqLen)
+ }
+ #get fragment length
+ #plot(tx3.len,tx5.len)
+
+ res$tx3.gap=tx3.gap
+ res$tx5.gap=tx5.gap
+ res$tx3.len=tx3.len
+ res$tx5.len=tx5.len
+
+ res$estFragLen=tx3.len+tx5.len
+
+ tx5GapMean=c(tx5GapMean,mean(tx5.gap))
+ tx5GapSd=c(tx5GapSd,sd(tx5.gap))
+ tx3GapMean=c(tx3GapMean,mean(tx3.gap))
+ tx3GapSd=c(tx3GapSd,sd(tx3.gap))
+
+ tx5LenMean=c(tx5LenMean,mean(tx5.len))
+ tx5LenSd=c(tx5LenSd,sd(tx5.len))
+ tx3LenMean=c(tx3LenMean,mean(tx3.len))
+ tx3LenSd=c(tx3LenSd,sd(tx3.len))
+
+ fragmentMean=c(fragmentMean,mean(res$estFragLen))
+ fragmentSd=c(fragmentSd,sd(res$estFragLen))
+ fragmentNum=c(fragmentNum,length(res$estFragLen))
+ # do a statistic test
+ myttest=pnorm(fragmentMean[length(fragmentMean)],mean=fragmentInfo$fragLengthMean,sd=fragmentInfo$fragLengthSd, lower.tail = TRUE)
+ fragmentTest=c(fragmentTest,myttest)
+
+ junctInfo[[myFusionFinal$fusionName[i]]]=res;
+ }
+
+
+ ###### now we work on gene5 and gene3 only
+ myFusionFinal$nondupCount=nondupCount
+ myFusionFinal$exNum1=exNum1
+ myFusionFinal$exNum2=exNum2
+ myFusionFinal$fragmentMean=fragmentMean
+ myFusionFinal$fragmentSd=fragmentSd
+ myFusionFinal$fragmentNum=fragmentNum
+ myFusionFinal$fragmentTest=fragmentTest
+ myFusionFinal$tx5GapMean=tx5GapMean
+ myFusionFinal$tx5GapSd=tx5GapSd
+ myFusionFinal$tx3GapMean=tx3GapMean
+ myFusionFinal$tx3GapSd=tx3GapSd
+
+ myFusionFinal$tx5LenMean=tx5LenMean
+ myFusionFinal$tx5LenSd=tx5LenSd
+ myFusionFinal$tx3LenMean=tx3LenMean
+ myFusionFinal$tx3LenSd=tx3LenSd
+
+
+ myFusionFinal$flen5=flen5
+ myFusionFinal$flen3=flen3
+ myFusionFinal$splitRNum5=splitRNum5
+ myFusionFinal$splitRNum3=splitRNum3
+
+
+ myFusionFinal$brpos5.start=brpos5.start
+ myFusionFinal$brpos3.start=brpos3.start
+ myFusionFinal$brpos5.end=brpos5.end
+ myFusionFinal$brpos3.end=brpos3.end
+
+ myFusionFinal$genebrpos5.start=genebrpos5.start
+ myFusionFinal$genebrpos5.end=genebrpos5.end
+ myFusionFinal$genebrpos3.start=genebrpos3.start
+ myFusionFinal$genebrpos3.end=genebrpos3.end
+
+ myFusionFinal$genebrpos5.rg=abs(myFusionFinal$genebrpos5.start-myFusionFinal$genebrpos5.end)+1
+ myFusionFinal$genebrpos3.rg=abs(myFusionFinal$genebrpos3.start-myFusionFinal$genebrpos3.end)+1
+
+ junctDist.mat=cbind(abs(myFusionFinal$brpos5.start-myFusionFinal$brpos3.start),
+ abs(myFusionFinal$brpos5.start-myFusionFinal$brpos3.end),
+ abs(myFusionFinal$brpos5.end-myFusionFinal$brpos3.start),
+ abs(myFusionFinal$brpos5.end-myFusionFinal$brpos3.end))
+ junctDist=unlist(apply(junctDist.mat,1,min))
+ myFusionFinal$junctDist=junctDist
+
+
+ cat("\n Get reads supporting constituent genes")
+ txeq=read.csv(paste(inPath,"/rawCount.txt",sep=""), header =TRUE, sep="\t")
+ txeq$geneID=geneAnno[match(as.character(txeq$Transcript),geneAnno[,1]),6]
+ geeq=txeq[,c(3,7,8)]
+ geeq=geeq[!duplicated(geeq),]
+ geCount=tapply(geeq$Count,geeq$geneID,sum)
+ myFusionFinal$gene1Count=geCount[match(as.character(myFusionFinal$gene1),names(geCount))]
+ myFusionFinal$gene2Count=geCount[match(as.character(myFusionFinal$gene2),names(geCount))]
+ myFusionFinal$gene1Count[is.na(myFusionFinal$gene1Count)]=0
+ myFusionFinal$gene2Count[is.na(myFusionFinal$gene2Count)]=0
+
+ #number of feq supporting a fge
+ feqNum=sapply(as.character(myFusionFinal$name12),function(mykey) length(feqFgeMap[[mykey]]))
+ myFusionFinal$feqNum=feqNum
+
+ return(list(myFusionFinal=myFusionFinal,junctInfo=junctInfo,fsizeLadder=fsizeLadder))
+ }
+
+
\ No newline at end of file
diff --git a/R/doBiologicalFilter.R b/R/doBiologicalFilter.R
new file mode 100644
index 0000000..759498f
--- /dev/null
+++ b/R/doBiologicalFilter.R
@@ -0,0 +1,59 @@
+############################################################
+#####extract biological features of fusion gene candidates in mapped read pipeline and do some filters
+#####input: geneParalog, hgncName, ribSubunitDb, mitoTransDb, ribonuproDb ... from global enviroment loaded from txAnnofile beforeward
+doBiologicalFilter<-function(fgeList, chromRef=paste("",c(1:22,"X","Y"),sep=""),onlyProteinCodingGenes=TRUE, doFilter=TRUE){
+ myFusionFinal=fgeList
+
+ if (onlyProteinCodingGenes){
+ cat("\n Keep only protein-coding genes")
+ keepID=which(myFusionFinal$geneType1=="protein_coding" & myFusionFinal$geneType2=="protein_coding")
+ myFusionFinal=myFusionFinal[keepID,]
+ }
+
+ rmID=unlist(lapply(c(1:nrow(myFusionFinal)), function(x){
+ par1=c(as.character(myFusionFinal$gene1[x]),geneParalog[which(geneParalog[,1]==as.character(myFusionFinal$gene1[x])),2])
+ par2=c(as.character(myFusionFinal$gene2[x]),geneParalog[which(geneParalog[,1]==as.character(myFusionFinal$gene2[x])),2])
+ if (length(par1)>0 & length(par2)>0) return(length(intersect(par1,par2))>0)
+ return(FALSE)
+ }))
+ myFusionFinal$paralog=rep(0,nrow(myFusionFinal))
+ myFusionFinal$paralog[rmID]=1
+
+ if (doFilter){
+ cat("\n Eliminate the fusion between genes and their paralogs")
+ myFusionFinal=myFusionFinal[myFusionFinal$paralog==0,]
+ }
+
+ gene5=as.character(myFusionFinal$gene1)
+ res <- hgncName[match(gene5,as.character(hgncName$ensembl_gene_id)) ,]
+ res=res[res$chromosome_name%in%chromRef,]
+ matchID=match(gene5,res$ensembl_gene_id)
+ myFusionFinal$gene1_ucsc=res$hgnc_symbol[matchID]
+ gene3=as.character(myFusionFinal$gene2)
+ res <- hgncName[match(gene3,as.character(hgncName$ensembl_gene_id)) ,]
+ res=res[res$chromosome_name%in%chromRef,]
+ matchID=match(gene3,res$ensembl_gene_id)
+ myFusionFinal$gene2_ucsc=res$hgnc_symbol[matchID]
+
+ #filter a fusion made by a gene and its read-through genes
+ keepID=unlist(lapply(c(1:nrow(myFusionFinal)), function(x){
+ res=c(unlist(strsplit(myFusionFinal$gene1_ucsc[x],"-")),unlist(strsplit(myFusionFinal$gene2_ucsc[x],"-")))
+ return((length(res) <= 2))
+ }))
+
+ readThrough=rep(1,nrow(myFusionFinal))
+ if (length(keepID)>0) readThrough[keepID]=0
+ myFusionFinal$readThrough=readThrough
+ if (doFilter){
+ cat("\n Eliminate the fusion between single gene and read-through gene")
+ myFusionFinal=myFusionFinal[myFusionFinal$readThrough==0,]
+
+ }
+
+ #compute again multiple duplicated genes
+ res=computeDupGene(myFusionFinal,dupGene.thres=-1)
+ colnames(res)=c("dupGene1_f1","dupGene2_f1")
+ myFusionFinal=cbind(myFusionFinal,res)
+
+ return(myFusionFinal)
+}
\ No newline at end of file
diff --git a/R/installBioconductor.R b/R/installBioconductor.R
new file mode 100644
index 0000000..e577386
--- /dev/null
+++ b/R/installBioconductor.R
@@ -0,0 +1,27 @@
+#####
+#Install some core packages of bioconductor for my docker
+#These codes are not mine (Nghia), I got them from https://github.com/Bioconductor/bioc_docker/tree/master/src/core
+#Note: must install libcurl4-openssl-dev libxml2-dev in ubuntu (if using) before insall GenomicFeatures because two dependencies R packages curl and xml require them
+############################################################
+source("http://bioconductor.org/biocLite.R")# This link works - Nghia
+biocLite()
+pkgs <- c(
+
+ "GenomicFeatures"
+)
+
+ap.db <- available.packages(contrib.url(biocinstallRepos()))
+ap <- rownames(ap.db)
+
+pkgs_to_install <- pkgs[pkgs %in% ap]
+
+biocLite(pkgs_to_install)
+
+warnings()
+
+if (!is.null(warnings()))
+{
+ w <- capture.output(warnings())
+ if (length(grep("is not available|had non-zero exit status", w)))
+ quit("no", 1L)
+}
\ No newline at end of file
diff --git a/R/integrateFusion.R b/R/integrateFusion.R
new file mode 100644
index 0000000..79f3026
--- /dev/null
+++ b/R/integrateFusion.R
@@ -0,0 +1,127 @@
+############################################################
+##### Combine two fusion gene candidate lists
+integrateFusion <-function(myFusionFinal.MR, myFusionFinal.SR, FuSeq.params, fragmentInfo=NULL, paralog.fc.thres=NULL){
+
+ minScore=FuSeq.params$minScore
+ #####last filter for MR
+ #filter by score
+ myFusionFinal.MR=myFusionFinal.MR[myFusionFinal.MR$score>=minScore,]
+ #junctiondistance
+ rmID=which(as.character(myFusionFinal.MR$chrom1)==as.character(myFusionFinal.MR$chrom2) & myFusionFinal.MR$junctDist<=FuSeq.params$minJunctionDist)
+ if (length(rmID)>0) myFusionFinal.MR=myFusionFinal.MR[-rmID,]
+ #genedistance
+ rmID=which(as.character(myFusionFinal.MR$chrom1)==as.character(myFusionFinal.MR$chrom2) & myFusionFinal.MR$geneDist<=FuSeq.params$minGeneDist)
+ if (length(rmID)>0) myFusionFinal.MR=myFusionFinal.MR[-rmID,]
+
+
+ ##### last filter for SR
+ #junctionDistance
+ rmID=which(as.character(myFusionFinal.SR$chrom1)==as.character(myFusionFinal.SR$chrom2) & myFusionFinal.SR$junctDist<=FuSeq.params$minJunctionDist)
+ if (length(rmID)>0) myFusionFinal.SR=myFusionFinal.SR[-rmID,]
+ # #geneDistance
+ rmID=which(as.character(myFusionFinal.SR$chrom1)==as.character(myFusionFinal.SR$chrom2) & myFusionFinal.SR$geneDist<=FuSeq.params$minGeneDist)
+ if (length(rmID)>0) myFusionFinal.SR=myFusionFinal.SR[-rmID,]
+
+ #filter by score
+ myFusionFinal.SR=myFusionFinal.SR[myFusionFinal.SR$totalCount>=minScore,]
+ #keep only one presentative for each fusion gene
+ myFusionFinal.SR=myFusionFinal.SR[!duplicated(myFusionFinal.SR$name12),]
+
+ #dup check here
+ myDup=duplicated(myFusionFinal.SR$name12)
+ myFusionNoDup=myFusionFinal.SR[!myDup,]
+ dupge1=table(myFusionNoDup$gene1)
+ dupge2=table(myFusionNoDup$gene2)
+ myFusionFinal.SR=cbind(myFusionFinal.SR,as.integer(dupge1[match(as.character(myFusionFinal.SR$gene1),names(dupge1))]))
+ myFusionFinal.SR=cbind(myFusionFinal.SR,as.integer(dupge2[match(as.character(myFusionFinal.SR$gene2),names(dupge2))]))
+ colnames(myFusionFinal.SR)[c(ncol(myFusionFinal.SR)-1,ncol(myFusionFinal.SR))]=c("dupge1f2","dupge2f2")
+ rmID=which(myFusionFinal.SR$dupge1f2>1 & myFusionFinal.SR$dupge2f2>1)
+ if (length(rmID)>0) myFusionFinal.SR=myFusionFinal.SR[-rmID,]
+
+
+ #deal with paralogs
+ if (!is.null(paralog.fc.thres)){
+ rmFusionName=NULL
+ res5=table(myFusionFinal.SR$note5)
+ res5=res5[-which(names(res5)=="")]
+ if (length(res5)>0){
+ for (i in 1:length(res5)){
+ mySR=myFusionFinal.SR[myFusionFinal.SR$note5==names(res5)[i],]
+ mySR=mySR[order(mySR$totalCount,decreasing = TRUE),]
+ rmID=which(mySR$totalCount*paralog.fc.thres0){
+ rmFusionName=c(rmFusionName,mySR$fusionName[rmID])
+ }
+ }
+ }
+ res3=table(myFusionFinal.SR$note3)
+ res3=res3[-which(names(res3)=="")]
+ if (length(res3)>0){
+ for (i in 1:length(res3)){
+ mySR=myFusionFinal.SR[myFusionFinal.SR$note3==names(res3)[i],]
+ mySR=mySR[order(mySR$totalCount,decreasing = TRUE),]
+ rmID=which(mySR$totalCount*paralog.fc.thres0){
+ rmFusionName=c(rmFusionName,mySR$fusionName[rmID])
+ }
+ }
+ }
+
+ if (length(rmFusionName)>0){
+ rmFusionName=unique(rmFusionName)
+ rmID=match(rmFusionName,myFusionFinal.SR$fusionName)
+ myFusionFinal.SR=myFusionFinal.SR[-rmID,]
+ }
+ }
+ #if the fusion shares breaking points in both sides
+ rmID=which(myFusionFinal.SR$note3!="" & myFusionFinal.SR$note5!="")
+ if (length(rmID)>0) myFusionFinal.SR=myFusionFinal.SR[-rmID,]
+
+
+
+ #create common features
+ myFusionFinal.SR$chrom5p=myFusionFinal.SR$chrom1
+ myFusionFinal.SR$brpos5.start=myFusionFinal.SR$brchposEx5
+ myFusionFinal.SR$brpos5.end=myFusionFinal.SR$brchposEx5+1
+ myFusionFinal.SR$strand5p=myFusionFinal.SR$strand1
+ myFusionFinal.SR$chrom3p=myFusionFinal.SR$chrom2
+ myFusionFinal.SR$brpos3.start=myFusionFinal.SR$brchposEx3
+ myFusionFinal.SR$brpos3.end=myFusionFinal.SR$brchposEx3+1
+ myFusionFinal.SR$strand3p=myFusionFinal.SR$strand2
+
+ ##### merging two fusion lists to be one
+ myFusionFinal=myFusionFinal.SR[,c("chrom5p","brpos5.start","brpos5.end","chrom3p","brpos3.start","brpos3.end","fusionName","score","strand5p","strand3p","supportRead")]
+ myFusionFinal=rbind(myFusionFinal,myFusionFinal.MR[,c("chrom5p","brpos5.start","brpos5.end","chrom3p","brpos3.start","brpos3.end","fusionName","score","strand5p","strand3p","supportRead")])
+
+ myFusionFinal=myFusionFinal[!duplicated(myFusionFinal$fusionName),]
+ dim(myFusionFinal)
+ myFusionFinal$name12=myFusionFinal$fusionName
+ myFusionFinal$name21=sapply(as.character(myFusionFinal$fusionName),function(x) paste(rev(unlist(strsplit(x,"-"))),collapse ="-"))
+
+ myFusionFinal$gene5=sapply(as.character(myFusionFinal$fusionName),function(x) unlist(strsplit(x,"-"))[1])
+ myFusionFinal$gene3=sapply(as.character(myFusionFinal$fusionName),function(x) unlist(strsplit(x,"-"))[2])
+
+
+ #if they are from cytosolic ribosomal subunit
+ myFusionFinal$ribSub5=match(as.character(myFusionFinal$gene5),as.character(ribSubunitDb$ensembl_gene_id))
+ myFusionFinal$ribSub3=match(as.character(myFusionFinal$gene3),as.character(ribSubunitDb$ensembl_gene_id))
+ #if they are from mitochondrial transclation
+ myFusionFinal$mitoTrans5=match(as.character(myFusionFinal$gene5),as.character(mitoTransDb$ensembl_gene_id))
+ myFusionFinal$mitoTrans3=match(as.character(myFusionFinal$gene3),as.character(mitoTransDb$ensembl_gene_id))
+ #if they are from ribonucleoprotein complex
+ myFusionFinal$ribonupro5=match(as.character(myFusionFinal$gene5),as.character(ribonuproDb$ensembl_gene_id))
+ myFusionFinal$ribonupro3=match(as.character(myFusionFinal$gene3),as.character(ribonuproDb$ensembl_gene_id))
+
+ #order by score
+ myFusionFinal=myFusionFinal[order(myFusionFinal$score,decreasing = TRUE),]
+
+
+ myFusionFinal$MR=myFusionFinal$SR=0
+ myFusionFinal$SR[which(!is.na(match(as.character(myFusionFinal$fusionName),as.character(myFusionFinal.SR$fusionName))))]=1
+ myFusionFinal$MR[which(!is.na(match(as.character(myFusionFinal$fusionName),as.character(myFusionFinal.MR$fusionName))))]=1
+
+ return(list(myFusionFinal=myFusionFinal,myFusionFinal.SR=myFusionFinal.SR,myFusionFinal.MR=myFusionFinal.MR))
+}
+
+
+
diff --git a/R/params.txt b/R/params.txt
new file mode 100644
index 0000000..aff05f9
--- /dev/null
+++ b/R/params.txt
@@ -0,0 +1,17 @@
+#parameter setting
+readStrands="UN"
+chromRef=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y
+onlyProteinCodingGenes=TRUE
+maxSharedCount=5e-2
+minGeneDist=1e5
+minJunctionDist=1e5
+maxInvertedFusionCount=0.01
+minMR=2
+minNonDupMR=2
+maxMRfusionFc=2
+maxMRfusionNum=2
+sgtMRcount=10
+minSR=1
+minScore=3
+keepRData=FALSE
+exportFasta=FALSE
\ No newline at end of file
diff --git a/R/postProcessMappedRead.R b/R/postProcessMappedRead.R
new file mode 100644
index 0000000..aaa2fd3
--- /dev/null
+++ b/R/postProcessMappedRead.R
@@ -0,0 +1,111 @@
+############################################################
+#####post process mapped reads
+############################################################
+
+postProcessMappedRead <-function(inPath, anntxdb, FuSeq.SR, FuSeq.MR, FuSeq.params){
+ cat("\n Post processing mapped reads (MR)...")
+
+ myFusionFinal=FuSeq.MR$myFusionFinal
+ fragmentInfo=FuSeq.SR$fragmentInfo
+ fragDist=FuSeq.SR$fragDist
+
+ ##### revisit the information of junction breaks
+ junctBr=refineJunctionBreak(FuSeq.MR$junctBr, anntxdb, fragmentInfo, FuSeq.params$readStrands, fragDist=fragDist)
+ # update to myFusionFinal
+
+ myFusionFinal$adjFragmentNum=myFusionFinal$outlierNum=NA
+ myFusionFinal$ftxLenProp=myFusionFinal$ftxMedianLen=myFusionFinal$ftxMeanLen=NA
+ myFusionFinal$ftx5LenSd=myFusionFinal$ftx5LenMean=myFusionFinal$ftx3LenSd=myFusionFinal$ftx3LenMean=NA
+
+ matchID=match(as.character(myFusionFinal$fusionName),as.character(junctBr$myFusionFinal$fusionName))
+
+ myFusionFinal$adjFragmentNum=junctBr$myFusionFinal$adjFragmentNum[matchID]
+ myFusionFinal$outlierNum= junctBr$myFusionFinal$outlierNum[matchID]
+ myFusionFinal$ftxLenProp=junctBr$myFusionFinal$ftxLenProp[matchID]
+ myFusionFinal$ftxMedianLen=junctBr$myFusionFinal$ftxMedianLen[matchID]
+ myFusionFinal$ftxMeanLen=junctBr$myFusionFinal$ftxMeanLen[matchID]
+ myFusionFinal$ftx5LenMean=junctBr$myFusionFinal$ftx5LenMean[matchID]
+ myFusionFinal$ftx5LenSd=junctBr$myFusionFinal$ftx5LenSd[matchID]
+ myFusionFinal$ftx3LenMean=junctBr$myFusionFinal$ftx3LenMean[matchID]
+ myFusionFinal$ftx3LenSd=junctBr$myFusionFinal$ftx3LenSd[matchID]
+
+ keepID=which(!is.na(junctBr$myFusionFinal$crt.tx5LenMean[matchID]))
+ if (length(keepID)>0){
+ myFusionFinal$tx5LenMean[keepID]=junctBr$myFusionFinal$crt.tx5LenMean[matchID][keepID]
+ myFusionFinal$tx5LenSd[keepID]=junctBr$myFusionFinal$crt.tx5LenSd[matchID][keepID]
+ myFusionFinal$tx3LenMean[keepID]=junctBr$myFusionFinal$crt.tx3LenMean[matchID][keepID]
+ myFusionFinal$tx3LenSd[keepID]=junctBr$myFusionFinal$crt.tx3LenSd[matchID][keepID]
+ }
+
+ ##### quick filter here
+ keepID=which(myFusionFinal$ftx5LenMean > 0)
+ myFusionFinal=myFusionFinal[keepID,]
+ keepID=which(myFusionFinal$ftx3LenMean > 0)
+ myFusionFinal=myFusionFinal[keepID,]
+
+ keepID=which(myFusionFinal$ftxMeanLen < 1000 & myFusionFinal$ftxMeanLen > fragmentInfo$readlen )
+ myFusionFinal=myFusionFinal[keepID,]
+ #get empirical probabilities
+ myFusionFinal$ftxLenEmpProp=sapply(myFusionFinal$ftxMedianLen,function(x) sum(fragDist[fragDist[,1]>x,2])/sum(fragDist[,2]))
+ #filter by 1e-04
+ myFusionFinal=myFusionFinal[myFusionFinal$ftxLenEmpProp>1e-04,]
+
+
+ ########################## filtering
+ #Remove false positives
+ matchID=match(myFusionFinal$fusionName,FuSeq.SR$myFusionFP$name12)
+ myFusionFinal=myFusionFinal[which(is.na(matchID)),]
+ #txlen test
+ rmID=c(which(myFusionFinal$tx5LenSd<=1 & myFusionFinal$fragmentNum>=3),which(myFusionFinal$tx3LenSd<=1 & myFusionFinal$fragmentNum>=3))
+ rmFusion=unique(c(myFusionFinal$fusionName[rmID]))
+ if (length(rmFusion)>0){
+ myFusionFinal=myFusionFinal[which(is.na(match(myFusionFinal$fusionName,rmFusion))),]
+ }
+
+
+ tx3LenTest=tx5LenTest=NULL;
+ for (i in 1:nrow(myFusionFinal)){
+ res=testFtxlen(mu=fragmentInfo$fragLengthMean, sig=fragmentInfo$fragLengthSd, r=fragmentInfo$readlen,ftxlen=myFusionFinal$flen5[i], kmerlen=fragmentInfo$kmer,fragDist=fragDist,M=10000)
+ tx5LenTest=c(tx5LenTest,sum(res$x<=myFusionFinal$tx5LenMean[i])/length(res$x))
+ res=testFtxlen(mu=fragmentInfo$fragLengthMean, sig=fragmentInfo$fragLengthSd, r=fragmentInfo$readlen,ftxlen=myFusionFinal$flen3[i], kmerlen=fragmentInfo$kmer,fragDist=fragDist,M=10000)
+ tx3LenTest=c(tx3LenTest,sum(res$x<=myFusionFinal$tx3LenMean[i])/length(res$x))
+ }
+ myFusionFinal$tx5LenTest=tx5LenTest
+ myFusionFinal$tx3LenTest=tx3LenTest
+ myFusionFinal=myFusionFinal[myFusionFinal$tx5LenTest >= 0.10,]
+ myFusionFinal=myFusionFinal[myFusionFinal$tx3LenTest >= 0.10,]
+
+ # ##### create a score
+ myFusionFinal$score=myFusionFinal$correctedCount
+
+ #get split reads
+ myFusionFinal$SR_supportCount=0
+ matchID=match(myFusionFinal$fusionName,FuSeq.SR$fusionGene$name12)
+ myFusionFinal$SR_supportCount[which(!is.na(matchID))]=FuSeq.SR$fusionGene$supportCount[na.omit(matchID)]
+
+ myFusionFinal$SR_correctedCount=0
+ matchID=match(myFusionFinal$fusionName,FuSeq.SR$fusionGene$name12)
+ myFusionFinal$SR_correctedCount[which(!is.na(matchID))]=FuSeq.SR$fusionGene$adjtx12Count[na.omit(matchID)]
+ myFusionFinal$score=myFusionFinal$score+myFusionFinal$SR_correctedCount
+
+
+ myFusionFinal$srEst3=myFusionFinal$supportCount/myFusionFinal$flen3 * (fragmentInfo$readlen-2*fragmentInfo$kmer)
+ myFusionFinal$srEst5=myFusionFinal$supportCount/myFusionFinal$flen5 * (fragmentInfo$readlen-2*fragmentInfo$kmer)
+ #smRatio indicates the ratio between mapped reads and split reads, we expect 1 split reads randomly happen from 1000 mapped reads
+ smRatio=0.001
+ rmID=unique(c(which(myFusionFinal$SR_supportCount > smRatio*myFusionFinal$supportCount & myFusionFinal$SR_supportCountsmRatio*myFusionFinal$supportCount & myFusionFinal$SR_supportCount0) myFusionFinal=myFusionFinal[-rmID,]
+
+ #check ending exon in MR
+ rmID.MR=checkEndExon(myFusionFinal=myFusionFinal, junctBr=junctBr, anntxdb=anntxdb, readStrands=FuSeq.params$readStrands,shrinkLen=5, type="MR")
+ #cat("\n Number of ending exon in MR: ",length(rmID.MR))
+ if (length(rmID.MR)>0) myFusionFinal=myFusionFinal[-rmID.MR,]
+
+ myFusionFinal$supportRead=myFusionFinal$supportCount+myFusionFinal$SR_supportCount
+
+ res=list(myFusionFinal=myFusionFinal, junctBr.refine=junctBr)
+ return(res)
+}
+
+
+
diff --git a/R/postProcessSplitRead.R b/R/postProcessSplitRead.R
new file mode 100644
index 0000000..d4db565
--- /dev/null
+++ b/R/postProcessSplitRead.R
@@ -0,0 +1,631 @@
+############################################################
+#####post process split reads
+############################################################
+
+postProcessSplitRead <-function(inPath, anntxdb, FuSeq.SR, FuSeq.MR, txFastaFile, FuSeq.params, shrinkLen=5){
+cat("\n Post processing split reads (SR)...")
+##### post processing with information from split reads
+myFusionTmp=FuSeq.SR$myFusionFinal
+fragmentInfo=FuSeq.SR$fragmentInfo
+fragDist=FuSeq.SR$fragDist
+
+
+mappedFge=FuSeq.MR$feqInfo$fgeList
+readStrands=FuSeq.params$readStrands
+if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){
+ mappedFge$gene5p=mappedFge$gene2
+ mappedFge$gene3p=mappedFge$gene1
+ mappedFge$chrom5p=mappedFge$chrom2
+ mappedFge$chrom3p=mappedFge$chrom1
+ mappedFge$strand5p=mappedFge$strand2
+ mappedFge$strand3p=mappedFge$strand1
+
+}else{
+ mappedFge$gene5p=mappedFge$gene1
+ mappedFge$gene3p=mappedFge$gene2
+ mappedFge$chrom5p=mappedFge$chrom1
+ mappedFge$chrom3p=mappedFge$chrom2
+ mappedFge$strand5p=mappedFge$strand1
+ mappedFge$strand3p=mappedFge$strand2
+}
+mappedFge$fusionName=paste(mappedFge$gene5p,mappedFge$gene3p,sep="-")
+
+
+myFusionTmp2=myFusionTmp
+#If we limit only splicing sites at exon boundary
+myFusionTmp2=myFusionTmp2[myFusionTmp2$ssEnd<=2,]
+myFusionTmp2=myFusionTmp2[myFusionTmp2$ssStart<=2,]
+matchID=match(as.character(myFusionTmp2$name12),as.character(mappedFge$fusionName))
+
+myFusionTmp2$total21=myFusionTmp2$tx21Count
+myFusionTmp2$total21[which(!is.na(matchID))]=myFusionTmp2$total21[which(!is.na(matchID))]+mappedFge$name21Count[na.omit(matchID)]
+myFusionTmp2$totalCount=myFusionTmp2$adjtx12Count
+myFusionTmp2$totalCount[which(!is.na(matchID))]=myFusionTmp2$totalCount[which(!is.na(matchID))]+mappedFge$correctedCount[na.omit(matchID)]
+myFusionTmp2$mappedCrtCount=myFusionTmp2$totalCount-myFusionTmp2$adjtx12Count
+myFusionTmp2$mappedCount=myFusionTmp2$mappedCrtCount
+myFusionTmp2$mappedCount=0
+myFusionTmp2$mappedCount[which(!is.na(matchID))]=mappedFge$supportCount[na.omit(matchID)]
+
+#filter again by inverted direction fusion genes
+myFusionTmp2=myFusionTmp2[myFusionTmp2$total21 <= myFusionTmp2$totalCount*0.01,]
+
+
+##### process cases: geneA-geneB vs geneA-geneC where geneB and geneC are paralogs or overlapping
+myFusion=myFusionTmp2
+#do some filters here
+# totalCount here is the sum of adjusted counts from mapped reads and split reads
+myFusion=myFusion[myFusion$totalCount>=1,]
+
+myFusion$note3=myFusion$note5=""
+myDup=duplicated(myFusion$name12)
+myFusionNoDup=myFusion[!myDup,]
+dupge1=table(myFusionNoDup$gene1)
+dupge2=table(myFusionNoDup$gene2)
+myFusion=cbind(myFusion,as.integer(dupge1[match(as.character(myFusion$gene1),names(dupge1))]))
+myFusion=cbind(myFusion,as.integer(dupge2[match(as.character(myFusion$gene2),names(dupge2))]))
+colnames(myFusion)[c(ncol(myFusion)-1,ncol(myFusion))]=c("dupge1f","dupge2f")
+
+exonInfo=select(anntxdb, keys=unique(c(as.character(myFusion$gene1),as.character(myFusion$gene2))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+
+
+frontDupge=unique(as.character(myFusion$gene1[which(myFusion$dupge1f>1)]))
+rmFusion=NULL;
+if (length(frontDupge)>0)
+ for (myge in frontDupge){
+ dupFusion=myFusion[which(as.character(myFusion$gene1)==myge),]
+ mygene2=unique(as.character(dupFusion$gene2))
+ #check if two adjacent genes are overlapped
+ myEx=exonInfo[which(!is.na(match(exonInfo$GENEID,mygene2))),]
+ myEx=myEx[order(myEx$EXONSTART, decreasing = FALSE),] #keep genes in the order of exonstart
+ mygene2=unique(as.character(myEx$GENEID))
+ brStart=tapply(myEx$EXONSTART,myEx$GENEID,min)
+ brEnd=tapply(myEx$EXONEND,myEx$GENEID,max)
+
+ olid1=olid2=NULL
+ for (i in 1:(length(brStart)-1)){
+ for (j in (i+1):length(brStart)){
+ isParalog=FALSE
+ myStatusij=(brStart[i]-brStart[j])/1e8*(brEnd[i]-brStart[j])
+ myStatusji=(brStart[j]-brStart[i])/1e8*(brEnd[j]-brStart[i])
+ if (myStatusij < 0 | myStatusji <0) isParalog=TRUE
+ if (!isParalog){
+ par1=c(as.character(mygene2[i]),geneParalog[which(geneParalog[,1]==as.character(mygene2[i])),2])
+ par2=c(as.character(mygene2[j]),geneParalog[which(geneParalog[,1]==as.character(mygene2[j])),2])
+ if (length(intersect(par1,par2))>0) isParalog=TRUE
+ }
+ if (isParalog){
+ olid1=c(olid1,i)
+ olid2=c(olid2,j)
+ }
+ }
+ }
+ if (length(olid1)>0){
+ olGroup=seq(brStart)
+ olGroup[olid2]=olid1
+ olGroupU=rep(-1,length(olGroup))
+ while(sum(olGroup!=olGroupU)>0){
+ olGroupU=olGroup
+ olGroup=olGroup[olGroup]
+ }
+ olGroupID=unique(olGroup)
+ for (myol in olGroupID){#select only one
+ keepID=which(olGroup==myol)
+ if (length(keepID) >1){
+ olFusionName=paste(myge,mygene2[keepID],sep="-")
+ olFusion=dupFusion[match(olFusionName,dupFusion$name12),]
+ selectID=which.max(olFusion$totalCount)
+ #check if no fusion gene has higher total count
+ if (sum(olFusion$totalCount[selectID] > olFusion$totalCount[-selectID])==0){
+ #so we need another way to select the best candidate, we select the one closer geneDist
+ selectID=which.min(olFusion$geneDist)
+ }
+ #update to the removal list
+ keepID=which(!is.na(match(myFusion$name12,olFusionName)))
+ myFusion$note3[keepID]=paste(myFusion$note3[keepID],paste(olFusionName,collapse = ","),sep=";")
+ }
+ }
+ }
+ }
+
+backDupge=unique(as.character(myFusion$gene2[which(myFusion$dupge2f>1)]))
+rmFusion=NULL;
+if (length(backDupge)>0)
+ for (myge in backDupge){
+ dupFusion=myFusion[which(as.character(myFusion$gene2)==myge),]
+ mygene1=unique(as.character(dupFusion$gene1))
+ #check if two adjacent genes are overlapped
+ myEx=exonInfo[which(!is.na(match(exonInfo$GENEID,mygene1))),]
+ myEx=myEx[order(myEx$EXONSTART, decreasing = FALSE),] #keep genes in the order of exonstart
+ mygene1=unique(as.character(myEx$GENEID))
+ brStart=tapply(myEx$EXONSTART,myEx$GENEID,min)
+ brEnd=tapply(myEx$EXONEND,myEx$GENEID,max)
+
+ olid1=olid2=NULL
+ for (i in 1:(length(brStart)-1)){
+ for (j in (i+1):length(brStart)){
+ isParalog=FALSE
+ myStatusij=(brStart[i]-brStart[j])/1e8*(brEnd[i]-brStart[j])
+ myStatusji=(brStart[j]-brStart[i])/1e8*(brEnd[j]-brStart[i])
+ if (myStatusij < 0 | myStatusji <0) isParalog=TRUE
+ if (!isParalog){
+ par1=c(as.character(mygene1[i]),geneParalog[which(geneParalog[,1]==as.character(mygene1[i])),2])
+ par2=c(as.character(mygene1[j]),geneParalog[which(geneParalog[,1]==as.character(mygene1[j])),2])
+ if (length(intersect(par1,par2))>0) isParalog=TRUE
+ }
+ if (isParalog){
+ olid1=c(olid1,i)
+ olid2=c(olid2,j)
+ }
+ }
+ }
+ if (length(olid1)>0){
+ olGroup=seq(brStart)
+ olGroup[olid2]=olid1
+ olGroupU=rep(-1,length(olGroup))
+ while(sum(olGroup!=olGroupU)>0){
+ olGroupU=olGroup
+ olGroup=olGroup[olGroup]
+ }
+ olGroupID=unique(olGroup)
+ for (myol in olGroupID){#select only one
+ keepID=which(olGroup==myol)
+ if (length(keepID) >1){
+ olFusionName=paste(mygene1[keepID],myge,sep="-")
+ olFusion=dupFusion[match(olFusionName,dupFusion$name12),]
+ selectID=which.max(olFusion$totalCount)
+ #check if no fusion gene has higher total count
+ if (sum(olFusion$totalCount[selectID] > olFusion$totalCount[-selectID])==0){
+ #so we need another way to select the best candidate, we select the one closer geneDist
+ selectID=which.min(olFusion$geneDist)
+ }
+ #update to the removal list
+ keepID=which(!is.na(match(myFusion$name12,olFusionName)))
+ myFusion$note5[keepID]=paste(myFusion$note5[keepID],paste(olFusionName,collapse = ","),sep=";")
+ }
+
+ }
+ }
+ }
+
+
+##### checking read sequences
+
+fastaDat2=fastaDat1=list();
+fastaSplit2=fastaSplit1=list();
+frfiles=list.files(inPath,paste(readStrands,"_fusionMappedReadsChunk_*",sep=""))
+for (i in 1:length(frfiles)){
+ #read fasta files of mapped reads
+ ftag=rev(strsplit(strsplit(frfiles[i],"\\.")[[1]][1],"_")[[1]])[1]
+ # con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ # mydata=readLines(con)
+ # close(con)
+ # fastaDat1[[frfiles[i]]]=mydata
+ #
+ # con <- file(paste(inPath,"/",readStrands,"_fastaseq_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ # mydata=readLines(con)
+ # close(con)
+ # fastaDat2[[frfiles[i]]]=mydata
+
+ #read fasta files of split reads
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_1.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaSplit1[[frfiles[i]]]=mydata
+
+ con <- file(paste(inPath,"/","splitRead_",ftag,"_2.fa",sep=""), "r", blocking = FALSE)
+ mydata=readLines(con)
+ close(con)
+ fastaSplit2[[frfiles[i]]]=mydata
+
+}
+
+fastaSplit1=unlist(fastaSplit1)
+fastaSplit2=unlist(fastaSplit2)
+
+myheader=as.character(myFusion$header)
+rID.adj=match(myheader,fastaSplit1)
+mySplit5N=fastaSplit1[rID.adj+1]
+mySplit3N=fastaSplit2[rID.adj+1]
+#if RF, convert 5N
+if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR") mySplit5N=sapply(mySplit5N,convertReverseComplement) else mySplit3N=sapply(mySplit3N,convertReverseComplement)
+
+
+library(Biostrings)
+fasta = readDNAStringSet(txFastaFile)
+fasta_txnames=sapply(names(fasta), function(x) unlist(strsplit(x," "))[1])
+#shrinkLen=5
+
+tx5fa=rep("",length(mySplit5N))
+frontTxList=as.character(myFusion$front_tx)
+frontTxSet=unique(frontTxList)
+cat("\n Total transcripts at 5 prime",length(frontTxSet))
+for (i in 1:length(frontTxSet)){
+ keepID=which(frontTxList==frontTxSet[i])
+ txname=frontTxSet[i]
+ matchID=match(txname,fasta_txnames)
+ mytxFasta=fasta[matchID]
+ mybrpos=myFusion$front_hitpos[keepID] -myFusion$front_querypos[keepID] +1
+ tx5fa[keepID]=substring(mytxFasta,mybrpos,mybrpos+fragmentInfo$readlen-1)
+}
+
+
+tx3fa=rep("",length(mySplit3N))
+backTxList=as.character(myFusion$back_tx)
+backTxSet=unique(backTxList)
+cat("\n Total transcripts at 3 prime",length(backTxSet))
+for (i in 1:length(backTxSet)){
+ keepID=which(backTxList==backTxSet[i])
+ txname=backTxSet[i]
+ matchID=match(txname,fasta_txnames)
+ mytxFasta=fasta[matchID]
+ mybrpos=myFusion$back_hitpos[keepID] - myFusion$back_querypos[keepID]+1
+ tx3fa[keepID]=substring(mytxFasta,mybrpos,mybrpos+fragmentInfo$readlen-1)
+}
+
+#matchedNum.thres=fragmentInfo$readlen-fragmentInfo$kmer+1+10
+matchedNum.thres=fragmentInfo$readlen*0.85
+rmID=NULL
+matchedNum=apply(cbind(mySplit5N,tx5fa),1,function(x){
+ mync=min(nchar(x[1]),nchar(x[2]))
+ return(sum(unlist(strsplit(x[1],""))[1:mync]==unlist(strsplit(x[2],""))[1:mync]))
+})
+rmID=c(rmID,which(matchedNum>matchedNum.thres))
+myFusion$mn5N5=matchedNum
+
+matchedNum=apply(cbind(mySplit3N,tx5fa),1,function(x){
+ mync=min(nchar(x[1]),nchar(x[2]))
+ return(sum(unlist(strsplit(x[1],""))[1:mync]==unlist(strsplit(x[2],""))[1:mync]))
+})
+rmID=c(rmID,which(matchedNum>matchedNum.thres))
+myFusion$mn3N5=matchedNum
+
+matchedNum=apply(cbind(mySplit5N,tx3fa),1,function(x){
+ mync=min(nchar(x[1]),nchar(x[2]))
+ return(sum(unlist(strsplit(x[1],""))[(nchar(x[1])-mync+1):nchar(x[1])]==unlist(strsplit(x[2],""))[(nchar(x[2])-mync+1):nchar(x[2])]))
+})
+rmID=c(rmID,which(matchedNum>matchedNum.thres))
+myFusion$mn5N3=matchedNum
+
+matchedNum=apply(cbind(mySplit3N,tx3fa),1,function(x){
+ mync=min(nchar(x[1]),nchar(x[2]))
+ return(sum(unlist(strsplit(x[1],""))[(nchar(x[1])-mync+1):nchar(x[1])]==unlist(strsplit(x[2],""))[(nchar(x[2])-mync+1):nchar(x[2])]))
+})
+rmID=c(rmID,which(matchedNum>matchedNum.thres))
+myFusion$mn3N3=matchedNum
+
+rmID=unique(rmID)
+if (length(rmID)>0) myFusion=myFusion[-rmID,]
+
+
+#####check the direction of read pairs:
+#FR: correct direction is 1-0 and 2-1
+#RF or UN: correct direction is 2-0 and 1-1
+if (readStrands=="RF" || readStrands=="RR") rmID=c(which(myFusion$readType==1 & myFusion$direction==0),which(myFusion$readType==2 & myFusion$direction==1))
+
+if (readStrands=="FR" || readStrands=="FF") rmID=c(which(myFusion$readType==1 & myFusion$direction==1),which(myFusion$readType==2 & myFusion$direction==0))
+
+if (readStrands=="UN") rmID=NULL #can not apply
+
+#remove the fusion candidates if there are at least 5% incorrect direction read pairs
+if (length(rmID)>0){
+ res=table(myFusion$name12[rmID])
+ myFusion$fDirCount=0
+ myFusion$fDirCount[which(!is.na(match(as.character(myFusion$name12),names(res))))]=res[na.omit(match(as.character(myFusion$name12),names(res)))]
+ myFusion$fDirProp=myFusion$fDirCount/myFusion$supportCount
+ myFusion=myFusion[myFusion$fDirProp < 0.05,]
+}
+
+
+
+#### filter by shared break points when the partner genes are not paralogs
+myFusion2=myFusion
+res=table(myFusion2$name12)
+myFusion2$supportCount3=res[match(myFusion2$name12,names(res))]
+myFusion2=myFusion2[myFusion2$supportCount3 > 1,] #consider at least 2 supporting split reads
+myDup=duplicated(myFusion2$name12)
+myFusionNoDup=myFusion2[!myDup,]
+dupge1=table(myFusionNoDup$gene1)
+dupge2=table(myFusionNoDup$gene2)
+myFusion2=cbind(myFusion2,as.integer(dupge1[match(as.character(myFusion2$gene1),names(dupge1))]))
+myFusion2=cbind(myFusion2,as.integer(dupge2[match(as.character(myFusion2$gene2),names(dupge2))]))
+colnames(myFusion2)[c(ncol(myFusion2)-1,ncol(myFusion2))]=c("dupge1f2","dupge2f2")
+
+frontDupge=unique(as.character(myFusion2$gene1[which(myFusion2$dupge1f2>1)]))
+rmFusion=NULL;
+if (length(frontDupge)>0)
+ for (myge in frontDupge){
+ dupFusion=myFusion2[which(as.character(myFusion2$gene1)==myge),]
+ dupFusion=dupFusion[!duplicated(dupFusion$name12),]
+ #group by brchposEx5
+ brPos=dupFusion$brchposEx5
+ names(brPos)=seq(brPos)
+ brPos=sort(brPos, decreasing = FALSE)
+ myGroup=seq(brPos)
+ myDiff=diff(brPos)
+ myGroup[which(myDiff<=shrinkLen)+1]=which(myDiff<=shrinkLen)
+ myGroupU=rep(-1,length(myGroup))
+ while(sum(myGroup!=myGroupU)>0){
+ myGroupU=myGroup
+ myGroup=myGroup[myGroup]
+ }
+ myGroupID=unique(myGroup)
+ for (myGrp in myGroupID){
+ keepID=which(myGroup==myGrp)
+ if (length(keepID) >1){
+ grpFusion=dupFusion[as.integer(names(brPos[keepID])),]
+ if(sum(grpFusion$note3=="" & grpFusion$note5=="") >0) rmFusion=c(rmFusion,unique(grpFusion$name12))
+ }
+ }
+
+ }
+
+backDupge=unique(as.character(myFusion2$gene2[which(myFusion2$dupge2f2>1)]))
+if (length(backDupge)>0)
+ for (myge in backDupge){
+ dupFusion=myFusion2[which(as.character(myFusion2$gene2)==myge),]
+ dupFusion=dupFusion[!duplicated(dupFusion$name12),]
+ #group by brchposEx3
+ brPos=dupFusion$brchposEx3
+ names(brPos)=seq(brPos)
+ brPos=sort(brPos, decreasing = FALSE)
+ myGroup=seq(brPos)
+ myDiff=diff(brPos)
+ myGroup[which(myDiff<=shrinkLen)+1]=which(myDiff<=shrinkLen)
+ myGroupU=rep(-1,length(myGroup))
+ while(sum(myGroup!=myGroupU)>0){
+ myGroupU=myGroup
+ myGroup=myGroup[myGroup]
+ }
+ myGroupID=unique(myGroup)
+ for (myGrp in myGroupID){
+ keepID=which(myGroup==myGrp)
+ if (length(keepID) >1){
+ grpFusion=dupFusion[as.integer(names(brPos[keepID])),]
+ if(sum(grpFusion$note3=="" & grpFusion$note5=="") >0) rmFusion=c(rmFusion,unique(grpFusion$name12))
+ }
+ }
+ }
+
+
+
+
+if (length(rmFusion)){
+ rmID=which(!is.na(match(as.character(myFusion$name12),rmFusion)))
+ myFusion=myFusion[-rmID,]
+}
+
+
+# filter by junction distances
+rmID=which(as.character(myFusion$chrom1)==as.character(myFusion$chrom2) & myFusion$junctDist<=FuSeq.params$minJunctionDist)
+if (length(rmID)>0) myFusion=myFusion[-rmID,]
+
+res=table(myFusion$tx12)
+myFusion$tx12Count3=res[match(myFusion$tx12,names(res))]
+myFusion$mEstCount=myFusion$tx12Count3/(fragmentInfo$readlen-2*fragmentInfo$kmer-1) * (2*fragmentInfo$kmer+1)
+myFusion$mEstProp=myFusion$mappedCount/myFusion$mEstCount
+
+
+
+############
+
+#check the consistency between mapped reads and split reads
+#myFusionMapped=myFusionTmp2[myFusionTmp2$mappedCrtCount>=1,]
+myFusion$fusionName=myFusion$name12
+myFusionMapped=myFusion
+myDup=duplicated(myFusionMapped$name12)
+myFusionMapped=myFusionMapped[!myDup,]
+
+
+if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){
+ #switch name21 - name12 for running function detectJunctionBreaks()
+ myFusionMapped$name12_raw=myFusionMapped$name12
+ myFusionMapped$name21_raw=myFusionMapped$name21
+ myFusionMapped$name12=myFusionMapped$name21_raw
+ myFusionMapped$name21=myFusionMapped$name12_raw
+
+ myFusionMapped$gene1_raw=myFusionMapped$gene1
+ myFusionMapped$gene2_raw=myFusionMapped$gene2
+ myFusionMapped$gene1=myFusionMapped$gene2_raw
+ myFusionMapped$gene2=myFusionMapped$gene1_raw
+}
+
+matchID=match(as.character(myFusionMapped$name12), names(FuSeq.MR$feqInfo$feqFgeMap))
+myFusionMapped=myFusionMapped[which(!is.na(matchID)),]
+
+if (nrow(myFusionMapped) > 0){
+ junctBr=detectJunctionBreaks(myFusionMapped,inPath, FuSeq.MR$feqInfo$feq,FuSeq.MR$feqInfo$feqFgeMap, anntxdb, readStrands=FuSeq.params$readStrands)
+ myFusionMapped=junctBr$myFusionFinal
+
+ ok5Pos=ok3Pos=NULL
+ for (i in 1:nrow(myFusionMapped)){
+ res=junctBr$junctInfo[[myFusionMapped$fusionName[i]]]
+ ck5Pos=unlist(res$readL.chrPos)
+ if (myFusionMapped$strand1[i]=="+") ck5Pos= sum(ck5Pos+unlist(res$readL.seqLen)-1-shrinkLen<= myFusionMapped$brchposEx5[i])/length(ck5Pos) else ck5Pos= sum(ck5Pos-unlist(res$readL.seqLen)+1+shrinkLen >= myFusionMapped$brchposEx5[i])/length(ck5Pos)
+ ok5Pos=c(ok5Pos,ck5Pos)
+
+ ck3Pos=unlist(res$readR.chrPos)
+ if (myFusionMapped$strand2[i]=="+") ck3Pos= sum(ck3Pos+shrinkLen>= myFusionMapped$brchposEx3[i])/length(ck3Pos) else ck3Pos= sum(ck3Pos-shrinkLen<= myFusionMapped$brchposEx3[i])/length(ck3Pos)
+ ok3Pos=c(ok3Pos,ck3Pos)
+ }
+ myFusionMapped$ok5Pos=ok5Pos
+ myFusionMapped$ok3Pos=ok3Pos
+
+ rmFusion=c(myFusionMapped$name12[myFusionMapped$ok5Pos==0],myFusionMapped$name12[myFusionMapped$ok3Pos==0])
+
+ #txlen test
+ tx3LenTest=tx5LenTest=NULL;
+ for (i in 1:nrow(myFusionMapped)){
+ res=testFtxlen(mu=fragmentInfo$fragLengthMean, sig=fragmentInfo$fragLengthSd, r=fragmentInfo$readlen,ftxlen=myFusionMapped$flen5[i], kmerlen=fragmentInfo$kmer,fragDist=fragDist,M=10000)
+ tx5LenTest=c(tx5LenTest,sum(res$x<=myFusionMapped$tx5LenMean[i])/length(res$x))
+ res=testFtxlen(mu=fragmentInfo$fragLengthMean, sig=fragmentInfo$fragLengthSd, r=fragmentInfo$readlen,ftxlen=myFusionMapped$flen3[i], kmerlen=fragmentInfo$kmer,fragDist=fragDist,M=10000)
+ tx3LenTest=c(tx3LenTest,sum(res$x<=myFusionMapped$tx3LenMean[i])/length(res$x))
+ }
+ myFusionMapped$tx5LenTest=tx5LenTest
+ myFusionMapped$tx3LenTest=tx3LenTest
+ rmID=c(which(myFusionMapped$tx5LenSd<=1),which(myFusionMapped$tx3LenSd<=1),which(myFusionMapped$tx5LenTest<=0.05),which(myFusionMapped$tx3LenTest<=0.05))
+
+ #estimate split reads from mapped reads
+ myFusionMapped$srEst3=myFusionMapped$fragmentNum/myFusionMapped$flen3 * (fragmentInfo$readlen-2*fragmentInfo$kmer)
+ myFusionMapped$srEst5=myFusionMapped$fragmentNum/myFusionMapped$flen5 * (fragmentInfo$readlen-2*fragmentInfo$kmer)
+ myFusionMapped$srEstCount=apply(cbind(myFusionMapped$srEst3,myFusionMapped$srEst5),1,max)
+
+ #junctInfo=junctBr$junctInfo
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionMapped$front_tx),as.character(myFusionMapped$back_tx))), columns=c("EXONSTART","EXONEND"), keytype = "TXNAME")
+ myFusionMapped$tx2End=myFusionMapped$tx2Start=myFusionMapped$tx1End=myFusionMapped$tx1Start=NULL
+ myFusionMapped$tx2exAN=myFusionMapped$tx1exAN=NULL
+ for (i in 1:nrow(myFusionMapped)){
+ txname=as.character(myFusionMapped$front_tx[i])
+ res=exonInfo[exonInfo$TXNAME==txname,]
+ myFusionMapped$tx1Start[i]=min(res$EXONSTART)
+ myFusionMapped$tx1End[i]=max(res$EXONEND)
+ if (myFusionMapped$strand1[i]=="+") myFusionMapped$tx1exAN[i]=sum(res$EXONSTART<= myFusionMapped$brpos5.start[i]) else myFusionMapped$tx1exAN[i]=sum(res$EXONEND>= myFusionMapped$brpos5.start[i])
+
+ txname=as.character(myFusionMapped$back_tx[i])
+ res=exonInfo[exonInfo$TXNAME==txname,]
+ myFusionMapped$tx2Start[i]=min(res$EXONSTART)
+ myFusionMapped$tx2End[i]=max(res$EXONEND)
+ if (myFusionMapped$strand2[i]=="+") myFusionMapped$tx2exAN[i]=sum(res$EXONEND>= myFusionMapped$brpos3.start[i]) else myFusionMapped$tx2exAN[i]=sum(res$EXONSTART<= myFusionMapped$brpos3.start[i])
+
+ }
+
+
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionMapped$gene1),as.character(myFusionMapped$gene2))), columns=c("GENEID","TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ myFusionMapped$gechr.start1=myFusionMapped$gechr.end1=myFusionMapped$exid.start1=myFusionMapped$exid.end1=NULL
+ myFusionMapped$gechr.start2=myFusionMapped$gechr.end2=myFusionMapped$exid.start2myFusionMapped$exid.end2=NULL
+ for (i in 1:nrow(myFusionMapped)){
+ myEx=exonInfo[exonInfo$GENEID==myFusionMapped$gene1[i],]
+ myFusionMapped$gechr.start1[i]=min(myEx$EXONSTART)
+ myFusionMapped$gechr.end1[i]=max(myEx$EXONEND)
+ myFusionMapped$exid.start1[i]=myEx$EXONID[which.min(myEx$EXONSTART)]
+ myFusionMapped$exid.end1[i]=myEx$EXONID[which.max(myEx$EXONEND)]
+
+ myEx=exonInfo[exonInfo$GENEID==myFusionMapped$gene2[i],]
+ myFusionMapped$gechr.start2[i]=min(myEx$EXONSTART)
+ myFusionMapped$gechr.end2[i]=max(myEx$EXONEND)
+ myFusionMapped$exid.start2[i]=myEx$EXONID[which.min(myEx$EXONSTART)]
+ myFusionMapped$exid.end2[i]=myEx$EXONID[which.max(myEx$EXONEND)]
+
+ }
+
+ #extract junctInfo
+ junctInfo=junctBr$junctInfo
+
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionMapped$gene1),as.character(myFusionMapped$gene2))), columns=c("GENEID","TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ for (i in 1:nrow(myFusionMapped)){
+ res=junctInfo[[i]]
+
+ mappedExonL=exonInfo[match(sort(unique(unlist(res$readL.ExonID))),exonInfo$EXONID),]
+ geneExonL=exonInfo[exonInfo$GENEID==mappedExonL$GENEID[1],]
+
+ mappedExonR=exonInfo[match(sort(unique(unlist(res$readR.ExonID))),exonInfo$EXONID),]
+ geneExonR=exonInfo[exonInfo$GENEID==mappedExonR$GENEID[1],]
+
+ junctInfo[[i]]$mappedExonL=mappedExonL
+ junctInfo[[i]]$geneExonL=geneExonL
+
+ junctInfo[[i]]$mappedExonR=mappedExonR
+ junctInfo[[i]]$geneExonR=geneExonR
+ }
+
+
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionMapped$gene1),as.character(myFusionMapped$gene2))), columns=c("GENEID","TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ myFusionMapped$ANflen3=myFusionMapped$ANflen5=NULL
+ for (i in 1:nrow(myFusionMapped)){
+ res=junctInfo[[i]]
+ #summary(unlist(res$new.readL.GenePos))
+
+ mappedExonL=exonInfo[match(sort(unique(unlist(res$readL.ExonID))),exonInfo$EXONID),]
+ geneExonL=exonInfo[exonInfo$GENEID==mappedExonL$GENEID[1],]
+
+ mappedExonR=exonInfo[match(sort(unique(unlist(res$readR.ExonID))),exonInfo$EXONID),]
+ geneExonR=exonInfo[exonInfo$GENEID==mappedExonR$GENEID[1],]
+
+ ###get annotated flen
+ if (mappedExonL$TXSTRAND[1]=="+") ANExonL=geneExonL[geneExonL$EXONSTART <= min(mappedExonL$EXONSTART),] else ANExonL=geneExonL[geneExonL$EXONSTART >= min(mappedExonL$EXONSTART),]
+ myFusionMapped$ANflen5[i]=getGeneLen(geneExonMat=ANExonL)
+ if (mappedExonR$TXSTRAND[1]=="+") ANExonR=geneExonR[geneExonR$EXONSTART >= min(mappedExonR$EXONSTART),] else ANExonR=geneExonR[geneExonR$EXONSTART <= min(mappedExonR$EXONSTART),]
+ myFusionMapped$ANflen3[i]=getGeneLen(geneExonMat=ANExonR)
+
+
+ #Estimate split reads from mapped reads
+ myFusion$srEstCount=0
+ myFusion$srEstCount[which(!is.na(match(as.character(myFusion$fusionName),as.character(myFusionMapped$fusionName))))]=myFusionMapped$srEstCount[na.omit(match(as.character(myFusion$fusionName),as.character(myFusionMapped$fusionName)))]
+ # filter by the estimated number of split reads from mapped reads
+ rmID=which(myFusion$mappedCount>0 & myFusion$supportCount < trunc(myFusion$srEstCount)-1)
+ if (length(rmID)>0) myFusion=myFusion[-rmID,]
+
+ #filter by standard deviation of flen of the mapped reads
+ rmID=c(which(myFusionMapped$tx5LenSd<=1 & myFusionMapped$fragmentNum>=3),which(myFusionMapped$tx3LenSd<=1 & myFusionMapped$fragmentNum>=3))
+ rmFusion=unique(c(myFusionMapped$fusionName[rmID]))
+ if (length(rmFusion)>0){
+ myFusion=myFusion[which(is.na(match(myFusion$fusionName,rmFusion))),]
+ }
+ }
+
+ ### consistency between mapped and split - we compare by the end points to be more robust
+ myFusionMapped$brsign5=ifelse(myFusionMapped$brchposEx5-myFusionMapped$brpos5.end>0,"+","-")
+ myFusionMapped$brSign3=ifelse(myFusionMapped$brchposEx3-myFusionMapped$brpos3.end>0,"-","+")
+ # This filter depends very much on the correction of the mapped reads. In most of cases, they are ok. However, if only 1 wrong mapped read pair might change the results. We use this filter as a soft filter after this step.
+ rmID=c(which(myFusionMapped$strand1!=myFusionMapped$brsign5),which(myFusionMapped$strand2!=myFusionMapped$brsign3))
+ if (length(rmID)>0){
+ rmFusion=myFusionMapped$fusionName[rmID]
+ myFusion=myFusion[which(is.na(match(myFusion$fusionName,rmFusion))),]
+ }
+
+ junctBr.refine=refineJunctionBreak(junctBr, anntxdb, fragmentInfo, readStrands, fragDist)
+
+} else {
+ myFusionMapped=NULL
+ junctBr.refine=NULL
+ junctInfo=NULL
+} #end of if nrow(myFusionMapped)>0
+
+### proportion of remaining reads after filtering
+res=table(myFusion$name12)
+myFusion$supportCount3=res[match(myFusion$name12,names(res))]
+myFusion$survProp=myFusion$supportCount3/myFusion$supportCount
+
+### check for fusion genes with supporting reads >=5
+myFusionFinal=myFusion
+myFusionFinal=myFusionFinal[!duplicated(myFusionFinal$name12),]
+dim(myFusionFinal)
+keepID=which(myFusionFinal$supportCount3>=5)
+rmID=NULL
+if (length(keepID)>0)
+for (i in 1:length(keepID)){
+ myID=which(as.character(myFusion$name12)==as.character(myFusionFinal$name12[keepID[i]]))
+ res=myFusion[myID,]
+
+ if(sd(res$front_hitpos)<1) rmID=c(rmID,myID)
+ if(sd(res$back_hitpos)<1) rmID=c(rmID,myID)
+}
+
+if(length(rmID)>0) myFusion=myFusion[-rmID,]
+
+
+
+### get final results
+myFusionFinal=myFusion
+myFusionFinal=myFusionFinal[!duplicated(myFusionFinal$name12),]
+dim(myFusionFinal)
+
+# Filter by minSR
+myFusionFinal=myFusionFinal[myFusionFinal$supportCount>=FuSeq.params$minSR,]
+# Check if fusion breaks locate at the ending exon of gene
+rmID.SR=checkEndExon(myFusionFinal=myFusionFinal, junctBr=NULL, anntxdb=anntxdb, readStrands=FuSeq.params$readStrands,shrinkLen=5, type="SR")
+
+if (length(rmID.SR)>0) myFusionFinal=myFusionFinal[-rmID.SR,]
+
+#assign a score by totalCount
+myFusionFinal$score=myFusionFinal$totalCount
+
+myFusionFinal$supportRead=myFusionFinal$supportCount+myFusionFinal$mappedCount
+
+return(list(junctInfo=junctInfo,myFusionFinal=myFusionFinal, myFusion=myFusion, myFusionMapped=myFusionMapped,junctBr.refine=junctBr.refine))
+
+
+}
+
+
+
+
diff --git a/R/processFEQ.R b/R/processFEQ.R
new file mode 100644
index 0000000..af8261c
--- /dev/null
+++ b/R/processFEQ.R
@@ -0,0 +1,149 @@
+############################################################
+#####process fusion equivalence classes to generate initial fusion gene candidates
+processFEQ <-function(inPath,geneAnno,anntxdb,geeqMap,readStrands="UN",chromRef=as.character(c(1:22,"X","Y"))){
+ cat("\n Read fusion equivalence classes")
+ ##### read fragment information
+ fragmentInfo=read.csv(paste(inPath,"/fragmentInfo.txt",sep=""), header =TRUE, sep="\t")
+ libsize=fragmentInfo[1,5]
+ #read fusion-equivalence classes
+ feqRaw=read.csv(paste(inPath,"/feq_",readStrands,".txt",sep=""), header =TRUE, sep="\t")
+
+ #generate feq
+ res=feqRaw[,c(2,4)]
+ myDup=duplicated(res)
+ res=res[!myDup,]
+ feq=res[,1]
+ names(feq)=res[,2]
+ cat("\n The total number of fusion equivalence classes: ",length(feq))
+
+ if (length(feq) == 0) return(NULL)
+
+ cat("\n Create the maps between feq and fge")
+ #get a map between tx and gene
+ txToGene=select(anntxdb, keys=as.character(feqRaw[,1]), columns=c("GENEID","TXCHROM"), keytype = "TXNAME")
+ feqRaw$GENEID=txToGene$GENEID
+ feqGene=feqRaw[,-c(1,2)]
+ #remove duplicates
+ myDup=duplicated(feqGene)
+ feqGene=feqGene[!myDup,]
+ feqGene1=feqGene[feqGene$Read==1,]
+ feqGene2=feqGene[feqGene$Read==2,]
+ #remove duplicates of txToGene
+ myDup=duplicated(txToGene)
+ txToGene=txToGene[!myDup,]
+ ##### do indexing feq and fge
+ feqGene1Num=table(feqGene1$Feq)
+ feqGene2Num=table(feqGene2$Feq)
+
+ feqGene1$Read=feqGene2Num[feqGene1$Feq]
+ feqGene2$Read=feqGene1Num[feqGene2$Feq]
+
+ gene1list=apply(feqGene1,1,function(x){
+ rep(x[3],x[1])
+ })
+ gene1list=unlist(gene1list)
+ res=tapply(feqGene2$GENEID,feqGene2$Feq,c)
+ res=data.frame(y=feqGene1Num,x=res)
+ gene2list=apply(res,1,function(x){
+ rep(x[3],x[2])
+ })
+ gene2list=unlist(gene2list)
+
+ res=cbind(seq_along(feqGene1Num),feqGene1Num,feqGene2Num)
+ feqID=apply(res,1,function(x){
+ rep(x[1],x[2]*x[3])
+ })
+ feqID=unlist(feqID)
+
+ fgeneNames=paste(gene1list,gene2list,sep="-")
+ res=feqID
+ names(res)=fgeneNames
+
+ #index from fge to feq
+ feqFgeMap=tapply(res,names(res),c)
+ feqFgeMap=lapply(feqFgeMap,function(x) as.integer(unlist(x)))
+ length(feqFgeMap) # should be equal to number of fge
+ #create fge
+ fge=data.frame(fgeID=c(1:length(feqFgeMap)), name12=names(feqFgeMap))
+
+ #index from feq to fge
+ matchID=match(names(res),as.character(fge$name12))
+ names(res)=matchID
+ fgeFeqMap=tapply(names(res),res,c)
+ fgeFeqMap=lapply(fgeFeqMap,function(x) as.integer(unlist(x)))
+ length(fgeFeqMap) #shoud be equal to number of feq
+
+
+ ##### add features to fge
+ res=lapply(as.character(fge$name12), function(x) unlist(strsplit(x,"-")))
+ res=do.call(rbind,res)
+ colnames(res)=c("gene1","gene2")
+ fge=cbind(fge,res)
+ fge$name21=paste(fge$gene2,fge$gene1,sep="-")
+
+ ###########
+ cat("\n Get the number of supporting reads")
+ ### find raw counts of fusion genes
+ fusionGene=fge
+ #sum-up all counts of feq
+ supportCount=rep(0,nrow(fge))
+ for (feqID in 1:length(feq)){
+ feqCount=feq[feqID]
+ gid=unlist(fgeFeqMap[feqID])
+ supportCount[gid]=supportCount[gid]+feqCount
+ }
+ fusionGene$supportCount=supportCount
+
+ ### estimate counts for fusion genes
+ cat("\n Correct the number of supporting reads")
+ alp0=rep(sum(feq)/nrow(fusionGene),nrow(fusionGene))
+ alpOut=rep(0,nrow(fusionGene))
+
+ res=estimateCountEM(alp0,alpOut,feq,fgeFeqMap,itNum=1,alpDiff.thres=0.01)
+
+ fusionGene$correctedCount=res$correctedCount
+ fusionGene=fusionGene[order(fusionGene$correctedCount,decreasing=TRUE),]
+
+ dim(fusionGene)
+
+ #######
+ cat("\n Extract other biological information...")
+ #add few biological information
+ res=select(anntxdb, keys=as.character(fusionGene$gene1), columns=c("GENEID","TXCHROM","TXSTRAND"), keytype = "GENEID")
+ colnames(res)=c("GENEID","chrom1","strand1")
+ fusionGene=cbind(fusionGene,res[,-1])
+ res=select(anntxdb, keys=as.character(fusionGene$gene2), columns=c("GENEID","TXCHROM","TXSTRAND"), keytype = "GENEID")
+ colnames(res)=c("GENEID","chrom2","strand2")
+ fusionGene=cbind(fusionGene,res[,-1])
+
+ #####
+ cat("\n Keep only candidates in the selected chromosomes")
+ #do filter by chromosomes
+ fusionGene=chromFilter(fusionGene,chromRef=chromRef)
+
+ ##### generate features to detect fusion genes
+ cat("\n Extract extra features...")
+ myFusion=fusionGene
+ #Fusion-genes sharing the same set of fusion equivalence classes
+ matchID=match(as.character(myFusion$name12),names(feqFgeMap))
+ feqDup=duplicated(feqFgeMap[matchID], fromLast=FALSE) + duplicated(feqFgeMap[matchID], fromLast=TRUE)
+ myFusion$feqDup=feqDup
+
+ #compute cpm
+ myFusion$cpm=myFusion$supportCount*10^6/libsize
+ #distance between two genes >= minGeneDist
+ geneDist=computeGeneDistance(myFusion,anntxdb,minGeneDist=-1)
+ myFusion$geneDist=geneDist
+
+ #get reversed fusion (3-5) count
+ name21Count=computeReversedFusionCount(myFusion)
+ myFusion$name21Count=name21Count
+
+ #compute dupGene
+ res=computeDupGene(myFusion,dupGene.thres=-1)
+ myFusion=cbind(myFusion,res)
+
+ res=list(fgeList=myFusion,fge=fge,feq=feq,fgeFeqMap=fgeFeqMap,feqFgeMap=feqFgeMap,feqRaw=feqRaw)
+ return(res)
+
+}
\ No newline at end of file
diff --git a/R/processMappedRead.R b/R/processMappedRead.R
new file mode 100644
index 0000000..5bd8b1f
--- /dev/null
+++ b/R/processMappedRead.R
@@ -0,0 +1,204 @@
+############################################################
+##### process mapped reads
+############################################################
+
+processMappedRead <-function(inPath,geneAnno, anntxdb, geeqMap, FuSeq.params,feqInfo=NULL){
+
+ cat("\n ------------------------------------------------------------------")
+ cat("\n Processing mapped reads (MR) from dataset: ",inPath, " read strands:", FuSeq.params$readStrands)
+ if (is.null(feqInfo))
+ feqInfo=processFEQ(inPath,geneAnno,anntxdb,geeqMap,readStrands=FuSeq.params$readStrands,chromRef=FuSeq.params$chromRef)
+
+ if (is.null(feqInfo)) return(NULL)
+
+ #########################
+ fragmentInfo=read.csv(paste(inPath,"/fragmentInfo.txt",sep=""), header =TRUE, sep="\t")
+ fragDist = read.table(paste(inPath,"/fragmentDist.txt",sep=""))
+
+
+ maxSharedCount=FuSeq.params$maxSharedCount;
+ minGeneDist=FuSeq.params$minGeneDist;
+ maxInvertedFusionCount=FuSeq.params$maxInvertedFusionCount;
+ maxMRfusionFc=FuSeq.params$maxMRfusionFc;
+ maxMRfusionNum=FuSeq.params$maxMRfusionNum;
+ sgtMRcount=FuSeq.params$sgtMRcount;
+ readStrands=FuSeq.params$readStrands
+ countPropLowBound=0 # not use this one anymore
+
+ myFusionFinal=feqInfo$fgeList
+ cat("\n The total number of fge candidates: ",nrow(myFusionFinal))
+
+ if (readStrands=="RF" || readStrands=="UN" || readStrands=="RR"){
+ myFusionFinal$gene5p=myFusionFinal$gene2
+ myFusionFinal$gene3p=myFusionFinal$gene1
+ myFusionFinal$chrom5p=myFusionFinal$chrom2
+ myFusionFinal$chrom3p=myFusionFinal$chrom1
+ myFusionFinal$strand5p=myFusionFinal$strand2
+ myFusionFinal$strand3p=myFusionFinal$strand1
+
+ }else{
+ myFusionFinal$gene5p=myFusionFinal$gene1
+ myFusionFinal$gene3p=myFusionFinal$gene2
+ myFusionFinal$chrom5p=myFusionFinal$chrom1
+ myFusionFinal$chrom3p=myFusionFinal$chrom2
+ myFusionFinal$strand5p=myFusionFinal$strand1
+ myFusionFinal$strand3p=myFusionFinal$strand2
+ }
+
+ myFusionFinal$fusionName=paste(myFusionFinal$gene5p,myFusionFinal$gene3p,sep="-")
+
+ cat("\n Start filtering ...")
+ ##### do some strong filters here
+ if (maxSharedCount>0) myFusionFinal=myFusionFinal[abs(myFusionFinal$supportCount-myFusionFinal$correctedCount)/myFusionFinal$supportCount <= maxSharedCount,]
+
+ #remove name21 count
+ if (maxInvertedFusionCount>0) myFusionFinal=myFusionFinal[myFusionFinal$name21Count-1 <= myFusionFinal$supportCount*maxInvertedFusionCount,]
+ #remove small gene distance
+ if (minGeneDist > 0){
+ rmID=which(as.character(myFusionFinal$chrom1)==as.character(myFusionFinal$chrom2) & myFusionFinal$geneDist <= minGeneDist)
+ if (length(rmID)>0)
+ myFusionFinal=myFusionFinal[-rmID,]
+ }
+ myFusionFinal=myFusionFinal[order(myFusionFinal$supportCount, decreasing = TRUE),]
+
+
+ ### add gene types, keep only protein_coding genes later
+ dim(geneAnno)
+ matchID=match(myFusionFinal$gene1,geneAnno[,6])
+ res=geneAnno[matchID,]
+ colnames(res)=paste(colnames(res),"1",sep="")
+ myFusionFinal=cbind(myFusionFinal,res[,c(2,4)])
+ matchID=match(myFusionFinal$gene2,geneAnno[,6])
+ res=geneAnno[matchID,]
+ colnames(res)=paste(colnames(res),"2",sep="")
+ myFusionFinal=cbind(myFusionFinal,res[,c(2,4)])
+
+ #fiter low counts with multiple duplicated genes
+ res=computeDupGene(myFusionFinal,dupGene.thres=-1)
+ colnames(res)=c("dupGene1_f1","dupGene2_f1")
+ myFusionFinal=cbind(myFusionFinal,res)
+
+ rmID=(myFusionFinal$supportCount<=1) & (myFusionFinal$dupGene1_f1 > 1 | myFusionFinal$dupGene2_f1 > 1)
+ myFusionFinal=myFusionFinal[!rmID,]
+
+
+ #filter by dupGenes: keep maxMRfusionNum duplicated genes
+ keepID1=unlist(lapply(unique(as.character(myFusionFinal$gene1)), function(g){
+ keepID=which(myFusionFinal$gene1==g)
+ if (sum(myFusionFinal$supportCount[keepID]>sgtMRcount)>maxMRfusionNum) return (NULL)
+ if (length(keepID) < maxMRfusionNum) return(keepID)
+ if(length(keepID) > maxMRfusionNum )
+ if (myFusionFinal$supportCount[keepID[maxMRfusionNum+1]]*maxMRfusionFc >= myFusionFinal$supportCount[keepID[1]]) return(NULL)
+ keepID=keepID[1:maxMRfusionNum]
+ return(keepID)
+
+ }))
+ keepID2=unlist(lapply(unique(as.character(myFusionFinal$gene2)), function(g){
+ keepID=which(myFusionFinal$gene2==g)
+ if (sum(myFusionFinal$supportCount[keepID]>sgtMRcount)>maxMRfusionNum) return (NULL)
+ if (length(keepID) < maxMRfusionNum) return(keepID)
+ if(length(keepID) > maxMRfusionNum )
+ if (myFusionFinal$supportCount[keepID[maxMRfusionNum+1]]*maxMRfusionFc >= myFusionFinal$supportCount[keepID[1]]) return(NULL)
+ keepID=keepID[1:maxMRfusionNum]
+ return(keepID)
+ }))
+ # keepID=unique(c(keepID1,keepID2))
+ keepID=intersect(keepID1,keepID2)
+ myFusionFinal=myFusionFinal[keepID,]
+ myFusionFinal=myFusionFinal[order(myFusionFinal$supportCount, decreasing = TRUE),]
+
+
+ cat("\n The number of remaining fge candidates: ",nrow(myFusionFinal))
+ ######### compute Count of fge from ftx
+ cat("\n Get the sum count of ftx")
+
+ feqRaw1=feqInfo$feqRaw[feqInfo$feqRaw$Read==1,]
+ feqRaw2=feqInfo$feqRaw[feqInfo$feqRaw$Read==2,]
+
+ myfeqID=lapply(as.character(myFusionFinal$name12), function(mykey) feqInfo$feqFgeMap[[mykey]])
+ myfeqIDSize=sapply(myfeqID, length)
+ myfeqIDName=unlist(apply(cbind(as.character(myFusionFinal$name12),myfeqIDSize),1, function(x) rep(x[1],x[2])))
+ myfeqID=unlist(myfeqID)
+
+ ufeqID=unique(myfeqID)
+ mydat=feqRaw1[!is.na(match(feqRaw1$Feq,ufeqID)),]
+ tx1Num=tapply(mydat[,3],mydat[,4],sum)
+ mydat=feqRaw2[!is.na(match(feqRaw2$Feq,ufeqID)),]
+ tx2Num=tapply(mydat[,3],mydat[,4],sum)/2
+ mytxCount=tx1Num*tx2Num*feqInfo$feq[as.integer(names(tx2Num))]
+ matchID=match(myfeqID,as.integer(names(tx2Num)))
+
+ myres=tapply(mytxCount[matchID],myfeqIDName,sum)
+ myres=myres[match(as.character(myFusionFinal$name12),names(myres))]
+
+ #get the aggregation counts from tx
+ myFusionFinal$aggtxCount=myres
+ myFusionFinal$countProp=myFusionFinal$aggtxCount/myFusionFinal$supportCount
+
+ #get the number of tx of gene1
+ myres=tapply(tx1Num[matchID],myfeqIDName,sum)
+ myres=myres[match(as.character(myFusionFinal$name12),names(myres))]
+ myFusionFinal$tx1Num=myres
+ #get the number of tx of gene2
+ myres=tapply(tx2Num[matchID],myfeqIDName,sum)
+ myres=myres[match(as.character(myFusionFinal$name12),names(myres))]
+ myFusionFinal$tx2Num=myres
+
+
+ cat("\n Continue the filtering ...")
+
+ #filter by count
+ myFusionFinal=myFusionFinal[myFusionFinal$supportCount >=FuSeq.params$minMR,]
+
+ #filter by countProp
+ myFusionFinal=myFusionFinal[myFusionFinal$countProp>countPropLowBound,]
+
+ cat("\n The number of remaining fge candidates: ",nrow(myFusionFinal))
+
+ #do biological filters
+ cat("\n Filter by biological features... ")
+ bioFilter.res=doBiologicalFilter(myFusionFinal, chromRef=FuSeq.params$chromRef, onlyProteinCodingGenes=FuSeq.params$onlyProteinCodingGenes, doFilter=TRUE)
+ myFusionFinal=bioFilter.res
+
+ cat("\n The number of remaining fge candidates: ",nrow(myFusionFinal))
+ #sequence similarity between two genes
+ cat("\n Filter by sequence similarity... ")
+ seqHmlog=NULL
+ for (i in 1:nrow(myFusionFinal)){
+ res=intersect(geeqMap[[as.character(myFusionFinal$gene2[i])]],geeqMap[[as.character(myFusionFinal$gene1[i])]])
+ if (length(res) > 0) seqHmlog=c(seqHmlog,1) else (seqHmlog=c(seqHmlog,0))
+ }
+ myFusionFinal$seqHmlog=seqHmlog
+
+ #do filter
+ myFusionFinal=myFusionFinal[myFusionFinal$seqHmlog==0,]
+ cat("\n The number of remaining fge candidates: ",nrow(myFusionFinal))
+
+
+ #detect junction breaks
+ cat("\n Detect junction breaks... ")
+ junctBr=detectJunctionBreaks(myFusionFinal,inPath, feqInfo$feq,feqInfo$feqFgeMap, anntxdb, readStrands=FuSeq.params$readStrands)
+ myFusionFinal=junctBr$myFusionFinal
+
+ myFusionFinal=myFusionFinal[order(myFusionFinal$nondupCount, decreasing = TRUE),]
+ #filter by nondupCount
+ myFusionFinal=myFusionFinal[myFusionFinal$nondupCount>=FuSeq.params$minNonDupMR,]
+
+ #filter by junction distance
+ myFusionFinal=myFusionFinal[myFusionFinal$junctDist>FuSeq.params$minJunctionDist,]
+
+ if (nrow(myFusionFinal) == 0){
+ cat("\n The number of final fge candidates: ",nrow(myFusionFinal))
+ return(NULL)
+ }
+
+ #get coverage
+ myFusionFinal$cover5=myFusionFinal$genebrpos5.rg/myFusionFinal$flen5
+ myFusionFinal$cover3=myFusionFinal$genebrpos3.rg/myFusionFinal$flen3
+
+
+ cat("\n The number of final fge candidates: ",nrow(myFusionFinal))
+
+ res=list(myFusionFinal=myFusionFinal,junctBr=junctBr,feqInfo=feqInfo,fragmentInfo=fragmentInfo,fragDist=fragDist)
+ return(res)
+}
diff --git a/R/processSplitRead.R b/R/processSplitRead.R
new file mode 100644
index 0000000..bdef684
--- /dev/null
+++ b/R/processSplitRead.R
@@ -0,0 +1,390 @@
+############################################################
+##### process split reads
+############################################################
+
+processSplitRead <-function(inPath,geneAnno, anntxdb, geeqMap, txFastaFile, FuSeq.params){
+ cat("\n ------------------------------------------------------------------")
+ cat("\n Processing split reads (SR) from dataset: ",inPath, " read strands:", FuSeq.params$readStrands)
+
+ ##### get fragment information
+ fragmentInfo=read.csv(paste(inPath,"/fragmentInfo.txt",sep=""), header =TRUE, sep="\t")
+ fragDist = read.table(paste(inPath,"/fragmentDist.txt",sep=""))
+ fragRg=fragDist[fragDist[,2]>0,1]
+ flen.min=min(fragRg)
+ flen.max=max(fragRg)
+ ##### find split reads
+ cat("\n Get split reads ...")
+ splitReads=fsizes=NULL
+ frfiles=list.files(inPath,paste("splitReadInfo_*",sep=""))
+ for (i in 1:length(frfiles)){
+ tmpDat=read.csv(paste(inPath,"/",frfiles[i],sep=""), header =FALSE, sep="\t")
+ splitReads=rbind(splitReads,tmpDat)
+ fsizes=c(fsizes,nrow(tmpDat))
+ }
+ fsizeLadder=cumsum(fsizes)
+ colnames(splitReads)=c("header","readType","direction","front_tx","front_gene","front_hitpos","front_querypos","front_len","back_tx","back_gene","back_hitpos","back_querypos","back_len","matchedGene","matchedDirect","matchedPos")
+ splitReads$tx12=paste(splitReads$front_tx,splitReads$back_tx,sep="-")
+ splitReads$tx21=paste(splitReads$back_tx,splitReads$front_tx,sep="-")
+ splitReads$name12=paste(splitReads$front_gene,splitReads$back_gene,sep="-")
+ splitReads$name21=paste(splitReads$back_gene,splitReads$front_gene,sep="-")
+
+
+ ############# starting process
+ fusionGene=splitReads
+
+ cat("\n Extract other biological information...")
+ #add few biological information
+ res=select(anntxdb, keys=as.character(fusionGene$front_gene), columns=c("GENEID","TXCHROM","TXSTRAND"), keytype = "GENEID")
+ colnames(res)=c("GENEID","chrom1","strand1")
+ fusionGene=cbind(fusionGene,res[,-1])
+ res=select(anntxdb, keys=as.character(fusionGene$back_gene), columns=c("GENEID","TXCHROM","TXSTRAND"), keytype = "GENEID")
+ colnames(res)=c("GENEID","chrom2","strand2")
+ fusionGene=cbind(fusionGene,res[,-1])
+ fusionGene=chromFilter(fusionGene)
+
+ fusionGene$gene1=fusionGene$front_gene
+ fusionGene$gene2=fusionGene$back_gene
+
+
+ matchID=match(fusionGene$gene1,geneAnno[,6])
+ res=geneAnno[matchID,]
+ colnames(res)=paste(colnames(res),"1",sep="")
+ fusionGene=cbind(fusionGene,res[,c(2,4)])
+ matchID=match(fusionGene$gene2,geneAnno[,6])
+ res=geneAnno[matchID,]
+ colnames(res)=paste(colnames(res),"2",sep="")
+ fusionGene=cbind(fusionGene,res[,c(2,4)])
+ #filter by protein coding
+ keepID=which(fusionGene$geneType1=="protein_coding" & fusionGene$geneType2=="protein_coding")
+ fusionGene=fusionGene[keepID,]
+
+
+ ##### get supporting count
+ res=table(fusionGene$name12)
+ fusionGene$supportCount=res[match(fusionGene$name12,names(res))]
+
+ ##### count of name21
+ matchID=match(fusionGene$tx12, fusionGene$tx21)
+ tx21Count=fusionGene$supportCount[matchID]
+ tx21Count[is.na(tx21Count)]=0
+ fusionGene$tx21Count=tx21Count
+
+ ##### shared count
+ res=table(as.character(fusionGene$header))
+ length(res)
+ fusionGene$readProp=1/res[match(as.character(fusionGene$header),names(res))]
+
+ res=table(fusionGene$tx12)
+ fusionGene$tx12Count=res[match(fusionGene$tx12,names(res))]
+ adjtx12Count=tapply(as.double(fusionGene$readProp),as.character(fusionGene$tx12),sum)
+ fusionGene$adjtx12Count=adjtx12Count[match(as.character(fusionGene$tx12),names(adjtx12Count))]
+
+ #gene distance
+ geneDist=computeGeneDistance(fusionGene,anntxdb,minGeneDist=-1)
+ fusionGene$geneDist=geneDist
+
+ myFusion=fusionGene
+
+ #filter by gene distance
+ rmID=which(as.character(myFusion$chrom1)==as.character(myFusion$chrom2) & myFusion$geneDist <= FuSeq.params$minGeneDist)
+ if (length(rmID)>0) myFusion=myFusion[-rmID,]
+
+ #filter by overlapping sequences
+ myFusion$brol=myFusion$front_querypos+myFusion$front_len-myFusion$back_querypos
+ myFusionFP=myFusion[myFusion$brol>10,]
+ myFusion=myFusion[myFusion$brol<=10,]
+
+ FPlist=unique(as.character(myFusionFP$name12))
+ matchID=match(as.character(myFusion$name12),FPlist)
+ myFusion=myFusion[which(is.na(matchID)),]
+
+ res=table(myFusion$name12)
+ myFusion$supportCount2=res[match(myFusion$name12,names(res))]
+ #transcript level
+ res=table(myFusion$tx12)
+ myFusion$tx12Count2=res[match(myFusion$tx12,names(res))]
+ #remove all ftx not satisfying the sequence overlapping
+ keepID=which(myFusion$tx12Count2==myFusion$tx12Count)
+ myFusion=myFusion[keepID,]
+
+
+ myFusion$flen=rep(0,nrow(myFusion))
+ fwID=which(myFusion$direction==0 | myFusion$direction==3)
+ rcID=which(myFusion$direction==1 | myFusion$direction==4)
+ #forward
+ myFusion$flen[fwID]=myFusion$back_querypos[fwID] + myFusion$matchedPos[fwID]-myFusion$back_hitpos[fwID] + fragmentInfo$readlen
+ #rc
+ myFusion$flen[rcID]=(myFusion$front_hitpos[rcID] -myFusion$front_querypos[rcID]- myFusion$matchedPos[rcID] ) + fragmentInfo$readlen
+ myFusion=myFusion[myFusion$flen>=flen.min,]
+ myFusion=myFusion[myFusion$flen<=flen.max,]
+ #mySR$front_hitpos+mySR$front_len-mySR$front_querypos
+ mytest=pnorm(myFusion$flen, mean=fragmentInfo$fragLengthMean, sd=fragmentInfo$fragLengthSd)
+ myFusion$flenTest=mytest
+ myFusion=myFusion[myFusion$flenTest>=0.001,]
+ myFusion=myFusion[myFusion$flenTest<=0.999,]
+
+
+ ### find duplicate tx
+ myDup=duplicated(myFusion$tx12)
+ myFusionNoDup=myFusion[!myDup,]
+
+ duptx1=table(myFusionNoDup$front_tx)
+ duptx2=table(myFusionNoDup$back_tx)
+ myFusion=cbind(myFusion,as.integer(duptx1[match(as.character(myFusion$front_tx),names(duptx1))]))
+ myFusion=cbind(myFusion,as.integer(duptx2[match(as.character(myFusion$back_tx),names(duptx2))]))
+ colnames(myFusion)[c(ncol(myFusion)-1,ncol(myFusion))]=c("duptx1","duptx2")
+
+
+ ####### check canonical splicing sites
+ cat("\n Remaining fusion reads: ",nrow(myFusion))
+ cat("\n Check canonical splicing sites, it takes time ...")
+
+ #####preparing annotation
+ library(Biostrings)
+ fasta = readDNAStringSet(txFastaFile)
+ fasta_txnames=sapply(names(fasta), function(x) unlist(strsplit(x," "))[1])
+
+ shrinkLen=5
+ myFusion$front_brpos=myFusion$front_hitpos+myFusion$front_len-1
+ myFusion$brchposEx5=-1
+ myFusion$back_brpos=myFusion$back_hitpos-(myFusion$back_querypos-myFusion$front_querypos-myFusion$front_len)-1
+ myFusion$brchposEx3=-1
+
+
+ myFusion$GTATCEnd=myFusion$ATATCEnd=myFusion$ATEnd=myFusion$GCEnd=myFusion$GTEnd=myFusion$ssExEnd=myFusion$ssExEndGe=rep(-1,nrow(myFusion))
+ myFusion$AAStart=myFusion$ATStart=myFusion$ACStart=myFusion$AGStart=myFusion$ssExStart=myFusion$ssExStartGe=rep(-1,nrow(myFusion))
+ ##### check splicing
+ cat("\n Checking in 5 prime site...")
+
+ #to speedup we do in blocks
+ blockSize=20000
+ blockNum=trunc(nrow(myFusion)%/%blockSize) + ifelse(nrow(myFusion)%%blockSize>0,1,0)
+ #sorted by front_tx
+ myFusion=myFusion[order(myFusion$front_tx),]
+
+ mytime <- system.time({
+
+ for (blockID in 1:blockNum){
+ cat("\n",blockID," blocks processed")
+
+ block.keepID=c(((blockID-1)*blockSize+1):(blockID*blockSize))
+ block.keepID=block.keepID[block.keepID<=nrow(myFusion)]
+ myFusionBlock=myFusion[block.keepID,]
+
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionBlock$front_gene))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+ frontTxList=as.character(myFusionBlock$front_tx)
+ frontTxSet=unique(frontTxList)
+ cat("\n Total transcripts ",length(frontTxSet))
+ for (i in 1:length(frontTxSet)){
+
+ keepID=which(frontTxList==frontTxSet[i])
+ mySR=myFusionBlock[keepID,]
+ txname=frontTxSet[i]
+
+ matchID=match(txname,fasta_txnames)
+ mytxFasta=fasta[matchID]
+ txExonMat=exonInfo[exonInfo$TXNAME==txname,]
+
+ if (txExonMat$TXSTRAND[1]=="+") {
+ txExonMat=txExonMat[order(txExonMat$EXONSTART),]#sort exons by increasing order for forward strand
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ txExonMat$EXONTXSTART=c(0,exonlenCumSum[-length(exonlenCumSum)])
+ txExonMat$EXONTXEND=exonlenCumSum-1
+ }else{
+ txExonMat=txExonMat[order(txExonMat$EXONEND, decreasing=TRUE),]#sort exons by decreasing order for reverse strand
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ txExonMat$EXONTXSTART=c(0,exonlenCumSum[-length(exonlenCumSum)])
+ txExonMat$EXONTXEND=exonlenCumSum-1
+ }
+
+ myDiff=NULL
+ myDonor5=myDonor=NULL
+ if (txExonMat$TXSTRAND[1]=="-") diff=unlist(lapply(mySR$front_brpos,function(x) min(abs(x-txExonMat$EXONTXSTART)))) else diff=unlist(lapply(mySR$front_brpos,function(x) min(abs(x-txExonMat$EXONTXEND))))
+ myDiff=diff
+
+ for (k in 1:shrinkLen){
+ mybrpos=mySR$front_brpos-k+1
+ donorSeq=substring(mytxFasta,mybrpos-1,mybrpos)
+ myDonor=cbind(myDonor,donorSeq)
+
+ donorSeq5=substring(mytxFasta,mybrpos-4,mybrpos)
+ myDonor5=cbind(myDonor5,donorSeq5)
+
+ }
+ exEnd=myDiff
+ myFusionBlock$ssExEnd[keepID]=exEnd
+ myDonorCk=apply(myDonor,1,function(x) max(x=="GT"))
+ myFusionBlock$GTEnd[keepID]=myDonorCk
+ myDonorCk=apply(myDonor,1,function(x) max(x=="GC"))
+ myFusionBlock$GCEnd[keepID]=myDonorCk
+ myDonorCk=apply(myDonor,1,function(x) max(x=="AT"))
+ myFusionBlock$ATEnd[keepID]=myDonorCk
+
+ myDonorCk=apply(myDonor5,1,function(x) max(x=="ATATC"))
+ myFusionBlock$ATATCEnd[keepID]=myDonorCk
+
+ myDonorCk=apply(myDonor5,1,function(x) max(x=="GTATC"))
+ myFusionBlock$GTATCEnd[keepID]=myDonorCk
+
+
+ myFusionBlock$brchposEx5[keepID]=convertChrPos(txname=txname,txpos=myFusionBlock$front_brpos[keepID],txExonMat=txExonMat)
+ #check exon at gene-level
+ geExonMat=exonInfo[exonInfo$GENEID==mySR$gene1[1],]
+ myDiff=NULL
+ #diff=unlist(lapply(myFusionBlock$brchposEx5[keepID],function(x) min(abs(x-c(geExonMat$EXONSTART,geExonMat$EXONEND))))) #this one is less strict where we allow a shift between exons. Results of this will be concordant with the results from tx checking
+ if (geExonMat$TXSTRAND[1]=="-") diff=unlist(lapply(myFusionBlock$brchposEx5[keepID],function(x) min(abs(x-geExonMat$EXONSTART)))) else diff=unlist(lapply(myFusionBlock$brchposEx5[keepID],function(x) min(abs(x-geExonMat$EXONEND)))) #this one is more strict, so the result might be not concordant with the tx checking
+ myDiff=diff
+
+
+ myFusionBlock$ssExEndGe[keepID]=myDiff
+
+ if (i %% 1000 ==0) cat("\n",i," transcripts processed")
+ }
+ #update results
+ myFusion[block.keepID,]=myFusionBlock
+ }
+
+ })
+ mytime
+
+
+
+ cat("\n\n Checking in 3 prime site...")
+
+ #to speedup we do in blocks
+ blockSize=20000
+ blockNum=trunc(nrow(myFusion)%/%blockSize) + ifelse(nrow(myFusion)%%blockSize>0,1,0)
+ #sorted by back_tx
+ myFusion=myFusion[order(myFusion$back_tx),]
+
+ mytime <- system.time({
+
+ for (blockID in 1:blockNum){
+ cat("\n",blockID," blocks processed")
+
+ block.keepID=c(((blockID-1)*blockSize+1):(blockID*blockSize))
+ block.keepID=block.keepID[block.keepID<=nrow(myFusion)]
+ myFusionBlock=myFusion[block.keepID,]
+
+ exonInfo=select(anntxdb, keys=unique(c(as.character(myFusionBlock$back_gene))), columns=c("TXNAME","EXONID","EXONSTART","EXONEND","TXSTRAND"), keytype = "GENEID")
+
+ backTxList=as.character(myFusionBlock$back_tx)
+ backTxSet=unique(backTxList)
+ cat("\n Total transcripts ",length(backTxSet))
+ for (i in 1:length(backTxSet)){
+ keepID=which(backTxList==backTxSet[i])
+ mySR=myFusionBlock[keepID,]
+ txname=backTxSet[i]
+
+ matchID=match(txname,fasta_txnames)
+ mytxFasta=fasta[matchID]
+ txExonMat=exonInfo[exonInfo$TXNAME==txname,]
+ if (txExonMat$TXSTRAND[1]=="+") {
+ txExonMat=txExonMat[order(txExonMat$EXONSTART),]#sort exons by increasing order for forward strand
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ txExonMat$EXONTXSTART=c(0,exonlenCumSum[-length(exonlenCumSum)])
+ txExonMat$EXONTXEND=exonlenCumSum-1
+ }else{
+ txExonMat=txExonMat[order(txExonMat$EXONEND, decreasing=TRUE),]#sort exons by decreasing order for reverse strand
+ exonlen=txExonMat$EXONEND-txExonMat$EXONSTART+1
+ exonlenCumSum=cumsum(exonlen)
+ txExonMat$EXONTXSTART=c(0,exonlenCumSum[-length(exonlenCumSum)])
+ txExonMat$EXONTXEND=exonlenCumSum-1
+ }
+
+ myDiff=NULL
+ myAcceptor=NULL
+ if (txExonMat$TXSTRAND[1]=="+") diff=unlist(lapply(mySR$back_brpos,function(x) min(abs(x-txExonMat$EXONTXSTART)))) else diff=unlist(lapply(mySR$back_brpos,function(x) min(abs(x-txExonMat$EXONTXEND))))
+ myDiff=diff
+
+ for (k in 1:shrinkLen){
+ mybrpos=mySR$back_brpos+k
+ acceptorSeq=substring(mytxFasta,mybrpos-1,mybrpos)
+ myAcceptor=cbind(myAcceptor,acceptorSeq)
+ }
+ #exStart=rowMin(myDiff)
+ exStart=myDiff
+ myFusionBlock$ssExStart[keepID]=exStart
+
+ myAcceptorCk=apply(myAcceptor,1,function(x) max(x=="AG"))
+ myFusionBlock$AGStart[keepID]=myAcceptorCk
+ myAcceptorCk=apply(myAcceptor,1,function(x) max(x=="AC"))
+ myFusionBlock$ACStart[keepID]=myAcceptorCk
+ myAcceptorCk=apply(myAcceptor,1,function(x) max(x=="AT"))
+ myFusionBlock$ATStart[keepID]=myAcceptorCk
+ myAcceptorCk=apply(myAcceptor,1,function(x) max(x=="AA"))
+ myFusionBlock$AAStart[keepID]=myAcceptorCk
+
+
+ myFusionBlock$brchposEx3[keepID]=convertChrPos(txname=txname,txpos=myFusionBlock$back_brpos[keepID],txExonMat=txExonMat)
+ #check exon at gene-level
+ geExonMat=exonInfo[exonInfo$GENEID==mySR$gene2[1],]
+ myDiff=NULL
+ #diff=unlist(lapply(myFusionBlock$brchposEx3[keepID],function(x) min(abs(x-c(geExonMat$EXONSTART,geExonMat$EXONEND))))) #this one is less strict where we allow a shift between exons. Results of this will be concordant with the results from tx checking
+ if (geExonMat$TXSTRAND[1]=="+") diff=unlist(lapply(myFusionBlock$brchposEx3[keepID],function(x) min(abs(x-geExonMat$EXONSTART)))) else diff=unlist(lapply(myFusionBlock$brchposEx3[keepID],function(x) min(abs(x-geExonMat$EXONEND)))) #this one is more strict, so the result might be not concordant with the tx checking
+ myDiff=diff
+
+ myFusionBlock$ssExStartGe[keepID]=myDiff
+
+ if (i %% 1000 ==0) cat("\n",i," processed")
+ }
+
+
+
+ #update results
+ myFusion[block.keepID,]=myFusionBlock
+ }
+
+ })
+ mytime
+
+ myFusion$junctDist=abs(myFusion$brchposEx5-myFusion$brchposEx3)
+
+ myFusion$ssStart=myFusion$ssEnd=rep(-1,nrow(myFusion))
+ myFusion$ssEnd=ifelse(abs(myFusion$GCEnd)>0,4,myFusion$ssEnd)
+ myFusion$ssEnd=ifelse(abs(myFusion$GTEnd)>0,3,myFusion$ssEnd)
+ #myFusion$ssEnd=ifelse(abs(myFusion$ssCkEnd)>0,3,myFusion$ssEnd)
+ myFusion$ssEnd=ifelse(abs(myFusion$ssExEndGe)0,3,myFusion$ssStart)
+ #myFusion$ssStart=ifelse(abs(myFusion$ssCkStart)>0,3,myFusion$ssStart)
+ myFusion$ssStart=ifelse(abs(myFusion$ssExStartGe)0,]
+ myFusionTmp=myFusionTmp[myFusionTmp$ssEnd>0,]
+
+ rmID=which(myFusionTmp$ssEnd>=3 & myFusionTmp$ssStart>=3)
+ if (length(rmID)>0) myFusionTmp=myFusionTmp[-rmID,]
+
+ cat("\n\n Checking possible paralogs...")
+
+ #remove paralogs from database
+ rmID=unlist(lapply(c(1:nrow(myFusionTmp)), function(x){
+ par1=c(as.character(myFusionTmp$gene1[x]),geneParalog[which(geneParalog[,1]==as.character(myFusionTmp$gene1[x])),2])
+ par2=c(as.character(myFusionTmp$gene2[x]),geneParalog[which(geneParalog[,1]==as.character(myFusionTmp$gene2[x])),2])
+ if (length(par1)>0 & length(par2)>0) return(length(intersect(par1,par2))>0)
+ return(FALSE)
+ }))
+
+ myFusionTmp$paralog=rep(0,nrow(myFusionTmp))
+ myFusionTmp$paralog[rmID]=1
+ myFusionTmp=myFusionTmp[myFusionTmp$paralog==0,]
+
+
+ myFusionFinal=myFusionTmp
+ res=list(myFusionFinal=myFusionFinal,myFusion=myFusion,fusionGene=fusionGene, splitReads=splitReads,fragmentInfo=fragmentInfo,fragDist=fragDist,myFusionFP=myFusionFP)
+ return(res)
+}
+
+
+
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..be1d13d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,127 @@
+#####################################
+# Documents for FuSeq version 0.1.0
+#####################################
+
+## 1. Introduction
+FuSeq is a novel method to discover fusion genes from paired-end RNA sequencing data. We acknowledge for materials from Sailfish, Rapmap and other tools used in this software.
+
+Software requirements for FuSeq:
+- A C++-11 compliant compiler version of GCC (g++ >= 4.8.2)
+- R packages version 3.3.0 or latter with following installed packages: GenomicFeatures
+
+Annotation reference: FuSeq requires a fasta file of transcript sequences and a gtf file of transcript annotation. FuSeq supports the ensembl annotation version GRCh37.75 in the current version:
+- Download the sequences of transcripts: http://ftp.ensembl.org/pub/release-75/fasta/homo_sapiens/cdna/Homo_sapiens.GRCh37.75.cdna.all.fa.gz
+- Download the annotation of transcripts: http://ftp.ensembl.org/pub/release-75/gtf/homo_sapiens/Homo_sapiens.GRCh37.75.gtf.gz
+
+The latest version and information of FuSeq are updated at https://github.com/nghiavtr/FuSeq
+
+## 2. Download and installation
+If you use the binary verion of FuSeq:
+- Download the lastest binary version from FuSeq website: [FuSeq_v0.1.0_linux_x86-64](https://github.com/nghiavtr/FuSeq/releases/download/v0.1.0/FuSeq_v0.1.0_linux_x86-64.tar.gz)
+- Uncompress to folder
+```sh
+tar -xzvf FuSeq_v0.1.0_linux_x86-64.tar.gz
+```
+- Move to the *FuSeq_home* directory and do configuration for FuSeq
+```sh
+cd FuSeq_v0.1.0_linux_x86-64
+bash configure.sh
+```
+- Add paths of lib folder and bin folder to LD_LIBRARY_PATH and PATH
+```sh
+export LD_LIBRARY_PATH=/path/to/FuSeq_v0.1.0_linux_x86-64/linux/lib:$LD_LIBRARY_PATH
+export PATH=/path/to/FuSeq_v0.1.0_linux_x86-64/linux/bin:$PATH
+```
+If you want to build FuSeq from sources:
+- Download FuSeq from [FuSeq website](https://github.com/nghiavtr/FuSeq) and move to *FuSeq_home* directory
+```sh
+wget https://github.com/nghiavtr/FuSeq/archive/v0.1.0.tar.gz
+tar -xzvf v0.1.0.tar.gz
+cd FuSeq-0.1.0
+```
+- FuSeq requires information of flags from Sailfish including DFETCH_BOOST, DBOOST_ROOT, DTBB_INSTALL_DIR and DCMAKE_INSTALL_PREFIX. Please refer to the Sailfish website for more details of these flags.
+- Do installation by the following command:
+```sh
+DBOOST_ROOT=/path/to/boostDir/ DTBB_INSTALL_DIR=/path/to/tbbDir/ DCMAKE_INSTALL_PREFIX=/path/to/expectedBuildDir bash install.sh
+```
+-After the installation is finished, remember to add the paths of lib folder and bin folder to LD_LIBRARY_PATH and PATH
+```sh
+export LD_LIBRARY_PATH=/path/to/expectedBuildDir/lib:$LD_LIBRARY_PATH
+export PATH=/path/to/expectedBuildDir/bin:$PATH
+```
+
+### Do not forget to replace "/path/to/" by your local path.
+
+## 3. Index
+The command for indexing transcript fasta is similar to the indexing of sailfish and rapmap. For example:
+```sh
+TxIndexer -t /path/to/transcripts.fa -o TxIndexer_idx
+```
+#### K-mer length for a short-read RNA-seq
+In order to be able to capture split reads, the k-mer length must be less than a half of read length. Thus, the default k-mer length (31) of rapmap/sailfish is not proper for a short-read RNA-seq dataset, e.g 50 bp long. For the short-read RNA-seq dataset, we use k-mer length of 21 instead as the follow:
+```sh
+TxIndexer -t /path/to/transcripts.fa -k 21 -o TxIndexer_idx
+```
+
+
+## 4. Extract fusion equivalence classes and split reads
+This step requires a annotation file (gtf_file) in the gtf format to get the map between gene and transcript.
+- The command to generate fusion equivalence classes is similar to "sailfish quant". For example, we want to run FuSeq with 8 cpus:
+```sh
+FuSeq -i /path/to/TxIndexer_idx -l IU -1 read1.fasta -2 read2.fasta -p 8 -g /path/to/gtf_file -o /path/to/feqDir
+```
+- If the data is compressed in gz format. We can combine with gunzip for depressing on-fly:
+```sh
+FuSeq -i /path/to/TxIndexer_idx -l IU -1 <(gunzip -c read1.gz) -2 <(gunzip -c read2.gz) -p 8 -g /path/to/gtf_file -o /path/to/feqDir
+```
+## 5. Discover fusion genes
+FuSeq uses R scripts in *FuSeq_home/R* directory for this step. The transcript fasta (/path/to/transcripts.fa in the index step) and two additional files are required:
+- A sqlite file containing the annotation file created by using function makeTxDbFromGFF() of GenomicFeatures. We prepare simple R codes (createSqlite.R) to generate the sqlite file, for example:
+```sh
+Rscript FuSeq_home/R/createSqlite.R Homo_sapiens.GRCh37.75.gtf Homo_sapiens.GRCh37.75.sqlite
+```
+- A supporting annotation file containing information of paralogs, gene types, etc. For human Ensemble annotation version GRCh37.75, the file was prepared and available for download ([Homo_sapiens.GRCh37.75.txAnno.RData](https://github.com/nghiavtr/FuSeq/releases/download/v0.1.0/Homo_sapiens.GRCh37.75.txAnno.RData)). The similar files for other annotation versions are preparing and will be available soon.
+```sh
+ wget https://github.com/nghiavtr/FuSeq/releases/download/v0.1.0/Homo_sapiens.GRCh37.75.txAnno.RData -O Homo_sapiens.GRCh37.75.txAnno.RData
+```
+
+Now, we can use another R script to discover fusion genes.
+```sh
+Rscript FuSeq_home/R/FuSeq.R in=/path/to/feqDir txfasta=/path/to/transcripts.fa sqlite=/path/to/sqlite_file txanno=/path/to/txanno_file out=FuSeq_outDir params=/path/to/params_file
+```
+Herein, the settings for "params" and "out" are optional. If the params_file is not supplied, the default parameter setting will be used. Details about parameter setting are presented in next section. If FuSeq_outDir is not input, FuSeq will save the output into the same directory of the fusion equivalence classes (/path/to/feqDir).
+Since this step is usually fast, parallel is not implemented.
+
+### Output of FuSeq
+Fusion genes discovered by FuSeq are stored in a file named *fusions.fuseq* containing information of the fusion genes:
+- gene5,chrom5,strand5,gene5.start,gene5.end: information of gene at 5 prime including gene id. chromosome, strand, starting and ending of the fusion junction
+- gene3,chrom3,strand3,gene3.start,gene3.end: similar information but for gene at 3 prime
+- fusionName: names of fusion genes
+- supportRead: the number of reads supporting the fusion genes
+- score: score of each fusion genes from FuSeq
+- info: additional information of the fusion gene, for example constituent genes involve in mitochondrial translation, cytosolic ribosomal subunit and ribonucleoprotein.
+
+##### - If keepRData=TRUE is set in the *params_file*, all data generated during the FuSeq processes from will be saved in a *.RData file
+##### - If exportFasta=TRUE is set in the *params_file*, FuSeq will export fusion reads supporting fusion genes in two fasta files named *_fusionReads_1.fa and *_fusionReads_2.fa for read1 and read2, respectively.
+
+## 6. Parameter setting
+There are several parameters input for the pipeline. The default parameter setting is available at FuSeq_home/R/params.txt. Details of these parameters are refered to main publication, herein they are shortly described as the below:
+- readStrands (UN): indicates the directions of read1 and read2 depending on library type. There are a total of 5 types FF, FR, RF, RR, UN. "F" and "R" indicate forward and reverse complement directions, respectively. For example, if the libraries are prepared by TruSeq Stranded mRNA LT Sample Prep Kit where read1 is reverse complement and read2 is forward, a setting of readStrands=RF is suitable.The setting of readStrands=UN is used for unstranded sequencing data.
+- chromRef: limits the chromosomes contributing to fusion genes, we usually consider chromosomes 1:22,X and Y (chromRef=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y)
+- onlyProteinCodingGenes (TRUE): if users want to keep only fusion genes from protein-coding genes.
+- maxSharedCount (5e-2): the maximum proportion of sharing counts of a fusion gene.
+- minGeneDist (1e5): the minimum distance between two constituent genes.
+- minJunctionDist (1e5): the minimum junction distance of fusion gene.
+- maxInvertedFusionCount (0.01): the proportion of expression of inverted fusion.
+- maxMRfusionFc (2), maxMRfusionNum (2) and sgtMRcount (10): the parameter settings for fitlering multiple-fusion genes in the mapped read (MR) pipeline.
+- minMR (2), minNonDupMR (2): the minimum supporting count (non-duplicated supporting count) of a fusion gene in the mapped read pipeline.
+- minSR (1): the minimum supporting count of a fusion gene in the split read (SR) pipeline.
+- minScore (3): the minimum score of a fusion gene.
+- keepRData (FALSE): if users want to save all data generated during fusion gene discovery using Rscripts. If it is set keepRData=TRUE, a single *.RData file will be created to store the data.
+- exportFasta (FALSE): Set exportFasta=TRUE if users want to export sequences of fusion reads
+
+## 7. License
+FuSeq uses GNU General Public License GPL-3
+
+## 8. References
+(update later)
diff --git a/configure.sh b/configure.sh
new file mode 100644
index 0000000..f1068e9
--- /dev/null
+++ b/configure.sh
@@ -0,0 +1,7 @@
+#!/bin/bash -l
+##### Date:21/05/2017
+##### configure.sh: set the current path for loading R functions
+istr="/path/to"
+ostr="$PWD/R"
+eval "sed -i -e 's#"$istr"#"$ostr"#g' R/FuSeq.R"
+echo "Done!"
\ No newline at end of file
diff --git a/include/EmpiricalDistribution.hpp b/include/EmpiricalDistribution.hpp
new file mode 100644
index 0000000..33888e6
--- /dev/null
+++ b/include/EmpiricalDistribution.hpp
@@ -0,0 +1,96 @@
+/*
+Date:01/11/2016
+Note:This implementation is from Sailfish. We modified few parts to fit to our purposes.
+*/
+/**
+ * This implementation for keeping an empirical distribution and
+ * querying the PDF and CDF is taken (and ever-so-slightly-modified) from
+ * https://raw.githubusercontent.com/dcjones/isolator/master/src/emp_dist.hpp.
+ * The original author is Daniel C. Jones; NOT me (Rob Patro).
+ **/
+#ifndef EMPIRICAL_DISTRIBUTION_HPP
+#define EMPIRICAL_DISTRIBUTION_HPP
+
+#include
+#include
+#include
+
+
+class EmpiricalDistribution
+{
+ public:
+ EmpiricalDistribution(EmpiricalDistribution&);
+
+ /* Construct a emperical distribution from n observations stored in xs.
+ *
+ * Input in run-length encoded samples, which must be in sorted order.
+ *
+ * Args:
+ * vals: An array of unique observations.
+ * lens: Nuber of occurances for each observation.
+ * n: Length of vals and lens.
+ */
+ EmpiricalDistribution(const std::vector& vals,
+ const std::vector& count);
+
+
+ EmpiricalDistribution();
+
+ void buildDistribution( const std::vector& vals,
+ const std::vector& lens);
+
+ /* Compute the median of the distribution. */
+ float median() const;
+
+ /* Compute the mean of the distribution. */
+ float mean() const;
+
+ //for FuSeq
+ /* Compute the sd of the distribution. */
+ float sd() const;
+
+ //for FuSeq
+
+ /* Probability density function. */
+ float pdf(unsigned int x) const;
+
+ /* Comulative p robabability. */
+ float cdf(unsigned int x) const;
+
+ /* The minimum observed value. */
+ uint32_t minValue() const;
+
+ /* The maximum observed value. */
+ uint32_t maxValue() const;
+
+ /* True if there are observations and false otherwise */
+ bool valid() const;
+
+ /* Realize the distribution as a vector of counts, where
+ * numSamp samples are drawn from the underlying distribution
+ */
+ std::vector realize(uint32_t numSamp = 10000) const;
+
+ private:
+ std::vector pdfvals;
+ std::vector cdfvals;
+
+ /* Precomputed median */
+ float med;
+ /* Precomputed mean */
+ float mu;
+
+ //for FuSeq
+ /* Precomputed sd */
+ float sdval;
+ //for FuSeq
+
+ /* Min and Max Values */
+ uint32_t minVal;
+ uint32_t maxVal;
+ std::atomic isValid_{false};
+};
+
+
+
+#endif
diff --git a/include/EquivalenceClassFusionTxBuilder.hpp b/include/EquivalenceClassFusionTxBuilder.hpp
new file mode 100644
index 0000000..e6f854c
--- /dev/null
+++ b/include/EquivalenceClassFusionTxBuilder.hpp
@@ -0,0 +1,159 @@
+/*
+Date:01/11/2016
+Note:This implementation is adapted from EquivalenceClassBuilder.hpp of Sailfish for our purpose.
+*/
+
+#ifndef EQUIVALENCE_CLASS_FUSION_TX_BUILDER_HPP
+#define EQUIVALENCE_CLASS_FUSION_TX_BUILDER_HPP
+
+#include
+#include
+#include
+#include
+#include
+
+// Logger includes
+#include "spdlog/spdlog.h"
+
+#include "cuckoohash_map.hh"
+#include "concurrentqueue.h"
+#include "TranscriptGroup.hpp"
+
+
+struct TGFusionTxValue {
+ TGFusionTxValue(const TGFusionTxValue& o) {
+ weights = o.weights;
+ count.store(o.count.load());
+
+ minLeftReadPos.store(o.minLeftReadPos.load());
+ maxLeftReadPos.store(o.maxLeftReadPos.load());
+
+ minRightReadPos.store(o.minRightReadPos.load());
+ maxRightReadPos.store(o.maxRightReadPos.load());
+
+ }
+
+ TGFusionTxValue(std::vector& weightIn, uint64_t countIn, int32_t minLeftReadPosIn, int32_t maxLeftReadPosIn, int32_t minRightReadPosIn, int32_t maxRightReadPosIn) :
+ weights(weightIn) { count.store(countIn); minLeftReadPos.store(minLeftReadPosIn);maxLeftReadPos.store(maxLeftReadPosIn); minRightReadPos.store(minRightReadPosIn);maxRightReadPos.store(maxRightReadPosIn);}
+
+ // const is a lie
+ void normalizeAux() const {
+ double sumOfAux{0.0};
+ for (size_t i = 0; i < weights.size(); ++i) {
+ sumOfAux += weights[i];
+ }
+ double norm = 1.0 / sumOfAux;
+ for (size_t i = 0; i < weights.size(); ++i) {
+ weights[i] *= norm;
+ }
+ /* LOG SPACE
+ double sumOfAux = salmon::math::LOG_0;
+ for (size_t i = 0; i < weights.size(); ++i) {
+ sumOfAux = salmon::math::logAdd(sumOfAux, weights[i]);
+ }
+ for (size_t i = 0; i < weights.size(); ++i) {
+ weights[i] = std::exp(weights[i] - sumOfAux);
+ }
+ */
+ }
+
+ // forget synchronizing this for the time being
+ mutable std::vector weights;
+ std::atomic count{0};
+ std::atomic minLeftReadPos{2147483646};
+ std::atomic maxLeftReadPos{0};
+
+ std::atomic minRightReadPos{2147483646};
+ std::atomic maxRightReadPos{0};
+
+};
+
+class EquivalenceClassFusionTxBuilder {
+ public:
+ EquivalenceClassFusionTxBuilder(std::shared_ptr loggerIn) :
+ logger_(loggerIn) {
+ countMap_.reserve(1000000);
+ }
+
+ ~EquivalenceClassFusionTxBuilder() {}
+
+ void start() { active_ = true; }
+
+ bool finish() {
+ active_ = false;
+ size_t totalCount{0};
+ auto lt = countMap_.lock_table();
+ for (auto& kv : lt) {
+ //for (auto kv = countMap_.begin(); !kv.is_end(); ++kv) {
+ kv.second.normalizeAux();
+ totalCount += kv.second.count;
+ countVec_.push_back(kv);
+ }
+
+ logger_->info("Computed {} rich equivalence classes "
+ "for further processing", countVec_.size());
+ logger_->info("Counted {} total reads in the equivalence classes ",
+ totalCount);
+ return true;
+ }
+
+ inline void insertGroup(TranscriptGroup g, uint32_t count, int32_t minLeftReadPos, int32_t maxLeftReadPos, int32_t minRightReadPos, int32_t maxRightReadPos) {
+ std::vector weights(g.txps.size(), 0.0);
+ //auto updatefn = [count](TGFusionTxValue& x) { x.count = count; };
+ TGFusionTxValue v(weights, count, minLeftReadPos, maxLeftReadPos, minRightReadPos, maxRightReadPos);
+ countVec_.push_back(std::make_pair(g, v));
+ //countMap_.upsert(g, updatefn, v);
+ }
+
+ inline void addGroup(TranscriptGroup&& g,
+ std::vector& weights, int32_t leftReadPos, int32_t rightReadPos) {
+
+ auto upfn = [&weights, &leftReadPos, &rightReadPos](TGFusionTxValue& x) -> void {
+ // update the count
+ x.count++;
+ // update the weights
+ for (size_t i = 0; i < x.weights.size(); ++i) {
+ // Possibly atomicized in the future
+ weights[i] += x.weights[i];
+ /* LOG SPACE
+ x.weights[i] =
+ salmon::math::logAdd(x.weights[i], weights[i]);
+ */
+ }
+ //update minPos and maxPos of the left
+ int32_t old_minLeft = x.minLeftReadPos.load();
+ while(old_minLeft > leftReadPos &&
+ x.minLeftReadPos.compare_exchange_weak(old_minLeft, leftReadPos));
+
+ int32_t old_maxLeft = x.maxLeftReadPos.load();
+ while(old_maxLeft < leftReadPos &&
+ !x.maxLeftReadPos.compare_exchange_weak(old_maxLeft, leftReadPos));
+
+
+ //update minPos and maxPos of the right
+ int32_t old_minRight = x.minRightReadPos.load();
+ while(old_minRight > rightReadPos &&
+ x.minRightReadPos.compare_exchange_weak(old_minRight, rightReadPos));
+
+ int32_t old_maxRight = x.maxRightReadPos.load();
+ while(old_maxRight < rightReadPos &&
+ !x.maxRightReadPos.compare_exchange_weak(old_maxRight, rightReadPos));
+
+
+ };
+ TGFusionTxValue v(weights, 1, leftReadPos, leftReadPos+1, rightReadPos, rightReadPos+1);
+ countMap_.upsert(g, upfn, v);
+ }
+
+ std::vector>& eqVec() {
+ return countVec_;
+ }
+
+ private:
+ std::atomic active_;
+ cuckoohash_map countMap_;
+ std::vector> countVec_;
+ std::shared_ptr logger_;
+};
+
+#endif // EQUIVALENCE_CLASS_FUSION_BUILDER_HPP
diff --git a/include/ExportFeq.hpp b/include/ExportFeq.hpp
new file mode 100644
index 0000000..508add9
--- /dev/null
+++ b/include/ExportFeq.hpp
@@ -0,0 +1,44 @@
+/*
+Date:01/11/2016
+Note:This implementation is adapted from CollapsedEMOptimizer.hpp of Sailfish for our purpose.
+*/
+
+#ifndef EXPORT_FEQ_HPP
+#define EXPORT_FEQ_HPP
+
+#include
+#include
+#include
+
+#include "tbb/atomic.h"
+#include "tbb/task_scheduler_init.h"
+
+#include "ReadExperiment.hpp"
+#include "SailfishOpts.hpp"
+
+#include "cuckoohash_map.hh"
+#include "Eigen/Dense"
+
+//for FuSeq
+#include
+#include
+#include
+#include
+//for FuSeq
+
+
+//class BootstrapWriter;
+
+class ExportFeq {
+ public:
+ ExportFeq();
+
+ bool writeFeq(ReadExperiment& readExp,
+ SailfishOpts& sopt,
+ const boost::filesystem::path& feqOutputPath = "/" //for FuSeq
+ );
+
+};
+
+#endif // EXPORT_FEQ_HPP
+
diff --git a/include/ReadExperiment.hpp b/include/ReadExperiment.hpp
new file mode 100644
index 0000000..03db560
--- /dev/null
+++ b/include/ReadExperiment.hpp
@@ -0,0 +1,379 @@
+/*
+Date:01/11/2016
+Note:This implementation is from Sailfish. We modified few parts to fit to our purposes.
+*/
+
+#ifndef EXPERIMENT_HPP
+#define EXPERIMENT_HPP
+
+// Our includes
+#include "Transcript.hpp"
+#include "ReadLibrary.hpp"
+//#include "FragmentLengthDistribution.hpp"
+//#include "SequenceBiasModel.hpp"
+#include "SailfishOpts.hpp"
+#include "SailfishIndex.hpp"
+#include "EquivalenceClassBuilder.hpp"
+
+//for FuSeq
+#include "EquivalenceClassFusionTxBuilder.hpp"
+//for FuSeq
+
+// Logger includes
+#include "spdlog/spdlog.h"
+
+// Boost includes
+#include
+#include
+
+// Standard includes
+#include
+#include
+#include
+#include
+
+#include "UtilityFunctions.hpp"
+#include "ReadKmerDist.hpp"
+#include "EmpiricalDistribution.hpp"
+#include "TranscriptGeneMap.hpp"
+
+/**
+ * This class represents a library of reads used to quantify
+ * a set of target transcripts.
+ */
+class ReadExperiment {
+
+ public:
+
+ ReadExperiment(std::vector& readLibraries,
+ const boost::filesystem::path& indexDirectory,
+ SailfishOpts& sopt) :
+ readLibraries_(readLibraries),
+ transcripts_(std::vector()),
+ eqBuilder_(sopt.jointLog),
+ //for FuSeq
+ eqFusionTxBuilder_(sopt.jointLog),
+ eqFusionTxBuilderRR_(sopt.jointLog),
+ eqFusionTxBuilderFF_(sopt.jointLog),
+ eqFusionTxBuilderRF_(sopt.jointLog),
+ eqFusionTxBuilderFR_(sopt.jointLog),
+
+ feqBuilder_(sopt.jointLog),
+ feqBuilderRR_(sopt.jointLog),
+ feqBuilderRF_(sopt.jointLog),
+ feqBuilderFF_(sopt.jointLog),
+ feqBuilderFR_(sopt.jointLog),
+ feqBuilderUN_(sopt.jointLog),
+ //for FuSeq
+ expectedSeqBias_(constExprPow(4, readBias_.getK()), 1.0),
+ expectedGC_(101, 1.0),
+ observedGC_(101) {
+ namespace bfs = boost::filesystem;
+
+ // pseudocount for the observed distribution
+ for (size_t i = 0; i < observedGC_.size(); ++i) { observedGC_[i] += 1; }
+
+ // Make sure the read libraries are valid.
+ for (auto& rl : readLibraries_) { rl.checkValid(); }
+
+ size_t maxFragLen = sopt.fragLenDistMax;
+ size_t meanFragLen = sopt.fragLenDistPriorMean;
+ size_t fragLenStd = sopt.fragLenDistPriorSD;
+
+ sfIndex_.reset(new SailfishIndex(sopt.jointLog));
+ sfIndex_->load(indexDirectory);
+ loadTranscriptsFromQuasi(sopt);
+ }
+
+ EquivalenceClassBuilder& equivalenceClassBuilder() {
+ return eqBuilder_;
+ }
+
+ //for FuSeq
+ EquivalenceClassFusionTxBuilder& equivalenceFusionTxClassBuilder() {
+ return eqFusionTxBuilder_;
+ }
+
+ uint32_t getReadLength() {
+ return inputreadLen_;
+ }
+ void setReadLength(uint32_t inputreadLenIn) {
+ inputreadLen_ = inputreadLenIn;
+ }
+
+ void setTranscriptGeneMap(TranscriptGeneMap tranGeneMapIn) {
+ tranGeneMap_ = tranGeneMapIn;
+ }
+ TranscriptGeneMap& getTranscriptGeneMap(){
+ return tranGeneMap_;
+ }
+
+ bool getExistTranGeneMap() {
+ return existTranGeneMap_;
+ }
+ void setExistTranGeneMap(bool existTranGeneMapIn) {
+ existTranGeneMap_ = existTranGeneMapIn;
+ }
+
+
+
+
+ EquivalenceClassFusionTxBuilder& equivalenceFusionTxClassBuilderRR() {
+ return eqFusionTxBuilderRR_;
+ }
+ EquivalenceClassFusionTxBuilder& equivalenceFusionTxClassBuilderFF() {
+ return eqFusionTxBuilderFF_;
+ }
+ EquivalenceClassFusionTxBuilder& equivalenceFusionTxClassBuilderRF() {
+ return eqFusionTxBuilderRF_;
+ }
+ EquivalenceClassFusionTxBuilder& equivalenceFusionTxClassBuilderFR() {
+ return eqFusionTxBuilderFR_;
+ }
+
+ EquivalenceClassBuilder& feqClassBuilder() {
+ return feqBuilder_;
+ }
+ EquivalenceClassBuilder& feqClassBuilderRR() {
+ return feqBuilderRR_;
+ }
+ EquivalenceClassBuilder& feqClassBuilderRF() {
+ return feqBuilderRF_;
+ }
+ EquivalenceClassBuilder& feqClassBuilderFF() {
+ return feqBuilderFF_;
+ }
+ EquivalenceClassBuilder& feqClassBuilderFR() {
+ return feqBuilderFR_;
+ }
+ EquivalenceClassBuilder& feqClassBuilderUN() {
+ return feqBuilderUN_;
+ }
+
+
+
+ //for FuSeq
+
+
+ std::vector& transcripts() { return transcripts_; }
+
+ const std::vector& transcripts() const { return transcripts_; }
+
+ uint64_t numFragHits() { return numFragHits_; }
+ std::atomic& numFragHitsAtomic() { return numFragHits_; }
+
+ uint64_t numMappedFragments() const { return numMappedFragments_; }
+
+ uint64_t upperBoundHits() { return upperBoundHits_; }
+ std::atomic& upperBoundHitsAtomic() { return upperBoundHits_; }
+ void setUpperBoundHits(uint64_t ubh) { upperBoundHits_.store(ubh); }
+
+ uint64_t numObservedFragments() const { return numObservedFragments_; }
+ std::atomic& numObservedFragmentsAtomic() { return numObservedFragments_; }
+
+ std::atomic& numMappedFragmentsAtomic() { return numMappedFragments_; }
+
+ void setNumObservedFragments(uint64_t numObserved) { numObservedFragments_ = numObserved; }
+
+ double mappingRate() const {
+ return static_cast(numMappedFragments_) / numObservedFragments_;
+ }
+
+ void addNumFwd(int32_t numMappings) { numFwd_ += numMappings; }
+ void addNumRC(int32_t numMappings) { numRC_ += numMappings; }
+
+ int64_t numFwd() const { return numFwd_.load(); }
+ int64_t numRC() const { return numRC_.load(); }
+
+ SailfishIndex* getIndex() { return sfIndex_.get(); }
+
+ template
+ void loadTranscriptsFromQuasiIndex(IndexT* idx_, const SailfishOpts& sopt) {
+ size_t numRecords = idx_->txpNames.size();
+
+ fmt::print(stderr, "Index contained {} targets\n", numRecords);
+ double alpha = 0.005;
+ for (auto i : boost::irange(size_t(0), numRecords)) {
+ uint32_t id = i;
+ const char* name = idx_->txpNames[i].c_str();
+ uint32_t len = idx_->txpLens[i];
+ // copy over the length, then we're done.
+ transcripts_.emplace_back(id, name, len);
+ auto& txp = transcripts_.back();
+ // The transcript sequence
+ txp.setSequence(idx_->seq.c_str() + idx_->txpOffsets[i],
+ sopt.gcBiasCorrect, sopt.gcSampFactor);
+ }
+ // ====== Done loading the transcripts from file
+ fmt::print(stderr, "Loaded targets\n");
+ }
+
+ void loadTranscriptsFromQuasi(const SailfishOpts& sopt) {
+ if (sfIndex_->is64BitQuasi()) {
+ if (sfIndex_->isPerfectHashQuasi()) {
+ loadTranscriptsFromQuasiIndex>>
+ (sfIndex_->quasiIndexPerfectHash64(), sopt);
+ } else {
+ loadTranscriptsFromQuasiIndex>>
+ (sfIndex_->quasiIndex64(), sopt);
+ }
+ } else { // 32-bit
+ if (sfIndex_->isPerfectHashQuasi()) {
+ loadTranscriptsFromQuasiIndex>>
+ (sfIndex_->quasiIndexPerfectHash32(), sopt);
+ } else {
+ loadTranscriptsFromQuasiIndex>>
+ (sfIndex_->quasiIndex32(), sopt);
+ }
+ }
+ }
+
+ std::string readFilesAsString() {
+ std::stringstream sstr;
+ size_t ln{0};
+ size_t numReadLibraries{readLibraries_.size()};
+
+ for (auto &rl : readLibraries_) {
+ sstr << rl.readFilesAsString();
+ if (ln++ < numReadLibraries) { sstr << "; "; }
+ }
+ return sstr.str();
+ }
+
+ double effectiveMappingRate() {
+ return effectiveMappingRate_;
+ }
+
+ void setEffetiveMappingRate(double emr) {
+ effectiveMappingRate_ = emr;
+ }
+ /*
+ SequenceBiasModel& sequenceBiasModel() {
+ return seqBiasModel_;
+ }
+ */
+
+ std::vector& readLibraries() { return readLibraries_; }
+ //FragmentLengthDistribution* fragmentLengthDistribution() { return fragLengthDist_.get(); }
+
+ void setFragLengthDist(const std::vector& fldIn) {
+ // vector of positions
+ std::vector pos(fldIn.size());
+ std::iota(pos.begin(), pos.end(), 0);
+ // vector of counts
+ std::vector counts(fldIn.begin(), fldIn.end());
+ fld_.reset(new EmpiricalDistribution(pos, counts));
+ }
+
+ EmpiricalDistribution* fragLengthDist() {
+ return fld_.get();
+ }
+
+ const EmpiricalDistribution* fragLengthDist() const {
+ return fld_.get();
+ }
+
+
+ void setExpectedSeqBias(const std::vector& expectedBiasIn) {
+ expectedSeqBias_ = expectedBiasIn;
+ }
+
+ std::vector& expectedSeqBias() {
+ return expectedSeqBias_;
+ }
+
+ const std::vector& expectedSeqBias() const {
+ return expectedSeqBias_;
+ }
+
+ void setExpectedGCBias(const std::vector& expectedBiasIn) {
+ expectedGC_ = expectedBiasIn;
+ }
+
+ std::vector& expectedGCBias() {
+ return expectedGC_;
+ }
+
+ const std::vector& expectedGCBias() const {
+ return expectedGC_;
+ }
+
+ const std::vector>& observedGC() const {
+ return observedGC_;
+ }
+
+ std::vector>& observedGC() {
+ return observedGC_;
+ }
+
+ //S_AYUSH_CODE
+ ReadKmerDist<6, std::atomic>& readBias() { return readBias_; }
+ const ReadKmerDist<6, std::atomic>& readBias() const { return readBias_; }
+ //T_AYUSH_CODE
+
+ private:
+ /**
+ * The file from which the alignments will be read.
+ * This can be a SAM or BAM file, and can be a regular
+ * file or a fifo.
+ */
+ std::vector readLibraries_;
+ /**
+ * The targets (transcripts) to be quantified.
+ */
+ std::vector transcripts_;
+ /**
+ * The index we've built on the set of transcripts.
+ */
+ std::unique_ptr sfIndex_{nullptr};
+
+ //SequenceBiasModel seqBiasModel_;
+
+ /** Keeps track of the number of passes that have been
+ * made through the alignment file.
+ */
+ std::atomic numObservedFragments_{0};
+ std::atomic numMappedFragments_{0};
+ std::atomic numFragHits_{0};
+ std::atomic upperBoundHits_{0};
+ std::atomic numFwd_{0};
+ std::atomic numRC_{0};
+ double effectiveMappingRate_{0.0};
+ //std::unique_ptr fragLengthDist_;
+ EquivalenceClassBuilder eqBuilder_;
+
+ //for FuSeq
+ EquivalenceClassFusionTxBuilder eqFusionTxBuilder_;
+ uint32_t inputreadLen_{0};
+ EquivalenceClassFusionTxBuilder eqFusionTxBuilderRR_;
+ EquivalenceClassFusionTxBuilder eqFusionTxBuilderFF_;
+ EquivalenceClassFusionTxBuilder eqFusionTxBuilderRF_;
+ EquivalenceClassFusionTxBuilder eqFusionTxBuilderFR_;
+
+ EquivalenceClassBuilder feqBuilder_;
+ EquivalenceClassBuilder feqBuilderRR_;
+ EquivalenceClassBuilder feqBuilderFF_;
+ EquivalenceClassBuilder feqBuilderRF_;
+ EquivalenceClassBuilder feqBuilderFR_;
+ EquivalenceClassBuilder feqBuilderUN_;
+
+ TranscriptGeneMap tranGeneMap_;
+ bool existTranGeneMap_{false};
+
+ //for FuSeq
+
+ //S_AYUSH_CODE
+ // Since multiple threads can touch this dist, we
+ // need atomic counters.
+ ReadKmerDist<6, std::atomic> readBias_;
+ std::vector expectedSeqBias_;
+ //T_AYUSH_CODE
+
+ // One bin for each percentage GC content
+ std::vector> observedGC_;
+ std::vector expectedGC_;
+
+ std::unique_ptr fld_;
+};
+
+#endif // EXPERIMENT_HPP
diff --git a/include/SACollectorFuSeq.hpp b/include/SACollectorFuSeq.hpp
new file mode 100644
index 0000000..f5edf07
--- /dev/null
+++ b/include/SACollectorFuSeq.hpp
@@ -0,0 +1,588 @@
+/*
+Date:17/03/2017
+Note:This implementation is adapted from SACollector.hpp of Rapmap for our purpose.
+*/
+
+#ifndef SA_COLLECTOR_FUSEQ_HPP
+#define SA_COLLECTOR_FUSEQ_HPP
+
+#include "RapMapUtils.hpp"
+#include "RapMapSAIndex.hpp"
+#include "SASearcher.hpp"
+
+#include
+#include
+#include
+
+template
+class SACollectorFuSeq {
+ public:
+ using OffsetT = typename RapMapIndexT::IndexType;
+ using SAIntervalHit = rapmap::utils::SAIntervalHit;
+
+ SACollectorFuSeq(RapMapIndexT* rmi) : rmi_(rmi) {}
+ bool operator()(std::string& read,
+ std::vector& hits,
+ std::vector &fwdSAInts,
+ std::vector &rcSAInts,
+ SASearcher& saSearcher,
+ rapmap::utils::MateStatus mateStatus,
+ bool strictCheck=false,
+ bool consistentHits=false) {
+
+ using QuasiAlignment = rapmap::utils::QuasiAlignment;
+ using MateStatus = rapmap::utils::MateStatus;
+
+ //auto& posIDs = rmi_->positionIDs;
+ auto& rankDict = rmi_->rankDict;
+ auto& txpStarts = rmi_->txpOffsets;
+ auto& SA = rmi_->SA;
+ auto& khash = rmi_->khash;
+ auto& text = rmi_->seq;
+ uint32_t sampFactor{1};
+ auto salen = SA.size();
+
+ auto readLen = read.length();
+ auto maxDist = 1.5 * readLen;
+ auto k = rapmap::utils::my_mer::k();
+ auto readStartIt = read.begin();
+ auto readEndIt = read.end();
+
+ auto readRevStartIt = read.rbegin();
+ auto readRevEndIt = read.rend();
+
+ auto rb = read.begin();
+ auto re = rb + k;
+ OffsetT lbLeftFwd = 0, ubLeftFwd = 0;
+ OffsetT lbLeftRC = 0, ubLeftRC = 0;
+ OffsetT lbRightFwd = 0, ubRightFwd = 0;
+ OffsetT lbRightRC = 0, ubRightRC = 0;
+ OffsetT matchedLen;
+
+ uint32_t fwdHit{0};
+ uint32_t rcHit{0};
+
+ bool foundHit = false;
+ bool isRev = false;
+ rapmap::utils::my_mer mer;
+ rapmap::utils::my_mer rcMer;
+
+ enum HitStatus { ABSENT = -1, UNTESTED = 0, PRESENT = 1 };
+ // Record if k-mers are hits in the
+ // fwd direction, rc direction or both
+ struct KmerDirScore {
+ KmerDirScore(rapmap::utils::my_mer kmerIn, int32_t kposIn, HitStatus fwdScoreIn, HitStatus rcScoreIn) :
+ kmer(kmerIn), kpos(kposIn), fwdScore(fwdScoreIn), rcScore(rcScoreIn) {}
+ KmerDirScore() : kpos(0), fwdScore(UNTESTED), rcScore(UNTESTED) {}
+ bool operator==(const KmerDirScore& other) const { return kpos == other.kpos; }
+ bool operator<(const KmerDirScore& other) const { return kpos < other.kpos; }
+ void print() {
+ std::cerr << "{ " << kmer.to_str() << ", " << kpos << ", " << ((fwdScore) ? "PRESENT" : "ABSENT") << ", " << ((rcScore) ? "PRESENT" : "ABSENT") << "}\t";
+ }
+ rapmap::utils::my_mer kmer;
+ int32_t kpos;
+ HitStatus fwdScore;
+ HitStatus rcScore;
+ };
+
+ // This allows implementing our heurisic for comparing
+ // forward and reverse-complement strand matches
+ std::vector kmerScores;
+
+// using SAIntervalHit = rapmap::utils::SAIntervalHit;
+
+// std::vector fwdSAInts;
+// std::vector rcSAInts;
+
+ std::vector leftTxps, leftTxpsRC;
+ std::vector rightTxps, rightTxpsRC;
+ OffsetT maxInterval{1000};
+
+ // The number of bases that a new query position (to which
+ // we skipped) should overlap the previous extension. A
+ // value of 0 means no overlap (the new search begins at the next
+ // base) while a value of (k - 1) means that k-1 bases (one less than
+ // the k-mer size) must overlap.
+ OffsetT skipOverlap = k-1;
+ // Number of nucleotides to skip when encountering a homopolymer k-mer.
+ OffsetT homoPolymerSkip = k/2;
+
+ // Find a hit within the read
+ // While we haven't fallen off the end
+ while (re < read.end()) {
+
+ // Get the k-mer at the current start position.
+ // And make sure that it's valid (contains no Ns).
+ auto pos = std::distance(readStartIt, rb);
+ auto invalidPos = read.find_first_of("nN", pos);
+ if (invalidPos <= pos + k) {
+ rb = read.begin() + invalidPos + 1;
+ re = rb + k;
+ continue;
+ }
+
+ // If the next k-bases are valid, get the k-mer and
+ // reverse complement k-mer
+ mer = rapmap::utils::my_mer(read.c_str() + pos);
+ if (mer.is_homopolymer()) { rb += homoPolymerSkip; re += homoPolymerSkip; continue; }
+ rcMer = mer.get_reverse_complement();
+
+ // See if we can find this k-mer in the hash
+ auto merIt = khash.find(mer.get_bits(0, 2*k));
+ auto rcMerIt = khash.find(rcMer.get_bits(0, 2*k));
+
+ // If we can find the k-mer in the hash, get its SA interval
+ if (merIt != khash.end()) {
+ OffsetT lb = merIt->second.begin;
+ OffsetT ub = merIt->second.end;
+
+ // lb must be 1 *less* then the current lb
+ auto lbRestart = std::max(static_cast(0), lb-1);
+ // Extend the SA interval using the read sequence as far as
+ // possible
+ std::tie(lbLeftFwd, ubLeftFwd, matchedLen) =
+ saSearcher.extendSearchNaive(lbRestart, ub, k, rb, readEndIt);
+
+ // If the SA interval is valid, and not too wide, then record
+ // the hit.
+ OffsetT diff = ubLeftFwd - lbLeftFwd;
+ if (ubLeftFwd > lbLeftFwd and diff < maxInterval) {
+ auto queryStart = std::distance(read.begin(), rb);
+ fwdSAInts.emplace_back(lbLeftFwd, ubLeftFwd, matchedLen, queryStart, false);
+ if (strictCheck) {
+ ++fwdHit;
+ // If we also match this k-mer in the rc direction
+ if (rcMerIt != khash.end()) {
+ ++rcHit;
+ kmerScores.emplace_back(mer, pos, PRESENT, PRESENT);
+ } else { // Otherwise it doesn't match in the rc direction
+ kmerScores.emplace_back(mer, pos, PRESENT, ABSENT);
+ }
+
+ // If we didn't end the match b/c we exhausted the query
+ // test the mismatching k-mer in the other strand
+ // TODO: check for 'N'?
+ if (rb + matchedLen < readEndIt){
+ auto kmerPos = std::distance(readStartIt, rb + matchedLen - skipOverlap);
+ mer = rapmap::utils::my_mer(read.c_str() + kmerPos);
+ kmerScores.emplace_back(mer, kmerPos, ABSENT, UNTESTED);
+ }
+ } else { // no strict check
+ ++fwdHit;
+ if (rcMerIt != khash.end()) { ++rcHit; }
+ }
+ }
+ }
+
+ // See if the reverse complement k-mer is in the hash
+ if (rcMerIt != khash.end()) {
+ lbLeftRC = rcMerIt->second.begin;
+ ubLeftRC = rcMerIt->second.end;
+ OffsetT diff = ubLeftRC - lbLeftRC;
+ if (ubLeftRC > lbLeftRC) {
+ // The original k-mer didn't match in the foward direction
+ if (!fwdHit) {
+ ++rcHit;
+ if (strictCheck) {
+ kmerScores.emplace_back(mer, pos, ABSENT, PRESENT);
+ }
+ }
+ }
+ }
+
+ // If we had a hit with either k-mer then we can
+ // break out of this loop to look for the next informative position
+ if (fwdHit + rcHit > 0) {
+ foundHit = true;
+ break;
+ }
+ ++rb; ++re;
+ }
+
+ // If we went the entire length of the read without finding a hit
+ // then we can bail.
+ if (!foundHit) { return false; }
+
+ bool lastSearch{false};
+ // If we had a hit on the forward strand
+ if (fwdHit) {
+
+ // The length of this match
+ auto matchLen = fwdSAInts.front().len;
+ // The iterator to where this match began
+ rb = read.begin() + fwdSAInts.front().queryPos;
+
+ // [lb, ub) is the suffix array interval for the MMP (maximum mappable prefix)
+ // of the k-mer we found. The NIP (next informative position) in the sequence
+ // is the position after the LCE (longest common extension) of
+ // T[SA[lb]:] and T[SA[ub-1]:]
+ auto remainingLength = std::distance(rb + matchLen, readEndIt);
+ auto lce = saSearcher.lce(lbLeftFwd, ubLeftFwd-1, matchLen, remainingLength);
+ auto fwdSkip = std::max(static_cast(matchLen) - skipOverlap,
+ static_cast(lce) - skipOverlap);
+
+ size_t nextInformativePosition = std::min(
+ std::max(static_cast(0),
+ static_cast(readLen)- static_cast(k)),
+ static_cast(std::distance(readStartIt, rb) + fwdSkip)
+ );
+
+ rb = read.begin() + nextInformativePosition;
+ re = rb + k;
+
+ size_t invalidPos{0};
+ while (re <= readEndIt) {
+ // The offset into the string
+ auto pos = std::distance(readStartIt, rb);
+
+ // The position of the first N in the k-mer (if there is one)
+ // If we have already verified there are no Ns in the remainder
+ // of the string (invalidPos is std::string::npos) then we can
+ // skip this test.
+ if (invalidPos != std::string::npos) {
+ invalidPos = read.find_first_of("nN", pos);
+ }
+
+ // If the first N is within k bases, then this k-mer is invalid
+ if (invalidPos < pos + k) {
+ // A valid k-mer can't start until after the 'N'
+ nextInformativePosition = invalidPos + 1;
+ rb = read.begin() + nextInformativePosition;
+ re = rb + k;
+ // Go to the next iteration of the while loop
+ continue;
+ }
+
+ // If the current end position is valid
+ if (re <= readEndIt) {
+
+ mer = rapmap::utils::my_mer(read.c_str() + pos);
+ if (mer.is_homopolymer()) { rb += homoPolymerSkip; re = rb + k; continue; }
+ auto merIt = khash.find(mer.get_bits(0, 2*k));
+
+ if (merIt != khash.end()) {
+ if (strictCheck) {
+ ++fwdHit;
+ kmerScores.emplace_back(mer, pos, PRESENT, UNTESTED);
+ auto rcMer = mer.get_reverse_complement();
+ auto rcMerIt = khash.find(rcMer.get_bits(0, 2*k));
+ if (rcMerIt != khash.end()) {
+ ++rcHit;
+ kmerScores.back().rcScore = PRESENT;
+ }
+ }
+
+ lbRightFwd = merIt->second.begin;
+ ubRightFwd = merIt->second.end;
+
+ // lb must be 1 *less* then the current lb
+ lbRightFwd = std::max(static_cast(0), lbRightFwd - 1);
+ std::tie(lbRightFwd, ubRightFwd, matchedLen) =
+ saSearcher.extendSearchNaive(lbRightFwd, ubRightFwd,
+ k, rb, readEndIt);
+
+ OffsetT diff = ubRightFwd - lbRightFwd;
+ if (ubRightFwd > lbRightFwd and diff < maxInterval) {
+ auto queryStart = std::distance(read.begin(), rb);
+ fwdSAInts.emplace_back(lbRightFwd, ubRightFwd, matchedLen, queryStart, false);
+ // If we didn't end the match b/c we exhausted the query
+ // test the mismatching k-mer in the other strand
+ // TODO: check for 'N'?
+ if (strictCheck and rb + matchedLen < readEndIt){
+ auto kmerPos = std::distance(readStartIt, rb + matchedLen - skipOverlap);
+ mer = rapmap::utils::my_mer(read.c_str() + kmerPos);
+ // TODO: 04/11/16
+ kmerScores.emplace_back(mer, kmerPos, UNTESTED, UNTESTED);
+ }
+
+ }
+
+ if (lastSearch) { break; }
+ auto mismatchIt = rb + matchedLen;
+ if (mismatchIt < readEndIt) {
+ auto remainingDistance = std::distance(mismatchIt, readEndIt);
+ auto lce = saSearcher.lce(lbRightFwd, ubRightFwd-1, matchedLen, remainingDistance);
+
+ // Where we would jump if we just used the MMP
+ auto skipMatch = mismatchIt - skipOverlap;
+ // Where we would jump if we used the LCE
+ auto skipLCE = rb + lce - skipOverlap;
+ // Pick the larger of the two
+ rb = std::max(skipLCE, skipMatch);
+ if (rb > (readEndIt - k)) {
+ rb = readEndIt - k;
+ lastSearch = true;
+ }
+ re = rb + k;
+ } else {
+ lastSearch = true;
+ rb = readEndIt - k;
+ re = rb + k;
+ }
+
+ } else {
+ rb += sampFactor;
+ re = rb + k;
+ }
+ }
+ }
+ }
+
+ lastSearch = false;
+ if (rcHit >= fwdHit) {
+ size_t pos{read.length() - k};
+
+ auto revReadEndIt = read.rend();
+
+ auto revRB = read.rbegin();
+ auto revRE = revRB + k;
+
+ auto invalidPosIt = revRB;
+ while (revRE <= revReadEndIt){
+
+ revRE = revRB + k;
+ if (revRE > revReadEndIt) { break; }
+
+ // See if this k-mer would contain an N
+ // only check if we don't yet know that there are no remaining
+ // Ns
+ if (invalidPosIt != revReadEndIt) {
+ invalidPosIt = std::find_if(revRB, revRE,
+ [](const char c) -> bool {
+ return c == 'n' or c == 'N';
+ });
+ }
+
+ // If we found an N before the end of the k-mer
+ if (invalidPosIt < revRE) {
+ // Skip to the k-mer starting at the next position
+ // (i.e. right past the N)
+ revRB = invalidPosIt + 1;
+ continue;
+ }
+
+ // The distance from the beginning of the read to the
+ // start of the k-mer
+ pos = std::distance(revRE, revReadEndIt);
+
+ // Get the k-mer and query it in the hash
+ mer = rapmap::utils::my_mer(read.c_str() + pos);
+ if (mer.is_homopolymer()) { revRB += homoPolymerSkip; revRE += homoPolymerSkip; continue; }
+ rcMer = mer.get_reverse_complement();
+ auto rcMerIt = khash.find(rcMer.get_bits(0, 2*k));
+
+ // If we found the k-mer
+ if (rcMerIt != khash.end()) {
+ if (strictCheck) {
+ ++rcHit;
+ kmerScores.emplace_back(mer, pos, UNTESTED, PRESENT);
+ auto merIt = khash.find(mer.get_bits(0, 2*k));
+ if (merIt != khash.end()) {
+ ++fwdHit;
+ kmerScores.back().fwdScore = PRESENT;
+ }
+ }
+
+
+ lbRightRC = rcMerIt->second.begin;
+ ubRightRC = rcMerIt->second.end;
+
+ // lb must be 1 *less* then the current lb
+ // We can't move any further in the reverse complement direction
+ lbRightRC = std::max(static_cast(0), lbRightRC - 1);
+ std::tie(lbRightRC, ubRightRC, matchedLen) =
+ saSearcher.extendSearchNaive(lbRightRC, ubRightRC, k,
+ revRB, revReadEndIt, true);
+
+ OffsetT diff = ubRightRC - lbRightRC;
+ if (ubRightRC > lbRightRC and diff < maxInterval) {
+ auto queryStart = std::distance(read.rbegin(), revRB);
+ rcSAInts.emplace_back(lbRightRC, ubRightRC, matchedLen, queryStart, true);
+ // If we didn't end the match b/c we exhausted the query
+ // test the mismatching k-mer in the other strand
+ // TODO: check for 'N'?
+ if (strictCheck and revRB + matchedLen < revReadEndIt){
+ auto kmerPos = std::distance(revRB + matchedLen, revReadEndIt);
+ mer = rapmap::utils::my_mer(read.c_str() + kmerPos);
+ // TODO: 04/11/16
+ kmerScores.emplace_back(mer, kmerPos, UNTESTED, UNTESTED);
+ }
+ }
+
+ if (lastSearch) { break; }
+ auto mismatchIt = revRB + matchedLen;
+ if (mismatchIt < revReadEndIt) {
+ auto remainingDistance = std::distance(mismatchIt, revReadEndIt);
+ auto lce = saSearcher.lce(lbRightRC, ubRightRC-1, matchedLen, remainingDistance);
+
+ // Where we would jump if we just used the MMP
+ auto skipMatch = mismatchIt - skipOverlap;
+ // Where we would jump if we used the lce
+ auto skipLCE = revRB + lce - skipOverlap;
+ // Choose the larger of the two
+ revRB = std::max(skipLCE, skipMatch);
+ if (revRB > (revReadEndIt - k)) {
+ revRB = revReadEndIt - k;
+ lastSearch = true;
+ }
+ revRE = revRB + k;
+ } else {
+ lastSearch = true;
+ revRB = revReadEndIt - k;
+ revRE = revRB + k;
+ }
+
+ } else {
+ revRB += sampFactor;
+ revRE = revRB + k;
+ }
+ }
+ }
+
+ if (strictCheck) {
+ // The first two conditions shouldn't happen
+ // but I'm just being paranoid here
+ if (fwdHit > 0 and rcHit == 0) {
+ rcSAInts.clear();
+ } else if (rcHit > 0 and fwdHit == 0) {
+ fwdSAInts.clear();
+ } else {
+ std::sort( kmerScores.begin(), kmerScores.end() );
+ auto e = std::unique(kmerScores.begin(), kmerScores.end());
+ // Compute the score for the k-mers we need to
+ // test in both the forward and rc directions.
+ int32_t fwdScore{0};
+ int32_t rcScore{0};
+ // For every kmer score structure
+ //std::cerr << "[\n";
+ for (auto kmsIt = kmerScores.begin(); kmsIt != e; ++kmsIt) {//: kmerScores) {
+ auto& kms = *kmsIt;
+ // If the forward k-mer is untested, then test it
+ if (kms.fwdScore == UNTESTED) {
+ auto merIt = khash.find(kms.kmer.get_bits(0, 2*k));
+ kms.fwdScore = (merIt != khash.end()) ? PRESENT : ABSENT;
+ }
+ // accumulate the score
+ fwdScore += kms.fwdScore;
+
+ // If the rc k-mer is untested, then test it
+ if (kms.rcScore == UNTESTED) {
+ rcMer = kms.kmer.get_reverse_complement();
+ auto rcMerIt = khash.find(rcMer.get_bits(0, 2*k));
+ kms.rcScore = (rcMerIt != khash.end()) ? PRESENT : ABSENT;
+ }
+ // accumulate the score
+ rcScore += kms.rcScore;
+ //kms.print();
+ //std::cerr << "\n";
+ }
+ //std::cerr << "]\n";
+ // If the forward score is strictly greater
+ // then get rid of the rc hits.
+ if (fwdScore > rcScore) {
+ rcSAInts.clear();
+ } else if (rcScore > fwdScore) {
+ // If the rc score is strictly greater
+ // get rid of the forward hits
+ fwdSAInts.clear();
+ }
+ }
+ }
+
+ auto fwdHitsStart = hits.size();
+ // If we had > 1 forward hit
+ if (fwdSAInts.size() > 1) {
+ auto processedHits = rapmap::hit_manager::intersectSAHits(fwdSAInts, *rmi_, consistentHits);
+ rapmap::hit_manager::collectHitsSimpleSA(processedHits, readLen, maxDist, hits, mateStatus);
+ } else if (fwdSAInts.size() == 1) { // only 1 hit!
+ auto& saIntervalHit = fwdSAInts.front();
+ auto initialSize = hits.size();
+ for (OffsetT i = saIntervalHit.begin; i != saIntervalHit.end; ++i) {
+ auto globalPos = SA[i];
+ auto txpID = rmi_->transcriptAtPosition(globalPos);
+ // the offset into this transcript
+ auto pos = globalPos - txpStarts[txpID];
+ int32_t hitPos = pos - saIntervalHit.queryPos;
+ hits.emplace_back(txpID, hitPos, true, readLen);
+ hits.back().mateStatus = mateStatus;
+ }
+ // Now sort by transcript ID (then position) and eliminate
+ // duplicates
+ auto sortStartIt = hits.begin() + initialSize;
+ auto sortEndIt = hits.end();
+ std::sort(sortStartIt, sortEndIt,
+ [](const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ if (a.tid == b.tid) {
+ return a.pos < b.pos;
+ } else {
+ return a.tid < b.tid;
+ }
+ });
+ auto newEnd = std::unique(hits.begin() + initialSize, hits.end(),
+ [] (const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ return a.tid == b.tid;
+ });
+ hits.resize(std::distance(hits.begin(), newEnd));
+ }
+ auto fwdHitsEnd = hits.size();
+
+ auto rcHitsStart = fwdHitsEnd;
+ // If we had > 1 rc hit
+ if (rcSAInts.size() > 1) {
+ auto processedHits = rapmap::hit_manager::intersectSAHits(rcSAInts, *rmi_, consistentHits);
+ rapmap::hit_manager::collectHitsSimpleSA(processedHits, readLen, maxDist, hits, mateStatus);
+ } else if (rcSAInts.size() == 1) { // only 1 hit!
+ auto& saIntervalHit = rcSAInts.front();
+ auto initialSize = hits.size();
+ for (OffsetT i = saIntervalHit.begin; i != saIntervalHit.end; ++i) {
+ auto globalPos = SA[i];
+ auto txpID = rmi_->transcriptAtPosition(globalPos);
+ // the offset into this transcript
+ auto pos = globalPos - txpStarts[txpID];
+ int32_t hitPos = pos - saIntervalHit.queryPos;
+ hits.emplace_back(txpID, hitPos, false, readLen);
+ hits.back().mateStatus = mateStatus;
+ }
+ // Now sort by transcript ID (then position) and eliminate
+ // duplicates
+ auto sortStartIt = hits.begin() + rcHitsStart;
+ auto sortEndIt = hits.end();
+ std::sort(sortStartIt, sortEndIt,
+ [](const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ if (a.tid == b.tid) {
+ return a.pos < b.pos;
+ } else {
+ return a.tid < b.tid;
+ }
+ });
+ auto newEnd = std::unique(sortStartIt, sortEndIt,
+ [] (const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ return a.tid == b.tid;
+ });
+ hits.resize(std::distance(hits.begin(), newEnd));
+ }
+ auto rcHitsEnd = hits.size();
+
+ // If we had both forward and RC hits, then merge them
+ if ((fwdHitsEnd > fwdHitsStart) and (rcHitsEnd > rcHitsStart)) {
+ // Merge the forward and reverse hits
+ std::inplace_merge(hits.begin() + fwdHitsStart, hits.begin() + fwdHitsEnd, hits.begin() + rcHitsEnd,
+ [](const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ return a.tid < b.tid;
+ });
+ // And get rid of duplicate transcript IDs
+ auto newEnd = std::unique(hits.begin() + fwdHitsStart, hits.begin() + rcHitsEnd,
+ [] (const QuasiAlignment& a, const QuasiAlignment& b) -> bool {
+ return a.tid == b.tid;
+ });
+ hits.resize(std::distance(hits.begin(), newEnd));
+ }
+ // Return true if we had any valid hits and false otherwise.
+ return foundHit;
+ }
+
+ private:
+ RapMapIndexT* rmi_;
+};
+
+#endif // SA_COLLECTOR_FUSEQ_HPP
diff --git a/install.sh b/install.sh
new file mode 100644
index 0000000..daee836
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+##############################
+##### Date:21/05/2017
+##### This file is used to install FuSeq from source codes. It will automatically Sailfish and its dependences.
+##############################
+CMAKECMD="cmake"
+if [ "$DFETCH_BOOST" != "" ]; then
+ #echo "DFETCH_BOOST"
+ CMAKECMD=$(echo $CMAKECMD" -DFETCH_BOOST="$DFETCH_BOOST)
+fi;
+if [ "$DBOOST_ROOT" != "" ]; then
+ #echo "DBOOST_ROOT"
+ CMAKECMD=$(echo $CMAKECMD" -DBOOST_ROOT="$DBOOST_ROOT)
+fi;
+if [ "$DTBB_INSTALL_DIR" != "" ]; then
+ #echo "DTBB_INSTALL_DIR"
+ CMAKECMD=$(echo $CMAKECMD" -DTBB_INSTALL_DIR="$DTBB_INSTALL_DIR)
+fi;
+if [ "$DCMAKE_INSTALL_PREFIX" != "" ]; then
+ #echo "DCMAKE_INSTALL_PREFIX"
+ if [[ "$DCMAKE_INSTALL_PREFIX" != /* ]]; then
+ DCMAKE_INSTALL_PREFIX=$(echo $PWD"/"$DCMAKE_INSTALL_PREFIX)
+ fi;
+ CMAKECMD=$(echo $CMAKECMD" -DCMAKE_INSTALL_PREFIX="$DCMAKE_INSTALL_PREFIX)
+fi;
+
+#echo $CMAKECMD
+#download sailfish
+wget https://github.com/kingsfordgroup/sailfish/archive/v0.10.0.tar.gz
+tar -xzvf v0.10.0.tar.gz
+#copy our files
+cp -r include sailfish-0.10.0/
+cp -r src sailfish-0.10.0/
+#move to sailfish directory
+cd sailfish-0.10.0
+#do cmake
+eval $CMAKECMD
+make
+make install
+cd ..
+#Configuration: set the current path for loading R functions
+istr="/path/to"
+ostr="$PWD/R"
+eval "sed -i -e 's#"$istr"#"$ostr"#g' R/FuSeq.R"
+echo "Done!"
+##### done
+
+
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644
index 0000000..806cf1f
--- /dev/null
+++ b/src/CMakeLists.txt
@@ -0,0 +1,303 @@
+#####
+#Date:14/03/2017
+#-Clean codes
+#Date:01/11/2016
+#-Version 0.1.0
+#Note:This implementation is from Sailfish. We modified few parts to fit to our purposes.
+#####
+#set ( SAILFISH_MAIN_SRCS
+#Sailfish.cpp
+#)
+
+set ( FUSEQ_MAIN_SRCS
+FuSeq.cpp
+)
+
+set ( TXINDEXER_MAIN_SRCS
+TxIndexer.cpp
+)
+
+#set ( UNIT_TESTS_SRCS
+# ${GAT_SOURCE_DIR}/tests/UnitTests.cpp
+#)
+
+# Build the specific Sailfish commands as a
+# shared libraray (for some reason, building
+# them into a single executable was causing
+# multiple symbold definition errors).
+set (SAILFISH_LIB_SRCS
+VersionChecker.cpp
+#SailfishIndexer.cpp
+TxIndexer.cpp
+#SailfishQuantify.cpp
+FuSeq.cpp
+SailfishUtils.cpp
+SailfishStringUtils.cpp
+LibraryFormat.cpp
+TranscriptGroup.cpp
+CollapsedEMOptimizer.cpp
+ExportFeq.cpp
+CollapsedGibbsSampler.cpp
+EmpiricalDistribution.cpp
+#HDF5Writer.cpp
+GZipWriter.cpp
+xxhash.c
+${GAT_SOURCE_DIR}/external/install/src/rapmap/RapMapFileSystem.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/RapMapSAIndexer.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/RapMapSAIndex.cpp
+#${GAT_SOURCE_DIR}/external/install/src/rapmap/RapMapSAMapper.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/RapMapUtils.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/HitManager.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/rank9b.cpp
+${GAT_SOURCE_DIR}/external/install/src/rapmap/bit_array.c
+${GAT_SOURCE_DIR}/external/install/src/rapmap/EMPHFCommon.cpp
+#${GAT_SOURCE_DIR}/external/install/src/EasyH5Utils.cpp
+)
+
+include_directories(
+${GAT_SOURCE_DIR}/tests
+${GAT_SOURCE_DIR}/include
+${GAT_SOURCE_DIR}/include/eigen3
+${GAT_SOURCE_DIR}/external
+${GAT_SOURCE_DIR}/external/cereal/include
+${GAT_SOURCE_DIR}/external/install/include
+${GAT_SOURCE_DIR}/external/install/include/rapmap
+${ZLIB_INCLUDE_DIR}
+${TBB_INCLUDE_DIRS}
+${Boost_INCLUDE_DIRS}
+)
+
+if (JELLYFISH_FOUND)
+ include_directories(${JELLYFISH_INCLUDE_DIR})
+else()
+ include_directories(${GAT_SOURCE_DIR}/external/install/include/jellyfish-2.2.5)
+endif()
+
+
+link_directories(
+${GAT_SOURCE_DIR}/lib
+${GAT_SOURCE_DIR}/external/install/lib
+${Boost_LIBRARY_DIRS}
+${TBB_LIBRARY_DIRS}
+${LAPACK_LIBRARY_DIR}
+${BLAS_LIBRARY_DIR}
+)
+
+#dd_library(pca SHARED ${PCA_LIB_SRCS})
+
+message("TBB_LIBRARIES = ${TBB_LIBRARIES}")
+message("Boost_LIBRARIES = ${Boost_LIBRARIES}")
+
+# Set the RPATH
+if (APPLE)
+ ## This DOES NOT do what I / any one sane, expects. Setting the
+ ## linker path on OSX is messed up. Just tell the user to use
+ ## DYLD_FALLBACK_LIBRARY_PATH for now
+ set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
+else()
+ set(CMAKE_INSTALL_RPATH "$ORIGIN/../lib:$ORIGIN/../../lib:$ORIGIN/:$ORIGIN/../../external/install/lib")
+endif()
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
+
+# Build the Sailfish library
+add_library(sailfish_core STATIC ${SAILFISH_LIB_SRCS} )
+
+# Build the Sailfish executable
+#add_executable(sailfish ${SAILFISH_MAIN_SRCS})
+
+#for FuSeq
+# Build the FuSeq executable
+add_executable(FuSeq ${FUSEQ_MAIN_SRCS})
+# Build the TxIndexer executable
+add_executable(TxIndexer ${TXINDEXER_MAIN_SRCS})
+#for FuSeq
+
+# Build the Sailfish executable
+#add_executable(unitTests ${UNIT_TESTS_SRCS})
+
+# our suffix array construction libraries
+set (SUFFARRAY_LIB ${GAT_SOURCE_DIR}/external/install/lib/libdivsufsort.a)
+set (SUFFARRAY64_LIB ${GAT_SOURCE_DIR}/external/install/lib/libdivsufsort64.a)
+
+# Link the executable
+#target_link_libraries(sailfish
+# sailfish_core
+# ${PTHREAD_LIB}
+# ${Boost_LIBRARIES}
+# gff
+# ${ZLIB_LIBRARY}
+# ${SUFFARRAY_LIB}
+# ${SUFFARRAY64_LIB}
+# ${GAT_SOURCE_DIR}/external/install/lib/libjellyfish-2.0.a
+# m
+# ${TBB_LIBRARIES}
+# ${LIBSAILFISH_LINKER_FLAGS}
+# ${NON_APPLECLANG_LIBS}
+# #${HDF5_LIBRARIES}
+# ${FAST_MALLOC_LIB}
+#)
+#for FuSeq
+# Link the executable
+target_link_libraries(FuSeq
+ sailfish_core
+ ${PTHREAD_LIB}
+ ${Boost_LIBRARIES}
+ gff
+ ${ZLIB_LIBRARY}
+ ${SUFFARRAY_LIB}
+ ${SUFFARRAY64_LIB}
+ ${GAT_SOURCE_DIR}/external/install/lib/libjellyfish-2.0.a
+ m
+ ${TBB_LIBRARIES}
+ ${LIBSAILFISH_LINKER_FLAGS}
+ ${NON_APPLECLANG_LIBS}
+ #${HDF5_LIBRARIES}
+ ${FAST_MALLOC_LIB}
+)
+
+# Link the executable
+target_link_libraries(TxIndexer
+ sailfish_core
+ ${PTHREAD_LIB}
+ ${Boost_LIBRARIES}
+ gff
+ ${ZLIB_LIBRARY}
+ ${SUFFARRAY_LIB}
+ ${SUFFARRAY64_LIB}
+ ${GAT_SOURCE_DIR}/external/install/lib/libjellyfish-2.0.a
+ m
+ ${TBB_LIBRARIES}
+ ${LIBSAILFISH_LINKER_FLAGS}
+ ${NON_APPLECLANG_LIBS}
+ #${HDF5_LIBRARIES}
+ ${FAST_MALLOC_LIB}
+)
+#for FuSeq
+
+## Link the executable
+#target_link_libraries(unitTests
+# sailfish_core
+# ${PTHREAD_LIB}
+# ${Boost_LIBRARIES}
+# gff
+# ${ZLIB_LIBRARY}
+# ${SUFFARRAY_LIB}
+# ${SUFFARRAY64_LIB}
+# ${GAT_SOURCE_DIR}/external/install/lib/libjellyfish-2.0.a
+# m
+# ${TBB_LIBRARIES}
+# ${LIBSAILFISH_LINKER_FLAGS}
+# ${NON_APPLECLANG_LIBS}
+# ${FAST_MALLOC_LIB}
+#)
+
+##
+# This ensures that the sailfish executable should work with or without `make install`
+##
+# Grumble grumble . . . OSX
+if (APPLE)
+ # only attempt install_name_tool for tbb if we installed it
+ if (${TBB_LIBRARY_DIRS} MATCHES ${GAT_SOURCE_DIR}/external/install/lib)
+# add_custom_command(TARGET sailfish
+# POST_BUILD
+# COMMAND install_name_tool -change libtbb.dylib @rpath/libtbb.dylib ${GAT_SOURCE_DIR}/build/src/sailfish
+# COMMAND install_name_tool -change libtbbmalloc.dylib @rpath/libtbbmalloc.dylib ${GAT_SOURCE_DIR}/build/src/sailfish
+# COMMAND install_name_tool -change libtbbmalloc_proxy.dylib @rpath/libtbbmalloc_proxy.dylib ${GAT_SOURCE_DIR}/build/src/sailfish
+# COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib ${GAT_SOURCE_DIR}/build/src/sailfish
+# )
+ add_custom_command(TARGET FuSeq
+ POST_BUILD
+ COMMAND install_name_tool -change libtbb.dylib @rpath/libtbb.dylib ${GAT_SOURCE_DIR}/build/src/FuSeq
+ COMMAND install_name_tool -change libtbbmalloc.dylib @rpath/libtbbmalloc.dylib ${GAT_SOURCE_DIR}/build/src/FuSeq
+ COMMAND install_name_tool -change libtbbmalloc_proxy.dylib @rpath/libtbbmalloc_proxy.dylib ${GAT_SOURCE_DIR}/build/src/FuSeq
+ COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib ${GAT_SOURCE_DIR}/build/src/FuSeq
+ )
+ add_custom_command(TARGET TxIndexer
+ POST_BUILD
+ COMMAND install_name_tool -change libtbb.dylib @rpath/libtbb.dylib ${GAT_SOURCE_DIR}/build/src/TxIndexer
+ COMMAND install_name_tool -change libtbbmalloc.dylib @rpath/libtbbmalloc.dylib ${GAT_SOURCE_DIR}/build/src/TxIndexer
+ COMMAND install_name_tool -change libtbbmalloc_proxy.dylib @rpath/libtbbmalloc_proxy.dylib ${GAT_SOURCE_DIR}/build/src/TxIndexer
+ COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib ${GAT_SOURCE_DIR}/build/src/TxIndexer
+ )
+# add_custom_command(TARGET unitTests
+# POST_BUILD
+# COMMAND install_name_tool -change libtbb.dylib @rpath/libtbb.dylib ${GAT_SOURCE_DIR}/build/src/unitTests
+# COMMAND install_name_tool -change libtbbmalloc.dylib @rpath/libtbbmalloc.dylib ${GAT_SOURCE_DIR}/build/src/unitTests
+# COMMAND install_name_tool -change libtbbmalloc_proxy.dylib @rpath/libtbbmalloc_proxy.dylib ${GAT_SOURCE_DIR}/build/src/unitTests
+# COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib ${GAT_SOURCE_DIR}/build/src/unitTests
+# )
+ endif()
+else()
+ # related to complete static linking --- on hold
+ set (BOOST_THREAD_LIBRARY)
+endif()
+
+
+#if (APPLE)
+# add_custom_command(TARGET sailfish
+# POST_BUILD
+# COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib/libtbb.dylib sailfish
+# COMMAND install_name_tool -add_rpath ${GAT_SOURCE_DIR}/external/install/lib/libtbbmalloc.dylib sailfish
+# COMMAND install_name_tool -add_rpath @executable_path/../lib/libtbb.dylib sailfish
+# COMMAND install_name_tool -add_rpath @executable_path/../lib/libtbbmalloc.dylib sailfish
+# )
+#endif()
+#
+##### ======================================
+IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+ SET(CMAKE_INSTALL_PREFIX
+ "${GAT_SOURCE_DIR}" CACHE PATH "Default install prefix" FORCE
+ )
+ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+
+set(INSTALL_LIB_DIR lib )
+set(INSTALL_BIN_DIR bin )
+set(INSTALL_INCLUDE_DIR include )
+
+install(DIRECTORY
+ ${GAT_SOURCE_DIR}/external/install/lib/
+ DESTINATION ${INSTALL_LIB_DIR}
+ FILES_MATCHING PATTERN "libtbb*.${SHARED_LIB_EXTENSION}*"
+ )
+
+# install(FILES ${Boost_LIBRARIES}
+# DESTINATION ${INSTALL_LIB_DIR})
+
+#install(TARGETS sailfish sailfish_core
+# RUNTIME DESTINATION bin
+# LIBRARY DESTINATION lib
+# ARCHIVE DESTINATION lib
+# )
+install(TARGETS FuSeq sailfish_core
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+ )
+install(TARGETS TxIndexer sailfish_core
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+ )
+#install(TARGETS unitTests
+# RUNTIME DESTINATION tests
+#)
+
+set(POST_INSTALL_SCRIPT ${GAT_SOURCE_DIR}/cmake/PostInstall.cmake)
+
+install(
+ CODE
+ "
+ execute_process(COMMAND \"${CMAKE_COMMAND}\"
+ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME}
+ -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
+ -P \"${POST_INSTALL_SCRIPT}\")
+ "
+)
+
+# install(FILES ${GAT_SOURCE_DIR}/scripts/SFPipeline.py DESTINATION scripts/SFPipeline.py )
+# install(FILES ${GAT_SOURCE_DIR}/experimental_configs/SRX016368_25mers.cfg DESTINATION experimental_configs/SRX016368_25mers.cfg )
+
+#include(InstallRequiredSystemLibraries)
+#add_test( NAME unit_tests COMMAND ${CMAKE_COMMAND} -DTOPLEVEL_DIR=${CMAKE_INSTALL_PREFIX} -P ${GAT_SOURCE_DIR}/cmake/UnitTests.cmake )
+#add_test( NAME simple_test COMMAND ${CMAKE_COMMAND} -DTOPLEVEL_DIR=${CMAKE_INSTALL_PREFIX} -P ${GAT_SOURCE_DIR}/cmake/SimpleTest.cmake )
diff --git a/src/EmpiricalDistribution.cpp b/src/EmpiricalDistribution.cpp
new file mode 100644
index 0000000..47dcbb9
--- /dev/null
+++ b/src/EmpiricalDistribution.cpp
@@ -0,0 +1,181 @@
+/*
+Date:17/03/2017
+- Correct the calculation of standard deviation (sd)
+Date:01/11/2016
+Note:This implementation is from Sailfish. We modified few parts to fit to our purposes.
+*/
+/**
+ * This implementation for keeping an empirical distribution and
+ * querying the PDF and CDF is taken (and ever-so-slightly-modified) from
+ * https://raw.githubusercontent.com/dcjones/isolator/master/src/emp_dist.cpp.
+ * The original author is Daniel C. Jones; NOT me (Rob Patro).
+ **/
+
+#include
+#include
+#include
+#include
+//for FuSeq
+ #include
+ //for FuSeq
+
+#include "EmpiricalDistribution.hpp"
+
+EmpiricalDistribution::EmpiricalDistribution(EmpiricalDistribution& other)
+ : pdfvals(other.pdfvals) , cdfvals(other.cdfvals) , med(other.med),
+ minVal(other.minVal), maxVal(other.maxVal) { isValid_.store(other.isValid_.load()); }
+
+
+EmpiricalDistribution::EmpiricalDistribution() {}
+
+EmpiricalDistribution::EmpiricalDistribution(
+ const std::vector& vals,
+ const std::vector& lens) {
+ buildDistribution(vals, lens);
+}
+
+
+void EmpiricalDistribution::buildDistribution(
+ const std::vector& vals,
+ const std::vector& lens) {
+ assert(vals.size() == lens.size());
+ auto n = vals.size();
+
+ minVal = std::numeric_limits::max();
+ maxVal = 0;
+ double valsum = 0;
+
+ for (size_t i = 0; i < n; ++i) {
+ minVal = (vals[i] < minVal) ? vals[i] : minVal;
+ maxVal = (vals[i] > maxVal) ? vals[i] : maxVal;
+ valsum += lens[i];
+ }
+
+ double cumpr = 0.0;
+ unsigned int lastval = 0, maxval = 1;
+ for (; lastval < n; ++lastval) {
+ cumpr += lens[lastval] / valsum;
+ maxval = vals[lastval];
+ if (cumpr > 1.0 - 1e-6) {
+ break;
+ }
+ }
+
+ auto upperBound = lastval + 1;
+ pdfvals.resize(upperBound);
+ valsum = 0.0;
+ for (unsigned int i = 0; i < upperBound; ++i) {
+ valsum += lens[i];
+ }
+
+ for (unsigned int val = 0, i = 0; val < upperBound; ) {
+ if (val == vals[i]) {
+ pdfvals[val] = lens[i] / valsum;
+ ++val;
+ ++i;
+ }
+ else if (val < vals[i]) {
+ pdfvals[val] = 0.0;
+ ++val;
+ }
+ }
+
+ cdfvals.resize(upperBound);
+ cdfvals[0] = pdfvals[0];
+ mu = 0.0;
+ for (unsigned int val = 1; val < upperBound; ++val) {
+ cdfvals[val] = cdfvals[val - 1] + pdfvals[val];
+ mu += val * pdfvals[val];
+ }
+
+ //for FuSeq
+ // compute sd
+ sdval = 0.0;
+ for (unsigned int i = 0; i < upperBound; ++i) {
+ sdval += (i-mu)*(i-mu)*pdfvals[i];
+ }
+ sdval = std::sqrt(sdval);
+ //for FuSeq
+
+ // compute median
+ size_t i = 0, j = n - 1;
+ unsigned int u = lens[0], v = lens[n - 1];
+ while (i < j) {
+ if (u <= v) {
+ v -= u;
+ u = lens[++i];
+ }
+ else {
+ u -= v;
+ v = lens[--j];
+ }
+ }
+ med = vals[i];
+ isValid_ = true;
+}
+
+uint32_t EmpiricalDistribution::minValue() const {
+ return minVal;
+}
+
+
+uint32_t EmpiricalDistribution::maxValue() const {
+ return maxVal;
+}
+
+bool EmpiricalDistribution::valid() const {
+ return (isValid_ and (pdfvals.size() > 0));
+}
+
+float EmpiricalDistribution::median() const
+{
+ if (pdfvals.size() == 0) return NAN;
+ else return med;
+}
+
+float EmpiricalDistribution::mean () const
+{
+ if (pdfvals.size() == 0) return NAN;
+ else return mu;
+}
+
+//for FuSeq
+float EmpiricalDistribution::sd () const
+{
+ if (pdfvals.size() == 0) return NAN;
+ else return sdval;
+}
+
+//for FuSeq
+
+float EmpiricalDistribution::pdf(unsigned int x) const
+{
+ return x < pdfvals.size() ? pdfvals[x] : 0.0;
+}
+
+
+float EmpiricalDistribution::cdf(unsigned int x) const
+{
+ return x < cdfvals.size() ? cdfvals[x] : 1.0;
+}
+
+std::vector EmpiricalDistribution::realize(uint32_t numSamp) const {
+ // start at 0 instead of minVal
+ size_t distSize = maxVal + 1;
+ std::vector paddedPDF(distSize, 0.0);
+ for (size_t i = 0; i <= maxVal; ++i) {
+ paddedPDF[i] = pdf(i);
+ }
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::discrete_distribution d(paddedPDF.begin(), paddedPDF.end());
+
+ std::vector samples(distSize, 0);
+ for (size_t i = 0; i < numSamp; ++i) {
+ ++samples[d(gen)];
+ }
+
+ return samples;
+}
+
+
diff --git a/src/ExportFeq.cpp b/src/ExportFeq.cpp
new file mode 100644
index 0000000..fe72500
--- /dev/null
+++ b/src/ExportFeq.cpp
@@ -0,0 +1,231 @@
+/*
+Date:01/11/2016
+Note:This implementation is adapted from CollapsedEMOptimizer.cpp of Sailfish for our purpose.
+*/
+#include
+#include
+#include
+
+#include "tbb/task_scheduler_init.h"
+#include "tbb/parallel_for.h"
+#include "tbb/parallel_for_each.h"
+#include "tbb/parallel_reduce.h"
+#include "tbb/blocked_range.h"
+#include "tbb/partitioner.h"
+#include "concurrentqueue.h"
+
+#include
+//for FuSeq
+#include
+#include
+#include
+#include
+
+#include "EmpiricalDistribution.hpp"
+#include "ReadLibrary.hpp"
+#include "RapMapUtils.hpp"
+//for FuSeq
+
+// C++ string formatting library
+#include "spdlog/details/format.h"
+
+#include "cuckoohash_map.hh"
+#include "Eigen/Dense"
+
+#include "ExportFeq.hpp"
+#include "Transcript.hpp"
+#include "TranscriptGroup.hpp"
+#include "SailfishMath.hpp"
+#include "ReadExperiment.hpp"
+#include "BootstrapWriter.hpp"
+#include "MultinomialSampler.hpp"
+
+ExportFeq::ExportFeq() {}
+
+
+bool ExportFeq::writeFeq(ReadExperiment& readExp,
+ SailfishOpts& sopt,
+ const boost::filesystem::path& feqOutputPath //for FuSeq
+ ){
+
+ std::vector& transcripts = readExp.transcripts();
+ Eigen::VectorXd effLens(transcripts.size());
+
+ // Fill in the effective length vector
+ double totalLen{0.0};
+ for (size_t i = 0; i < transcripts.size(); ++i) {
+ effLens(i) = (sopt.noEffectiveLengthCorrection) ?
+ transcripts[i].RefLength : transcripts[i].EffectiveLength;
+ if (effLens(i) <= 1.0) { effLens(i) = 1.0; }
+ totalLen += effLens(i);
+ }
+
+ std::vector>& eqVec =
+ readExp.equivalenceClassBuilder().eqVec();
+
+
+ std::cout << "=========================================================================\n" << std::endl;
+ std::cout << "[FuSeq] -- We are export some data here -- \n" << std::endl;
+ std::cout << "=========================================================================\n" << std::endl;
+ std::cout << "[FuSeq] -- Export fragment information \n" << std::endl;
+ boost::filesystem::path fragfname = feqOutputPath / "fragmentInfo.txt";
+ std::unique_ptr FragOutput(std::fopen(fragfname.c_str(), "w"), std::fclose);
+
+ auto kmerLen = rapmap::utils::my_mer::k();
+ fmt::print(FragOutput.get(), "readlen\tfragLengthMedian\tfragLengthMean\tfragLengthSd\tnumObservedFragments\tnumMappedFragments\tnumHits\tkmer\n");
+ fmt::print(FragOutput.get(), "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",readExp.getReadLength(),readExp.fragLengthDist()->median(),readExp.fragLengthDist()->mean(),readExp.fragLengthDist()->sd(),readExp.numObservedFragments(),readExp.numMappedFragments(),readExp.numFragHitsAtomic(),kmerLen);
+ std::cout <<"Read length "<median() << " fragLengthMean " << readExp.fragLengthDist()->mean() << " fragLengthSd " << readExp.fragLengthDist()->sd() << "Observed Fragments "< SequgioOutput(std::fopen(sequgiofname.c_str(), "w"), std::fclose);
+ fmt::print(SequgioOutput.get(), "Transcript\tWeight\tCount\teffLens\tRefLength\tEffectiveLength\teqClass\n");
+ // we can export information of transcript mapped read counts before bias correction and optimization
+ uint32_t eqClassID=0;
+ for (auto& kv : eqVec) {
+ eqClassID=eqClassID+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ fmt::print(SequgioOutput.get(), "{}\t{}\t{}\t{}\t{}\t{}\t{}\n",transcripts[t].RefName,v.weights[i],v.count ,effLens(t),transcripts[t].RefLength ,transcripts[t].EffectiveLength, eqClassID);
+
+ }
+ }
+
+ std::cout << "[FuSeq] -- Extracting RR fusion equivalence classes \n" << std::endl;
+ std::vector>& feqVecRR = readExp.feqClassBuilderRR().eqVec();
+
+ boost::filesystem::path feqfnameRR = feqOutputPath / "feq_RR.txt";
+ std::unique_ptr feqOutputRR(std::fopen(feqfnameRR.c_str(), "w"), std::fclose);
+ fmt::print(feqOutputRR.get(),"Transcript\tCount\tRead\tFeq\n");
+
+ uint32_t feqClassID_RR=0;
+ for (auto& kv : feqVecRR) {
+ feqClassID_RR=feqClassID_RR+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ uint32_t readType=1;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ if (t==0){
+ readType=2;
+ }else{
+ fmt::print(feqOutputRR.get(), "{}\t{}\t{}\t{}\n",transcripts[t-1].RefName,v.count, readType, feqClassID_RR);
+ }
+ }
+ }
+
+ std::cout << "[FuSeq] -- Extracting RF fusion equivalence classes \n" << std::endl;
+ std::vector>& feqVecRF = readExp.feqClassBuilderRF().eqVec();
+
+ boost::filesystem::path feqfnameRF = feqOutputPath / "feq_RF.txt";
+ std::unique_ptr feqOutputRF(std::fopen(feqfnameRF.c_str(), "w"), std::fclose);
+ fmt::print(feqOutputRF.get(),"Transcript\tCount\tRead\tFeq\n");
+
+ uint32_t feqClassID_RF=0;
+ for (auto& kv : feqVecRF) {
+ feqClassID_RF=feqClassID_RF+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ uint32_t readType=1;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ if (t==0){
+ readType=2;
+ }else{
+ fmt::print(feqOutputRF.get(), "{}\t{}\t{}\t{}\n",transcripts[t-1].RefName,v.count, readType, feqClassID_RF);
+ }
+ }
+ }
+
+ std::cout << "[FuSeq] -- Extracting FF fusion equivalence classes \n" << std::endl;
+ std::vector>& feqVecFF = readExp.feqClassBuilderFF().eqVec();
+
+ boost::filesystem::path feqfnameFF = feqOutputPath / "feq_FF.txt";
+ std::unique_ptr feqOutputFF(std::fopen(feqfnameFF.c_str(), "w"), std::fclose);
+ fmt::print(feqOutputFF.get(),"Transcript\tCount\tRead\tFeq\n");
+
+ uint32_t feqClassID_FF=0;
+ for (auto& kv : feqVecFF) {
+ feqClassID_FF=feqClassID_FF+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ uint32_t readType=1;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ if (t==0){
+ readType=2;
+ }else{
+ fmt::print(feqOutputFF.get(), "{}\t{}\t{}\t{}\n",transcripts[t-1].RefName,v.count, readType, feqClassID_FF);
+ }
+ }
+ }
+
+ std::cout << "[FuSeq] -- Extracting FR fusion equivalence classes \n" << std::endl;
+ std::vector>& feqVecFR = readExp.feqClassBuilderFR().eqVec();
+
+ boost::filesystem::path feqfnameFR = feqOutputPath / "feq_FR.txt";
+ std::unique_ptr feqOutputFR(std::fopen(feqfnameFR.c_str(), "w"), std::fclose);
+ fmt::print(feqOutputFR.get(),"Transcript\tCount\tRead\tFeq\n");
+
+ uint32_t feqClassID_FR=0;
+ for (auto& kv : feqVecFR) {
+ feqClassID_FR=feqClassID_FR+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ uint32_t readType=1;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ if (t==0){
+ readType=2;
+ }else{
+ fmt::print(feqOutputFR.get(), "{}\t{}\t{}\t{}\n",transcripts[t-1].RefName,v.count, readType, feqClassID_FR);
+ }
+ }
+ }
+
+
+ std::cout << "[FuSeq] -- Extracting UN fusion equivalence classes \n" << std::endl;
+ std::vector>& feqVecUN = readExp.feqClassBuilderUN().eqVec();
+
+ boost::filesystem::path feqfnameUN = feqOutputPath / "feq_UN.txt";
+ std::unique_ptr feqOutputUN(std::fopen(feqfnameUN.c_str(), "w"), std::fclose);
+ fmt::print(feqOutputUN.get(),"Transcript\tCount\tRead\tFeq\n");
+
+ uint32_t feqClassID_UN=0;
+ for (auto& kv : feqVecUN) {
+ feqClassID_UN=feqClassID_UN+1;
+ auto& tg = kv.first;
+ // The size of the label
+ size_t classSize = tg.txps.size();
+ // The weights of the label
+ TGValue& v = kv.second;
+ uint32_t readType=1;
+ for (size_t i = 0; i < classSize; ++i) {
+ auto& t = tg.txps[i];
+ if (t==0){
+ readType=2;
+ }else{
+ fmt::print(feqOutputUN.get(), "{}\t{}\t{}\t{}\n",transcripts[t-1].RefName,v.count, readType, feqClassID_UN);
+ }
+ }
+ }
+
+ return true;
+}
diff --git a/src/FuSeq.cpp b/src/FuSeq.cpp
new file mode 100644
index 0000000..fe68828
--- /dev/null
+++ b/src/FuSeq.cpp
@@ -0,0 +1,2767 @@
+/*
+Date:23/03/2017
+- Improve codes
+Date:01/11/2016
+Note:This implementation is adapted from SailfishQuantify.cpp of Sailfish for our purpose.
+*/
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+//for FuSeq
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "cereal/archives/binary.hpp"
+#include
+#include
+#include
+#include
+
+//#include "KmerDist.hpp"
+#include "SailfishUtils.hpp"
+#include "SailfishConfig.hpp"
+#include "VersionChecker.hpp"
+//for FuSeq
+
+#include
+#include
+#include
+#include
+#include
+
+// TBB include
+#include "tbb/atomic.h"
+#include "tbb/blocked_range.h"
+#include "tbb/parallel_for.h"
+
+// Jellyfish 2 include
+#include "jellyfish/mer_dna.hpp"
+#include "jellyfish/stream_manager.hpp"
+#include "jellyfish/whole_sequence_parser.hpp"
+
+//#include "BiasIndex.hpp"
+#include "VersionChecker.hpp"
+#include "SailfishConfig.hpp"
+#include "SailfishUtils.hpp"
+#include "SailfishIndex.hpp"
+#include "TranscriptGeneMap.hpp"
+//#include "CollapsedEMOptimizer.hpp"
+#include "ExportFeq.hpp"
+#include "CollapsedGibbsSampler.hpp"
+#include "ReadLibrary.hpp"
+#include "RapMapUtils.hpp"
+#include "HitManager.hpp"
+#include "SASearcher.hpp"
+//#include "SACollector.hpp"
+#include "SACollectorFuSeq.hpp"
+#include "EmpiricalDistribution.hpp"
+#include "TextBootstrapWriter.hpp"
+#include "GZipWriter.hpp"
+//#include "HDF5Writer.hpp"
+
+#include "RapMapUtils.hpp"
+#include "RapMapSAIndex.hpp"
+
+
+
+
+#include "spdlog/spdlog.h"
+
+//S_AYUSH_CODE
+#include "ReadKmerDist.hpp"
+//T_AYUSH_CODE
+
+/****** QUASI MAPPING DECLARATIONS *********/
+using MateStatus = rapmap::utils::MateStatus;
+using QuasiAlignment = rapmap::utils::QuasiAlignment;
+/****** QUASI MAPPING DECLARATIONS *******/
+
+/****** Parser aliases ***/
+//using paired_parser = pair_sequence_parser::iterator>;
+using paired_parser = pair_sequence_parser;//std::vector::iterator>;
+using stream_manager = jellyfish::stream_manager::const_iterator>;
+using single_parser = jellyfish::whole_sequence_parser;
+/****** Parser aliases ***/
+
+
+// using FragLengthCountMap = std::unordered_map;
+using FragLengthCountMap = std::vector>;
+
+using std::string;
+
+constexpr uint32_t readGroupSize{1000};
+
+/**
+ * Compute and return the mean fragment length ---
+ * rounded down to the nearest integer --- of the fragment
+ * length distribution.
+ */
+int32_t getMeanFragLen(const FragLengthCountMap& flMap) {
+ double totalCount{0.0};
+ double totalLength{0.0};
+ for (size_t i = 0; i < flMap.size(); ++i) {
+ auto c = flMap[i];
+ totalLength += i * c;
+ totalCount += c;
+ }
+ double ret{200.0};
+ if (totalCount <= 0.0) {
+ std::cerr << "Saw no fragments; can't compute mean fragment length.\n";
+ std::cerr << "This appears to be a bug. Please report it on GitHub.\n";
+ return ret;
+ }
+ if (totalLength > totalCount) {
+ ret = (totalLength / totalCount);
+ }
+ return static_cast(ret);
+}
+
+//for FuSeq
+// Find fusion hits
+bool findFusionLeftRightHits(
+ std::vector& leftHits,
+ std::vector& rightHits,
+ std::vector& fusionLeftHits,
+ std::vector& fusionRightHits) {
+
+
+ if (leftHits.size() > 0) {
+ if (rightHits.size() > 0) {
+ //find left fusion hits
+ for (auto leftIt = leftHits.begin(); leftIt < leftHits.end(); ++leftIt) {
+ uint32_t leftTxp = leftIt->tid;
+ bool isShare{false};
+
+ for (auto rightIt = rightHits.begin(); rightIt < rightHits.end(); ++rightIt) {
+ uint32_t rightTxp = rightIt->tid;
+
+ if (rightTxp == leftTxp){
+ isShare = true;
+ rightIt = rightHits.end();
+ }
+ }
+ if (!isShare) {
+ fusionLeftHits.emplace_back(leftTxp,
+ leftIt->pos,
+ leftIt->fwd,
+ leftIt->readLen,
+ 0, true);
+ }
+ }
+
+ //find right fusion hits
+ for (auto rightIt = rightHits.begin(); rightIt < rightHits.end(); ++rightIt) {
+ uint32_t rightTxp = rightIt->tid;
+ bool isShare{false};
+ for (auto leftIt = leftHits.begin(); leftIt < leftHits.end(); ++leftIt) {
+ uint32_t leftTxp = leftIt->tid;
+ if (rightTxp == leftTxp){
+ isShare= true;
+ leftIt = leftHits.end();
+ }
+ }
+ if (!isShare) {
+ fusionRightHits.emplace_back(rightTxp,
+ rightIt->pos,
+ rightIt->fwd,
+ rightIt->readLen,
+ 0, true);
+ }
+ }
+ }
+ }
+
+ if (fusionLeftHits.size() > 0 and fusionRightHits.size() > 0) return true;
+
+ return false;
+}
+//for FuSeq
+
+
+/**
+ * For paired-end reads:
+ * Do the main work of mapping the reads and building
+ * the equivalence classes.
+ */
+template
+void processReadsQuasi(paired_parser* parser,
+ IndexT* sidx,
+ ReadExperiment& readExp,
+ ReadLibrary& rl,
+ SailfishOpts& sfOpts,
+ FragLengthCountMap& flMap,
+ std::atomic& remainingFLOps,
+ std::mutex& iomutex) {
+
+ uint32_t maxFragLen = sfOpts.maxFragLen;
+ uint64_t prevObservedFrags{1};
+ uint64_t leftHitCount{0};
+ uint64_t hitListCount{0};
+ int32_t meanFragLen{-1};
+
+ size_t locRead{0};
+ uint64_t localUpperBoundHits{0};
+
+ bool tooManyHits{false};
+ size_t maxNumHits{sfOpts.maxReadOccs};
+ size_t readLen{0};
+
+ auto& jointLog = sfOpts.jointLog;
+ auto& numObservedFragments = readExp.numObservedFragmentsAtomic();
+ auto& validHits = readExp.numMappedFragmentsAtomic();
+ auto& totalHits = readExp.numFragHitsAtomic();
+ auto& upperBoundHits = readExp.upperBoundHitsAtomic();
+ auto& eqBuilder = readExp.equivalenceClassBuilder();
+ //for FuSeq
+ auto& eqFusionTxBuilder = readExp.equivalenceFusionTxClassBuilder();
+ auto& eqFusionTxBuilderRR = readExp.equivalenceFusionTxClassBuilderRR();
+ auto& eqFusionTxBuilderFF = readExp.equivalenceFusionTxClassBuilderFF();
+ auto& eqFusionTxBuilderRF = readExp.equivalenceFusionTxClassBuilderRF();
+ auto& eqFusionTxBuilderFR = readExp.equivalenceFusionTxClassBuilderFR();
+
+ auto& feqBuilder = readExp.feqClassBuilder();
+ auto& feqBuilderRR = readExp.feqClassBuilderRR();
+ auto& feqBuilderFF = readExp.feqClassBuilderFF();
+ auto& feqBuilderRF = readExp.feqClassBuilderRF();
+ auto& feqBuilderFR = readExp.feqClassBuilderFR();
+ auto& feqBuilderUN = readExp.feqClassBuilderUN();
+
+ auto& tranGeneMap = readExp.getTranscriptGeneMap();
+ bool useTGM = readExp.getExistTranGeneMap();
+ //for FuSeq
+ auto& transcripts = readExp.transcripts();
+
+ auto& readBias = readExp.readBias();
+ auto& observedGC = readExp.observedGC();
+ bool estimateGCBias = sfOpts.gcBiasCorrect;
+ bool strictIntersect = sfOpts.strictIntersect;
+ bool discardOrphans = !sfOpts.allowOrphans;
+
+ SACollectorFuSeq hitCollector(sidx);
+ SASearcher saSearcher(sidx);
+ rapmap::utils::HitCounters hctr;
+
+ std::vector leftHits;
+ std::vector rightHits;
+ std::vector jointHits;
+ //for FuSeq
+ std::vector fusionLeftHits;
+ std::vector fusionRightHits;
+ std::vector txpIDsFusion;
+ std::vector auxProbsFusion;
+
+
+ //template
+ using OffsetT = typename IndexT::IndexType;
+ using SAIntervalHit = rapmap::utils::SAIntervalHit;
+
+ std::vector leftFwdSAInts;
+ std::vector leftRcSAInts;
+ std::vector rightFwdSAInts;
+ std::vector rightRcSAInts;
+
+ auto& SA = sidx->SA;
+ auto& txpStarts = sidx->txpOffsets;
+
+ //std::vector> mydat;
+
+ //for FuSeq
+ std::vector txpIDsAll;
+ std::vector auxProbsAll;
+
+ std::vector txpIDsCompat;
+ std::vector auxProbsCompat;
+
+ // *Completely* ignore strandedness information
+ bool ignoreCompat = sfOpts.ignoreLibCompat;
+ // Don't *strictly* enforce compatibility --- if
+ // the only hits are incompatible with the library
+ // type then allow them.
+ bool enforceCompat = sfOpts.enforceLibCompat;
+ // True when we have compatible hits, false otherwise
+ bool haveCompat{false};
+ auto expectedLibType = rl.format();
+
+ bool canDovetail = sfOpts.allowDovetail;
+
+ bool mappedFrag{false};
+ std::unique_ptr empDist{nullptr};
+
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<> dis(0, sfOpts.maxReadOccs);
+
+ //generate a unique ID for as single thread
+ string ftag=std::to_string(std::rand());
+
+// string fmrfn ="all_fusionMappedReadsChunk_" + ftag +".txt";
+ string FF_fmrfn = "FF_fusionMappedReadsChunk_" + ftag +".txt";
+ string FR_fmrfn = "FR_fusionMappedReadsChunk_" + ftag +".txt";
+ string RR_fmrfn = "RR_fusionMappedReadsChunk_" + ftag +".txt";
+ string RF_fmrfn = "RF_fusionMappedReadsChunk_" + ftag +".txt";
+ string UN_fmrfn = "UN_fusionMappedReadsChunk_" + ftag +".txt";
+// boost::filesystem::path txsetsfname = sfOpts.outputDirectory / fmrfn;
+// std::unique_ptr txsetsOutput(std::fopen(txsetsfname.c_str(), "a"), std::fclose);
+ boost::filesystem::path FF_txsetsfname = sfOpts.outputDirectory / FF_fmrfn;
+ std::unique_ptr FF_txsetsOutput(std::fopen(FF_txsetsfname.c_str(), "a"), std::fclose);
+ boost::filesystem::path FR_txsetsfname = sfOpts.outputDirectory / FR_fmrfn;
+ std::unique_ptr FR_txsetsOutput(std::fopen(FR_txsetsfname.c_str(), "a"), std::fclose);
+ boost::filesystem::path RR_txsetsfname = sfOpts.outputDirectory / RR_fmrfn;
+ std::unique_ptr RR_txsetsOutput(std::fopen(RR_txsetsfname.c_str(), "a"), std::fclose);
+ boost::filesystem::path RF_txsetsfname = sfOpts.outputDirectory / RF_fmrfn;
+ std::unique_ptr RF_txsetsOutput(std::fopen(RF_txsetsfname.c_str(), "a"), std::fclose);
+ boost::filesystem::path UN_txsetsfname = sfOpts.outputDirectory / UN_fmrfn;
+ std::unique_ptr UN_txsetsOutput(std::fopen(UN_txsetsfname.c_str(), "a"), std::fclose);
+
+// string fafn1 ="all_fastaseq_" + ftag +"_1.fa";
+ string FF_fafn1 = "FF_fastaseq_" + ftag +"_1.fa";
+ string FR_fafn1 = "FR_fastaseq_" + ftag +"_1.fa";
+ string RR_fafn1 = "RR_fastaseq_" + ftag +"_1.fa";
+ string RF_fafn1 = "RF_fastaseq_" + ftag +"_1.fa";
+ string UN_fafn1 = "UN_fastaseq_" + ftag +"_1.fa";
+// boost::filesystem::path readfafn1 = sfOpts.outputDirectory / fafn1;
+// std::unique_ptr faOutput1(std::fopen(readfafn1.c_str(), "a"), std::fclose);
+ boost::filesystem::path FF_readfafn1 = sfOpts.outputDirectory / FF_fafn1;
+ std::unique_ptr FF_faOutput1(std::fopen(FF_readfafn1.c_str(), "a"), std::fclose);
+ boost::filesystem::path FR_readfafn1 = sfOpts.outputDirectory / FR_fafn1;
+ std::unique_ptr FR_faOutput1(std::fopen(FR_readfafn1.c_str(), "a"), std::fclose);
+ boost::filesystem::path RR_readfafn1 = sfOpts.outputDirectory / RR_fafn1;
+ std::unique_ptr RR_faOutput1(std::fopen(RR_readfafn1.c_str(), "a"), std::fclose);
+ boost::filesystem::path RF_readfafn1 = sfOpts.outputDirectory / RF_fafn1;
+ std::unique_ptr RF_faOutput1(std::fopen(RF_readfafn1.c_str(), "a"), std::fclose);
+ boost::filesystem::path UN_readfafn1 = sfOpts.outputDirectory / UN_fafn1;
+ std::unique_ptr UN_faOutput1(std::fopen(UN_readfafn1.c_str(), "a"), std::fclose);
+
+// string fafn2 ="all_fastaseq_" + ftag +"_2.fa";
+ string FF_fafn2 = "FF_fastaseq_" + ftag +"_2.fa";
+ string FR_fafn2 = "FR_fastaseq_" + ftag +"_2.fa";
+ string RR_fafn2 = "RR_fastaseq_" + ftag +"_2.fa";
+ string RF_fafn2 = "RF_fastaseq_" + ftag +"_2.fa";
+ string UN_fafn2 = "UN_fastaseq_" + ftag +"_2.fa";
+// boost::filesystem::path readfafn2 = sfOpts.outputDirectory / fafn2;
+// std::unique_ptr faOutput2(std::fopen(readfafn2.c_str(), "a"), std::fclose);
+ boost::filesystem::path FF_readfafn2 = sfOpts.outputDirectory / FF_fafn2;
+ std::unique_ptr FF_faOutput2(std::fopen(FF_readfafn2.c_str(), "a"), std::fclose);
+ boost::filesystem::path FR_readfafn2 = sfOpts.outputDirectory / FR_fafn2;
+ std::unique_ptr FR_faOutput2(std::fopen(FR_readfafn2.c_str(), "a"), std::fclose);
+ boost::filesystem::path RR_readfafn2 = sfOpts.outputDirectory / RR_fafn2;
+ std::unique_ptr RR_faOutput2(std::fopen(RR_readfafn2.c_str(), "a"), std::fclose);
+ boost::filesystem::path RF_readfafn2 = sfOpts.outputDirectory / RF_fafn2;
+ std::unique_ptr RF_faOutput2(std::fopen(RF_readfafn2.c_str(), "a"), std::fclose);
+ boost::filesystem::path UN_readfafn2 = sfOpts.outputDirectory / UN_fafn2;
+ std::unique_ptr