From 9da1c92e98980d2352ce3454a44f81b730bdedeb Mon Sep 17 00:00:00 2001 From: codemeleon Date: Mon, 5 Dec 2022 23:19:19 +0000 Subject: [PATCH] A New start --- LICENSE | 674 +++++++ README.md | 81 + seqPanther/CodonCounter/CodonCounter.py | 410 +++++ seqPanther/CodonCounter/__init__.py | 0 seqPanther/CodonCounter/auto_cpu.py | 23 + .../CodonCounter/bam_nuc_codon_count.py.bkp | 1057 +++++++++++ seqPanther/CodonCounter/bammer.py | 28 + seqPanther/CodonCounter/codon_table.py | 69 + seqPanther/CodonCounter/coors_with_changes.py | 213 +++ seqPanther/CodonCounter/gff_reader.py | 37 + seqPanther/CodonCounter/indel_frames.py | 273 +++ seqPanther/CodonCounter/subs.py | 232 +++ seqPanther/CodonCounter/update_missing.py | 25 + seqPanther/NucIn/__init__.py | 0 seqPanther/NucIn/changes.txt | 63 + seqPanther/NucIn/nuc_in.py | 93 + seqPanther/NucIn/organise.py | 133 ++ seqPanther/__init__.py | 0 .../__pycache__/__init__.cpython-39.pyc | Bin 0 -> 152 bytes .../__pycache__/seqPanther.cpython-39.pyc | Bin 0 -> 872 bytes seqPanther/seqPanther.py | 27 + seqPanther/seqPatcher/__init__.py | 0 seqPanther/seqPatcher/check_orientation.py | 56 + seqPanther/seqPatcher/seqpatcher.py | 1585 +++++++++++++++++ seqPanther_codon_counter.sh | 9 + seqPanther_nucsub.sh | 0 seqPanther_seqpatcher.sh | 15 + setup.py | 22 + 28 files changed, 5125 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 seqPanther/CodonCounter/CodonCounter.py create mode 100644 seqPanther/CodonCounter/__init__.py create mode 100644 seqPanther/CodonCounter/auto_cpu.py create mode 100644 seqPanther/CodonCounter/bam_nuc_codon_count.py.bkp create mode 100644 seqPanther/CodonCounter/bammer.py create mode 100644 seqPanther/CodonCounter/codon_table.py create mode 100644 seqPanther/CodonCounter/coors_with_changes.py create mode 100755 seqPanther/CodonCounter/gff_reader.py create mode 100755 seqPanther/CodonCounter/indel_frames.py create mode 100755 seqPanther/CodonCounter/subs.py create mode 100755 seqPanther/CodonCounter/update_missing.py create mode 100644 seqPanther/NucIn/__init__.py create mode 100644 seqPanther/NucIn/changes.txt create mode 100644 seqPanther/NucIn/nuc_in.py create mode 100644 seqPanther/NucIn/organise.py create mode 100644 seqPanther/__init__.py create mode 100644 seqPanther/__pycache__/__init__.cpython-39.pyc create mode 100644 seqPanther/__pycache__/seqPanther.cpython-39.pyc create mode 100755 seqPanther/seqPanther.py create mode 100644 seqPanther/seqPatcher/__init__.py create mode 100644 seqPanther/seqPatcher/check_orientation.py create mode 100644 seqPanther/seqPatcher/seqpatcher.py create mode 100644 seqPanther_codon_counter.sh create mode 100644 seqPanther_nucsub.sh create mode 100644 seqPanther_seqpatcher.sh create mode 100644 setup.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /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/README.md b/README.md new file mode 100644 index 0000000..d15a52a --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# SeqPanther + +SeqPanther tool consists set of commands as follows: + +* **seqpatcher** : integrates sanger sequencing of missing regions of an incomplete assembly to the assembly. This command is modification of [SeqPatcher tool](https://github.com/krisp-kwazulu-natal/seqPatcher) + +* **codoncounter** : performs variant calling, generates nucleotide stats at variant sites and reports impacts of nucleotide changes on amino acids in the translated proteins. + +* **transform** : performs transformation of codoncounter output in a format where user can select variant to integrate in the reference or assemblies using **nucsub** command. + +* **nucsub** : integrates the alteration list generated by codoncounter in a given reference or assembled genome based on the user recommendations. + +## Operating system compatibility + +Unix platforms. + +## Dependencies + +The tool relies on multiple external programs and python modules as listed below: + +### External Tools + +1. Muscle + +* To perform multiple sequence alignment +* Can be downloaded and install from +* `conda install muscle` to install + +2. BLAT + +* To query sequence location in the genome. +* `conda install blat` to install + +## Python modules + + + +All the python module used for this program is listed in `requirements.txt`. + +# Installation + +## Manual installation + +1. `pip install -r requirements.txt` +2. `python setup.py install` + +## Directly from the repo + +`pip install git+https://github.com/codemeleon/seqPanther.git` + +# Usages + +The commands are selft explanatory. + +seqPanther contains three commands, which can be accessed using `seqPanther --help` + +## CodonCounter + +This command can be used as `seqPanther CodonCounter`. The help accessible at `seqPanther CodonCounter --help` or [CodonCounter GitHub page](https://github.com/codemeleon/CodonCounter) + +## SeqIn + +This command can be used as `seqPanther SeqIn`. The help accessible at `seqPanther SeqIn --help` or [SeqIn GitHub page](https://github.com/codemeleon/SeqIn) + +## SeqPatcher + +This command can be used as `seqPanther SeqPatcher`. The help accessible at `seqPanther SeqPatcher --help` or [SeqPatcher GitHub page](https://github.com/CERI-KRISP/SeqPatcher) + +# Features + +Codon Counter and SeqIn commands were specifically defined for this program. However, each sub-command can be installed and used independently of this program. + +# Bug reporting + +Please report bugs on this portal or associated GitHub repos of the command + +# Cite + +If you use this tool, please cite it as + + Bib for the opensource software journal (JOSS) diff --git a/seqPanther/CodonCounter/CodonCounter.py b/seqPanther/CodonCounter/CodonCounter.py new file mode 100644 index 0000000..7f6d4da --- /dev/null +++ b/seqPanther/CodonCounter/CodonCounter.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python +import tempfile +import itertools + +from os import path +from glob import glob +from shutil import rmtree +from functools import partial +import click +import numpy as np +import pandas as pd + +from Bio import SeqIO +import pyfaidx +import matplotlib.backends.backend_pdf as bpdf +from pylab import * + +from . import auto_cpu, bammer, coors_with_changes, gff_reader + +__author__ = "Anmol Kiran" +__organisation__ = ( + "Malawi-Liverpool-Wellcome Trust, Malawi; University of Liverpool, UK") +__github__ = "codemeleon" +__email__ = "akiran@mlw.mw" +__version__ = "0.0.2" + + +def str2coors(coorstr): + """Converts comma separated values to coordinates and coordinate ranges.""" + coorslist = [x.strip() for x in coorstr.split(',')] + try: + coorrange = [] + for coor in coorslist: + if '-' in coor: + start, end = coor.split("-") + coorrange.append([int(start), int(end) + 1]) + pass + else: + coorrange.append([int(coor), int(coor) + 1]) + return coorrange + except: + exit( + "Coordinate accept only , and - as alpha numeric values. Please check your coordinate input" + ) + + +@click.command() +@click.option( + "-bam", + help="Bam files", + # default="/home/devil/Documents/Tools/BitterBits/src/test_data/" + # "K032623-rep-consensus_alignment_sorted.REF_NC_045512.2.bam", + # default="./test_data/NC_045512.2.sorted.bam", + # default="./test_data/InDel/K011018-NC_045512.2_1-consensus_alignment_sorted.bam", # Deletion + default="test_data/InDel/Insert/SRR17051909.sorted.bam", # Inserttion + type=click.Path(exists=True), + required=True, + show_default=True, +) +@click.option( + "-rid", + help="Reference ID", + type=str, + default="NC_045512.2", + required=True, + show_default=True, +) +@click.option( + "-ref", + help="Reference fasta files", + type=str, # click.File("r"), + default="./test_data/NC_045512.2.fasta", + required=True, + # default="./test_data/NC_045512.2_rev_comp.fasta", + show_default=True, +) +@click.option( + "-coor_range", + help="Coordinates in the reference, zero index based, end exclusive", + type=str, + # default="21000-25000", # Forward sub + # default="4900-9000", # Reverse sub + # default="22279-22300", # For Deletion position + default="22190-22206", # Forward insert + show_default=True, +) +@click.option( + "--output_type", + help="Output type", + type=click.Choice(["nuc", "codon", "both"]), + default="codon", + show_default=True, +) +@click.option( + "-gff", + help="Gff Annotation File", + type=click.File("r"), + default="/home/devil/Documents/Tools/BitterBits/src/test_data/genemap.gff", + required=True, + # default="./test_data/genemap_rev_complement.gff", + show_default=True, +) +@click.option( + "--ignore_orphans", + help="Ignore orphaned (Unpaired) reads", + type=bool, + default=False, + show_default=True, +) +@click.option( + "--min_mapping_quality", + help="Mapping quality of reads", + type=int, + default=0, + show_default=True, +) +@click.option( + "--min_base_quality", + help="Minimum base quality for correct base call", + type=int, + default=0, + show_default=True, +) +@click.option( + "--ignore_overlaps", + help="Ignore paired overlapping reads", + type=bool, + default=False, + show_default=True, +) +@click.option( + "--sort_index", + help="Sort and index bam file", + type=bool, + default=False, + show_default=True, +) +# TODO: Add samfiles relates conditions +@click.option( + "--min_seq_depth", + help="Minimum sequencing depth at position to be considred", + type=int, + default=20, + show_default=True, +) +@click.option( + "--alt_nuc_count", + help="Minimum alternate nucleotide count fraction", + type=click.FloatRange(0.003, 0.5), + default=0.03, + show_default=True, +) +@click.option( + "-n", + "--cpu", + "cpu", + help="Number of CPUs to use", + type=int, + default=1, + show_default=True, +) +@click.option( + "-c", + "--codoncountfile", + "codoncountfile", + help="Ouput codon counting CSV File", + type=click.File("w"), + default="codon_output.csv", + show_default=True, +) +@click.option("-e", + "--endlen", + "endlen", + help="Ingnore mismached around the end of reads", + type=int, + default=5, + show_default=True) +@click.option( + "-s", + "--subcountfile", + "subcountfile", + help="Ouput subsubstitution counting CSV File", + type=click.File("w"), + default="sub_output.csv", + show_default=True, +) +@click.option( + "-i", + "--indelcountfile", + "indelcountfile", + help="Ouput subsubstitution counting CSV File", + type=click.File("w"), + default="indel_output.csv", + show_default=True, +) +def run( + bam, + rid, + coor_range, + ref, + output_type, # TODO:Integrate in main code + gff, + ignore_orphans, + min_mapping_quality, + min_base_quality, + ignore_overlaps, + sort_index, + min_seq_depth, + alt_nuc_count, + cpu, + endlen, + codoncountfile, + subcountfile, + indelcountfile): + """Expected to that bam file is sorted based on coordinate and indexed.""" + + gff_data = gff_reader.gff2tab(gff) # gff to pandas dataframe + if rid not in gff_data["seq_id"].unique(): # Checking presence of given id + exit("Reference sequence is not in gff file.\n" + f"References in the gff file {gff_data['seq_id'].unique()}\n" + "Exiting") + else: + gff_data = gff_data[gff_data["seq_id"] == + rid] # Filtering gff dataframe + + # reference sequence + try: + ref_seq = pyfaidx.Fasta(ref) + except: + exit(f"{ref} is not in fasta format. Exiting. . . .") + try: + ref_seq = ref_seq[rid] + except: + exit(f"Reference ID {rid} is not in fasta file {ref}") + + # Listing bam files + bam_files = None + + if path.isdir(bam): + bam_files = glob(f"{bam}/*.bam") + if not bam_files: + exit("No bam files found in the given directory.\n" + f"Directory: {bam}\n" + "Exiting") + elif path.isfile(bam) and bam.endswith(".bam"): + bam_files = [bam] + else: + exit("Bam file is not in the correct format.\n" + "Exiting") + + # Sorting and indexing bam files + tmp_dir = tempfile.mkdtemp() + for i, bam in enumerate(bam_files): + bam_files[i] = bammer.check_sort_and_index_bam(bam, tmp_dir=tmp_dir) + + # NOTE: genomic range + coor_range = str2coors(coor_range) + + pool = auto_cpu.cpus(cpu) # CPU Selection + + codon_related = [] + nuc_sub_related = [] + nuc_indel_related = [] + # Parameter to select reads + for start, end in coor_range: + # changes = [] + # TODO: Shift the bottom part and merge in single table + + params = { + "rid": rid, + "start": start, + "end": end, + "gff_data": gff_data, + "output_type": output_type, + "ref": ref, + "endlen": endlen, + "ignore_orphans": ignore_orphans, + "min_mapping_quality": min_mapping_quality, + "min_seq_depth": min_seq_depth, + "min_base_quality": min_base_quality, + "ignore_overlaps": ignore_overlaps, + "alt_nuc_count": alt_nuc_count, + } + + changes = partial(coors_with_changes.coor_with_changes_run, params) + changes = pool.map(changes, bam_files) + + pdf = bpdf.PdfPages("output.pdf") + + for cng in changes: + if output_type in ["codon", "both"]: + codon_related.append(cng[0]) + if output_type in ["nuc", "both"]: + nuc_sub_related.append(cng[1][0]) + nuc_indel_related.append(cng[1][1]) + indel = cng[1][1] + ins = indel[indel["indel"] > 1] + delt = indel[indel["indel"] < 1] + for key, value in cng[-1].items(): + fig = figure(figsize=(8, 6)) + value.index = value.pos + value = value.reindex( + np.arange(value.pos.min(), + value.pos.max() + 1)).fillna(0) + fill_between(value.index, + y1=value.depth, + y2=0, + alpha=0.5, + color='gray', + linewidth=0) + value.to_csv("testxxx.csv") + sub = value[value.pos.isin(cng[1][0].pos)] + scatter(sub["pos"], + sub["depth"], + color="green", + label="Substitutions", + alpha=0.4, + s=10) + + inst = value[value.pos.isin(ins.coor)] + scatter(inst["pos"], + inst["depth"], + color="red", + label="Insertions", + alpha=0.4, + s=10) + deltt = value[value.pos.isin(delt.coor)] + scatter(deltt["pos"], + deltt["depth"], + color="blue", + label="Deletions", + alpha=0.4, + s=10) + title(key) + legend() + + yscale('log') + pdf.savefig(fig) + + pdf.close() + + if output_type in ["codon", "both"]: + + codon_related = pd.concat(codon_related) + if len(codon_related): + + codon_related.insert(0, "Reference ID", rid) + columns = list(codon_related.columns) + columns.remove("Sample") + columns = ["Sample"] + columns + + codon_related = codon_related[columns] + del codon_related["total_codon_count"] + codon_related.to_csv( + codoncountfile, + index=False, + sep="\t" if codoncountfile.name.endswith(".tsv") else ",") + + if output_type in ["nuc", "both"]: + nuc_sub_related = pd.concat(nuc_sub_related) + if len(nuc_sub_related): + nuc_sub_related = nuc_sub_related.rename( + columns={ + 'base_count': 'Nucleotide Frequency', + 'base_pt': 'Nucleotide Percent', + 'ref_base': 'Reference Nucleotide', + 'sample': 'Sample' + }) + nuc_sub_related.insert(0, "Reference ID", rid) + + nuc_sub_related[[ + "Sample", "Reference ID", "pos", "Reference Nucleotide", + "read_count", "Nucleotide Frequency", "Nucleotide Percent" + ]].to_csv(subcountfile, + index=False, + sep="\t" if subcountfile.name.endswith(".tsv") else ",") + if len(nuc_indel_related): + nuc_indel_related = pd.concat(nuc_indel_related) + nuc_indel_related["tp"] = "ins" + nuc_indel_related.loc[nuc_indel_related["indel"] < 0, "tp"] = "del" + nuc_indel_related["indelx"] = nuc_indel_related.apply( + lambda x: + f"{x['tp']}{x['seq']}:{x['indel_read_count']},read_count:{x['depth']}", + axis=1) + nuc_indel_related["indely"] = nuc_indel_related.apply( + lambda x: f"{'%0.2f' % x['indel_read_pt']}", axis=1) + nuc_indel_related = nuc_indel_related.drop( + [ + "indel", "seq", "indel_read_count", "depth", + "indel_read_pt", "tp" + ], + axis=1).rename( + columns={ + "indelx": "Nucleotide Frequency", + "indely": "Nucleotide Percent", + "sample": "Sample" + }) + nuc_indel_related.insert(0, "Reference ID", rid) + + nuc_indel_related[[ + "Sample", "Reference ID", "coor", "Nucleotide Frequency", + "Nucleotide Percent" + ]].to_csv( + indelcountfile, + index=False, + sep="\t" if indelcountfile.name.endswith(".tsv") else ",") + + +if __name__ == "__main__": + run() diff --git a/seqPanther/CodonCounter/__init__.py b/seqPanther/CodonCounter/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/seqPanther/CodonCounter/auto_cpu.py b/seqPanther/CodonCounter/auto_cpu.py new file mode 100644 index 0000000..820e076 --- /dev/null +++ b/seqPanther/CodonCounter/auto_cpu.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +"""Assigns number of CPU should be use by the application.""" + +from multiprocessing import cpu_count, Pool +import warnings + + +def cpus(ncr): + """Return number of cpus to be used based on user provided cores. + uses all the core is 0 is provided. + if given number of cores is greater than the number of cores available, + then it will use n-2 cores. where n is the number of cores available. + + :ncr: number of cores to be used. + :returns: pool + + """ + if ncr <= 0 or ncr > cpu_count(): + ncr = cpu_count() - 2 + warnings.warn("Number of cores provided is either 0, negative or more " + "than the number of cores available.\n" + "Using {} cores".format(ncr)) + return Pool(ncr) diff --git a/seqPanther/CodonCounter/bam_nuc_codon_count.py.bkp b/seqPanther/CodonCounter/bam_nuc_codon_count.py.bkp new file mode 100644 index 0000000..318d6ee --- /dev/null +++ b/seqPanther/CodonCounter/bam_nuc_codon_count.py.bkp @@ -0,0 +1,1057 @@ +#!/usr/bin/env python + +import itertools +from glob import glob +from collections import Counter +from Bio import SeqIO, Seq +import sys +import pysam +import numpy as np +import pandas as pd +import click +import tempfile +from os import path +from functools import partial +from shutil import rmtree + +__author__ = "Anmol Kiran" +__organisation__ = ( + "Malawi-Liverpool-Wellcome Trust, Malawi; University of Liverpool, UK" +) +__github__ = "codemeleon" +__email__ = "akiran@mlw.mw" +__version__ = "0.0.1" + + +_codon_table = { + "TAG": "*", + "TAA": "*", + "TGA": "*", + "TTT": "F", + "TTC": "F", + "TTA": "L", + "TTG": "L", + "TCT": "S", + "TCC": "S", + "TCA": "S", + "TCG": "S", + "TAT": "Y", + "TAC": "Y", + "TGT": "C", + "TGC": "C", + "TGG": "W", + "CTT": "L", + "CTC": "L", + "CTA": "L", + "CTG": "L", + "CCT": "P", + "CCC": "P", + "CCA": "P", + "CCG": "P", + "CAT": "H", + "CAC": "H", + "CAA": "Q", + "CAG": "Q", + "CGT": "R", + "CGC": "R", + "CGA": "R", + "CGG": "R", + "ATT": "I", + "ATC": "I", + "ATA": "I", + "ATG": "M", + "ACT": "T", + "ACC": "T", + "ACA": "T", + "ACG": "T", + "AAT": "N", + "AAC": "N", + "AAA": "K", + "AAG": "K", + "AGT": "S", + "AGC": "S", + "AGA": "R", + "AGG": "R", + "GTT": "V", + "GTC": "V", + "GTA": "V", + "GTG": "V", + "GCT": "A", + "GCC": "A", + "GCA": "A", + "GCG": "A", + "GAT": "D", + "GAC": "D", + "GAA": "E", + "GAG": "E", + "GGT": "G", + "GGC": "G", + "GGA": "G", + "GGG": "G", +} + + +def ranges(i): + def ranges_gen(i): + for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]): + b = list(b) + yield b[0][1], b[-1][1] + + return list(ranges_gen(np.sort(list(set(i))))) + + +def check_sort_and_index_bam(bam_file, tmp_dir): + """ + Checks file is sorted or not. If not, sorts and indexes. + """ + stats = pysam.stats(bam_file).splitlines() + is_sorted = False + for line in stats: + if line.startswith("SN"): + line_split = line.split("\t") + if line_split[1] == "is sorted": + if line_split[2] == "1": + is_sorted = True + break + if is_sorted: + if not path.exists(bam_file + ".bai"): + pysam.index(bam_file) + return bam_file + else: + output_prefix = tmp_dir + "/" + path.split(bam_file)[1] + pysam.sort("-o", output_prefix, bam_file) + pysam.index(output_prefix) + return output_prefix + + +@click.command() +@click.option( + "-bam", + help="Bam files", + # default="/home/devil/Documents/Tools/BitterBits/src/test_data/" + # "K032623-rep-consensus_alignment_sorted.REF_NC_045512.2.bam", + # default="./test_data/NC_045512.2.sorted.bam", + # default="./test_data/InDel/K011018-NC_045512.2_1-consensus_alignment_sorted.bam", # Deletion + default="test_data/InDel/Insert/SRR17051909.sorted.bam", # Inserttion + type=str, + show_default=True, +) +@click.option( + "-rid", + help="Reference ID", + type=str, + default="NC_045512.2", + show_default=True, +) +@click.option( + "-ref", + help="Reference fasta files", + type=click.File("r"), + default="./test_data/NC_045512.2.fasta", + # default="./test_data/NC_045512.2_rev_comp.fasta", + show_default=True, +) +@click.option( + "-coor_range", + help="Coordinates in the reference, zero index based, end exclusive", + type=str, + # default="21000-25000", # Forward sub + # default="4900-9000", # Reverse sub + # default="22279-22300", # For Deletion position + default="22190-22206", # Forward insert + show_default=True, +) +@click.option( + "-gff", + help="Gff Annotation File", + type=click.File("r"), + default="/home/devil/Documents/Tools/BitterBits/src/test_data/genemap.gff", + # default="./test_data/genemap_rev_complement.gff", + show_default=True, +) +@click.option( + "--ignore_orphans", + help="Ignore orphaned (Unpaired) reads", + type=bool, + default=False, + show_default=True, +) +@click.option( + "--min_mapping_quality", + help="Mapping quality of reads", + type=int, + default=0, + show_default=True, +) +@click.option( + "--min_base_quality", + help="Minimum base quality for correct base call", + type=int, + default=0, + show_default=True, +) +@click.option( + "--ignore_overlaps", + help="Ignore paired overlapping reads", + type=bool, + default=False, + show_default=True, +) +@click.option( + "--sort_index", + help="Sort and index bam file", + type=bool, + default=False, + show_default=True, +) +# TODO: Add samfiles relates conditions +@click.option( + "--min_seq_depth", + help="Minimum sequencing depth at position to be considred", + type=int, + default=20, + show_default=True, +) +@click.option( + "--alt_nuc_count", + help="Minimum alternate nucleotide count fraction", + type=click.FloatRange(0.03, 0.5), + default=0.03, + show_default=True, +) +def run( + bam, + rid, + coor_range, + ref, + gff, + ignore_orphans, + min_mapping_quality, + min_base_quality, + ignore_overlaps, + sort_index, + min_seq_depth, + alt_nuc_count, +): + """Expected to that bam file is sorted based on coordinate and indexed.""" + + # NOTE: GFF to table + gff_data = gff.read() + gff_data = gff_data.split("##FASTA")[0] + gff_data = gff_data.split("\n") + gff_data = [x for x in gff_data if (x == "" or x[0] == "#") is False] + gff_data = [x.split("\t") for x in gff_data] + gff_data = pd.DataFrame( + gff_data, + columns=[ + "seq_id", + "source", + "feature", + "start", + "end", + "score", + "strand", + "frame", + "attribute", + ], + ) + gff_data = gff_data.loc[gff_data["feature"] == "CDS"] + gff_data["start"] = gff_data["start"].astype(int) - 1 + gff_data["end"] = gff_data["end"].astype(int) + if rid not in gff_data["seq_id"].unique(): + print("Reference sequence is not in gff file. Exiting.") + print("Reference", gff_data["seq_id"].unique()) + exit() + + # TODO: Need details whether the fist and last are in the same CDS. If not, need to split the CDS. + # TODO: If a region is not part of a CDS, consider that as part of intergenic region. + + # NOTE: reference sequence + sequences = {} + for rec in SeqIO.parse(ref, "fasta"): + sequences[rec.id] = str(rec.seq).upper() + # print(gff_data) + # exit(0) + + # print(sequences["NC_045512.2"][265:268]) + # print(gff_data) + # exit(0) + + # MOTE: Listing bam files + bam_files = [] + + if not bam: + print("Bam file not given.") + sys.exit(0) + if not path.exists(bam): + print(f"Given bam file path {bam} doesn't exist.") + sys.exit(0) + if path.isdir(bam): + bam_files = glob(f"{bam}/*.bam") + if path.isfile(bam): + bam_files = [bam] + + tmp_dir = tempfile.mkdtemp() + for i, bam in enumerate(bam_files): + bam_files[i] = check_sort_and_index_bam(bam, tmp_dir=tmp_dir) + + # NOTE: genomic range + coor_range = coor_range.split("-") + if len(coor_range) == 2: + try: + start = int(coor_range[0]) + except ValueError: + exit("Range format is not correct, value before '-' is not numerical") + try: + end = int(coor_range[1]) + 1 + except Exception as e: + exit("Range format is not correct, value after '-' is not numerical") + elif len(coor_range) == 1: + try: + start = int(coor_range[0]) + end = int(coor_range[0]) + 1 + except: + exit("Given coordinate is not numerical") + else: + print("Coordinate range is not in correct format") + sys.exit(0) + + all_changes = [] + + for bam in bam_files: + sample = path.split(bam)[1].split(".")[0] + samfile = pysam.AlignmentFile(bam, "rb") + + if rid not in samfile.references: + print(f"Given reference {ref} not in given bam file {bam}") + print("List of references") + print(samfile.references) + print(f"Ignoring {bam}") + continue + + # TODO: How will you handle the frame shift? + # TODO: What if there are indels in the gene? + # NOTE: Not for genome with splicing + + iter = samfile.pileup( + rid, + start, + end, + ignore_orphans=ignore_orphans, + # Play with all these three parameters + min_mapping_quality=min_mapping_quality, + min_base_quality=min_base_quality, + ignore_overlaps=ignore_overlaps, + ) + # TODO: First report the coordinates with mismatches only. Then report the codon and amino acid. + # TODO: merge the nucletide which are part of the same codon. + # TODO: Then check if they results in the same amino acid or not. + coordinates_with_change = {} + indel_read_depth = {} + indel_pos_type_size = {"coor": [], "indel": []} + # del_pos_depth = {} + for pileupcol in iter: + # print(help(pileupcol)) + # exit(0) + if pileupcol.n < min_seq_depth: + continue + if (pileupcol.pos >= start) & (pileupcol.pos < end): + # TODO: Include base call quality + bases = {} + nuc_count = 0 + # del_bool = True + + for pread in pileupcol.pileups: + if pread.indel: + if pileupcol.pos not in indel_read_depth: + indel_read_depth[pileupcol.pos] = pileupcol.n + indel_pos_type_size["coor"].append(pileupcol.pos) + indel_pos_type_size["indel"].append(pread.indel) + # print(pread.indel, "kiran", pileupcol.pos) + + if not pread.is_del and not pread.is_refskip: + if ( + pread.alignment.query_sequence[pread.query_position] + not in "ATGC" + ): + continue + if ( + pread.alignment.query_sequence[pread.query_position] + not in bases + ): + bases[ + pread.alignment.query_sequence[pread.query_position] + ] = {"nuc_count": 0, "codon_count": {}} + bases[pread.alignment.query_sequence[pread.query_position]][ + "nuc_count" + ] += 1 + nuc_count += 1 + # NOTE: Deleting nucleotide which have low frequency + + nucs_to_delete = "" + for nuc in bases.keys(): + if bases[nuc]["nuc_count"] < alt_nuc_count * nuc_count: + nucs_to_delete += nuc + for nuc in nucs_to_delete: + del bases[nuc] + if set(bases) - set([sequences[rid][pileupcol.pos]]): + coordinates_with_change[pileupcol.pos] = { + "bases": bases, + # pileupcol.n, # NOTE: Pileup.n doesn't change based on given chriterian + "read_count": nuc_count, + } + indel_read_depth = pd.DataFrame( + { + "coor": list(indel_read_depth.keys()), + "depth": list(indel_read_depth.values()), + } + ) + indel_pos_type_size = pd.DataFrame(indel_pos_type_size) + indel_pos_type_size = ( + indel_pos_type_size.groupby(["coor", "indel"]).size().reset_index() + ).rename(columns={0: "indel_read_count"}) + indel_pos_type_size = indel_pos_type_size.merge( + indel_read_depth, on="coor") + indel_pos_type_size = indel_pos_type_size[ + indel_pos_type_size["indel_read_count"] + > alt_nuc_count * indel_pos_type_size["depth"] + ] + # TODO: use when you need it + frame_shift_indel = indel_pos_type_size[indel_pos_type_size["indel"] % 3 != 0] + indel_pos_type_size = indel_pos_type_size[indel_pos_type_size["indel"] % 3 == 0] + print(coordinates_with_change) + # exit(0) + deletion_frame = {} + insertion_frame = {} + + for _, row in indel_pos_type_size.iterrows(): + t_gff_data = gff_data[ + (gff_data["start"] <= row["coor"]) & ( + gff_data["end"] > row["coor"]) + ] + if len(t_gff_data) == 0: + print(f'No gff data found for {row["coor"]}') + continue + for _, gff_row in t_gff_data.iterrows(): + iter = samfile.pileup( + rid, + row["coor"], + row["coor"] + 1, + ignore_orphans=ignore_orphans, + min_mapping_quality=min_mapping_quality, + min_base_quality=min_base_quality, + ignore_overlaps=ignore_overlaps, + ) + + if row["indel"] < 0: + for pileupcol in iter: + if pileupcol.pos != row["coor"]: + continue + adjusted_coor = row["coor"] + 1 + shift = (adjusted_coor - gff_row["start"]) % 3 # + 1 + r_shift = (3 - shift) % 3 + ref_sub_seq = sequences[rid][ + adjusted_coor + - shift: adjusted_coor + - 1 * row["indel"] + + r_shift + ] + amino_pos = ( + adjusted_coor - gff_row["start"] + ) // 3 # - 1 * row["indel"] + # print(row, shift, row["coor"], gff_row["start"]) + ref_count = 0 + deleted_codon = [] + for pread in pileupcol.pileups: + if (pread.indel < 0) and (pread.indel == row["indel"]): + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position + - shift + + 1: pread.query_position + + r_shift + + 1 + ] + if len(read_sub_seq) % 3 == 0: + deleted_codon.append(read_sub_seq) + if not pread.is_refskip and not pread.is_del: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position + - shift + + 1: pread.query_position + - 1 * row["indel"] + + r_shift + + 1 + ] + # print(read_sub_seq, ref_sub_seq) + + if read_sub_seq == ref_sub_seq: + ref_count += 1 + if pileupcol.pos not in deletion_frame: + deletion_frame[pileupcol.pos] = [] + # deletion_frame[pileupcol.pos].append( + # { # +1 + # "ref": ref_sub_seq, + # "shift": shift, + # "amino_pos": amino_pos, + # "r_shift": r_shift, + # "ref_count": ref_count, + # "alt_count": Counter(deleted_codon), + # } + # ) + print(pileupcol.pos, deletion_frame[pileupcol.pos]) + if gff_row["strand"] == "-": + amino_pos = ( + (gff_row["end"] - gff_row["start"]) // 3 + - (len(ref_sub_seq) - (shift + r_shift)) // 3 + - amino_pos + - (1 if shift else 0) + ) + shift, r_shift = r_shift, shift + for i, codon in enumerate(deleted_codon): + deleted_codon[i] = Seq.Seq( + codon).reverse_complement() + ref_sub_seq = Seq.Seq( + ref_sub_seq).reverse_complement() + + deletion_frame[pileupcol.pos].append( + { # +1 + "ref": ref_sub_seq, + "shift": shift, + "amino_pos": amino_pos, + "r_shift": r_shift, + "ref_count": ref_count, + "alt_count": Counter(deleted_codon), + "strand": "+" if gff_row["strand"] == "+" else "-", + } + ) + # print(deletion_frame, shift, r_shift, row["indel"], "") + break + + if (row["indel"] > 0) and (pread.indel == row["indel"]): + + for pileupcol in iter: + if pileupcol.pos != row["coor"]: + continue + + shift = (row["coor"] - gff_row["start"] + 1) % 3 # + 1 + amino_pos = (row["coor"] - gff_row["start"] + 1) // 3 + + r_shift = (3 - shift) % 3 + ref_sub_seq = sequences[rid][ + row["coor"] - shift + 1: row["coor"] + r_shift + 1 + ] + print(row, gff_row, shift, ref_sub_seq, "anmol") + inserted_codon = [] + ref_count = 0 + + for pread in pileupcol.pileups: + if pread.indel > 0: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position + - shift + + 1: pread.query_position + + row["indel"] + + r_shift + + 1 + ] + inserted_codon.append(read_sub_seq) + if not pread.is_del and not pread.is_refskip: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position + - shift + + 1: pread.query_position + + r_shift + + 1 + ] + # print(read_sub_seq, "test") + if read_sub_seq == ref_sub_seq: + ref_count += 1 + + if gff_row["strand"] == "-": + print( + gff_row["end"], + gff_row["start"], + (gff_row["end"] - gff_row["start"] + 1), + "MM", + ) + amino_pos = ( + (gff_row["end"] - gff_row["start"]) // 3 + - (shift + r_shift) // 3 + - amino_pos + + (1 if shift else 0) + ) + for i, codon in enumerate(inserted_codon): + inserted_codon[i] = Seq.Seq( + codon).reverse_complement() + print(ref_sub_seq, "HAHAHAH") + ref_sub_seq = Seq.Seq( + ref_sub_seq).reverse_complement() + print(ref_sub_seq, "You are ") + + insertion_frame[ + pileupcol.pos # - shift + ] = { # Location is where codon start + "ref": ref_sub_seq, + "amino_pos": amino_pos, + # "ref_codon_position":pileupcol.pos - shift, + "ref_count": ref_count, + "shift": shift, + "r_shift": r_shift, + "alt_count": Counter(inserted_codon), + } + print(insertion_frame) + # TODO: Count support the reference + # print(set(inserted_codon), shift, r_shift) + break + print(row["coor"], ref_sub_seq) + # print(row["coor"], row["indel"]) + + # shift = row["coor"] - gff_row["end"] + + # TODO: How will you count supported codons + # NOTE: Considerring that Deletion is in coding region and deletion is one codon - This is Tricky + # exit(0) + # coordinates_with_change = {21011: coordinates_with_change[21011]} + # print(coordinates_with_change) + # NOTE: Dropping the coodinates where ref bases are more 97% + # exit(0) + + keys = set(coordinates_with_change) + # print(keys, len(keys)) + # print(coordinates_with_change) + # exit(0) + + for ( + _, + row, + ) in ( + gff_data.iterrows() + ): # TODO: Invert the iterations with reported coordinate + # TODO: End coordinate might need to be included + selected_coordinates = keys & set(range(row["start"], row["end"])) + if selected_coordinates: + # TODO: Add count of codon. Ignore with ambigious nucleotide and gaps + # TODO: Check if there is any 3 base indels + for selected_coordinate in selected_coordinates: + coordinates_with_change[selected_coordinate]["start"] = row["start"] + coordinates_with_change[selected_coordinate]["end"] = row["end"] + coordinates_with_change[selected_coordinate]["strand"] = row[ + "strand" + ] + shift = (selected_coordinate - row["start"]) % 3 + # print(shift) + # exit(0) + iter = samfile.pileup( + rid, + selected_coordinate, + selected_coordinate + 1, + ignore_orphans=ignore_orphans, + min_mapping_quality=min_base_quality, + min_base_quality=min_base_quality, + ignore_overlaps=ignore_overlaps, + ) + # TODO: Discuss with san to use codon count or nuc count to detect proportion + total_codon_count = 0 + for pileupcol in iter: + if pileupcol.pos != selected_coordinate: + continue + for pread in pileupcol.pileups: + if not pread.is_del and not pread.is_refskip: + codon = pread.alignment.query_sequence[ + pread.query_position + - shift: pread.query_position + - shift + + 3 + ] + # TODO: Count codon can keep the same count distribution as the same as bases + if (codon in _codon_table) and ( + pread.alignment.query_sequence[pread.query_position] + in coordinates_with_change[pileupcol.pos]["bases"] + ): + + if ( + codon + not in coordinates_with_change[pileupcol.pos][ + "bases" + ][ + pread.alignment.query_sequence[ + pread.query_position + ] + ][ + "codon_count" + ] + ): + coordinates_with_change[pileupcol.pos]["bases"][ + pread.alignment.query_sequence[ + pread.query_position + ] + ]["codon_count"][codon] = 0 + coordinates_with_change[pileupcol.pos]["bases"][ + pread.alignment.query_sequence[ + pread.query_position + ] + ]["codon_count"][codon] += 1 + total_codon_count += 1 + + elif len(codon) > 3: + print(codon, selected_coordinate) + + if pileupcol.pos == selected_coordinate: + # print( + # selected_coordinate, + # coordinates_with_change[selected_coordinate], + # ) + # exit(0) + break + # TODO: Removing less less common codons + coordinates_with_change[selected_coordinate][ + "total_codon_count" + ] = total_codon_count + + # print( + # selected_coordinate, + # coordinates_with_change[selected_coordinate], + # ) + # exit(0) + + # row["strand"] = "+" + ref_base = sequences[rid][selected_coordinate] + ref_codon = sequences[rid][ + selected_coordinate - shift: selected_coordinate - shift + 3 + ] # TODO: Integrate the ref codon in dictionary itself + # print(ref_codon, "Anmol") + # NOTE: Reverse complement + if row["strand"] == "-": + ref_codon = str( + Seq.Seq(ref_codon).reverse_complement()) + ref_base = str(Seq.Seq(ref_base).reverse_complement()) + # print(ref_codon) + for k in coordinates_with_change[selected_coordinate]["bases"]: + # TODO: base need to be reverse complemented + + codon_count = coordinates_with_change[selected_coordinate][ + "bases" + ][k]["codon_count"] + new_codon_count = {} + for codon in codon_count: + new_codon_count[ + str(Seq.Seq(codon).reverse_complement()) + ] = codon_count[codon] + + coordinates_with_change[selected_coordinate]["bases"][k][ + "codon_count" + ] = new_codon_count + new_base = {} + for k in coordinates_with_change[selected_coordinate]["bases"]: + new_base[ + str(Seq.Seq(k).reverse_complement()) + ] = coordinates_with_change[selected_coordinate]["bases"][k] + coordinates_with_change[selected_coordinate]["bases"] = new_base + coordinates_with_change[selected_coordinate][ + "ref_codon" + ] = ref_codon + coordinates_with_change[selected_coordinate]["codon_pos"] = ( + selected_coordinate - shift + ) + coordinates_with_change[selected_coordinate]["ref_base"] = ref_base + # print( + # selected_coordinate, + # coordinates_with_change[selected_coordinate], + # ) + # if selected_coordinate == 21215: + # print(row["start"]) + # exit(0) + + if row["strand"] == "+": + + amino_pos = (selected_coordinate - + row["start"]) // 3 + 1 + + else: + amino_pos = (row["end"] - selected_coordinate) // 3 + 1 + + coordinates_with_change[selected_coordinate][ + "amino_pos" + ] = amino_pos + # print( + # selected_coordinate, + # coordinates_with_change[selected_coordinate], + # ) + # exit(0) + + print(deletion_frame) + delete_final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt_codon_count": [], + # "total_codon_count": [], + "coor": [], + "ref_codon": [], + "ref_codon_count": [], + # "ref_codon_position":[] + } + # for coor in deletion_frame: + # for info in deletion_frame[coor]: + # for inserted_seq in deletion_frame[coor]["alt_count"]: + # delete_final_table["Amino Acid Change"].append( + # f"{Seq.Seq(deletion_frame[coor]['ref']).translate()}{deletion_frame[coor]['amino_pos']}{Seq.Seq(inserted_seq).translate()}" + # ) + # delete_final_table["Codon Change"].append( + # f"{coor+1}{deletion_frame[coor]['ref']}>{inserted_seq}" + # ) + # delete_final_table["Nucleotide Change"].append( + # f"{coor+1+deletion_frame[coor]['shift']}{deletion_frame[coor]['ref'][deletion_frame[coor]['shift']:-1*deletion_frame[coor]['r_shift'] if deletion_frame[coor]['shift'] else len(deletion_frame[coor]['ref'])]}>" + # ) + # # delete_final_table["Codon Change"].append(f"{}{}>{}") + # delete_final_table["coor"].append(coor) + # delete_final_table["ref_codon"].append(deletion_frame[coor]["ref"]) + # delete_final_table["ref_codon_count"].append( + # deletion_frame[coor]["ref_count"] + # ) + # delete_final_table["Sample"].append(sample) + # delete_final_table["alt_codon"].append(inserted_seq) + # delete_final_table["alt_codon_count"].append( + # deletion_frame[coor]["alt_count"][inserted_seq] + # ) + + for coor in deletion_frame: + for info in deletion_frame[coor]: + print(coor, info) + for inserted_seq in info["alt_count"]: + delete_final_table["Amino Acid Change"].append( + f"{Seq.Seq(info['ref']).translate()}{info['amino_pos']}{Seq.Seq(inserted_seq).translate()}" + ) + delete_final_table["Codon Change"].append( + f"{coor+(1 if info['shift'] else 2)}{info['ref']}>{inserted_seq}" + ) + delete_final_table["Nucleotide Change"].append( + f"{coor+(1 if info['shift'] else 2) +(info['shift'] if info['strand']=='+' else info['r_shift'])}{info['ref'][info['shift']:-1*info['r_shift'] if info['shift'] else len(info['ref'])]}>" + ) + # delete_final_table["Codon Change"].append(f"{}{}>{}") + delete_final_table["coor"].append(coor) + delete_final_table["ref_codon"].append(info["ref"]) + delete_final_table["ref_codon_count"].append( + info["ref_count"]) + delete_final_table["Sample"].append(sample) + delete_final_table["alt_codon"].append(inserted_seq) + delete_final_table["alt_codon_count"].append( + info["alt_count"][inserted_seq] + ) + delete_final_table = pd.DataFrame(delete_final_table) + delete_final_table = delete_final_table[ + delete_final_table["alt_codon_count"] + >= alt_nuc_count + * ( + delete_final_table["alt_codon_count"] + + delete_final_table["ref_codon_count"] + ) + ] + if not delete_final_table.empty: + delete_final_table["codon_count"] = delete_final_table.apply( + lambda x: f"{x['ref_codon']}-{x['ref_codon_count']};{x['alt_codon']}-{x['alt_codon_count']}", + axis=1, + ) + delete_final_table = delete_final_table.drop( + ["ref_codon", "ref_codon_count", "alt_codon", "alt_codon_count", "coor"], + axis=1, + ) + all_changes.append(delete_final_table) + # print(delete_final_table) + + # exit(0) + insert_final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt_codon_count": [], + # "total_codon_count": [], + "coor": [], + "ref_codon": [], + "ref_codon_count": [], + # "ref_codon_position":[] + } + for coor in insertion_frame: + for inserted_seq in insertion_frame[coor]["alt_count"]: + insert_final_table["Amino Acid Change"].append( + f"{Seq.Seq(insertion_frame[coor]['ref']).translate()}{insertion_frame[coor]['amino_pos']}{Seq.Seq(inserted_seq).translate()}" + ) + insert_final_table["Codon Change"].append( + f"{coor+1}{insertion_frame[coor]['ref']}>{inserted_seq}" + ) + insert_final_table["Nucleotide Change"].append( + f"{coor+1+insertion_frame[coor]['shift']}>{inserted_seq[insertion_frame[coor]['shift']:len(inserted_seq)-1*insertion_frame[coor]['r_shift']]}" + ) + # insert_final_table["Codon Change"].append(f"{}{}>{}") + insert_final_table["coor"].append(coor) + insert_final_table["ref_codon"].append( + insertion_frame[coor]["ref"]) + insert_final_table["ref_codon_count"].append( + insertion_frame[coor]["ref_count"] + ) + insert_final_table["Sample"].append(sample) + insert_final_table["alt_codon"].append(inserted_seq) + insert_final_table["alt_codon_count"].append( + insertion_frame[coor]["alt_count"][inserted_seq] + ) + insert_final_table = pd.DataFrame(insert_final_table) + insert_final_table = insert_final_table[ + insert_final_table["alt_codon_count"] + >= alt_nuc_count + * ( + insert_final_table["alt_codon_count"] + + insert_final_table["ref_codon_count"] + ) + ] + print(insert_final_table, "test buddy") + if not insert_final_table.empty: + insert_final_table["codon_count"] = insert_final_table.apply( + lambda x: f"{x['ref_codon']}-{x['ref_codon_count']};{x['alt_codon']}-{x['alt_codon_count']}", + axis=1, + ) + insert_final_table = insert_final_table.drop( + ["ref_codon", "ref_codon_count", "alt_codon", "alt_codon_count", "coor"], + axis=1, + ) + all_changes.append(insert_final_table) + + # print(insert_final_table, "Kiran") + + ref_codon_count = {"coor": [], "ref_codon": [], "ref_codon_count": []} + final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt_codon_count": [], + "total_codon_count": [], + "coor": [], + "ref_codon": [], + } + for coor in coordinates_with_change: + bases = coordinates_with_change[coor]["bases"] + read_count = coordinates_with_change[coor]["read_count"] + ref_codon_bool = False + for base in bases: + codon_counts = bases[base]["codon_count"] + for codon in codon_counts: + if codon == coordinates_with_change[coor]["ref_codon"]: + ref_codon_bool = True + ref_codon_count["coor"].append(coor) + ref_codon_count["ref_codon"].append( + coordinates_with_change[coor]["ref_codon"] + ) + ref_codon_count["ref_codon_count"].append( + codon_counts[codon]) + continue + if (base == coordinates_with_change[coor]["ref_base"]) or ( + _codon_table[coordinates_with_change[coor] + ["ref_codon"]] + == _codon_table[codon] + ): + continue + final_table["Amino Acid Change"].append( + f"{_codon_table[coordinates_with_change[coor]['ref_codon']]}{coordinates_with_change[coor]['amino_pos']}{_codon_table[codon]}" + ) + final_table["Nucleotide Change"].append( + f'{coor}{coordinates_with_change[coor]["ref_base"]}>{base}' + ) + final_table["Codon Change"].append( + f'{coordinates_with_change[coor]["codon_pos"]}{coordinates_with_change[coor]["ref_codon"]}>{codon}' + ) + final_table["Sample"].append(sample) + final_table["alt_codon"].append(codon) + final_table["alt_codon_count"].append(codon_counts[codon]) + final_table["total_codon_count"].append( + coordinates_with_change[coor]["total_codon_count"] + ) + final_table["coor"].append(coor) + final_table["ref_codon"].append( + coordinates_with_change[coor]["ref_codon"] + ) + # print( + # "Amino acid change", + # f"{_codon_table[coordinates_with_change[coor]['ref_codon']]}{coordinates_with_change[coor]['amino_pos']}{_codon_table[codon]}", + # ) + # print( + # "Nucleotide change", + # f'{coor}{coordinates_with_change[coor]["ref_base"]}>{base}', + # ) + # print( + # "Codon Change", + # f'{coordinates_with_change[coor]["codon_pos"]}{coordinates_with_change[coor]["ref_codon"]}>{codon}', + # ) + # print(sample) + # print(coor) + # print(base, read_count) + # print(codon, codon_counts[codon]) + if not ref_codon_bool: + ref_codon_count["coor"].append(coor) + ref_codon_count["ref_codon"].append( + coordinates_with_change[coor]["ref_codon"] + ) + ref_codon_count["ref_codon_count"].append(0) + final_table = pd.DataFrame(final_table) + ref_codon_count = pd.DataFrame(ref_codon_count) + final_table = final_table.merge( + ref_codon_count, on=["coor", "ref_codon"], how="inner" + ) + final_table = final_table[ + (final_table["total_codon_count"] >= min_seq_depth) + & ( + final_table["alt_codon_count"] + > alt_nuc_count * final_table["total_codon_count"] + ) + ] + if not final_table.empty: + + final_table["codon_count"] = final_table[ + ["ref_codon", "ref_codon_count", "alt_codon", "alt_codon_count"] + ].apply( + lambda x: f"{x['ref_codon']}-{x['ref_codon_count']};{x['alt_codon']}-{x['alt_codon_count']}", + axis=1, + ) + final_table = final_table.drop( + [ + "ref_codon", + "ref_codon_count", + "alt_codon", + "alt_codon_count", + "coor", + "total_codon_count", + ], + axis=1, + ) + + # print(final_table) + all_changes.append(final_table) + all_changes = pd.concat(all_changes) + all_changes = all_changes.pivot( + index=["Amino Acid Change", "Nucleotide Change", "Codon Change"], + columns="Sample", + values="codon_count", + ).reset_index() + print(all_changes) + all_changes.to_csv(f"all_changes.csv", sep="\t", index=False) + # print(ref_codon_count) + # exit(0) + + # final_table = pd.DataFrame(final_table) + # final_table = final_table.pivot( + # index=["Amino Acid Change", "Nucleotide Change", "Codon Change"], + # columns="Samples", + # values="Codon Count", + # ).reset_index() + + # print(final_table) + # TODO: Try to create multiple tree and concat and then pivot + rmtree(tmp_dir) + + +if __name__ == "__main__": + run() diff --git a/seqPanther/CodonCounter/bammer.py b/seqPanther/CodonCounter/bammer.py new file mode 100644 index 0000000..2da85a5 --- /dev/null +++ b/seqPanther/CodonCounter/bammer.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +import pysam +from os import path + + +def check_sort_and_index_bam(bam_file, tmp_dir): + """ + Checks file is sorted or not. If not, sorts and indexes. + """ + stats = pysam.stats(bam_file).splitlines() + is_sorted = False + for line in stats: + if line.startswith("SN"): + line_split = line.split("\t") + if line_split[1] == "is sorted": + if line_split[2] == "1": + is_sorted = True + break + if is_sorted: + if not path.exists(bam_file + ".bai"): + pysam.index(bam_file) + return bam_file + else: + output_prefix = tmp_dir + "/" + path.split(bam_file)[1] + pysam.sort("-o", output_prefix, bam_file) + pysam.index(output_prefix) + return output_prefix diff --git a/seqPanther/CodonCounter/codon_table.py b/seqPanther/CodonCounter/codon_table.py new file mode 100644 index 0000000..6a3bf5d --- /dev/null +++ b/seqPanther/CodonCounter/codon_table.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# Codon table + +codon_table = { + "TAG": "*", + "TAA": "*", + "TGA": "*", + "TTT": "F", + "TTC": "F", + "TTA": "L", + "TTG": "L", + "TCT": "S", + "TCC": "S", + "TCA": "S", + "TCG": "S", + "TAT": "Y", + "TAC": "Y", + "TGT": "C", + "TGC": "C", + "TGG": "W", + "CTT": "L", + "CTC": "L", + "CTA": "L", + "CTG": "L", + "CCT": "P", + "CCC": "P", + "CCA": "P", + "CCG": "P", + "CAT": "H", + "CAC": "H", + "CAA": "Q", + "CAG": "Q", + "CGT": "R", + "CGC": "R", + "CGA": "R", + "CGG": "R", + "ATT": "I", + "ATC": "I", + "ATA": "I", + "ATG": "M", + "ACT": "T", + "ACC": "T", + "ACA": "T", + "ACG": "T", + "AAT": "N", + "AAC": "N", + "AAA": "K", + "AAG": "K", + "AGT": "S", + "AGC": "S", + "AGA": "R", + "AGG": "R", + "GTT": "V", + "GTC": "V", + "GTA": "V", + "GTG": "V", + "GCT": "A", + "GCC": "A", + "GCA": "A", + "GCG": "A", + "GAT": "D", + "GAC": "D", + "GAA": "E", + "GAG": "E", + "GGT": "G", + "GGC": "G", + "GGA": "G", + "GGG": "G", +} diff --git a/seqPanther/CodonCounter/coors_with_changes.py b/seqPanther/CodonCounter/coors_with_changes.py new file mode 100644 index 0000000..b5b6314 --- /dev/null +++ b/seqPanther/CodonCounter/coors_with_changes.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python +import pysam +import pandas as pd + +import pyfaidx +from os import path + +from .subs import sub_table +from .gff_reader import gff2tab +from .indel_frames import indel_frames + + +def changed_coordinates(params, bam): + print(f"Analysing {bam}.") + rid = params["rid"] + start = params["start"] + end = params["end"] + gff_data = params["gff_data"] + endlen = params['endlen'] + sequences = params["sequences"] + ignore_orphans = params["ignore_orphans"] + min_mapping_quality = params["min_mapping_quality"] + min_base_quality = params["min_base_quality"] + min_seq_depth = params["min_seq_depth"] + alt_nuc_count = params["alt_nuc_count"] + ignore_overlaps = params["ignore_overlaps"] + + samfile = pysam.AlignmentFile(bam, "rb") + if rid not in samfile.references: + print(f"Given reference {ref} not in given bam file {bam}") + print("List of references") + print(samfile.references) + print(f"Ignoring {bam}") + return + iter = samfile.pileup( + rid, + start, + end, + ignore_orphans=ignore_orphans, + min_base_quality=min_base_quality, + min_mapping_quality=min_mapping_quality, + ignore_overlaps=ignore_overlaps, + ) + coordinates_with_change = {} + indel_read_depth = {} + indel_pos_type_size = {"coor": [], "indel": [], "seq": []} + # del_pos_depth = {} + depth = {'pos': [], 'depth': []} + for pileupcol in iter: + if pileupcol.n < min_seq_depth: + continue + if (pileupcol.pos >= start) & (pileupcol.pos < end): + # TODO: Include base call quality + bases = {} + nuc_count = 0 + nuc_indel_count = 0 + + for pread in pileupcol.pileups: + # print(pread) + + if pread.indel: + nuc_indel_count += 1 + if pileupcol.pos not in indel_read_depth: + indel_read_depth[pileupcol.pos] = pileupcol.n + indel_pos_type_size["coor"].append(pileupcol.pos) + indel_pos_type_size["indel"].append(pread.indel) + if pread.indel > 0: + indel_pos_type_size["seq"].append( + pread.alignment.query_sequence[ + pread.query_position:pread.query_position + + pread.indel]) + else: + + indel_pos_type_size["seq"].append("") + # TODO: The sequences for read and reference + + if not pread.is_del and not pread.is_refskip: + if (pread.query_position < endlen + or (len(pread.alignment.query_sequence) - + pread.query_position) < endlen): + continue + # if (pread.alignment.query_sequence[pread.query_position] + # not in + # "ATGC" # WARNING: Should we allow other nucleotide + # ): + # continue + if (pread.alignment.query_sequence[pread.query_position] + not in bases): + bases[pread.alignment.query_sequence[ + pread.query_position]] = { + "nuc_count": 0, + "codon_count": {}, + } + bases[pread.alignment.query_sequence[ + pread.query_position]]["nuc_count"] += 1 + nuc_count += 1 + # NOTE: Deleting nucleotide which have low frequency + depth['pos'].append(pileupcol.pos) + depth['depth'].append( + nuc_count + nuc_indel_count) # TODO: Recheck this information + + nucs_to_delete = "" + for nuc in bases.keys(): + if bases[nuc]["nuc_count"] < alt_nuc_count * nuc_count: + nucs_to_delete += nuc + for nuc in nucs_to_delete: + del bases[nuc] + if set(bases) - set([sequences[pileupcol.pos].seq]): + coordinates_with_change[pileupcol.pos] = { + "bases": bases, + # pileupcol.n, # NOTE: Pileup.n doesn't change based on given chriterian + "read_count": nuc_count, + } + indel_read_depth = pd.DataFrame({ + "coor": list(indel_read_depth.keys()), + "depth": list(indel_read_depth.values()), + }) + indel_pos_type_size = pd.DataFrame(indel_pos_type_size) + indel_pos_type_size = (indel_pos_type_size.groupby( + ["coor", "indel", + "seq"]).size().reset_index().rename(columns={0: "indel_read_count"})) + indel_pos_type_size = indel_pos_type_size.merge(indel_read_depth, + on="coor") + indel_pos_type_size_full = indel_pos_type_size.copy() + indel_pos_type_size = indel_pos_type_size[ + indel_pos_type_size["indel_read_count"] > alt_nuc_count * + indel_pos_type_size["depth"]] + # frame_shift_indel = indel_pos_type_size[indel_pos_type_size["indel"] % + # 3 != 0] + indel_pos_type_size = indel_pos_type_size[indel_pos_type_size["indel"] % + 3 == 0] + # pd.DataFrame(depth).to_csv("testtt.csv", index=False) + # print(coordinates_with_change, indel_pos_type_size_full) + + return coordinates_with_change, indel_pos_type_size, indel_pos_type_size_full, depth + + +# if __name__ == "__main__": +# # NOTE: This part is only for testing of the scripts +# sequences = "" +# for rec in SeqIO.parse( +# "/home/devil/Documents/Tools/CodonCounter/test_data/NC_045512.2.fasta", "fasta" +# ): +# if rec.id == "NC_045512.2": +# sequences = rec.seq + + +# params = { +# "rid": "NC_045512.2", +# "start": 21000, +# "end": 25000, +# "gff_data": gff2tab( +# open("/home/devil/Documents/Tools/CodonCounter/test_data/genemap.gff") +# ), +# "sequences": sequences, +# "ignore_orphans": False, +# "min_seq_depth": 10, +# "min_mapping_quality": 0, +# "min_base_quality": 0, +# "ignore_overlaps": True, +# "alt_nuc_count": 0.03, +# } +# bam = "/home/devil/Documents/Tools/CodonCounter/test_data/forward/K011018_f_sorted.bam" +def coor_with_changes_run(params, bam): + params["sequences"] = pyfaidx.Fasta(params["ref"])[params["rid"]] + merged_table = None + merged_table_nuc = None + res = changed_coordinates(params, bam) + if params["output_type"] in ["codon", "both"]: + indelframes = indel_frames(res[1], bam, params) + subs_table = sub_table(res[0], bam, params) + merged_table = pd.concat([indelframes[0], indelframes[1], subs_table]) + if params["output_type"] in ["nuc", "both"]: + # TODO: First json to table + flb = path.split(bam)[1].split(".")[0] + res_indel = res[2] + res_indel.loc[res_indel["indel"] < 0, + "seq"] = res_indel.loc[res_indel["indel"] < 0].apply( + lambda x: params["sequences"][x["coor"]:x["coor"] - + x["indel"]].seq, + axis=1) + res_indel["sample"] = flb + res_sub = res[0] + res_table = { + "pos": [], + "read_count": [], + "base_count": [], + "base_pt": [] + } + for pos in res_sub: + # print(pos) + res_table["pos"].append(pos) + res_table["read_count"].append(res_sub[pos]["read_count"]) + base_count = [] + base_pt = [] + for base in res_sub[pos]["bases"]: + base_count.append( + f"{base}: {res_sub[pos]['bases'][base]['nuc_count']}") + pt_val = '%.f' % (res_sub[pos]['bases'][base]['nuc_count'] * + 100. / res_sub[pos]['read_count']) + base_pt.append(f"{base}: {pt_val}") + res_table["base_count"].append(",".join(base_count).replace( + " ", "")) + res_table["base_pt"].append(",".join(base_pt).replace(" ", "")) + res_table = pd.DataFrame(res_table) + res_table["sample"] = flb + res_table["ref_base"] = res_table.apply( + lambda x: params["sequences"][x["pos"]].seq, axis=1) + res_indel['indel_read_pt'] = res_indel[ + 'indel_read_count'] * 100. / res_indel['depth'] + # print(res_indel) + merged_table_nuc = [res_table, res_indel] + return merged_table, merged_table_nuc, {flb: pd.DataFrame(res[-1])} diff --git a/seqPanther/CodonCounter/gff_reader.py b/seqPanther/CodonCounter/gff_reader.py new file mode 100755 index 0000000..b5303b6 --- /dev/null +++ b/seqPanther/CodonCounter/gff_reader.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +import pandas as pd + + +"""Reads gff file buffer""" + + +def gff2tab(gff_buffer): + """Convert gff file information to pandas data frame for CDS. + + :gff_buffer: gff file buffer + :returns: pandas data frame for CDS + """ + gff_data = gff_buffer.read() + gff_data = gff_data.split("##FASTA")[0] + gff_data = gff_data.split("\n") + gff_data = [x for x in gff_data if (x == "" or x[0] == "#") is False] + gff_data = [x.split("\t") for x in gff_data] + gff_data = pd.DataFrame( + gff_data, + columns=[ + "seq_id", + "source", + "feature", + "start", + "end", + "score", + "strand", + "frame", + "attribute", + ], + ) + gff_data = gff_data.loc[gff_data["feature"] == "CDS"] + gff_data["start"] = gff_data["start"].astype(int) - 1 + gff_data["end"] = gff_data["end"].astype(int) + return gff_data diff --git a/seqPanther/CodonCounter/indel_frames.py b/seqPanther/CodonCounter/indel_frames.py new file mode 100755 index 0000000..e07a74d --- /dev/null +++ b/seqPanther/CodonCounter/indel_frames.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python + +import pysam +import pandas as pd +from collections import Counter + +from Bio import Seq +import pyfaidx +from os import path + + +def indel_frames(indel_pos_type_size, bam, params): + rid = params["rid"] + gff_data = params["gff_data"] + sequences = pyfaidx.Fasta(params["ref"])[rid] + ignore_orphans = params["ignore_orphans"] + min_mapping_quality = params["min_mapping_quality"] + min_base_quality = params["min_base_quality"] + ignore_overlaps = params["ignore_overlaps"] + alt_nuc_count = params["alt_nuc_count"] + sample = path.split(bam)[1].split(".bam")[0] + + deletion_frame = {} + insertion_frame = {} + samfile = pysam.AlignmentFile(bam, "rb") + + for _, row in indel_pos_type_size.iterrows(): + t_gff_data = gff_data[(gff_data["start"] <= row["coor"]) + & (gff_data["end"] > row["coor"])] + if len(t_gff_data) == 0: + print(f'No gff data found for {row["coor"]}') + continue + for _, gff_row in t_gff_data.iterrows(): + iter = samfile.pileup( + rid, + row["coor"], + row["coor"] + 1, + ignore_orphans=ignore_orphans, + min_mapping_quality=min_mapping_quality, + min_base_quality=min_base_quality, + ignore_overlaps=ignore_overlaps, + ) + + if row["indel"] < 0: + for pileupcol in iter: + if pileupcol.pos != row["coor"]: + continue + adjusted_coor = row["coor"] + 1 + shift = (adjusted_coor - gff_row["start"]) % 3 # + 1 + r_shift = (3 - shift) % 3 + ref_sub_seq = sequences[adjusted_coor - + shift:adjusted_coor - + 1 * row["indel"] + r_shift].seq + amino_pos = (adjusted_coor - + gff_row["start"]) // 3 # - 1 * row["indel"] + ref_count = 0 + deleted_codon = [] + for pread in pileupcol.pileups: + if (pread.indel < 0) and (pread.indel == row["indel"]): + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position - shift + + 1:pread.query_position + r_shift + 1] + if len(read_sub_seq) % 3 == 0: + deleted_codon.append(read_sub_seq) + if not pread.is_refskip and not pread.is_del: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position - shift + + 1:pread.query_position - 1 * row["indel"] + + r_shift + 1] + + if read_sub_seq == ref_sub_seq: + ref_count += 1 + if pileupcol.pos not in deletion_frame: + deletion_frame[pileupcol.pos] = [] + # print(pileupcol.pos, deletion_frame[pileupcol.pos]) + if gff_row["strand"] == "-": + amino_pos = ((gff_row["end"] - gff_row["start"]) // 3 - + (len(ref_sub_seq) - + (shift + r_shift)) // 3 - amino_pos - + (1 if shift else 0)) + shift, r_shift = r_shift, shift + for i, codon in enumerate(deleted_codon): + deleted_codon[i] = Seq.Seq( + codon).reverse_complement() + ref_sub_seq = Seq.Seq(ref_sub_seq).reverse_complement() + + deletion_frame[pileupcol.pos].append( + { # +1 + "ref": ref_sub_seq, + "shift": shift, + "amino_pos": amino_pos, + "r_shift": r_shift, + "ref_count": ref_count, + "alt_count": Counter(deleted_codon), + "strand": "+" if gff_row["strand"] == "+" else "-", + } + ) + break + + if (row["indel"] > 0) and (pread.indel == row["indel"]): + + for pileupcol in iter: + if pileupcol.pos != row["coor"]: + continue + + shift = (row["coor"] - gff_row["start"] + 1) % 3 # + 1 + amino_pos = (row["coor"] - gff_row["start"] + 1) // 3 + + r_shift = (3 - shift) % 3 + ref_sub_seq = sequences[row["coor"] - shift + + 1:row["coor"] + r_shift + 1].seq + # print(row, gff_row, shift, ref_sub_seq, "anmol") + inserted_codon = [] + ref_count = 0 + + for pread in pileupcol.pileups: + if pread.indel > 0: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position - shift + + 1:pread.query_position + row["indel"] + + r_shift + 1] + inserted_codon.append(read_sub_seq) + if not pread.is_del and not pread.is_refskip: + read_sub_seq = pread.alignment.query_sequence[ + pread.query_position - shift + + 1:pread.query_position + r_shift + 1] + if read_sub_seq == ref_sub_seq: + ref_count += 1 + + if gff_row["strand"] == "-": + # print( + # gff_row["end"], + # gff_row["start"], + # (gff_row["end"] - gff_row["start"] + 1), + # "MM", + # ) + amino_pos = ((gff_row["end"] - gff_row["start"]) // 3 - + (shift + r_shift) // 3 - amino_pos + + (1 if shift else 0)) + for i, codon in enumerate(inserted_codon): + inserted_codon[i] = Seq.Seq( + codon).reverse_complement() + ref_sub_seq = Seq.Seq(ref_sub_seq).reverse_complement() + + insertion_frame[ + pileupcol.pos # - shift + ] = { # Location is where codon start + "ref": ref_sub_seq, + "amino_pos": amino_pos, + "ref_count": ref_count, + "shift": shift, + "r_shift": r_shift, + "alt_count": Counter(inserted_codon), + } + break + delete_final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt_codon_count": [], + "coor": [], + "ref_codon": [], + "ref_codon_count": [], + "total_codon_count": [], + } + for coor in deletion_frame: + codon_count = 0 + for x in deletion_frame[coor]: + codon_count += x["ref_count"] + sum(x["alt_count"].values()) + + for info in deletion_frame[coor]: + # print(coor, info) + for inserted_seq in info["alt_count"]: + delete_final_table["Amino Acid Change"].append( + f"{Seq.Seq(info['ref']).translate()}{info['amino_pos']}{Seq.Seq(inserted_seq).translate()}" + ) + delete_final_table["Codon Change"].append( + f"{coor+(1 if info['shift'] else 2)}:{info['ref']}>{inserted_seq}" + ) + delete_final_table["Nucleotide Change"].append( + f"{coor+(1 if info['shift'] else 2) +(info['shift'] if info['strand']=='+' else info['r_shift'])}:{info['ref'][info['shift']:-1*info['r_shift'] if info['shift'] else len(info['ref'])]}>" + ) + # delete_final_table["Codon Change"].append(f"{}{}>{}") + delete_final_table["coor"].append(coor) + delete_final_table["ref_codon"].append(info["ref"]) + delete_final_table["ref_codon_count"].append(info["ref_count"]) + delete_final_table["Sample"].append(sample) + delete_final_table["alt_codon"].append(inserted_seq) + delete_final_table["alt_codon_count"].append( + info["alt_count"][inserted_seq]) + delete_final_table["total_codon_count"].append(codon_count) + delete_final_table = pd.DataFrame(delete_final_table) + delete_final_table = delete_final_table[ + delete_final_table["alt_codon_count"] >= alt_nuc_count * + (delete_final_table["alt_codon_count"] + + delete_final_table["ref_codon_count"])] + if not delete_final_table.empty: + delete_final_table["codon_count"] = delete_final_table.apply( + lambda x: + f"{x['ref_codon']}-{x['ref_codon_count']};{x['alt_codon']}-{x['alt_codon_count']}", + axis=1, + ) + delete_final_table["codon_percent"] = delete_final_table.apply( + lambda x: + f"{x['ref_codon']}-{'%0.2f' % (x['ref_codon_count']*100./x['total_codon_count'])};{x['alt_codon']}-{'%0.2f' % (x['alt_codon_count']*100./x['total_codon_count'])}", + axis=1, + ) + delete_final_table = delete_final_table.drop( + [ + "ref_codon", "ref_codon_count", "alt_codon", "alt_codon_count", + "coor" + ], + axis=1, + ) + + insert_final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt_codon_count": [], + "coor": [], + "ref_codon": [], + "ref_codon_count": [], + } + for coor in insertion_frame: + for inserted_seq in insertion_frame[coor]["alt_count"]: + insert_final_table["Amino Acid Change"].append( + f"{Seq.Seq(insertion_frame[coor]['ref']).translate()}{insertion_frame[coor]['amino_pos']}{Seq.Seq(inserted_seq).translate()}" + ) + insert_final_table["Codon Change"].append( + f"{coor+1}:{insertion_frame[coor]['ref']}>{inserted_seq}") + insert_final_table["Nucleotide Change"].append( + f"{coor+1+insertion_frame[coor]['shift']}:>{inserted_seq[insertion_frame[coor]['shift']:len(inserted_seq)-1*insertion_frame[coor]['r_shift']]}" + ) + # insert_final_table["Codon Change"].append(f"{}{}>{}") + insert_final_table["coor"].append(coor) + insert_final_table["ref_codon"].append( + insertion_frame[coor]["ref"]) + insert_final_table["ref_codon_count"].append( + insertion_frame[coor]["ref_count"]) + insert_final_table["Sample"].append(sample) + insert_final_table["alt_codon"].append(inserted_seq) + insert_final_table["alt_codon_count"].append( + insertion_frame[coor]["alt_count"][inserted_seq]) + insert_final_table = pd.DataFrame(insert_final_table) + insert_final_table = insert_final_table[ + insert_final_table["alt_codon_count"] >= alt_nuc_count * + (insert_final_table["alt_codon_count"] + + insert_final_table["ref_codon_count"])] + if not insert_final_table.empty: + insert_final_table["codon_count"] = insert_final_table.apply( + lambda x: + f"{x['ref_codon']}-{x['ref_codon_count']};{x['alt_codon']}-{x['alt_codon_count']}", + axis=1, + ) + insert_final_table["codon_percent"] = insert_final_table.apply( + lambda x: + f"{x['ref_codon']}-{'%0.2f' % (x['ref_codon_count']*100./(x['ref_codon_count']+x['alt_codon_count']))};{x['alt_codon']}-{'%0.2f' % (x['alt_codon_count']*100./(x['ref_codon_count']+x['alt_codon_count']))}", + axis=1, + ) + insert_final_table = insert_final_table.drop( + [ + "ref_codon", "ref_codon_count", "alt_codon", "alt_codon_count", + "coor" + ], + axis=1, + ) + + return delete_final_table, insert_final_table diff --git a/seqPanther/CodonCounter/subs.py b/seqPanther/CodonCounter/subs.py new file mode 100755 index 0000000..35c4a8f --- /dev/null +++ b/seqPanther/CodonCounter/subs.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python + +import pandas as pd +from .codon_table import codon_table +from os import path +import pysam + + +def sub_table(coordinates_with_change, bam, params): + sample = path.split(bam)[1] + alt_nuc_count = params["alt_nuc_count"] + sequences = params["sequences"] + rid = params["rid"] + ignore_orphans = params["ignore_orphans"] + ignore_overlaps = params["ignore_overlaps"] + min_base_quality = params["min_base_quality"] + + gff_data = params["gff_data"] + min_seq_depth = params["min_seq_depth"] + sample = path.split(bam)[1] + keys = set(coordinates_with_change) + samfile = pysam.AlignmentFile(bam, "rb") + + for ( + _, + row, + ) in gff_data.iterrows(): + selected_coordinates = keys & set(range(row["start"], row["end"])) + if selected_coordinates: + # TODO: Add count of codon. Ignore with ambigious nucleotide and gaps + # TODO: Check if there is any 3 base indels + for selected_coordinate in selected_coordinates: + coordinates_with_change[selected_coordinate]["start"] = row[ + "start"] + coordinates_with_change[selected_coordinate]["end"] = row[ + "end"] + coordinates_with_change[selected_coordinate]["strand"] = row[ + "strand"] + shift = (selected_coordinate - row["start"]) % 3 + iter = samfile.pileup( + rid, + selected_coordinate, + selected_coordinate + 1, + ignore_orphans=ignore_orphans, + min_mapping_quality=min_base_quality, + min_base_quality=min_base_quality, + ignore_overlaps=ignore_overlaps, + ) + # TODO: Discuss with san to use codon count or nuc count to detect proportion + total_codon_count = 0 + for pileupcol in iter: + if pileupcol.pos != selected_coordinate: + continue + for pread in pileupcol.pileups: + if not pread.is_del and not pread.is_refskip: + codon = pread.alignment.query_sequence[ + pread.query_position - + shift:pread.query_position - shift + 3] + # NOTE: Count codon can keep the same count distribution as the same as bases + if (codon in codon_table) and ( + pread.alignment.query_sequence[ + pread.query_position] + in coordinates_with_change[ + pileupcol.pos]["bases"]): + + if (codon not in coordinates_with_change[ + pileupcol.pos]["bases"] + [pread.alignment.query_sequence[ + pread.query_position]]["codon_count"]): + coordinates_with_change[ + pileupcol.pos]["bases"][ + pread.alignment.query_sequence[ + pread.query_position]][ + "codon_count"][codon] = 0 + coordinates_with_change[pileupcol.pos][ + "bases"][pread.alignment.query_sequence[ + pread.query_position]]["codon_count"][ + codon] += 1 + total_codon_count += 1 + + elif len(codon) > 3: + print(codon, selected_coordinate) + + if pileupcol.pos == selected_coordinate: + break + # NOTE: Removing less less common codons + coordinates_with_change[selected_coordinate][ + "total_codon_count"] = total_codon_count + + ref_base = sequences[selected_coordinate].seq + ref_codon = sequences[ + selected_coordinate - shift:selected_coordinate - shift + + 3].seq # TODO: Integrate the ref codon in dictionary itself + # NOTE: Reverse complement + if row["strand"] == "-": + ref_codon = str(Seq.Seq(ref_codon).reverse_complement()) + ref_base = str(Seq.Seq(ref_base).reverse_complement()) + for k in coordinates_with_change[selected_coordinate][ + "bases"]: + # NOTE: base need to be reverse complemented + + codon_count = coordinates_with_change[ + selected_coordinate]["bases"][k]["codon_count"] + new_codon_count = {} + for codon in codon_count: + new_codon_count[str( + Seq.Seq(codon).reverse_complement() + )] = codon_count[codon] + + coordinates_with_change[selected_coordinate]["bases"][ + k]["codon_count"] = new_codon_count + new_base = {} + for k in coordinates_with_change[selected_coordinate][ + "bases"]: + new_base[str(Seq.Seq(k).reverse_complement( + ))] = coordinates_with_change[selected_coordinate][ + "bases"][k] + coordinates_with_change[selected_coordinate][ + "bases"] = new_base + coordinates_with_change[selected_coordinate][ + "ref_codon"] = ref_codon + coordinates_with_change[selected_coordinate]["codon_pos"] = ( + selected_coordinate - shift) + coordinates_with_change[selected_coordinate][ + "ref_base"] = ref_base + + if row["strand"] == "+": + + amino_pos = (selected_coordinate - row["start"]) // 3 + 1 + + else: + amino_pos = (row["end"] - selected_coordinate) // 3 + 1 + + coordinates_with_change[selected_coordinate][ + "amino_pos"] = amino_pos + + ref = {"coor": [], "ref_codon": [], "ref_codon_count": []} + final_table = { + "Amino Acid Change": [], + "Nucleotide Change": [], + "Codon Change": [], + "Sample": [], + "alt_codon": [], + "alt": [], + "total": [], + "coor": [], + "ref_codon": [], + } + # print(coordinates_with_change[21359]['total_codon_count']) + for coor in coordinates_with_change: + bases = coordinates_with_change[coor]["bases"] + read_count = coordinates_with_change[coor]["read_count"] + ref_codon_bool = False + for base in bases: + codon_counts = bases[base]["codon_count"] + for codon in codon_counts: + if codon == coordinates_with_change[coor]["ref_codon"]: + ref_codon_bool = True + ref["coor"].append(coor) + ref["ref_codon"].append( + coordinates_with_change[coor]["ref_codon"]) + ref["ref_codon_count"].append(codon_counts[codon]) + continue + if (base == coordinates_with_change[coor]["ref_base"]) or ( + codon_table[coordinates_with_change[coor]["ref_codon"]] + == codon_table[codon]): + continue + final_table["Amino Acid Change"].append( + f"""{codon_table[coordinates_with_change[coor]['ref_codon'] + ]}{coordinates_with_change[coor + ]['amino_pos']}{codon_table[codon]}""") + final_table["Nucleotide Change"].append( + f'{coor}:{coordinates_with_change[coor]["ref_base"]}>{base}' + ) + final_table["Codon Change"].append( + f"""{coordinates_with_change[coor]["codon_pos" + ]}:{coordinates_with_change[coor + ]["ref_codon"]}>{codon}""") + final_table["Sample"].append(sample.split(".bam")[0]) + final_table["alt_codon"].append(codon) + final_table["alt"].append(codon_counts[codon]) + final_table["total"].append( + coordinates_with_change[coor]["total_codon_count"]) + final_table["coor"].append(coor) + final_table["ref_codon"].append( + coordinates_with_change[coor]["ref_codon"]) + # if not ref_codon_bool: + # ref["coor"].append(coor) + # print(coor) + # print(coordinates_with_change[coor]) + # ref["ref_codon"].append(coordinates_with_change[coor]["ref_codon"]) + # ref["ref_codon_count"].append(0) + final_table = pd.DataFrame(final_table) + ref = pd.DataFrame(ref) + final_table = final_table.merge(ref, on=["coor", "ref_codon"], how="inner") + final_table = final_table[ + (final_table["total"] >= min_seq_depth) + & (final_table["alt"] > alt_nuc_count * final_table["total"])] + # print(final_table) + # print(final_table.columns) + if not final_table.empty: + + final_table["codon_count"] = final_table[[ + "ref_codon", "ref_codon_count", "alt_codon", "alt" + ]].apply( + lambda x: f"""{x['ref_codon']}-{x['ref_codon_count']};{ + x['alt_codon'] + }-{x['alt']}""", + axis=1, + ) + final_table["codon_percent"] = final_table[[ + "coor", "ref_codon", "ref_codon_count", "alt_codon", "alt" + ]].apply( + lambda x: + f"""{x['ref_codon']}-{f'%.2f' % (x['ref_codon_count']*100./coordinates_with_change[x['coor']]['total_codon_count'])};{ + x['alt_codon'] + }-{f'%.2f'% (x['alt']*100./coordinates_with_change[x['coor']]['total_codon_count'])}""", + axis=1, + ) + # all_codon_count = final_table[] + final_table = final_table.drop( + [ + "ref_codon", + "ref_codon_count", + "alt_codon", + "alt", + "coor", + "total", + ], + axis=1, + ) + return final_table diff --git a/seqPanther/CodonCounter/update_missing.py b/seqPanther/CodonCounter/update_missing.py new file mode 100755 index 0000000..b11e857 --- /dev/null +++ b/seqPanther/CodonCounter/update_missing.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python + +# Will fill the missing values in the table + +import pysam + + +def missing(bamfile, ref, pos, offset, type="S"): + # TODO: add information from user + """Will resturn codon count for current position + + :bamfile: index bam file + :ref: reference name + :pos: 0-based index + :offset: offset from pos + :returns: file name, ref, position, offset, codon count + + """ + samfile = pysam.Samfile(bamfile, "rb") + for pileupcol in samfile.pileup(ref, pos, pos+1, truncate=True): + if pileupcol.pos != pos: + continue + for item in iterable: + pass + break diff --git a/seqPanther/NucIn/__init__.py b/seqPanther/NucIn/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/seqPanther/NucIn/changes.txt b/seqPanther/NucIn/changes.txt new file mode 100644 index 0000000..a256472 --- /dev/null +++ b/seqPanther/NucIn/changes.txt @@ -0,0 +1,63 @@ +SampleA C:21301:A,C:23063:C,T:25312:G,G:22188:T +SampleB G:21301:A,C:23063:C,T:25312:G +SampleC T:21301:A,C:23063:C,T:25312:G,G:22188:T,T:27672:C +SampleD T:21301:A,A:23063:C,C:21633:CCCCT +SampleE G:21301:A,C:21453:C,G:26412:T +SampleE T:21301:A,C:21453:C,A:26412:T,ATCTAA:21764:------,C:23603:A + + + +Tracy + +disputed-payment-response-inbox@barclays.com + + +fxdocumentmanagment@barclayscorp.com + +Title: Dispute Response Form + + + + + +Kind regards, + +Anmol Kiran +Post Doctoral Bioinformatician +Malawi-Liverpool-Wellcome Trust +Clinical Research Programme +PO Box 30096 +Chichiri, Blantyre 3 +Malawi +Mob: +265 993936219 + + + +Please find the attached Signed Dispute Response Form and screenshot of the Police Case Confirmation Number submitted on August 10th in Stellenbosch, South Africa. My card was swallowed in an FNB bank ATM in Stellenbosch. I am also attaching the screenshot of the phone call to FNB bank. I made the call to FNB as soon as I realized I was not getting my card back. However, I didn't receive much support from FNB other than a statement that I will not get the card back and a suggestion to cancel the card as soon as possible. + + +I tried to call Barclays on the phone. However, failed to reach any assisting member. Therefore, I went online and tried to cancel my card and I couldn't cancel. After that, I tried to transfer all the money from my current account to my savings account. Furthermore, I could transfer only £4,615.92 (of £7,159.90) but showing my current account balance £0 after transfer. Later, I called Barclays again, requesting to cancel my debit card and send a new one. I ran out of call credits as I am on roaming in South Africa. Therefore, I made a request using multiple phone calls. I guess, before could transfer all the money to my saving account, my card details were stolen and used by the criminals. Therefore, I couldn't transfer £2,543.98. I received the notification about £2,543.98 on the next day, August 10th. I informed about these transactions (£2,543.98) to Barclays and local police. + + + +Please let me know if additional information is required. +Thank you for all your kind help. + + +- Font color and font type (Fixed, color fixed) + + - Make consistant +- Reduce the font size +- Menu on side +- Add another icon + +- Activate all the links +- Add a sentence on resources +- +- Perhaps it would be more intuitive to use specific icons for external links, download etc. Eg we use fontawesome icons for the catalog: https://fontawesome.com/search?favorites=staff&s=solid%2Cbrands +- show icon for external link +- Add an example file add link to help page + + + +Please find the attached signed response form and screenshot of the Police Case Confirmation Number submitted on August 10th in Stellenbosch, South Africa. My card was inflated from an FNB bank ATM in Stellenbosch. I am also attaching the screenshot of the phone call to FNB bank. I made the call as soon as I realized I wasn't getting my card back (within 5 minutes). However, we have received no support from FNB other than a statement that I will not get the card back and a suggestion to cancel the card as soon as possible. Please let me know if additional information is required. diff --git a/seqPanther/NucIn/nuc_in.py b/seqPanther/NucIn/nuc_in.py new file mode 100644 index 0000000..35621f7 --- /dev/null +++ b/seqPanther/NucIn/nuc_in.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 + +import click +from Bio import SeqIO +import pandas as pd +from glob import glob +from os import path + + +def parse_and_sort(coor_and_changes): + """ + Parse the changes for each sequence id and sort them by position in decreasing order. + example input: SampleA C:21301:A,C:23063:C,T:25312:G,G:22188:T + """ + to_return = {} + with open(coor_and_changes) as f: + for line in f: + dt1 = line[:-1].split('\t') + changes = dt1[1].split(",") + changes_with_coor = {"coor": [], "from": [], "to": []} + for change in changes: + dt2 = change.split(":") + changes_with_coor["coor"].append(int(dt2[1])) + changes_with_coor["from"].append(dt2[0]) + changes_with_coor["to"].append(dt2[2]) + changes_with_coor = pd.DataFrame(changes_with_coor).sort_values( + by="coor", ascending=False) + + to_return[dt1[0]] = changes_with_coor + return to_return + + +@click.command() +@click.option('--fasta', + '-f', + help="Fasta file or folder", + type=click.File('r'), + required=True) +@click.option('--tab', + '-t', + help="Nucletide substitution table", + type=click.File('r'), + required=True) +@click.option('--outfile', + '-o', + help="Output fasta file", + type=click.File('w'), + default="output.fasta", + required=True) +def run(fasta, tab, outfile): + """ + Integrate changes in nucleotide sequences.\n + fasta: file for folder containing fasta files name ending with .fasta\n + tab: file containing changes in format of\n + SampleA\tC:21301:A,C:23063:C,T:25312:G,G:22188:T\n + outfile: Output fasta file. All the sequences will be in one file + + """ + + important_ids = parse_and_sort(tab) + + sequences = {} + + if path.isfile(fasta): + for rec in SeqIO.parse(fasta, 'fasta'): + if rec.id in important_ids: + seq = rec.seq + for _, row in important_ids[rec.id].iterrows(): + seq = seq[:row["coor"]] + row["to"] + seq[ + row["coor"] + 1:] # TODO: check if this is correct + sequences[rec.id] = seq + else: + + sequences[rec.id] = list(rec.seq) + else: + for fl in glob("*.fasta"): + for rec in SeqIO.parse(fl, 'fasta'): + if rec.id in important_ids: + seq = rec.seq + for _, row in important_ids[rec.id].iterrows(): + seq = seq[:row["coor"]] + row["to"] + seq[ + row["coor"] + 1:] # TODO: check if this is correct + else: + sequences[rec.id] = list(rec.seq) + for sid in sequences: + outfile.write(f">{sid}\n{sequences[sid]}\n") + # TODO: Merge the details + + +if __name__ == "__main__": + run() + # res = parse_and_sort("changes.txt") + # print(res) diff --git a/seqPanther/NucIn/organise.py b/seqPanther/NucIn/organise.py new file mode 100644 index 0000000..66d6146 --- /dev/null +++ b/seqPanther/NucIn/organise.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python + +import click +import pandas as pd +from os import path, system +from pyfaidx import Fasta +from glob import glob + + +def indel2sub(indel, ref): + """Converts indels to Substitution form.""" + indel = pd.read_csv( + indel, usecols=["coor", 'Nucleotide Frequency', 'Nucleotide Percent']) + print(indel) + indel['type'] = indel["Nucleotide Frequency"].apply(lambda x: x[:3]) + indel["Nucleotide Frequency"] = indel["Nucleotide Frequency"].apply( + lambda x: x[3:]) + indel["sub"] = "-" + indel.loc[indel["type"] == "del", "sub"] = indel.loc[ + indel["type"] == "del", ["coor", "Nucleotide Frequency"]].apply( + lambda x: x["Nucleotide Frequency"].split(':')[0] + ":" + indel[ + "coor"].apply(str) + ":" + "-" * len(x["Nucleotide Frequency"]. + split(':')[0]), + axis=1) # Add more values here + + fasta = 'seq' # pyfaidx.Fasta(ref) + indel.loc[indel["type"] == "ins", "sub"] = indel.loc[ + indel["type"] == "ins", + ["coor", "Nucleotide Frequency"]].apply(lambda x: fasta[x["coor"]] + x[ + "Nucleotide Frequency"].split(":")[0] + ":" + x["coor"].apply( + str) + ":" + x["Nucleotide Frequency"].split(":")[0], + axis=1) + return indel + + +@click.command() +@click.option("-s", + "--sub", + "sub", + help="Substitution table generated by codoncounter", + type=str, + default=None, + show_default=True) +@click.option("-i", + "--id", + "indel", + help="Indel table generated by codoncounter", + type=str, + default=None, + show_default=True) +@click.option("-r", + "--ref", + "ref", + help="Reference fasta file, containing only one sequence", + type=str, + default=None, + show_default=True) +@click.option("-o", + "--out", + "out", + help="Output file name", + type=str, + default=None, + show_default=True, + required=True) +def run(sub, indel, asm, ref, out): + "Please input csv files generated by .... command" + if not sub and not indel: + exit("No input file given. Exiting") + if not out: + exit("No output file path given. Exiting") + if not ref: + exit("Reference sequence file must be provided. Exiting.") + + sequences = Fasta(ref) + + changed_table = [] + if sub: + if path.isfile(sub): + sub = pd.read_csv(sub, + usecols=[ + "Sample", "pos", "read_count", + "Reference Nucleotide", "Nucleotide Percent" + ]) + sub["sub"] = sub["Reference Nucleotide"] + ":" + sub["pos"].apply( + str) + ":" + sub["Nucleotide Percent"] + changed_table.append(sub[["Sample", "sub"]]) + + else: + exit(f"Given {sub} is not file") + if indel: + if path.isfile(indel): + indel = pd.read_csv( + indel, + usecols=["coor", 'Nucleotide Frequency', 'Nucleotide Percent']) + indel['type'] = indel["Nucleotide Frequency"].apply( + lambda x: x[:3]) + indel["Nucleotide Frequency"] = indel[ + "Nucleotide Frequency"].apply(lambda x: x[3:]) + indel["sub"] = "-" + indel.loc[indel["type"] == "del", "sub"] = indel.loc[ + indel["type"] == "del", + ["coor", "Nucleotide Frequency"]].apply( + lambda x: x["Nucleotide Frequency"].split(':')[ + 0] + ":" + indel["coor"].apply(str) + ":" + "-" * len( + x["Nucleotide Frequency"].split(':')[0]), + axis=1) # Add more values here + + fasta = pyfaidx.Fasta(ref) + indel.loc[indel["type"] == "ins", "sub"] = indel.loc[ + indel["type"] == "ins", + ["coor", "Nucleotide Frequency"]].apply( + lambda x: fasta[x["coor"]] + x["Nucleotide Frequency"]. + split(":")[0] + ":" + x["coor"].apply(str) + ":" + x[ + "Nucleotide Frequency"].split(":")[0], + axis=1) + changed_table.append(indel) + else: + exit(f"Given {indel} is not file") + changed_table = pd.concat(changed_table) # TODO: Request for coodrinates + changed_table = changed_table.sort_values("coor", ascending=True) + changed_table = changed_table.groupby("Sample")["sub"].apply( + lambda x: ','.join(list(x))) + changed_table.to_csv("", index=False, header=False, sep="\t") + print( + "Output file genrated, please remove not required changes from the file" + ) + + +if __name__ == "__main__": + run() + # run("../CodonCounter/sub_output.csv", "../CodonCounter/indel_output.csv", + # None, "../CodonCounter/test_data/NC_045512.2.fasta", "xxx") diff --git a/seqPanther/__init__.py b/seqPanther/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/seqPanther/__pycache__/__init__.cpython-39.pyc b/seqPanther/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..303cadfa8dad9f75d0a1bcf42183c19d5d46ae29 GIT binary patch literal 152 zcmYe~<>g`k0v|!XWDxxrL?8o3AjbiSi&=m~3PUi1CZpdfjN5Vf7nZo1j8wjd-<5x13Kw{S*Kv|K8r3JDOBFP0m-yJ7tioTOEAEhi*? z0JruA62B-{PW%N&!C`i1=ikp!qE~C20OXoaGly;3_lnDZpz$sN-Vq z+NVPYpwpW4rbx60MJ=k6f`)1O%oI(;nC6*bY`WKksmjtdo!rHn9arg*ao(p3ytDgT zdo65RaTDml*4}nwoPUf>pD|vQE9)3*CX8)*%FE0`aKF3E%2jm&c!x0wIVpfKV{H@L zGvU(NDsQ?r_m^6QP0WR0o9cQkhHJ^#U14vK|5uvmxwfKG@`YDZJOUHp2_E19>EO)_ Mx}Jw4+)fhVe_p}wjQ{`u literal 0 HcmV?d00001 diff --git a/seqPanther/seqPanther.py b/seqPanther/seqPanther.py new file mode 100755 index 0000000..cb99a0e --- /dev/null +++ b/seqPanther/seqPanther.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +import click +from seqPanther.NucIn import nuc_in, organise +from seqPanther.seqPatcher import seqpatcher +from seqPanther.CodonCounter import CodonCounter + +__author__ = "Anmol Kiran" +__organisation__ = ("University College Cork, Ireland") +__github__ = "codemeleon" +__email__ = "akiran@mlw.mw" +__version__ = "0.0.1" + + +@click.group() +@click.option("-a", help="first value") +def run(a): + """Wrapper for commands below""" + pass + + +run.add_command(seqpatcher.run, "seqpatcher") +run.add_command(CodonCounter.run, "codoncounter") +run.add_command(nuc_in.run, "nucsubs") +run.add_command(organise.run, "cc2ns") + +if __name__ == "__main__": + run() diff --git a/seqPanther/seqPatcher/__init__.py b/seqPanther/seqPatcher/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/seqPanther/seqPatcher/check_orientation.py b/seqPanther/seqPatcher/check_orientation.py new file mode 100644 index 0000000..f343edf --- /dev/null +++ b/seqPanther/seqPatcher/check_orientation.py @@ -0,0 +1,56 @@ +from Bio import SeqIO +import click +from os import system +import pandas as pd + + +@click.command() +@click.option( + "-r", + "--ref", + "ref", + help="Refernce fasta file", + type=str, + default=None, + show_default=True, +) +@click.option( + "-a", + "--ab", + "ab", + help="ab1 sanger file.", + type=str, + default=None, + show_default=True, +) +def run(ref, ab): + """TODO: Docstring for run. + + :ref: TODO + :ab: TODO + :returns: TODO + + """ + record = SeqIO.read(ab, "abi") + seq = "".join(chr(x) for x in record.annotations["abif_raw"]["PBAS1"]) + with open("test.fasta", "w") as fout: + fout.write(f">query\n{seq}\n") + system(f"blat -noHead {ref} test.fasta test.psl") + data = ( + pd.read_table("test.psl", header=None).sort_values( + 0, ascending=False).head(1) + ) + for _, row in data.iterrows(): + if row[8] == "-": + strand = "reverse" + else: + strand = "forward" + break + + system("rm test.fasta test.psl") + + print(f"{ab} is on {strand}.") + + +if __name__ == "__main__": + run() diff --git a/seqPanther/seqPatcher/seqpatcher.py b/seqPanther/seqPatcher/seqpatcher.py new file mode 100644 index 0000000..b49216d --- /dev/null +++ b/seqPanther/seqPatcher/seqpatcher.py @@ -0,0 +1,1585 @@ +#!/usr/bin/env python + +# Author: Anmol Kiran +# Affiliation: University of Liverpool. UK +# and Malawi-Liverpool-Wellcome Trust, Malawi +# V0.0.1: 20/04/2021 + +from Bio import Seq, SeqIO +import pandas as pd +import numpy as np +import click +import warnings +from functools import partial + +# import re + +# from collections import ChainMap +from shutil import copyfile, rmtree + +# from functools import partial +import tempfile as tmf +from os import makedirs, path # , access +from glob import glob + +# from multiprocessing import cpu_count, Pool +from collections import defaultdict + +# import sys +import subprocess as sb + +# import os + +from pandas._libs.lib import is_list_like + +warnings.filterwarnings("ignore") +# warnings.simplefilter(action="ignore", category=FutureWarning) + + +__version__ = "0.0.1" + +_s_gene_seq = """ATGTTTGTTTTTCTTGTTTTATTGCCACTAGTCTCTAGTCAGTGTGTT +AATCTTACAACCAGAACTCAATTACCCCCTGCATACACTAATTCTTTCACACGTGGTGTTTATTACCCTGACAAA +GTTTTCAGATCCTCAGTTTTACATTCAACTCAGGACTTGTTCTTACCTTTCTTTTCCAATGTTACTTGGTTCCAT +GCTATACATGTCTCTGGGACCAATGGTACTAAGAGGTTTGATAACCCTGTCCTACCATTTAATGATGGTGTTTAT +TTTGCTTCCACTGAGAAGTCTAACATAATAAGAGGCTGGATTTTTGGTACTACTTTAGATTCGAAGACCCAGTCC +CTACTTATTGTTAATAACGCTACTAATGTTGTTATTAAAGTCTGTGAATTTCAATTTTGTAATGATCCATTTTTG +GGTGTTTATTACCACAAAAACAACAAAAGTTGGATGGAAAGTGAGTTCAGAGTTTATTCTAGTGCGAATAATTGC +ACTTTTGAATATGTCTCTCAGCCTTTTCTTATGGACCTTGAAGGAAAACAGGGTAATTTCAAAAATCTTAGGGAA +TTTGTGTTTAAGAATATTGATGGTTATTTTAAAATATATTCTAAGCACACGCCTATTAATTTAGTGCGTGATCTC +CCTCAGGGTTTTTCGGCTTTAGAACCATTGGTAGATTTGCCAATAGGTATTAACATCACTAGGTTTCAAACTTTA +CTTGCTTTACATAGAAGTTATTTGACTCCTGGTGATTCTTCTTCAGGTTGGACAGCTGGTGCTGCAGCTTATTAT +GTGGGTTATCTTCAACCTAGGACTTTTCTATTAAAATATAATGAAAATGGAACCATTACAGATGCTGTAGACTGT +GCACTTGACCCTCTCTCAGAAACAAAGTGTACGTTGAAATCCTTCACTGTAGAAAAAGGAATCTATCAAACTTCT +AACTTTAGAGTCCAACCAACAGAATCTATTGTTAGATTTCCTAATATTACAAACTTGTGCCCTTTTGGTGAAGTT +TTTAACGCCACCAGATTTGCATCTGTTTATGCTTGGAACAGGAAGAGAATCAGCAACTGTGTTGCTGATTATTCT +GTCCTATATAATTCCGCATCATTTTCCACTTTTAAGTGTTATGGAGTGTCTCCTACTAAATTAAATGATCTCTGC +TTTACTAATGTCTATGCAGATTCATTTGTAATTAGAGGTGATGAAGTCAGACAAATCGCTCCAGGGCAAACTGGA +AAGATTGCTGATTATAATTATAAATTACCAGATGATTTTACAGGCTGCGTTATAGCTTGGAATTCTAACAATCTT +GATTCTAAGGTTGGTGGTAATTATAATTACCTGTATAGATTGTTTAGGAAGTCTAATCTCAAACCTTTTGAGAGA +GATATTTCAACTGAAATCTATCAGGCCGGTAGCACACCTTGTAATGGTGTTGAAGGTTTTAATTGTTACTTTCCT +TTACAATCATATGGTTTCCAACCCACTAATGGTGTTGGTTACCAACCATACAGAGTAGTAGTACTTTCTTTTGAA +CTTCTACATGCACCAGCAACTGTTTGTGGACCTAAAAAGTCTACTAATTTGGTTAAAAACAAATGTGTCAATTTC +AACTTCAATGGTTTAACAGGCACAGGTGTTCTTACTGAGTCTAACAAAAAGTTTCTGCCTTTCCAACAATTTGGC +AGAGACATTGCTGACACTACTGATGCTGTCCGTGATCCACAGACACTTGAGATTCTTGACATTACACCATGTTCT +TTTGGTGGTGTCAGTGTTATAACACCAGGAACAAATACTTCTAACCAGGTTGCTGTTCTTTATCAGGATGTTAAC +TGCACAGAAGTCCCTGTTGCTATTCATGCAGATCAACTTACTCCTACTTGGCGTGTTTATTCTACAGGTTCTAAT +GTTTTTCAAACACGTGCAGGCTGTTTAATAGGGGCTGAACATGTCAACAACTCATATGAGTGTGACATACCCATT +GGTGCAGGTATATGCGCTAGTTATCAGACTCAGACTAATTCTCCTCGGCGGGCACGTAGTGTAGCTAGTCAATCC +ATCATTGCCTACACTATGTCACTTGGTGCAGAAAATTCAGTTGCTTACTCTAATAACTCTATTGCCATACCCACA +AATTTTACTATTAGTGTTACCACAGAAATTCTACCAGTGTCTATGACCAAGACATCAGTAGATTGTACAATGTAC +ATTTGTGGTGATTCAACTGAATGCAGCAATCTTTTGTTGCAATATGGCAGTTTTTGTACACAATTAAACCGTGCT +TTAACTGGAATAGCTGTTGAACAAGACAAAAACACCCAAGAAGTTTTTGCACAAGTCAAACAAATTTACAAAACA +CCACCAATTAAAGATTTTGGTGGTTTTAATTTTTCACAAATATTACCAGATCCATCAAAACCAAGCAAGAGGTCA +TTTATTGAAGATCTACTTTTCAACAAAGTGACACTTGCAGATGCTGGCTTCATCAAACAATATGGTGATTGCCTT +GGTGATATTGCTGCTAGAGACCTCATTTGTGCACAAAAGTTTAACGGCCTTACTGTTTTGCCACCTTTGCTCACA +GATGAAATGATTGCTCAATACACTTCTGCACTGTTAGCGGGTACAATCACTTCTGGTTGGACCTTTGGTGCAGGT +GCTGCATTACAAATACCATTTGCTATGCAAATGGCTTATAGGTTTAATGGTATTGGAGTTACACAGAATGTTCTC +TATGAGAACCAAAAATTGATTGCCAACCAATTTAATAGTGCTATTGGCAAAATTCAAGACTCACTTTCTTCCACA +GCAAGTGCACTTGGAAAACTTCAAGATGTGGTCAACCAAAATGCACAAGCTTTAAACACGCTTGTTAAACAACTT +AGCTCCAATTTTGGTGCAATTTCAAGTGTTTTAAATGATATCCTTTCACGTCTTGACAAAGTTGAGGCTGAAGTG +CAAATTGATAGGTTGATCACAGGCAGACTTCAAAGTTTGCAGACATATGTGACTCAACAATTAATTAGAGCTGCA +GAAATCAGAGCTTCTGCTAATCTTGCTGCTACTAAAATGTCAGAGTGTGTACTTGGACAATCAAAAAGAGTTGAT +TTTTGTGGAAAGGGCTATCATCTTATGTCCTTCCCTCAGTCAGCACCTCATGGTGTAGTCTTCTTGCATGTGACT +TATGTCCCTGCACAAGAAAAGAACTTCACAACTGCTCCTGCCATTTGTCATGATGGAAAAGCACACTTTCCTCGT +GAAGGTGTCTTTGTTTCAAATGGCACACACTGGTTTGTAACACAAAGGAATTTTTATGAACCACAAATCATTACT +ACAGACAACACATTTGTGTCTGGTAACTGTGATGTTGTAATAGGAATTGTCAACAACACAGTTTATGATCCTTTG +CAACCTGAATTAGACTCATTCAAGGAGGAGTTAGATAAATATTTTAAGAATCATACATCACCAGATGTTGATTTA +GGTGACATCTCTGGCATTAATGCTTCAGTTGTAAACATTCAAAAAGAAATTGACCGCCTCAATGAGGTTGCCAAG +AATTTAAATGAATCTCTCATCGATCTCCAAGAACTTGGAAAGTATGAGCAGTATATAAAATGGCCATGGTACATT +TGGCTAGGTTTTATAGCTGGCTTGATTGCCATAGTAATGGTGACAATTATGCTTTGCTGTATGACCAGTTGCTGT +AGTTGTCTCAAGGGCTGTTGTTCTTGTGGATCCTGCTGCAAATTTGATGAAGACGACTCTGAGCCAGTGCTCAAA +GGAGTCAAATTACATTACACATAA""" + +_amb_base = { # All ambiguous nucleotides + "N": set(["A", "C", "G", "T"]), + "R": set(["A", "G"]), + "Y": set(["T", "C"]), + "K": set(["G", "T"]), + "M": set(["A", "C"]), + "S": set(["G", "C"]), + "W": set(["A", "T"]), + "B": set(["C", "G", "T"]), + "D": set(["A", "G", "T"]), + "H": set(["A", "C", "T"]), + "V": set(["A", "C", "G"]), +} + +_amb_base_ext = { # Opposite of above + tuple(set(["A", "C", "G", "T"])): "N", + tuple(set(["A", "G"])): "R", + tuple(set(["T", "C"])): "Y", + tuple(set(["G", "T"])): "K", + tuple(set(["A", "C"])): "M", + tuple(set(["G", "C"])): "S", + tuple(set(["A", "T"])): "W", + tuple(set(["C", "G", "T"])): "B", + tuple(set(["A", "G", "T"])): "D", + tuple(set(["A", "C", "T"])): "H", + tuple(set(["A", "C", "G"])): "V", +} + + +def cmd(command): + """Runs all the command using Popen communicate. + :command: in form of list ie ['ls', '-l'] + :return: None + """ + sb.Popen(command, stdout=sb.DEVNULL, stderr=sb.DEVNULL).communicate() + + +def min_max(values): + """Returns minimum and maximum values in the given list/array. + + :values: list/array + :returns: touple of min and max + + """ + return min(values), max(values) + + +# 2 20 + + +def trim(mmcount, length, aln_df): + """Trim the sequence at the end based on mismatched in given length of + + :mmcount: Mismatch count in given range + :length: Length at both end to explore + :returns: trimmed alignment dataframe + + """ + # aln_len = length(aln) + for col in aln_df.columns: + if col == "ref": + continue + min_, max_ = min_max(aln_df[aln_df[col] != "-"].index) + mismach_locations = aln_df[aln_df[col].isin("-NRYKMSWBDHV")].index + mismach_locations = mismach_locations[ + (mismach_locations >= min_) & (mismach_locations <= max_) + ] + start_mismatch_location = mismach_locations[mismach_locations < length] + if len(start_mismatch_location) >= mmcount: + min_ = start_mismatch_location[-1] + 1 + end_mismatch_locations = mismach_locations[ + mismach_locations > (length(aln_df) - length) + ] + if len(end_mismatch_locations) >= mmcount: + max_ = end_mismatch_locations[0] - 1 + aln_df.loc[:min_, col] = "-" + aln_df.loc[max_:, col] = "-" + + return aln_df + + +def codon_aln(aln_df): + """Correct alignment around codon + + :aln_df: normal alignment dataframe + :returns: colodon alinment dataframe + + """ + df_shape = aln_df.shape[1] + non_ref_seq = [seq_id for seq_id in df_shape.columns if seq_id != "ref"] + if df_shape == 2: + aln_min, aln_max = min_max(aln_df[aln_df[non_ref_seq[0]] != "-"].index) + # TODO: Check whether is a 0 position if not change the locatio in no indel at next two positions + # + + pass + elif df_shape == 3: + # TODO: Accept nucleotide at overhang and then try to change the codon alignmentt + + pass + else: + pass + + return + + +# TODO: How many codon should be allow to be remove without replacing with N +# TODO: Remove text from last mismatch - I don't think it will make any difference - But allow to extend the ends for better mapping + + +def ranges(lst, given_gap=0): + """ + A generator returns list of range based on given numbers + [1,2,3,4,5, 10, 11, 12, 13, 14] => [[1,5], [10,14]] + """ + # print(given_gap, "Anmol") + lst_sorted = sorted(lst) + init = 0 + for num in range(1, len(lst_sorted)): + # reported_gap = lst_sorted[num] - lst_sorted[num - 1] - 1 + if lst_sorted[num] > given_gap + 1 + lst_sorted[num - 1]: + # or (reported_gap % 3 != 0): + # gap=0 means overlapping + yield (lst_sorted[init], lst_sorted[num - 1]) + init = num + yield (lst_sorted[init], lst_sorted[-1]) + + +def useful_range(lst, gap=10): # TODO: Add in command + """Returns first occurance maximum length block range.""" + # TODO: Check with other that if they are happy with it + # or they want other fragment to be selected + + trange = list(ranges(lst, gap)) + # print(trange, "kiran") + pre_frag_len = 0 + myrange = trange[0] + for rng in trange: + frag_len = rng[1] - rng[0] + 1 + if pre_frag_len < frag_len: + pre_frag_len = frag_len + myrange = rng + return myrange + + +def df_reverse_complement(dataframe): + """Reverse Complement of the nucleotide dataframe.""" + dataframe = dataframe.loc[::-1] + + def rvc(nuc): + """Return complement base.""" + return str(Seq.Seq(nuc).complement()) + + def rvc_dict(nuc_dict): + """Returns complement dictionary.""" + temp_nuc_dict = {} + for nuc in nuc_dict: + temp_nuc_dict[rvc(nuc)] = nuc_dict[nuc] + return temp_nuc_dict + + dataframe["nuc"] = dataframe["nuc"].apply(rvc) + dataframe["peak"] = dataframe["peak"].apply(rvc_dict) + return dataframe + + +def orient(seqfile, ref, tmp_fold): + """Returns orientation of the sequence""" + if seqfile.endswith(".ab1"): + flb = path.split(seqfile)[1].rsplit(".", 1)[0] + record = SeqIO.read(seqfile, "abi") + seq = "".join( + [chr(ascii_val) + for ascii_val in record.annotations["abif_raw"]["PBAS1"]] + ) + with open(f"{tmp_fold}/{flb}.fasta", "w") as fout: + fout.write(f">tmp\n{seq}\n") + seqfile = f"{tmp_fold}/{flb}.fasta" + + flb = path.split(seqfile)[1].rsplit(".", 1)[0] + command = [ + "blat", + "-noHead", + ref, + seqfile, + f"{tmp_fold}/{flb}.psl", + ] # Mapping against reference + cmd(command) + blat_df = ( + pd.read_table(f"{tmp_fold}/{flb}.psl", header=None) + .sort_values(0, ascending=False) + .drop_duplicates(9) + ) + if len(blat_df) != 1: + print(f"No match found of {seqfile}. Ignoring") + return None + for _, row in blat_df.iterrows(): + if row[8] == "-": + return "R" + else: + return "F" + + +def ab1_to_fasta_wihout_ref(ab1_list, tmp_fold, res_fold): + """Convert ab1 to fasta without reference. Not functional at moment""" + # TODO: If sequence is single just move to results after trimming bad ends + + if len(ab1_list) == 1: + seqfile = ab1_list[0] + if seqfile.endswith(".ab1"): + flb = path.split(seqfile)[1].split(".", 1)[0] + record = SeqIO.read(seqfile, "abi") + seq = "".join( + [ + chr(ascii_val) + for ascii_val in record.annotations["abif_raw"]["PBAS1"] + ] + ) + with open(f"{res_fold}/{flb}.fasta", "w") as fout: + fout.write(f">{flb}\n{seq}\n") + else: + copyfile(seqfile, res_fold) + else: + flb = path.split(ab1_list[0])[1].split(".", 1)[0] + # TODO: Check whether both seqyences are same strand + with open(f"{tmp_fold}/{flb}.fasta", "w") as fout: + for num, seqfile in enumerate(ab1_list): + if seqfile.endswith(".ab1"): + record = SeqIO.read(seqfile, "abi") + seq = "".join( + [ + chr(ascii_val) + for ascii_val in record.annotations["abif_raw"]["PBAS1"] + ] + ) + if num: + seq = Seq.Seq(seq).reverse_complement() + fout.write(f">{flb}_{num}\n{seq}\n") + command = [ + "blat", + "-noHead", + f"{tmp_fold}/{flb}.fasta", + f"{tmp_fold}/{flb}.fasta", + f"{tmp_fold}/{flb}.psl", + ] # Mapping against reference + cmd(command) + blat_df = pd.read_table(f"{tmp_fold}/{flb}.psl", header=None).sort_values( + 0, ascending=False + ) + blat_df = blat_df[blat_df[9] != blat_df[13]].head(2) + strands = list(set(blat_df[8].values)) + if len(strands) > 1: + print(f"{flb} has multiple strands. Ignoring") + return None + strands = strands[0] + if strands == "-": + sequences = {} + for i, rec in enumerate(SeqIO.parse(f"{tmp_fold}/{flb}.fasta", "fasta")): + if i: + seq = Seq.Seq(rec.seq).reverse_complement() + else: + seq = rec.seq + sequences[rec.id] = seq + with open(f"{tmp_fold}/{flb}.fasta", "w") as fout: + for k in sequences: + fout.write(f">{k}\n{sequences[k]}\n") + + command = [ + "muscle", + "-in", + f"{tmp_fold}/{flb}.fasta", + "-out", + f"{tmp_fold}/{flb}_aln.fasta", + ] + cmd(command) + seq_df = {} + for rec in SeqIO.parse(f"{tmp_fold}/{flb}_aln.fasta", "fasta"): + seq_df[rec.id] = list(rec.seq) + seq_df = pd.DataFrame(seq_df) + # TODO: add options to extend or not to extend ovelappes + # TODO: How to select the bases + + # TODO: Look for gaps at the end and trim them + with open(f"{res_fold}/{flb}.fasta", "w") as fout: + fout.write(f">{flb}\n{str(seq_df.iloc[0])}\n") # Change this part + + +def ab1seq(infile): + """ab1 to seq trimmed based on reference.""" + + bases = {"DATA9": "G", "DATA10": "A", "DATA11": "T", "DATA12": "C"} + + record = SeqIO.read(infile, "abi") + trace = defaultdict(list) + + for channel in bases: + trace[bases[channel]] = record.annotations["abif_raw"][channel] + + nuc_df = {"nuc": [], "peak": []} + + for channel in zip( + record.annotations["abif_raw"]["PBAS1"], + record.annotations["abif_raw"]["PLOC1"], + ): + ambi_base = chr(channel[0]) + nuc_df["nuc"].append(ambi_base) + if ambi_base in _amb_base: + # if not peak_selection: + td = {} # TODO: Please check what does td reprensts + for base in _amb_base[ambi_base]: + td[base] = trace[base][channel[1]] + nuc_df["peak"].append(td) + + else: + nuc_df["peak"].append({ambi_base: trace[ambi_base][channel[1]]}) + # NOTE: In case of ambigious nucleotides + nuc_df = pd.DataFrame(nuc_df) + peak = nuc_df["peak"].apply(lambda x: np.mean(list(x.values()))).values + mid_point = int(len(peak) / 2) + spread = int(mid_point / 2.0) + peak_mean = np.mean(peak[mid_point - spread: mid_point + spread]) + if peak_mean < 50: + warnings.warn( + f"Peak mean is {peak_mean} which is below 50 for {infile}. " + "This may be due to low quality sequence. " + "Please check the quality of the sequence." + ) + + correct_peak_pos = np.where(peak > 0.2 * peak_mean)[0] + # TODO: Autothreshold, check with the sliding window + # Added 10 extra as towards the end of the sequence quality goes down + min_pos, max_pos = correct_peak_pos[0], correct_peak_pos[-1] + nuc_df = nuc_df.loc[min_pos:max_pos] + + if infile.endswith(".R.ab1"): + nuc_df = df_reverse_complement(nuc_df) + return nuc_df + + +def aln_df_with_ref(seq_dict, flb, tmp_fold): + """Alignment dataframe""" + inf = f"{tmp_fold}/{flb}.in.fasta" + otf = f"{tmp_fold}/{flb}.out.fasta" + with open(inf, "w") as fout: + for k in seq_dict: + fout.write(f">{k}\n{seq_dict[k]}\n") + command = ["muscle", "-in", inf, "-out", otf] + cmd(command) + sequences = {} + for rec in SeqIO.parse(otf, "fasta"): + sequences[rec.id] = list(str(rec.seq).upper()) + return pd.DataFrame(sequences) + + +def drop_from_here(arg1): + """TODO: Docstring for drop_from_here. + + :arg1: TODO + :returns: TODO + + """ + pass + + +def merge_base_peak(nuc_df, peak_dict): + """Merge the peak related information in nucleotide dataframe.""" + # NOTE: Useful only when there is ambigiuity in the base call, rest remove to save memory + + nuc_df["idx"] = list(nuc_df.index) + + # df = enumerate_columns(df) + # print(df) + to_drop = ["idx"] + for nuc in peak_dict: + # Expecting sequence will not change while aligning, except insertion of gaps + peak_dict[nuc][f"{nuc}_idx"] = list( + nuc_df[nuc_df[f"{nuc}"] != "-"].index + ) # list(range(len(peak_dict[k])) + nuc_df = nuc_df.merge( + peak_dict[nuc], left_on="idx", right_on=f"{nuc}_idx", how="outer" + ) + to_drop += [f"{nuc}_idx", f"{nuc}_nuc"] + + nuc_df = nuc_df.drop(to_drop, axis=1) + return nuc_df + + +def rep_paired_base(lst, ambiguous=False): + """Selecting representative base in presence of forward and + reverse sanger sequencing data.""" + # NOTE: Select nucleotide based on peak value. Might be incorrect + if lst["F"] == lst["R"]: + return lst["F"] + if lst["F"] == "-": + if lst["R"] == "-": + return "-" + else: + if ambiguous: + return lst["R"] + # amb_base = tuple(set(lst["R_peak"])) + # return _amb_base_ext[amb_base] + else: + bmax = 0 + base = "A" + peaks = lst["R_peak"] + for bs in peaks: + if peaks[bs] > bmax: + bmax = peaks[bs] + base = bs + return base + else: + if lst["R"] == "-": + if ambiguous: + return lst["F"] + # amb_base = tuple(set(lst["F_peak"])) + # return _amb_base_ext[amb_base] + else: + # TODO: Correct issues because of gap + bmax = 0 + base = "A" + peaks = lst["F_peak"] + for bs in peaks: + if peaks[bs] > bmax: + bmax = peaks[bs] + base = bs + return base + else: + # if ambiguous: + # print(lst["F_peak"], lst["R_peak"], "Kkiran", lst) + amb_base = tuple(list(set(lst["F_peak"]) & set(lst["R_peak"]))) + if not amb_base: + amb_base = tuple(list(set(lst["F_peak"]) | set(lst["R_peak"]))) + if len(amb_base) == 1: + return amb_base[0] + else: + if ambiguous: + return _amb_base_ext[amb_base] + else: + tbase = "A" + tval = 0 + for bs in amb_base: + if bs in lst["F_peak"]: + if lst["F_peak"][bs] > tval: + tval = lst["F_peak"][bs] + tbase = bs + if bs in lst["R_peak"]: + if lst["R_peak"][bs] > tval: + tval = lst["R_peak"][bs] + tbase = bs + + return tbase + + +def aln_clean(aln_df, gap=15, ambiguous=False): # , at, res_fold): + """Clearning alihnment dataframe to remove unneccessary gaps and + alignements.""" + sang_type = None + rev = {"R": "F", "F": "R"} + if "F" in aln_df and "R" in aln_df: + idx = aln_df[~((aln_df["F"] == "-") & (aln_df["R"] == "-"))].index + idx_f = aln_df[aln_df["F"] != "-"].index + idx_r = aln_df[aln_df["R"] != "-"].index + u_range_f = list(useful_range(list(idx_f), gap)) + aln_df.loc[: u_range_f[0] - 1, "F"] = "-" + aln_df.loc[u_range_f[-1] + 1:, "F"] = "-" + u_range_r = list(useful_range(list(idx_r), gap)) + aln_df.loc[: u_range_r[0] - 1, "R"] = "-" + aln_df.loc[u_range_r[-1] + 1:, "R"] = "-" + locations_to_check = [ + u_range_f[0], + u_range_f[0] + 1, + u_range_r[0], + u_range_r[0] + 1, + ] + for ltc in locations_to_check: + for dir in ["F", "R"]: + if aln_df.loc[ltc, dir] == "-" and aln_df.loc[ltc, rev[dir]] != "-": + if aln_df.loc[ltc, rev[dir]] != aln_df.loc[ltc, "ref"]: + if (aln_df.loc[ltc, rev[dir]] in _amb_base) and ( + aln_df.loc[ltc, "ref"] + in _amb_base[aln_df.loc[ltc, rev[dir]]] + ): + pass + else: + aln_df.loc[:ltc, rev[dir]] = "-" + locations_to_check = [ + u_range_f[-1], + u_range_f[-1] - 1, + u_range_r[-1], + u_range_r[-1] - 1, + ] + for ltc in locations_to_check: + for dir in ["F", "R"]: + if aln_df.loc[ltc, dir] == "-" and aln_df.loc[ltc, rev[dir]] != "-": + if aln_df.loc[ltc, rev[dir]] != aln_df.loc[ltc, "ref"]: + if (aln_df.loc[ltc, rev[dir]] in _amb_base) and ( + aln_df.loc[ltc, "ref"] + in _amb_base[aln_df.loc[ltc, rev[dir]]] + ): + pass + else: + aln_df.loc[ltc:, rev[dir]] = "-" + + # print(aln_df.loc[u_range_r[-1] + 1 : u_range_r[-1] + 30, "R"]) + # print(u_range_f, u_range_r, "dead zone") + u_range = [ + np.min([u_range_f[0], u_range_r[0]]), + np.max([u_range_f[-1], u_range_r[-1]]), + ] + aln_df.loc[: u_range[0] - 1, ["F", "R"]] = "-" + aln_df.loc[u_range[1] + 1:, ["F", "R"]] = "-" + sang_type = "P" # For paired + # print(aln_df.head()) + # TODO: Must check in case of mismatch and ambigious it remove it carefully + # print(idx) + else: + if "F" in aln_df: + idx = aln_df[aln_df["F"] != "-"].index + u_range = list(useful_range(list(idx), gap)) + sang_type = "F" + aln_df.loc[: u_range[0] - 1, "F"] = "-" + aln_df.loc[u_range[1] + 1:, "F"] = "-" + else: + idx = aln_df[aln_df["R"] != "-"].index + u_range = list(useful_range(list(idx), gap)) + sang_type = "R" + aln_df.loc[: u_range[0] - 1, "R"] = "-" + aln_df.loc[u_range[1] + 1:, "R"] = "-" + + # TODO: This part need to be corrected + for col in aln_df.columns: + + if col not in ["F", "R"]: + continue + ambi_indexes = aln_df[aln_df[col].isin(list("NRYKMSWBDHV"))].index + ambi_indexes = ambi_indexes[ + (ambi_indexes >= u_range[0]) & (ambi_indexes <= u_range[-1]) + ] + # print(u_range, ambi_indexes, "anmol", u_range) + + if len(ambi_indexes): + print(ambi_indexes) + ambi_index_left = ambi_indexes[ambi_indexes < u_range[0] + 20] + ambi_index_right = ambi_indexes[ambi_indexes > u_range[-1] - 20] + if ambi_index_left.any(): + u_range[0] = ambi_index_left.max() + if ambi_index_right.any(): + u_range[-1] = ambi_index_right.min() + # print(u_range, "testing") + # exit() + aln_df.loc[: u_range[0] - 1, col] = "-" + aln_df.loc[u_range[1] + 1:, col] = "-" + # print(aln_df.loc[u_range_r[-1]: u_range_r[-1] + 30, "R"]) + # TODO: Avoid gap + + # # TODO: Perform average base call for gaps + + if sang_type in "FR": + # TODO: Select if both shows the same base + aln_df["consensus"] = aln_df[sang_type].values + aln_df.loc[: u_range[0] - 1, "consensus"] = aln_df.loc[ + : u_range[0] - 1, "ref" + ].values + aln_df.loc[u_range[1] + 1:, "consensus"] = aln_df.loc[ + u_range[1] + 1:, "ref" + ].values + # TODO: Create a file for ambigious nucleotides + if not ambiguous: + ambi_indexes = aln_df[aln_df[sang_type].isin( + list("NRYKMSWBDHV"))].index + # Delete 3 in range of 20 + + for ambi_index in ambi_indexes: + bmax = 0 + base = "A" + peaks = aln_df.loc[ambi_index, f"{sang_type}_peak"] + for bs in peaks: + if peaks[bs] > bmax: + bmax = peaks[bs] + base = bs + aln_df.loc[ambi_index, "consensus"] = base + + insert_ranges = aln_df.loc[u_range[0]: u_range[1]] + insert_ranges = insert_ranges[insert_ranges["ref"] == "-"].index + if insert_ranges.any(): + insert_ranges = ranges(insert_ranges) + for insert_range in insert_ranges: + if (insert_range[1] - insert_range[0] + 1) % 3 == 0: + continue + else: + if (insert_range[1] - insert_range[0] + 1) < 3: + aln_df.loc[insert_range[0] + : insert_range[1], "consensus"] = "-" + else: + # TODO: Talk to san one more time + aln_df.loc[insert_range[0] + : insert_range[1], "consensus"] = "N" + del_ranges = aln_df.loc[u_range[0]: u_range[1]] + del_ranges = del_ranges[del_ranges[sang_type] == "-"].index + if del_ranges.any(): + del_ranges = ranges(del_ranges) + for del_range in del_ranges: + if (del_range[1] - del_range[0] + 1) % 3 == 0: + continue + else: + if (del_range[1] - del_range[0] + 1) < 3: + aln_df.loc[ + del_range[0]: del_range[1], "consensus" + ] = aln_df.loc[del_range[0]: del_range[1], "ref"].values + else: + aln_df.loc[del_range[0] + : del_range[1], "consensus"] = "N" + + else: + mistmatched_indexes = aln_df[aln_df["F"] != aln_df["R"]].index + # TODO: Reduce the size of the index + f_range = aln_df[aln_df["F"] != "-"].index + f_range = f_range.min(), f_range.max() + r_range = aln_df[aln_df["R"] != "-"].index + r_range = r_range.min(), r_range.max() + f_end = np.max([f_range[0], r_range[0]]) + r_end = np.min([f_range[1], r_range[1]]) + mistmatched_indexes = mistmatched_indexes[ + (mistmatched_indexes >= f_end) & (mistmatched_indexes <= r_end) + ] + for mismatched_index in mistmatched_indexes: + # print( + # "test", + # mistmatched_indexes, + # aln_df.loc[mismatched_index, "F"], + # aln_df.loc[mismatched_index, "R"], + # ) + + if ( + aln_df.loc[mismatched_index, "F"] == "-" + or aln_df.loc[mismatched_index, "R"] == "-" + ): + continue + if ( + aln_df.loc[mismatched_index - 1, "F"] == "-" + and aln_df.loc[mismatched_index - 1, "R"] + == aln_df.loc[mismatched_index, "F"] + ): + aln_df.loc[mismatched_index, "F"] = "-" + aln_df.loc[mismatched_index - 1, "F"] = aln_df.loc[ + mismatched_index - 1, "R" + ] + aln_df.loc[mismatched_index - 1, "F_peak"] = [ + aln_df.loc[mismatched_index, "F_peak"] + ] + + aln_df.loc[mismatched_index, "F_peak"] = np.nan + + elif ( + aln_df.loc[mismatched_index + 1, "F"] == "-" + and aln_df.loc[mismatched_index + 1, "R"] + == aln_df.loc[mismatched_index, "F"] + ): + aln_df.loc[mismatched_index, "F"] = "-" + aln_df.loc[mismatched_index + 1, "F"] = aln_df.loc[ + mismatched_index + 1, "R" + ] + + aln_df.loc[mismatched_index + 1, "F_peak"] = [ + aln_df.loc[mismatched_index, "F_peak"] + ] + aln_df.loc[mismatched_index, "F_peak"] = np.nan + + if ( + aln_df.loc[mismatched_index - 1, "R"] == "-" + and aln_df.loc[mismatched_index - 1, "F"] + == aln_df.loc[mismatched_index, "R"] + ): + aln_df.loc[mismatched_index, "R"] = "-" + aln_df.loc[mismatched_index - 1, "R"] = aln_df.loc[ + mismatched_index - 1, "F" + ] + aln_df.loc[mismatched_index - 1, "R_peak"] = [ + aln_df.loc[mismatched_index, "R_peak"] + ] + aln_df.loc[mismatched_index, "R_peak"] = np.nan + elif ( + aln_df.loc[mismatched_index + 1, "R"] == "-" + and aln_df.loc[mismatched_index + 1, "F"] + == aln_df.loc[mismatched_index, "R"] + ): + # print( + # mismatched_index, + # aln_df.loc[mismatched_index + 1, "R"], + # aln_df.loc[mismatched_index + 1, "F"], + # aln_df.loc[mismatched_index, "R"], + # "TEsting", + # ) + aln_df.loc[mismatched_index, "R"] = "-" + aln_df.loc[mismatched_index + 1, "R"] = aln_df.loc[ + mismatched_index + 1, "F" + ] + aln_df.loc[mismatched_index + 1, "R_peak"] = [ + aln_df.loc[mismatched_index, "R_peak"] + ] + aln_df.loc[mismatched_index, "R_peak"] = np.nan + # aln_df.to_csv("test.csv") + + mistmatched_indexes = aln_df[aln_df["F"] != aln_df["R"]].index + mistmatched_indexes = mistmatched_indexes[ + (mistmatched_indexes >= f_end) & (mistmatched_indexes <= r_end) + ] + + # Corrections around single nucleotide indels + # print(f_range, "abd", r_range, f_end, r_end, "KK") + for mismatched_index in mistmatched_indexes: + for rv in rev: + + if ( + (aln_df.loc[mismatched_index, f"{rv}"] == "-") + & (aln_df.loc[mismatched_index - 1, f"{rv}"] != "-") + & (aln_df.loc[mismatched_index + 1, f"{rv}"] != "-") + ): + if aln_df.loc[mismatched_index, f"{rev[rv]}"] not in _amb_base: + aln_df.loc[mismatched_index, f"{rv}"] = aln_df.loc[ + mismatched_index, f"{rev[rv]}" + ] + else: + if ( + aln_df.loc[mismatched_index + 1, f"{rev[rv]}"] + == aln_df.loc[mismatched_index - 1, f"{rev[rv]}"] + ) and ( + aln_df.loc[mismatched_index + 1, f"{rev[rv]}"] + in _amb_base[aln_df.loc[mismatched_index, f"{rev[rv]}"]] + ): + aln_df.loc[mismatched_index, f"{rv}"] = aln_df.loc[ + mismatched_index + 1, f"{rev[rv]}" + ] + aln_df.loc[mismatched_index, f"{rev[rv]}"] = aln_df.loc[ + mismatched_index + 1, f"{rev[rv]}" + ] + else: + aln_df.loc[mismatched_index, f"{rv}"] = aln_df.loc[ + mismatched_index, f"{rev[rv]}" + ] + # TODO: insert a variable inticating that only on was present + + # TODO: Mismach near ends + + # aln_df.to_csv("test2.csv") + + # exit(1) + rep_paired_base_fn = partial(rep_paired_base, ambiguous=ambiguous) + aln_df["consensus"] = aln_df.apply(rep_paired_base_fn, axis=1) + + insert_ranges = aln_df.loc[u_range[0]: u_range[1]] + insert_ranges = insert_ranges[ + (insert_ranges["ref"] == "-") + & ((insert_ranges["F"] != "-") & (insert_ranges["R"] != "-")) + ].index + if insert_ranges.any(): + insert_ranges = ranges(insert_ranges) + for insert_range in insert_ranges: + if (insert_range[1] - insert_range[0] + 1) % 3 == 0: + continue + else: + if (insert_range[1] - insert_range[0] + 1) < 3: + aln_df.loc[insert_range[0] + : insert_range[1], "consensus"] = "-" + else: + # TODO: Talk to san one more time + aln_df.loc[insert_range[0] + : insert_range[1], "consensus"] = "N" + + del_ranges = aln_df.loc[u_range[0]: u_range[1]] + del_ranges = del_ranges[ + (del_ranges["ref"] != "-") + & ((del_ranges["F"] == "-") & (del_ranges["R"] == "-")) + ].index + if del_ranges.any(): + del_ranges = ranges(del_ranges) + for del_range in del_ranges: + if (del_range[1] - del_range[0] + 1) % 3 == 0: + continue + else: + if (del_range[1] - del_range[0] + 1) < 3: + aln_df.loc[ + del_range[0]: del_range[1], "consensus" + ] = aln_df.loc[del_range[0]: del_range[1], "ref"].values + else: + aln_df.loc[del_range[0] + : del_range[1], "consensus"] = "N" + consesus_range = aln_df[aln_df["consensus"] != "-"].index + consensus_range = np.min(consesus_range), np.max(consesus_range) + + aln_df.loc[: consensus_range[0] - 1, "consensus"] = aln_df.loc[ + : consensus_range[0] - 1, "ref" + ] + aln_df.loc[consensus_range[1] + 1:, "consensus"] = aln_df.loc[ + consensus_range[1] + 1:, "ref" + ] + gaps_index = aln_df[aln_df["consensus"] == "-"].index + gaps_index = gaps_index[(gaps_index >= u_range[0]) + & (gaps_index <= u_range[1])] + u_range[-1] -= len(gaps_index) + aln_df = aln_df[aln_df["consensus"] != "-"] + + return aln_df, u_range + + +def fasta_map2ref(infile, gap, tmp_fold, n3, idb): + # TODO: Use some part for arranging the sequence + """Integrates Sanger fasta to refgene + + :args: infile, outfile, tmp_fold, idb, gap + + + """ + sequences = {} + for rec in SeqIO.parse(infile, "fasta"): + if infile.endswith(".R.fasta"): # Generates revese complement + sequences[rec.id] = rec.seq.reverse_complement() + else: + sequences[rec.id] = rec.seq + cds = True # TODO: get this information from reference sequence file + for rec in SeqIO.parse(f"{tmp_fold}/ref.fasta", "fasta"): + sequences["ref"] = rec.seq + # if rec.description.split()[1] == "CDS": + # cds = True + + flb = path.split(infile)[1].split(".")[0] + + aln_df = aln_df_with_ref(sequences, flb, tmp_fold) + # print(aln_df) + mapped_index = aln_df[aln_df[flb] != "-"].index + u_range = useful_range(mapped_index, gap) + aln_df["concensus"] = "-" + aln_df.loc[: u_range[0], "concensus"] = aln_df.loc[: u_range[0], "ref"] + aln_df.loc[u_range[0]: u_range[1], "concensus"] = aln_df.loc[ + u_range[0]: u_range[1], flb + ] + aln_df.loc[u_range[1]:, "concensus"] = aln_df.loc[u_range[1]:, "ref"] + # TODO: Use cds value here + if idb in ["del", "both"]: + del_sites = aln_df[aln_df[flb] == "-"].index.values + if len(del_sites): + del_ranges = ranges(del_sites) + del_ranges = [ # Selecting internal deletions + rng for rng in del_ranges if (rng[0] > u_range[0] & rng[1] < u_range[1]) + ] + # Del codon is accepted when codon deletion is allowed else deletions are filled with gaps + for rng in del_ranges: + if n3: + if (rng[1] - rng[0] + 1) % 3 != 0: + aln_df.loc[rng[0]: rng[1], "concensus"] = "N" + # aln_df.loc[ + # rng[0]: rng[1], "ref" + # ] + # else: # TODO: Talk to SAN, does he want insert ref, of Ns or leave as gaps + # aln_df.loc[rng[0]: rng[1], "concensus"] = aln_df.loc[ + # rng[0]: rng[1], "ref" + # ] + + if idb in ["ins", "both"]: + ins_sites = aln_df[aln_df["ref"] == "-"].index.values + if len(ins_sites): + ins_ranges = ranges(ins_sites) + ins_ranges = [ # Internal inserts + rng for rng in ins_ranges if (rng[0] > u_range[0] & rng[1] < u_range[1]) + ] + for rng in ins_ranges: + if n3: + if (rng[1] - rng[0] + 1) % 3 != 0: + aln_df.loc[ + rng[0]: rng[1], "concensus" + ] = aln_df.loc[ # TODO: ask san whether he wants to insert Ns or leave reported nucletides + rng[0]: rng[1], "ref" + ] + # else: + # aln_df.loc[rng[0]: rng[1], "concensus"] = aln_df.loc[ + # rng[0]: rng[1], "ref" + # ] + + seq = "".join(aln_df["concensus"]) # .replace("-", "N") + outfile = f"{tmp_fold}/sanger_converted_fasta/{flb}.fasta" + + with open(outfile, "w") as fout: + fout.write(f">{flb} {u_range[0]} {u_range[1]}\n{seq}\n") + + +def ab1_2seq_map2ref(infiles, gap, tmp_fold): # , amb, at, res_fold): + """TODO: Docstring for ab1_2seq. + + :infiles: TODO + :returns: TODO + + """ + ab1seq_dfs = {} + tsequences = {} + flb = path.split(infiles[0])[1].split(".")[0] + for fl in infiles: + if fl.endswith(".F.ab1"): + ab1seq_dfs["F"] = ab1seq(fl) # TODO: add the condition + tsequences["F"] = "".join(ab1seq_dfs["F"]["nuc"].values) + else: + ab1seq_dfs["R"] = ab1seq(fl) + tsequences["R"] = "".join(ab1seq_dfs["R"]["nuc"].values) + # TODO: Keep the ref name as ref + for rec in SeqIO.parse(f"{tmp_fold}/ref.fasta", "fasta"): + tsequences[rec.id] = str(rec.seq) + + for k in ab1seq_dfs: + ab1seq_dfs[k].columns = [f"{k}_{col}" for col in ab1seq_dfs[k].columns] + + aln_with_peak = merge_base_peak( + aln_df_with_ref(tsequences, flb, tmp_fold), ab1seq_dfs + ) + # exit() + # add file names as well, amb, at, res_fold) + aln_with_peak, u_range = aln_clean(aln_with_peak, gap) + # aln_with_peak.to_csv(f"{flb}.csv") + # aln_with_peak.to_csv("testxx.csv") + # exit(0) + seq = "".join(list(aln_with_peak["consensus"].values)) + # TODO: Generate sequence and exit + outfile = path.split(infiles[0])[1].split(".")[0] + outfile = f"{tmp_fold}/sanger_converted_fasta/{outfile}.fasta" + + output_file = open(outfile, "w") + output_file.write(f">{flb} {u_range[0]} {u_range[1]}\n{seq}\n") + output_file.close() + + +def ab2fasta( + sang_dict, tmp_fold, gap, key, n3, idb # , bc="neigh" +): # Base criteria, max, neighbors, mixed # Inputfiles paired and none paired + # sanger_outputs, tmp_fold, gap + """Retains fasta and converts ab1 to fasta""" + # print(key, sang_dict) + infiles = sang_dict[key] + + if len(infiles) == 1 and infiles[0].endswith(".fasta"): + fasta_map2ref(infiles[0], gap, tmp_fold, n3, idb) + + else: + # TODO: Fin a way to usilise only this part to generate fasta + ab1_2seq_map2ref(infiles, gap, tmp_fold) + + +def files_and_groups(sanger_files): + """List fasta and ab1 sequences as dictionary. + + :sanger_files: List of files in the folder + :returns: dictionary of files as paired/single and fasta/ab1 + + """ + file_groups = {} + for file_ in sanger_files: + flx = path.split(file_)[1] + flb = flx.split(".")[0] + if flb not in file_groups: + file_groups[flb] = [] + file_groups[flb].append(file_) + return file_groups + + +# TODO: generate sequence in absence of reference. +# TODO: Integration if sequence is not from coding region. + + +def non_overlapping_ids(asseblies, ab1s): + """Check for ovelapping and non-ovelapping ids and generates csv table + + :asseblies: Fasta assembly containing folder + :ab1s: Sanger generated ab1 or fasta files + :returns: Pandas dataframe + + """ + # Assembly IDS + assembly_ids = [] + for fl in glob(f"{asseblies}/*.fasta"): + for rec in SeqIO.parse(fl, "fasta"): + assembly_ids.append(rec.id) + + # Sanger sequences IDs + sanger_fasta = [] + for fl in glob(f"{ab1s}/*.fasta"): + for rec in SeqIO.parse(fl, "fasta"): + sanger_fasta.append(rec.id) + sanger_fasta_missing_assembly = ",".join( + set(sanger_fasta) - set(assembly_ids)) + + # Sanger forward ab1 IDs + sanger_ab1_f = [] + for fl in glob(f"{ab1s}/*.F.ab1"): + sanger_ab1_f.append(path.split(fl)[1].split(".F.ab1")[0]) + sanger_ab1_f_missing_assembly = ",".join( + set(sanger_fasta) - set(sanger_ab1_f)) + + # Sanger Reverse ab1 IDs + sanger_ab1_r = [] + for fl in glob(f"{ab1s}/*.R.ab1"): + sanger_ab1_r.append(path.split(fl)[1].split(".R.ab1")[0]) + sanger_ab1_r_missing_assembly = ",".join( + set(sanger_fasta) - set(sanger_ab1_r)) + + data_frame = {"assembly": [], "ab1_Forward": [], + "ab1_Reverse": [], "fasta": []} + for assembly_id in assembly_ids: + data_frame["assembly"].append(assembly_id) + + if assembly_id in sanger_ab1_f: + data_frame["ab1_Forward"].append(1) + else: + data_frame["ab1_Forward"].append(0) + + if assembly_id in sanger_ab1_r: + data_frame["ab1_Reverse"].append(1) + else: + data_frame["ab1_Reverse"].append(0) + + if assembly_id in sanger_fasta: + data_frame["fasta"].append(1) + else: + data_frame["fasta"].append(0) + + deduct = False + + if ( + sanger_ab1_f_missing_assembly + or sanger_ab1_r_missing_assembly + or sanger_fasta_missing_assembly + ): + deduct = True + data_frame["assembly"].append("No Assembly") + data_frame["ab1_Forward"].append(sanger_ab1_f_missing_assembly) + data_frame["ab1_Reverse"].append(sanger_ab1_r_missing_assembly) + data_frame["fasta"].append(sanger_fasta_missing_assembly) + + data_frame = pd.DataFrame(data_frame) + + # Check for overlap + if deduct: + is_overlap = ( + data_frame.iloc[:-1][["ab1_Forward", + "ab1_Reverse", "fasta"]].sum().sum() + ) + else: + is_overlap = data_frame[["ab1_Forward", + "ab1_Reverse", "fasta"]].sum().sum() + + if not is_overlap: + return pd.DataFrame() + return data_frame + + +# TODO: Generate min-max stats for each sequence and provide warnings + + +def integrate_in_assembly(outputfold, tmp_fold, sample_id): + """Mergre sange sequences in NGS assemblies + :outputfold: Final output folder + :tempfold: Intermediate files generated by other part of the script + :sample_id: Sample with NGS assembly and sange sequencing + + """ + # TODO: create psl folder in temp folder + + assembly = f"{tmp_fold}/assemblies/{sample_id}.fasta" + if not path.exists(assembly): + return + sanger = f"{tmp_fold}/sanger_converted_fasta/{sample_id}.fasta" + psl_file = f"{tmp_fold}/tmp/{sample_id}.psl" + command = ["blat", "-noHead", assembly, sanger, psl_file] + cmd(command) + + sanger_seq = {} + sanger_seq_desc = {} + for rec in SeqIO.parse(sanger, "fasta"): + sanger_seq_desc[rec.id] = rec.description + sanger_seq[rec.id] = str(rec.seq) + org_seq = {} + for rec in SeqIO.parse(assembly, "fasta"): + org_seq[rec.id] = str(rec.seq) + blat_df = pd.read_table(psl_file, header=None) + + blat_df = ( + blat_df[blat_df[9] == blat_df[13]] + .sort_values(0, ascending=False) + .drop_duplicates(9) + ) + + for _, row in blat_df.iterrows(): + start, end = list(map(int, sanger_seq_desc[row[9]].split()[1:])) + qstarts = np.array(list(map(int, row[19][:-1].split(",")))) + tstarts = np.array(list(map(int, row[20][:-1].split(",")))) + block = np.array(list(map(int, row[18][:-1].split(",")))) + qends = qstarts + block + # tends = tstarts + block + my_start, my_end = None, None + for ps in range(row[17]): + if start >= qstarts[ps] and start <= qends[ps]: + my_start = tstarts[ps] + start - qstarts[ps] + if end >= qstarts[ps] and end <= qends[ps]: + my_end = tstarts[ps] + end - qstarts[ps] + # tseq = org_seq[row[13]][my_start:my_end] + # range_gen = re.finditer("N+", tseq) + # n_range = [match.span() for match in range_gen] + # print(my_start, my_end, start, end, n_range, "anmol") + + org_seq[row[13]] = ( + org_seq[row[13]][:my_start] + + sanger_seq[row[9]][start:end] + + org_seq[row[13]][my_end:] + ) + + # print("Please report at a bug at") + # print("https://github.com/krisp-kwazulu-natal/" "seqPatcher/issues") + with open(f"{outputfold}/{sample_id}.fasta", "w") as fout: + for k in org_seq: + fout.write(f">{k}\n{org_seq[k]}\n") + + +@click.command() +@click.option( + "-s", + "--sanger-ab1", + "sa_ab1", + help="Folder containing Sanger sequencing trace files or Fasta files" + " generated from trace files.", + type=str, + default="ab1", + show_default=True, +) # Convert this to folder +# "/home/devil/Documents/San/Corona/Merging/Sanger/12April2021" +# @click.option("-fa", help="Fasta output file. +# If not given, only sequences will be printed in terminal", +# type=str, default=None, show_default=True) +@click.option( + "-a", + "-assemblies-foder", + "asf", + help="Folder containing HTS generate incomplete assembly Fasta files", + type=str, + default="assemblies", + show_default=True, +) +@click.option( + "-o", + "--out-dir", + "outd", + help="Result output Folder", + type=str, + default="Results", + show_default=True, +) +@click.option( + "-t", + "--tab", + "tab", + help="CSV file for overlapping assemblies and Sanger IDs." + " If not specified, stdout.", + type=str, + default=None, + show_default=True, +) +@click.option( + "-O", + "--output-fasta", + "ss", + help="Ouput file name for Fasta from sanger ab1", + type=str, + default=None, + show_default=True, +) +@click.option( + "-R", + "--ref-gene-fasta-file", + "rf", + help="Refence gene in fasta format", + type=str, + default=None, + show_default=True, +) +# @click.option( +# "-p", +# "--peak-value", +# "pv", +# help="Minmum value for peak. if sequence with peak not covering length of minimum of 50 nucleode length, will return error message", +# default=50, +# type=int, +# show_default=True, +# ) +# TODO: ask user if they want accoring to proxymity to end +# TODO: Check the stats of peak decrease over length and generate the math equation for that in case of ambious nucleotide is not utilised +# TODO: Whats happend ins case of ambigious nucleotide is not utilised +# @click.option( +# "-n", +# "--cpu", +# "cpu", +# help="Number of CPU to use", +# type=int, +# default=1, +# show_default=True, +# ) +@click.option( + "-c", + "--clean-intermediate", + "ci", + help="Remove intermediate files", + type=bool, + default=True, + show_default=True, +) +@click.option( + "-g", + "--gap-allowed", + "gap", + help="Minimum gap length between aligned fragment to consider the alignment continuous", + type=int, + default=10, + show_default=True, +) +@click.option( + "-3", + "--only-3-nuc", + "n3", + help="Allow multiple 3 nucleotide InDels else replace with reference nucleotides or Ns ", + type=bool, + default=True, + show_default=True, +) +@click.option( + "-x", + "--indel-selection", + "idb", + help="Replace Insertion, Deletion or Both", + type=click.Choice(["del", "ins", "both"]), + default="del", + show_default=True, + multiple=False, +) +@click.option( + "-m", + "--allow-ambi-nuc", + "amb", + help="Allow ambigious nucleotide integration, if present in both forward and reverse sequences. Else nucleotide will be calculated.", + type=bool, + default=False, + show_default=True, +) +# @click.option( +# "-M", +# "--ambigious-base-table", +# "at", +# help="Generate table of ambigious nucletide in reads and their replacement" +# " in concestion alongth with the position in consesus", +# type=bool, +# default=False, +# show_default=True, +# ) +# TODO: Suggest option to integrate ambigious nucleotide +@click.version_option(__version__) +def run( + sa_ab1, asf, outd, tab, ss, rf, ci, gap, n3, idb, amb # , at +): # , fa, asb, al, bscpu, + # print(sa_ab1, asf, outd, tab, ss, rf, cpu, ci, gap, n3, idb) + """ + Reports nucleotide sequence from Sanger chromatogram data based on user + provided parameters and integrate that in assembly generated using NGS + data""" + # TODO: Integrate multi core system + # if cpu < 1: + # print("Number of CPU use given is < 1.") + # print("Using default CPU value of 1") + # cpu = 1 + # elif cpu > cpu_count() - 1: + # print("Given cpu usage is more or equal to cpus avalable on system") + # print(f"Setting CPU usage to {cpu_count() - 1 }") + # cpu = cpu_count() - 1 + # else: + # pass + + # pool = Pool(cpu) + + if not sa_ab1: + exit("Sanger data folder is not given. Exiting . . . .") + if not path.exists(sa_ab1) or not path.isdir(sa_ab1): + exit( + f"Given sanger data folder {sa_ab1} doesn't exist or path is not a folder." + " Exiting . . . . ." + ) + + if not asf: + exit("Assembly folder not given. Exiting . . . . . . .") + if not path.exists(asf) or not path.isdir(asf): + exit( + f"Given assembly folder {asf} doesn't exist or path is not a folder." + " Exiting . . . . ." + ) + + if not rf: + print( + "Reference sequence file is not given." + " Considering sars-cov-2 spike protein sequence as reference" + ) + elif not path.exists(rf) or not path.isfile(rf): + print( + f"Given reference file {rf} doesn't exist or path is not a file.") + + print("Considering sars-cov-2 spike protein sequence as reference") + rf = None + + # tmp_fold = "tmp" + tmp_fold = tmf.mkdtemp() + + # ----------Housekeeping---------------- + # Creating temporary files and folders + + ref_path = f"{tmp_fold}/ref.fasta" + makedirs(outd, exist_ok=True) + for folder in [ + "assemblies", + "sanger_raw", + "sanger_converted_fasta", + "sanger_final_fasta", + "tmp", + ]: + makedirs(f"{tmp_fold}/{folder}", exist_ok=True) + + # Copying ref fasta + # TODO: If ref fasta not given, convert ab1 with them and provide region of overlaps + with open(ref_path, "w") as fout: + if not rf: + fout.write(f">ref CDS 0\n{_s_gene_seq}\n") + else: + seq_count = 0 + for rec in SeqIO.parse(rf, "fasta"): + seq_count += 1 + if seq_count > 1: + if ci: + rmtree(tmp_fold) + exit( + f"{rf} contains more than 1 sequence. " + "Expect only one." + " Exiting." + ) + seq_desc = rec.description.split() + # TODO: Include in future documentation + seq = rec.seq + if len(seq_desc) == 3 and seq_desc[1] == "CDS": + seq = seq[int(seq_desc[2]):] + fout.write(f">{rec.id} CDS 0\n{seq}\n") + else: + fout.write(f">{rec.id}\n{seq}\n") + + if not seq_count: + if ci: + rmtree(tmp_fold) + exit( + f"{rf} contains 0 (zero) sequence. " "Expect only one." " Exiting." + ) + + sanger_files = glob(f"{sa_ab1}/*") + if not sanger_files: + if ci: + rmtree(tmp_fold) + exit(f"No file found in {sa_ab1} folder. Exiting . . . .") + + sanger_names = [] + for fl in sanger_files: + if fl.endswith(".fasta"): + for rec in SeqIO.parse(fl, "fasta"): + if rec.id not in sanger_names: + sanger_names.append(rec.id) + if fl.endswith(".ab1"): + flb = path.split(fl)[1].split(".")[0] + if flb not in sanger_names: + sanger_names.append(flb) + # print(sanger_names) + # exit() + + ss = "Anmol.fasta" + for fl in glob(f"{sa_ab1}/*"): + if fl.endswith(".fasta"): # TODO: Allow fa, faa, fna, and other fasta formats + for rec in SeqIO.parse(fl, "fasta"): + with open(f"{tmp_fold}/tmp/{rec.id}.fasta", "w") as fout: + fout.write(f">{rec.id}\n{rec.seq}\n") + + l_r = orient( + f"{tmp_fold}/tmp/{rec.id}.fasta", + ref_path, + f"{tmp_fold}/tmp", + ) + + with open(f"{tmp_fold}/sanger_raw/{rec.id}.{l_r}.fasta", "w") as fout: + fout.write(f">{rec.id}\n{rec.seq}\n") + if fl.endswith(".ab1"): + fl_e = path.split(fl)[1] + flb = fl_e.split(".")[0] + l_r = orient(fl, ref_path, f"{tmp_fold}/tmp") + copyfile(fl, f"{tmp_fold}/sanger_raw/{flb}.{l_r}.ab1") + sanger_outputs = files_and_groups(glob(f"{tmp_fold}/sanger_raw/*")) + # print(sanger_outputs) + for k in sanger_outputs: + # print(k) + ab2fasta(sanger_outputs, tmp_fold, gap, k, n3, idb) + # exit() + + if ss: # WARNING: Does it matter? If this doesn't work while code be not functional + with open(ss, "w") as fout: + for fl in glob(f"{tmp_fold}/sanger_converted_fasta/*"): + for rec in SeqIO.parse(fl, "fasta"): + coors = rec.description.split()[1:] + coors = int(coors[0]), int(coors[1]) + fout.write(f">{rec.id}\n{rec.seq[coors[0]:coors[1]]}\n") + + assembly_files = glob(f"{asf}/*.fasta") + if not assembly_files: + if ci: + rmtree(tmp_fold) + exit(f"No file found in {asf} folder. Exiting . . . .") + assembly_names = [] + + for fl in assembly_files: + for rec in SeqIO.parse(fl, "fasta"): + assembly_names.append(rec.id) + # else: + # exit(f"No file is assembly folder {asf}. Exiting . . . .") + if not assembly_names: + # TODO: Should run even assemblies are not give and produce fasta from sanger seq + if ci: + rmtree(tmp_fold) + exit("No assembly sequence found. Exiting . . . . .") + + common_ids = set(assembly_names) & set(sanger_names) + if not common_ids: + if ci: + rmtree(tmp_fold) + exit( + "Genome assembly and sanger sequencing data doesn't have common" + " id(s). Exiting..." + ) + + # Copying assembly to tmp folder + for fl in glob(f"{asf}/*.fasta"): + for rec in SeqIO.parse(fl, "fasta"): + if rec.id in common_ids: + with open(f"{tmp_fold}/assemblies/{rec.id}.fasta", "w") as fout: + fout.write(f">{rec.id}\n{rec.seq}\n") + + seq_id_df = non_overlapping_ids( + f"{tmp_fold}/assemblies", f"{tmp_fold}/sanger_raw") + + seq_id_df = seq_id_df[ + ~( + (seq_id_df["assembly"] == "No Assembly") + | ( + (seq_id_df["ab1_Forward"] == 0) + & (seq_id_df["ab1_Reverse"] == 0) + & (seq_id_df["fasta"] == 0) + ) + ) + ] + + if tab: + seq_id_df.to_csv(tab, index=False) + else: + print(seq_id_df.to_csv(index=False)) + + seq_id_df = seq_id_df[ + ( + ((seq_id_df["ab1_Forward"] == 1) | (seq_id_df["ab1_Reverse"] == 1)) + & (seq_id_df["fasta"] == 0) + ) + | ( + ((seq_id_df["ab1_Forward"] == 0) & (seq_id_df["ab1_Reverse"] == 0)) + & (seq_id_df["fasta"] == 1) + ) + ] + print("The patcher executed for ..") + print(",".join(seq_id_df["assembly"])) + + # assemblies = glob(f"{tmp_fold}/assemblies/*.fasta") + + # sanger_outputs = files_and_groups(glob(f"{tmp_fold}/sanger_raw/*")) + # for k in sanger_outputs: + # ab2fasta(sanger_outputs, tmp_fold, gap, k, n3, idb) + + for id_ in sanger_outputs: + integrate_in_assembly(outd, tmp_fold, id_) + + if ci: + rmtree(tmp_fold) + + +if __name__ == "__main__": + run() diff --git a/seqPanther_codon_counter.sh b/seqPanther_codon_counter.sh new file mode 100644 index 0000000..713a650 --- /dev/null +++ b/seqPanther_codon_counter.sh @@ -0,0 +1,9 @@ +#!/bin/env bash + +seqpanther codoncounter \ + -bam examples/codoncounter/N47215.bam \ + -rid sars-cov-2 \ + -ref examples/codoncounter/NC_045512.2.fasta \ + -gff examples/codoncounter/genemap.gff \ + --output_type both \ + -coor_range 21000-25000 diff --git a/seqPanther_nucsub.sh b/seqPanther_nucsub.sh new file mode 100644 index 0000000..e69de29 diff --git a/seqPanther_seqpatcher.sh b/seqPanther_seqpatcher.sh new file mode 100644 index 0000000..ec9593b --- /dev/null +++ b/seqPanther_seqpatcher.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +# This script runs seqptcher command on test data. + +seqpanther seqptcher \ + -s examples/seqpatcher/ab1 \ + -a examples/seqpatcher/assemblies \ + -o examples/seqpatcher/results \ + -t examples/seqpatcher/results/mmf.csv \ + -R # If gene is known +-O anmol \ + -c True \ + -g 10 \ + -3 True \ + -x del diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..31a7f5f --- /dev/null +++ b/setup.py @@ -0,0 +1,22 @@ +from sys import version +from setuptools import setup, find_packages + +setup( + name="SeqPanther", + version="0.0.1", + install_requires=[ + 'biopython==1.80', 'click==7.1.2', 'numpy==1.22.1', 'pandas==1.5.2', + 'pyfaidx==0.6.3.1', 'pysam==0.18.0' + ], + packages=find_packages(include=["seqPanther", "seqPanther.*"]), + # package_dir={"seqPanther": "seqPanther"}, + # scripts=["bin/seqPanther"], + entry_points={ + 'console_scripts': ['seqpanther=seqPanther.seqPanther:run'], + }, + url="https://github.com/krisp-kwazulu-natal/seqPatcher", + license="GPLv3", + author="Anmol Kiran; San James Emmanuel", + author_email="anmol.kiran@gmail.com;sanemmanueljames@gmail.com", + description="A set of sequence manipulation tools", +)